clang 20.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclObjC.h"
22#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Scope.h"
41#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/SemaHLSL.h"
45#include "clang/Sema/SemaObjC.h"
46#include "clang/Sema/SemaPPC.h"
47#include "clang/Sema/Template.h"
49#include "llvm/ADT/APInt.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/STLForwardCompat.h"
52#include "llvm/ADT/StringExtras.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/TypeSize.h"
55#include <optional>
56using namespace clang;
57using namespace sema;
58
60 SourceLocation NameLoc,
61 const IdentifierInfo &Name) {
63
64 // Convert the nested-name-specifier into a type.
66 switch (NNS->getKind()) {
69 Type = QualType(NNS->getAsType(), 0);
70 break;
71
73 // Strip off the last layer of the nested-name-specifier and build a
74 // typename type for it.
75 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
78 break;
79
84 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
85 }
86
87 // This reference to the type is located entirely at the location of the
88 // final identifier in the qualified-id.
91}
92
94 SourceLocation NameLoc, Scope *S,
95 CXXScopeSpec &SS, bool EnteringContext) {
96 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
97 assert(CurClass && &II == CurClass->getIdentifier() &&
98 "not a constructor name");
99
100 // When naming a constructor as a member of a dependent context (eg, in a
101 // friend declaration or an inherited constructor declaration), form an
102 // unresolved "typename" type.
103 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
105 SS.getScopeRep(), &II);
106 return ParsedType::make(T);
107 }
108
109 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
110 return ParsedType();
111
112 // Find the injected-class-name declaration. Note that we make no attempt to
113 // diagnose cases where the injected-class-name is shadowed: the only
114 // declaration that can validly shadow the injected-class-name is a
115 // non-static data member, and if the class contains both a non-static data
116 // member and a constructor then it is ill-formed (we check that in
117 // CheckCompletedCXXClass).
118 CXXRecordDecl *InjectedClassName = nullptr;
119 for (NamedDecl *ND : CurClass->lookup(&II)) {
120 auto *RD = dyn_cast<CXXRecordDecl>(ND);
121 if (RD && RD->isInjectedClassName()) {
122 InjectedClassName = RD;
123 break;
124 }
125 }
126 if (!InjectedClassName) {
127 if (!CurClass->isInvalidDecl()) {
128 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
129 // properly. Work around it here for now.
131 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
132 }
133 return ParsedType();
134 }
135
136 QualType T = Context.getTypeDeclType(InjectedClassName);
137 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
138 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
139
140 return ParsedType::make(T);
141}
142
144 SourceLocation NameLoc, Scope *S,
145 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
146 bool EnteringContext) {
147 // Determine where to perform name lookup.
148
149 // FIXME: This area of the standard is very messy, and the current
150 // wording is rather unclear about which scopes we search for the
151 // destructor name; see core issues 399 and 555. Issue 399 in
152 // particular shows where the current description of destructor name
153 // lookup is completely out of line with existing practice, e.g.,
154 // this appears to be ill-formed:
155 //
156 // namespace N {
157 // template <typename T> struct S {
158 // ~S();
159 // };
160 // }
161 //
162 // void f(N::S<int>* s) {
163 // s->N::S<int>::~S();
164 // }
165 //
166 // See also PR6358 and PR6359.
167 //
168 // For now, we accept all the cases in which the name given could plausibly
169 // be interpreted as a correct destructor name, issuing off-by-default
170 // extension diagnostics on the cases that don't strictly conform to the
171 // C++20 rules. This basically means we always consider looking in the
172 // nested-name-specifier prefix, the complete nested-name-specifier, and
173 // the scope, and accept if we find the expected type in any of the three
174 // places.
175
176 if (SS.isInvalid())
177 return nullptr;
178
179 // Whether we've failed with a diagnostic already.
180 bool Failed = false;
181
184
185 // If we have an object type, it's because we are in a
186 // pseudo-destructor-expression or a member access expression, and
187 // we know what type we're looking for.
188 QualType SearchType =
189 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
190
191 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
192 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
193 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
194 if (!Type)
195 return false;
196
197 if (SearchType.isNull() || SearchType->isDependentType())
198 return true;
199
201 return Context.hasSameUnqualifiedType(T, SearchType);
202 };
203
204 unsigned NumAcceptableResults = 0;
205 for (NamedDecl *D : Found) {
206 if (IsAcceptableResult(D))
207 ++NumAcceptableResults;
208
209 // Don't list a class twice in the lookup failure diagnostic if it's
210 // found by both its injected-class-name and by the name in the enclosing
211 // scope.
212 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
213 if (RD->isInjectedClassName())
214 D = cast<NamedDecl>(RD->getParent());
215
216 if (FoundDeclSet.insert(D).second)
217 FoundDecls.push_back(D);
218 }
219
220 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
221 // results, and all non-matching results if we have a search type. It's not
222 // clear what the right behavior is if destructor lookup hits an ambiguity,
223 // but other compilers do generally accept at least some kinds of
224 // ambiguity.
225 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
226 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
227 LookupResult::Filter F = Found.makeFilter();
228 while (F.hasNext()) {
229 NamedDecl *D = F.next();
230 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
231 Diag(D->getLocation(), diag::note_destructor_type_here)
233 else
234 Diag(D->getLocation(), diag::note_destructor_nontype_here);
235
236 if (!IsAcceptableResult(D))
237 F.erase();
238 }
239 F.done();
240 }
241
242 if (Found.isAmbiguous())
243 Failed = true;
244
245 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
246 if (IsAcceptableResult(Type)) {
248 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
249 return CreateParsedType(
252 }
253 }
254
255 return nullptr;
256 };
257
258 bool IsDependent = false;
259
260 auto LookupInObjectType = [&]() -> ParsedType {
261 if (Failed || SearchType.isNull())
262 return nullptr;
263
264 IsDependent |= SearchType->isDependentType();
265
266 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
267 DeclContext *LookupCtx = computeDeclContext(SearchType);
268 if (!LookupCtx)
269 return nullptr;
270 LookupQualifiedName(Found, LookupCtx);
271 return CheckLookupResult(Found);
272 };
273
274 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
275 if (Failed)
276 return nullptr;
277
278 IsDependent |= isDependentScopeSpecifier(LookupSS);
279 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
280 if (!LookupCtx)
281 return nullptr;
282
283 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
284 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
285 Failed = true;
286 return nullptr;
287 }
288 LookupQualifiedName(Found, LookupCtx);
289 return CheckLookupResult(Found);
290 };
291
292 auto LookupInScope = [&]() -> ParsedType {
293 if (Failed || !S)
294 return nullptr;
295
296 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
297 LookupName(Found, S);
298 return CheckLookupResult(Found);
299 };
300
301 // C++2a [basic.lookup.qual]p6:
302 // In a qualified-id of the form
303 //
304 // nested-name-specifier[opt] type-name :: ~ type-name
305 //
306 // the second type-name is looked up in the same scope as the first.
307 //
308 // We interpret this as meaning that if you do a dual-scope lookup for the
309 // first name, you also do a dual-scope lookup for the second name, per
310 // C++ [basic.lookup.classref]p4:
311 //
312 // If the id-expression in a class member access is a qualified-id of the
313 // form
314 //
315 // class-name-or-namespace-name :: ...
316 //
317 // the class-name-or-namespace-name following the . or -> is first looked
318 // up in the class of the object expression and the name, if found, is used.
319 // Otherwise, it is looked up in the context of the entire
320 // postfix-expression.
321 //
322 // This looks in the same scopes as for an unqualified destructor name:
323 //
324 // C++ [basic.lookup.classref]p3:
325 // If the unqualified-id is ~ type-name, the type-name is looked up
326 // in the context of the entire postfix-expression. If the type T
327 // of the object expression is of a class type C, the type-name is
328 // also looked up in the scope of class C. At least one of the
329 // lookups shall find a name that refers to cv T.
330 //
331 // FIXME: The intent is unclear here. Should type-name::~type-name look in
332 // the scope anyway if it finds a non-matching name declared in the class?
333 // If both lookups succeed and find a dependent result, which result should
334 // we retain? (Same question for p->~type-name().)
335
336 if (NestedNameSpecifier *Prefix =
337 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
338 // This is
339 //
340 // nested-name-specifier type-name :: ~ type-name
341 //
342 // Look for the second type-name in the nested-name-specifier.
343 CXXScopeSpec PrefixSS;
344 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
345 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
346 return T;
347 } else {
348 // This is one of
349 //
350 // type-name :: ~ type-name
351 // ~ type-name
352 //
353 // Look in the scope and (if any) the object type.
354 if (ParsedType T = LookupInScope())
355 return T;
356 if (ParsedType T = LookupInObjectType())
357 return T;
358 }
359
360 if (Failed)
361 return nullptr;
362
363 if (IsDependent) {
364 // We didn't find our type, but that's OK: it's dependent anyway.
365
366 // FIXME: What if we have no nested-name-specifier?
367 QualType T =
369 SS.getWithLocInContext(Context), II, NameLoc);
370 return ParsedType::make(T);
371 }
372
373 // The remaining cases are all non-standard extensions imitating the behavior
374 // of various other compilers.
375 unsigned NumNonExtensionDecls = FoundDecls.size();
376
377 if (SS.isSet()) {
378 // For compatibility with older broken C++ rules and existing code,
379 //
380 // nested-name-specifier :: ~ type-name
381 //
382 // also looks for type-name within the nested-name-specifier.
383 if (ParsedType T = LookupInNestedNameSpec(SS)) {
384 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
385 << SS.getRange()
387 ("::" + II.getName()).str());
388 return T;
389 }
390
391 // For compatibility with other compilers and older versions of Clang,
392 //
393 // nested-name-specifier type-name :: ~ type-name
394 //
395 // also looks for type-name in the scope. Unfortunately, we can't
396 // reasonably apply this fallback for dependent nested-name-specifiers.
397 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
398 if (ParsedType T = LookupInScope()) {
399 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
401 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
403 return T;
404 }
405 }
406 }
407
408 // We didn't find anything matching; tell the user what we did find (if
409 // anything).
410
411 // Don't tell the user about declarations we shouldn't have found.
412 FoundDecls.resize(NumNonExtensionDecls);
413
414 // List types before non-types.
415 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
416 [](NamedDecl *A, NamedDecl *B) {
417 return isa<TypeDecl>(A->getUnderlyingDecl()) >
418 isa<TypeDecl>(B->getUnderlyingDecl());
419 });
420
421 // Suggest a fixit to properly name the destroyed type.
422 auto MakeFixItHint = [&]{
423 const CXXRecordDecl *Destroyed = nullptr;
424 // FIXME: If we have a scope specifier, suggest its last component?
425 if (!SearchType.isNull())
426 Destroyed = SearchType->getAsCXXRecordDecl();
427 else if (S)
428 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
429 if (Destroyed)
431 Destroyed->getNameAsString());
432 return FixItHint();
433 };
434
435 if (FoundDecls.empty()) {
436 // FIXME: Attempt typo-correction?
437 Diag(NameLoc, diag::err_undeclared_destructor_name)
438 << &II << MakeFixItHint();
439 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
440 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
441 assert(!SearchType.isNull() &&
442 "should only reject a type result if we have a search type");
444 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
445 << T << SearchType << MakeFixItHint();
446 } else {
447 Diag(NameLoc, diag::err_destructor_expr_nontype)
448 << &II << MakeFixItHint();
449 }
450 } else {
451 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
452 : diag::err_destructor_expr_mismatch)
453 << &II << SearchType << MakeFixItHint();
454 }
455
456 for (NamedDecl *FoundD : FoundDecls) {
457 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
458 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
460 else
461 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
462 << FoundD;
463 }
464
465 return nullptr;
466}
467
469 ParsedType ObjectType) {
471 return nullptr;
472
474 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
475 return nullptr;
476 }
477
479 "unexpected type in getDestructorType");
481
482 // If we know the type of the object, check that the correct destructor
483 // type was named now; we can give better diagnostics this way.
484 QualType SearchType = GetTypeFromParser(ObjectType);
485 if (!SearchType.isNull() && !SearchType->isDependentType() &&
486 !Context.hasSameUnqualifiedType(T, SearchType)) {
487 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
488 << T << SearchType;
489 return nullptr;
490 }
491
492 return ParsedType::make(T);
493}
494
496 const UnqualifiedId &Name, bool IsUDSuffix) {
497 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
498 if (!IsUDSuffix) {
499 // [over.literal] p8
500 //
501 // double operator""_Bq(long double); // OK: not a reserved identifier
502 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
503 const IdentifierInfo *II = Name.Identifier;
505 SourceLocation Loc = Name.getEndLoc();
506
508 Name.getSourceRange(),
509 (StringRef("operator\"\"") + II->getName()).str());
510
511 // Only emit this diagnostic if we start with an underscore, else the
512 // diagnostic for C++11 requiring a space between the quotes and the
513 // identifier conflicts with this and gets confusing. The diagnostic stating
514 // this is a reserved name should force the underscore, which gets this
515 // back.
516 if (II->isReservedLiteralSuffixId() !=
518 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
519
520 if (isReservedInAllContexts(Status))
521 Diag(Loc, diag::warn_reserved_extern_symbol)
522 << II << static_cast<int>(Status) << Hint;
523 }
524
525 if (!SS.isValid())
526 return false;
527
528 switch (SS.getScopeRep()->getKind()) {
532 // Per C++11 [over.literal]p2, literal operators can only be declared at
533 // namespace scope. Therefore, this unqualified-id cannot name anything.
534 // Reject it early, because we have no AST representation for this in the
535 // case where the scope is dependent.
536 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
537 << SS.getScopeRep();
538 return true;
539
544 return false;
545 }
546
547 llvm_unreachable("unknown nested name specifier kind");
548}
549
551 SourceLocation TypeidLoc,
552 TypeSourceInfo *Operand,
553 SourceLocation RParenLoc) {
554 // C++ [expr.typeid]p4:
555 // The top-level cv-qualifiers of the lvalue expression or the type-id
556 // that is the operand of typeid are always ignored.
557 // If the type of the type-id is a class type or a reference to a class
558 // type, the class shall be completely-defined.
559 Qualifiers Quals;
560 QualType T
561 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
562 Quals);
563 if (T->getAs<RecordType>() &&
564 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
565 return ExprError();
566
568 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
569
570 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
571 return ExprError();
572
573 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
574 SourceRange(TypeidLoc, RParenLoc));
575}
576
578 SourceLocation TypeidLoc,
579 Expr *E,
580 SourceLocation RParenLoc) {
581 bool WasEvaluated = false;
582 if (E && !E->isTypeDependent()) {
583 if (E->hasPlaceholderType()) {
585 if (result.isInvalid()) return ExprError();
586 E = result.get();
587 }
588
589 QualType T = E->getType();
590 if (const RecordType *RecordT = T->getAs<RecordType>()) {
591 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
592 // C++ [expr.typeid]p3:
593 // [...] If the type of the expression is a class type, the class
594 // shall be completely-defined.
595 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
596 return ExprError();
597
598 // C++ [expr.typeid]p3:
599 // When typeid is applied to an expression other than an glvalue of a
600 // polymorphic class type [...] [the] expression is an unevaluated
601 // operand. [...]
602 if (RecordD->isPolymorphic() && E->isGLValue()) {
603 if (isUnevaluatedContext()) {
604 // The operand was processed in unevaluated context, switch the
605 // context and recheck the subexpression.
607 if (Result.isInvalid())
608 return ExprError();
609 E = Result.get();
610 }
611
612 // We require a vtable to query the type at run time.
613 MarkVTableUsed(TypeidLoc, RecordD);
614 WasEvaluated = true;
615 }
616 }
617
619 if (Result.isInvalid())
620 return ExprError();
621 E = Result.get();
622
623 // C++ [expr.typeid]p4:
624 // [...] If the type of the type-id is a reference to a possibly
625 // cv-qualified type, the result of the typeid expression refers to a
626 // std::type_info object representing the cv-unqualified referenced
627 // type.
628 Qualifiers Quals;
629 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
630 if (!Context.hasSameType(T, UnqualT)) {
631 T = UnqualT;
632 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
633 }
634 }
635
637 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
638 << E->getType());
639 else if (!inTemplateInstantiation() &&
640 E->HasSideEffects(Context, WasEvaluated)) {
641 // The expression operand for typeid is in an unevaluated expression
642 // context, so side effects could result in unintended consequences.
643 Diag(E->getExprLoc(), WasEvaluated
644 ? diag::warn_side_effects_typeid
645 : diag::warn_side_effects_unevaluated_context);
646 }
647
648 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
649 SourceRange(TypeidLoc, RParenLoc));
650}
651
652/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
655 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
656 // typeid is not supported in OpenCL.
657 if (getLangOpts().OpenCLCPlusPlus) {
658 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
659 << "typeid");
660 }
661
662 // Find the std::type_info type.
663 if (!getStdNamespace())
664 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
665
666 if (!CXXTypeInfoDecl) {
667 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
668 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
671 // Microsoft's typeinfo doesn't have type_info in std but in the global
672 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
673 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
676 }
677 if (!CXXTypeInfoDecl)
678 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
679 }
680
681 if (!getLangOpts().RTTI) {
682 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
683 }
684
686
687 if (isType) {
688 // The operand is a type; handle it as such.
689 TypeSourceInfo *TInfo = nullptr;
691 &TInfo);
692 if (T.isNull())
693 return ExprError();
694
695 if (!TInfo)
696 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
697
698 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
699 }
700
701 // The operand is an expression.
703 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
704
705 if (!getLangOpts().RTTIData && !Result.isInvalid())
706 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
707 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
708 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
709 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
711 return Result;
712}
713
714/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
715/// a single GUID.
716static void
719 // Optionally remove one level of pointer, reference or array indirection.
720 const Type *Ty = QT.getTypePtr();
721 if (QT->isPointerOrReferenceType())
722 Ty = QT->getPointeeType().getTypePtr();
723 else if (QT->isArrayType())
724 Ty = Ty->getBaseElementTypeUnsafe();
725
726 const auto *TD = Ty->getAsTagDecl();
727 if (!TD)
728 return;
729
730 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
731 UuidAttrs.insert(Uuid);
732 return;
733 }
734
735 // __uuidof can grab UUIDs from template arguments.
736 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
737 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
738 for (const TemplateArgument &TA : TAL.asArray()) {
739 const UuidAttr *UuidForTA = nullptr;
740 if (TA.getKind() == TemplateArgument::Type)
741 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
742 else if (TA.getKind() == TemplateArgument::Declaration)
743 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
744
745 if (UuidForTA)
746 UuidAttrs.insert(UuidForTA);
747 }
748 }
749}
750
752 SourceLocation TypeidLoc,
753 TypeSourceInfo *Operand,
754 SourceLocation RParenLoc) {
755 MSGuidDecl *Guid = nullptr;
756 if (!Operand->getType()->isDependentType()) {
758 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
759 if (UuidAttrs.empty())
760 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
761 if (UuidAttrs.size() > 1)
762 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
763 Guid = UuidAttrs.back()->getGuidDecl();
764 }
765
766 return new (Context)
767 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
768}
769
771 Expr *E, SourceLocation RParenLoc) {
772 MSGuidDecl *Guid = nullptr;
773 if (!E->getType()->isDependentType()) {
775 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
777 } else {
779 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
780 if (UuidAttrs.empty())
781 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
782 if (UuidAttrs.size() > 1)
783 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
784 Guid = UuidAttrs.back()->getGuidDecl();
785 }
786 }
787
788 return new (Context)
789 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
790}
791
792/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
795 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
796 QualType GuidType = Context.getMSGuidType();
797 GuidType.addConst();
798
799 if (isType) {
800 // The operand is a type; handle it as such.
801 TypeSourceInfo *TInfo = nullptr;
803 &TInfo);
804 if (T.isNull())
805 return ExprError();
806
807 if (!TInfo)
808 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
809
810 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
811 }
812
813 // The operand is an expression.
814 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
815}
816
819 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
820 "Unknown C++ Boolean value!");
821 return new (Context)
822 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
823}
824
828}
829
832 bool IsThrownVarInScope = false;
833 if (Ex) {
834 // C++0x [class.copymove]p31:
835 // When certain criteria are met, an implementation is allowed to omit the
836 // copy/move construction of a class object [...]
837 //
838 // - in a throw-expression, when the operand is the name of a
839 // non-volatile automatic object (other than a function or catch-
840 // clause parameter) whose scope does not extend beyond the end of the
841 // innermost enclosing try-block (if there is one), the copy/move
842 // operation from the operand to the exception object (15.1) can be
843 // omitted by constructing the automatic object directly into the
844 // exception object
845 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
846 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
847 Var && Var->hasLocalStorage() &&
848 !Var->getType().isVolatileQualified()) {
849 for (; S; S = S->getParent()) {
850 if (S->isDeclScope(Var)) {
851 IsThrownVarInScope = true;
852 break;
853 }
854
855 // FIXME: Many of the scope checks here seem incorrect.
856 if (S->getFlags() &
859 break;
860 }
861 }
862 }
863
864 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
865}
866
868 bool IsThrownVarInScope) {
869 const llvm::Triple &T = Context.getTargetInfo().getTriple();
870 const bool IsOpenMPGPUTarget =
871 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
872 // Don't report an error if 'throw' is used in system headers or in an OpenMP
873 // target region compiled for a GPU architecture.
874 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
875 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
876 // Delay error emission for the OpenMP device code.
877 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
878 }
879
880 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
881 if (IsOpenMPGPUTarget)
882 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
883
884 // Exceptions aren't allowed in CUDA device code.
885 if (getLangOpts().CUDA)
886 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
887 << "throw" << llvm::to_underlying(CUDA().CurrentTarget());
888
889 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
890 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
891
892 // Exceptions that escape a compute construct are ill-formed.
893 if (getLangOpts().OpenACC && getCurScope() &&
894 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
895 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
896 << /*throw*/ 2 << /*out of*/ 0;
897
898 if (Ex && !Ex->isTypeDependent()) {
899 // Initialize the exception result. This implicitly weeds out
900 // abstract types or types with inaccessible copy constructors.
901
902 // C++0x [class.copymove]p31:
903 // When certain criteria are met, an implementation is allowed to omit the
904 // copy/move construction of a class object [...]
905 //
906 // - in a throw-expression, when the operand is the name of a
907 // non-volatile automatic object (other than a function or
908 // catch-clause
909 // parameter) whose scope does not extend beyond the end of the
910 // innermost enclosing try-block (if there is one), the copy/move
911 // operation from the operand to the exception object (15.1) can be
912 // omitted by constructing the automatic object directly into the
913 // exception object
914 NamedReturnInfo NRInfo =
915 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
916
917 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
918 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
919 return ExprError();
920
921 InitializedEntity Entity =
922 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
923 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
924 if (Res.isInvalid())
925 return ExprError();
926 Ex = Res.get();
927 }
928
929 // PPC MMA non-pointer types are not allowed as throw expr types.
930 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
931 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
932
933 return new (Context)
934 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
935}
936
937static void
939 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
940 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
941 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
942 bool ParentIsPublic) {
943 for (const CXXBaseSpecifier &BS : RD->bases()) {
944 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
945 bool NewSubobject;
946 // Virtual bases constitute the same subobject. Non-virtual bases are
947 // always distinct subobjects.
948 if (BS.isVirtual())
949 NewSubobject = VBases.insert(BaseDecl).second;
950 else
951 NewSubobject = true;
952
953 if (NewSubobject)
954 ++SubobjectsSeen[BaseDecl];
955
956 // Only add subobjects which have public access throughout the entire chain.
957 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
958 if (PublicPath)
959 PublicSubobjectsSeen.insert(BaseDecl);
960
961 // Recurse on to each base subobject.
962 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
963 PublicPath);
964 }
965}
966
969 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
970 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
971 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
972 SubobjectsSeen[RD] = 1;
973 PublicSubobjectsSeen.insert(RD);
974 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
975 /*ParentIsPublic=*/true);
976
977 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
978 // Skip ambiguous objects.
979 if (SubobjectsSeen[PublicSubobject] > 1)
980 continue;
981
982 Objects.push_back(PublicSubobject);
983 }
984}
985
987 QualType ExceptionObjectTy, Expr *E) {
988 // If the type of the exception would be an incomplete type or a pointer
989 // to an incomplete type other than (cv) void the program is ill-formed.
990 QualType Ty = ExceptionObjectTy;
991 bool isPointer = false;
992 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
993 Ty = Ptr->getPointeeType();
994 isPointer = true;
995 }
996
997 // Cannot throw WebAssembly reference type.
999 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
1000 return true;
1001 }
1002
1003 // Cannot throw WebAssembly table.
1004 if (isPointer && Ty.isWebAssemblyReferenceType()) {
1005 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
1006 return true;
1007 }
1008
1009 if (!isPointer || !Ty->isVoidType()) {
1010 if (RequireCompleteType(ThrowLoc, Ty,
1011 isPointer ? diag::err_throw_incomplete_ptr
1012 : diag::err_throw_incomplete,
1013 E->getSourceRange()))
1014 return true;
1015
1016 if (!isPointer && Ty->isSizelessType()) {
1017 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1018 return true;
1019 }
1020
1021 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1022 diag::err_throw_abstract_type, E))
1023 return true;
1024 }
1025
1026 // If the exception has class type, we need additional handling.
1028 if (!RD)
1029 return false;
1030
1031 // If we are throwing a polymorphic class type or pointer thereof,
1032 // exception handling will make use of the vtable.
1033 MarkVTableUsed(ThrowLoc, RD);
1034
1035 // If a pointer is thrown, the referenced object will not be destroyed.
1036 if (isPointer)
1037 return false;
1038
1039 // If the class has a destructor, we must be able to call it.
1040 if (!RD->hasIrrelevantDestructor()) {
1044 PDiag(diag::err_access_dtor_exception) << Ty);
1046 return true;
1047 }
1048 }
1049
1050 // The MSVC ABI creates a list of all types which can catch the exception
1051 // object. This list also references the appropriate copy constructor to call
1052 // if the object is caught by value and has a non-trivial copy constructor.
1054 // We are only interested in the public, unambiguous bases contained within
1055 // the exception object. Bases which are ambiguous or otherwise
1056 // inaccessible are not catchable types.
1057 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1058 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1059
1060 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1061 // Attempt to lookup the copy constructor. Various pieces of machinery
1062 // will spring into action, like template instantiation, which means this
1063 // cannot be a simple walk of the class's decls. Instead, we must perform
1064 // lookup and overload resolution.
1065 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1066 if (!CD || CD->isDeleted())
1067 continue;
1068
1069 // Mark the constructor referenced as it is used by this throw expression.
1071
1072 // Skip this copy constructor if it is trivial, we don't need to record it
1073 // in the catchable type data.
1074 if (CD->isTrivial())
1075 continue;
1076
1077 // The copy constructor is non-trivial, create a mapping from this class
1078 // type to this constructor.
1079 // N.B. The selection of copy constructor is not sensitive to this
1080 // particular throw-site. Lookup will be performed at the catch-site to
1081 // ensure that the copy constructor is, in fact, accessible (via
1082 // friendship or any other means).
1084
1085 // We don't keep the instantiated default argument expressions around so
1086 // we must rebuild them here.
1087 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1088 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1089 return true;
1090 }
1091 }
1092 }
1093
1094 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1095 // the runtime with no ability for the compiler to request additional
1096 // alignment. Warn if the exception type requires alignment beyond the minimum
1097 // guaranteed by the target C++ runtime.
1099 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1100 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1101 if (ExnObjAlign < TypeAlign) {
1102 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1103 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1104 << Ty << (unsigned)TypeAlign.getQuantity()
1105 << (unsigned)ExnObjAlign.getQuantity();
1106 }
1107 }
1108 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1109 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1110 auto Ty = Dtor->getType();
1111 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1112 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1113 !FT->isNothrow())
1114 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1115 }
1116 }
1117 }
1118
1119 return false;
1120}
1121
1123 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1124 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1125
1126 QualType ClassType = ThisTy->getPointeeType();
1127 LambdaScopeInfo *CurLSI = nullptr;
1128 DeclContext *CurDC = CurSemaContext;
1129
1130 // Iterate through the stack of lambdas starting from the innermost lambda to
1131 // the outermost lambda, checking if '*this' is ever captured by copy - since
1132 // that could change the cv-qualifiers of the '*this' object.
1133 // The object referred to by '*this' starts out with the cv-qualifiers of its
1134 // member function. We then start with the innermost lambda and iterate
1135 // outward checking to see if any lambda performs a by-copy capture of '*this'
1136 // - and if so, any nested lambda must respect the 'constness' of that
1137 // capturing lamdbda's call operator.
1138 //
1139
1140 // Since the FunctionScopeInfo stack is representative of the lexical
1141 // nesting of the lambda expressions during initial parsing (and is the best
1142 // place for querying information about captures about lambdas that are
1143 // partially processed) and perhaps during instantiation of function templates
1144 // that contain lambda expressions that need to be transformed BUT not
1145 // necessarily during instantiation of a nested generic lambda's function call
1146 // operator (which might even be instantiated at the end of the TU) - at which
1147 // time the DeclContext tree is mature enough to query capture information
1148 // reliably - we use a two pronged approach to walk through all the lexically
1149 // enclosing lambda expressions:
1150 //
1151 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1152 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1153 // enclosed by the call-operator of the LSI below it on the stack (while
1154 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1155 // the stack represents the innermost lambda.
1156 //
1157 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1158 // represents a lambda's call operator. If it does, we must be instantiating
1159 // a generic lambda's call operator (represented by the Current LSI, and
1160 // should be the only scenario where an inconsistency between the LSI and the
1161 // DeclContext should occur), so climb out the DeclContexts if they
1162 // represent lambdas, while querying the corresponding closure types
1163 // regarding capture information.
1164
1165 // 1) Climb down the function scope info stack.
1166 for (int I = FunctionScopes.size();
1167 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1168 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1169 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1170 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1171 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1172
1173 if (!CurLSI->isCXXThisCaptured())
1174 continue;
1175
1176 auto C = CurLSI->getCXXThisCapture();
1177
1178 if (C.isCopyCapture()) {
1179 if (CurLSI->lambdaCaptureShouldBeConst())
1180 ClassType.addConst();
1181 return ASTCtx.getPointerType(ClassType);
1182 }
1183 }
1184
1185 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1186 // can happen during instantiation of its nested generic lambda call
1187 // operator); 2. if we're in a lambda scope (lambda body).
1188 if (CurLSI && isLambdaCallOperator(CurDC)) {
1190 "While computing 'this' capture-type for a generic lambda, when we "
1191 "run out of enclosing LSI's, yet the enclosing DC is a "
1192 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1193 "lambda call oeprator");
1194 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1195
1196 auto IsThisCaptured =
1197 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1198 IsConst = false;
1199 IsByCopy = false;
1200 for (auto &&C : Closure->captures()) {
1201 if (C.capturesThis()) {
1202 if (C.getCaptureKind() == LCK_StarThis)
1203 IsByCopy = true;
1204 if (Closure->getLambdaCallOperator()->isConst())
1205 IsConst = true;
1206 return true;
1207 }
1208 }
1209 return false;
1210 };
1211
1212 bool IsByCopyCapture = false;
1213 bool IsConstCapture = false;
1214 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1215 while (Closure &&
1216 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1217 if (IsByCopyCapture) {
1218 if (IsConstCapture)
1219 ClassType.addConst();
1220 return ASTCtx.getPointerType(ClassType);
1221 }
1222 Closure = isLambdaCallOperator(Closure->getParent())
1223 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1224 : nullptr;
1225 }
1226 }
1227 return ThisTy;
1228}
1229
1233
1234 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1235 if (method && method->isImplicitObjectMemberFunction())
1236 ThisTy = method->getThisType().getNonReferenceType();
1237 }
1238
1240 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1241
1242 // This is a lambda call operator that is being instantiated as a default
1243 // initializer. DC must point to the enclosing class type, so we can recover
1244 // the 'this' type from it.
1245 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1246 // There are no cv-qualifiers for 'this' within default initializers,
1247 // per [expr.prim.general]p4.
1248 ThisTy = Context.getPointerType(ClassTy);
1249 }
1250
1251 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1252 // might need to be adjusted if the lambda or any of its enclosing lambda's
1253 // captures '*this' by copy.
1254 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1257 return ThisTy;
1258}
1259
1261 Decl *ContextDecl,
1262 Qualifiers CXXThisTypeQuals,
1263 bool Enabled)
1264 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1265{
1266 if (!Enabled || !ContextDecl)
1267 return;
1268
1269 CXXRecordDecl *Record = nullptr;
1270 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1271 Record = Template->getTemplatedDecl();
1272 else
1273 Record = cast<CXXRecordDecl>(ContextDecl);
1274
1276 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1277
1279 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1280
1281 this->Enabled = true;
1282}
1283
1284
1286 if (Enabled) {
1287 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1288 }
1289}
1290
1292 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1293 assert(!LSI->isCXXThisCaptured());
1294 // [=, this] {}; // until C++20: Error: this when = is the default
1296 !Sema.getLangOpts().CPlusPlus20)
1297 return;
1298 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1300 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1301}
1302
1304 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1305 const bool ByCopy) {
1306 // We don't need to capture this in an unevaluated context.
1308 return true;
1309
1310 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1311
1312 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1313 ? *FunctionScopeIndexToStopAt
1314 : FunctionScopes.size() - 1;
1315
1316 // Check that we can capture the *enclosing object* (referred to by '*this')
1317 // by the capturing-entity/closure (lambda/block/etc) at
1318 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1319
1320 // Note: The *enclosing object* can only be captured by-value by a
1321 // closure that is a lambda, using the explicit notation:
1322 // [*this] { ... }.
1323 // Every other capture of the *enclosing object* results in its by-reference
1324 // capture.
1325
1326 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1327 // stack), we can capture the *enclosing object* only if:
1328 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1329 // - or, 'L' has an implicit capture.
1330 // AND
1331 // -- there is no enclosing closure
1332 // -- or, there is some enclosing closure 'E' that has already captured the
1333 // *enclosing object*, and every intervening closure (if any) between 'E'
1334 // and 'L' can implicitly capture the *enclosing object*.
1335 // -- or, every enclosing closure can implicitly capture the
1336 // *enclosing object*
1337
1338
1339 unsigned NumCapturingClosures = 0;
1340 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1341 if (CapturingScopeInfo *CSI =
1342 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1343 if (CSI->CXXThisCaptureIndex != 0) {
1344 // 'this' is already being captured; there isn't anything more to do.
1345 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1346 break;
1347 }
1348 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1350 // This context can't implicitly capture 'this'; fail out.
1351 if (BuildAndDiagnose) {
1353 Diag(Loc, diag::err_this_capture)
1354 << (Explicit && idx == MaxFunctionScopesIndex);
1355 if (!Explicit)
1356 buildLambdaThisCaptureFixit(*this, LSI);
1357 }
1358 return true;
1359 }
1360 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1361 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1362 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1363 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1364 (Explicit && idx == MaxFunctionScopesIndex)) {
1365 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1366 // iteration through can be an explicit capture, all enclosing closures,
1367 // if any, must perform implicit captures.
1368
1369 // This closure can capture 'this'; continue looking upwards.
1370 NumCapturingClosures++;
1371 continue;
1372 }
1373 // This context can't implicitly capture 'this'; fail out.
1374 if (BuildAndDiagnose) {
1376 Diag(Loc, diag::err_this_capture)
1377 << (Explicit && idx == MaxFunctionScopesIndex);
1378 }
1379 if (!Explicit)
1380 buildLambdaThisCaptureFixit(*this, LSI);
1381 return true;
1382 }
1383 break;
1384 }
1385 if (!BuildAndDiagnose) return false;
1386
1387 // If we got here, then the closure at MaxFunctionScopesIndex on the
1388 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1389 // (including implicit by-reference captures in any enclosing closures).
1390
1391 // In the loop below, respect the ByCopy flag only for the closure requesting
1392 // the capture (i.e. first iteration through the loop below). Ignore it for
1393 // all enclosing closure's up to NumCapturingClosures (since they must be
1394 // implicitly capturing the *enclosing object* by reference (see loop
1395 // above)).
1396 assert((!ByCopy ||
1397 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1398 "Only a lambda can capture the enclosing object (referred to by "
1399 "*this) by copy");
1400 QualType ThisTy = getCurrentThisType();
1401 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1402 --idx, --NumCapturingClosures) {
1403 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1404
1405 // The type of the corresponding data member (not a 'this' pointer if 'by
1406 // copy').
1407 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1408
1409 bool isNested = NumCapturingClosures > 1;
1410 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1411 }
1412 return false;
1413}
1414
1416 // C++20 [expr.prim.this]p1:
1417 // The keyword this names a pointer to the object for which an
1418 // implicit object member function is invoked or a non-static
1419 // data member's initializer is evaluated.
1420 QualType ThisTy = getCurrentThisType();
1421
1422 if (CheckCXXThisType(Loc, ThisTy))
1423 return ExprError();
1424
1425 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1426}
1427
1429 if (!Type.isNull())
1430 return false;
1431
1432 // C++20 [expr.prim.this]p3:
1433 // If a declaration declares a member function or member function template
1434 // of a class X, the expression this is a prvalue of type
1435 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1436 // the optional cv-qualifier-seq and the end of the function-definition,
1437 // member-declarator, or declarator. It shall not appear within the
1438 // declaration of either a static member function or an explicit object
1439 // member function of the current class (although its type and value
1440 // category are defined within such member functions as they are within
1441 // an implicit object member function).
1443 const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1444 if (Method && Method->isExplicitObjectMemberFunction()) {
1445 Diag(Loc, diag::err_invalid_this_use) << 1;
1447 Diag(Loc, diag::err_invalid_this_use) << 1;
1448 } else {
1449 Diag(Loc, diag::err_invalid_this_use) << 0;
1450 }
1451 return true;
1452}
1453
1455 bool IsImplicit) {
1456 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1457 MarkThisReferenced(This);
1458 return This;
1459}
1460
1462 CheckCXXThisCapture(This->getExprLoc());
1463 if (This->isTypeDependent())
1464 return;
1465
1466 // Check if 'this' is captured by value in a lambda with a dependent explicit
1467 // object parameter, and mark it as type-dependent as well if so.
1468 auto IsDependent = [&]() {
1469 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1470 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1471 if (!LSI)
1472 continue;
1473
1474 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1475 LSI->AfterParameterList)
1476 return false;
1477
1478 // If this lambda captures 'this' by value, then 'this' is dependent iff
1479 // this lambda has a dependent explicit object parameter. If we can't
1480 // determine whether it does (e.g. because the CXXMethodDecl's type is
1481 // null), assume it doesn't.
1482 if (LSI->isCXXThisCaptured()) {
1483 if (!LSI->getCXXThisCapture().isCopyCapture())
1484 continue;
1485
1486 const auto *MD = LSI->CallOperator;
1487 if (MD->getType().isNull())
1488 return false;
1489
1490 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1491 return Ty && MD->isExplicitObjectMemberFunction() &&
1492 Ty->getParamType(0)->isDependentType();
1493 }
1494 }
1495 return false;
1496 }();
1497
1498 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1499}
1500
1502 // If we're outside the body of a member function, then we'll have a specified
1503 // type for 'this'.
1505 return false;
1506
1507 // Determine whether we're looking into a class that's currently being
1508 // defined.
1509 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1510 return Class && Class->isBeingDefined();
1511}
1512
1515 SourceLocation LParenOrBraceLoc,
1516 MultiExprArg exprs,
1517 SourceLocation RParenOrBraceLoc,
1518 bool ListInitialization) {
1519 if (!TypeRep)
1520 return ExprError();
1521
1522 TypeSourceInfo *TInfo;
1523 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1524 if (!TInfo)
1526
1527 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1528 RParenOrBraceLoc, ListInitialization);
1529 // Avoid creating a non-type-dependent expression that contains typos.
1530 // Non-type-dependent expressions are liable to be discarded without
1531 // checking for embedded typos.
1532 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1533 !Result.get()->isTypeDependent())
1535 else if (Result.isInvalid())
1537 RParenOrBraceLoc, exprs, Ty);
1538 return Result;
1539}
1540
1543 SourceLocation LParenOrBraceLoc,
1544 MultiExprArg Exprs,
1545 SourceLocation RParenOrBraceLoc,
1546 bool ListInitialization) {
1547 QualType Ty = TInfo->getType();
1548 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1549 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1550
1551 InitializedEntity Entity =
1553 InitializationKind Kind =
1554 Exprs.size()
1555 ? ListInitialization
1557 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1558 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1559 RParenOrBraceLoc)
1560 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1561 RParenOrBraceLoc);
1562
1563 // C++17 [expr.type.conv]p1:
1564 // If the type is a placeholder for a deduced class type, [...perform class
1565 // template argument deduction...]
1566 // C++23:
1567 // Otherwise, if the type contains a placeholder type, it is replaced by the
1568 // type determined by placeholder type deduction.
1569 DeducedType *Deduced = Ty->getContainedDeducedType();
1570 if (Deduced && !Deduced->isDeduced() &&
1571 isa<DeducedTemplateSpecializationType>(Deduced)) {
1573 Kind, Exprs);
1574 if (Ty.isNull())
1575 return ExprError();
1576 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1577 } else if (Deduced && !Deduced->isDeduced()) {
1578 MultiExprArg Inits = Exprs;
1579 if (ListInitialization) {
1580 auto *ILE = cast<InitListExpr>(Exprs[0]);
1581 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1582 }
1583
1584 if (Inits.empty())
1585 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1586 << Ty << FullRange);
1587 if (Inits.size() > 1) {
1588 Expr *FirstBad = Inits[1];
1589 return ExprError(Diag(FirstBad->getBeginLoc(),
1590 diag::err_auto_expr_init_multiple_expressions)
1591 << Ty << FullRange);
1592 }
1593 if (getLangOpts().CPlusPlus23) {
1594 if (Ty->getAs<AutoType>())
1595 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1596 }
1597 Expr *Deduce = Inits[0];
1598 if (isa<InitListExpr>(Deduce))
1599 return ExprError(
1600 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1601 << ListInitialization << Ty << FullRange);
1603 TemplateDeductionInfo Info(Deduce->getExprLoc());
1605 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1608 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1609 << Ty << Deduce->getType() << FullRange
1610 << Deduce->getSourceRange());
1611 if (DeducedType.isNull()) {
1613 return ExprError();
1614 }
1615
1616 Ty = DeducedType;
1617 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1618 }
1619
1622 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1623 RParenOrBraceLoc, ListInitialization);
1624
1625 // C++ [expr.type.conv]p1:
1626 // If the expression list is a parenthesized single expression, the type
1627 // conversion expression is equivalent (in definedness, and if defined in
1628 // meaning) to the corresponding cast expression.
1629 if (Exprs.size() == 1 && !ListInitialization &&
1630 !isa<InitListExpr>(Exprs[0])) {
1631 Expr *Arg = Exprs[0];
1632 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1633 RParenOrBraceLoc);
1634 }
1635
1636 // For an expression of the form T(), T shall not be an array type.
1637 QualType ElemTy = Ty;
1638 if (Ty->isArrayType()) {
1639 if (!ListInitialization)
1640 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1641 << FullRange);
1642 ElemTy = Context.getBaseElementType(Ty);
1643 }
1644
1645 // Only construct objects with object types.
1646 // The standard doesn't explicitly forbid function types here, but that's an
1647 // obvious oversight, as there's no way to dynamically construct a function
1648 // in general.
1649 if (Ty->isFunctionType())
1650 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1651 << Ty << FullRange);
1652
1653 // C++17 [expr.type.conv]p2, per DR2351:
1654 // If the type is cv void and the initializer is () or {}, the expression is
1655 // a prvalue of the specified type that performs no initialization.
1656 if (Ty->isVoidType()) {
1657 if (Exprs.empty())
1658 return new (Context) CXXScalarValueInitExpr(
1659 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1660 if (ListInitialization &&
1661 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {
1663 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,
1664 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),
1665 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());
1666 }
1667 } else if (RequireCompleteType(TyBeginLoc, ElemTy,
1668 diag::err_invalid_incomplete_type_use,
1669 FullRange))
1670 return ExprError();
1671
1672 // Otherwise, the expression is a prvalue of the specified type whose
1673 // result object is direct-initialized (11.6) with the initializer.
1674 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1675 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1676
1677 if (Result.isInvalid())
1678 return Result;
1679
1680 Expr *Inner = Result.get();
1681 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1682 Inner = BTE->getSubExpr();
1683 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1684 CE && CE->isImmediateInvocation())
1685 Inner = CE->getSubExpr();
1686 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1687 !isa<CXXScalarValueInitExpr>(Inner)) {
1688 // If we created a CXXTemporaryObjectExpr, that node also represents the
1689 // functional cast. Otherwise, create an explicit cast to represent
1690 // the syntactic form of a functional-style cast that was used here.
1691 //
1692 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1693 // would give a more consistent AST representation than using a
1694 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1695 // is sometimes handled by initialization and sometimes not.
1696 QualType ResultType = Result.get()->getType();
1697 SourceRange Locs = ListInitialization
1698 ? SourceRange()
1699 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1701 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1702 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1703 Locs.getBegin(), Locs.getEnd());
1704 }
1705
1706 return Result;
1707}
1708
1710 // [CUDA] Ignore this function, if we can't call it.
1711 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1712 if (getLangOpts().CUDA) {
1713 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1714 // If it's not callable at all, it's not the right function.
1715 if (CallPreference < SemaCUDA::CFP_WrongSide)
1716 return false;
1717 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1718 // Maybe. We have to check if there are better alternatives.
1720 Method->getDeclContext()->lookup(Method->getDeclName());
1721 for (const auto *D : R) {
1722 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1723 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1724 return false;
1725 }
1726 }
1727 // We've found no better variants.
1728 }
1729 }
1730
1732 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1733
1734 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1735 return Result;
1736
1737 // In case of CUDA, return true if none of the 1-argument deallocator
1738 // functions are actually callable.
1739 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1740 assert(FD->getNumParams() == 1 &&
1741 "Only single-operand functions should be in PreventedBy");
1742 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1743 });
1744}
1745
1746/// Determine whether the given function is a non-placement
1747/// deallocation function.
1749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1750 return S.isUsualDeallocationFunction(Method);
1751
1752 if (FD->getOverloadedOperator() != OO_Delete &&
1753 FD->getOverloadedOperator() != OO_Array_Delete)
1754 return false;
1755
1756 unsigned UsualParams = 1;
1757
1758 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1760 FD->getParamDecl(UsualParams)->getType(),
1761 S.Context.getSizeType()))
1762 ++UsualParams;
1763
1764 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1766 FD->getParamDecl(UsualParams)->getType(),
1768 ++UsualParams;
1769
1770 return UsualParams == FD->getNumParams();
1771}
1772
1773namespace {
1774 struct UsualDeallocFnInfo {
1775 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1776 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1777 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1778 Destroying(false), HasSizeT(false), HasAlignValT(false),
1779 CUDAPref(SemaCUDA::CFP_Native) {
1780 // A function template declaration is never a usual deallocation function.
1781 if (!FD)
1782 return;
1783 unsigned NumBaseParams = 1;
1784 if (FD->isDestroyingOperatorDelete()) {
1785 Destroying = true;
1786 ++NumBaseParams;
1787 }
1788
1789 if (NumBaseParams < FD->getNumParams() &&
1791 FD->getParamDecl(NumBaseParams)->getType(),
1792 S.Context.getSizeType())) {
1793 ++NumBaseParams;
1794 HasSizeT = true;
1795 }
1796
1797 if (NumBaseParams < FD->getNumParams() &&
1798 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1799 ++NumBaseParams;
1800 HasAlignValT = true;
1801 }
1802
1803 // In CUDA, determine how much we'd like / dislike to call this.
1804 if (S.getLangOpts().CUDA)
1805 CUDAPref = S.CUDA().IdentifyPreference(
1806 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1807 }
1808
1809 explicit operator bool() const { return FD; }
1810
1811 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1812 bool WantAlign) const {
1813 // C++ P0722:
1814 // A destroying operator delete is preferred over a non-destroying
1815 // operator delete.
1816 if (Destroying != Other.Destroying)
1817 return Destroying;
1818
1819 // C++17 [expr.delete]p10:
1820 // If the type has new-extended alignment, a function with a parameter
1821 // of type std::align_val_t is preferred; otherwise a function without
1822 // such a parameter is preferred
1823 if (HasAlignValT != Other.HasAlignValT)
1824 return HasAlignValT == WantAlign;
1825
1826 if (HasSizeT != Other.HasSizeT)
1827 return HasSizeT == WantSize;
1828
1829 // Use CUDA call preference as a tiebreaker.
1830 return CUDAPref > Other.CUDAPref;
1831 }
1832
1834 FunctionDecl *FD;
1835 bool Destroying, HasSizeT, HasAlignValT;
1837 };
1838}
1839
1840/// Determine whether a type has new-extended alignment. This may be called when
1841/// the type is incomplete (for a delete-expression with an incomplete pointee
1842/// type), in which case it will conservatively return false if the alignment is
1843/// not known.
1844static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1845 return S.getLangOpts().AlignedAllocation &&
1846 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1848}
1849
1850/// Select the correct "usual" deallocation function to use from a selection of
1851/// deallocation functions (either global or class-scope).
1852static UsualDeallocFnInfo resolveDeallocationOverload(
1853 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1854 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1855 UsualDeallocFnInfo Best;
1856
1857 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1858 UsualDeallocFnInfo Info(S, I.getPair());
1859 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1860 Info.CUDAPref == SemaCUDA::CFP_Never)
1861 continue;
1862
1863 if (!Best) {
1864 Best = Info;
1865 if (BestFns)
1866 BestFns->push_back(Info);
1867 continue;
1868 }
1869
1870 if (Best.isBetterThan(Info, WantSize, WantAlign))
1871 continue;
1872
1873 // If more than one preferred function is found, all non-preferred
1874 // functions are eliminated from further consideration.
1875 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1876 BestFns->clear();
1877
1878 Best = Info;
1879 if (BestFns)
1880 BestFns->push_back(Info);
1881 }
1882
1883 return Best;
1884}
1885
1886/// Determine whether a given type is a class for which 'delete[]' would call
1887/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1888/// we need to store the array size (even if the type is
1889/// trivially-destructible).
1891 QualType allocType) {
1892 const RecordType *record =
1893 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1894 if (!record) return false;
1895
1896 // Try to find an operator delete[] in class scope.
1897
1898 DeclarationName deleteName =
1899 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1900 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1901 S.LookupQualifiedName(ops, record->getDecl());
1902
1903 // We're just doing this for information.
1904 ops.suppressDiagnostics();
1905
1906 // Very likely: there's no operator delete[].
1907 if (ops.empty()) return false;
1908
1909 // If it's ambiguous, it should be illegal to call operator delete[]
1910 // on this thing, so it doesn't matter if we allocate extra space or not.
1911 if (ops.isAmbiguous()) return false;
1912
1913 // C++17 [expr.delete]p10:
1914 // If the deallocation functions have class scope, the one without a
1915 // parameter of type std::size_t is selected.
1916 auto Best = resolveDeallocationOverload(
1917 S, ops, /*WantSize*/false,
1918 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1919 return Best && Best.HasSizeT;
1920}
1921
1923Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1924 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1925 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1927 std::optional<Expr *> ArraySize;
1928 // If the specified type is an array, unwrap it and save the expression.
1929 if (D.getNumTypeObjects() > 0 &&
1930 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1931 DeclaratorChunk &Chunk = D.getTypeObject(0);
1932 if (D.getDeclSpec().hasAutoTypeSpec())
1933 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1934 << D.getSourceRange());
1935 if (Chunk.Arr.hasStatic)
1936 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1937 << D.getSourceRange());
1938 if (!Chunk.Arr.NumElts && !Initializer)
1939 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1940 << D.getSourceRange());
1941
1942 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1943 D.DropFirstTypeObject();
1944 }
1945
1946 // Every dimension shall be of constant size.
1947 if (ArraySize) {
1948 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1949 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1950 break;
1951
1952 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1953 if (Expr *NumElts = (Expr *)Array.NumElts) {
1954 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1955 // FIXME: GCC permits constant folding here. We should either do so consistently
1956 // or not do so at all, rather than changing behavior in C++14 onwards.
1957 if (getLangOpts().CPlusPlus14) {
1958 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1959 // shall be a converted constant expression (5.19) of type std::size_t
1960 // and shall evaluate to a strictly positive value.
1961 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1962 Array.NumElts
1965 .get();
1966 } else {
1967 Array.NumElts =
1969 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1970 .get();
1971 }
1972 if (!Array.NumElts)
1973 return ExprError();
1974 }
1975 }
1976 }
1977 }
1978
1980 QualType AllocType = TInfo->getType();
1981 if (D.isInvalidType())
1982 return ExprError();
1983
1984 SourceRange DirectInitRange;
1985 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1986 DirectInitRange = List->getSourceRange();
1987
1988 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1989 PlacementLParen, PlacementArgs, PlacementRParen,
1990 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1991 Initializer);
1992}
1993
1995 Expr *Init, bool IsCPlusPlus20) {
1996 if (!Init)
1997 return true;
1998 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1999 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2000 if (isa<ImplicitValueInitExpr>(Init))
2001 return true;
2002 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2003 return !CCE->isListInitialization() &&
2004 CCE->getConstructor()->isDefaultConstructor();
2005 else if (Style == CXXNewInitializationStyle::Braces) {
2006 assert(isa<InitListExpr>(Init) &&
2007 "Shouldn't create list CXXConstructExprs for arrays.");
2008 return true;
2009 }
2010 return false;
2011}
2012
2013bool
2015 if (!getLangOpts().AlignedAllocationUnavailable)
2016 return false;
2017 if (FD.isDefined())
2018 return false;
2019 std::optional<unsigned> AlignmentParam;
2020 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2021 AlignmentParam)
2022 return true;
2023 return false;
2024}
2025
2026// Emit a diagnostic if an aligned allocation/deallocation function that is not
2027// implemented in the standard library is selected.
2031 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2032 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2033 getASTContext().getTargetInfo().getPlatformName());
2034 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2035
2037 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2038 Diag(Loc, diag::err_aligned_allocation_unavailable)
2039 << IsDelete << FD.getType().getAsString() << OSName
2040 << OSVersion.getAsString() << OSVersion.empty();
2041 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2042 }
2043}
2044
2046 SourceLocation PlacementLParen,
2047 MultiExprArg PlacementArgs,
2048 SourceLocation PlacementRParen,
2049 SourceRange TypeIdParens, QualType AllocType,
2050 TypeSourceInfo *AllocTypeInfo,
2051 std::optional<Expr *> ArraySize,
2052 SourceRange DirectInitRange, Expr *Initializer) {
2053 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2054 SourceLocation StartLoc = Range.getBegin();
2055
2056 CXXNewInitializationStyle InitStyle;
2057 if (DirectInitRange.isValid()) {
2058 assert(Initializer && "Have parens but no initializer.");
2060 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2062 else {
2063 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2064 isa<CXXConstructExpr>(Initializer)) &&
2065 "Initializer expression that cannot have been implicitly created.");
2067 }
2068
2069 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2070 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2071 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2072 "paren init for non-call init");
2073 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2074 }
2075
2076 // C++11 [expr.new]p15:
2077 // A new-expression that creates an object of type T initializes that
2078 // object as follows:
2079 InitializationKind Kind = [&] {
2080 switch (InitStyle) {
2081 // - If the new-initializer is omitted, the object is default-
2082 // initialized (8.5); if no initialization is performed,
2083 // the object has indeterminate value
2085 return InitializationKind::CreateDefault(TypeRange.getBegin());
2086 // - Otherwise, the new-initializer is interpreted according to the
2087 // initialization rules of 8.5 for direct-initialization.
2089 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2090 DirectInitRange.getBegin(),
2091 DirectInitRange.getEnd());
2094 Initializer->getBeginLoc(),
2095 Initializer->getEndLoc());
2096 }
2097 llvm_unreachable("Unknown initialization kind");
2098 }();
2099
2100 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2101 auto *Deduced = AllocType->getContainedDeducedType();
2102 if (Deduced && !Deduced->isDeduced() &&
2103 isa<DeducedTemplateSpecializationType>(Deduced)) {
2104 if (ArraySize)
2105 return ExprError(
2106 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2107 diag::err_deduced_class_template_compound_type)
2108 << /*array*/ 2
2109 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2110
2111 InitializedEntity Entity
2112 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2114 AllocTypeInfo, Entity, Kind, Exprs);
2115 if (AllocType.isNull())
2116 return ExprError();
2117 } else if (Deduced && !Deduced->isDeduced()) {
2118 MultiExprArg Inits = Exprs;
2119 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2120 if (Braced) {
2121 auto *ILE = cast<InitListExpr>(Exprs[0]);
2122 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2123 }
2124
2125 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2126 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2127 << AllocType << TypeRange);
2128 if (Inits.size() > 1) {
2129 Expr *FirstBad = Inits[1];
2130 return ExprError(Diag(FirstBad->getBeginLoc(),
2131 diag::err_auto_new_ctor_multiple_expressions)
2132 << AllocType << TypeRange);
2133 }
2134 if (Braced && !getLangOpts().CPlusPlus17)
2135 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2136 << AllocType << TypeRange;
2137 Expr *Deduce = Inits[0];
2138 if (isa<InitListExpr>(Deduce))
2139 return ExprError(
2140 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2141 << Braced << AllocType << TypeRange);
2143 TemplateDeductionInfo Info(Deduce->getExprLoc());
2145 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2148 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2149 << AllocType << Deduce->getType() << TypeRange
2150 << Deduce->getSourceRange());
2151 if (DeducedType.isNull()) {
2153 return ExprError();
2154 }
2155 AllocType = DeducedType;
2156 }
2157
2158 // Per C++0x [expr.new]p5, the type being constructed may be a
2159 // typedef of an array type.
2160 // Dependent case will be handled separately.
2161 if (!ArraySize && !AllocType->isDependentType()) {
2162 if (const ConstantArrayType *Array
2163 = Context.getAsConstantArrayType(AllocType)) {
2164 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2166 TypeRange.getEnd());
2167 AllocType = Array->getElementType();
2168 }
2169 }
2170
2171 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2172 return ExprError();
2173
2174 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2175 return ExprError();
2176
2177 // In ARC, infer 'retaining' for the allocated
2178 if (getLangOpts().ObjCAutoRefCount &&
2179 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2180 AllocType->isObjCLifetimeType()) {
2181 AllocType = Context.getLifetimeQualifiedType(AllocType,
2182 AllocType->getObjCARCImplicitLifetime());
2183 }
2184
2185 QualType ResultType = Context.getPointerType(AllocType);
2186
2187 if (ArraySize && *ArraySize &&
2188 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2189 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2190 if (result.isInvalid()) return ExprError();
2191 ArraySize = result.get();
2192 }
2193 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2194 // integral or enumeration type with a non-negative value."
2195 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2196 // enumeration type, or a class type for which a single non-explicit
2197 // conversion function to integral or unscoped enumeration type exists.
2198 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2199 // std::size_t.
2200 std::optional<uint64_t> KnownArraySize;
2201 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2202 ExprResult ConvertedSize;
2203 if (getLangOpts().CPlusPlus14) {
2204 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2205
2206 ConvertedSize = PerformImplicitConversion(
2208
2209 if (!ConvertedSize.isInvalid() &&
2210 (*ArraySize)->getType()->getAs<RecordType>())
2211 // Diagnose the compatibility of this conversion.
2212 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2213 << (*ArraySize)->getType() << 0 << "'size_t'";
2214 } else {
2215 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2216 protected:
2217 Expr *ArraySize;
2218
2219 public:
2220 SizeConvertDiagnoser(Expr *ArraySize)
2221 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2222 ArraySize(ArraySize) {}
2223
2224 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2225 QualType T) override {
2226 return S.Diag(Loc, diag::err_array_size_not_integral)
2227 << S.getLangOpts().CPlusPlus11 << T;
2228 }
2229
2230 SemaDiagnosticBuilder diagnoseIncomplete(
2231 Sema &S, SourceLocation Loc, QualType T) override {
2232 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2233 << T << ArraySize->getSourceRange();
2234 }
2235
2236 SemaDiagnosticBuilder diagnoseExplicitConv(
2237 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2238 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2239 }
2240
2241 SemaDiagnosticBuilder noteExplicitConv(
2242 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2243 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2244 << ConvTy->isEnumeralType() << ConvTy;
2245 }
2246
2247 SemaDiagnosticBuilder diagnoseAmbiguous(
2248 Sema &S, SourceLocation Loc, QualType T) override {
2249 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2250 }
2251
2252 SemaDiagnosticBuilder noteAmbiguous(
2253 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2254 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2255 << ConvTy->isEnumeralType() << ConvTy;
2256 }
2257
2258 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2259 QualType T,
2260 QualType ConvTy) override {
2261 return S.Diag(Loc,
2262 S.getLangOpts().CPlusPlus11
2263 ? diag::warn_cxx98_compat_array_size_conversion
2264 : diag::ext_array_size_conversion)
2265 << T << ConvTy->isEnumeralType() << ConvTy;
2266 }
2267 } SizeDiagnoser(*ArraySize);
2268
2269 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2270 SizeDiagnoser);
2271 }
2272 if (ConvertedSize.isInvalid())
2273 return ExprError();
2274
2275 ArraySize = ConvertedSize.get();
2276 QualType SizeType = (*ArraySize)->getType();
2277
2278 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2279 return ExprError();
2280
2281 // C++98 [expr.new]p7:
2282 // The expression in a direct-new-declarator shall have integral type
2283 // with a non-negative value.
2284 //
2285 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2286 // per CWG1464. Otherwise, if it's not a constant, we must have an
2287 // unparenthesized array type.
2288
2289 // We've already performed any required implicit conversion to integer or
2290 // unscoped enumeration type.
2291 // FIXME: Per CWG1464, we are required to check the value prior to
2292 // converting to size_t. This will never find a negative array size in
2293 // C++14 onwards, because Value is always unsigned here!
2294 if (std::optional<llvm::APSInt> Value =
2295 (*ArraySize)->getIntegerConstantExpr(Context)) {
2296 if (Value->isSigned() && Value->isNegative()) {
2297 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2298 diag::err_typecheck_negative_array_size)
2299 << (*ArraySize)->getSourceRange());
2300 }
2301
2302 if (!AllocType->isDependentType()) {
2303 unsigned ActiveSizeBits =
2305 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2306 return ExprError(
2307 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2308 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2309 }
2310
2311 KnownArraySize = Value->getZExtValue();
2312 } else if (TypeIdParens.isValid()) {
2313 // Can't have dynamic array size when the type-id is in parentheses.
2314 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2315 << (*ArraySize)->getSourceRange()
2316 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2317 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2318
2319 TypeIdParens = SourceRange();
2320 }
2321
2322 // Note that we do *not* convert the argument in any way. It can
2323 // be signed, larger than size_t, whatever.
2324 }
2325
2326 FunctionDecl *OperatorNew = nullptr;
2327 FunctionDecl *OperatorDelete = nullptr;
2328 unsigned Alignment =
2329 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2330 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2331 bool PassAlignment = getLangOpts().AlignedAllocation &&
2332 Alignment > NewAlignment;
2333
2334 if (CheckArgsForPlaceholders(PlacementArgs))
2335 return ExprError();
2336
2338 if (!AllocType->isDependentType() &&
2339 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2341 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2342 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2343 OperatorNew, OperatorDelete))
2344 return ExprError();
2345
2346 // If this is an array allocation, compute whether the usual array
2347 // deallocation function for the type has a size_t parameter.
2348 bool UsualArrayDeleteWantsSize = false;
2349 if (ArraySize && !AllocType->isDependentType())
2350 UsualArrayDeleteWantsSize =
2351 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2352
2353 SmallVector<Expr *, 8> AllPlaceArgs;
2354 if (OperatorNew) {
2355 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2356 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2358
2359 // We've already converted the placement args, just fill in any default
2360 // arguments. Skip the first parameter because we don't have a corresponding
2361 // argument. Skip the second parameter too if we're passing in the
2362 // alignment; we've already filled it in.
2363 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2364 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2365 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2366 CallType))
2367 return ExprError();
2368
2369 if (!AllPlaceArgs.empty())
2370 PlacementArgs = AllPlaceArgs;
2371
2372 // We would like to perform some checking on the given `operator new` call,
2373 // but the PlacementArgs does not contain the implicit arguments,
2374 // namely allocation size and maybe allocation alignment,
2375 // so we need to conjure them.
2376
2377 QualType SizeTy = Context.getSizeType();
2378 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2379
2380 llvm::APInt SingleEltSize(
2381 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2382
2383 // How many bytes do we want to allocate here?
2384 std::optional<llvm::APInt> AllocationSize;
2385 if (!ArraySize && !AllocType->isDependentType()) {
2386 // For non-array operator new, we only want to allocate one element.
2387 AllocationSize = SingleEltSize;
2388 } else if (KnownArraySize && !AllocType->isDependentType()) {
2389 // For array operator new, only deal with static array size case.
2390 bool Overflow;
2391 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2392 .umul_ov(SingleEltSize, Overflow);
2393 (void)Overflow;
2394 assert(
2395 !Overflow &&
2396 "Expected that all the overflows would have been handled already.");
2397 }
2398
2399 IntegerLiteral AllocationSizeLiteral(
2400 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2401 SizeTy, SourceLocation());
2402 // Otherwise, if we failed to constant-fold the allocation size, we'll
2403 // just give up and pass-in something opaque, that isn't a null pointer.
2404 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2405 OK_Ordinary, /*SourceExpr=*/nullptr);
2406
2407 // Let's synthesize the alignment argument in case we will need it.
2408 // Since we *really* want to allocate these on stack, this is slightly ugly
2409 // because there might not be a `std::align_val_t` type.
2411 QualType AlignValT =
2413 IntegerLiteral AlignmentLiteral(
2414 Context,
2415 llvm::APInt(Context.getTypeSize(SizeTy),
2416 Alignment / Context.getCharWidth()),
2417 SizeTy, SourceLocation());
2418 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2419 CK_IntegralCast, &AlignmentLiteral,
2421
2422 // Adjust placement args by prepending conjured size and alignment exprs.
2424 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2425 CallArgs.emplace_back(AllocationSize
2426 ? static_cast<Expr *>(&AllocationSizeLiteral)
2427 : &OpaqueAllocationSize);
2428 if (PassAlignment)
2429 CallArgs.emplace_back(&DesiredAlignment);
2430 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2431
2432 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2433
2434 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2435 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2436
2437 // Warn if the type is over-aligned and is being allocated by (unaligned)
2438 // global operator new.
2439 if (PlacementArgs.empty() && !PassAlignment &&
2440 (OperatorNew->isImplicit() ||
2441 (OperatorNew->getBeginLoc().isValid() &&
2442 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2443 if (Alignment > NewAlignment)
2444 Diag(StartLoc, diag::warn_overaligned_type)
2445 << AllocType
2446 << unsigned(Alignment / Context.getCharWidth())
2447 << unsigned(NewAlignment / Context.getCharWidth());
2448 }
2449 }
2450
2451 // Array 'new' can't have any initializers except empty parentheses.
2452 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2453 // dialect distinction.
2454 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2456 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2457 Exprs.back()->getEndLoc());
2458 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2459 return ExprError();
2460 }
2461
2462 // If we can perform the initialization, and we've not already done so,
2463 // do it now.
2464 if (!AllocType->isDependentType() &&
2466 // The type we initialize is the complete type, including the array bound.
2467 QualType InitType;
2468 if (KnownArraySize)
2469 InitType = Context.getConstantArrayType(
2470 AllocType,
2471 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2472 *KnownArraySize),
2473 *ArraySize, ArraySizeModifier::Normal, 0);
2474 else if (ArraySize)
2475 InitType = Context.getIncompleteArrayType(AllocType,
2477 else
2478 InitType = AllocType;
2479
2480 InitializedEntity Entity
2481 = InitializedEntity::InitializeNew(StartLoc, InitType);
2482 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2483 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2484 if (FullInit.isInvalid())
2485 return ExprError();
2486
2487 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2488 // we don't want the initialized object to be destructed.
2489 // FIXME: We should not create these in the first place.
2490 if (CXXBindTemporaryExpr *Binder =
2491 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2492 FullInit = Binder->getSubExpr();
2493
2494 Initializer = FullInit.get();
2495
2496 // FIXME: If we have a KnownArraySize, check that the array bound of the
2497 // initializer is no greater than that constant value.
2498
2499 if (ArraySize && !*ArraySize) {
2500 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2501 if (CAT) {
2502 // FIXME: Track that the array size was inferred rather than explicitly
2503 // specified.
2504 ArraySize = IntegerLiteral::Create(
2505 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2506 } else {
2507 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2508 << Initializer->getSourceRange();
2509 }
2510 }
2511 }
2512
2513 // Mark the new and delete operators as referenced.
2514 if (OperatorNew) {
2515 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2516 return ExprError();
2517 MarkFunctionReferenced(StartLoc, OperatorNew);
2518 }
2519 if (OperatorDelete) {
2520 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2521 return ExprError();
2522 MarkFunctionReferenced(StartLoc, OperatorDelete);
2523 }
2524
2525 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2526 PassAlignment, UsualArrayDeleteWantsSize,
2527 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2528 Initializer, ResultType, AllocTypeInfo, Range,
2529 DirectInitRange);
2530}
2531
2533 SourceRange R) {
2534 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2535 // abstract class type or array thereof.
2536 if (AllocType->isFunctionType())
2537 return Diag(Loc, diag::err_bad_new_type)
2538 << AllocType << 0 << R;
2539 else if (AllocType->isReferenceType())
2540 return Diag(Loc, diag::err_bad_new_type)
2541 << AllocType << 1 << R;
2542 else if (!AllocType->isDependentType() &&
2544 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2545 return true;
2546 else if (RequireNonAbstractType(Loc, AllocType,
2547 diag::err_allocation_of_abstract_type))
2548 return true;
2549 else if (AllocType->isVariablyModifiedType())
2550 return Diag(Loc, diag::err_variably_modified_new_type)
2551 << AllocType;
2552 else if (AllocType.getAddressSpace() != LangAS::Default &&
2553 !getLangOpts().OpenCLCPlusPlus)
2554 return Diag(Loc, diag::err_address_space_qualified_new)
2555 << AllocType.getUnqualifiedType()
2557 else if (getLangOpts().ObjCAutoRefCount) {
2558 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2559 QualType BaseAllocType = Context.getBaseElementType(AT);
2560 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2561 BaseAllocType->isObjCLifetimeType())
2562 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2563 << BaseAllocType;
2564 }
2565 }
2566
2567 return false;
2568}
2569
2572 bool &PassAlignment, FunctionDecl *&Operator,
2573 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2574 OverloadCandidateSet Candidates(R.getNameLoc(),
2576 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2577 Alloc != AllocEnd; ++Alloc) {
2578 // Even member operator new/delete are implicitly treated as
2579 // static, so don't use AddMemberCandidate.
2580 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2581
2582 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2583 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2584 /*ExplicitTemplateArgs=*/nullptr, Args,
2585 Candidates,
2586 /*SuppressUserConversions=*/false);
2587 continue;
2588 }
2589
2590 FunctionDecl *Fn = cast<FunctionDecl>(D);
2591 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2592 /*SuppressUserConversions=*/false);
2593 }
2594
2595 // Do the resolution.
2597 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2598 case OR_Success: {
2599 // Got one!
2600 FunctionDecl *FnDecl = Best->Function;
2602 Best->FoundDecl) == Sema::AR_inaccessible)
2603 return true;
2604
2605 Operator = FnDecl;
2606 return false;
2607 }
2608
2610 // C++17 [expr.new]p13:
2611 // If no matching function is found and the allocated object type has
2612 // new-extended alignment, the alignment argument is removed from the
2613 // argument list, and overload resolution is performed again.
2614 if (PassAlignment) {
2615 PassAlignment = false;
2616 AlignArg = Args[1];
2617 Args.erase(Args.begin() + 1);
2618 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2619 Operator, &Candidates, AlignArg,
2620 Diagnose);
2621 }
2622
2623 // MSVC will fall back on trying to find a matching global operator new
2624 // if operator new[] cannot be found. Also, MSVC will leak by not
2625 // generating a call to operator delete or operator delete[], but we
2626 // will not replicate that bug.
2627 // FIXME: Find out how this interacts with the std::align_val_t fallback
2628 // once MSVC implements it.
2629 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2630 S.Context.getLangOpts().MSVCCompat) {
2631 R.clear();
2634 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2635 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2636 Operator, /*Candidates=*/nullptr,
2637 /*AlignArg=*/nullptr, Diagnose);
2638 }
2639
2640 if (Diagnose) {
2641 // If this is an allocation of the form 'new (p) X' for some object
2642 // pointer p (or an expression that will decay to such a pointer),
2643 // diagnose the missing inclusion of <new>.
2644 if (!R.isClassLookup() && Args.size() == 2 &&
2645 (Args[1]->getType()->isObjectPointerType() ||
2646 Args[1]->getType()->isArrayType())) {
2647 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2648 << R.getLookupName() << Range;
2649 // Listing the candidates is unlikely to be useful; skip it.
2650 return true;
2651 }
2652
2653 // Finish checking all candidates before we note any. This checking can
2654 // produce additional diagnostics so can't be interleaved with our
2655 // emission of notes.
2656 //
2657 // For an aligned allocation, separately check the aligned and unaligned
2658 // candidates with their respective argument lists.
2661 llvm::SmallVector<Expr*, 4> AlignedArgs;
2662 if (AlignedCandidates) {
2663 auto IsAligned = [](OverloadCandidate &C) {
2664 return C.Function->getNumParams() > 1 &&
2665 C.Function->getParamDecl(1)->getType()->isAlignValT();
2666 };
2667 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2668
2669 AlignedArgs.reserve(Args.size() + 1);
2670 AlignedArgs.push_back(Args[0]);
2671 AlignedArgs.push_back(AlignArg);
2672 AlignedArgs.append(Args.begin() + 1, Args.end());
2673 AlignedCands = AlignedCandidates->CompleteCandidates(
2674 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2675
2676 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2677 R.getNameLoc(), IsUnaligned);
2678 } else {
2679 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2680 R.getNameLoc());
2681 }
2682
2683 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2684 << R.getLookupName() << Range;
2685 if (AlignedCandidates)
2686 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2687 R.getNameLoc());
2688 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2689 }
2690 return true;
2691
2692 case OR_Ambiguous:
2693 if (Diagnose) {
2694 Candidates.NoteCandidates(
2696 S.PDiag(diag::err_ovl_ambiguous_call)
2697 << R.getLookupName() << Range),
2698 S, OCD_AmbiguousCandidates, Args);
2699 }
2700 return true;
2701
2702 case OR_Deleted: {
2703 if (Diagnose)
2705 Candidates, Best->Function, Args);
2706 return true;
2707 }
2708 }
2709 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2710}
2711
2713 AllocationFunctionScope NewScope,
2714 AllocationFunctionScope DeleteScope,
2715 QualType AllocType, bool IsArray,
2716 bool &PassAlignment, MultiExprArg PlaceArgs,
2717 FunctionDecl *&OperatorNew,
2718 FunctionDecl *&OperatorDelete,
2719 bool Diagnose) {
2720 // --- Choosing an allocation function ---
2721 // C++ 5.3.4p8 - 14 & 18
2722 // 1) If looking in AFS_Global scope for allocation functions, only look in
2723 // the global scope. Else, if AFS_Class, only look in the scope of the
2724 // allocated class. If AFS_Both, look in both.
2725 // 2) If an array size is given, look for operator new[], else look for
2726 // operator new.
2727 // 3) The first argument is always size_t. Append the arguments from the
2728 // placement form.
2729
2730 SmallVector<Expr*, 8> AllocArgs;
2731 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2732
2733 // We don't care about the actual value of these arguments.
2734 // FIXME: Should the Sema create the expression and embed it in the syntax
2735 // tree? Or should the consumer just recalculate the value?
2736 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2737 QualType SizeTy = Context.getSizeType();
2738 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2739 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2740 SourceLocation());
2741 AllocArgs.push_back(&Size);
2742
2743 QualType AlignValT = Context.VoidTy;
2744 if (PassAlignment) {
2747 }
2748 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2749 if (PassAlignment)
2750 AllocArgs.push_back(&Align);
2751
2752 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2753
2754 // C++ [expr.new]p8:
2755 // If the allocated type is a non-array type, the allocation
2756 // function's name is operator new and the deallocation function's
2757 // name is operator delete. If the allocated type is an array
2758 // type, the allocation function's name is operator new[] and the
2759 // deallocation function's name is operator delete[].
2761 IsArray ? OO_Array_New : OO_New);
2762
2763 QualType AllocElemType = Context.getBaseElementType(AllocType);
2764
2765 // Find the allocation function.
2766 {
2767 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2768
2769 // C++1z [expr.new]p9:
2770 // If the new-expression begins with a unary :: operator, the allocation
2771 // function's name is looked up in the global scope. Otherwise, if the
2772 // allocated type is a class type T or array thereof, the allocation
2773 // function's name is looked up in the scope of T.
2774 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2775 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2776
2777 // We can see ambiguity here if the allocation function is found in
2778 // multiple base classes.
2779 if (R.isAmbiguous())
2780 return true;
2781
2782 // If this lookup fails to find the name, or if the allocated type is not
2783 // a class type, the allocation function's name is looked up in the
2784 // global scope.
2785 if (R.empty()) {
2786 if (NewScope == AFS_Class)
2787 return true;
2788
2790 }
2791
2792 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2793 if (PlaceArgs.empty()) {
2794 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2795 } else {
2796 Diag(StartLoc, diag::err_openclcxx_placement_new);
2797 }
2798 return true;
2799 }
2800
2801 assert(!R.empty() && "implicitly declared allocation functions not found");
2802 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2803
2804 // We do our own custom access checks below.
2806
2807 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2808 OperatorNew, /*Candidates=*/nullptr,
2809 /*AlignArg=*/nullptr, Diagnose))
2810 return true;
2811 }
2812
2813 // We don't need an operator delete if we're running under -fno-exceptions.
2814 if (!getLangOpts().Exceptions) {
2815 OperatorDelete = nullptr;
2816 return false;
2817 }
2818
2819 // Note, the name of OperatorNew might have been changed from array to
2820 // non-array by resolveAllocationOverload.
2822 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2823 ? OO_Array_Delete
2824 : OO_Delete);
2825
2826 // C++ [expr.new]p19:
2827 //
2828 // If the new-expression begins with a unary :: operator, the
2829 // deallocation function's name is looked up in the global
2830 // scope. Otherwise, if the allocated type is a class type T or an
2831 // array thereof, the deallocation function's name is looked up in
2832 // the scope of T. If this lookup fails to find the name, or if
2833 // the allocated type is not a class type or array thereof, the
2834 // deallocation function's name is looked up in the global scope.
2835 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2836 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2837 auto *RD =
2838 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2839 LookupQualifiedName(FoundDelete, RD);
2840 }
2841 if (FoundDelete.isAmbiguous())
2842 return true; // FIXME: clean up expressions?
2843
2844 // Filter out any destroying operator deletes. We can't possibly call such a
2845 // function in this context, because we're handling the case where the object
2846 // was not successfully constructed.
2847 // FIXME: This is not covered by the language rules yet.
2848 {
2849 LookupResult::Filter Filter = FoundDelete.makeFilter();
2850 while (Filter.hasNext()) {
2851 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2852 if (FD && FD->isDestroyingOperatorDelete())
2853 Filter.erase();
2854 }
2855 Filter.done();
2856 }
2857
2858 bool FoundGlobalDelete = FoundDelete.empty();
2859 if (FoundDelete.empty()) {
2860 FoundDelete.clear(LookupOrdinaryName);
2861
2862 if (DeleteScope == AFS_Class)
2863 return true;
2864
2867 }
2868
2869 FoundDelete.suppressDiagnostics();
2870
2872
2873 // Whether we're looking for a placement operator delete is dictated
2874 // by whether we selected a placement operator new, not by whether
2875 // we had explicit placement arguments. This matters for things like
2876 // struct A { void *operator new(size_t, int = 0); ... };
2877 // A *a = new A()
2878 //
2879 // We don't have any definition for what a "placement allocation function"
2880 // is, but we assume it's any allocation function whose
2881 // parameter-declaration-clause is anything other than (size_t).
2882 //
2883 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2884 // This affects whether an exception from the constructor of an overaligned
2885 // type uses the sized or non-sized form of aligned operator delete.
2886 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2887 OperatorNew->isVariadic();
2888
2889 if (isPlacementNew) {
2890 // C++ [expr.new]p20:
2891 // A declaration of a placement deallocation function matches the
2892 // declaration of a placement allocation function if it has the
2893 // same number of parameters and, after parameter transformations
2894 // (8.3.5), all parameter types except the first are
2895 // identical. [...]
2896 //
2897 // To perform this comparison, we compute the function type that
2898 // the deallocation function should have, and use that type both
2899 // for template argument deduction and for comparison purposes.
2900 QualType ExpectedFunctionType;
2901 {
2902 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2903
2904 SmallVector<QualType, 4> ArgTypes;
2905 ArgTypes.push_back(Context.VoidPtrTy);
2906 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2907 ArgTypes.push_back(Proto->getParamType(I));
2908
2910 // FIXME: This is not part of the standard's rule.
2911 EPI.Variadic = Proto->isVariadic();
2912
2913 ExpectedFunctionType
2914 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2915 }
2916
2917 for (LookupResult::iterator D = FoundDelete.begin(),
2918 DEnd = FoundDelete.end();
2919 D != DEnd; ++D) {
2920 FunctionDecl *Fn = nullptr;
2921 if (FunctionTemplateDecl *FnTmpl =
2922 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2923 // Perform template argument deduction to try to match the
2924 // expected function type.
2925 TemplateDeductionInfo Info(StartLoc);
2926 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2928 continue;
2929 } else
2930 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2931
2932 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2933 ExpectedFunctionType,
2934 /*AdjustExcpetionSpec*/true),
2935 ExpectedFunctionType))
2936 Matches.push_back(std::make_pair(D.getPair(), Fn));
2937 }
2938
2939 if (getLangOpts().CUDA)
2940 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2941 Matches);
2942 } else {
2943 // C++1y [expr.new]p22:
2944 // For a non-placement allocation function, the normal deallocation
2945 // function lookup is used
2946 //
2947 // Per [expr.delete]p10, this lookup prefers a member operator delete
2948 // without a size_t argument, but prefers a non-member operator delete
2949 // with a size_t where possible (which it always is in this case).
2951 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2952 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2953 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2954 &BestDeallocFns);
2955 if (Selected)
2956 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2957 else {
2958 // If we failed to select an operator, all remaining functions are viable
2959 // but ambiguous.
2960 for (auto Fn : BestDeallocFns)
2961 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2962 }
2963 }
2964
2965 // C++ [expr.new]p20:
2966 // [...] If the lookup finds a single matching deallocation
2967 // function, that function will be called; otherwise, no
2968 // deallocation function will be called.
2969 if (Matches.size() == 1) {
2970 OperatorDelete = Matches[0].second;
2971
2972 // C++1z [expr.new]p23:
2973 // If the lookup finds a usual deallocation function (3.7.4.2)
2974 // with a parameter of type std::size_t and that function, considered
2975 // as a placement deallocation function, would have been
2976 // selected as a match for the allocation function, the program
2977 // is ill-formed.
2978 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2979 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2980 UsualDeallocFnInfo Info(*this,
2981 DeclAccessPair::make(OperatorDelete, AS_public));
2982 // Core issue, per mail to core reflector, 2016-10-09:
2983 // If this is a member operator delete, and there is a corresponding
2984 // non-sized member operator delete, this isn't /really/ a sized
2985 // deallocation function, it just happens to have a size_t parameter.
2986 bool IsSizedDelete = Info.HasSizeT;
2987 if (IsSizedDelete && !FoundGlobalDelete) {
2988 auto NonSizedDelete =
2989 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2990 /*WantAlign*/Info.HasAlignValT);
2991 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2992 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2993 IsSizedDelete = false;
2994 }
2995
2996 if (IsSizedDelete) {
2997 SourceRange R = PlaceArgs.empty()
2998 ? SourceRange()
2999 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3000 PlaceArgs.back()->getEndLoc());
3001 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3002 if (!OperatorDelete->isImplicit())
3003 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3004 << DeleteName;
3005 }
3006 }
3007
3008 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
3009 Matches[0].first);
3010 } else if (!Matches.empty()) {
3011 // We found multiple suitable operators. Per [expr.new]p20, that means we
3012 // call no 'operator delete' function, but we should at least warn the user.
3013 // FIXME: Suppress this warning if the construction cannot throw.
3014 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3015 << DeleteName << AllocElemType;
3016
3017 for (auto &Match : Matches)
3018 Diag(Match.second->getLocation(),
3019 diag::note_member_declared_here) << DeleteName;
3020 }
3021
3022 return false;
3023}
3024
3027 return;
3028
3029 // The implicitly declared new and delete operators
3030 // are not supported in OpenCL.
3031 if (getLangOpts().OpenCLCPlusPlus)
3032 return;
3033
3034 // C++ [basic.stc.dynamic.general]p2:
3035 // The library provides default definitions for the global allocation
3036 // and deallocation functions. Some global allocation and deallocation
3037 // functions are replaceable ([new.delete]); these are attached to the
3038 // global module ([module.unit]).
3039 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3040 PushGlobalModuleFragment(SourceLocation());
3041
3042 // C++ [basic.std.dynamic]p2:
3043 // [...] The following allocation and deallocation functions (18.4) are
3044 // implicitly declared in global scope in each translation unit of a
3045 // program
3046 //
3047 // C++03:
3048 // void* operator new(std::size_t) throw(std::bad_alloc);
3049 // void* operator new[](std::size_t) throw(std::bad_alloc);
3050 // void operator delete(void*) throw();
3051 // void operator delete[](void*) throw();
3052 // C++11:
3053 // void* operator new(std::size_t);
3054 // void* operator new[](std::size_t);
3055 // void operator delete(void*) noexcept;
3056 // void operator delete[](void*) noexcept;
3057 // C++1y:
3058 // void* operator new(std::size_t);
3059 // void* operator new[](std::size_t);
3060 // void operator delete(void*) noexcept;
3061 // void operator delete[](void*) noexcept;
3062 // void operator delete(void*, std::size_t) noexcept;
3063 // void operator delete[](void*, std::size_t) noexcept;
3064 //
3065 // These implicit declarations introduce only the function names operator
3066 // new, operator new[], operator delete, operator delete[].
3067 //
3068 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3069 // "std" or "bad_alloc" as necessary to form the exception specification.
3070 // However, we do not make these implicit declarations visible to name
3071 // lookup.
3072 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3073 // The "std::bad_alloc" class has not yet been declared, so build it
3074 // implicitly.
3078 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3079 getStdBadAlloc()->setImplicit(true);
3080
3081 // The implicitly declared "std::bad_alloc" should live in global module
3082 // fragment.
3083 if (TheGlobalModuleFragment) {
3086 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3087 }
3088 }
3089 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3090 // The "std::align_val_t" enum class has not yet been declared, so build it
3091 // implicitly.
3092 auto *AlignValT = EnumDecl::Create(
3094 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3095
3096 // The implicitly declared "std::align_val_t" should live in global module
3097 // fragment.
3098 if (TheGlobalModuleFragment) {
3099 AlignValT->setModuleOwnershipKind(
3101 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3102 }
3103
3104 AlignValT->setIntegerType(Context.getSizeType());
3105 AlignValT->setPromotionType(Context.getSizeType());
3106 AlignValT->setImplicit(true);
3107
3108 StdAlignValT = AlignValT;
3109 }
3110
3112
3114 QualType SizeT = Context.getSizeType();
3115
3116 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3117 QualType Return, QualType Param) {
3119 Params.push_back(Param);
3120
3121 // Create up to four variants of the function (sized/aligned).
3122 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3123 (Kind == OO_Delete || Kind == OO_Array_Delete);
3124 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3125
3126 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3127 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3128 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3129 if (Sized)
3130 Params.push_back(SizeT);
3131
3132 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3133 if (Aligned)
3134 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3135
3137 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3138
3139 if (Aligned)
3140 Params.pop_back();
3141 }
3142 }
3143 };
3144
3145 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3146 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3147 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3148 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3149
3150 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3151 PopGlobalModuleFragment();
3152}
3153
3154/// DeclareGlobalAllocationFunction - Declares a single implicit global
3155/// allocation function if it doesn't already exist.
3157 QualType Return,
3158 ArrayRef<QualType> Params) {
3160
3161 // Check if this function is already declared.
3162 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3163 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3164 Alloc != AllocEnd; ++Alloc) {
3165 // Only look at non-template functions, as it is the predefined,
3166 // non-templated allocation function we are trying to declare here.
3167 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3168 if (Func->getNumParams() == Params.size()) {
3170 for (auto *P : Func->parameters())
3171 FuncParams.push_back(
3172 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3173 if (llvm::ArrayRef(FuncParams) == Params) {
3174 // Make the function visible to name lookup, even if we found it in
3175 // an unimported module. It either is an implicitly-declared global
3176 // allocation function, or is suppressing that function.
3177 Func->setVisibleDespiteOwningModule();
3178 return;
3179 }
3180 }
3181 }
3182 }
3183
3185 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3186
3187 QualType BadAllocType;
3188 bool HasBadAllocExceptionSpec
3189 = (Name.getCXXOverloadedOperator() == OO_New ||
3190 Name.getCXXOverloadedOperator() == OO_Array_New);
3191 if (HasBadAllocExceptionSpec) {
3192 if (!getLangOpts().CPlusPlus11) {
3193 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3194 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3196 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3197 }
3198 if (getLangOpts().NewInfallible) {
3200 }
3201 } else {
3202 EPI.ExceptionSpec =
3204 }
3205
3206 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3207 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3209 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3210 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3211 true);
3212 Alloc->setImplicit();
3213 // Global allocation functions should always be visible.
3214 Alloc->setVisibleDespiteOwningModule();
3215
3216 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3217 !getLangOpts().CheckNew)
3218 Alloc->addAttr(
3219 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3220
3221 // C++ [basic.stc.dynamic.general]p2:
3222 // The library provides default definitions for the global allocation
3223 // and deallocation functions. Some global allocation and deallocation
3224 // functions are replaceable ([new.delete]); these are attached to the
3225 // global module ([module.unit]).
3226 //
3227 // In the language wording, these functions are attched to the global
3228 // module all the time. But in the implementation, the global module
3229 // is only meaningful when we're in a module unit. So here we attach
3230 // these allocation functions to global module conditionally.
3231 if (TheGlobalModuleFragment) {
3232 Alloc->setModuleOwnershipKind(
3234 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3235 }
3236
3238 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3240 ? VisibilityAttr::Hidden
3242 ? VisibilityAttr::Protected
3243 : VisibilityAttr::Default));
3244
3246 for (QualType T : Params) {
3247 ParamDecls.push_back(ParmVarDecl::Create(
3248 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3249 /*TInfo=*/nullptr, SC_None, nullptr));
3250 ParamDecls.back()->setImplicit();
3251 }
3252 Alloc->setParams(ParamDecls);
3253 if (ExtraAttr)
3254 Alloc->addAttr(ExtraAttr);
3257 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3258 };
3259
3260 if (!LangOpts.CUDA)
3261 CreateAllocationFunctionDecl(nullptr);
3262 else {
3263 // Host and device get their own declaration so each can be
3264 // defined or re-declared independently.
3265 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3266 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3267 }
3268}
3269
3271 bool CanProvideSize,
3272 bool Overaligned,
3273 DeclarationName Name) {
3275
3276 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3278
3279 // FIXME: It's possible for this to result in ambiguity, through a
3280 // user-declared variadic operator delete or the enable_if attribute. We
3281 // should probably not consider those cases to be usual deallocation
3282 // functions. But for now we just make an arbitrary choice in that case.
3283 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3284 Overaligned);
3285 assert(Result.FD && "operator delete missing from global scope?");
3286 return Result.FD;
3287}
3288
3290 CXXRecordDecl *RD) {
3292
3293 FunctionDecl *OperatorDelete = nullptr;
3294 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3295 return nullptr;
3296 if (OperatorDelete)
3297 return OperatorDelete;
3298
3299 // If there's no class-specific operator delete, look up the global
3300 // non-array delete.
3303 Name);
3304}
3305
3307 DeclarationName Name,
3308 FunctionDecl *&Operator, bool Diagnose,
3309 bool WantSize, bool WantAligned) {
3310 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3311 // Try to find operator delete/operator delete[] in class scope.
3313
3314 if (Found.isAmbiguous())
3315 return true;
3316
3317 Found.suppressDiagnostics();
3318
3319 bool Overaligned =
3320 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3321
3322 // C++17 [expr.delete]p10:
3323 // If the deallocation functions have class scope, the one without a
3324 // parameter of type std::size_t is selected.
3326 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3327 /*WantAlign*/ Overaligned, &Matches);
3328
3329 // If we could find an overload, use it.
3330 if (Matches.size() == 1) {
3331 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3332
3333 // FIXME: DiagnoseUseOfDecl?
3334 if (Operator->isDeleted()) {
3335 if (Diagnose) {
3336 StringLiteral *Msg = Operator->getDeletedMessage();
3337 Diag(StartLoc, diag::err_deleted_function_use)
3338 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3339 NoteDeletedFunction(Operator);
3340 }
3341 return true;
3342 }
3343
3344 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3345 Matches[0].Found, Diagnose) == AR_inaccessible)
3346 return true;
3347
3348 return false;
3349 }
3350
3351 // We found multiple suitable operators; complain about the ambiguity.
3352 // FIXME: The standard doesn't say to do this; it appears that the intent
3353 // is that this should never happen.
3354 if (!Matches.empty()) {
3355 if (Diagnose) {
3356 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3357 << Name << RD;
3358 for (auto &Match : Matches)
3359 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3360 }
3361 return true;
3362 }
3363
3364 // We did find operator delete/operator delete[] declarations, but
3365 // none of them were suitable.
3366 if (!Found.empty()) {
3367 if (Diagnose) {
3368 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3369 << Name << RD;
3370
3371 for (NamedDecl *D : Found)
3372 Diag(D->getUnderlyingDecl()->getLocation(),
3373 diag::note_member_declared_here) << Name;
3374 }
3375 return true;
3376 }
3377
3378 Operator = nullptr;
3379 return false;
3380}
3381
3382namespace {
3383/// Checks whether delete-expression, and new-expression used for
3384/// initializing deletee have the same array form.
3385class MismatchingNewDeleteDetector {
3386public:
3387 enum MismatchResult {
3388 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3389 NoMismatch,
3390 /// Indicates that variable is initialized with mismatching form of \a new.
3391 VarInitMismatches,
3392 /// Indicates that member is initialized with mismatching form of \a new.
3393 MemberInitMismatches,
3394 /// Indicates that 1 or more constructors' definitions could not been
3395 /// analyzed, and they will be checked again at the end of translation unit.
3396 AnalyzeLater
3397 };
3398
3399 /// \param EndOfTU True, if this is the final analysis at the end of
3400 /// translation unit. False, if this is the initial analysis at the point
3401 /// delete-expression was encountered.
3402 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3403 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3404 HasUndefinedConstructors(false) {}
3405
3406 /// Checks whether pointee of a delete-expression is initialized with
3407 /// matching form of new-expression.
3408 ///
3409 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3410 /// point where delete-expression is encountered, then a warning will be
3411 /// issued immediately. If return value is \c AnalyzeLater at the point where
3412 /// delete-expression is seen, then member will be analyzed at the end of
3413 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3414 /// couldn't be analyzed. If at least one constructor initializes the member
3415 /// with matching type of new, the return value is \c NoMismatch.
3416 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3417 /// Analyzes a class member.
3418 /// \param Field Class member to analyze.
3419 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3420 /// for deleting the \p Field.
3421 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3423 /// List of mismatching new-expressions used for initialization of the pointee
3425 /// Indicates whether delete-expression was in array form.
3426 bool IsArrayForm;
3427
3428private:
3429 const bool EndOfTU;
3430 /// Indicates that there is at least one constructor without body.
3431 bool HasUndefinedConstructors;
3432 /// Returns \c CXXNewExpr from given initialization expression.
3433 /// \param E Expression used for initializing pointee in delete-expression.
3434 /// E can be a single-element \c InitListExpr consisting of new-expression.
3435 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3436 /// Returns whether member is initialized with mismatching form of
3437 /// \c new either by the member initializer or in-class initialization.
3438 ///
3439 /// If bodies of all constructors are not visible at the end of translation
3440 /// unit or at least one constructor initializes member with the matching
3441 /// form of \c new, mismatch cannot be proven, and this function will return
3442 /// \c NoMismatch.
3443 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3444 /// Returns whether variable is initialized with mismatching form of
3445 /// \c new.
3446 ///
3447 /// If variable is initialized with matching form of \c new or variable is not
3448 /// initialized with a \c new expression, this function will return true.
3449 /// If variable is initialized with mismatching form of \c new, returns false.
3450 /// \param D Variable to analyze.
3451 bool hasMatchingVarInit(const DeclRefExpr *D);
3452 /// Checks whether the constructor initializes pointee with mismatching
3453 /// form of \c new.
3454 ///
3455 /// Returns true, if member is initialized with matching form of \c new in
3456 /// member initializer list. Returns false, if member is initialized with the
3457 /// matching form of \c new in this constructor's initializer or given
3458 /// constructor isn't defined at the point where delete-expression is seen, or
3459 /// member isn't initialized by the constructor.
3460 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3461 /// Checks whether member is initialized with matching form of
3462 /// \c new in member initializer list.
3463 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3464 /// Checks whether member is initialized with mismatching form of \c new by
3465 /// in-class initializer.
3466 MismatchResult analyzeInClassInitializer();
3467};
3468}
3469
3470MismatchingNewDeleteDetector::MismatchResult
3471MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3472 NewExprs.clear();
3473 assert(DE && "Expected delete-expression");
3474 IsArrayForm = DE->isArrayForm();
3475 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3476 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3477 return analyzeMemberExpr(ME);
3478 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3479 if (!hasMatchingVarInit(D))
3480 return VarInitMismatches;
3481 }
3482 return NoMismatch;
3483}
3484
3485const CXXNewExpr *
3486MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3487 assert(E != nullptr && "Expected a valid initializer expression");
3488 E = E->IgnoreParenImpCasts();
3489 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3490 if (ILE->getNumInits() == 1)
3491 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3492 }
3493
3494 return dyn_cast_or_null<const CXXNewExpr>(E);
3495}
3496
3497bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3498 const CXXCtorInitializer *CI) {
3499 const CXXNewExpr *NE = nullptr;
3500 if (Field == CI->getMember() &&
3501 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3502 if (NE->isArray() == IsArrayForm)
3503 return true;
3504 else
3505 NewExprs.push_back(NE);
3506 }
3507 return false;
3508}
3509
3510bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3511 const CXXConstructorDecl *CD) {
3512 if (CD->isImplicit())
3513 return false;
3514 const FunctionDecl *Definition = CD;
3516 HasUndefinedConstructors = true;
3517 return EndOfTU;
3518 }
3519 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3520 if (hasMatchingNewInCtorInit(CI))
3521 return true;
3522 }
3523 return false;
3524}
3525
3526MismatchingNewDeleteDetector::MismatchResult
3527MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3528 assert(Field != nullptr && "This should be called only for members");
3529 const Expr *InitExpr = Field->getInClassInitializer();
3530 if (!InitExpr)
3531 return EndOfTU ? NoMismatch : AnalyzeLater;
3532 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3533 if (NE->isArray() != IsArrayForm) {
3534 NewExprs.push_back(NE);
3535 return MemberInitMismatches;
3536 }
3537 }
3538 return NoMismatch;
3539}
3540
3541MismatchingNewDeleteDetector::MismatchResult
3542MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3543 bool DeleteWasArrayForm) {
3544 assert(Field != nullptr && "Analysis requires a valid class member.");
3545 this->Field = Field;
3546 IsArrayForm = DeleteWasArrayForm;
3547 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3548 for (const auto *CD : RD->ctors()) {
3549 if (hasMatchingNewInCtor(CD))
3550 return NoMismatch;
3551 }
3552 if (HasUndefinedConstructors)
3553 return EndOfTU ? NoMismatch : AnalyzeLater;
3554 if (!NewExprs.empty())
3555 return MemberInitMismatches;
3556 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3557 : NoMismatch;
3558}
3559
3560MismatchingNewDeleteDetector::MismatchResult
3561MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3562 assert(ME != nullptr && "Expected a member expression");
3563 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3564 return analyzeField(F, IsArrayForm);
3565 return NoMismatch;
3566}
3567
3568bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3569 const CXXNewExpr *NE = nullptr;
3570 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3571 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3572 NE->isArray() != IsArrayForm) {
3573 NewExprs.push_back(NE);
3574 }
3575 }
3576 return NewExprs.empty();
3577}
3578
3579static void
3581 const MismatchingNewDeleteDetector &Detector) {
3582 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3583 FixItHint H;
3584 if (!Detector.IsArrayForm)
3585 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3586 else {
3588 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3589 SemaRef.getLangOpts(), true);
3590 if (RSquare.isValid())
3591 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3592 }
3593 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3594 << Detector.IsArrayForm << H;
3595
3596 for (const auto *NE : Detector.NewExprs)
3597 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3598 << Detector.IsArrayForm;
3599}
3600
3601void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3602 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3603 return;
3604 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3605 switch (Detector.analyzeDeleteExpr(DE)) {
3606 case MismatchingNewDeleteDetector::VarInitMismatches:
3607 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3608 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3609 break;
3610 }
3611 case MismatchingNewDeleteDetector::AnalyzeLater: {
3612 DeleteExprs[Detector.Field].push_back(
3613 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3614 break;
3615 }
3616 case MismatchingNewDeleteDetector::NoMismatch:
3617 break;
3618 }
3619}
3620
3621void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3622 bool DeleteWasArrayForm) {
3623 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3624 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3625 case MismatchingNewDeleteDetector::VarInitMismatches:
3626 llvm_unreachable("This analysis should have been done for class members.");
3627 case MismatchingNewDeleteDetector::AnalyzeLater:
3628 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3629 "translation unit.");
3630 case MismatchingNewDeleteDetector::MemberInitMismatches:
3631 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3632 break;
3633 case MismatchingNewDeleteDetector::NoMismatch:
3634 break;
3635 }
3636}
3637
3639Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3640 bool ArrayForm, Expr *ExE) {
3641 // C++ [expr.delete]p1:
3642 // The operand shall have a pointer type, or a class type having a single
3643 // non-explicit conversion function to a pointer type. The result has type
3644 // void.
3645 //
3646 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3647
3648 ExprResult Ex = ExE;
3649 FunctionDecl *OperatorDelete = nullptr;
3650 bool ArrayFormAsWritten = ArrayForm;
3651 bool UsualArrayDeleteWantsSize = false;
3652
3653 if (!Ex.get()->isTypeDependent()) {
3654 // Perform lvalue-to-rvalue cast, if needed.
3655 Ex = DefaultLvalueConversion(Ex.get());
3656 if (Ex.isInvalid())
3657 return ExprError();
3658
3659 QualType Type = Ex.get()->getType();
3660
3661 class DeleteConverter : public ContextualImplicitConverter {
3662 public:
3663 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3664
3665 bool match(QualType ConvType) override {
3666 // FIXME: If we have an operator T* and an operator void*, we must pick
3667 // the operator T*.
3668 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3669 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3670 return true;
3671 return false;
3672 }
3673
3674 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3675 QualType T) override {
3676 return S.Diag(Loc, diag::err_delete_operand) << T;
3677 }
3678
3679 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3680 QualType T) override {
3681 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3682 }
3683
3684 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3685 QualType T,
3686 QualType ConvTy) override {
3687 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3688 }
3689
3690 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3691 QualType ConvTy) override {
3692 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3693 << ConvTy;
3694 }
3695
3696 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3697 QualType T) override {
3698 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3699 }
3700
3701 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3702 QualType ConvTy) override {
3703 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3704 << ConvTy;
3705 }
3706
3707 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3708 QualType T,
3709 QualType ConvTy) override {
3710 llvm_unreachable("conversion functions are permitted");
3711 }
3712 } Converter;
3713
3714 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3715 if (Ex.isInvalid())
3716 return ExprError();
3717 Type = Ex.get()->getType();
3718 if (!Converter.match(Type))
3719 // FIXME: PerformContextualImplicitConversion should return ExprError
3720 // itself in this case.
3721 return ExprError();
3722
3724 QualType PointeeElem = Context.getBaseElementType(Pointee);
3725
3726 if (Pointee.getAddressSpace() != LangAS::Default &&
3727 !getLangOpts().OpenCLCPlusPlus)
3728 return Diag(Ex.get()->getBeginLoc(),
3729 diag::err_address_space_qualified_delete)
3730 << Pointee.getUnqualifiedType()
3732
3733 CXXRecordDecl *PointeeRD = nullptr;
3734 if (Pointee->isVoidType() && !isSFINAEContext()) {
3735 // The C++ standard bans deleting a pointer to a non-object type, which
3736 // effectively bans deletion of "void*". However, most compilers support
3737 // this, so we treat it as a warning unless we're in a SFINAE context.
3738 // But we still prohibit this since C++26.
3739 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
3740 : diag::ext_delete_void_ptr_operand)
3741 << (LangOpts.CPlusPlus26 ? Pointee : Type)
3742 << Ex.get()->getSourceRange();
3743 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3744 Pointee->isSizelessType()) {
3745 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3746 << Type << Ex.get()->getSourceRange());
3747 } else if (!Pointee->isDependentType()) {
3748 // FIXME: This can result in errors if the definition was imported from a
3749 // module but is hidden.
3750 if (Pointee->isEnumeralType() ||
3751 !RequireCompleteType(StartLoc, Pointee,
3752 LangOpts.CPlusPlus26
3753 ? diag::err_delete_incomplete
3754 : diag::warn_delete_incomplete,
3755 Ex.get())) {
3756 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3757 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3758 }
3759 }
3760
3761 if (Pointee->isArrayType() && !ArrayForm) {
3762 Diag(StartLoc, diag::warn_delete_array_type)
3763 << Type << Ex.get()->getSourceRange()
3765 ArrayForm = true;
3766 }
3767
3769 ArrayForm ? OO_Array_Delete : OO_Delete);
3770
3771 if (PointeeRD) {
3772 if (!UseGlobal &&
3773 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3774 OperatorDelete))
3775 return ExprError();
3776
3777 // If we're allocating an array of records, check whether the
3778 // usual operator delete[] has a size_t parameter.
3779 if (ArrayForm) {
3780 // If the user specifically asked to use the global allocator,
3781 // we'll need to do the lookup into the class.
3782 if (UseGlobal)
3783 UsualArrayDeleteWantsSize =
3784 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3785
3786 // Otherwise, the usual operator delete[] should be the
3787 // function we just found.
3788 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete))
3789 UsualArrayDeleteWantsSize =
3790 UsualDeallocFnInfo(*this,
3791 DeclAccessPair::make(OperatorDelete, AS_public))
3792 .HasSizeT;
3793 }
3794
3795 if (!PointeeRD->hasIrrelevantDestructor())
3796 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3797 MarkFunctionReferenced(StartLoc,
3798 const_cast<CXXDestructorDecl*>(Dtor));
3799 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3800 return ExprError();
3801 }
3802
3803 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3804 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3805 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3806 SourceLocation());
3807 }
3808
3809 if (!OperatorDelete) {
3810 if (getLangOpts().OpenCLCPlusPlus) {
3811 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3812 return ExprError();
3813 }
3814
3815 bool IsComplete = isCompleteType(StartLoc, Pointee);
3816 bool CanProvideSize =
3817 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3818 Pointee.isDestructedType());
3819 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3820
3821 // Look for a global declaration.
3822 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3823 Overaligned, DeleteName);
3824 }
3825
3826 if (OperatorDelete->isInvalidDecl())
3827 return ExprError();
3828
3829 MarkFunctionReferenced(StartLoc, OperatorDelete);
3830
3831 // Check access and ambiguity of destructor if we're going to call it.
3832 // Note that this is required even for a virtual delete.
3833 bool IsVirtualDelete = false;
3834 if (PointeeRD) {
3835 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3836 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3837 PDiag(diag::err_access_dtor) << PointeeElem);
3838 IsVirtualDelete = Dtor->isVirtual();
3839 }
3840 }
3841
3842 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3843
3844 // Convert the operand to the type of the first parameter of operator
3845 // delete. This is only necessary if we selected a destroying operator
3846 // delete that we are going to call (non-virtually); converting to void*
3847 // is trivial and left to AST consumers to handle.
3848 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3849 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3850 Qualifiers Qs = Pointee.getQualifiers();
3851 if (Qs.hasCVRQualifiers()) {
3852 // Qualifiers are irrelevant to this conversion; we're only looking
3853 // for access and ambiguity.
3857 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3858 }
3859 Ex = PerformImplicitConversion(Ex.get(), ParamType,
3861 if (Ex.isInvalid())
3862 return ExprError();
3863 }
3864 }
3865
3867 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3868 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3869 AnalyzeDeleteExprMismatch(Result);
3870 return Result;
3871}
3872
3874 bool IsDelete,
3875 FunctionDecl *&Operator) {
3876
3878 IsDelete ? OO_Delete : OO_New);
3879
3880 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3882 assert(!R.empty() && "implicitly declared allocation functions not found");
3883 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3884
3885 // We do our own custom access checks below.
3887
3888 SmallVector<Expr *, 8> Args(TheCall->arguments());
3889 OverloadCandidateSet Candidates(R.getNameLoc(),
3891 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3892 FnOvl != FnOvlEnd; ++FnOvl) {
3893 // Even member operator new/delete are implicitly treated as
3894 // static, so don't use AddMemberCandidate.
3895 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3896
3897 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3898 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3899 /*ExplicitTemplateArgs=*/nullptr, Args,
3900 Candidates,
3901 /*SuppressUserConversions=*/false);
3902 continue;
3903 }
3904
3905 FunctionDecl *Fn = cast<FunctionDecl>(D);
3906 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3907 /*SuppressUserConversions=*/false);
3908 }
3909
3910 SourceRange Range = TheCall->getSourceRange();
3911
3912 // Do the resolution.
3914 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3915 case OR_Success: {
3916 // Got one!
3917 FunctionDecl *FnDecl = Best->Function;
3918 assert(R.getNamingClass() == nullptr &&
3919 "class members should not be considered");
3920
3922 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3923 << (IsDelete ? 1 : 0) << Range;
3924 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3925 << R.getLookupName() << FnDecl->getSourceRange();
3926 return true;
3927 }
3928
3929 Operator = FnDecl;
3930 return false;
3931 }
3932
3934 Candidates.NoteCandidates(
3936 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3937 << R.getLookupName() << Range),
3938 S, OCD_AllCandidates, Args);
3939 return true;
3940
3941 case OR_Ambiguous:
3942 Candidates.NoteCandidates(
3944 S.PDiag(diag::err_ovl_ambiguous_call)
3945 << R.getLookupName() << Range),
3946 S, OCD_AmbiguousCandidates, Args);
3947 return true;
3948
3949 case OR_Deleted:
3951 Candidates, Best->Function, Args);
3952 return true;
3953 }
3954 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3955}
3956
3957ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3958 bool IsDelete) {
3959 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3960 if (!getLangOpts().CPlusPlus) {
3961 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3962 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3963 << "C++";
3964 return ExprError();
3965 }
3966 // CodeGen assumes it can find the global new and delete to call,
3967 // so ensure that they are declared.
3969
3970 FunctionDecl *OperatorNewOrDelete = nullptr;
3971 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3972 OperatorNewOrDelete))
3973 return ExprError();
3974 assert(OperatorNewOrDelete && "should be found");
3975
3976 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3977 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3978
3979 TheCall->setType(OperatorNewOrDelete->getReturnType());
3980 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3981 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3982 InitializedEntity Entity =
3985 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3986 if (Arg.isInvalid())
3987 return ExprError();
3988 TheCall->setArg(i, Arg.get());
3989 }
3990 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3991 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3992 "Callee expected to be implicit cast to a builtin function pointer");
3993 Callee->setType(OperatorNewOrDelete->getType());
3994
3995 return TheCallResult;
3996}
3997
3999 bool IsDelete, bool CallCanBeVirtual,
4000 bool WarnOnNonAbstractTypes,
4001 SourceLocation DtorLoc) {
4002 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4003 return;
4004
4005 // C++ [expr.delete]p3:
4006 // In the first alternative (delete object), if the static type of the
4007 // object to be deleted is different from its dynamic type, the static
4008 // type shall be a base class of the dynamic type of the object to be
4009 // deleted and the static type shall have a virtual destructor or the
4010 // behavior is undefined.
4011 //
4012 const CXXRecordDecl *PointeeRD = dtor->getParent();
4013 // Note: a final class cannot be derived from, no issue there
4014 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4015 return;
4016
4017 // If the superclass is in a system header, there's nothing that can be done.
4018 // The `delete` (where we emit the warning) can be in a system header,
4019 // what matters for this warning is where the deleted type is defined.
4020 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4021 return;
4022
4023 QualType ClassType = dtor->getFunctionObjectParameterType();
4024 if (PointeeRD->isAbstract()) {
4025 // If the class is abstract, we warn by default, because we're
4026 // sure the code has undefined behavior.
4027 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4028 << ClassType;
4029 } else if (WarnOnNonAbstractTypes) {
4030 // Otherwise, if this is not an array delete, it's a bit suspect,
4031 // but not necessarily wrong.
4032 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4033 << ClassType;
4034 }
4035 if (!IsDelete) {
4036 std::string TypeStr;
4037 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4038 Diag(DtorLoc, diag::note_delete_non_virtual)
4039 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4040 }
4041}
4042
4044 SourceLocation StmtLoc,
4045 ConditionKind CK) {
4046 ExprResult E =
4047 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4048 if (E.isInvalid())
4049 return ConditionError();
4050 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4052}
4053
4055 SourceLocation StmtLoc,
4056 ConditionKind CK) {
4057 if (ConditionVar->isInvalidDecl())
4058 return ExprError();
4059
4060 QualType T = ConditionVar->getType();
4061
4062 // C++ [stmt.select]p2:
4063 // The declarator shall not specify a function or an array.
4064 if (T->isFunctionType())
4065 return ExprError(Diag(ConditionVar->getLocation(),
4066 diag::err_invalid_use_of_function_type)
4067 << ConditionVar->getSourceRange());
4068 else if (T->isArrayType())
4069 return ExprError(Diag(ConditionVar->getLocation(),
4070 diag::err_invalid_use_of_array_type)
4071 << ConditionVar->getSourceRange());
4072
4074 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4075 ConditionVar->getLocation());
4076
4077 switch (CK) {
4079 return CheckBooleanCondition(StmtLoc, Condition.get());
4080
4082 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4083
4085 return CheckSwitchCondition(StmtLoc, Condition.get());
4086 }
4087
4088 llvm_unreachable("unexpected condition kind");
4089}
4090
4091ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4092 // C++11 6.4p4:
4093 // The value of a condition that is an initialized declaration in a statement
4094 // other than a switch statement is the value of the declared variable
4095 // implicitly converted to type bool. If that conversion is ill-formed, the
4096 // program is ill-formed.
4097 // The value of a condition that is an expression is the value of the
4098 // expression, implicitly converted to bool.
4099 //
4100 // C++23 8.5.2p2
4101 // If the if statement is of the form if constexpr, the value of the condition
4102 // is contextually converted to bool and the converted expression shall be
4103 // a constant expression.
4104 //
4105
4107 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4108 return E;
4109
4110 // FIXME: Return this value to the caller so they don't need to recompute it.
4111 llvm::APSInt Cond;
4113 E.get(), &Cond,
4114 diag::err_constexpr_if_condition_expression_is_not_constant);
4115 return E;
4116}
4117
4118bool
4120 // Look inside the implicit cast, if it exists.
4121 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4122 From = Cast->getSubExpr();
4123
4124 // A string literal (2.13.4) that is not a wide string literal can
4125 // be converted to an rvalue of type "pointer to char"; a wide
4126 // string literal can be converted to an rvalue of type "pointer
4127 // to wchar_t" (C++ 4.2p2).
4128 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4129 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4130 if (const BuiltinType *ToPointeeType
4131 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4132 // This conversion is considered only when there is an
4133 // explicit appropriate pointer target type (C++ 4.2p2).
4134 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4135 switch (StrLit->getKind()) {
4139 // We don't allow UTF literals to be implicitly converted
4140 break;
4142 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4143 ToPointeeType->getKind() == BuiltinType::Char_S);
4146 QualType(ToPointeeType, 0));
4148 assert(false && "Unevaluated string literal in expression");
4149 break;
4150 }
4151 }
4152 }
4153
4154 return false;
4155}
4156
4158 SourceLocation CastLoc,
4159 QualType Ty,
4160 CastKind Kind,
4161 CXXMethodDecl *Method,
4162 DeclAccessPair FoundDecl,
4163 bool HadMultipleCandidates,
4164 Expr *From) {
4165 switch (Kind) {
4166 default: llvm_unreachable("Unhandled cast kind!");
4167 case CK_ConstructorConversion: {
4168 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4169 SmallVector<Expr*, 8> ConstructorArgs;
4170
4171 if (S.RequireNonAbstractType(CastLoc, Ty,
4172 diag::err_allocation_of_abstract_type))
4173 return ExprError();
4174
4175 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4176 ConstructorArgs))
4177 return ExprError();
4178
4179 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4181 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4182 return ExprError();
4183
4185 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4186 ConstructorArgs, HadMultipleCandidates,
4187 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4189 if (Result.isInvalid())
4190 return ExprError();
4191
4192 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4193 }
4194
4195 case CK_UserDefinedConversion: {
4196 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4197
4198 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4199 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4200 return ExprError();
4201
4202 // Create an implicit call expr that calls it.
4203 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4204 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4205 HadMultipleCandidates);
4206 if (Result.isInvalid())
4207 return ExprError();
4208 // Record usage of conversion in an implicit cast.
4209 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4210 CK_UserDefinedConversion, Result.get(),
4211 nullptr, Result.get()->getValueKind(),
4213
4214 return S.MaybeBindToTemporary(Result.get());
4215 }
4216 }
4217}
4218
4221 const ImplicitConversionSequence &ICS,
4222 AssignmentAction Action,
4224 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4226 !From->getType()->isRecordType())
4227 return From;
4228
4229 switch (ICS.getKind()) {
4231 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4232 Action, CCK);
4233 if (Res.isInvalid())
4234 return ExprError();
4235 From = Res.get();
4236 break;
4237 }
4238
4240
4243 QualType BeforeToType;
4244 assert(FD && "no conversion function for user-defined conversion seq");
4245 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4246 CastKind = CK_UserDefinedConversion;
4247
4248 // If the user-defined conversion is specified by a conversion function,
4249 // the initial standard conversion sequence converts the source type to
4250 // the implicit object parameter of the conversion function.
4251 BeforeToType = Context.getTagDeclType(Conv->getParent());
4252 } else {
4253 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4254 CastKind = CK_ConstructorConversion;
4255 // Do no conversion if dealing with ... for the first conversion.
4257 // If the user-defined conversion is specified by a constructor, the
4258 // initial standard conversion sequence converts the source type to
4259 // the type required by the argument of the constructor
4260 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4261 }
4262 }
4263 // Watch out for ellipsis conversion.
4266 From, BeforeToType, ICS.UserDefined.Before,
4268 if (Res.isInvalid())
4269 return ExprError();
4270 From = Res.get();
4271 }
4272
4274 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4275 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4277
4278 if (CastArg.isInvalid())
4279 return ExprError();
4280
4281 From = CastArg.get();
4282
4283 // C++ [over.match.oper]p7:
4284 // [...] the second standard conversion sequence of a user-defined
4285 // conversion sequence is not applied.
4287 return From;
4288
4289 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4291 }
4292
4294 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4295 PDiag(diag::err_typecheck_ambiguous_condition)
4296 << From->getSourceRange());
4297 return ExprError();
4298
4301 llvm_unreachable("bad conversion");
4302
4305 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4306 bool Diagnosed = DiagnoseAssignmentResult(
4307 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4308 ToType, From->getType(), From, Action);
4309 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4310 return ExprError();
4311 }
4312
4313 // Everything went well.
4314 return From;
4315}
4316
4317// adjustVectorType - Compute the intermediate cast type casting elements of the
4318// from type to the elements of the to type without resizing the vector.
4320 QualType ToType, QualType *ElTy = nullptr) {
4321 QualType ElType = ToType;
4322 if (auto *ToVec = ToType->getAs<VectorType>())
4323 ElType = ToVec->getElementType();
4324
4325 if (ElTy)
4326 *ElTy = ElType;
4327 if (!FromTy->isVectorType())
4328 return ElType;
4329 auto *FromVec = FromTy->castAs<VectorType>();
4330 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4331}
4332
4335 const StandardConversionSequence& SCS,
4336 AssignmentAction Action,
4338 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4340
4341 // Overall FIXME: we are recomputing too many types here and doing far too
4342 // much extra work. What this means is that we need to keep track of more
4343 // information that is computed when we try the implicit conversion initially,
4344 // so that we don't need to recompute anything here.
4345 QualType FromType = From->getType();
4346
4347 if (SCS.CopyConstructor) {
4348 // FIXME: When can ToType be a reference type?
4349 assert(!ToType->isReferenceType());
4350 if (SCS.Second == ICK_Derived_To_Base) {
4351 SmallVector<Expr*, 8> ConstructorArgs;
4353 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4354 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4355 return ExprError();
4356 return BuildCXXConstructExpr(
4357 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4358 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4359 /*HadMultipleCandidates*/ false,
4360 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4362 }
4363 return BuildCXXConstructExpr(
4364 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4366 /*HadMultipleCandidates*/ false,
4367 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4369 }
4370
4371 // Resolve overloaded function references.
4372 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4375 true, Found);
4376 if (!Fn)
4377 return ExprError();
4378
4379 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4380 return ExprError();
4381
4383 if (Res.isInvalid())
4384 return ExprError();
4385
4386 // We might get back another placeholder expression if we resolved to a
4387 // builtin.
4388 Res = CheckPlaceholderExpr(Res.get());
4389 if (Res.isInvalid())
4390 return ExprError();
4391
4392 From = Res.get();
4393 FromType = From->getType();
4394 }
4395
4396 // If we're converting to an atomic type, first convert to the corresponding
4397 // non-atomic type.
4398 QualType ToAtomicType;
4399 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4400 ToAtomicType = ToType;
4401 ToType = ToAtomic->getValueType();
4402 }
4403
4404 QualType InitialFromType = FromType;
4405 // Perform the first implicit conversion.
4406 switch (SCS.First) {
4407 case ICK_Identity:
4408 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4409 FromType = FromAtomic->getValueType().getUnqualifiedType();
4410 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4411 From, /*BasePath=*/nullptr, VK_PRValue,
4413 }
4414 break;
4415
4416 case ICK_Lvalue_To_Rvalue: {
4417 assert(From->getObjectKind() != OK_ObjCProperty);
4418 ExprResult FromRes = DefaultLvalueConversion(From);
4419 if (FromRes.isInvalid())
4420 return ExprError();
4421
4422 From = FromRes.get();
4423 FromType = From->getType();
4424 break;
4425 }
4426
4428 FromType = Context.getArrayDecayedType(FromType);
4429 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4430 /*BasePath=*/nullptr, CCK)
4431 .get();
4432 break;
4433
4435 if (ToType->isArrayParameterType()) {
4436 FromType = Context.getArrayParameterType(FromType);
4437 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4438 /*BasePath=*/nullptr, CCK)
4439 .get();
4440 } else { // FromType must be ArrayParameterType
4441 assert(FromType->isArrayParameterType() &&
4442 "FromType must be ArrayParameterType in ICK_HLSL_Array_RValue \
4443 if it is not ToType");
4444 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
4445 FromType = APT->getConstantArrayType(Context);
4446 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4447 /*BasePath=*/nullptr, CCK)
4448 .get();
4449 }
4450 break;
4451
4453 FromType = Context.getPointerType(FromType);
4454 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4455 VK_PRValue, /*BasePath=*/nullptr, CCK)
4456 .get();
4457 break;
4458
4459 default:
4460 llvm_unreachable("Improper first standard conversion");
4461 }
4462
4463 // Perform the second implicit conversion
4464 switch (SCS.Second) {
4465 case ICK_Identity:
4466 // C++ [except.spec]p5:
4467 // [For] assignment to and initialization of pointers to functions,
4468 // pointers to member functions, and references to functions: the
4469 // target entity shall allow at least the exceptions allowed by the
4470 // source value in the assignment or initialization.
4471 switch (Action) {
4474 // Note, function argument passing and returning are initialization.
4479 if (CheckExceptionSpecCompatibility(From, ToType))
4480 return ExprError();
4481 break;
4482
4485 // Casts and implicit conversions are not initialization, so are not
4486 // checked for exception specification mismatches.
4487 break;
4488 }
4489 // Nothing else to do.
4490 break;
4491
4494 QualType ElTy = ToType;
4495 QualType StepTy = ToType;
4496 if (FromType->isVectorType() || ToType->isVectorType())
4497 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4498 if (ElTy->isBooleanType()) {
4499 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4501 "only enums with fixed underlying type can promote to bool");
4502 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4503 /*BasePath=*/nullptr, CCK)
4504 .get();
4505 } else {
4506 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4507 /*BasePath=*/nullptr, CCK)
4508 .get();
4509 }
4510 break;
4511 }
4512
4515 QualType StepTy = ToType;
4516 if (FromType->isVectorType() || ToType->isVectorType())
4517 StepTy = adjustVectorType(Context, FromType, ToType);
4518 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4519 /*BasePath=*/nullptr, CCK)
4520 .get();
4521 break;
4522 }
4523
4526 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4527 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4528 CastKind CK;
4529 if (FromEl->isRealFloatingType()) {
4530 if (ToEl->isRealFloatingType())
4531 CK = CK_FloatingComplexCast;
4532 else
4533 CK = CK_FloatingComplexToIntegralComplex;
4534 } else if (ToEl->isRealFloatingType()) {
4535 CK = CK_IntegralComplexToFloatingComplex;
4536 } else {
4537 CK = CK_IntegralComplexCast;
4538 }
4539 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4540 CCK)
4541 .get();
4542 break;
4543 }
4544
4545 case ICK_Floating_Integral: {
4546 QualType ElTy = ToType;
4547 QualType StepTy = ToType;
4548 if (FromType->isVectorType() || ToType->isVectorType())
4549 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4550 if (ElTy->isRealFloatingType())
4551 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4552 /*BasePath=*/nullptr, CCK)
4553 .get();
4554 else
4555 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4556 /*BasePath=*/nullptr, CCK)
4557 .get();
4558 break;
4559 }
4560
4562 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4563 "Attempting implicit fixed point conversion without a fixed "
4564 "point operand");
4565 if (FromType->isFloatingType())
4566 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4567 VK_PRValue,
4568 /*BasePath=*/nullptr, CCK).get();
4569 else if (ToType->isFloatingType())
4570 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4571 VK_PRValue,
4572 /*BasePath=*/nullptr, CCK).get();
4573 else if (FromType->isIntegralType(Context))
4574 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4575 VK_PRValue,
4576 /*BasePath=*/nullptr, CCK).get();
4577 else if (ToType->isIntegralType(Context))
4578 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4579 VK_PRValue,
4580 /*BasePath=*/nullptr, CCK).get();
4581 else if (ToType->isBooleanType())
4582 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4583 VK_PRValue,
4584 /*BasePath=*/nullptr, CCK).get();
4585 else
4586 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4587 VK_PRValue,
4588 /*BasePath=*/nullptr, CCK).get();
4589 break;
4590
4592 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4593 /*BasePath=*/nullptr, CCK).get();
4594 break;
4595
4598 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {
4599 // Diagnose incompatible Objective-C conversions
4600 if (Action == AssignmentAction::Initializing ||
4602 Diag(From->getBeginLoc(),
4603 diag::ext_typecheck_convert_incompatible_pointer)
4604 << ToType << From->getType() << Action << From->getSourceRange()
4605 << 0;
4606 else
4607 Diag(From->getBeginLoc(),
4608 diag::ext_typecheck_convert_incompatible_pointer)
4609 << From->getType() << ToType << Action << From->getSourceRange()
4610 << 0;
4611
4612 if (From->getType()->isObjCObjectPointerType() &&
4613 ToType->isObjCObjectPointerType())
4615 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4616 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4617 From->getType())) {
4618 if (Action == AssignmentAction::Initializing)
4619 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4620 else
4621 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4622 << (Action == AssignmentAction::Casting) << From->getType()
4623 << ToType << From->getSourceRange();
4624 }
4625
4626 // Defer address space conversion to the third conversion.
4627 QualType FromPteeType = From->getType()->getPointeeType();
4628 QualType ToPteeType = ToType->getPointeeType();
4629 QualType NewToType = ToType;
4630 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4631 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4632 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4633 NewToType = Context.getAddrSpaceQualType(NewToType,
4634 FromPteeType.getAddressSpace());
4635 if (ToType->isObjCObjectPointerType())
4636 NewToType = Context.getObjCObjectPointerType(NewToType);
4637 else if (ToType->isBlockPointerType())
4638 NewToType = Context.getBlockPointerType(NewToType);
4639 else
4640 NewToType = Context.getPointerType(NewToType);
4641 }
4642
4643 CastKind Kind;
4644 CXXCastPath BasePath;
4645 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4646 return ExprError();
4647
4648 // Make sure we extend blocks if necessary.
4649 // FIXME: doing this here is really ugly.
4650 if (Kind == CK_BlockPointerToObjCPointerCast) {
4651 ExprResult E = From;
4653 From = E.get();
4654 }
4656 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4657 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4658 .get();
4659 break;
4660 }
4661
4662 case ICK_Pointer_Member: {
4663 CastKind Kind;
4664 CXXCastPath BasePath;
4665 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4666 return ExprError();
4667 if (CheckExceptionSpecCompatibility(From, ToType))
4668 return ExprError();
4669
4670 // We may not have been able to figure out what this member pointer resolved
4671 // to up until this exact point. Attempt to lock-in it's inheritance model.
4673 (void)isCompleteType(From->getExprLoc(), From->getType());
4674 (void)isCompleteType(From->getExprLoc(), ToType);
4675 }
4676
4677 From =
4678 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4679 break;
4680 }
4681
4683 // Perform half-to-boolean conversion via float.
4684 if (From->getType()->isHalfType()) {
4685 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4686 FromType = Context.FloatTy;
4687 }
4688 QualType ElTy = FromType;
4689 QualType StepTy = ToType;
4690 if (FromType->isVectorType())
4691 ElTy = FromType->castAs<VectorType>()->getElementType();
4692 if (getLangOpts().HLSL &&
4693 (FromType->isVectorType() || ToType->isVectorType()))
4694 StepTy = adjustVectorType(Context, FromType, ToType);
4695
4696 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
4697 VK_PRValue,
4698 /*BasePath=*/nullptr, CCK)
4699 .get();
4700 break;
4701 }
4702
4703 case ICK_Derived_To_Base: {
4704 CXXCastPath BasePath;
4706 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4707 From->getSourceRange(), &BasePath, CStyle))
4708 return ExprError();
4709
4710 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4711 CK_DerivedToBase, From->getValueKind(),
4712 &BasePath, CCK).get();
4713 break;
4714 }
4715
4717 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4718 /*BasePath=*/nullptr, CCK)
4719 .get();
4720 break;
4721
4724 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4725 /*BasePath=*/nullptr, CCK)
4726 .get();
4727 break;
4728
4729 case ICK_Vector_Splat: {
4730 // Vector splat from any arithmetic type to a vector.
4731 Expr *Elem = prepareVectorSplat(ToType, From).get();
4732 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4733 /*BasePath=*/nullptr, CCK)
4734 .get();
4735 break;
4736 }
4737
4738 case ICK_Complex_Real:
4739 // Case 1. x -> _Complex y
4740 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4741 QualType ElType = ToComplex->getElementType();
4742 bool isFloatingComplex = ElType->isRealFloatingType();
4743
4744 // x -> y
4745 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4746 // do nothing
4747 } else if (From->getType()->isRealFloatingType()) {
4748 From = ImpCastExprToType(From, ElType,
4749 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4750 } else {
4751 assert(From->getType()->isIntegerType());
4752 From = ImpCastExprToType(From, ElType,
4753 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4754 }
4755 // y -> _Complex y
4756 From = ImpCastExprToType(From, ToType,
4757 isFloatingComplex ? CK_FloatingRealToComplex
4758 : CK_IntegralRealToComplex).get();
4759
4760 // Case 2. _Complex x -> y
4761 } else {
4762 auto *FromComplex = From->getType()->castAs<ComplexType>();
4763 QualType ElType = FromComplex->getElementType();
4764 bool isFloatingComplex = ElType->isRealFloatingType();
4765
4766 // _Complex x -> x
4767 From = ImpCastExprToType(From, ElType,
4768 isFloatingComplex ? CK_FloatingComplexToReal
4769 : CK_IntegralComplexToReal,
4770 VK_PRValue, /*BasePath=*/nullptr, CCK)
4771 .get();
4772
4773 // x -> y
4774 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4775 // do nothing
4776 } else if (ToType->isRealFloatingType()) {
4777 From = ImpCastExprToType(From, ToType,
4778 isFloatingComplex ? CK_FloatingCast
4779 : CK_IntegralToFloating,
4780 VK_PRValue, /*BasePath=*/nullptr, CCK)
4781 .get();
4782 } else {
4783 assert(ToType->isIntegerType());
4784 From = ImpCastExprToType(From, ToType,
4785 isFloatingComplex ? CK_FloatingToIntegral
4786 : CK_IntegralCast,
4787 VK_PRValue, /*BasePath=*/nullptr, CCK)
4788 .get();
4789 }
4790 }
4791 break;
4792
4794 LangAS AddrSpaceL =
4796 LangAS AddrSpaceR =
4798 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,
4799 getASTContext()) &&
4800 "Invalid cast");
4801 CastKind Kind =
4802 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4803 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4804 VK_PRValue, /*BasePath=*/nullptr, CCK)
4805 .get();
4806 break;
4807 }
4808
4810 ExprResult FromRes = From;
4813 if (FromRes.isInvalid())
4814 return ExprError();
4815 From = FromRes.get();
4816 assert ((ConvTy == Sema::Compatible) &&
4817 "Improper transparent union conversion");
4818 (void)ConvTy;
4819 break;
4820 }
4821
4824 From = ImpCastExprToType(From, ToType,
4825 CK_ZeroToOCLOpaqueType,
4826 From->getValueKind()).get();
4827 break;
4828
4833 case ICK_Qualification:
4840 llvm_unreachable("Improper second standard conversion");
4841 }
4842
4843 if (SCS.Dimension != ICK_Identity) {
4844 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4845 // vectors or matrices.
4846
4847 // TODO: Support HLSL matrices.
4848 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4849 "Dimension conversion for matrix types is not implemented yet.");
4850 assert((ToType->isVectorType() || ToType->isBuiltinType()) &&
4851 "Dimension conversion output must be vector or scalar type.");
4852 switch (SCS.Dimension) {
4853 case ICK_HLSL_Vector_Splat: {
4854 // Vector splat from any arithmetic type to a vector.
4855 Expr *Elem = prepareVectorSplat(ToType, From).get();
4856 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4857 /*BasePath=*/nullptr, CCK)
4858 .get();
4859 break;
4860 }
4862 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
4863 // vector to a smaller vector or to a scalar, this can only operate on
4864 // arguments where the source type is an ExtVector and the destination
4865 // type is destination type is either an ExtVectorType or a builtin scalar
4866 // type.
4867 auto *FromVec = From->getType()->castAs<VectorType>();
4868 QualType TruncTy = FromVec->getElementType();
4869 if (auto *ToVec = ToType->getAs<VectorType>())
4870 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements());
4871 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4872 From->getValueKind())
4873 .get();
4874
4875 break;
4876 }
4877 case ICK_Identity:
4878 default:
4879 llvm_unreachable("Improper element standard conversion");
4880 }
4881 }
4882
4883 switch (SCS.Third) {
4884 case ICK_Identity:
4885 // Nothing to do.
4886 break;
4887
4889 // If both sides are functions (or pointers/references to them), there could
4890 // be incompatible exception declarations.
4891 if (CheckExceptionSpecCompatibility(From, ToType))
4892 return ExprError();
4893
4894 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4895 /*BasePath=*/nullptr, CCK)
4896 .get();
4897 break;
4898
4899 case ICK_Qualification: {
4900 ExprValueKind VK = From->getValueKind();
4901 CastKind CK = CK_NoOp;
4902
4903 if (ToType->isReferenceType() &&
4904 ToType->getPointeeType().getAddressSpace() !=
4905 From->getType().getAddressSpace())
4906 CK = CK_AddressSpaceConversion;
4907
4908 if (ToType->isPointerType() &&
4909 ToType->getPointeeType().getAddressSpace() !=
4911 CK = CK_AddressSpaceConversion;
4912
4913 if (!isCast(CCK) &&
4914 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4916 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4917 << InitialFromType << ToType;
4918 }
4919
4920 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4921 /*BasePath=*/nullptr, CCK)
4922 .get();
4923
4925 !getLangOpts().WritableStrings) {
4926 Diag(From->getBeginLoc(),
4928 ? diag::ext_deprecated_string_literal_conversion
4929 : diag::warn_deprecated_string_literal_conversion)
4930 << ToType.getNonReferenceType();
4931 }
4932
4933 break;
4934 }
4935
4936 default:
4937 llvm_unreachable("Improper third standard conversion");
4938 }
4939
4940 // If this conversion sequence involved a scalar -> atomic conversion, perform
4941 // that conversion now.
4942 if (!ToAtomicType.isNull()) {
4943 assert(Context.hasSameType(
4944 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4945 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4946 VK_PRValue, nullptr, CCK)
4947 .get();
4948 }
4949
4950 // Materialize a temporary if we're implicitly converting to a reference
4951 // type. This is not required by the C++ rules but is necessary to maintain
4952 // AST invariants.
4953 if (ToType->isReferenceType() && From->isPRValue()) {
4955 if (Res.isInvalid())
4956 return ExprError();
4957 From = Res.get();
4958 }
4959
4960 // If this conversion sequence succeeded and involved implicitly converting a
4961 // _Nullable type to a _Nonnull one, complain.
4962 if (!isCast(CCK))
4963 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4964 From->getBeginLoc());
4965
4966 return From;
4967}
4968
4969/// Checks that type T is not a VLA.
4970///
4971/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4972/// @c false otherwise.
4974 clang::tok::TokenKind TypeTraitID) {
4975 if (!T->getType()->isVariableArrayType())
4976 return false;
4977
4978 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
4979 << 1 << TypeTraitID;
4980 return true;
4981}
4982
4983/// Checks that type T is not an atomic type (_Atomic).
4984///
4985/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4986/// @c false otherwise.
4988 clang::tok::TokenKind TypeTraitID) {
4989 if (!T->getType()->isAtomicType())
4990 return false;
4991
4992 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_atomic_unsupported)
4993 << TypeTraitID;
4994 return true;
4995}
4996
4997/// Check the completeness of a type in a unary type trait.
4998///
4999/// If the particular type trait requires a complete type, tries to complete
5000/// it. If completing the type fails, a diagnostic is emitted and false
5001/// returned. If completing the type succeeds or no completion was required,
5002/// returns true.
5005 QualType ArgTy) {
5006 // C++0x [meta.unary.prop]p3:
5007 // For all of the class templates X declared in this Clause, instantiating
5008 // that template with a template argument that is a class template
5009 // specialization may result in the implicit instantiation of the template
5010 // argument if and only if the semantics of X require that the argument
5011 // must be a complete type.
5012 // We apply this rule to all the type trait expressions used to implement
5013 // these class templates. We also try to follow any GCC documented behavior
5014 // in these expressions to ensure portability of standard libraries.
5015 switch (UTT) {
5016 default: llvm_unreachable("not a UTT");
5017 // is_complete_type somewhat obviously cannot require a complete type.
5018 case UTT_IsCompleteType:
5019 // Fall-through
5020
5021 // These traits are modeled on the type predicates in C++0x
5022 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
5023 // requiring a complete type, as whether or not they return true cannot be
5024 // impacted by the completeness of the type.
5025 case UTT_IsVoid:
5026 case UTT_IsIntegral:
5027 case UTT_IsFloatingPoint:
5028 case UTT_IsArray:
5029 case UTT_IsBoundedArray:
5030 case UTT_IsPointer:
5031 case UTT_IsReferenceable:
5032 case UTT_IsLvalueReference:
5033 case UTT_IsRvalueReference:
5034 case UTT_IsMemberFunctionPointer:
5035 case UTT_IsMemberObjectPointer:
5036 case UTT_IsEnum:
5037 case UTT_IsScopedEnum:
5038 case UTT_IsUnion:
5039 case UTT_IsClass:
5040 case UTT_IsFunction:
5041 case UTT_IsReference:
5042 case UTT_IsArithmetic:
5043 case UTT_IsFundamental:
5044 case UTT_IsObject:
5045 case UTT_IsScalar:
5046 case UTT_IsCompound:
5047 case UTT_IsMemberPointer:
5048 case UTT_IsTypedResourceElementCompatible:
5049 // Fall-through
5050
5051 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5052 // which requires some of its traits to have the complete type. However,
5053 // the completeness of the type cannot impact these traits' semantics, and
5054 // so they don't require it. This matches the comments on these traits in
5055 // Table 49.
5056 case UTT_IsConst:
5057 case UTT_IsVolatile:
5058 case UTT_IsSigned:
5059 case UTT_IsUnboundedArray:
5060 case UTT_IsUnsigned:
5061
5062 // This type trait always returns false, checking the type is moot.
5063 case UTT_IsInterfaceClass:
5064 return true;
5065
5066 // C++14 [meta.unary.prop]:
5067 // If T is a non-union class type, T shall be a complete type.
5068 case UTT_IsEmpty:
5069 case UTT_IsPolymorphic:
5070 case UTT_IsAbstract:
5071 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5072 if (!RD->isUnion())
5073 return !S.RequireCompleteType(
5074 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5075 return true;
5076
5077 // C++14 [meta.unary.prop]:
5078 // If T is a class type, T shall be a complete type.
5079 case UTT_IsFinal:
5080 case UTT_IsSealed:
5081 if (ArgTy->getAsCXXRecordDecl())
5082 return !S.RequireCompleteType(
5083 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5084 return true;
5085
5086 // LWG3823: T shall be an array type, a complete type, or cv void.
5087 case UTT_IsAggregate:
5088 case UTT_IsImplicitLifetime:
5089 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5090 return true;
5091
5092 return !S.RequireCompleteType(
5093 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5094
5095 // C++1z [meta.unary.prop]:
5096 // remove_all_extents_t<T> shall be a complete type or cv void.
5097 case UTT_IsTrivial:
5098 case UTT_IsTriviallyCopyable:
5099 case UTT_IsStandardLayout:
5100 case UTT_IsPOD:
5101 case UTT_IsLiteral:
5102 case UTT_IsBitwiseCloneable:
5103 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5104 // impose the same constraints.
5105 case UTT_IsTriviallyRelocatable:
5106 case UTT_IsTriviallyEqualityComparable:
5107 case UTT_CanPassInRegs:
5108 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5109 // or an array of unknown bound. But GCC actually imposes the same constraints
5110 // as above.
5111 case UTT_HasNothrowAssign:
5112 case UTT_HasNothrowMoveAssign:
5113 case UTT_HasNothrowConstructor:
5114 case UTT_HasNothrowCopy:
5115 case UTT_HasTrivialAssign:
5116 case UTT_HasTrivialMoveAssign:
5117 case UTT_HasTrivialDefaultConstructor:
5118 case UTT_HasTrivialMoveConstructor:
5119 case UTT_HasTrivialCopy:
5120 case UTT_HasTrivialDestructor:
5121 case UTT_HasVirtualDestructor:
5122 // has_unique_object_representations<T> when T is an array is defined in terms
5123 // of has_unique_object_representations<remove_all_extents_t<T>>, so the base
5124 // type needs to be complete even if the type is an incomplete array type.
5125 case UTT_HasUniqueObjectRepresentations:
5126 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5127 [[fallthrough]];
5128
5129 // C++1z [meta.unary.prop]:
5130 // T shall be a complete type, cv void, or an array of unknown bound.
5131 case UTT_IsDestructible:
5132 case UTT_IsNothrowDestructible:
5133 case UTT_IsTriviallyDestructible:
5134 case UTT_IsIntangibleType:
5135 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5136 return true;
5137
5138 return !S.RequireCompleteType(
5139 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5140 }
5141}
5142
5144 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5145 bool (CXXRecordDecl::*HasTrivial)() const,
5146 bool (CXXRecordDecl::*HasNonTrivial)() const,
5147 bool (CXXMethodDecl::*IsDesiredOp)() const)
5148{
5149 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5150 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5151 return true;
5152
5153 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5154 DeclarationNameInfo NameInfo(Name, KeyLoc);
5156 if (Self.LookupQualifiedName(Res, RD)) {
5157 bool FoundOperator = false;
5158 Res.suppressDiagnostics();
5159 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5160 Op != OpEnd; ++Op) {
5161 if (isa<FunctionTemplateDecl>(*Op))
5162 continue;
5163
5164 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5165 if((Operator->*IsDesiredOp)()) {
5166 FoundOperator = true;
5167 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5168 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5169 if (!CPT || !CPT->isNothrow())
5170 return false;
5171 }
5172 }
5173 return FoundOperator;
5174 }
5175 return false;
5176}
5177
5179 const CXXRecordDecl *Decl,
5180 SourceLocation KeyLoc) {
5181 if (Decl->isUnion())
5182 return false;
5183 if (Decl->isLambda())
5184 return Decl->isCapturelessLambda();
5185
5186 {
5187 EnterExpressionEvaluationContext UnevaluatedContext(
5189 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5191
5192 // const ClassT& obj;
5193 OpaqueValueExpr Operand(
5194 KeyLoc,
5195 Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
5197 UnresolvedSet<16> Functions;
5198 // obj == obj;
5199 S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
5200
5201 auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
5202 Functions, &Operand, &Operand);
5203 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5204 return false;
5205
5206 const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());
5207 if (!CallExpr)
5208 return false;
5209 const auto *Callee = CallExpr->getDirectCallee();
5210 auto ParamT = Callee->getParamDecl(0)->getType();
5211 if (!Callee->isDefaulted())
5212 return false;
5213 if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
5214 return false;
5215 if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
5216 Decl->getTypeForDecl())
5217 return false;
5218 }
5219
5220 return llvm::all_of(Decl->bases(),
5221 [&](const CXXBaseSpecifier &BS) {
5222 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
5223 return HasNonDeletedDefaultedEqualityComparison(
5224 S, RD, KeyLoc);
5225 return true;
5226 }) &&
5227 llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {
5228 auto Type = FD->getType();
5229 if (Type->isArrayType())
5230 Type = Type->getBaseElementTypeUnsafe()
5231 ->getCanonicalTypeUnqualified();
5232
5233 if (Type->isReferenceType() || Type->isEnumeralType())
5234 return false;
5235 if (const auto *RD = Type->getAsCXXRecordDecl())
5236 return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
5237 return true;
5238 });
5239}
5240
5242 QualType CanonicalType = Type.getCanonicalType();
5243 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
5244 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
5245 return false;
5246
5247 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
5248 if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))
5249 return false;
5250 }
5251
5253 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
5254}
5255
5257 SourceLocation KeyLoc,
5258 TypeSourceInfo *TInfo) {
5259 QualType T = TInfo->getType();
5260 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5261
5262 ASTContext &C = Self.Context;
5263 switch(UTT) {
5264 default: llvm_unreachable("not a UTT");
5265 // Type trait expressions corresponding to the primary type category
5266 // predicates in C++0x [meta.unary.cat].
5267 case UTT_IsVoid:
5268 return T->isVoidType();
5269 case UTT_IsIntegral:
5270 return T->isIntegralType(C);
5271 case UTT_IsFloatingPoint:
5272 return T->isFloatingType();
5273 case UTT_IsArray:
5274 // Zero-sized arrays aren't considered arrays in partial specializations,
5275 // so __is_array shouldn't consider them arrays either.
5276 if (const auto *CAT = C.getAsConstantArrayType(T))
5277 return CAT->getSize() != 0;
5278 return T->isArrayType();
5279 case UTT_IsBoundedArray:
5280 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5281 return false;
5282 // Zero-sized arrays aren't considered arrays in partial specializations,
5283 // so __is_bounded_array shouldn't consider them arrays either.
5284 if (const auto *CAT = C.getAsConstantArrayType(T))
5285 return CAT->getSize() != 0;
5286 return T->isArrayType() && !T->isIncompleteArrayType();
5287 case UTT_IsUnboundedArray:
5288 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5289 return false;
5290 return T->isIncompleteArrayType();
5291 case UTT_IsPointer:
5292 return T->isAnyPointerType();
5293 case UTT_IsLvalueReference:
5294 return T->isLValueReferenceType();
5295 case UTT_IsRvalueReference:
5296 return T->isRValueReferenceType();
5297 case UTT_IsMemberFunctionPointer:
5299 case UTT_IsMemberObjectPointer:
5300 return T->isMemberDataPointerType();
5301 case UTT_IsEnum:
5302 return T->isEnumeralType();
5303 case UTT_IsScopedEnum:
5304 return T->isScopedEnumeralType();
5305 case UTT_IsUnion:
5306 return T->isUnionType();
5307 case UTT_IsClass:
5308 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5309 case UTT_IsFunction:
5310 return T->isFunctionType();
5311
5312 // Type trait expressions which correspond to the convenient composition
5313 // predicates in C++0x [meta.unary.comp].
5314 case UTT_IsReference:
5315 return T->isReferenceType();
5316 case UTT_IsArithmetic:
5317 return T->isArithmeticType() && !T->isEnumeralType();
5318 case UTT_IsFundamental:
5319 return T->isFundamentalType();
5320 case UTT_IsObject:
5321 return T->isObjectType();
5322 case UTT_IsScalar:
5323 // Note: semantic analysis depends on Objective-C lifetime types to be
5324 // considered scalar types. However, such types do not actually behave
5325 // like scalar types at run time (since they may require retain/release
5326 // operations), so we report them as non-scalar.
5327 if (T->isObjCLifetimeType()) {
5328 switch (T.getObjCLifetime()) {
5331 return true;
5332
5336 return false;
5337 }
5338 }
5339
5340 return T->isScalarType();
5341 case UTT_IsCompound:
5342 return T->isCompoundType();
5343 case UTT_IsMemberPointer:
5344 return T->isMemberPointerType();
5345
5346 // Type trait expressions which correspond to the type property predicates
5347 // in C++0x [meta.unary.prop].
5348 case UTT_IsConst:
5349 return T.isConstQualified();
5350 case UTT_IsVolatile:
5351 return T.isVolatileQualified();
5352 case UTT_IsTrivial:
5353 return T.isTrivialType(C);
5354 case UTT_IsTriviallyCopyable:
5355 return T.isTriviallyCopyableType(C);
5356 case UTT_IsStandardLayout:
5357 return T->isStandardLayoutType();
5358 case UTT_IsPOD:
5359 return T.isPODType(C);
5360 case UTT_IsLiteral:
5361 return T->isLiteralType(C);
5362 case UTT_IsEmpty:
5363 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5364 return !RD->isUnion() && RD->isEmpty();
5365 return false;
5366 case UTT_IsPolymorphic:
5367 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5368 return !RD->isUnion() && RD->isPolymorphic();
5369 return false;
5370 case UTT_IsAbstract:
5371 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5372 return !RD->isUnion() && RD->isAbstract();
5373 return false;
5374 case UTT_IsAggregate:
5375 // Report vector extensions and complex types as aggregates because they
5376 // support aggregate initialization. GCC mirrors this behavior for vectors
5377 // but not _Complex.
5378 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5380 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5381 // even then only when it is used with the 'interface struct ...' syntax
5382 // Clang doesn't support /CLR which makes this type trait moot.
5383 case UTT_IsInterfaceClass:
5384 return false;
5385 case UTT_IsFinal:
5386 case UTT_IsSealed:
5387 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5388 return RD->hasAttr<FinalAttr>();
5389 return false;
5390 case UTT_IsSigned:
5391 // Enum types should always return false.
5392 // Floating points should always return true.
5393 return T->isFloatingType() ||
5395 case UTT_IsUnsigned:
5396 // Enum types should always return false.
5397 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5398
5399 // Type trait expressions which query classes regarding their construction,
5400 // destruction, and copying. Rather than being based directly on the
5401 // related type predicates in the standard, they are specified by both
5402 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5403 // specifications.
5404 //
5405 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5406 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5407 //
5408 // Note that these builtins do not behave as documented in g++: if a class
5409 // has both a trivial and a non-trivial special member of a particular kind,
5410 // they return false! For now, we emulate this behavior.
5411 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5412 // does not correctly compute triviality in the presence of multiple special
5413 // members of the same kind. Revisit this once the g++ bug is fixed.
5414 case UTT_HasTrivialDefaultConstructor:
5415 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5416 // If __is_pod (type) is true then the trait is true, else if type is
5417 // a cv class or union type (or array thereof) with a trivial default
5418 // constructor ([class.ctor]) then the trait is true, else it is false.
5419 if (T.isPODType(C))
5420 return true;
5421 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5422 return RD->hasTrivialDefaultConstructor() &&
5424 return false;
5425 case UTT_HasTrivialMoveConstructor:
5426 // This trait is implemented by MSVC 2012 and needed to parse the
5427 // standard library headers. Specifically this is used as the logic
5428 // behind std::is_trivially_move_constructible (20.9.4.3).
5429 if (T.isPODType(C))
5430 return true;
5431 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5433 return false;
5434 case UTT_HasTrivialCopy:
5435 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5436 // If __is_pod (type) is true or type is a reference type then
5437 // the trait is true, else if type is a cv class or union type
5438 // with a trivial copy constructor ([class.copy]) then the trait
5439 // is true, else it is false.
5440 if (T.isPODType(C) || T->isReferenceType())
5441 return true;
5442 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5443 return RD->hasTrivialCopyConstructor() &&
5445 return false;
5446 case UTT_HasTrivialMoveAssign:
5447 // This trait is implemented by MSVC 2012 and needed to parse the
5448 // standard library headers. Specifically it is used as the logic
5449 // behind std::is_trivially_move_assignable (20.9.4.3)
5450 if (T.isPODType(C))
5451 return true;
5452 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5454 return false;
5455 case UTT_HasTrivialAssign:
5456 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5457 // If type is const qualified or is a reference type then the
5458 // trait is false. Otherwise if __is_pod (type) is true then the
5459 // trait is true, else if type is a cv class or union type with
5460 // a trivial copy assignment ([class.copy]) then the trait is
5461 // true, else it is false.
5462 // Note: the const and reference restrictions are interesting,
5463 // given that const and reference members don't prevent a class
5464 // from having a trivial copy assignment operator (but do cause
5465 // errors if the copy assignment operator is actually used, q.v.
5466 // [class.copy]p12).
5467
5468 if (T.isConstQualified())
5469 return false;
5470 if (T.isPODType(C))
5471 return true;
5472 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5473 return RD->hasTrivialCopyAssignment() &&
5475 return false;
5476 case UTT_IsDestructible:
5477 case UTT_IsTriviallyDestructible:
5478 case UTT_IsNothrowDestructible:
5479 // C++14 [meta.unary.prop]:
5480 // For reference types, is_destructible<T>::value is true.
5481 if (T->isReferenceType())
5482 return true;
5483
5484 // Objective-C++ ARC: autorelease types don't require destruction.
5485 if (T->isObjCLifetimeType() &&
5486 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5487 return true;
5488
5489 // C++14 [meta.unary.prop]:
5490 // For incomplete types and function types, is_destructible<T>::value is
5491 // false.
5492 if (T->isIncompleteType() || T->isFunctionType())
5493 return false;
5494
5495 // A type that requires destruction (via a non-trivial destructor or ARC
5496 // lifetime semantics) is not trivially-destructible.
5497 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5498 return false;
5499
5500 // C++14 [meta.unary.prop]:
5501 // For object types and given U equal to remove_all_extents_t<T>, if the
5502 // expression std::declval<U&>().~U() is well-formed when treated as an
5503 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5504 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5505 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5506 if (!Destructor)
5507 return false;
5508 // C++14 [dcl.fct.def.delete]p2:
5509 // A program that refers to a deleted function implicitly or
5510 // explicitly, other than to declare it, is ill-formed.
5511 if (Destructor->isDeleted())
5512 return false;
5513 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5514 return false;
5515 if (UTT == UTT_IsNothrowDestructible) {
5516 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5517 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5518 if (!CPT || !CPT->isNothrow())
5519 return false;
5520 }
5521 }
5522 return true;
5523
5524 case UTT_HasTrivialDestructor:
5525 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5526 // If __is_pod (type) is true or type is a reference type
5527 // then the trait is true, else if type is a cv class or union
5528 // type (or array thereof) with a trivial destructor
5529 // ([class.dtor]) then the trait is true, else it is
5530 // false.
5531 if (T.isPODType(C) || T->isReferenceType())
5532 return true;
5533
5534 // Objective-C++ ARC: autorelease types don't require destruction.
5535 if (T->isObjCLifetimeType() &&
5536 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5537 return true;
5538
5539 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5540 return RD->hasTrivialDestructor();
5541 return false;
5542 // TODO: Propagate nothrowness for implicitly declared special members.
5543 case UTT_HasNothrowAssign:
5544 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5545 // If type is const qualified or is a reference type then the
5546 // trait is false. Otherwise if __has_trivial_assign (type)
5547 // is true then the trait is true, else if type is a cv class
5548 // or union type with copy assignment operators that are known
5549 // not to throw an exception then the trait is true, else it is
5550 // false.
5551 if (C.getBaseElementType(T).isConstQualified())
5552 return false;
5553 if (T->isReferenceType())
5554 return false;
5555 if (T.isPODType(C) || T->isObjCLifetimeType())
5556 return true;
5557
5558 if (const RecordType *RT = T->getAs<RecordType>())
5559 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5563 return false;
5564 case UTT_HasNothrowMoveAssign:
5565 // This trait is implemented by MSVC 2012 and needed to parse the
5566 // standard library headers. Specifically this is used as the logic
5567 // behind std::is_nothrow_move_assignable (20.9.4.3).
5568 if (T.isPODType(C))
5569 return true;
5570
5571 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5572 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5576 return false;
5577 case UTT_HasNothrowCopy:
5578 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5579 // If __has_trivial_copy (type) is true then the trait is true, else
5580 // if type is a cv class or union type with copy constructors that are
5581 // known not to throw an exception then the trait is true, else it is
5582 // false.
5583 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5584 return true;
5585 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5586 if (RD->hasTrivialCopyConstructor() &&
5588 return true;
5589
5590 bool FoundConstructor = false;
5591 unsigned FoundTQs;
5592 for (const auto *ND : Self.LookupConstructors(RD)) {
5593 // A template constructor is never a copy constructor.
5594 // FIXME: However, it may actually be selected at the actual overload
5595 // resolution point.
5596 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5597 continue;
5598 // UsingDecl itself is not a constructor
5599 if (isa<UsingDecl>(ND))
5600 continue;
5601 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5602 if (Constructor->isCopyConstructor(FoundTQs)) {
5603 FoundConstructor = true;
5604 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5605 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5606 if (!CPT)
5607 return false;
5608 // TODO: check whether evaluating default arguments can throw.
5609 // For now, we'll be conservative and assume that they can throw.
5610 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5611 return false;
5612 }
5613 }
5614
5615 return FoundConstructor;
5616 }
5617 return false;
5618 case UTT_HasNothrowConstructor:
5619 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5620 // If __has_trivial_constructor (type) is true then the trait is
5621 // true, else if type is a cv class or union type (or array
5622 // thereof) with a default constructor that is known not to
5623 // throw an exception then the trait is true, else it is false.
5624 if (T.isPODType(C) || T->isObjCLifetimeType())
5625 return true;
5626 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5627 if (RD->hasTrivialDefaultConstructor() &&
5629 return true;
5630
5631 bool FoundConstructor = false;
5632 for (const auto *ND : Self.LookupConstructors(RD)) {
5633 // FIXME: In C++0x, a constructor template can be a default constructor.
5634 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5635 continue;
5636 // UsingDecl itself is not a constructor
5637 if (isa<UsingDecl>(ND))
5638 continue;
5639 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5640 if (Constructor->isDefaultConstructor()) {
5641 FoundConstructor = true;
5642 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5643 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5644 if (!CPT)
5645 return false;
5646 // FIXME: check whether evaluating default arguments can throw.
5647 // For now, we'll be conservative and assume that they can throw.
5648 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5649 return false;
5650 }
5651 }
5652 return FoundConstructor;
5653 }
5654 return false;
5655 case UTT_HasVirtualDestructor:
5656 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5657 // If type is a class type with a virtual destructor ([class.dtor])
5658 // then the trait is true, else it is false.
5659 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5660 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5661 return Destructor->isVirtual();
5662 return false;
5663
5664 // These type trait expressions are modeled on the specifications for the
5665 // Embarcadero C++0x type trait functions:
5666 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5667 case UTT_IsCompleteType:
5668 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5669 // Returns True if and only if T is a complete type at the point of the
5670 // function call.
5671 return !T->isIncompleteType();
5672 case UTT_HasUniqueObjectRepresentations:
5673 return C.hasUniqueObjectRepresentations(T);
5674 case UTT_IsTriviallyRelocatable:
5675 return T.isTriviallyRelocatableType(C);
5676 case UTT_IsBitwiseCloneable:
5677 return T.isBitwiseCloneableType(C);
5678 case UTT_IsReferenceable:
5679 return T.isReferenceable();
5680 case UTT_CanPassInRegs:
5681 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5682 return RD->canPassInRegisters();
5683 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5684 return false;
5685 case UTT_IsTriviallyEqualityComparable:
5686 return isTriviallyEqualityComparableType(Self, T, KeyLoc);
5687 case UTT_IsImplicitLifetime: {
5689 tok::kw___builtin_is_implicit_lifetime);
5691 tok::kw___builtin_is_implicit_lifetime);
5692
5693 // [basic.types.general] p9
5694 // Scalar types, implicit-lifetime class types ([class.prop]),
5695 // array types, and cv-qualified versions of these types
5696 // are collectively called implicit-lifetime types.
5698 if (UnqualT->isScalarType())
5699 return true;
5700 if (UnqualT->isArrayType() || UnqualT->isVectorType())
5701 return true;
5702 const CXXRecordDecl *RD = UnqualT->getAsCXXRecordDecl();
5703 if (!RD)
5704 return false;
5705
5706 // [class.prop] p9
5707 // A class S is an implicit-lifetime class if
5708 // - it is an aggregate whose destructor is not user-provided or
5709 // - it has at least one trivial eligible constructor and a trivial,
5710 // non-deleted destructor.
5711 const CXXDestructorDecl *Dtor = RD->getDestructor();
5712 if (UnqualT->isAggregateType())
5713 if (Dtor && !Dtor->isUserProvided())
5714 return true;
5715 if (RD->hasTrivialDestructor() && (!Dtor || !Dtor->isDeleted()))
5716 if (RD->hasTrivialDefaultConstructor() ||
5718 return true;
5719 return false;
5720 }
5721 case UTT_IsIntangibleType:
5722 assert(Self.getLangOpts().HLSL && "intangible types are HLSL-only feature");
5723 if (!T->isVoidType() && !T->isIncompleteArrayType())
5724 if (Self.RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), T,
5725 diag::err_incomplete_type))
5726 return false;
5728 tok::kw___builtin_hlsl_is_intangible))
5729 return false;
5730 return T->isHLSLIntangibleType();
5731
5732 case UTT_IsTypedResourceElementCompatible:
5733 assert(Self.getLangOpts().HLSL &&
5734 "typed resource element compatible types are an HLSL-only feature");
5735 if (T->isIncompleteType())
5736 return false;
5737
5738 return Self.HLSL().IsTypedResourceElementCompatible(T);
5739 }
5740}
5741
5742static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5743 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5744
5746 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5747 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5748
5749 QualType LhsT = Lhs->getType();
5750 QualType RhsT = Rhs->getType();
5751
5752 // C++0x [meta.rel]p4:
5753 // Given the following function prototype:
5754 //
5755 // template <class T>
5756 // typename add_rvalue_reference<T>::type create();
5757 //
5758 // the predicate condition for a template specialization
5759 // is_convertible<From, To> shall be satisfied if and only if
5760 // the return expression in the following code would be
5761 // well-formed, including any implicit conversions to the return
5762 // type of the function:
5763 //
5764 // To test() {
5765 // return create<From>();
5766 // }
5767 //
5768 // Access checking is performed as if in a context unrelated to To and
5769 // From. Only the validity of the immediate context of the expression
5770 // of the return-statement (including conversions to the return type)
5771 // is considered.
5772 //
5773 // We model the initialization as a copy-initialization of a temporary
5774 // of the appropriate type, which for this expression is identical to the
5775 // return statement (since NRVO doesn't apply).
5776
5777 // Functions aren't allowed to return function or array types.
5778 if (RhsT->isFunctionType() || RhsT->isArrayType())
5779 return ExprError();
5780
5781 // A function definition requires a complete, non-abstract return type.
5782 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5783 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5784 return ExprError();
5785
5786 // Compute the result of add_rvalue_reference.
5787 if (LhsT->isObjectType() || LhsT->isFunctionType())
5788 LhsT = Self.Context.getRValueReferenceType(LhsT);
5789
5790 // Build a fake source and destination for initialization.
5792 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5793 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5795 InitializationKind Kind =
5797
5798 // Perform the initialization in an unevaluated context within a SFINAE
5799 // trap at translation unit scope.
5802 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5803 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5804 InitializationSequence Init(Self, To, Kind, From);
5805 if (Init.Failed())
5806 return ExprError();
5807
5808 ExprResult Result = Init.Perform(Self, To, Kind, From);
5809 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5810 return ExprError();
5811
5812 return Result;
5813}
5814
5816 SourceLocation KWLoc,
5818 SourceLocation RParenLoc,
5819 bool IsDependent) {
5820 if (IsDependent)
5821 return false;
5822
5823 if (Kind <= UTT_Last)
5824 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5825
5826 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5827 // alongside the IsConstructible traits to avoid duplication.
5828 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5829 Kind != BTT_ReferenceConstructsFromTemporary &&
5830 Kind != BTT_ReferenceConvertsFromTemporary)
5831 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5832 Args[1], RParenLoc);
5833
5834 switch (Kind) {
5835 case clang::BTT_ReferenceBindsToTemporary:
5836 case clang::BTT_ReferenceConstructsFromTemporary:
5837 case clang::BTT_ReferenceConvertsFromTemporary:
5838 case clang::TT_IsConstructible:
5839 case clang::TT_IsNothrowConstructible:
5840 case clang::TT_IsTriviallyConstructible: {
5841 // C++11 [meta.unary.prop]:
5842 // is_trivially_constructible is defined as:
5843 //
5844 // is_constructible<T, Args...>::value is true and the variable
5845 // definition for is_constructible, as defined below, is known to call
5846 // no operation that is not trivial.
5847 //
5848 // The predicate condition for a template specialization
5849 // is_constructible<T, Args...> shall be satisfied if and only if the
5850 // following variable definition would be well-formed for some invented
5851 // variable t:
5852 //
5853 // T t(create<Args>()...);
5854 assert(!Args.empty());
5855
5856 // Precondition: T and all types in the parameter pack Args shall be
5857 // complete types, (possibly cv-qualified) void, or arrays of
5858 // unknown bound.
5859 for (const auto *TSI : Args) {
5860 QualType ArgTy = TSI->getType();
5861 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5862 continue;
5863
5864 if (S.RequireCompleteType(KWLoc, ArgTy,
5865 diag::err_incomplete_type_used_in_type_trait_expr))
5866 return false;
5867 }
5868
5869 // Make sure the first argument is not incomplete nor a function type.
5870 QualType T = Args[0]->getType();
5871 if (T->isIncompleteType() || T->isFunctionType())
5872 return false;
5873
5874 // Make sure the first argument is not an abstract type.
5876 if (RD && RD->isAbstract())
5877 return false;
5878
5879 llvm::BumpPtrAllocator OpaqueExprAllocator;
5880 SmallVector<Expr *, 2> ArgExprs;
5881 ArgExprs.reserve(Args.size() - 1);
5882 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5883 QualType ArgTy = Args[I]->getType();
5884 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5885 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5886 ArgExprs.push_back(
5887 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5888 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5891 }
5892
5893 // Perform the initialization in an unevaluated context within a SFINAE
5894 // trap at translation unit scope.
5897 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5901 InitializationKind InitKind(
5902 Kind == clang::BTT_ReferenceConvertsFromTemporary
5903 ? InitializationKind::CreateCopy(KWLoc, KWLoc)
5904 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5905 InitializationSequence Init(S, To, InitKind, ArgExprs);
5906 if (Init.Failed())
5907 return false;
5908
5909 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5910 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5911 return false;
5912
5913 if (Kind == clang::TT_IsConstructible)
5914 return true;
5915
5916 if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5917 Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5918 Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5919 if (!T->isReferenceType())
5920 return false;
5921
5922 if (!Init.isDirectReferenceBinding())
5923 return true;
5924
5925 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5926 return false;
5927
5928 QualType U = Args[1]->getType();
5929 if (U->isReferenceType())
5930 return false;
5931
5933 S.Context.getPointerType(T.getNonReferenceType()));
5935 S.Context.getPointerType(U.getNonReferenceType()));
5936 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5937 OpaqueExprAllocator)
5938 .isInvalid();
5939 }
5940
5941 if (Kind == clang::TT_IsNothrowConstructible)
5942 return S.canThrow(Result.get()) == CT_Cannot;
5943
5944 if (Kind == clang::TT_IsTriviallyConstructible) {
5945 // Under Objective-C ARC and Weak, if the destination has non-trivial
5946 // Objective-C lifetime, this is a non-trivial construction.
5947 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5948 return false;
5949
5950 // The initialization succeeded; now make sure there are no non-trivial
5951 // calls.
5952 return !Result.get()->hasNonTrivialCall(S.Context);
5953 }
5954
5955 llvm_unreachable("unhandled type trait");
5956 return false;
5957 }
5958 default: llvm_unreachable("not a TT");
5959 }
5960
5961 return false;
5962}
5963
5964namespace {
5965void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5966 SourceLocation KWLoc) {
5967 TypeTrait Replacement;
5968 switch (Kind) {
5969 case UTT_HasNothrowAssign:
5970 case UTT_HasNothrowMoveAssign:
5971 Replacement = BTT_IsNothrowAssignable;
5972 break;
5973 case UTT_HasNothrowCopy:
5974 case UTT_HasNothrowConstructor:
5975 Replacement = TT_IsNothrowConstructible;
5976 break;
5977 case UTT_HasTrivialAssign:
5978 case UTT_HasTrivialMoveAssign:
5979 Replacement = BTT_IsTriviallyAssignable;
5980 break;
5981 case UTT_HasTrivialCopy:
5982 Replacement = UTT_IsTriviallyCopyable;
5983 break;
5984 case UTT_HasTrivialDefaultConstructor:
5985 case UTT_HasTrivialMoveConstructor:
5986 Replacement = TT_IsTriviallyConstructible;
5987 break;
5988 case UTT_HasTrivialDestructor:
5989 Replacement = UTT_IsTriviallyDestructible;
5990 break;
5991 default:
5992 return;
5993 }
5994 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5995 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5996}
5997}
5998
5999bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
6000 if (Arity && N != Arity) {
6001 Diag(Loc, diag::err_type_trait_arity)
6002 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
6003 return false;
6004 }
6005
6006 if (!Arity && N == 0) {
6007 Diag(Loc, diag::err_type_trait_arity)
6008 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
6009 return false;
6010 }
6011 return true;
6012}
6013
6015 Bool,
6016};
6017
6019 return TypeTraitReturnType::Bool;
6020}
6021
6024 SourceLocation RParenLoc) {
6025 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
6026 return ExprError();
6027
6029 *this, Kind, KWLoc, Args[0]->getType()))
6030 return ExprError();
6031
6032 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
6033
6034 bool Dependent = false;
6035 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
6036 if (Args[I]->getType()->isDependentType()) {
6037 Dependent = true;
6038 break;
6039 }
6040 }
6041
6042 switch (GetReturnType(Kind)) {
6043 case TypeTraitReturnType::Bool: {
6044 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
6045 Dependent);
6047 KWLoc, Kind, Args, RParenLoc, Result);
6048 }
6049 }
6050 llvm_unreachable("unhandled type trait return type");
6051}
6052
6055 SourceLocation RParenLoc) {
6057 ConvertedArgs.reserve(Args.size());
6058
6059 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
6060 TypeSourceInfo *TInfo;
6061 QualType T = GetTypeFromParser(Args[I], &TInfo);
6062 if (!TInfo)
6063 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
6064
6065 ConvertedArgs.push_back(TInfo);
6066 }
6067
6068 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
6069}
6070
6072 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
6073 QualType LhsT = Lhs->getType();
6074 QualType RhsT = Rhs->getType();
6075
6076 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
6077 "Cannot evaluate traits of dependent types");
6078
6079 switch(BTT) {
6080 case BTT_IsBaseOf: {
6081 // C++0x [meta.rel]p2
6082 // Base is a base class of Derived without regard to cv-qualifiers or
6083 // Base and Derived are not unions and name the same class type without
6084 // regard to cv-qualifiers.
6085
6086 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
6087 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
6088 if (!rhsRecord || !lhsRecord) {
6089 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
6090 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
6091 if (!LHSObjTy || !RHSObjTy)
6092 return false;
6093
6094 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
6095 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
6096 if (!BaseInterface || !DerivedInterface)
6097 return false;
6098
6099 if (Self.RequireCompleteType(
6100 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6101 diag::err_incomplete_type_used_in_type_trait_expr))
6102 return false;
6103
6104 return BaseInterface->isSuperClassOf(DerivedInterface);
6105 }
6106
6107 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6108 == (lhsRecord == rhsRecord));
6109
6110 // Unions are never base classes, and never have base classes.
6111 // It doesn't matter if they are complete or not. See PR#41843
6112 if (lhsRecord && lhsRecord->getDecl()->isUnion())
6113 return false;
6114 if (rhsRecord && rhsRecord->getDecl()->isUnion())
6115 return false;
6116
6117 if (lhsRecord == rhsRecord)
6118 return true;
6119
6120 // C++0x [meta.rel]p2:
6121 // If Base and Derived are class types and are different types
6122 // (ignoring possible cv-qualifiers) then Derived shall be a
6123 // complete type.
6124 if (Self.RequireCompleteType(
6125 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6126 diag::err_incomplete_type_used_in_type_trait_expr))
6127 return false;
6128
6129 return cast<CXXRecordDecl>(rhsRecord->getDecl())
6130 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6131 }
6132 case BTT_IsVirtualBaseOf: {
6133 const RecordType *BaseRecord = LhsT->getAs<RecordType>();
6134 const RecordType *DerivedRecord = RhsT->getAs<RecordType>();
6135
6136 if (!BaseRecord || !DerivedRecord) {
6138 tok::kw___builtin_is_virtual_base_of);
6140 tok::kw___builtin_is_virtual_base_of);
6141 return false;
6142 }
6143
6144 if (BaseRecord->isUnionType() || DerivedRecord->isUnionType())
6145 return false;
6146
6147 if (!BaseRecord->isStructureOrClassType() ||
6148 !DerivedRecord->isStructureOrClassType())
6149 return false;
6150
6151 if (Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6152 diag::err_incomplete_type))
6153 return false;
6154
6155 return cast<CXXRecordDecl>(DerivedRecord->getDecl())
6156 ->isVirtuallyDerivedFrom(cast<CXXRecordDecl>(BaseRecord->getDecl()));
6157 }
6158 case BTT_IsSame:
6159 return Self.Context.hasSameType(LhsT, RhsT);
6160 case BTT_TypeCompatible: {
6161 // GCC ignores cv-qualifiers on arrays for this builtin.
6162 Qualifiers LhsQuals, RhsQuals;
6163 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6164 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6165 return Self.Context.typesAreCompatible(Lhs, Rhs);
6166 }
6167 case BTT_IsConvertible:
6168 case BTT_IsConvertibleTo:
6169 case BTT_IsNothrowConvertible: {
6170 if (RhsT->isVoidType())
6171 return LhsT->isVoidType();
6172 llvm::BumpPtrAllocator OpaqueExprAllocator;
6174 OpaqueExprAllocator);
6175 if (Result.isInvalid())
6176 return false;
6177
6178 if (BTT != BTT_IsNothrowConvertible)
6179 return true;
6180
6181 return Self.canThrow(Result.get()) == CT_Cannot;
6182 }
6183
6184 case BTT_IsAssignable:
6185 case BTT_IsNothrowAssignable:
6186 case BTT_IsTriviallyAssignable: {
6187 // C++11 [meta.unary.prop]p3:
6188 // is_trivially_assignable is defined as:
6189 // is_assignable<T, U>::value is true and the assignment, as defined by
6190 // is_assignable, is known to call no operation that is not trivial
6191 //
6192 // is_assignable is defined as:
6193 // The expression declval<T>() = declval<U>() is well-formed when
6194 // treated as an unevaluated operand (Clause 5).
6195 //
6196 // For both, T and U shall be complete types, (possibly cv-qualified)
6197 // void, or arrays of unknown bound.
6198 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6199 Self.RequireCompleteType(
6200 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6201 diag::err_incomplete_type_used_in_type_trait_expr))
6202 return false;
6203 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6204 Self.RequireCompleteType(
6205 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6206 diag::err_incomplete_type_used_in_type_trait_expr))
6207 return false;
6208
6209 // cv void is never assignable.
6210 if (LhsT->isVoidType() || RhsT->isVoidType())
6211 return false;
6212
6213 // Build expressions that emulate the effect of declval<T>() and
6214 // declval<U>().
6215 if (LhsT->isObjectType() || LhsT->isFunctionType())
6216 LhsT = Self.Context.getRValueReferenceType(LhsT);
6217 if (RhsT->isObjectType() || RhsT->isFunctionType())
6218 RhsT = Self.Context.getRValueReferenceType(RhsT);
6219 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6221 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6223
6224 // Attempt the assignment in an unevaluated context within a SFINAE
6225 // trap at translation unit scope.
6228 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6229 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6230 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6231 &Rhs);
6232 if (Result.isInvalid())
6233 return false;
6234
6235 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6236 Self.CheckUnusedVolatileAssignment(Result.get());
6237
6238 if (SFINAE.hasErrorOccurred())
6239 return false;
6240
6241 if (BTT == BTT_IsAssignable)
6242 return true;
6243
6244 if (BTT == BTT_IsNothrowAssignable)
6245 return Self.canThrow(Result.get()) == CT_Cannot;
6246
6247 if (BTT == BTT_IsTriviallyAssignable) {
6248 // Under Objective-C ARC and Weak, if the destination has non-trivial
6249 // Objective-C lifetime, this is a non-trivial assignment.
6251 return false;
6252
6253 return !Result.get()->hasNonTrivialCall(Self.Context);
6254 }
6255
6256 llvm_unreachable("unhandled type trait");
6257 return false;
6258 }
6259 case BTT_IsLayoutCompatible: {
6260 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6261 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6262 diag::err_incomplete_type);
6263 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6264 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6265 diag::err_incomplete_type);
6266
6267 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6268 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6269
6270 return Self.IsLayoutCompatible(LhsT, RhsT);
6271 }
6272 case BTT_IsPointerInterconvertibleBaseOf: {
6273 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6274 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6275 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6276 diag::err_incomplete_type);
6277 }
6278
6280 tok::kw___is_pointer_interconvertible_base_of);
6282 tok::kw___is_pointer_interconvertible_base_of);
6283
6284 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6285 }
6286 case BTT_IsDeducible: {
6287 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6288 sema::TemplateDeductionInfo Info(KeyLoc);
6289 return Self.DeduceTemplateArgumentsFromType(
6290 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6292 }
6293 case BTT_IsScalarizedLayoutCompatible: {
6294 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6295 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6296 diag::err_incomplete_type))
6297 return true;
6298 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6299 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6300 diag::err_incomplete_type))
6301 return true;
6302
6304 Self, Lhs, tok::kw___builtin_hlsl_is_scalarized_layout_compatible);
6306 Self, Rhs, tok::kw___builtin_hlsl_is_scalarized_layout_compatible);
6307
6308 return Self.HLSL().IsScalarizedLayoutCompatible(LhsT, RhsT);
6309 }
6310 default:
6311 llvm_unreachable("not a BTT");
6312 }
6313 llvm_unreachable("Unknown type trait or not implemented");
6314}
6315
6317 SourceLocation KWLoc,
6318 ParsedType Ty,
6319 Expr* DimExpr,
6320 SourceLocation RParen) {
6321 TypeSourceInfo *TSInfo;
6322 QualType T = GetTypeFromParser(Ty, &TSInfo);
6323 if (!TSInfo)
6325
6326 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6327}
6328
6330 QualType T, Expr *DimExpr,
6331 SourceLocation KeyLoc) {
6332 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6333
6334 switch(ATT) {
6335 case ATT_ArrayRank:
6336 if (T->isArrayType()) {
6337 unsigned Dim = 0;
6338 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6339 ++Dim;
6340 T = AT->getElementType();
6341 }
6342 return Dim;
6343 }
6344 return 0;
6345
6346 case ATT_ArrayExtent: {
6347 llvm::APSInt Value;
6348 uint64_t Dim;
6349 if (Self.VerifyIntegerConstantExpression(
6350 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6351 .isInvalid())
6352 return 0;
6353 if (Value.isSigned() && Value.isNegative()) {
6354 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6355 << DimExpr->getSourceRange();
6356 return 0;
6357 }
6358 Dim = Value.getLimitedValue();
6359
6360 if (T->isArrayType()) {
6361 unsigned D = 0;
6362 bool Matched = false;
6363 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6364 if (Dim == D) {
6365 Matched = true;
6366 break;
6367 }
6368 ++D;
6369 T = AT->getElementType();
6370 }
6371
6372 if (Matched && T->isArrayType()) {
6373 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6374 return CAT->getLimitedSize();
6375 }
6376 }
6377 return 0;
6378 }
6379 }
6380 llvm_unreachable("Unknown type trait or not implemented");
6381}
6382
6384 SourceLocation KWLoc,
6385 TypeSourceInfo *TSInfo,
6386 Expr* DimExpr,
6387 SourceLocation RParen) {
6388 QualType T = TSInfo->getType();
6389
6390 // FIXME: This should likely be tracked as an APInt to remove any host
6391 // assumptions about the width of size_t on the target.
6392 uint64_t Value = 0;
6393 if (!T->isDependentType())
6394 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6395
6396 // While the specification for these traits from the Embarcadero C++
6397 // compiler's documentation says the return type is 'unsigned int', Clang
6398 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6399 // compiler, there is no difference. On several other platforms this is an
6400 // important distinction.
6401 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6402 RParen, Context.getSizeType());
6403}
6404
6406 SourceLocation KWLoc,
6407 Expr *Queried,
6408 SourceLocation RParen) {
6409 // If error parsing the expression, ignore.
6410 if (!Queried)
6411 return ExprError();
6412
6413 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6414
6415 return Result;
6416}
6417
6419 switch (ET) {
6420 case ET_IsLValueExpr: return E->isLValue();
6421 case ET_IsRValueExpr:
6422 return E->isPRValue();
6423 }
6424 llvm_unreachable("Expression trait not covered by switch");
6425}
6426
6428 SourceLocation KWLoc,
6429 Expr *Queried,
6430 SourceLocation RParen) {
6431 if (Queried->isTypeDependent()) {
6432 // Delay type-checking for type-dependent expressions.
6433 } else if (Queried->hasPlaceholderType()) {
6434 ExprResult PE = CheckPlaceholderExpr(Queried);
6435 if (PE.isInvalid()) return ExprError();
6436 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6437 }
6438
6439 bool Value = EvaluateExpressionTrait(ET, Queried);
6440
6441 return new (Context)
6442 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6443}
6444
6446 ExprValueKind &VK,
6448 bool isIndirect) {
6449 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6450 "placeholders should have been weeded out by now");
6451
6452 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6453 // temporary materialization conversion otherwise.
6454 if (isIndirect)
6455 LHS = DefaultLvalueConversion(LHS.get());
6456 else if (LHS.get()->isPRValue())
6458 if (LHS.isInvalid())
6459 return QualType();
6460
6461 // The RHS always undergoes lvalue conversions.
6462 RHS = DefaultLvalueConversion(RHS.get());
6463 if (RHS.isInvalid()) return QualType();
6464
6465 const char *OpSpelling = isIndirect ? "->*" : ".*";
6466 // C++ 5.5p2
6467 // The binary operator .* [p3: ->*] binds its second operand, which shall
6468 // be of type "pointer to member of T" (where T is a completely-defined
6469 // class type) [...]
6470 QualType RHSType = RHS.get()->getType();
6471 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6472 if (!MemPtr) {
6473 Diag(Loc, diag::err_bad_memptr_rhs)
6474 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6475 return QualType();
6476 }
6477
6478 QualType Class(MemPtr->getClass(), 0);
6479
6480 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6481 // member pointer points must be completely-defined. However, there is no
6482 // reason for this semantic distinction, and the rule is not enforced by
6483 // other compilers. Therefore, we do not check this property, as it is
6484 // likely to be considered a defect.
6485
6486 // C++ 5.5p2
6487 // [...] to its first operand, which shall be of class T or of a class of
6488 // which T is an unambiguous and accessible base class. [p3: a pointer to
6489 // such a class]
6490 QualType LHSType = LHS.get()->getType();
6491 if (isIndirect) {
6492 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6493 LHSType = Ptr->getPointeeType();
6494 else {
6495 Diag(Loc, diag::err_bad_memptr_lhs)
6496 << OpSpelling << 1 << LHSType
6498 return QualType();
6499 }
6500 }
6501
6502 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6503 // If we want to check the hierarchy, we need a complete type.
6504 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6505 OpSpelling, (int)isIndirect)) {
6506 return QualType();
6507 }
6508
6509 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6510 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6511 << (int)isIndirect << LHS.get()->getType();
6512 return QualType();
6513 }
6514
6515 CXXCastPath BasePath;
6517 LHSType, Class, Loc,
6518 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6519 &BasePath))
6520 return QualType();
6521
6522 // Cast LHS to type of use.
6523 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6524 if (isIndirect)
6525 UseType = Context.getPointerType(UseType);
6526 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6527 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6528 &BasePath);
6529 }
6530
6531 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6532 // Diagnose use of pointer-to-member type which when used as
6533 // the functional cast in a pointer-to-member expression.
6534 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6535 return QualType();
6536 }
6537
6538 // C++ 5.5p2
6539 // The result is an object or a function of the type specified by the
6540 // second operand.
6541 // The cv qualifiers are the union of those in the pointer and the left side,
6542 // in accordance with 5.5p5 and 5.2.5.
6543 QualType Result = MemPtr->getPointeeType();
6545
6546 // C++0x [expr.mptr.oper]p6:
6547 // In a .* expression whose object expression is an rvalue, the program is
6548 // ill-formed if the second operand is a pointer to member function with
6549 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6550 // expression is an lvalue, the program is ill-formed if the second operand
6551 // is a pointer to member function with ref-qualifier &&.
6552 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6553 switch (Proto->getRefQualifier()) {
6554 case RQ_None:
6555 // Do nothing
6556 break;
6557
6558 case RQ_LValue:
6559 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6560 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6561 // is (exactly) 'const'.
6562 if (Proto->isConst() && !Proto->isVolatile())
6564 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6565 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6566 else
6567 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6568 << RHSType << 1 << LHS.get()->getSourceRange();
6569 }
6570 break;
6571
6572 case RQ_RValue:
6573 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6574 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6575 << RHSType << 0 << LHS.get()->getSourceRange();
6576 break;
6577 }
6578 }
6579
6580 // C++ [expr.mptr.oper]p6:
6581 // The result of a .* expression whose second operand is a pointer
6582 // to a data member is of the same value category as its
6583 // first operand. The result of a .* expression whose second
6584 // operand is a pointer to a member function is a prvalue. The
6585 // result of an ->* expression is an lvalue if its second operand
6586 // is a pointer to data member and a prvalue otherwise.
6587 if (Result->isFunctionType()) {
6588 VK = VK_PRValue;
6589 return Context.BoundMemberTy;
6590 } else if (isIndirect) {
6591 VK = VK_LValue;
6592 } else {
6593 VK = LHS.get()->getValueKind();
6594 }
6595
6596 return Result;
6597}
6598
6599/// Try to convert a type to another according to C++11 5.16p3.
6600///
6601/// This is part of the parameter validation for the ? operator. If either
6602/// value operand is a class type, the two operands are attempted to be
6603/// converted to each other. This function does the conversion in one direction.
6604/// It returns true if the program is ill-formed and has already been diagnosed
6605/// as such.
6606static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6607 SourceLocation QuestionLoc,
6608 bool &HaveConversion,
6609 QualType &ToType) {
6610 HaveConversion = false;
6611 ToType = To->getType();
6612
6613 InitializationKind Kind =
6615 // C++11 5.16p3
6616 // The process for determining whether an operand expression E1 of type T1
6617 // can be converted to match an operand expression E2 of type T2 is defined
6618 // as follows:
6619 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6620 // implicitly converted to type "lvalue reference to T2", subject to the
6621 // constraint that in the conversion the reference must bind directly to
6622 // an lvalue.
6623 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6624 // implicitly converted to the type "rvalue reference to R2", subject to
6625 // the constraint that the reference must bind directly.
6626 if (To->isGLValue()) {
6627 QualType T = Self.Context.getReferenceQualifiedType(To);
6629
6630 InitializationSequence InitSeq(Self, Entity, Kind, From);
6631 if (InitSeq.isDirectReferenceBinding()) {
6632 ToType = T;
6633 HaveConversion = true;
6634 return false;
6635 }
6636
6637 if (InitSeq.isAmbiguous())
6638 return InitSeq.Diagnose(Self, Entity, Kind, From);
6639 }
6640
6641 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6642 // -- if E1 and E2 have class type, and the underlying class types are
6643 // the same or one is a base class of the other:
6644 QualType FTy = From->getType();
6645 QualType TTy = To->getType();
6646 const RecordType *FRec = FTy->getAs<RecordType>();
6647 const RecordType *TRec = TTy->getAs<RecordType>();
6648 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6649 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6650 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6651 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6652 // E1 can be converted to match E2 if the class of T2 is the
6653 // same type as, or a base class of, the class of T1, and
6654 // [cv2 > cv1].
6655 if (FRec == TRec || FDerivedFromT) {
6656 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) {
6658 InitializationSequence InitSeq(Self, Entity, Kind, From);
6659 if (InitSeq) {
6660 HaveConversion = true;
6661 return false;
6662 }
6663
6664 if (InitSeq.isAmbiguous())
6665 return InitSeq.Diagnose(Self, Entity, Kind, From);
6666 }
6667 }
6668
6669 return false;
6670 }
6671
6672 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6673 // implicitly converted to the type that expression E2 would have
6674 // if E2 were converted to an rvalue (or the type it has, if E2 is
6675 // an rvalue).
6676 //
6677 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6678 // to the array-to-pointer or function-to-pointer conversions.
6679 TTy = TTy.getNonLValueExprType(Self.Context);
6680
6682 InitializationSequence InitSeq(Self, Entity, Kind, From);
6683 HaveConversion = !InitSeq.Failed();
6684 ToType = TTy;
6685 if (InitSeq.isAmbiguous())
6686 return InitSeq.Diagnose(Self, Entity, Kind, From);
6687
6688 return false;
6689}
6690
6691/// Try to find a common type for two according to C++0x 5.16p5.
6692///
6693/// This is part of the parameter validation for the ? operator. If either
6694/// value operand is a class type, overload resolution is used to find a
6695/// conversion to a common type.
6697 SourceLocation QuestionLoc) {
6698 Expr *Args[2] = { LHS.get(), RHS.get() };
6699 OverloadCandidateSet CandidateSet(QuestionLoc,
6701 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6702 CandidateSet);
6703
6705 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6706 case OR_Success: {
6707 // We found a match. Perform the conversions on the arguments and move on.
6708 ExprResult LHSRes = Self.PerformImplicitConversion(
6709 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6711 if (LHSRes.isInvalid())
6712 break;
6713 LHS = LHSRes;
6714
6715 ExprResult RHSRes = Self.PerformImplicitConversion(
6716 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6718 if (RHSRes.isInvalid())
6719 break;
6720 RHS = RHSRes;
6721 if (Best->Function)
6722 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6723 return false;
6724 }
6725
6727
6728 // Emit a better diagnostic if one of the expressions is a null pointer
6729 // constant and the other is a pointer type. In this case, the user most
6730 // likely forgot to take the address of the other expression.
6731 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6732 return true;
6733
6734 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6735 << LHS.get()->getType() << RHS.get()->getType()
6736 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6737 return true;
6738
6739 case OR_Ambiguous:
6740 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6741 << LHS.get()->getType() << RHS.get()->getType()
6742 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6743 // FIXME: Print the possible common types by printing the return types of
6744 // the viable candidates.
6745 break;
6746
6747 case OR_Deleted:
6748 llvm_unreachable("Conditional operator has only built-in overloads");
6749 }
6750 return true;
6751}
6752
6753/// Perform an "extended" implicit conversion as returned by
6754/// TryClassUnification.
6757 InitializationKind Kind =
6759 Expr *Arg = E.get();
6760 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6761 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6762 if (Result.isInvalid())
6763 return true;
6764
6765 E = Result;
6766 return false;
6767}
6768
6769// Check the condition operand of ?: to see if it is valid for the GCC
6770// extension.
6772 QualType CondTy) {
6773 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6774 return false;
6775 const QualType EltTy =
6776 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6777 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6778 return EltTy->isIntegralType(Ctx);
6779}
6780
6782 QualType CondTy) {
6783 if (!CondTy->isSveVLSBuiltinType())
6784 return false;
6785 const QualType EltTy =
6786 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6787 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6788 return EltTy->isIntegralType(Ctx);
6789}
6790
6792 ExprResult &RHS,
6793 SourceLocation QuestionLoc) {
6796
6797 QualType CondType = Cond.get()->getType();
6798 const auto *CondVT = CondType->castAs<VectorType>();
6799 QualType CondElementTy = CondVT->getElementType();
6800 unsigned CondElementCount = CondVT->getNumElements();
6801 QualType LHSType = LHS.get()->getType();
6802 const auto *LHSVT = LHSType->getAs<VectorType>();
6803 QualType RHSType = RHS.get()->getType();
6804 const auto *RHSVT = RHSType->getAs<VectorType>();
6805
6806 QualType ResultType;
6807
6808
6809 if (LHSVT && RHSVT) {
6810 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6811 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6812 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6813 return {};
6814 }
6815
6816 // If both are vector types, they must be the same type.
6817 if (!Context.hasSameType(LHSType, RHSType)) {
6818 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6819 << LHSType << RHSType;
6820 return {};
6821 }
6822 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6823 } else if (LHSVT || RHSVT) {
6824 ResultType = CheckVectorOperands(
6825 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6826 /*AllowBoolConversions*/ false,
6827 /*AllowBoolOperation*/ true,
6828 /*ReportInvalid*/ true);
6829 if (ResultType.isNull())
6830 return {};
6831 } else {
6832 // Both are scalar.
6833 LHSType = LHSType.getUnqualifiedType();
6834 RHSType = RHSType.getUnqualifiedType();
6835 QualType ResultElementTy =
6836 Context.hasSameType(LHSType, RHSType)
6837 ? Context.getCommonSugaredType(LHSType, RHSType)
6838 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6840
6841 if (ResultElementTy->isEnumeralType()) {
6842 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6843 << ResultElementTy;
6844 return {};
6845 }
6846 if (CondType->isExtVectorType())
6847 ResultType =
6848 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6849 else
6850 ResultType = Context.getVectorType(
6851 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6852
6853 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6854 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6855 }
6856
6857 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6858 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6859 "Result should have been a vector type");
6860 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6861 QualType ResultElementTy = ResultVectorTy->getElementType();
6862 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6863
6864 if (ResultElementCount != CondElementCount) {
6865 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6866 << ResultType;
6867 return {};
6868 }
6869
6870 if (Context.getTypeSize(ResultElementTy) !=
6871 Context.getTypeSize(CondElementTy)) {
6872 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6873 << ResultType;
6874 return {};
6875 }
6876
6877 return ResultType;
6878}
6879
6881 ExprResult &LHS,
6882 ExprResult &RHS,
6883 SourceLocation QuestionLoc) {
6886
6887 QualType CondType = Cond.get()->getType();
6888 const auto *CondBT = CondType->castAs<BuiltinType>();
6889 QualType CondElementTy = CondBT->getSveEltType(Context);
6890 llvm::ElementCount CondElementCount =
6892
6893 QualType LHSType = LHS.get()->getType();
6894 const auto *LHSBT =
6895 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6896 QualType RHSType = RHS.get()->getType();
6897 const auto *RHSBT =
6898 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6899
6900 QualType ResultType;
6901
6902 if (LHSBT && RHSBT) {
6903 // If both are sizeless vector types, they must be the same type.
6904 if (!Context.hasSameType(LHSType, RHSType)) {
6905 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6906 << LHSType << RHSType;
6907 return QualType();
6908 }
6909 ResultType = LHSType;
6910 } else if (LHSBT || RHSBT) {
6911 ResultType = CheckSizelessVectorOperands(
6912 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6913 if (ResultType.isNull())
6914 return QualType();
6915 } else {
6916 // Both are scalar so splat
6917 QualType ResultElementTy;
6918 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6919 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6920
6921 if (Context.hasSameType(LHSType, RHSType))
6922 ResultElementTy = LHSType;
6923 else
6924 ResultElementTy =
6925 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6926
6927 if (ResultElementTy->isEnumeralType()) {
6928 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6929 << ResultElementTy;
6930 return QualType();
6931 }
6932
6933 ResultType = Context.getScalableVectorType(
6934 ResultElementTy, CondElementCount.getKnownMinValue());
6935
6936 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6937 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6938 }
6939
6940 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6941 "Result should have been a vector type");
6942 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6943 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6944 llvm::ElementCount ResultElementCount =
6945 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6946
6947 if (ResultElementCount != CondElementCount) {
6948 Diag(QuestionLoc, diag::err_conditional_vector_size)
6949 << CondType << ResultType;
6950 return QualType();
6951 }
6952
6953 if (Context.getTypeSize(ResultElementTy) !=
6954 Context.getTypeSize(CondElementTy)) {
6955 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6956 << CondType << ResultType;
6957 return QualType();
6958 }
6959
6960 return ResultType;
6961}
6962
6964 ExprResult &RHS, ExprValueKind &VK,
6965 ExprObjectKind &OK,
6966 SourceLocation QuestionLoc) {
6967 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6968 // pointers.
6969
6970 // Assume r-value.
6971 VK = VK_PRValue;
6972 OK = OK_Ordinary;
6973 bool IsVectorConditional =
6975
6976 bool IsSizelessVectorConditional =
6978 Cond.get()->getType());
6979
6980 // C++11 [expr.cond]p1
6981 // The first expression is contextually converted to bool.
6982 if (!Cond.get()->isTypeDependent()) {
6983 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6985 : CheckCXXBooleanCondition(Cond.get());
6986 if (CondRes.isInvalid())
6987 return QualType();
6988 Cond = CondRes;
6989 } else {
6990 // To implement C++, the first expression typically doesn't alter the result
6991 // type of the conditional, however the GCC compatible vector extension
6992 // changes the result type to be that of the conditional. Since we cannot
6993 // know if this is a vector extension here, delay the conversion of the
6994 // LHS/RHS below until later.
6995 return Context.DependentTy;
6996 }
6997
6998
6999 // Either of the arguments dependent?
7000 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
7001 return Context.DependentTy;
7002
7003 // C++11 [expr.cond]p2
7004 // If either the second or the third operand has type (cv) void, ...
7005 QualType LTy = LHS.get()->getType();
7006 QualType RTy = RHS.get()->getType();
7007 bool LVoid = LTy->isVoidType();
7008 bool RVoid = RTy->isVoidType();
7009 if (LVoid || RVoid) {
7010 // ... one of the following shall hold:
7011 // -- The second or the third operand (but not both) is a (possibly
7012 // parenthesized) throw-expression; the result is of the type
7013 // and value category of the other.
7014 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
7015 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
7016
7017 // Void expressions aren't legal in the vector-conditional expressions.
7018 if (IsVectorConditional) {
7019 SourceRange DiagLoc =
7020 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
7021 bool IsThrow = LVoid ? LThrow : RThrow;
7022 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
7023 << DiagLoc << IsThrow;
7024 return QualType();
7025 }
7026
7027 if (LThrow != RThrow) {
7028 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
7029 VK = NonThrow->getValueKind();
7030 // DR (no number yet): the result is a bit-field if the
7031 // non-throw-expression operand is a bit-field.
7032 OK = NonThrow->getObjectKind();
7033 return NonThrow->getType();
7034 }
7035
7036 // -- Both the second and third operands have type void; the result is of
7037 // type void and is a prvalue.
7038 if (LVoid && RVoid)
7039 return Context.getCommonSugaredType(LTy, RTy);
7040
7041 // Neither holds, error.
7042 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
7043 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
7044 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7045 return QualType();
7046 }
7047
7048 // Neither is void.
7049 if (IsVectorConditional)
7050 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
7051
7052 if (IsSizelessVectorConditional)
7053 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
7054
7055 // WebAssembly tables are not allowed as conditional LHS or RHS.
7056 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
7057 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
7058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7059 return QualType();
7060 }
7061
7062 // C++11 [expr.cond]p3
7063 // Otherwise, if the second and third operand have different types, and
7064 // either has (cv) class type [...] an attempt is made to convert each of
7065 // those operands to the type of the other.
7066 if (!Context.hasSameType(LTy, RTy) &&
7067 (LTy->isRecordType() || RTy->isRecordType())) {
7068 // These return true if a single direction is already ambiguous.
7069 QualType L2RType, R2LType;
7070 bool HaveL2R, HaveR2L;
7071 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
7072 return QualType();
7073 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
7074 return QualType();
7075
7076 // If both can be converted, [...] the program is ill-formed.
7077 if (HaveL2R && HaveR2L) {
7078 Diag(QuestionLoc, diag::err_conditional_ambiguous)
7079 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7080 return QualType();
7081 }
7082
7083 // If exactly one conversion is possible, that conversion is applied to
7084 // the chosen operand and the converted operands are used in place of the
7085 // original operands for the remainder of this section.
7086 if (HaveL2R) {
7087 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
7088 return QualType();
7089 LTy = LHS.get()->getType();
7090 } else if (HaveR2L) {
7091 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
7092 return QualType();
7093 RTy = RHS.get()->getType();
7094 }
7095 }
7096
7097 // C++11 [expr.cond]p3
7098 // if both are glvalues of the same value category and the same type except
7099 // for cv-qualification, an attempt is made to convert each of those
7100 // operands to the type of the other.
7101 // FIXME:
7102 // Resolving a defect in P0012R1: we extend this to cover all cases where
7103 // one of the operands is reference-compatible with the other, in order
7104 // to support conditionals between functions differing in noexcept. This
7105 // will similarly cover difference in array bounds after P0388R4.
7106 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
7107 // that instead?
7108 ExprValueKind LVK = LHS.get()->getValueKind();
7109 ExprValueKind RVK = RHS.get()->getValueKind();
7110 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
7111 // DerivedToBase was already handled by the class-specific case above.
7112 // FIXME: Should we allow ObjC conversions here?
7113 const ReferenceConversions AllowedConversions =
7114 ReferenceConversions::Qualification |
7115 ReferenceConversions::NestedQualification |
7116 ReferenceConversions::Function;
7117
7118 ReferenceConversions RefConv;
7119 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
7121 !(RefConv & ~AllowedConversions) &&
7122 // [...] subject to the constraint that the reference must bind
7123 // directly [...]
7124 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
7125 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
7126 RTy = RHS.get()->getType();
7127 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
7129 !(RefConv & ~AllowedConversions) &&
7130 !LHS.get()->refersToBitField() &&
7131 !LHS.get()->refersToVectorElement()) {
7132 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
7133 LTy = LHS.get()->getType();
7134 }
7135 }
7136
7137 // C++11 [expr.cond]p4
7138 // If the second and third operands are glvalues of the same value
7139 // category and have the same type, the result is of that type and
7140 // value category and it is a bit-field if the second or the third
7141 // operand is a bit-field, or if both are bit-fields.
7142 // We only extend this to bitfields, not to the crazy other kinds of
7143 // l-values.
7144 bool Same = Context.hasSameType(LTy, RTy);
7145 if (Same && LVK == RVK && LVK != VK_PRValue &&
7148 VK = LHS.get()->getValueKind();
7149 if (LHS.get()->getObjectKind() == OK_BitField ||
7150 RHS.get()->getObjectKind() == OK_BitField)
7151 OK = OK_BitField;
7152 return Context.getCommonSugaredType(LTy, RTy);
7153 }
7154
7155 // C++11 [expr.cond]p5
7156 // Otherwise, the result is a prvalue. If the second and third operands
7157 // do not have the same type, and either has (cv) class type, ...
7158 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7159 // ... overload resolution is used to determine the conversions (if any)
7160 // to be applied to the operands. If the overload resolution fails, the
7161 // program is ill-formed.
7162 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7163 return QualType();
7164 }
7165
7166 // C++11 [expr.cond]p6
7167 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7168 // conversions are performed on the second and third operands.
7171 if (LHS.isInvalid() || RHS.isInvalid())
7172 return QualType();
7173 LTy = LHS.get()->getType();
7174 RTy = RHS.get()->getType();
7175
7176 // After those conversions, one of the following shall hold:
7177 // -- The second and third operands have the same type; the result
7178 // is of that type. If the operands have class type, the result
7179 // is a prvalue temporary of the result type, which is
7180 // copy-initialized from either the second operand or the third
7181 // operand depending on the value of the first operand.
7182 if (Context.hasSameType(LTy, RTy)) {
7183 if (LTy->isRecordType()) {
7184 // The operands have class type. Make a temporary copy.
7187 if (LHSCopy.isInvalid())
7188 return QualType();
7189
7192 if (RHSCopy.isInvalid())
7193 return QualType();
7194
7195 LHS = LHSCopy;
7196 RHS = RHSCopy;
7197 }
7198 return Context.getCommonSugaredType(LTy, RTy);
7199 }
7200
7201 // Extension: conditional operator involving vector types.
7202 if (LTy->isVectorType() || RTy->isVectorType())
7203 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7204 /*AllowBothBool*/ true,
7205 /*AllowBoolConversions*/ false,
7206 /*AllowBoolOperation*/ false,
7207 /*ReportInvalid*/ true);
7208
7209 // -- The second and third operands have arithmetic or enumeration type;
7210 // the usual arithmetic conversions are performed to bring them to a
7211 // common type, and the result is of that type.
7212 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7213 QualType ResTy =
7214 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7215 if (LHS.isInvalid() || RHS.isInvalid())
7216 return QualType();
7217 if (ResTy.isNull()) {
7218 Diag(QuestionLoc,
7219 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7220 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7221 return QualType();
7222 }
7223
7224 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7225 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7226
7227 return ResTy;
7228 }
7229
7230 // -- The second and third operands have pointer type, or one has pointer
7231 // type and the other is a null pointer constant, or both are null
7232 // pointer constants, at least one of which is non-integral; pointer
7233 // conversions and qualification conversions are performed to bring them
7234 // to their composite pointer type. The result is of the composite
7235 // pointer type.
7236 // -- The second and third operands have pointer to member type, or one has
7237 // pointer to member type and the other is a null pointer constant;
7238 // pointer to member conversions and qualification conversions are
7239 // performed to bring them to a common type, whose cv-qualification
7240 // shall match the cv-qualification of either the second or the third
7241 // operand. The result is of the common type.
7242 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7243 if (!Composite.isNull())
7244 return Composite;
7245
7246 // Similarly, attempt to find composite type of two objective-c pointers.
7247 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7248 if (LHS.isInvalid() || RHS.isInvalid())
7249 return QualType();
7250 if (!Composite.isNull())
7251 return Composite;
7252
7253 // Check if we are using a null with a non-pointer type.
7254 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7255 return QualType();
7256
7257 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7258 << LHS.get()->getType() << RHS.get()->getType()
7259 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7260 return QualType();
7261}
7262
7264 Expr *&E1, Expr *&E2,
7265 bool ConvertArgs) {
7266 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7267
7268 // C++1z [expr]p14:
7269 // The composite pointer type of two operands p1 and p2 having types T1
7270 // and T2
7271 QualType T1 = E1->getType(), T2 = E2->getType();
7272
7273 // where at least one is a pointer or pointer to member type or
7274 // std::nullptr_t is:
7275 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7276 T1->isNullPtrType();
7277 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7278 T2->isNullPtrType();
7279 if (!T1IsPointerLike && !T2IsPointerLike)
7280 return QualType();
7281
7282 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7283 // This can't actually happen, following the standard, but we also use this
7284 // to implement the end of [expr.conv], which hits this case.
7285 //
7286 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7287 if (T1IsPointerLike &&
7289 if (ConvertArgs)
7290 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7291 ? CK_NullToMemberPointer
7292 : CK_NullToPointer).get();
7293 return T1;
7294 }
7295 if (T2IsPointerLike &&
7297 if (ConvertArgs)
7298 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7299 ? CK_NullToMemberPointer
7300 : CK_NullToPointer).get();
7301 return T2;
7302 }
7303
7304 // Now both have to be pointers or member pointers.
7305 if (!T1IsPointerLike || !T2IsPointerLike)
7306 return QualType();
7307 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7308 "nullptr_t should be a null pointer constant");
7309
7310 struct Step {
7311 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7312 // Qualifiers to apply under the step kind.
7313 Qualifiers Quals;
7314 /// The class for a pointer-to-member; a constant array type with a bound
7315 /// (if any) for an array.
7316 const Type *ClassOrBound;
7317
7318 Step(Kind K, const Type *ClassOrBound = nullptr)
7319 : K(K), ClassOrBound(ClassOrBound) {}
7320 QualType rebuild(ASTContext &Ctx, QualType T) const {
7321 T = Ctx.getQualifiedType(T, Quals);
7322 switch (K) {
7323 case Pointer:
7324 return Ctx.getPointerType(T);
7325 case MemberPointer:
7326 return Ctx.getMemberPointerType(T, ClassOrBound);
7327 case ObjCPointer:
7328 return Ctx.getObjCObjectPointerType(T);
7329 case Array:
7330 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7331 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7332 ArraySizeModifier::Normal, 0);
7333 else
7334 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7335 }
7336 llvm_unreachable("unknown step kind");
7337 }
7338 };
7339
7341
7342 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7343 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7344 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7345 // respectively;
7346 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7347 // to member of C2 of type cv2 U2" for some non-function type U, where
7348 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7349 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7350 // respectively;
7351 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7352 // T2;
7353 //
7354 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7355 // and to prepare to form the cv-combined type if so.
7356 QualType Composite1 = T1;
7357 QualType Composite2 = T2;
7358 unsigned NeedConstBefore = 0;
7359 while (true) {
7360 assert(!Composite1.isNull() && !Composite2.isNull());
7361
7362 Qualifiers Q1, Q2;
7363 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7364 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7365
7366 // Top-level qualifiers are ignored. Merge at all lower levels.
7367 if (!Steps.empty()) {
7368 // Find the qualifier union: (approximately) the unique minimal set of
7369 // qualifiers that is compatible with both types.
7371 Q2.getCVRUQualifiers());
7372
7373 // Under one level of pointer or pointer-to-member, we can change to an
7374 // unambiguous compatible address space.
7375 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7376 Quals.setAddressSpace(Q1.getAddressSpace());
7377 } else if (Steps.size() == 1) {
7378 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext());
7379 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext());
7380 if (MaybeQ1 == MaybeQ2) {
7381 // Exception for ptr size address spaces. Should be able to choose
7382 // either address space during comparison.
7385 MaybeQ1 = true;
7386 else
7387 return QualType(); // No unique best address space.
7388 }
7389 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7390 : Q2.getAddressSpace());
7391 } else {
7392 return QualType();
7393 }
7394
7395 // FIXME: In C, we merge __strong and none to __strong at the top level.
7396 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7397 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7398 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7399 assert(Steps.size() == 1);
7400 else
7401 return QualType();
7402
7403 // Mismatched lifetime qualifiers never compatibly include each other.
7404 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7405 Quals.setObjCLifetime(Q1.getObjCLifetime());
7406 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7407 assert(Steps.size() == 1);
7408 else
7409 return QualType();
7410
7411 Steps.back().Quals = Quals;
7412 if (Q1 != Quals || Q2 != Quals)
7413 NeedConstBefore = Steps.size() - 1;
7414 }
7415
7416 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7417
7418 const ArrayType *Arr1, *Arr2;
7419 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7420 (Arr2 = Context.getAsArrayType(Composite2))) {
7421 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7422 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7423 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7424 Composite1 = Arr1->getElementType();
7425 Composite2 = Arr2->getElementType();
7426 Steps.emplace_back(Step::Array, CAT1);
7427 continue;
7428 }
7429 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7430 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7431 if ((IAT1 && IAT2) ||
7432 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7433 ((bool)CAT1 != (bool)CAT2) &&
7434 (Steps.empty() || Steps.back().K != Step::Array))) {
7435 // In C++20 onwards, we can unify an array of N T with an array of
7436 // a different or unknown bound. But we can't form an array whose
7437 // element type is an array of unknown bound by doing so.
7438 Composite1 = Arr1->getElementType();
7439 Composite2 = Arr2->getElementType();
7440 Steps.emplace_back(Step::Array);
7441 if (CAT1 || CAT2)
7442 NeedConstBefore = Steps.size();
7443 continue;
7444 }
7445 }
7446
7447 const PointerType *Ptr1, *Ptr2;
7448 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7449 (Ptr2 = Composite2->getAs<PointerType>())) {
7450 Composite1 = Ptr1->getPointeeType();
7451 Composite2 = Ptr2->getPointeeType();
7452 Steps.emplace_back(Step::Pointer);
7453 continue;
7454 }
7455
7456 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7457 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7458 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7459 Composite1 = ObjPtr1->getPointeeType();
7460 Composite2 = ObjPtr2->getPointeeType();
7461 Steps.emplace_back(Step::ObjCPointer);
7462 continue;
7463 }
7464
7465 const MemberPointerType *MemPtr1, *MemPtr2;
7466 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7467 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7468 Composite1 = MemPtr1->getPointeeType();
7469 Composite2 = MemPtr2->getPointeeType();
7470
7471 // At the top level, we can perform a base-to-derived pointer-to-member
7472 // conversion:
7473 //
7474 // - [...] where C1 is reference-related to C2 or C2 is
7475 // reference-related to C1
7476 //
7477 // (Note that the only kinds of reference-relatedness in scope here are
7478 // "same type or derived from".) At any other level, the class must
7479 // exactly match.
7480 const Type *Class = nullptr;
7481 QualType Cls1(MemPtr1->getClass(), 0);
7482 QualType Cls2(MemPtr2->getClass(), 0);
7483 if (Context.hasSameType(Cls1, Cls2))
7484 Class = MemPtr1->getClass();
7485 else if (Steps.empty())
7486 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7487 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7488 if (!Class)
7489 return QualType();
7490
7491 Steps.emplace_back(Step::MemberPointer, Class);
7492 continue;
7493 }
7494
7495 // Special case: at the top level, we can decompose an Objective-C pointer
7496 // and a 'cv void *'. Unify the qualifiers.
7497 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7498 Composite2->isObjCObjectPointerType()) ||
7499 (Composite1->isObjCObjectPointerType() &&
7500 Composite2->isVoidPointerType()))) {
7501 Composite1 = Composite1->getPointeeType();
7502 Composite2 = Composite2->getPointeeType();
7503 Steps.emplace_back(Step::Pointer);
7504 continue;
7505 }
7506
7507 // FIXME: block pointer types?
7508
7509 // Cannot unwrap any more types.
7510 break;
7511 }
7512
7513 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7514 // "pointer to function", where the function types are otherwise the same,
7515 // "pointer to function";
7516 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7517 // type is "pointer to member of C2 of type noexcept function", and C1
7518 // is reference-related to C2 or C2 is reference-related to C1, where
7519 // the function types are otherwise the same, "pointer to member of C2 of
7520 // type function" or "pointer to member of C1 of type function",
7521 // respectively;
7522 //
7523 // We also support 'noreturn' here, so as a Clang extension we generalize the
7524 // above to:
7525 //
7526 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7527 // "pointer to member function" and the pointee types can be unified
7528 // by a function pointer conversion, that conversion is applied
7529 // before checking the following rules.
7530 //
7531 // We've already unwrapped down to the function types, and we want to merge
7532 // rather than just convert, so do this ourselves rather than calling
7533 // IsFunctionConversion.
7534 //
7535 // FIXME: In order to match the standard wording as closely as possible, we
7536 // currently only do this under a single level of pointers. Ideally, we would
7537 // allow this in general, and set NeedConstBefore to the relevant depth on
7538 // the side(s) where we changed anything. If we permit that, we should also
7539 // consider this conversion when determining type similarity and model it as
7540 // a qualification conversion.
7541 if (Steps.size() == 1) {
7542 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7543 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7544 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7545 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7546
7547 // The result is noreturn if both operands are.
7548 bool Noreturn =
7549 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7550 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7551 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7552
7553 // The result is nothrow if both operands are.
7554 SmallVector<QualType, 8> ExceptionTypeStorage;
7556 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7558
7559 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7560 FPT1->getParamTypes(), EPI1);
7561 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7562 FPT2->getParamTypes(), EPI2);
7563 }
7564 }
7565 }
7566
7567 // There are some more conversions we can perform under exactly one pointer.
7568 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7569 !Context.hasSameType(Composite1, Composite2)) {
7570 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7571 // "pointer to cv2 T", where T is an object type or void,
7572 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7573 if (Composite1->isVoidType() && Composite2->isObjectType())
7574 Composite2 = Composite1;
7575 else if (Composite2->isVoidType() && Composite1->isObjectType())
7576 Composite1 = Composite2;
7577 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7578 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7579 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7580 // T1, respectively;
7581 //
7582 // The "similar type" handling covers all of this except for the "T1 is a
7583 // base class of T2" case in the definition of reference-related.
7584 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7585 Composite1 = Composite2;
7586 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7587 Composite2 = Composite1;
7588 }
7589
7590 // At this point, either the inner types are the same or we have failed to
7591 // find a composite pointer type.
7592 if (!Context.hasSameType(Composite1, Composite2))
7593 return QualType();
7594
7595 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7596 // differing qualifier.
7597 for (unsigned I = 0; I != NeedConstBefore; ++I)
7598 Steps[I].Quals.addConst();
7599
7600 // Rebuild the composite type.
7601 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7602 for (auto &S : llvm::reverse(Steps))
7603 Composite = S.rebuild(Context, Composite);
7604
7605 if (ConvertArgs) {
7606 // Convert the expressions to the composite pointer type.
7607 InitializedEntity Entity =
7609 InitializationKind Kind =
7611
7612 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7613 if (!E1ToC)
7614 return QualType();
7615
7616 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7617 if (!E2ToC)
7618 return QualType();
7619
7620 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7621 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7622 if (E1Result.isInvalid())
7623 return QualType();
7624 E1 = E1Result.get();
7625
7626 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7627 if (E2Result.isInvalid())
7628 return QualType();
7629 E2 = E2Result.get();
7630 }
7631
7632 return Composite;
7633}
7634
7636 if (!E)
7637 return ExprError();
7638
7639 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7640
7641 // If the result is a glvalue, we shouldn't bind it.
7642 if (E->isGLValue())
7643 return E;
7644
7645 // In ARC, calls that return a retainable type can return retained,
7646 // in which case we have to insert a consuming cast.
7647 if (getLangOpts().ObjCAutoRefCount &&
7649
7650 bool ReturnsRetained;
7651
7652 // For actual calls, we compute this by examining the type of the
7653 // called value.
7654 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7655 Expr *Callee = Call->getCallee()->IgnoreParens();
7656 QualType T = Callee->getType();
7657
7658 if (T == Context.BoundMemberTy) {
7659 // Handle pointer-to-members.
7660 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7661 T = BinOp->getRHS()->getType();
7662 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7663 T = Mem->getMemberDecl()->getType();
7664 }
7665
7666 if (const PointerType *Ptr = T->getAs<PointerType>())
7667 T = Ptr->getPointeeType();
7668 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7669 T = Ptr->getPointeeType();
7670 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7671 T = MemPtr->getPointeeType();
7672
7673 auto *FTy = T->castAs<FunctionType>();
7674 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7675
7676 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7677 // type always produce a +1 object.
7678 } else if (isa<StmtExpr>(E)) {
7679 ReturnsRetained = true;
7680
7681 // We hit this case with the lambda conversion-to-block optimization;
7682 // we don't want any extra casts here.
7683 } else if (isa<CastExpr>(E) &&
7684 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7685 return E;
7686
7687 // For message sends and property references, we try to find an
7688 // actual method. FIXME: we should infer retention by selector in
7689 // cases where we don't have an actual method.
7690 } else {
7691 ObjCMethodDecl *D = nullptr;
7692 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7693 D = Send->getMethodDecl();
7694 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7695 D = BoxedExpr->getBoxingMethod();
7696 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7697 // Don't do reclaims if we're using the zero-element array
7698 // constant.
7699 if (ArrayLit->getNumElements() == 0 &&
7701 return E;
7702
7703 D = ArrayLit->getArrayWithObjectsMethod();
7704 } else if (ObjCDictionaryLiteral *DictLit
7705 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7706 // Don't do reclaims if we're using the zero-element dictionary
7707 // constant.
7708 if (DictLit->getNumElements() == 0 &&
7710 return E;
7711
7712 D = DictLit->getDictWithObjectsMethod();
7713 }
7714
7715 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7716
7717 // Don't do reclaims on performSelector calls; despite their
7718 // return type, the invoked method doesn't necessarily actually
7719 // return an object.
7720 if (!ReturnsRetained &&
7721 D && D->getMethodFamily() == OMF_performSelector)
7722 return E;
7723 }
7724
7725 // Don't reclaim an object of Class type.
7726 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7727 return E;
7728
7730
7731 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7732 : CK_ARCReclaimReturnedObject);
7733 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7735 }
7736
7739
7740 if (!getLangOpts().CPlusPlus)
7741 return E;
7742
7743 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7744 // a fast path for the common case that the type is directly a RecordType.
7746 const RecordType *RT = nullptr;
7747 while (!RT) {
7748 switch (T->getTypeClass()) {
7749 case Type::Record:
7750 RT = cast<RecordType>(T);
7751 break;
7752 case Type::ConstantArray:
7753 case Type::IncompleteArray:
7754 case Type::VariableArray:
7755 case Type::DependentSizedArray:
7756 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7757 break;
7758 default:
7759 return E;
7760 }
7761 }
7762
7763 // That should be enough to guarantee that this type is complete, if we're
7764 // not processing a decltype expression.
7765 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7766 if (RD->isInvalidDecl() || RD->isDependentContext())
7767 return E;
7768
7769 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7771 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7772
7773 if (Destructor) {
7776 PDiag(diag::err_access_dtor_temp)
7777 << E->getType());
7779 return ExprError();
7780
7781 // If destructor is trivial, we can avoid the extra copy.
7782 if (Destructor->isTrivial())
7783 return E;
7784
7785 // We need a cleanup, but we don't need to remember the temporary.
7787 }
7788
7791
7792 if (IsDecltype)
7793 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7794
7795 return Bind;
7796}
7797
7800 if (SubExpr.isInvalid())
7801 return ExprError();
7802
7803 return MaybeCreateExprWithCleanups(SubExpr.get());
7804}
7805
7807 assert(SubExpr && "subexpression can't be null!");
7808
7810
7811 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7812 assert(ExprCleanupObjects.size() >= FirstCleanup);
7813 assert(Cleanup.exprNeedsCleanups() ||
7814 ExprCleanupObjects.size() == FirstCleanup);
7816 return SubExpr;
7817
7818 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7819 ExprCleanupObjects.size() - FirstCleanup);
7820
7822 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7824
7825 return E;
7826}
7827
7829 assert(SubStmt && "sub-statement can't be null!");
7830
7832
7834 return SubStmt;
7835
7836 // FIXME: In order to attach the temporaries, wrap the statement into
7837 // a StmtExpr; currently this is only used for asm statements.
7838 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7839 // a new AsmStmtWithTemporaries.
7840 CompoundStmt *CompStmt =
7843 Expr *E = new (Context)
7845 /*FIXME TemplateDepth=*/0);
7847}
7848
7850 assert(ExprEvalContexts.back().ExprContext ==
7852 "not in a decltype expression");
7853
7855 if (Result.isInvalid())
7856 return ExprError();
7857 E = Result.get();
7858
7859 // C++11 [expr.call]p11:
7860 // If a function call is a prvalue of object type,
7861 // -- if the function call is either
7862 // -- the operand of a decltype-specifier, or
7863 // -- the right operand of a comma operator that is the operand of a
7864 // decltype-specifier,
7865 // a temporary object is not introduced for the prvalue.
7866
7867 // Recursively rebuild ParenExprs and comma expressions to strip out the
7868 // outermost CXXBindTemporaryExpr, if any.
7869 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7870 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7871 if (SubExpr.isInvalid())
7872 return ExprError();
7873 if (SubExpr.get() == PE->getSubExpr())
7874 return E;
7875 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7876 }
7877 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7878 if (BO->getOpcode() == BO_Comma) {
7879 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7880 if (RHS.isInvalid())
7881 return ExprError();
7882 if (RHS.get() == BO->getRHS())
7883 return E;
7884 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7885 BO->getType(), BO->getValueKind(),
7886 BO->getObjectKind(), BO->getOperatorLoc(),
7887 BO->getFPFeatures());
7888 }
7889 }
7890
7891 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7892 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7893 : nullptr;
7894 if (TopCall)
7895 E = TopCall;
7896 else
7897 TopBind = nullptr;
7898
7899 // Disable the special decltype handling now.
7900 ExprEvalContexts.back().ExprContext =
7902
7904 if (Result.isInvalid())
7905 return ExprError();
7906 E = Result.get();
7907
7908 // In MS mode, don't perform any extra checking of call return types within a
7909 // decltype expression.
7910 if (getLangOpts().MSVCCompat)
7911 return E;
7912
7913 // Perform the semantic checks we delayed until this point.
7914 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7915 I != N; ++I) {
7916 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7917 if (Call == TopCall)
7918 continue;
7919
7920 if (CheckCallReturnType(Call->getCallReturnType(Context),
7921 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7922 return ExprError();
7923 }
7924
7925 // Now all relevant types are complete, check the destructors are accessible
7926 // and non-deleted, and annotate them on the temporaries.
7927 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7928 I != N; ++I) {
7930 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7931 if (Bind == TopBind)
7932 continue;
7933
7934 CXXTemporary *Temp = Bind->getTemporary();
7935
7936 CXXRecordDecl *RD =
7937 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7940
7941 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7942 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7943 PDiag(diag::err_access_dtor_temp)
7944 << Bind->getType());
7945 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7946 return ExprError();
7947
7948 // We need a cleanup, but we don't need to remember the temporary.
7950 }
7951
7952 // Possibly strip off the top CXXBindTemporaryExpr.
7953 return E;
7954}
7955
7956/// Note a set of 'operator->' functions that were used for a member access.
7958 ArrayRef<FunctionDecl *> OperatorArrows) {
7959 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7960 // FIXME: Make this configurable?
7961 unsigned Limit = 9;
7962 if (OperatorArrows.size() > Limit) {
7963 // Produce Limit-1 normal notes and one 'skipping' note.
7964 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7965 SkipCount = OperatorArrows.size() - (Limit - 1);
7966 }
7967
7968 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7969 if (I == SkipStart) {
7970 S.Diag(OperatorArrows[I]->getLocation(),
7971 diag::note_operator_arrows_suppressed)
7972 << SkipCount;
7973 I += SkipCount;
7974 } else {
7975 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7976 << OperatorArrows[I]->getCallResultType();
7977 ++I;
7978 }
7979 }
7980}
7981
7983 SourceLocation OpLoc,
7984 tok::TokenKind OpKind,
7985 ParsedType &ObjectType,
7986 bool &MayBePseudoDestructor) {
7987 // Since this might be a postfix expression, get rid of ParenListExprs.
7989 if (Result.isInvalid()) return ExprError();
7990 Base = Result.get();
7991
7993 if (Result.isInvalid()) return ExprError();
7994 Base = Result.get();
7995
7996 QualType BaseType = Base->getType();
7997 MayBePseudoDestructor = false;
7998 if (BaseType->isDependentType()) {
7999 // If we have a pointer to a dependent type and are using the -> operator,
8000 // the object type is the type that the pointer points to. We might still
8001 // have enough information about that type to do something useful.
8002 if (OpKind == tok::arrow)
8003 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
8004 BaseType = Ptr->getPointeeType();
8005
8006 ObjectType = ParsedType::make(BaseType);
8007 MayBePseudoDestructor = true;
8008 return Base;
8009 }
8010
8011 // C++ [over.match.oper]p8:
8012 // [...] When operator->returns, the operator-> is applied to the value
8013 // returned, with the original second operand.
8014 if (OpKind == tok::arrow) {
8015 QualType StartingType = BaseType;
8016 bool NoArrowOperatorFound = false;
8017 bool FirstIteration = true;
8018 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
8019 // The set of types we've considered so far.
8021 SmallVector<FunctionDecl*, 8> OperatorArrows;
8022 CTypes.insert(Context.getCanonicalType(BaseType));
8023
8024 while (BaseType->isRecordType()) {
8025 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
8026 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
8027 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
8028 noteOperatorArrows(*this, OperatorArrows);
8029 Diag(OpLoc, diag::note_operator_arrow_depth)
8030 << getLangOpts().ArrowDepth;
8031 return ExprError();
8032 }
8033
8035 S, Base, OpLoc,
8036 // When in a template specialization and on the first loop iteration,
8037 // potentially give the default diagnostic (with the fixit in a
8038 // separate note) instead of having the error reported back to here
8039 // and giving a diagnostic with a fixit attached to the error itself.
8040 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
8041 ? nullptr
8042 : &NoArrowOperatorFound);
8043 if (Result.isInvalid()) {
8044 if (NoArrowOperatorFound) {
8045 if (FirstIteration) {
8046 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8047 << BaseType << 1 << Base->getSourceRange()
8048 << FixItHint::CreateReplacement(OpLoc, ".");
8049 OpKind = tok::period;
8050 break;
8051 }
8052 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
8053 << BaseType << Base->getSourceRange();
8054 CallExpr *CE = dyn_cast<CallExpr>(Base);
8055 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
8056 Diag(CD->getBeginLoc(),
8057 diag::note_member_reference_arrow_from_operator_arrow);
8058 }
8059 }
8060 return ExprError();
8061 }
8062 Base = Result.get();
8063 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
8064 OperatorArrows.push_back(OpCall->getDirectCallee());
8065 BaseType = Base->getType();
8066 CanQualType CBaseType = Context.getCanonicalType(BaseType);
8067 if (!CTypes.insert(CBaseType).second) {
8068 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
8069 noteOperatorArrows(*this, OperatorArrows);
8070 return ExprError();
8071 }
8072 FirstIteration = false;
8073 }
8074
8075 if (OpKind == tok::arrow) {
8076 if (BaseType->isPointerType())
8077 BaseType = BaseType->getPointeeType();
8078 else if (auto *AT = Context.getAsArrayType(BaseType))
8079 BaseType = AT->getElementType();
8080 }
8081 }
8082
8083 // Objective-C properties allow "." access on Objective-C pointer types,
8084 // so adjust the base type to the object type itself.
8085 if (BaseType->isObjCObjectPointerType())
8086 BaseType = BaseType->getPointeeType();
8087
8088 // C++ [basic.lookup.classref]p2:
8089 // [...] If the type of the object expression is of pointer to scalar
8090 // type, the unqualified-id is looked up in the context of the complete
8091 // postfix-expression.
8092 //
8093 // This also indicates that we could be parsing a pseudo-destructor-name.
8094 // Note that Objective-C class and object types can be pseudo-destructor
8095 // expressions or normal member (ivar or property) access expressions, and
8096 // it's legal for the type to be incomplete if this is a pseudo-destructor
8097 // call. We'll do more incomplete-type checks later in the lookup process,
8098 // so just skip this check for ObjC types.
8099 if (!BaseType->isRecordType()) {
8100 ObjectType = ParsedType::make(BaseType);
8101 MayBePseudoDestructor = true;
8102 return Base;
8103 }
8104
8105 // The object type must be complete (or dependent), or
8106 // C++11 [expr.prim.general]p3:
8107 // Unlike the object expression in other contexts, *this is not required to
8108 // be of complete type for purposes of class member access (5.2.5) outside
8109 // the member function body.
8110 if (!BaseType->isDependentType() &&
8112 RequireCompleteType(OpLoc, BaseType,
8113 diag::err_incomplete_member_access)) {
8114 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
8115 }
8116
8117 // C++ [basic.lookup.classref]p2:
8118 // If the id-expression in a class member access (5.2.5) is an
8119 // unqualified-id, and the type of the object expression is of a class
8120 // type C (or of pointer to a class type C), the unqualified-id is looked
8121 // up in the scope of class C. [...]
8122 ObjectType = ParsedType::make(BaseType);
8123 return Base;
8124}
8125
8126static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
8127 tok::TokenKind &OpKind, SourceLocation OpLoc) {
8128 if (Base->hasPlaceholderType()) {
8130 if (result.isInvalid()) return true;
8131 Base = result.get();
8132 }
8133 ObjectType = Base->getType();
8134
8135 // C++ [expr.pseudo]p2:
8136 // The left-hand side of the dot operator shall be of scalar type. The
8137 // left-hand side of the arrow operator shall be of pointer to scalar type.
8138 // This scalar type is the object type.
8139 // Note that this is rather different from the normal handling for the
8140 // arrow operator.
8141 if (OpKind == tok::arrow) {
8142 // The operator requires a prvalue, so perform lvalue conversions.
8143 // Only do this if we might plausibly end with a pointer, as otherwise
8144 // this was likely to be intended to be a '.'.
8145 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8146 ObjectType->isFunctionType()) {
8148 if (BaseResult.isInvalid())
8149 return true;
8150 Base = BaseResult.get();
8151 ObjectType = Base->getType();
8152 }
8153
8154 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8155 ObjectType = Ptr->getPointeeType();
8156 } else if (!Base->isTypeDependent()) {
8157 // The user wrote "p->" when they probably meant "p."; fix it.
8158 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8159 << ObjectType << true
8160 << FixItHint::CreateReplacement(OpLoc, ".");
8161 if (S.isSFINAEContext())
8162 return true;
8163
8164 OpKind = tok::period;
8165 }
8166 }
8167
8168 return false;
8169}
8170
8171/// Check if it's ok to try and recover dot pseudo destructor calls on
8172/// pointer objects.
8173static bool
8175 QualType DestructedType) {
8176 // If this is a record type, check if its destructor is callable.
8177 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8178 if (RD->hasDefinition())
8180 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8181 return false;
8182 }
8183
8184 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8185 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8186 DestructedType->isVectorType();
8187}
8188
8190 SourceLocation OpLoc,
8191 tok::TokenKind OpKind,
8192 const CXXScopeSpec &SS,
8193 TypeSourceInfo *ScopeTypeInfo,
8194 SourceLocation CCLoc,
8195 SourceLocation TildeLoc,
8196 PseudoDestructorTypeStorage Destructed) {
8197 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8198
8199 QualType ObjectType;
8200 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8201 return ExprError();
8202
8203 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8204 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {
8205 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8206 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8207 else {
8208 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8209 << ObjectType << Base->getSourceRange();
8210 return ExprError();
8211 }
8212 }
8213
8214 // C++ [expr.pseudo]p2:
8215 // [...] The cv-unqualified versions of the object type and of the type
8216 // designated by the pseudo-destructor-name shall be the same type.
8217 if (DestructedTypeInfo) {
8218 QualType DestructedType = DestructedTypeInfo->getType();
8219 SourceLocation DestructedTypeStart =
8220 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8221 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8222 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8223 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8224 // Foo *foo;
8225 // foo.~Foo();
8226 if (OpKind == tok::period && ObjectType->isPointerType() &&
8227 Context.hasSameUnqualifiedType(DestructedType,
8228 ObjectType->getPointeeType())) {
8229 auto Diagnostic =
8230 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8231 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8232
8233 // Issue a fixit only when the destructor is valid.
8235 *this, DestructedType))
8237
8238 // Recover by setting the object type to the destructed type and the
8239 // operator to '->'.
8240 ObjectType = DestructedType;
8241 OpKind = tok::arrow;
8242 } else {
8243 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8244 << ObjectType << DestructedType << Base->getSourceRange()
8245 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8246
8247 // Recover by setting the destructed type to the object type.
8248 DestructedType = ObjectType;
8249 DestructedTypeInfo =
8250 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8251 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8252 }
8253 } else if (DestructedType.getObjCLifetime() !=
8254 ObjectType.getObjCLifetime()) {
8255
8256 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8257 // Okay: just pretend that the user provided the correctly-qualified
8258 // type.
8259 } else {
8260 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8261 << ObjectType << DestructedType << Base->getSourceRange()
8262 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8263 }
8264
8265 // Recover by setting the destructed type to the object type.
8266 DestructedType = ObjectType;
8267 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8268 DestructedTypeStart);
8269 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8270 }
8271 }
8272 }
8273
8274 // C++ [expr.pseudo]p2:
8275 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8276 // form
8277 //
8278 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8279 //
8280 // shall designate the same scalar type.
8281 if (ScopeTypeInfo) {
8282 QualType ScopeType = ScopeTypeInfo->getType();
8283 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8284 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8285
8286 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8287 diag::err_pseudo_dtor_type_mismatch)
8288 << ObjectType << ScopeType << Base->getSourceRange()
8289 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8290
8291 ScopeType = QualType();
8292 ScopeTypeInfo = nullptr;
8293 }
8294 }
8295
8296 Expr *Result
8298 OpKind == tok::arrow, OpLoc,
8300 ScopeTypeInfo,
8301 CCLoc,
8302 TildeLoc,
8303 Destructed);
8304
8305 return Result;
8306}
8307
8309 SourceLocation OpLoc,
8310 tok::TokenKind OpKind,
8311 CXXScopeSpec &SS,
8312 UnqualifiedId &FirstTypeName,
8313 SourceLocation CCLoc,
8314 SourceLocation TildeLoc,
8315 UnqualifiedId &SecondTypeName) {
8316 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8317 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8318 "Invalid first type name in pseudo-destructor");
8319 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8320 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8321 "Invalid second type name in pseudo-destructor");
8322
8323 QualType ObjectType;
8324 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8325 return ExprError();
8326
8327 // Compute the object type that we should use for name lookup purposes. Only
8328 // record types and dependent types matter.
8329 ParsedType ObjectTypePtrForLookup;
8330 if (!SS.isSet()) {
8331 if (ObjectType->isRecordType())
8332 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8333 else if (ObjectType->isDependentType())
8334 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8335 }
8336
8337 // Convert the name of the type being destructed (following the ~) into a
8338 // type (with source-location information).
8339 QualType DestructedType;
8340 TypeSourceInfo *DestructedTypeInfo = nullptr;
8341 PseudoDestructorTypeStorage Destructed;
8342 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8343 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8344 SecondTypeName.StartLocation,
8345 S, &SS, true, false, ObjectTypePtrForLookup,
8346 /*IsCtorOrDtorName*/true);
8347 if (!T &&
8348 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8349 (!SS.isSet() && ObjectType->isDependentType()))) {
8350 // The name of the type being destroyed is a dependent name, and we
8351 // couldn't find anything useful in scope. Just store the identifier and
8352 // it's location, and we'll perform (qualified) name lookup again at
8353 // template instantiation time.
8354 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8355 SecondTypeName.StartLocation);
8356 } else if (!T) {
8357 Diag(SecondTypeName.StartLocation,
8358 diag::err_pseudo_dtor_destructor_non_type)
8359 << SecondTypeName.Identifier << ObjectType;
8360 if (isSFINAEContext())
8361 return ExprError();
8362
8363 // Recover by assuming we had the right type all along.
8364 DestructedType = ObjectType;
8365 } else
8366 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8367 } else {
8368 // Resolve the template-id to a type.
8369 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8370 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8371 TemplateId->NumArgs);
8373 SS,
8374 TemplateId->TemplateKWLoc,
8375 TemplateId->Template,
8376 TemplateId->Name,
8377 TemplateId->TemplateNameLoc,
8378 TemplateId->LAngleLoc,
8379 TemplateArgsPtr,
8380 TemplateId->RAngleLoc,
8381 /*IsCtorOrDtorName*/true);
8382 if (T.isInvalid() || !T.get()) {
8383 // Recover by assuming we had the right type all along.
8384 DestructedType = ObjectType;
8385 } else
8386 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8387 }
8388
8389 // If we've performed some kind of recovery, (re-)build the type source
8390 // information.
8391 if (!DestructedType.isNull()) {
8392 if (!DestructedTypeInfo)
8393 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8394 SecondTypeName.StartLocation);
8395 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8396 }
8397
8398 // Convert the name of the scope type (the type prior to '::') into a type.
8399 TypeSourceInfo *ScopeTypeInfo = nullptr;
8400 QualType ScopeType;
8401 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8402 FirstTypeName.Identifier) {
8403 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8404 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8405 FirstTypeName.StartLocation,
8406 S, &SS, true, false, ObjectTypePtrForLookup,
8407 /*IsCtorOrDtorName*/true);
8408 if (!T) {
8409 Diag(FirstTypeName.StartLocation,
8410 diag::err_pseudo_dtor_destructor_non_type)
8411 << FirstTypeName.Identifier << ObjectType;
8412
8413 if (isSFINAEContext())
8414 return ExprError();
8415
8416 // Just drop this type. It's unnecessary anyway.
8417 ScopeType = QualType();
8418 } else
8419 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8420 } else {
8421 // Resolve the template-id to a type.
8422 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8423 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8424 TemplateId->NumArgs);
8426 SS,
8427 TemplateId->TemplateKWLoc,
8428 TemplateId->Template,
8429 TemplateId->Name,
8430 TemplateId->TemplateNameLoc,
8431 TemplateId->LAngleLoc,
8432 TemplateArgsPtr,
8433 TemplateId->RAngleLoc,
8434 /*IsCtorOrDtorName*/true);
8435 if (T.isInvalid() || !T.get()) {
8436 // Recover by dropping this type.
8437 ScopeType = QualType();
8438 } else
8439 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8440 }
8441 }
8442
8443 if (!ScopeType.isNull() && !ScopeTypeInfo)
8444 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8445 FirstTypeName.StartLocation);
8446
8447
8448 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8449 ScopeTypeInfo, CCLoc, TildeLoc,
8450 Destructed);
8451}
8452
8454 SourceLocation OpLoc,
8455 tok::TokenKind OpKind,
8456 SourceLocation TildeLoc,
8457 const DeclSpec& DS) {
8458 QualType ObjectType;
8459 QualType T;
8460 TypeLocBuilder TLB;
8461 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) ||
8463 return ExprError();
8464
8465 switch (DS.getTypeSpecType()) {
8467 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8468 return true;
8469 }
8471 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8472 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8473 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8474 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8475 break;
8476 }
8479 DS.getBeginLoc(), DS.getEllipsisLoc());
8481 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8482 DS.getBeginLoc());
8484 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8485 break;
8486 }
8487 default:
8488 llvm_unreachable("Unsupported type in pseudo destructor");
8489 }
8490 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8491 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8492
8493 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8494 nullptr, SourceLocation(), TildeLoc,
8495 Destructed);
8496}
8497
8499 SourceLocation RParen) {
8500 // If the operand is an unresolved lookup expression, the expression is ill-
8501 // formed per [over.over]p1, because overloaded function names cannot be used
8502 // without arguments except in explicit contexts.
8503 ExprResult R = CheckPlaceholderExpr(Operand);
8504 if (R.isInvalid())
8505 return R;
8506
8508 if (R.isInvalid())
8509 return ExprError();
8510
8511 Operand = R.get();
8512
8513 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8514 Operand->HasSideEffects(Context, false)) {
8515 // The expression operand for noexcept is in an unevaluated expression
8516 // context, so side effects could result in unintended consequences.
8517 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8518 }
8519
8520 CanThrowResult CanThrow = canThrow(Operand);
8521 return new (Context)
8522 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8523}
8524
8526 Expr *Operand, SourceLocation RParen) {
8527 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8528}
8529
8531 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8532 DeclRefExpr *LHS = nullptr;
8533 bool IsCompoundAssign = false;
8534 bool isIncrementDecrementUnaryOp = false;
8535 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8536 if (BO->getLHS()->getType()->isDependentType() ||
8537 BO->getRHS()->getType()->isDependentType()) {
8538 if (BO->getOpcode() != BO_Assign)
8539 return;
8540 } else if (!BO->isAssignmentOp())
8541 return;
8542 else
8543 IsCompoundAssign = BO->isCompoundAssignmentOp();
8544 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8545 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8546 if (COCE->getOperator() != OO_Equal)
8547 return;
8548 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8549 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8550 if (!UO->isIncrementDecrementOp())
8551 return;
8552 isIncrementDecrementUnaryOp = true;
8553 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8554 }
8555 if (!LHS)
8556 return;
8557 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8558 if (!VD)
8559 return;
8560 // Don't decrement RefsMinusAssignments if volatile variable with compound
8561 // assignment (+=, ...) or increment/decrement unary operator to avoid
8562 // potential unused-but-set-variable warning.
8563 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8565 return;
8566 auto iter = RefsMinusAssignments.find(VD);
8567 if (iter == RefsMinusAssignments.end())
8568 return;
8569 iter->getSecond()--;
8570}
8571
8572/// Perform the conversions required for an expression used in a
8573/// context that ignores the result.
8576
8577 if (E->hasPlaceholderType()) {
8579 if (result.isInvalid()) return E;
8580 E = result.get();
8581 }
8582
8583 if (getLangOpts().CPlusPlus) {
8584 // The C++11 standard defines the notion of a discarded-value expression;
8585 // normally, we don't need to do anything to handle it, but if it is a
8586 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8587 // conversion.
8590 if (Res.isInvalid())
8591 return E;
8592 E = Res.get();
8593 } else {
8594 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8595 // it occurs as a discarded-value expression.
8597 }
8598
8599 // C++1z:
8600 // If the expression is a prvalue after this optional conversion, the
8601 // temporary materialization conversion is applied.
8602 //
8603 // We do not materialize temporaries by default in order to avoid creating
8604 // unnecessary temporary objects. If we skip this step, IR generation is
8605 // able to synthesize the storage for itself in the aggregate case, and
8606 // adding the extra node to the AST is just clutter.
8608 E->isPRValue() && !E->getType()->isVoidType()) {
8610 if (Res.isInvalid())
8611 return E;
8612 E = Res.get();
8613 }
8614 return E;
8615 }
8616
8617 // C99 6.3.2.1:
8618 // [Except in specific positions,] an lvalue that does not have
8619 // array type is converted to the value stored in the
8620 // designated object (and is no longer an lvalue).
8621 if (E->isPRValue()) {
8622 // In C, function designators (i.e. expressions of function type)
8623 // are r-values, but we still want to do function-to-pointer decay
8624 // on them. This is both technically correct and convenient for
8625 // some clients.
8628
8629 return E;
8630 }
8631
8632 // GCC seems to also exclude expressions of incomplete enum type.
8633 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8634 if (!T->getDecl()->isComplete()) {
8635 // FIXME: stupid workaround for a codegen bug!
8636 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8637 return E;
8638 }
8639 }
8640
8642 if (Res.isInvalid())
8643 return E;
8644 E = Res.get();
8645
8646 if (!E->getType()->isVoidType())
8648 diag::err_incomplete_type);
8649 return E;
8650}
8651
8653 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8654 // it occurs as an unevaluated operand.
8656
8657 return E;
8658}
8659
8660// If we can unambiguously determine whether Var can never be used
8661// in a constant expression, return true.
8662// - if the variable and its initializer are non-dependent, then
8663// we can unambiguously check if the variable is a constant expression.
8664// - if the initializer is not value dependent - we can determine whether
8665// it can be used to initialize a constant expression. If Init can not
8666// be used to initialize a constant expression we conclude that Var can
8667// never be a constant expression.
8668// - FXIME: if the initializer is dependent, we can still do some analysis and
8669// identify certain cases unambiguously as non-const by using a Visitor:
8670// - such as those that involve odr-use of a ParmVarDecl, involve a new
8671// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8674 if (isa<ParmVarDecl>(Var)) return true;
8675 const VarDecl *DefVD = nullptr;
8676
8677 // If there is no initializer - this can not be a constant expression.
8678 const Expr *Init = Var->getAnyInitializer(DefVD);
8679 if (!Init)
8680 return true;
8681 assert(DefVD);
8682 if (DefVD->isWeak())
8683 return false;
8684
8685 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8686 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8687 // of value-dependent expressions, and use it here to determine whether the
8688 // initializer is a potential constant expression.
8689 return false;
8690 }
8691
8693}
8694
8695/// Check if the current lambda has any potential captures
8696/// that must be captured by any of its enclosing lambdas that are ready to
8697/// capture. If there is a lambda that can capture a nested
8698/// potential-capture, go ahead and do so. Also, check to see if any
8699/// variables are uncaptureable or do not involve an odr-use so do not
8700/// need to be captured.
8701
8703 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8704
8705 assert(!S.isUnevaluatedContext());
8706 assert(S.CurContext->isDependentContext());
8707#ifndef NDEBUG
8708 DeclContext *DC = S.CurContext;
8709 while (isa_and_nonnull<CapturedDecl>(DC))
8710 DC = DC->getParent();
8711 assert(
8712 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&
8713 "The current call operator must be synchronized with Sema's CurContext");
8714#endif // NDEBUG
8715
8716 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8717
8718 // All the potentially captureable variables in the current nested
8719 // lambda (within a generic outer lambda), must be captured by an
8720 // outer lambda that is enclosed within a non-dependent context.
8721 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8722 // If the variable is clearly identified as non-odr-used and the full
8723 // expression is not instantiation dependent, only then do we not
8724 // need to check enclosing lambda's for speculative captures.
8725 // For e.g.:
8726 // Even though 'x' is not odr-used, it should be captured.
8727 // int test() {
8728 // const int x = 10;
8729 // auto L = [=](auto a) {
8730 // (void) +x + a;
8731 // };
8732 // }
8733 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8734 !IsFullExprInstantiationDependent)
8735 return;
8736
8737 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8738 if (!UnderlyingVar)
8739 return;
8740
8741 // If we have a capture-capable lambda for the variable, go ahead and
8742 // capture the variable in that lambda (and all its enclosing lambdas).
8743 if (const std::optional<unsigned> Index =
8745 S.FunctionScopes, Var, S))
8746 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8747 const bool IsVarNeverAConstantExpression =
8749 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8750 // This full expression is not instantiation dependent or the variable
8751 // can not be used in a constant expression - which means
8752 // this variable must be odr-used here, so diagnose a
8753 // capture violation early, if the variable is un-captureable.
8754 // This is purely for diagnosing errors early. Otherwise, this
8755 // error would get diagnosed when the lambda becomes capture ready.
8756 QualType CaptureType, DeclRefType;
8757 SourceLocation ExprLoc = VarExpr->getExprLoc();
8758 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8759 /*EllipsisLoc*/ SourceLocation(),
8760 /*BuildAndDiagnose*/false, CaptureType,
8761 DeclRefType, nullptr)) {
8762 // We will never be able to capture this variable, and we need
8763 // to be able to in any and all instantiations, so diagnose it.
8764 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8765 /*EllipsisLoc*/ SourceLocation(),
8766 /*BuildAndDiagnose*/true, CaptureType,
8767 DeclRefType, nullptr);
8768 }
8769 }
8770 });
8771
8772 // Check if 'this' needs to be captured.
8773 if (CurrentLSI->hasPotentialThisCapture()) {
8774 // If we have a capture-capable lambda for 'this', go ahead and capture
8775 // 'this' in that lambda (and all its enclosing lambdas).
8776 if (const std::optional<unsigned> Index =
8778 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8779 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8781 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8782 &FunctionScopeIndexOfCapturableLambda);
8783 }
8784 }
8785
8786 // Reset all the potential captures at the end of each full-expression.
8787 CurrentLSI->clearPotentialCaptures();
8788}
8789
8792 const TypoCorrection &TC) {
8793 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8794 Consumer.getLookupResult().getLookupKind());
8795 const CXXScopeSpec *SS = Consumer.getSS();
8796 CXXScopeSpec NewSS;
8797
8798 // Use an approprate CXXScopeSpec for building the expr.
8799 if (auto *NNS = TC.getCorrectionSpecifier())
8801 else if (SS && !TC.WillReplaceSpecifier())
8802 NewSS = *SS;
8803
8804 if (auto *ND = TC.getFoundDecl()) {
8805 R.setLookupName(ND->getDeclName());
8806 R.addDecl(ND);
8807 if (ND->isCXXClassMember()) {
8808 // Figure out the correct naming class to add to the LookupResult.
8809 CXXRecordDecl *Record = nullptr;
8810 if (auto *NNS = TC.getCorrectionSpecifier())
8811 Record = NNS->getAsType()->getAsCXXRecordDecl();
8812 if (!Record)
8813 Record =
8814 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8815 if (Record)
8817
8818 // Detect and handle the case where the decl might be an implicit
8819 // member.
8821 NewSS, R, Consumer.isAddressOfOperand()))
8823 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8824 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8825 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8826 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8827 Ivar->getIdentifier());
8828 }
8829 }
8830
8831 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8832 /*AcceptInvalidDecl*/ true);
8833}
8834
8835namespace {
8836class FindTypoExprs : public DynamicRecursiveASTVisitor {
8838
8839public:
8840 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8841 : TypoExprs(TypoExprs) {}
8842 bool VisitTypoExpr(TypoExpr *TE) override {
8843 TypoExprs.insert(TE);
8844 return true;
8845 }
8846};
8847
8848class TransformTypos : public TreeTransform<TransformTypos> {
8849 typedef TreeTransform<TransformTypos> BaseTransform;
8850
8851 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8852 // process of being initialized.
8853 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8854 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8855 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8856 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8857
8858 /// Emit diagnostics for all of the TypoExprs encountered.
8859 ///
8860 /// If the TypoExprs were successfully corrected, then the diagnostics should
8861 /// suggest the corrections. Otherwise the diagnostics will not suggest
8862 /// anything (having been passed an empty TypoCorrection).
8863 ///
8864 /// If we've failed to correct due to ambiguous corrections, we need to
8865 /// be sure to pass empty corrections and replacements. Otherwise it's
8866 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8867 /// and we don't want to report those diagnostics.
8868 void EmitAllDiagnostics(bool IsAmbiguous) {
8869 for (TypoExpr *TE : TypoExprs) {
8870 auto &State = SemaRef.getTypoExprState(TE);
8871 if (State.DiagHandler) {
8872 TypoCorrection TC = IsAmbiguous
8873 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8874 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8875
8876 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8877 // TypoCorrection, replacing the existing decls. This ensures the right
8878 // NamedDecl is used in diagnostics e.g. in the case where overload
8879 // resolution was used to select one from several possible decls that
8880 // had been stored in the TypoCorrection.
8881 if (auto *ND = getDeclFromExpr(
8882 Replacement.isInvalid() ? nullptr : Replacement.get()))
8883 TC.setCorrectionDecl(ND);
8884
8885 State.DiagHandler(TC);
8886 }
8887 SemaRef.clearDelayedTypo(TE);
8888 }
8889 }
8890
8891 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8892 /// We allow advancement of the correction stream by removing it from the
8893 /// TransformCache which allows `TransformTypoExpr` to advance during the
8894 /// next transformation attempt.
8895 ///
8896 /// Any substitution attempts for the previous TypoExprs (which must have been
8897 /// finished) will need to be retried since it's possible that they will now
8898 /// be invalid given the latest advancement.
8899 ///
8900 /// We need to be sure that we're making progress - it's possible that the
8901 /// tree is so malformed that the transform never makes it to the
8902 /// `TransformTypoExpr`.
8903 ///
8904 /// Returns true if there are any untried correction combinations.
8905 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8906 for (auto *TE : TypoExprs) {
8907 auto &State = SemaRef.getTypoExprState(TE);
8908 TransformCache.erase(TE);
8909 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8910 return false;
8911 if (!State.Consumer->finished())
8912 return true;
8913 State.Consumer->resetCorrectionStream();
8914 }
8915 return false;
8916 }
8917
8919 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8920 E = OverloadResolution[OE];
8921
8922 if (!E)
8923 return nullptr;
8924 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8925 return DRE->getFoundDecl();
8926 if (auto *ME = dyn_cast<MemberExpr>(E))
8927 return ME->getFoundDecl();
8928 // FIXME: Add any other expr types that could be seen by the delayed typo
8929 // correction TreeTransform for which the corresponding TypoCorrection could
8930 // contain multiple decls.
8931 return nullptr;
8932 }
8933
8934 ExprResult TryTransform(Expr *E) {
8935 Sema::SFINAETrap Trap(SemaRef);
8936 ExprResult Res = TransformExpr(E);
8937 if (Trap.hasErrorOccurred() || Res.isInvalid())
8938 return ExprError();
8939
8940 return ExprFilter(Res.get());
8941 }
8942
8943 // Since correcting typos may intoduce new TypoExprs, this function
8944 // checks for new TypoExprs and recurses if it finds any. Note that it will
8945 // only succeed if it is able to correct all typos in the given expression.
8946 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8947 if (Res.isInvalid()) {
8948 return Res;
8949 }
8950 // Check to see if any new TypoExprs were created. If so, we need to recurse
8951 // to check their validity.
8952 Expr *FixedExpr = Res.get();
8953
8954 auto SavedTypoExprs = std::move(TypoExprs);
8955 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8956 TypoExprs.clear();
8957 AmbiguousTypoExprs.clear();
8958
8959 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8960 if (!TypoExprs.empty()) {
8961 // Recurse to handle newly created TypoExprs. If we're not able to
8962 // handle them, discard these TypoExprs.
8963 ExprResult RecurResult =
8964 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8965 if (RecurResult.isInvalid()) {
8966 Res = ExprError();
8967 // Recursive corrections didn't work, wipe them away and don't add
8968 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8969 // since we don't want to clear them twice. Note: it's possible the
8970 // TypoExprs were created recursively and thus won't be in our
8971 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8972 auto &SemaTypoExprs = SemaRef.TypoExprs;
8973 for (auto *TE : TypoExprs) {
8974 TransformCache.erase(TE);
8975 SemaRef.clearDelayedTypo(TE);
8976
8977 auto SI = find(SemaTypoExprs, TE);
8978 if (SI != SemaTypoExprs.end()) {
8979 SemaTypoExprs.erase(SI);
8980 }
8981 }
8982 } else {
8983 // TypoExpr is valid: add newly created TypoExprs since we were
8984 // able to correct them.
8985 Res = RecurResult;
8986 SavedTypoExprs.set_union(TypoExprs);
8987 }
8988 }
8989
8990 TypoExprs = std::move(SavedTypoExprs);
8991 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8992
8993 return Res;
8994 }
8995
8996 // Try to transform the given expression, looping through the correction
8997 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8998 //
8999 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
9000 // true and this method immediately will return an `ExprError`.
9001 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
9002 ExprResult Res;
9003 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
9004 SemaRef.TypoExprs.clear();
9005
9006 while (true) {
9007 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
9008
9009 // Recursion encountered an ambiguous correction. This means that our
9010 // correction itself is ambiguous, so stop now.
9011 if (IsAmbiguous)
9012 break;
9013
9014 // If the transform is still valid after checking for any new typos,
9015 // it's good to go.
9016 if (!Res.isInvalid())
9017 break;
9018
9019 // The transform was invalid, see if we have any TypoExprs with untried
9020 // correction candidates.
9021 if (!CheckAndAdvanceTypoExprCorrectionStreams())
9022 break;
9023 }
9024
9025 // If we found a valid result, double check to make sure it's not ambiguous.
9026 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
9027 auto SavedTransformCache =
9028 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
9029
9030 // Ensure none of the TypoExprs have multiple typo correction candidates
9031 // with the same edit length that pass all the checks and filters.
9032 while (!AmbiguousTypoExprs.empty()) {
9033 auto TE = AmbiguousTypoExprs.back();
9034
9035 // TryTransform itself can create new Typos, adding them to the TypoExpr map
9036 // and invalidating our TypoExprState, so always fetch it instead of storing.
9037 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
9038
9039 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
9040 TypoCorrection Next;
9041 do {
9042 // Fetch the next correction by erasing the typo from the cache and calling
9043 // `TryTransform` which will iterate through corrections in
9044 // `TransformTypoExpr`.
9045 TransformCache.erase(TE);
9046 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
9047
9048 if (!AmbigRes.isInvalid() || IsAmbiguous) {
9049 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
9050 SavedTransformCache.erase(TE);
9051 Res = ExprError();
9052 IsAmbiguous = true;
9053 break;
9054 }
9055 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
9056 Next.getEditDistance(false) == TC.getEditDistance(false));
9057
9058 if (IsAmbiguous)
9059 break;
9060
9061 AmbiguousTypoExprs.remove(TE);
9062 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
9063 TransformCache[TE] = SavedTransformCache[TE];
9064 }
9065 TransformCache = std::move(SavedTransformCache);
9066 }
9067
9068 // Wipe away any newly created TypoExprs that we don't know about. Since we
9069 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
9070 // possible if a `TypoExpr` is created during a transformation but then
9071 // fails before we can discover it.
9072 auto &SemaTypoExprs = SemaRef.TypoExprs;
9073 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
9074 auto TE = *Iterator;
9075 auto FI = find(TypoExprs, TE);
9076 if (FI != TypoExprs.end()) {
9077 Iterator++;
9078 continue;
9079 }
9080 SemaRef.clearDelayedTypo(TE);
9081 Iterator = SemaTypoExprs.erase(Iterator);
9082 }
9083 SemaRef.TypoExprs = std::move(SavedTypoExprs);
9084
9085 return Res;
9086 }
9087
9088public:
9089 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
9090 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
9091
9092 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
9093 MultiExprArg Args,
9094 SourceLocation RParenLoc,
9095 Expr *ExecConfig = nullptr) {
9096 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
9097 RParenLoc, ExecConfig);
9098 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
9099 if (Result.isUsable()) {
9100 Expr *ResultCall = Result.get();
9101 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
9102 ResultCall = BE->getSubExpr();
9103 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
9104 OverloadResolution[OE] = CE->getCallee();
9105 }
9106 }
9107 return Result;
9108 }
9109
9110 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
9111
9112 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
9113
9114 ExprResult Transform(Expr *E) {
9115 bool IsAmbiguous = false;
9116 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
9117
9118 if (!Res.isUsable())
9119 FindTypoExprs(TypoExprs).TraverseStmt(E);
9120
9121 EmitAllDiagnostics(IsAmbiguous);
9122
9123 return Res;
9124 }
9125
9126 ExprResult TransformTypoExpr(TypoExpr *E) {
9127 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
9128 // cached transformation result if there is one and the TypoExpr isn't the
9129 // first one that was encountered.
9130 auto &CacheEntry = TransformCache[E];
9131 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
9132 return CacheEntry;
9133 }
9134
9135 auto &State = SemaRef.getTypoExprState(E);
9136 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
9137
9138 // For the first TypoExpr and an uncached TypoExpr, find the next likely
9139 // typo correction and return it.
9140 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
9141 if (InitDecl && TC.getFoundDecl() == InitDecl)
9142 continue;
9143 // FIXME: If we would typo-correct to an invalid declaration, it's
9144 // probably best to just suppress all errors from this typo correction.
9145 ExprResult NE = State.RecoveryHandler ?
9146 State.RecoveryHandler(SemaRef, E, TC) :
9147 attemptRecovery(SemaRef, *State.Consumer, TC);
9148 if (!NE.isInvalid()) {
9149 // Check whether there may be a second viable correction with the same
9150 // edit distance; if so, remember this TypoExpr may have an ambiguous
9151 // correction so it can be more thoroughly vetted later.
9152 TypoCorrection Next;
9153 if ((Next = State.Consumer->peekNextCorrection()) &&
9154 Next.getEditDistance(false) == TC.getEditDistance(false)) {
9155 AmbiguousTypoExprs.insert(E);
9156 } else {
9157 AmbiguousTypoExprs.remove(E);
9158 }
9159 assert(!NE.isUnset() &&
9160 "Typo was transformed into a valid-but-null ExprResult");
9161 return CacheEntry = NE;
9162 }
9163 }
9164 return CacheEntry = ExprError();
9165 }
9166};
9167}
9168
9171 bool RecoverUncorrectedTypos,
9172 llvm::function_ref<ExprResult(Expr *)> Filter) {
9173 // If the current evaluation context indicates there are uncorrected typos
9174 // and the current expression isn't guaranteed to not have typos, try to
9175 // resolve any TypoExpr nodes that might be in the expression.
9176 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9177 (E->isTypeDependent() || E->isValueDependent() ||
9179 auto TyposResolved = DelayedTypos.size();
9180 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9181 TyposResolved -= DelayedTypos.size();
9182 if (Result.isInvalid() || Result.get() != E) {
9183 ExprEvalContexts.back().NumTypos -= TyposResolved;
9184 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9185 struct TyposReplace : TreeTransform<TyposReplace> {
9186 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9187 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9188 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9189 E->getEndLoc(), {});
9190 }
9191 } TT(*this);
9192 return TT.TransformExpr(E);
9193 }
9194 return Result;
9195 }
9196 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9197 }
9198 return E;
9199}
9200
9202 bool DiscardedValue, bool IsConstexpr,
9203 bool IsTemplateArgument) {
9204 ExprResult FullExpr = FE;
9205
9206 if (!FullExpr.get())
9207 return ExprError();
9208
9209 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9210 return ExprError();
9211
9212 if (DiscardedValue) {
9213 // Top-level expressions default to 'id' when we're in a debugger.
9214 if (getLangOpts().DebuggerCastResultToId &&
9215 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9217 if (FullExpr.isInvalid())
9218 return ExprError();
9219 }
9220
9222 if (FullExpr.isInvalid())
9223 return ExprError();
9224
9226 if (FullExpr.isInvalid())
9227 return ExprError();
9228
9229 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9230 }
9231
9232 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9233 /*RecoverUncorrectedTypos=*/true);
9234 if (FullExpr.isInvalid())
9235 return ExprError();
9236
9237 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9238
9239 // At the end of this full expression (which could be a deeply nested
9240 // lambda), if there is a potential capture within the nested lambda,
9241 // have the outer capture-able lambda try and capture it.
9242 // Consider the following code:
9243 // void f(int, int);
9244 // void f(const int&, double);
9245 // void foo() {
9246 // const int x = 10, y = 20;
9247 // auto L = [=](auto a) {
9248 // auto M = [=](auto b) {
9249 // f(x, b); <-- requires x to be captured by L and M
9250 // f(y, a); <-- requires y to be captured by L, but not all Ms
9251 // };
9252 // };
9253 // }
9254
9255 // FIXME: Also consider what happens for something like this that involves
9256 // the gnu-extension statement-expressions or even lambda-init-captures:
9257 // void f() {
9258 // const int n = 0;
9259 // auto L = [&](auto a) {
9260 // +n + ({ 0; a; });
9261 // };
9262 // }
9263 //
9264 // Here, we see +n, and then the full-expression 0; ends, so we don't
9265 // capture n (and instead remove it from our list of potential captures),
9266 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9267 // for us to see that we need to capture n after all.
9268
9269 LambdaScopeInfo *const CurrentLSI =
9270 getCurLambda(/*IgnoreCapturedRegions=*/true);
9271 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9272 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9273 // for an example of the code that might cause this asynchrony.
9274 // By ensuring we are in the context of a lambda's call operator
9275 // we can fix the bug (we only need to check whether we need to capture
9276 // if we are within a lambda's body); but per the comments in that
9277 // PR, a proper fix would entail :
9278 // "Alternative suggestion:
9279 // - Add to Sema an integer holding the smallest (outermost) scope
9280 // index that we are *lexically* within, and save/restore/set to
9281 // FunctionScopes.size() in InstantiatingTemplate's
9282 // constructor/destructor.
9283 // - Teach the handful of places that iterate over FunctionScopes to
9284 // stop at the outermost enclosing lexical scope."
9285 DeclContext *DC = CurContext;
9286 while (isa_and_nonnull<CapturedDecl>(DC))
9287 DC = DC->getParent();
9288 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9289 if (IsInLambdaDeclContext && CurrentLSI &&
9290 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9292 *this);
9294}
9295
9297 if (!FullStmt) return StmtError();
9298
9299 return MaybeCreateStmtWithCleanups(FullStmt);
9300}
9301
9304 CXXScopeSpec &SS,
9305 const DeclarationNameInfo &TargetNameInfo) {
9306 DeclarationName TargetName = TargetNameInfo.getName();
9307 if (!TargetName)
9308 return IER_DoesNotExist;
9309
9310 // If the name itself is dependent, then the result is dependent.
9311 if (TargetName.isDependentName())
9312 return IER_Dependent;
9313
9314 // Do the redeclaration lookup in the current scope.
9315 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9316 RedeclarationKind::NotForRedeclaration);
9317 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9319
9320 switch (R.getResultKind()) {
9325 return IER_Exists;
9326
9328 return IER_DoesNotExist;
9329
9331 return IER_Dependent;
9332 }
9333
9334 llvm_unreachable("Invalid LookupResult Kind!");
9335}
9336
9339 bool IsIfExists, CXXScopeSpec &SS,
9340 UnqualifiedId &Name) {
9341 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9342
9343 // Check for an unexpanded parameter pack.
9344 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9345 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9346 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9347 return IER_Error;
9348
9349 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9350}
9351
9353 return BuildExprRequirement(E, /*IsSimple=*/true,
9354 /*NoexceptLoc=*/SourceLocation(),
9355 /*ReturnTypeRequirement=*/{});
9356}
9357
9359 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9360 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9361 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9362 "Exactly one of TypeName and TemplateId must be specified.");
9363 TypeSourceInfo *TSI = nullptr;
9364 if (TypeName) {
9365 QualType T =
9367 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9368 &TSI, /*DeducedTSTContext=*/false);
9369 if (T.isNull())
9370 return nullptr;
9371 } else {
9372 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9373 TemplateId->NumArgs);
9374 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9375 TemplateId->TemplateKWLoc,
9376 TemplateId->Template, TemplateId->Name,
9377 TemplateId->TemplateNameLoc,
9378 TemplateId->LAngleLoc, ArgsPtr,
9379 TemplateId->RAngleLoc);
9380 if (T.isInvalid())
9381 return nullptr;
9382 if (GetTypeFromParser(T.get(), &TSI).isNull())
9383 return nullptr;
9384 }
9385 return BuildTypeRequirement(TSI);
9386}
9387
9390 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9391 /*ReturnTypeRequirement=*/{});
9392}
9393
9396 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9397 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9398 // C++2a [expr.prim.req.compound] p1.3.3
9399 // [..] the expression is deduced against an invented function template
9400 // F [...] F is a void function template with a single type template
9401 // parameter T declared with the constrained-parameter. Form a new
9402 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9403 // around the constrained-parameter. F has a single parameter whose
9404 // type-specifier is cv T followed by the abstract-declarator. [...]
9405 //
9406 // The cv part is done in the calling function - we get the concept with
9407 // arguments and the abstract declarator with the correct CV qualification and
9408 // have to synthesize T and the single parameter of F.
9409 auto &II = Context.Idents.get("expr-type");
9412 SourceLocation(), Depth,
9413 /*Index=*/0, &II,
9414 /*Typename=*/true,
9415 /*ParameterPack=*/false,
9416 /*HasTypeConstraint=*/true);
9417
9418 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9419 /*EllipsisLoc=*/SourceLocation(),
9420 /*AllowUnexpandedPack=*/true))
9421 // Just produce a requirement with no type requirements.
9422 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9423
9426 ArrayRef<NamedDecl *>(TParam),
9428 /*RequiresClause=*/nullptr);
9429 return BuildExprRequirement(
9430 E, /*IsSimple=*/false, NoexceptLoc,
9432}
9433
9436 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9439 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9441 ReturnTypeRequirement.isDependent())
9443 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9445 else if (ReturnTypeRequirement.isSubstitutionFailure())
9447 else if (ReturnTypeRequirement.isTypeConstraint()) {
9448 // C++2a [expr.prim.req]p1.3.3
9449 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9450 // be satisfied.
9452 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9453 QualType MatchedType =
9456 Args.push_back(TemplateArgument(MatchedType));
9457
9458 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9459
9460 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9461 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9462 const TypeConstraint *TC = Param->getTypeConstraint();
9463 assert(TC && "Type Constraint cannot be null here");
9464 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9465 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9466 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9467 if (Constraint.isInvalid()) {
9469 createSubstDiagAt(IDC->getExprLoc(),
9470 [&](llvm::raw_ostream &OS) {
9471 IDC->printPretty(OS, /*Helper=*/nullptr,
9472 getPrintingPolicy());
9473 }),
9474 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9475 }
9476 SubstitutedConstraintExpr =
9477 cast<ConceptSpecializationExpr>(Constraint.get());
9478 if (!SubstitutedConstraintExpr->isSatisfied())
9480 }
9481 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9482 ReturnTypeRequirement, Status,
9483 SubstitutedConstraintExpr);
9484}
9485
9488 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9489 bool IsSimple, SourceLocation NoexceptLoc,
9491 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9492 IsSimple, NoexceptLoc,
9493 ReturnTypeRequirement);
9494}
9495
9499}
9500
9504 return new (Context) concepts::TypeRequirement(SubstDiag);
9505}
9506
9508 return BuildNestedRequirement(Constraint);
9509}
9510
9513 ConstraintSatisfaction Satisfaction;
9514 if (!Constraint->isInstantiationDependent() &&
9515 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9516 Constraint->getSourceRange(), Satisfaction))
9517 return nullptr;
9518 return new (Context) concepts::NestedRequirement(Context, Constraint,
9519 Satisfaction);
9520}
9521
9523Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9524 const ASTConstraintSatisfaction &Satisfaction) {
9526 InvalidConstraintEntity,
9528}
9529
9532 ArrayRef<ParmVarDecl *> LocalParameters,
9533 Scope *BodyScope) {
9534 assert(BodyScope);
9535
9537 RequiresKWLoc);
9538
9539 PushDeclContext(BodyScope, Body);
9540
9541 for (ParmVarDecl *Param : LocalParameters) {
9542 if (Param->getType()->isVoidType()) {
9543 if (LocalParameters.size() > 1) {
9544 Diag(Param->getBeginLoc(), diag::err_void_only_param);
9545 Param->setType(Context.IntTy);
9546 } else if (Param->getIdentifier()) {
9547 Diag(Param->getBeginLoc(), diag::err_param_with_void_type);
9548 Param->setType(Context.IntTy);
9549 } else if (Param->getType().hasQualifiers()) {
9550 Diag(Param->getBeginLoc(), diag::err_void_param_qualified);
9551 }
9552 } else if (Param->hasDefaultArg()) {
9553 // C++2a [expr.prim.req] p4
9554 // [...] A local parameter of a requires-expression shall not have a
9555 // default argument. [...]
9556 Diag(Param->getDefaultArgRange().getBegin(),
9557 diag::err_requires_expr_local_parameter_default_argument);
9558 // Ignore default argument and move on
9559 } else if (Param->isExplicitObjectParameter()) {
9560 // C++23 [dcl.fct]p6:
9561 // An explicit-object-parameter-declaration is a parameter-declaration
9562 // with a this specifier. An explicit-object-parameter-declaration
9563 // shall appear only as the first parameter-declaration of a
9564 // parameter-declaration-list of either:
9565 // - a member-declarator that declares a member function, or
9566 // - a lambda-declarator.
9567 //
9568 // The parameter-declaration-list of a requires-expression is not such
9569 // a context.
9570 Diag(Param->getExplicitObjectParamThisLoc(),
9571 diag::err_requires_expr_explicit_object_parameter);
9572 Param->setExplicitObjectParameterLoc(SourceLocation());
9573 }
9574
9575 Param->setDeclContext(Body);
9576 // If this has an identifier, add it to the scope stack.
9577 if (Param->getIdentifier()) {
9578 CheckShadow(BodyScope, Param);
9579 PushOnScopeChains(Param, BodyScope);
9580 }
9581 }
9582 return Body;
9583}
9584
9586 assert(CurContext && "DeclContext imbalance!");
9588 assert(CurContext && "Popped translation unit!");
9589}
9590
9592 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9593 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9594 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9595 SourceLocation ClosingBraceLoc) {
9596 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9597 LocalParameters, RParenLoc, Requirements,
9598 ClosingBraceLoc);
9600 return ExprError();
9601 return RE;
9602}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
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:2686
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
Definition: CGCall.cpp:110
const Decl * D
Expr * E
enum clang::sema::@1718::IndirectLocalPathEntry::EntryKind Kind
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3365
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.
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 void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl * > &VBases, llvm::SetVector< CXXRecordDecl * > &PublicSubobjectsSeen, bool ParentIsPublic)
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs, SourceLocation KeyLoc)
static bool HasNonDeletedDefaultedEqualityComparison(Sema &S, const CXXRecordDecl *Decl, SourceLocation KeyLoc)
static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, clang::tok::TokenKind TypeTraitID)
Checks that type T is not a VLA.
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 ExprResult attemptRecovery(Sema &SemaRef, const TypoCorrectionConsumer &Consumer, const TypoCorrection &TC)
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 QualType adjustVectorType(ASTContext &Context, QualType FromTy, QualType ToType, QualType *ElTy=nullptr)
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.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr * > &Args, bool &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo * > FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
static bool DiagnoseAtomicInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, clang::tok::TokenKind TypeTraitID)
Checks that type T is not an atomic type (_Atomic).
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 HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, Sema &Self, SourceLocation KeyLoc, ASTContext &C, bool(CXXRecordDecl::*HasTrivial)() const, bool(CXXRecordDecl::*HasNonTrivial)() const, bool(CXXMethodDecl::*IsDesiredOp)() const)
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E)
static UsualDeallocFnInfo resolveDeallocationOverload(Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 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)
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 doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, QualType allocType)
Determine whether a given type is a class for which 'delete[]' would call a member 'operator delete[]...
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, SourceLocation KeyLoc, TypeSourceInfo *TInfo)
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, QualType T, Expr *DimExpr, SourceLocation KeyLoc)
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, SourceLocation Loc, QualType ArgTy)
Check the completeness of a type in a unary type trait.
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl * > OperatorArrows)
Note a set of 'operator->' functions that were used for a member access.
static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI)
static ExprResult CheckConvertibilityForTypeTraits(Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs, SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator)
TypeTraitReturnType
static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool IsDependent)
static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, SourceLocation KeyLoc)
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14673
This file declares semantic analysis for HLSL constructs.
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
CanQualType FloatTy
Definition: ASTContext.h:1172
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2273
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1188
CanQualType NullPtrTy
Definition: ASTContext.h:1187
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
IdentifierTable & Idents
Definition: ASTContext.h:680
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:834
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1161
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1169
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2482
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
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 getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1681
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2284
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2312
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1920
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2132
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.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2513
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3747
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition: Type.cpp:270
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2853
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
QualType getElementType() const
Definition: Type.h:3589
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7761
Attr - This represents one attribute.
Definition: Attr.h:43
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
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:4895
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1097
const Expr * getSubExpr() const
Definition: ExprCXX.h:1513
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2318
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2458
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2520
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
bool isArrayForm() const
Definition: ExprCXX.h:2524
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2548
Expr * getArgument()
Definition: ExprCXX.h:2539
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
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:901
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isVirtual() const
Definition: DeclCXX.h:2133
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl * > &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2),...
Definition: DeclCXX.cpp:2472
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2582
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2228
bool isConst() const
Definition: DeclCXX.h:2130
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2560
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, 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:291
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4126
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2617
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1353
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1346
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1378
base_class_range bases()
Definition: DeclCXX.h:620
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1313
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1290
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1226
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1340
capture_const_range captures() const
Definition: DeclCXX.h:1109
ctor_range ctors() const
Definition: DeclCXX.h:682
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1233
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1414
bool hasNonTrivialMoveConstructor() const
Determine whether this class has a non-trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1325
bool hasDefinition() const
Definition: DeclCXX.h:572
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1198
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2069
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1360
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1259
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1300
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2182
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:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:142
SourceLocation getEndLoc() const
Definition: DeclSpec.h:85
SourceRange getRange() const
Definition: DeclSpec.h:80
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Represents a C++ temporary.
Definition: ExprCXX.h:1457
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1470
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1092
Represents the this expression in C++.
Definition: ExprCXX.h:1152
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1568
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool IsListInit)
Definition: ExprCXX.cpp:1471
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3081
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
Expr * getCallee()
Definition: Expr.h:3024
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3055
arg_range arguments()
Definition: Expr.h:3116
Decl * getCalleeDecl()
Definition: Expr.h:3041
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.
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:390
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Definition: ExprConcepts.h:124
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
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:205
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:245
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2105
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:313
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_decltype
Definition: DeclSpec.h:311
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
static const TST TST_decltype_auto
Definition: DeclSpec.h:312
static const TST TST_error
Definition: DeclSpec.h:328
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:592
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:822
void setImplicit(bool I=true)
Definition: DeclBase.h:597
DeclContext * getDeclContext()
Definition: DeclBase.h:451
bool hasAttr() const
Definition: DeclBase.h:580
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:870
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:430
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 ...
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2118
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2115
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6522
bool isDeduced() const
Definition: Type.h:6544
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
Definition: Diagnostic.h:1512
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:585
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
Recursive AST visitor that supports extension via dynamic dispatch.
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4875
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4061
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
bool isLValue() const
Definition: Expr.h:380
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isReadIfDiscardedInCPlusPlus11() const
Determine whether an lvalue-to-rvalue conversion should implicitly be applied to this expression if i...
Definition: Expr.cpp:2551
bool isGLValue() const
Definition: Expr.h:280
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:4178
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
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:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3310
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
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:3587
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
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:3963
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:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
An expression trait intrinsic.
Definition: ExprCXX.h:2924
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
Represents a function declaration or definition.
Definition: Decl.h:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4064
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2249
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2633
QualType getReturnType() const
Definition: Decl.h:2720
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2305
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2468
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3372
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4405
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2338
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3702
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:3210
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5474
Declaration of a template function.
Definition: DeclTemplate.h:959
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
bool getNoReturn() const
Definition: Type.h:4480
bool getProducesResult() const
Definition: Type.h:4481
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
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.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2082
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:618
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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.
Definition: SemaInit.cpp:7584
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3825
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8672
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....
Definition: SemaInit.cpp:3814
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 InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
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:973
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:788
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:693
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:803
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:798
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:1357
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
bool isAmbiguous() const
Definition: Lookup.h:324
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
bool isClassLookup() const
Returns whether these results arose from performing a lookup into a class.
Definition: Lookup.h:432
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
A global _GUID constant.
Definition: DeclCXX.h:4307
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3323
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
QualType getPointeeType() const
Definition: Type.h:3535
const Type * getClass() const
Definition: Type.h:3549
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:260
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:296
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1809
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7580
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7592
Represents a class type in Objective C.
Definition: Type.h:7326
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7559
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:436
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:2143
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
Represents a parameter to a function.
Definition: Decl.h:1725
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:2922
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2566
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2582
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
@ DK_nontrivial_c_struct
Definition: Type.h:1524
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
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: Type.h:8134
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2885
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7977
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1437
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: Type.h:8114
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
GC getObjCGCAttr() const
Definition: Type.h:512
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:347
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:343
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
bool hasCVRQualifiers() const
Definition: Type.h:480
bool hasUnaligned() const
Definition: Type.h:504
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:571
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: Type.h:701
void setAddressSpace(LangAS space)
Definition: Type.h:584
unsigned getCVRUQualifiers() const
Definition: Type.h:482
void setObjCGCAttr(GC type)
Definition: Type.h:513
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:434
LangAS getAddressSpace() const
Definition: Type.h:564
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:541
Represents a struct/union/class.
Definition: Decl.h:4148
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4277
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
Represents the body of a requires-expression.
Definition: DeclCXX.h:2047
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2268
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
@ 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:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
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:817
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:318
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:225
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
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.
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:259
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:3003
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10024
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12079
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12109
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6394
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:731
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2030
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:7837
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:8998
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:8986
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9028
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:412
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
VariadicCallType
Definition: Sema.h:2308
@ VariadicDoesNotApply
Definition: Sema.h:2313
@ VariadicFunction
Definition: Sema.h:2309
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
TypeResult ActOnTemplateIdType(Scope *S, 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)
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition: Sema.h:8453
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:8458
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:8462
@ IER_Error
An error occurred.
Definition: Sema.h:8465
@ IER_Exists
The symbol exists.
Definition: Sema.h:8455
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1557
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
SemaCUDA & CUDA()
Definition: Sema.h:1070
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...
Definition: SemaExpr.cpp:20380
ConditionKind
Definition: Sema.h:7344
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:848
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10116
@ AR_inaccessible
Definition: Sema.h:1262
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:3377
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)
Definition: SemaExpr.cpp:18430
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17145
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10143
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1658
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),...
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:1568
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:
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1102
ASTContext & Context
Definition: Sema.h:908
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:614
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.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:528
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...
Definition: SemaExpr.cpp:7893
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1110
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....
@ AllowFold
Definition: Sema.h:7238
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1497
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19660
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
ASTContext & getASTContext() const
Definition: Sema.h:531
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.
Definition: SemaExpr.cpp:18930
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15295
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9576
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N)
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:690
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.
Definition: SemaExpr.cpp:6199
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)
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
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:816
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7955
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...
Definition: SemaStmt.cpp:3283
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 CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
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:420
FPOptions & getCurFPFeatures()
Definition: Sema.h:526
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:13941
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:13944
const LangOptions & getLangOpts() const
Definition: Sema.h:524
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...
Definition: SemaExpr.cpp:7292
SemaOpenACC & OpenACC()
Definition: Sema.h:1115
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:907
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
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)
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14368
const LangOptions & LangOpts
Definition: Sema.h:906
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2404
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.
Definition: SemaInit.cpp:7547
SemaHLSL & HLSL()
Definition: Sema.h:1075
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,...
Definition: SemaExpr.cpp:17468
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
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.
Definition: SemaExpr.cpp:20059
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:6473
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc)
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.
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:782
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.
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)
Definition: SemaExpr.cpp:10406
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6470
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9788
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7778
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9581
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:2077
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7669
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5787
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...
Definition: SemaExpr.cpp:7915
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7770
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1548
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7573
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7575
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7654
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).
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7400
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:7966
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4109
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20964
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17367
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:13483
SourceManager & getSourceManager() const
Definition: Sema.h:529
@ TryCapture_Implicit
Definition: Sema.h:6587
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:8037
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.
Definition: SemaStmt.cpp:3418
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...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
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 ?: under C++ semantics.
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
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.
Definition: SemaDecl.cpp:8262
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
Definition: SemaExprCXX.cpp:59
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:14938
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:7962
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:9995
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
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:286
ASTConsumer & Consumer
Definition: Sema.h:909
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:6477
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16547
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
Definition: SemaType.cpp:9653
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5703
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20252
SemaPPC & PPC()
Definition: Sema.h:1130
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9068
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:871
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.
Definition: SemaExpr.cpp:20894
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:7973
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17897
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7910
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1308
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
DiagnosticsEngine & Diags
Definition: Sema.h:910
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:516
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9718
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:1783
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
Definition: SemaType.cpp:9667
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
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...
Definition: SemaExpr.cpp:16812
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,...
Definition: SemaExpr.cpp:18078
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5953
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1961
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21161
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:93
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7959
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9154
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
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)
Definition: SemaType.cpp:2750
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:7331
IdentifierResolver IdResolver
Definition: Sema.h:2996
const TypoExprState & getTypoExprState(TypoExpr *TE) const
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7287
ExprResult ActOnCXXThis(SourceLocation Loc)
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
AllocationFunctionScope
The scope in which to find allocation functions.
Definition: Sema.h:8156
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:8164
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:8161
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:8158
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5332
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8261
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)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:378
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4466
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
StringRef getString() const
Definition: Expr.h:1855
bool isUnion() const
Definition: Decl.h:3770
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:752
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Represents a template argument.
Definition: TemplateBase.h:61
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
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, std::optional< unsigned > NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
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:242
Represents a declaration of a type.
Definition: Decl.h:3370
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:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7913
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1876
The base class of the type hierarchy.
Definition: Type.h:1828
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:2511
bool isStructureType() const
Definition: Type.cpp:662
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2937
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8486
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2180
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool isRValueReferenceType() const
Definition: Type.h:8212
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:8149
bool isVoidPointerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8258
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isPointerType() const
Definition: Type.h:8186
bool isArrayParameterType() const
Definition: Type.h:8274
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isHLSLIntangibleType() const
Definition: Type.cpp:5103
bool isEnumeralType() const
Definition: Type.h:8290
bool isScalarType() const
Definition: Type.h:8609
bool isInterfaceType() const
Definition: Type.cpp:684
bool isVariableArrayType() const
Definition: Type.h:8270
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isExtVectorType() const
Definition: Type.h:8302
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
bool isMemberDataPointerType() const
Definition: Type.h:8251
bool isLValueReferenceType() const
Definition: Type.h:8208
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2372
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isHalfType() const
Definition: Type.h:8514
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2045
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:8160
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8681
bool isMemberPointerType() const
Definition: Type.h:8240
bool isAtomicType() const
Definition: Type.h:8341
bool isMatrixType() const
Definition: Type.h:8316
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:3018
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2446
bool isPointerOrReferenceType() const
Definition: Type.h:8190
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4991
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool isStructureOrClassType() const
Definition: Type.cpp:690
bool isMemberFunctionPointerType() const
Definition: Type.h:8244
bool isVectorType() const
Definition: Type.h:8298
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isFloatingType() const
Definition: Type.cpp:2283
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2230
bool isAnyPointerType() const
Definition: Type.h:8194
bool isClassType() const
Definition: Type.cpp:656
TypeClass getTypeClass() const
Definition: Type.h:2341
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4997
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
bool isObjCRetainableType() const
Definition: Type.cpp:5028
bool isUnionType() const
Definition: Type.cpp:704
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1924
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition: Type.cpp:721
Simple class containing the result of Sema::CorrectTypo.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6837
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition: DeclSpec.h:1056
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1110
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1080
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5388
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3392
Represents a variable declaration or definition.
Definition: Decl.h:882
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2179
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:2500
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1309
Represents a GCC generic vector type.
Definition: Type.h:4034
TemplateParameterList * getTypeConstraintTemplateParameterList() const
Definition: ExprConcepts.h:347
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:758
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:950
bool hasPotentialThisCapture() const
Definition: ScopeInfo.h:999
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
bool hasPotentialCaptures() const
Definition: ScopeInfo.h:1065
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition: ScopeInfo.h:1048
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
void visitPotentialCaptures(llvm::function_ref< void(ValueDecl *, Expr *)> Callback) const
Definition: ScopeInfo.cpp:235
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
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:1157
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
bool isLambdaCallWithImplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:43
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
ArrayTypeTrait
Names for the array type traits.
Definition: TypeTraits.h:42
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
unsigned getTypeTraitArity(TypeTrait T) LLVM_READONLY
Return the arity of the type trait T.
Definition: TypeTraits.cpp:107
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
CanThrowResult
Possible results from evaluation of a noexcept expression.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:180
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1768
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1771
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1774
@ 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
@ 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>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ SC_None
Definition: Specifiers.h:250
@ OMF_performSelector
StmtResult StmtError()
Definition: Ownership.h:265
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
@ 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:205
@ 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:202
@ 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:208
@ 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_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
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
@ Class
The "class" keyword.
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition: Sema.h:210
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
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
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:364
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ Generic
not a target-specific vector type
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ReservedIdentifierStatus
@ Other
Other implicit parameter.
TypeTrait
Names for traits that operate specifically on types.
Definition: TypeTraits.h:21
@ BTT_Last
Definition: TypeTraits.h:30
@ UTT_Last
Definition: TypeTraits.h:24
CXXNewInitializationStyle
Definition: ExprCXX.h:2226
@ Parens
New-expression has a C++98 paren-delimited initializer.
@ None
New-expression has no initializer as written.
@ Braces
New-expression has a C++11 list-initializer.
@ EST_DynamicNone
throw()
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:433
@ CStyleCast
A C-style cast.
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ FunctionalCast
A functional-style cast.
@ AS_public
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define false
Definition: stdbool.h:26
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:89
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
Definition: ASTConcept.cpp:69
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:1312
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1321
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
ArrayTypeInfo Arr
Definition: DeclSpec.h:1641
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1259
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5161
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5164
Extra information about a function prototype.
Definition: Type.h:5187
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5194
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5188
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4282
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10124
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:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461