clang 19.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"
21#include "clang/AST/ExprCXX.h"
23#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"
44#include "clang/Sema/Template.h"
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/STLExtras.h"
48#include "llvm/ADT/STLForwardCompat.h"
49#include "llvm/ADT/StringExtras.h"
50#include "llvm/Support/ErrorHandling.h"
51#include "llvm/Support/TypeSize.h"
52#include <optional>
53using namespace clang;
54using namespace sema;
55
56/// Handle the result of the special case name lookup for inheriting
57/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
58/// constructor names in member using declarations, even if 'X' is not the
59/// name of the corresponding type.
61 SourceLocation NameLoc,
62 const IdentifierInfo &Name) {
64
65 // Convert the nested-name-specifier into a type.
67 switch (NNS->getKind()) {
70 Type = QualType(NNS->getAsType(), 0);
71 break;
72
74 // Strip off the last layer of the nested-name-specifier and build a
75 // typename type for it.
76 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
79 break;
80
85 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
86 }
87
88 // This reference to the type is located entirely at the location of the
89 // final identifier in the qualified-id.
92}
93
95 SourceLocation NameLoc, Scope *S,
96 CXXScopeSpec &SS, bool EnteringContext) {
97 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
98 assert(CurClass && &II == CurClass->getIdentifier() &&
99 "not a constructor name");
100
101 // When naming a constructor as a member of a dependent context (eg, in a
102 // friend declaration or an inherited constructor declaration), form an
103 // unresolved "typename" type.
104 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
106 SS.getScopeRep(), &II);
107 return ParsedType::make(T);
108 }
109
110 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
111 return ParsedType();
112
113 // Find the injected-class-name declaration. Note that we make no attempt to
114 // diagnose cases where the injected-class-name is shadowed: the only
115 // declaration that can validly shadow the injected-class-name is a
116 // non-static data member, and if the class contains both a non-static data
117 // member and a constructor then it is ill-formed (we check that in
118 // CheckCompletedCXXClass).
119 CXXRecordDecl *InjectedClassName = nullptr;
120 for (NamedDecl *ND : CurClass->lookup(&II)) {
121 auto *RD = dyn_cast<CXXRecordDecl>(ND);
122 if (RD && RD->isInjectedClassName()) {
123 InjectedClassName = RD;
124 break;
125 }
126 }
127 if (!InjectedClassName) {
128 if (!CurClass->isInvalidDecl()) {
129 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
130 // properly. Work around it here for now.
132 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
133 }
134 return ParsedType();
135 }
136
137 QualType T = Context.getTypeDeclType(InjectedClassName);
138 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
139 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
140
141 return ParsedType::make(T);
142}
143
145 SourceLocation NameLoc, Scope *S,
146 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
147 bool EnteringContext) {
148 // Determine where to perform name lookup.
149
150 // FIXME: This area of the standard is very messy, and the current
151 // wording is rather unclear about which scopes we search for the
152 // destructor name; see core issues 399 and 555. Issue 399 in
153 // particular shows where the current description of destructor name
154 // lookup is completely out of line with existing practice, e.g.,
155 // this appears to be ill-formed:
156 //
157 // namespace N {
158 // template <typename T> struct S {
159 // ~S();
160 // };
161 // }
162 //
163 // void f(N::S<int>* s) {
164 // s->N::S<int>::~S();
165 // }
166 //
167 // See also PR6358 and PR6359.
168 //
169 // For now, we accept all the cases in which the name given could plausibly
170 // be interpreted as a correct destructor name, issuing off-by-default
171 // extension diagnostics on the cases that don't strictly conform to the
172 // C++20 rules. This basically means we always consider looking in the
173 // nested-name-specifier prefix, the complete nested-name-specifier, and
174 // the scope, and accept if we find the expected type in any of the three
175 // places.
176
177 if (SS.isInvalid())
178 return nullptr;
179
180 // Whether we've failed with a diagnostic already.
181 bool Failed = false;
182
185
186 // If we have an object type, it's because we are in a
187 // pseudo-destructor-expression or a member access expression, and
188 // we know what type we're looking for.
189 QualType SearchType =
190 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
191
192 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
193 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
194 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
195 if (!Type)
196 return false;
197
198 if (SearchType.isNull() || SearchType->isDependentType())
199 return true;
200
202 return Context.hasSameUnqualifiedType(T, SearchType);
203 };
204
205 unsigned NumAcceptableResults = 0;
206 for (NamedDecl *D : Found) {
207 if (IsAcceptableResult(D))
208 ++NumAcceptableResults;
209
210 // Don't list a class twice in the lookup failure diagnostic if it's
211 // found by both its injected-class-name and by the name in the enclosing
212 // scope.
213 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
214 if (RD->isInjectedClassName())
215 D = cast<NamedDecl>(RD->getParent());
216
217 if (FoundDeclSet.insert(D).second)
218 FoundDecls.push_back(D);
219 }
220
221 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
222 // results, and all non-matching results if we have a search type. It's not
223 // clear what the right behavior is if destructor lookup hits an ambiguity,
224 // but other compilers do generally accept at least some kinds of
225 // ambiguity.
226 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
227 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
228 LookupResult::Filter F = Found.makeFilter();
229 while (F.hasNext()) {
230 NamedDecl *D = F.next();
231 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
232 Diag(D->getLocation(), diag::note_destructor_type_here)
234 else
235 Diag(D->getLocation(), diag::note_destructor_nontype_here);
236
237 if (!IsAcceptableResult(D))
238 F.erase();
239 }
240 F.done();
241 }
242
243 if (Found.isAmbiguous())
244 Failed = true;
245
246 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
247 if (IsAcceptableResult(Type)) {
249 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
250 return CreateParsedType(
253 }
254 }
255
256 return nullptr;
257 };
258
259 bool IsDependent = false;
260
261 auto LookupInObjectType = [&]() -> ParsedType {
262 if (Failed || SearchType.isNull())
263 return nullptr;
264
265 IsDependent |= SearchType->isDependentType();
266
267 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
268 DeclContext *LookupCtx = computeDeclContext(SearchType);
269 if (!LookupCtx)
270 return nullptr;
271 LookupQualifiedName(Found, LookupCtx);
272 return CheckLookupResult(Found);
273 };
274
275 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
276 if (Failed)
277 return nullptr;
278
279 IsDependent |= isDependentScopeSpecifier(LookupSS);
280 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
281 if (!LookupCtx)
282 return nullptr;
283
284 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
285 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
286 Failed = true;
287 return nullptr;
288 }
289 LookupQualifiedName(Found, LookupCtx);
290 return CheckLookupResult(Found);
291 };
292
293 auto LookupInScope = [&]() -> ParsedType {
294 if (Failed || !S)
295 return nullptr;
296
297 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
298 LookupName(Found, S);
299 return CheckLookupResult(Found);
300 };
301
302 // C++2a [basic.lookup.qual]p6:
303 // In a qualified-id of the form
304 //
305 // nested-name-specifier[opt] type-name :: ~ type-name
306 //
307 // the second type-name is looked up in the same scope as the first.
308 //
309 // We interpret this as meaning that if you do a dual-scope lookup for the
310 // first name, you also do a dual-scope lookup for the second name, per
311 // C++ [basic.lookup.classref]p4:
312 //
313 // If the id-expression in a class member access is a qualified-id of the
314 // form
315 //
316 // class-name-or-namespace-name :: ...
317 //
318 // the class-name-or-namespace-name following the . or -> is first looked
319 // up in the class of the object expression and the name, if found, is used.
320 // Otherwise, it is looked up in the context of the entire
321 // postfix-expression.
322 //
323 // This looks in the same scopes as for an unqualified destructor name:
324 //
325 // C++ [basic.lookup.classref]p3:
326 // If the unqualified-id is ~ type-name, the type-name is looked up
327 // in the context of the entire postfix-expression. If the type T
328 // of the object expression is of a class type C, the type-name is
329 // also looked up in the scope of class C. At least one of the
330 // lookups shall find a name that refers to cv T.
331 //
332 // FIXME: The intent is unclear here. Should type-name::~type-name look in
333 // the scope anyway if it finds a non-matching name declared in the class?
334 // If both lookups succeed and find a dependent result, which result should
335 // we retain? (Same question for p->~type-name().)
336
337 if (NestedNameSpecifier *Prefix =
338 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
339 // This is
340 //
341 // nested-name-specifier type-name :: ~ type-name
342 //
343 // Look for the second type-name in the nested-name-specifier.
344 CXXScopeSpec PrefixSS;
345 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
346 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
347 return T;
348 } else {
349 // This is one of
350 //
351 // type-name :: ~ type-name
352 // ~ type-name
353 //
354 // Look in the scope and (if any) the object type.
355 if (ParsedType T = LookupInScope())
356 return T;
357 if (ParsedType T = LookupInObjectType())
358 return T;
359 }
360
361 if (Failed)
362 return nullptr;
363
364 if (IsDependent) {
365 // We didn't find our type, but that's OK: it's dependent anyway.
366
367 // FIXME: What if we have no nested-name-specifier?
368 QualType T =
370 SS.getWithLocInContext(Context), II, NameLoc);
371 return ParsedType::make(T);
372 }
373
374 // The remaining cases are all non-standard extensions imitating the behavior
375 // of various other compilers.
376 unsigned NumNonExtensionDecls = FoundDecls.size();
377
378 if (SS.isSet()) {
379 // For compatibility with older broken C++ rules and existing code,
380 //
381 // nested-name-specifier :: ~ type-name
382 //
383 // also looks for type-name within the nested-name-specifier.
384 if (ParsedType T = LookupInNestedNameSpec(SS)) {
385 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
386 << SS.getRange()
388 ("::" + II.getName()).str());
389 return T;
390 }
391
392 // For compatibility with other compilers and older versions of Clang,
393 //
394 // nested-name-specifier type-name :: ~ type-name
395 //
396 // also looks for type-name in the scope. Unfortunately, we can't
397 // reasonably apply this fallback for dependent nested-name-specifiers.
398 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
399 if (ParsedType T = LookupInScope()) {
400 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
402 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
404 return T;
405 }
406 }
407 }
408
409 // We didn't find anything matching; tell the user what we did find (if
410 // anything).
411
412 // Don't tell the user about declarations we shouldn't have found.
413 FoundDecls.resize(NumNonExtensionDecls);
414
415 // List types before non-types.
416 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
417 [](NamedDecl *A, NamedDecl *B) {
418 return isa<TypeDecl>(A->getUnderlyingDecl()) >
419 isa<TypeDecl>(B->getUnderlyingDecl());
420 });
421
422 // Suggest a fixit to properly name the destroyed type.
423 auto MakeFixItHint = [&]{
424 const CXXRecordDecl *Destroyed = nullptr;
425 // FIXME: If we have a scope specifier, suggest its last component?
426 if (!SearchType.isNull())
427 Destroyed = SearchType->getAsCXXRecordDecl();
428 else if (S)
429 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
430 if (Destroyed)
432 Destroyed->getNameAsString());
433 return FixItHint();
434 };
435
436 if (FoundDecls.empty()) {
437 // FIXME: Attempt typo-correction?
438 Diag(NameLoc, diag::err_undeclared_destructor_name)
439 << &II << MakeFixItHint();
440 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
441 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
442 assert(!SearchType.isNull() &&
443 "should only reject a type result if we have a search type");
445 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
446 << T << SearchType << MakeFixItHint();
447 } else {
448 Diag(NameLoc, diag::err_destructor_expr_nontype)
449 << &II << MakeFixItHint();
450 }
451 } else {
452 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
453 : diag::err_destructor_expr_mismatch)
454 << &II << SearchType << MakeFixItHint();
455 }
456
457 for (NamedDecl *FoundD : FoundDecls) {
458 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
459 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
461 else
462 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
463 << FoundD;
464 }
465
466 return nullptr;
467}
468
470 ParsedType ObjectType) {
472 return nullptr;
473
475 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
476 return nullptr;
477 }
478
480 "unexpected type in getDestructorType");
482
483 // If we know the type of the object, check that the correct destructor
484 // type was named now; we can give better diagnostics this way.
485 QualType SearchType = GetTypeFromParser(ObjectType);
486 if (!SearchType.isNull() && !SearchType->isDependentType() &&
487 !Context.hasSameUnqualifiedType(T, SearchType)) {
488 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
489 << T << SearchType;
490 return nullptr;
491 }
492
493 return ParsedType::make(T);
494}
495
497 const UnqualifiedId &Name, bool IsUDSuffix) {
498 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
499 if (!IsUDSuffix) {
500 // [over.literal] p8
501 //
502 // double operator""_Bq(long double); // OK: not a reserved identifier
503 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
504 const IdentifierInfo *II = Name.Identifier;
506 SourceLocation Loc = Name.getEndLoc();
508 if (auto Hint = FixItHint::CreateReplacement(
509 Name.getSourceRange(),
510 (StringRef("operator\"\"") + II->getName()).str());
511 isReservedInAllContexts(Status)) {
512 Diag(Loc, diag::warn_reserved_extern_symbol)
513 << II << static_cast<int>(Status) << Hint;
514 } else {
515 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
516 }
517 }
518 }
519
520 if (!SS.isValid())
521 return false;
522
523 switch (SS.getScopeRep()->getKind()) {
527 // Per C++11 [over.literal]p2, literal operators can only be declared at
528 // namespace scope. Therefore, this unqualified-id cannot name anything.
529 // Reject it early, because we have no AST representation for this in the
530 // case where the scope is dependent.
531 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
532 << SS.getScopeRep();
533 return true;
534
539 return false;
540 }
541
542 llvm_unreachable("unknown nested name specifier kind");
543}
544
545/// Build a C++ typeid expression with a type operand.
547 SourceLocation TypeidLoc,
548 TypeSourceInfo *Operand,
549 SourceLocation RParenLoc) {
550 // C++ [expr.typeid]p4:
551 // The top-level cv-qualifiers of the lvalue expression or the type-id
552 // that is the operand of typeid are always ignored.
553 // If the type of the type-id is a class type or a reference to a class
554 // type, the class shall be completely-defined.
555 Qualifiers Quals;
556 QualType T
557 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
558 Quals);
559 if (T->getAs<RecordType>() &&
560 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
561 return ExprError();
562
564 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
565
566 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
567 return ExprError();
568
569 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
570 SourceRange(TypeidLoc, RParenLoc));
571}
572
573/// Build a C++ typeid expression with an expression operand.
575 SourceLocation TypeidLoc,
576 Expr *E,
577 SourceLocation RParenLoc) {
578 bool WasEvaluated = false;
579 if (E && !E->isTypeDependent()) {
580 if (E->hasPlaceholderType()) {
582 if (result.isInvalid()) return ExprError();
583 E = result.get();
584 }
585
586 QualType T = E->getType();
587 if (const RecordType *RecordT = T->getAs<RecordType>()) {
588 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
589 // C++ [expr.typeid]p3:
590 // [...] If the type of the expression is a class type, the class
591 // shall be completely-defined.
592 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
593 return ExprError();
594
595 // C++ [expr.typeid]p3:
596 // When typeid is applied to an expression other than an glvalue of a
597 // polymorphic class type [...] [the] expression is an unevaluated
598 // operand. [...]
599 if (RecordD->isPolymorphic() && E->isGLValue()) {
600 if (isUnevaluatedContext()) {
601 // The operand was processed in unevaluated context, switch the
602 // context and recheck the subexpression.
604 if (Result.isInvalid())
605 return ExprError();
606 E = Result.get();
607 }
608
609 // We require a vtable to query the type at run time.
610 MarkVTableUsed(TypeidLoc, RecordD);
611 WasEvaluated = true;
612 }
613 }
614
616 if (Result.isInvalid())
617 return ExprError();
618 E = Result.get();
619
620 // C++ [expr.typeid]p4:
621 // [...] If the type of the type-id is a reference to a possibly
622 // cv-qualified type, the result of the typeid expression refers to a
623 // std::type_info object representing the cv-unqualified referenced
624 // type.
625 Qualifiers Quals;
626 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
627 if (!Context.hasSameType(T, UnqualT)) {
628 T = UnqualT;
629 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
630 }
631 }
632
634 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
635 << E->getType());
636 else if (!inTemplateInstantiation() &&
637 E->HasSideEffects(Context, WasEvaluated)) {
638 // The expression operand for typeid is in an unevaluated expression
639 // context, so side effects could result in unintended consequences.
640 Diag(E->getExprLoc(), WasEvaluated
641 ? diag::warn_side_effects_typeid
642 : diag::warn_side_effects_unevaluated_context);
643 }
644
645 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
646 SourceRange(TypeidLoc, RParenLoc));
647}
648
649/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
652 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
653 // typeid is not supported in OpenCL.
654 if (getLangOpts().OpenCLCPlusPlus) {
655 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
656 << "typeid");
657 }
658
659 // Find the std::type_info type.
660 if (!getStdNamespace())
661 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
662
663 if (!CXXTypeInfoDecl) {
664 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
665 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
668 // Microsoft's typeinfo doesn't have type_info in std but in the global
669 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
670 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
673 }
674 if (!CXXTypeInfoDecl)
675 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
676 }
677
678 if (!getLangOpts().RTTI) {
679 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
680 }
681
683
684 if (isType) {
685 // The operand is a type; handle it as such.
686 TypeSourceInfo *TInfo = nullptr;
688 &TInfo);
689 if (T.isNull())
690 return ExprError();
691
692 if (!TInfo)
693 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
694
695 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
696 }
697
698 // The operand is an expression.
700 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
701
702 if (!getLangOpts().RTTIData && !Result.isInvalid())
703 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
704 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
705 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
706 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
708 return Result;
709}
710
711/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
712/// a single GUID.
713static void
716 // Optionally remove one level of pointer, reference or array indirection.
717 const Type *Ty = QT.getTypePtr();
718 if (QT->isPointerType() || QT->isReferenceType())
719 Ty = QT->getPointeeType().getTypePtr();
720 else if (QT->isArrayType())
721 Ty = Ty->getBaseElementTypeUnsafe();
722
723 const auto *TD = Ty->getAsTagDecl();
724 if (!TD)
725 return;
726
727 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
728 UuidAttrs.insert(Uuid);
729 return;
730 }
731
732 // __uuidof can grab UUIDs from template arguments.
733 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
734 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
735 for (const TemplateArgument &TA : TAL.asArray()) {
736 const UuidAttr *UuidForTA = nullptr;
737 if (TA.getKind() == TemplateArgument::Type)
738 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
739 else if (TA.getKind() == TemplateArgument::Declaration)
740 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
741
742 if (UuidForTA)
743 UuidAttrs.insert(UuidForTA);
744 }
745 }
746}
747
748/// Build a Microsoft __uuidof expression with a type operand.
750 SourceLocation TypeidLoc,
751 TypeSourceInfo *Operand,
752 SourceLocation RParenLoc) {
753 MSGuidDecl *Guid = nullptr;
754 if (!Operand->getType()->isDependentType()) {
756 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
757 if (UuidAttrs.empty())
758 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
759 if (UuidAttrs.size() > 1)
760 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
761 Guid = UuidAttrs.back()->getGuidDecl();
762 }
763
764 return new (Context)
765 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
766}
767
768/// Build a Microsoft __uuidof expression with an expression operand.
770 Expr *E, SourceLocation RParenLoc) {
771 MSGuidDecl *Guid = nullptr;
772 if (!E->getType()->isDependentType()) {
774 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
776 } else {
778 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
779 if (UuidAttrs.empty())
780 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
781 if (UuidAttrs.size() > 1)
782 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
783 Guid = UuidAttrs.back()->getGuidDecl();
784 }
785 }
786
787 return new (Context)
788 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
789}
790
791/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
794 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
795 QualType GuidType = Context.getMSGuidType();
796 GuidType.addConst();
797
798 if (isType) {
799 // The operand is a type; handle it as such.
800 TypeSourceInfo *TInfo = nullptr;
802 &TInfo);
803 if (T.isNull())
804 return ExprError();
805
806 if (!TInfo)
807 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
808
809 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
810 }
811
812 // The operand is an expression.
813 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
814}
815
816/// ActOnCXXBoolLiteral - Parse {true,false} literals.
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
825/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
829}
830
831/// ActOnCXXThrow - Parse throw expressions.
834 bool IsThrownVarInScope = false;
835 if (Ex) {
836 // C++0x [class.copymove]p31:
837 // When certain criteria are met, an implementation is allowed to omit the
838 // copy/move construction of a class object [...]
839 //
840 // - in a throw-expression, when the operand is the name of a
841 // non-volatile automatic object (other than a function or catch-
842 // clause parameter) whose scope does not extend beyond the end of the
843 // innermost enclosing try-block (if there is one), the copy/move
844 // operation from the operand to the exception object (15.1) can be
845 // omitted by constructing the automatic object directly into the
846 // exception object
847 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
848 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
849 Var && Var->hasLocalStorage() &&
850 !Var->getType().isVolatileQualified()) {
851 for (; S; S = S->getParent()) {
852 if (S->isDeclScope(Var)) {
853 IsThrownVarInScope = true;
854 break;
855 }
856
857 // FIXME: Many of the scope checks here seem incorrect.
858 if (S->getFlags() &
861 break;
862 }
863 }
864 }
865
866 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
867}
868
870 bool IsThrownVarInScope) {
871 const llvm::Triple &T = Context.getTargetInfo().getTriple();
872 const bool IsOpenMPGPUTarget =
873 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
874 // Don't report an error if 'throw' is used in system headers or in an OpenMP
875 // target region compiled for a GPU architecture.
876 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
877 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
878 // Delay error emission for the OpenMP device code.
879 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
880 }
881
882 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
883 if (IsOpenMPGPUTarget)
884 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
885
886 // Exceptions aren't allowed in CUDA device code.
887 if (getLangOpts().CUDA)
888 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
889 << "throw" << llvm::to_underlying(CUDA().CurrentTarget());
890
891 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
892 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
893
894 // Exceptions that escape a compute construct are ill-formed.
895 if (getLangOpts().OpenACC && getCurScope() &&
896 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
897 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
898 << /*throw*/ 2 << /*out of*/ 0;
899
900 if (Ex && !Ex->isTypeDependent()) {
901 // Initialize the exception result. This implicitly weeds out
902 // abstract types or types with inaccessible copy constructors.
903
904 // C++0x [class.copymove]p31:
905 // When certain criteria are met, an implementation is allowed to omit the
906 // copy/move construction of a class object [...]
907 //
908 // - in a throw-expression, when the operand is the name of a
909 // non-volatile automatic object (other than a function or
910 // catch-clause
911 // parameter) whose scope does not extend beyond the end of the
912 // innermost enclosing try-block (if there is one), the copy/move
913 // operation from the operand to the exception object (15.1) can be
914 // omitted by constructing the automatic object directly into the
915 // exception object
916 NamedReturnInfo NRInfo =
917 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
918
919 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
920 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
921 return ExprError();
922
923 InitializedEntity Entity =
924 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
925 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
926 if (Res.isInvalid())
927 return ExprError();
928 Ex = Res.get();
929 }
930
931 // PPC MMA non-pointer types are not allowed as throw expr types.
932 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
933 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
934
935 return new (Context)
936 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
937}
938
939static void
941 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
942 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
943 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
944 bool ParentIsPublic) {
945 for (const CXXBaseSpecifier &BS : RD->bases()) {
946 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
947 bool NewSubobject;
948 // Virtual bases constitute the same subobject. Non-virtual bases are
949 // always distinct subobjects.
950 if (BS.isVirtual())
951 NewSubobject = VBases.insert(BaseDecl).second;
952 else
953 NewSubobject = true;
954
955 if (NewSubobject)
956 ++SubobjectsSeen[BaseDecl];
957
958 // Only add subobjects which have public access throughout the entire chain.
959 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
960 if (PublicPath)
961 PublicSubobjectsSeen.insert(BaseDecl);
962
963 // Recurse on to each base subobject.
964 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
965 PublicPath);
966 }
967}
968
971 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
972 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
973 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
974 SubobjectsSeen[RD] = 1;
975 PublicSubobjectsSeen.insert(RD);
976 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
977 /*ParentIsPublic=*/true);
978
979 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
980 // Skip ambiguous objects.
981 if (SubobjectsSeen[PublicSubobject] > 1)
982 continue;
983
984 Objects.push_back(PublicSubobject);
985 }
986}
987
988/// CheckCXXThrowOperand - Validate the operand of a throw.
990 QualType ExceptionObjectTy, Expr *E) {
991 // If the type of the exception would be an incomplete type or a pointer
992 // to an incomplete type other than (cv) void the program is ill-formed.
993 QualType Ty = ExceptionObjectTy;
994 bool isPointer = false;
995 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
996 Ty = Ptr->getPointeeType();
997 isPointer = true;
998 }
999
1000 // Cannot throw WebAssembly reference type.
1001 if (Ty.isWebAssemblyReferenceType()) {
1002 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
1003 return true;
1004 }
1005
1006 // Cannot throw WebAssembly table.
1007 if (isPointer && Ty.isWebAssemblyReferenceType()) {
1008 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
1009 return true;
1010 }
1011
1012 if (!isPointer || !Ty->isVoidType()) {
1013 if (RequireCompleteType(ThrowLoc, Ty,
1014 isPointer ? diag::err_throw_incomplete_ptr
1015 : diag::err_throw_incomplete,
1016 E->getSourceRange()))
1017 return true;
1018
1019 if (!isPointer && Ty->isSizelessType()) {
1020 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1021 return true;
1022 }
1023
1024 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1025 diag::err_throw_abstract_type, E))
1026 return true;
1027 }
1028
1029 // If the exception has class type, we need additional handling.
1031 if (!RD)
1032 return false;
1033
1034 // If we are throwing a polymorphic class type or pointer thereof,
1035 // exception handling will make use of the vtable.
1036 MarkVTableUsed(ThrowLoc, RD);
1037
1038 // If a pointer is thrown, the referenced object will not be destroyed.
1039 if (isPointer)
1040 return false;
1041
1042 // If the class has a destructor, we must be able to call it.
1043 if (!RD->hasIrrelevantDestructor()) {
1047 PDiag(diag::err_access_dtor_exception) << Ty);
1049 return true;
1050 }
1051 }
1052
1053 // The MSVC ABI creates a list of all types which can catch the exception
1054 // object. This list also references the appropriate copy constructor to call
1055 // if the object is caught by value and has a non-trivial copy constructor.
1057 // We are only interested in the public, unambiguous bases contained within
1058 // the exception object. Bases which are ambiguous or otherwise
1059 // inaccessible are not catchable types.
1060 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1061 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1062
1063 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1064 // Attempt to lookup the copy constructor. Various pieces of machinery
1065 // will spring into action, like template instantiation, which means this
1066 // cannot be a simple walk of the class's decls. Instead, we must perform
1067 // lookup and overload resolution.
1068 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1069 if (!CD || CD->isDeleted())
1070 continue;
1071
1072 // Mark the constructor referenced as it is used by this throw expression.
1074
1075 // Skip this copy constructor if it is trivial, we don't need to record it
1076 // in the catchable type data.
1077 if (CD->isTrivial())
1078 continue;
1079
1080 // The copy constructor is non-trivial, create a mapping from this class
1081 // type to this constructor.
1082 // N.B. The selection of copy constructor is not sensitive to this
1083 // particular throw-site. Lookup will be performed at the catch-site to
1084 // ensure that the copy constructor is, in fact, accessible (via
1085 // friendship or any other means).
1087
1088 // We don't keep the instantiated default argument expressions around so
1089 // we must rebuild them here.
1090 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1091 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1092 return true;
1093 }
1094 }
1095 }
1096
1097 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1098 // the runtime with no ability for the compiler to request additional
1099 // alignment. Warn if the exception type requires alignment beyond the minimum
1100 // guaranteed by the target C++ runtime.
1102 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1103 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1104 if (ExnObjAlign < TypeAlign) {
1105 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1106 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1107 << Ty << (unsigned)TypeAlign.getQuantity()
1108 << (unsigned)ExnObjAlign.getQuantity();
1109 }
1110 }
1111 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1112 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1113 auto Ty = Dtor->getType();
1114 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1115 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1116 !FT->isNothrow())
1117 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1118 }
1119 }
1120 }
1121
1122 return false;
1123}
1124
1126 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1127 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1128
1129 QualType ClassType = ThisTy->getPointeeType();
1130 LambdaScopeInfo *CurLSI = nullptr;
1131 DeclContext *CurDC = CurSemaContext;
1132
1133 // Iterate through the stack of lambdas starting from the innermost lambda to
1134 // the outermost lambda, checking if '*this' is ever captured by copy - since
1135 // that could change the cv-qualifiers of the '*this' object.
1136 // The object referred to by '*this' starts out with the cv-qualifiers of its
1137 // member function. We then start with the innermost lambda and iterate
1138 // outward checking to see if any lambda performs a by-copy capture of '*this'
1139 // - and if so, any nested lambda must respect the 'constness' of that
1140 // capturing lamdbda's call operator.
1141 //
1142
1143 // Since the FunctionScopeInfo stack is representative of the lexical
1144 // nesting of the lambda expressions during initial parsing (and is the best
1145 // place for querying information about captures about lambdas that are
1146 // partially processed) and perhaps during instantiation of function templates
1147 // that contain lambda expressions that need to be transformed BUT not
1148 // necessarily during instantiation of a nested generic lambda's function call
1149 // operator (which might even be instantiated at the end of the TU) - at which
1150 // time the DeclContext tree is mature enough to query capture information
1151 // reliably - we use a two pronged approach to walk through all the lexically
1152 // enclosing lambda expressions:
1153 //
1154 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1155 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1156 // enclosed by the call-operator of the LSI below it on the stack (while
1157 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1158 // the stack represents the innermost lambda.
1159 //
1160 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1161 // represents a lambda's call operator. If it does, we must be instantiating
1162 // a generic lambda's call operator (represented by the Current LSI, and
1163 // should be the only scenario where an inconsistency between the LSI and the
1164 // DeclContext should occur), so climb out the DeclContexts if they
1165 // represent lambdas, while querying the corresponding closure types
1166 // regarding capture information.
1167
1168 // 1) Climb down the function scope info stack.
1169 for (int I = FunctionScopes.size();
1170 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1171 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1172 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1173 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1174 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1175
1176 if (!CurLSI->isCXXThisCaptured())
1177 continue;
1178
1179 auto C = CurLSI->getCXXThisCapture();
1180
1181 if (C.isCopyCapture()) {
1182 if (CurLSI->lambdaCaptureShouldBeConst())
1183 ClassType.addConst();
1184 return ASTCtx.getPointerType(ClassType);
1185 }
1186 }
1187
1188 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1189 // can happen during instantiation of its nested generic lambda call
1190 // operator); 2. if we're in a lambda scope (lambda body).
1191 if (CurLSI && isLambdaCallOperator(CurDC)) {
1193 "While computing 'this' capture-type for a generic lambda, when we "
1194 "run out of enclosing LSI's, yet the enclosing DC is a "
1195 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1196 "lambda call oeprator");
1197 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1198
1199 auto IsThisCaptured =
1200 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1201 IsConst = false;
1202 IsByCopy = false;
1203 for (auto &&C : Closure->captures()) {
1204 if (C.capturesThis()) {
1205 if (C.getCaptureKind() == LCK_StarThis)
1206 IsByCopy = true;
1207 if (Closure->getLambdaCallOperator()->isConst())
1208 IsConst = true;
1209 return true;
1210 }
1211 }
1212 return false;
1213 };
1214
1215 bool IsByCopyCapture = false;
1216 bool IsConstCapture = false;
1217 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1218 while (Closure &&
1219 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1220 if (IsByCopyCapture) {
1221 if (IsConstCapture)
1222 ClassType.addConst();
1223 return ASTCtx.getPointerType(ClassType);
1224 }
1225 Closure = isLambdaCallOperator(Closure->getParent())
1226 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1227 : nullptr;
1228 }
1229 }
1230 return ThisTy;
1231}
1232
1236
1237 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1238 if (method && method->isImplicitObjectMemberFunction())
1239 ThisTy = method->getThisType().getNonReferenceType();
1240 }
1241
1243 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1244
1245 // This is a lambda call operator that is being instantiated as a default
1246 // initializer. DC must point to the enclosing class type, so we can recover
1247 // the 'this' type from it.
1248 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1249 // There are no cv-qualifiers for 'this' within default initializers,
1250 // per [expr.prim.general]p4.
1251 ThisTy = Context.getPointerType(ClassTy);
1252 }
1253
1254 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1255 // might need to be adjusted if the lambda or any of its enclosing lambda's
1256 // captures '*this' by copy.
1257 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1260 return ThisTy;
1261}
1262
1264 Decl *ContextDecl,
1265 Qualifiers CXXThisTypeQuals,
1266 bool Enabled)
1267 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1268{
1269 if (!Enabled || !ContextDecl)
1270 return;
1271
1272 CXXRecordDecl *Record = nullptr;
1273 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1274 Record = Template->getTemplatedDecl();
1275 else
1276 Record = cast<CXXRecordDecl>(ContextDecl);
1277
1279 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1280
1282 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1283
1284 this->Enabled = true;
1285}
1286
1287
1289 if (Enabled) {
1290 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1291 }
1292}
1293
1295 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1296 assert(!LSI->isCXXThisCaptured());
1297 // [=, this] {}; // until C++20: Error: this when = is the default
1299 !Sema.getLangOpts().CPlusPlus20)
1300 return;
1301 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1303 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1304}
1305
1306bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1307 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1308 const bool ByCopy) {
1309 // We don't need to capture this in an unevaluated context.
1310 if (isUnevaluatedContext() && !Explicit)
1311 return true;
1312
1313 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1314
1315 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1316 ? *FunctionScopeIndexToStopAt
1317 : FunctionScopes.size() - 1;
1318
1319 // Check that we can capture the *enclosing object* (referred to by '*this')
1320 // by the capturing-entity/closure (lambda/block/etc) at
1321 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1322
1323 // Note: The *enclosing object* can only be captured by-value by a
1324 // closure that is a lambda, using the explicit notation:
1325 // [*this] { ... }.
1326 // Every other capture of the *enclosing object* results in its by-reference
1327 // capture.
1328
1329 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1330 // stack), we can capture the *enclosing object* only if:
1331 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1332 // - or, 'L' has an implicit capture.
1333 // AND
1334 // -- there is no enclosing closure
1335 // -- or, there is some enclosing closure 'E' that has already captured the
1336 // *enclosing object*, and every intervening closure (if any) between 'E'
1337 // and 'L' can implicitly capture the *enclosing object*.
1338 // -- or, every enclosing closure can implicitly capture the
1339 // *enclosing object*
1340
1341
1342 unsigned NumCapturingClosures = 0;
1343 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1344 if (CapturingScopeInfo *CSI =
1345 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1346 if (CSI->CXXThisCaptureIndex != 0) {
1347 // 'this' is already being captured; there isn't anything more to do.
1348 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1349 break;
1350 }
1351 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1353 // This context can't implicitly capture 'this'; fail out.
1354 if (BuildAndDiagnose) {
1356 Diag(Loc, diag::err_this_capture)
1357 << (Explicit && idx == MaxFunctionScopesIndex);
1358 if (!Explicit)
1359 buildLambdaThisCaptureFixit(*this, LSI);
1360 }
1361 return true;
1362 }
1363 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1364 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1365 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1366 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1367 (Explicit && idx == MaxFunctionScopesIndex)) {
1368 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1369 // iteration through can be an explicit capture, all enclosing closures,
1370 // if any, must perform implicit captures.
1371
1372 // This closure can capture 'this'; continue looking upwards.
1373 NumCapturingClosures++;
1374 continue;
1375 }
1376 // This context can't implicitly capture 'this'; fail out.
1377 if (BuildAndDiagnose) {
1379 Diag(Loc, diag::err_this_capture)
1380 << (Explicit && idx == MaxFunctionScopesIndex);
1381 }
1382 if (!Explicit)
1383 buildLambdaThisCaptureFixit(*this, LSI);
1384 return true;
1385 }
1386 break;
1387 }
1388 if (!BuildAndDiagnose) return false;
1389
1390 // If we got here, then the closure at MaxFunctionScopesIndex on the
1391 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1392 // (including implicit by-reference captures in any enclosing closures).
1393
1394 // In the loop below, respect the ByCopy flag only for the closure requesting
1395 // the capture (i.e. first iteration through the loop below). Ignore it for
1396 // all enclosing closure's up to NumCapturingClosures (since they must be
1397 // implicitly capturing the *enclosing object* by reference (see loop
1398 // above)).
1399 assert((!ByCopy ||
1400 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1401 "Only a lambda can capture the enclosing object (referred to by "
1402 "*this) by copy");
1403 QualType ThisTy = getCurrentThisType();
1404 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1405 --idx, --NumCapturingClosures) {
1406 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1407
1408 // The type of the corresponding data member (not a 'this' pointer if 'by
1409 // copy').
1410 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1411
1412 bool isNested = NumCapturingClosures > 1;
1413 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1414 }
1415 return false;
1416}
1417
1419 // C++20 [expr.prim.this]p1:
1420 // The keyword this names a pointer to the object for which an
1421 // implicit object member function is invoked or a non-static
1422 // data member's initializer is evaluated.
1423 QualType ThisTy = getCurrentThisType();
1424
1425 if (CheckCXXThisType(Loc, ThisTy))
1426 return ExprError();
1427
1428 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1429}
1430
1432 if (!Type.isNull())
1433 return false;
1434
1435 // C++20 [expr.prim.this]p3:
1436 // If a declaration declares a member function or member function template
1437 // of a class X, the expression this is a prvalue of type
1438 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1439 // the optional cv-qualifier-seq and the end of the function-definition,
1440 // member-declarator, or declarator. It shall not appear within the
1441 // declaration of either a static member function or an explicit object
1442 // member function of the current class (although its type and value
1443 // category are defined within such member functions as they are within
1444 // an implicit object member function).
1446 if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1447 Method && Method->isExplicitObjectMemberFunction()) {
1448 Diag(Loc, diag::err_invalid_this_use) << 1;
1450 Diag(Loc, diag::err_invalid_this_use) << 1;
1451 } else {
1452 Diag(Loc, diag::err_invalid_this_use) << 0;
1453 }
1454 return true;
1455}
1456
1458 bool IsImplicit) {
1459 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1460 MarkThisReferenced(This);
1461 return This;
1462}
1463
1465 CheckCXXThisCapture(This->getExprLoc());
1466 if (This->isTypeDependent())
1467 return;
1468
1469 // Check if 'this' is captured by value in a lambda with a dependent explicit
1470 // object parameter, and mark it as type-dependent as well if so.
1471 auto IsDependent = [&]() {
1472 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1473 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1474 if (!LSI)
1475 continue;
1476
1477 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1478 LSI->AfterParameterList)
1479 return false;
1480
1481 // If this lambda captures 'this' by value, then 'this' is dependent iff
1482 // this lambda has a dependent explicit object parameter. If we can't
1483 // determine whether it does (e.g. because the CXXMethodDecl's type is
1484 // null), assume it doesn't.
1485 if (LSI->isCXXThisCaptured()) {
1486 if (!LSI->getCXXThisCapture().isCopyCapture())
1487 continue;
1488
1489 const auto *MD = LSI->CallOperator;
1490 if (MD->getType().isNull())
1491 return false;
1492
1493 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1494 return Ty && MD->isExplicitObjectMemberFunction() &&
1495 Ty->getParamType(0)->isDependentType();
1496 }
1497 }
1498 return false;
1499 }();
1500
1501 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1502}
1503
1505 // If we're outside the body of a member function, then we'll have a specified
1506 // type for 'this'.
1508 return false;
1509
1510 // Determine whether we're looking into a class that's currently being
1511 // defined.
1512 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1513 return Class && Class->isBeingDefined();
1514}
1515
1516/// Parse construction of a specified type.
1517/// Can be interpreted either as function-style casting ("int(x)")
1518/// or class type construction ("ClassType(x,y,z)")
1519/// or creation of a value-initialized type ("int()").
1522 SourceLocation LParenOrBraceLoc,
1523 MultiExprArg exprs,
1524 SourceLocation RParenOrBraceLoc,
1525 bool ListInitialization) {
1526 if (!TypeRep)
1527 return ExprError();
1528
1529 TypeSourceInfo *TInfo;
1530 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1531 if (!TInfo)
1533
1534 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1535 RParenOrBraceLoc, ListInitialization);
1536 // Avoid creating a non-type-dependent expression that contains typos.
1537 // Non-type-dependent expressions are liable to be discarded without
1538 // checking for embedded typos.
1539 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1540 !Result.get()->isTypeDependent())
1542 else if (Result.isInvalid())
1544 RParenOrBraceLoc, exprs, Ty);
1545 return Result;
1546}
1547
1550 SourceLocation LParenOrBraceLoc,
1551 MultiExprArg Exprs,
1552 SourceLocation RParenOrBraceLoc,
1553 bool ListInitialization) {
1554 QualType Ty = TInfo->getType();
1555 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1556
1557 assert((!ListInitialization || Exprs.size() == 1) &&
1558 "List initialization must have exactly one expression.");
1559 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1560
1561 InitializedEntity Entity =
1563 InitializationKind Kind =
1564 Exprs.size()
1565 ? ListInitialization
1567 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1568 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1569 RParenOrBraceLoc)
1570 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1571 RParenOrBraceLoc);
1572
1573 // C++17 [expr.type.conv]p1:
1574 // If the type is a placeholder for a deduced class type, [...perform class
1575 // template argument deduction...]
1576 // C++23:
1577 // Otherwise, if the type contains a placeholder type, it is replaced by the
1578 // type determined by placeholder type deduction.
1579 DeducedType *Deduced = Ty->getContainedDeducedType();
1580 if (Deduced && !Deduced->isDeduced() &&
1581 isa<DeducedTemplateSpecializationType>(Deduced)) {
1583 Kind, Exprs);
1584 if (Ty.isNull())
1585 return ExprError();
1586 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1587 } else if (Deduced && !Deduced->isDeduced()) {
1588 MultiExprArg Inits = Exprs;
1589 if (ListInitialization) {
1590 auto *ILE = cast<InitListExpr>(Exprs[0]);
1591 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1592 }
1593
1594 if (Inits.empty())
1595 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1596 << Ty << FullRange);
1597 if (Inits.size() > 1) {
1598 Expr *FirstBad = Inits[1];
1599 return ExprError(Diag(FirstBad->getBeginLoc(),
1600 diag::err_auto_expr_init_multiple_expressions)
1601 << Ty << FullRange);
1602 }
1603 if (getLangOpts().CPlusPlus23) {
1604 if (Ty->getAs<AutoType>())
1605 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1606 }
1607 Expr *Deduce = Inits[0];
1608 if (isa<InitListExpr>(Deduce))
1609 return ExprError(
1610 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1611 << ListInitialization << Ty << FullRange);
1613 TemplateDeductionInfo Info(Deduce->getExprLoc());
1615 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1618 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1619 << Ty << Deduce->getType() << FullRange
1620 << Deduce->getSourceRange());
1621 if (DeducedType.isNull()) {
1623 return ExprError();
1624 }
1625
1626 Ty = DeducedType;
1627 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1628 }
1629
1632 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1633 RParenOrBraceLoc, ListInitialization);
1634
1635 // C++ [expr.type.conv]p1:
1636 // If the expression list is a parenthesized single expression, the type
1637 // conversion expression is equivalent (in definedness, and if defined in
1638 // meaning) to the corresponding cast expression.
1639 if (Exprs.size() == 1 && !ListInitialization &&
1640 !isa<InitListExpr>(Exprs[0])) {
1641 Expr *Arg = Exprs[0];
1642 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1643 RParenOrBraceLoc);
1644 }
1645
1646 // For an expression of the form T(), T shall not be an array type.
1647 QualType ElemTy = Ty;
1648 if (Ty->isArrayType()) {
1649 if (!ListInitialization)
1650 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1651 << FullRange);
1652 ElemTy = Context.getBaseElementType(Ty);
1653 }
1654
1655 // Only construct objects with object types.
1656 // The standard doesn't explicitly forbid function types here, but that's an
1657 // obvious oversight, as there's no way to dynamically construct a function
1658 // in general.
1659 if (Ty->isFunctionType())
1660 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1661 << Ty << FullRange);
1662
1663 // C++17 [expr.type.conv]p2:
1664 // If the type is cv void and the initializer is (), the expression is a
1665 // prvalue of the specified type that performs no initialization.
1666 if (!Ty->isVoidType() &&
1667 RequireCompleteType(TyBeginLoc, ElemTy,
1668 diag::err_invalid_incomplete_type_use, FullRange))
1669 return ExprError();
1670
1671 // Otherwise, the expression is a prvalue of the specified type whose
1672 // result object is direct-initialized (11.6) with the initializer.
1673 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1674 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1675
1676 if (Result.isInvalid())
1677 return Result;
1678
1679 Expr *Inner = Result.get();
1680 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1681 Inner = BTE->getSubExpr();
1682 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1683 CE && CE->isImmediateInvocation())
1684 Inner = CE->getSubExpr();
1685 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1686 !isa<CXXScalarValueInitExpr>(Inner)) {
1687 // If we created a CXXTemporaryObjectExpr, that node also represents the
1688 // functional cast. Otherwise, create an explicit cast to represent
1689 // the syntactic form of a functional-style cast that was used here.
1690 //
1691 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1692 // would give a more consistent AST representation than using a
1693 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1694 // is sometimes handled by initialization and sometimes not.
1695 QualType ResultType = Result.get()->getType();
1696 SourceRange Locs = ListInitialization
1697 ? SourceRange()
1698 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1700 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1701 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1702 Locs.getBegin(), Locs.getEnd());
1703 }
1704
1705 return Result;
1706}
1707
1709 // [CUDA] Ignore this function, if we can't call it.
1710 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1711 if (getLangOpts().CUDA) {
1712 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1713 // If it's not callable at all, it's not the right function.
1714 if (CallPreference < SemaCUDA::CFP_WrongSide)
1715 return false;
1716 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1717 // Maybe. We have to check if there are better alternatives.
1719 Method->getDeclContext()->lookup(Method->getDeclName());
1720 for (const auto *D : R) {
1721 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1722 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1723 return false;
1724 }
1725 }
1726 // We've found no better variants.
1727 }
1728 }
1729
1731 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1732
1733 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1734 return Result;
1735
1736 // In case of CUDA, return true if none of the 1-argument deallocator
1737 // functions are actually callable.
1738 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1739 assert(FD->getNumParams() == 1 &&
1740 "Only single-operand functions should be in PreventedBy");
1741 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1742 });
1743}
1744
1745/// Determine whether the given function is a non-placement
1746/// deallocation function.
1748 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1749 return S.isUsualDeallocationFunction(Method);
1750
1751 if (FD->getOverloadedOperator() != OO_Delete &&
1752 FD->getOverloadedOperator() != OO_Array_Delete)
1753 return false;
1754
1755 unsigned UsualParams = 1;
1756
1757 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1759 FD->getParamDecl(UsualParams)->getType(),
1760 S.Context.getSizeType()))
1761 ++UsualParams;
1762
1763 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1765 FD->getParamDecl(UsualParams)->getType(),
1767 ++UsualParams;
1768
1769 return UsualParams == FD->getNumParams();
1770}
1771
1772namespace {
1773 struct UsualDeallocFnInfo {
1774 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1775 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1776 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1777 Destroying(false), HasSizeT(false), HasAlignValT(false),
1778 CUDAPref(SemaCUDA::CFP_Native) {
1779 // A function template declaration is never a usual deallocation function.
1780 if (!FD)
1781 return;
1782 unsigned NumBaseParams = 1;
1783 if (FD->isDestroyingOperatorDelete()) {
1784 Destroying = true;
1785 ++NumBaseParams;
1786 }
1787
1788 if (NumBaseParams < FD->getNumParams() &&
1790 FD->getParamDecl(NumBaseParams)->getType(),
1791 S.Context.getSizeType())) {
1792 ++NumBaseParams;
1793 HasSizeT = true;
1794 }
1795
1796 if (NumBaseParams < FD->getNumParams() &&
1797 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1798 ++NumBaseParams;
1799 HasAlignValT = true;
1800 }
1801
1802 // In CUDA, determine how much we'd like / dislike to call this.
1803 if (S.getLangOpts().CUDA)
1804 CUDAPref = S.CUDA().IdentifyPreference(
1805 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1806 }
1807
1808 explicit operator bool() const { return FD; }
1809
1810 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1811 bool WantAlign) const {
1812 // C++ P0722:
1813 // A destroying operator delete is preferred over a non-destroying
1814 // operator delete.
1815 if (Destroying != Other.Destroying)
1816 return Destroying;
1817
1818 // C++17 [expr.delete]p10:
1819 // If the type has new-extended alignment, a function with a parameter
1820 // of type std::align_val_t is preferred; otherwise a function without
1821 // such a parameter is preferred
1822 if (HasAlignValT != Other.HasAlignValT)
1823 return HasAlignValT == WantAlign;
1824
1825 if (HasSizeT != Other.HasSizeT)
1826 return HasSizeT == WantSize;
1827
1828 // Use CUDA call preference as a tiebreaker.
1829 return CUDAPref > Other.CUDAPref;
1830 }
1831
1832 DeclAccessPair Found;
1833 FunctionDecl *FD;
1834 bool Destroying, HasSizeT, HasAlignValT;
1836 };
1837}
1838
1839/// Determine whether a type has new-extended alignment. This may be called when
1840/// the type is incomplete (for a delete-expression with an incomplete pointee
1841/// type), in which case it will conservatively return false if the alignment is
1842/// not known.
1843static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1844 return S.getLangOpts().AlignedAllocation &&
1845 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1847}
1848
1849/// Select the correct "usual" deallocation function to use from a selection of
1850/// deallocation functions (either global or class-scope).
1851static UsualDeallocFnInfo resolveDeallocationOverload(
1852 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1853 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1854 UsualDeallocFnInfo Best;
1855
1856 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1857 UsualDeallocFnInfo Info(S, I.getPair());
1858 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1859 Info.CUDAPref == SemaCUDA::CFP_Never)
1860 continue;
1861
1862 if (!Best) {
1863 Best = Info;
1864 if (BestFns)
1865 BestFns->push_back(Info);
1866 continue;
1867 }
1868
1869 if (Best.isBetterThan(Info, WantSize, WantAlign))
1870 continue;
1871
1872 // If more than one preferred function is found, all non-preferred
1873 // functions are eliminated from further consideration.
1874 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1875 BestFns->clear();
1876
1877 Best = Info;
1878 if (BestFns)
1879 BestFns->push_back(Info);
1880 }
1881
1882 return Best;
1883}
1884
1885/// Determine whether a given type is a class for which 'delete[]' would call
1886/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1887/// we need to store the array size (even if the type is
1888/// trivially-destructible).
1890 QualType allocType) {
1891 const RecordType *record =
1892 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1893 if (!record) return false;
1894
1895 // Try to find an operator delete[] in class scope.
1896
1897 DeclarationName deleteName =
1898 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1899 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1900 S.LookupQualifiedName(ops, record->getDecl());
1901
1902 // We're just doing this for information.
1903 ops.suppressDiagnostics();
1904
1905 // Very likely: there's no operator delete[].
1906 if (ops.empty()) return false;
1907
1908 // If it's ambiguous, it should be illegal to call operator delete[]
1909 // on this thing, so it doesn't matter if we allocate extra space or not.
1910 if (ops.isAmbiguous()) return false;
1911
1912 // C++17 [expr.delete]p10:
1913 // If the deallocation functions have class scope, the one without a
1914 // parameter of type std::size_t is selected.
1915 auto Best = resolveDeallocationOverload(
1916 S, ops, /*WantSize*/false,
1917 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1918 return Best && Best.HasSizeT;
1919}
1920
1921/// Parsed a C++ 'new' expression (C++ 5.3.4).
1922///
1923/// E.g.:
1924/// @code new (memory) int[size][4] @endcode
1925/// or
1926/// @code ::new Foo(23, "hello") @endcode
1927///
1928/// \param StartLoc The first location of the expression.
1929/// \param UseGlobal True if 'new' was prefixed with '::'.
1930/// \param PlacementLParen Opening paren of the placement arguments.
1931/// \param PlacementArgs Placement new arguments.
1932/// \param PlacementRParen Closing paren of the placement arguments.
1933/// \param TypeIdParens If the type is in parens, the source range.
1934/// \param D The type to be allocated, as well as array dimensions.
1935/// \param Initializer The initializing expression or initializer-list, or null
1936/// if there is none.
1938Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1939 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1940 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1942 std::optional<Expr *> ArraySize;
1943 // If the specified type is an array, unwrap it and save the expression.
1944 if (D.getNumTypeObjects() > 0 &&
1946 DeclaratorChunk &Chunk = D.getTypeObject(0);
1947 if (D.getDeclSpec().hasAutoTypeSpec())
1948 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1949 << D.getSourceRange());
1950 if (Chunk.Arr.hasStatic)
1951 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1952 << D.getSourceRange());
1953 if (!Chunk.Arr.NumElts && !Initializer)
1954 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1955 << D.getSourceRange());
1956
1957 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1959 }
1960
1961 // Every dimension shall be of constant size.
1962 if (ArraySize) {
1963 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1965 break;
1966
1968 if (Expr *NumElts = (Expr *)Array.NumElts) {
1969 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1970 // FIXME: GCC permits constant folding here. We should either do so consistently
1971 // or not do so at all, rather than changing behavior in C++14 onwards.
1972 if (getLangOpts().CPlusPlus14) {
1973 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1974 // shall be a converted constant expression (5.19) of type std::size_t
1975 // and shall evaluate to a strictly positive value.
1976 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1977 Array.NumElts
1980 .get();
1981 } else {
1982 Array.NumElts =
1984 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1985 .get();
1986 }
1987 if (!Array.NumElts)
1988 return ExprError();
1989 }
1990 }
1991 }
1992 }
1993
1995 QualType AllocType = TInfo->getType();
1996 if (D.isInvalidType())
1997 return ExprError();
1998
1999 SourceRange DirectInitRange;
2000 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
2001 DirectInitRange = List->getSourceRange();
2002
2003 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2004 PlacementLParen, PlacementArgs, PlacementRParen,
2005 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2006 Initializer);
2007}
2008
2010 Expr *Init, bool IsCPlusPlus20) {
2011 if (!Init)
2012 return true;
2013 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2014 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2015 if (isa<ImplicitValueInitExpr>(Init))
2016 return true;
2017 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2018 return !CCE->isListInitialization() &&
2019 CCE->getConstructor()->isDefaultConstructor();
2020 else if (Style == CXXNewInitializationStyle::Braces) {
2021 assert(isa<InitListExpr>(Init) &&
2022 "Shouldn't create list CXXConstructExprs for arrays.");
2023 return true;
2024 }
2025 return false;
2026}
2027
2028bool
2030 if (!getLangOpts().AlignedAllocationUnavailable)
2031 return false;
2032 if (FD.isDefined())
2033 return false;
2034 std::optional<unsigned> AlignmentParam;
2035 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2036 AlignmentParam)
2037 return true;
2038 return false;
2039}
2040
2041// Emit a diagnostic if an aligned allocation/deallocation function that is not
2042// implemented in the standard library is selected.
2044 SourceLocation Loc) {
2046 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2047 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2048 getASTContext().getTargetInfo().getPlatformName());
2049 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2050
2052 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2053 Diag(Loc, diag::err_aligned_allocation_unavailable)
2054 << IsDelete << FD.getType().getAsString() << OSName
2055 << OSVersion.getAsString() << OSVersion.empty();
2056 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2057 }
2058}
2059
2061 SourceLocation PlacementLParen,
2062 MultiExprArg PlacementArgs,
2063 SourceLocation PlacementRParen,
2064 SourceRange TypeIdParens, QualType AllocType,
2065 TypeSourceInfo *AllocTypeInfo,
2066 std::optional<Expr *> ArraySize,
2067 SourceRange DirectInitRange, Expr *Initializer) {
2068 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2069 SourceLocation StartLoc = Range.getBegin();
2070
2071 CXXNewInitializationStyle InitStyle;
2072 if (DirectInitRange.isValid()) {
2073 assert(Initializer && "Have parens but no initializer.");
2075 } else if (Initializer && isa<InitListExpr>(Initializer))
2077 else {
2078 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2079 isa<CXXConstructExpr>(Initializer)) &&
2080 "Initializer expression that cannot have been implicitly created.");
2082 }
2083
2084 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2085 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2086 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2087 "paren init for non-call init");
2088 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2089 }
2090
2091 // C++11 [expr.new]p15:
2092 // A new-expression that creates an object of type T initializes that
2093 // object as follows:
2094 InitializationKind Kind = [&] {
2095 switch (InitStyle) {
2096 // - If the new-initializer is omitted, the object is default-
2097 // initialized (8.5); if no initialization is performed,
2098 // the object has indeterminate value
2100 return InitializationKind::CreateDefault(TypeRange.getBegin());
2101 // - Otherwise, the new-initializer is interpreted according to the
2102 // initialization rules of 8.5 for direct-initialization.
2104 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2105 DirectInitRange.getBegin(),
2106 DirectInitRange.getEnd());
2109 Initializer->getBeginLoc(),
2110 Initializer->getEndLoc());
2111 }
2112 llvm_unreachable("Unknown initialization kind");
2113 }();
2114
2115 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2116 auto *Deduced = AllocType->getContainedDeducedType();
2117 if (Deduced && !Deduced->isDeduced() &&
2118 isa<DeducedTemplateSpecializationType>(Deduced)) {
2119 if (ArraySize)
2120 return ExprError(
2121 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2122 diag::err_deduced_class_template_compound_type)
2123 << /*array*/ 2
2124 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2125
2126 InitializedEntity Entity
2127 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2129 AllocTypeInfo, Entity, Kind, Exprs);
2130 if (AllocType.isNull())
2131 return ExprError();
2132 } else if (Deduced && !Deduced->isDeduced()) {
2133 MultiExprArg Inits = Exprs;
2134 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2135 if (Braced) {
2136 auto *ILE = cast<InitListExpr>(Exprs[0]);
2137 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2138 }
2139
2140 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2141 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2142 << AllocType << TypeRange);
2143 if (Inits.size() > 1) {
2144 Expr *FirstBad = Inits[1];
2145 return ExprError(Diag(FirstBad->getBeginLoc(),
2146 diag::err_auto_new_ctor_multiple_expressions)
2147 << AllocType << TypeRange);
2148 }
2149 if (Braced && !getLangOpts().CPlusPlus17)
2150 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2151 << AllocType << TypeRange;
2152 Expr *Deduce = Inits[0];
2153 if (isa<InitListExpr>(Deduce))
2154 return ExprError(
2155 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2156 << Braced << AllocType << TypeRange);
2158 TemplateDeductionInfo Info(Deduce->getExprLoc());
2160 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2163 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2164 << AllocType << Deduce->getType() << TypeRange
2165 << Deduce->getSourceRange());
2166 if (DeducedType.isNull()) {
2168 return ExprError();
2169 }
2170 AllocType = DeducedType;
2171 }
2172
2173 // Per C++0x [expr.new]p5, the type being constructed may be a
2174 // typedef of an array type.
2175 if (!ArraySize) {
2176 if (const ConstantArrayType *Array
2177 = Context.getAsConstantArrayType(AllocType)) {
2178 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2180 TypeRange.getEnd());
2181 AllocType = Array->getElementType();
2182 }
2183 }
2184
2185 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2186 return ExprError();
2187
2188 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2189 return ExprError();
2190
2191 // In ARC, infer 'retaining' for the allocated
2192 if (getLangOpts().ObjCAutoRefCount &&
2193 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2194 AllocType->isObjCLifetimeType()) {
2195 AllocType = Context.getLifetimeQualifiedType(AllocType,
2196 AllocType->getObjCARCImplicitLifetime());
2197 }
2198
2199 QualType ResultType = Context.getPointerType(AllocType);
2200
2201 if (ArraySize && *ArraySize &&
2202 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2203 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2204 if (result.isInvalid()) return ExprError();
2205 ArraySize = result.get();
2206 }
2207 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2208 // integral or enumeration type with a non-negative value."
2209 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2210 // enumeration type, or a class type for which a single non-explicit
2211 // conversion function to integral or unscoped enumeration type exists.
2212 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2213 // std::size_t.
2214 std::optional<uint64_t> KnownArraySize;
2215 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2216 ExprResult ConvertedSize;
2217 if (getLangOpts().CPlusPlus14) {
2218 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2219
2220 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2222
2223 if (!ConvertedSize.isInvalid() &&
2224 (*ArraySize)->getType()->getAs<RecordType>())
2225 // Diagnose the compatibility of this conversion.
2226 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2227 << (*ArraySize)->getType() << 0 << "'size_t'";
2228 } else {
2229 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2230 protected:
2231 Expr *ArraySize;
2232
2233 public:
2234 SizeConvertDiagnoser(Expr *ArraySize)
2235 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2236 ArraySize(ArraySize) {}
2237
2238 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2239 QualType T) override {
2240 return S.Diag(Loc, diag::err_array_size_not_integral)
2241 << S.getLangOpts().CPlusPlus11 << T;
2242 }
2243
2244 SemaDiagnosticBuilder diagnoseIncomplete(
2245 Sema &S, SourceLocation Loc, QualType T) override {
2246 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2247 << T << ArraySize->getSourceRange();
2248 }
2249
2250 SemaDiagnosticBuilder diagnoseExplicitConv(
2251 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2252 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2253 }
2254
2255 SemaDiagnosticBuilder noteExplicitConv(
2256 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2257 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2258 << ConvTy->isEnumeralType() << ConvTy;
2259 }
2260
2261 SemaDiagnosticBuilder diagnoseAmbiguous(
2262 Sema &S, SourceLocation Loc, QualType T) override {
2263 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2264 }
2265
2266 SemaDiagnosticBuilder noteAmbiguous(
2267 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2268 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2269 << ConvTy->isEnumeralType() << ConvTy;
2270 }
2271
2272 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2273 QualType T,
2274 QualType ConvTy) override {
2275 return S.Diag(Loc,
2276 S.getLangOpts().CPlusPlus11
2277 ? diag::warn_cxx98_compat_array_size_conversion
2278 : diag::ext_array_size_conversion)
2279 << T << ConvTy->isEnumeralType() << ConvTy;
2280 }
2281 } SizeDiagnoser(*ArraySize);
2282
2283 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2284 SizeDiagnoser);
2285 }
2286 if (ConvertedSize.isInvalid())
2287 return ExprError();
2288
2289 ArraySize = ConvertedSize.get();
2290 QualType SizeType = (*ArraySize)->getType();
2291
2292 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2293 return ExprError();
2294
2295 // C++98 [expr.new]p7:
2296 // The expression in a direct-new-declarator shall have integral type
2297 // with a non-negative value.
2298 //
2299 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2300 // per CWG1464. Otherwise, if it's not a constant, we must have an
2301 // unparenthesized array type.
2302
2303 // We've already performed any required implicit conversion to integer or
2304 // unscoped enumeration type.
2305 // FIXME: Per CWG1464, we are required to check the value prior to
2306 // converting to size_t. This will never find a negative array size in
2307 // C++14 onwards, because Value is always unsigned here!
2308 if (std::optional<llvm::APSInt> Value =
2309 (*ArraySize)->getIntegerConstantExpr(Context)) {
2310 if (Value->isSigned() && Value->isNegative()) {
2311 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2312 diag::err_typecheck_negative_array_size)
2313 << (*ArraySize)->getSourceRange());
2314 }
2315
2316 if (!AllocType->isDependentType()) {
2317 unsigned ActiveSizeBits =
2319 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2320 return ExprError(
2321 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2322 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2323 }
2324
2325 KnownArraySize = Value->getZExtValue();
2326 } else if (TypeIdParens.isValid()) {
2327 // Can't have dynamic array size when the type-id is in parentheses.
2328 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2329 << (*ArraySize)->getSourceRange()
2330 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2331 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2332
2333 TypeIdParens = SourceRange();
2334 }
2335
2336 // Note that we do *not* convert the argument in any way. It can
2337 // be signed, larger than size_t, whatever.
2338 }
2339
2340 FunctionDecl *OperatorNew = nullptr;
2341 FunctionDecl *OperatorDelete = nullptr;
2342 unsigned Alignment =
2343 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2344 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2345 bool PassAlignment = getLangOpts().AlignedAllocation &&
2346 Alignment > NewAlignment;
2347
2348 if (CheckArgsForPlaceholders(PlacementArgs))
2349 return ExprError();
2350
2352 if (!AllocType->isDependentType() &&
2353 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2355 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2356 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2357 OperatorNew, OperatorDelete))
2358 return ExprError();
2359
2360 // If this is an array allocation, compute whether the usual array
2361 // deallocation function for the type has a size_t parameter.
2362 bool UsualArrayDeleteWantsSize = false;
2363 if (ArraySize && !AllocType->isDependentType())
2364 UsualArrayDeleteWantsSize =
2365 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2366
2367 SmallVector<Expr *, 8> AllPlaceArgs;
2368 if (OperatorNew) {
2369 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2370 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2372
2373 // We've already converted the placement args, just fill in any default
2374 // arguments. Skip the first parameter because we don't have a corresponding
2375 // argument. Skip the second parameter too if we're passing in the
2376 // alignment; we've already filled it in.
2377 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2378 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2379 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2380 CallType))
2381 return ExprError();
2382
2383 if (!AllPlaceArgs.empty())
2384 PlacementArgs = AllPlaceArgs;
2385
2386 // We would like to perform some checking on the given `operator new` call,
2387 // but the PlacementArgs does not contain the implicit arguments,
2388 // namely allocation size and maybe allocation alignment,
2389 // so we need to conjure them.
2390
2391 QualType SizeTy = Context.getSizeType();
2392 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2393
2394 llvm::APInt SingleEltSize(
2395 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2396
2397 // How many bytes do we want to allocate here?
2398 std::optional<llvm::APInt> AllocationSize;
2399 if (!ArraySize && !AllocType->isDependentType()) {
2400 // For non-array operator new, we only want to allocate one element.
2401 AllocationSize = SingleEltSize;
2402 } else if (KnownArraySize && !AllocType->isDependentType()) {
2403 // For array operator new, only deal with static array size case.
2404 bool Overflow;
2405 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2406 .umul_ov(SingleEltSize, Overflow);
2407 (void)Overflow;
2408 assert(
2409 !Overflow &&
2410 "Expected that all the overflows would have been handled already.");
2411 }
2412
2413 IntegerLiteral AllocationSizeLiteral(
2414 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2415 SizeTy, SourceLocation());
2416 // Otherwise, if we failed to constant-fold the allocation size, we'll
2417 // just give up and pass-in something opaque, that isn't a null pointer.
2418 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2419 OK_Ordinary, /*SourceExpr=*/nullptr);
2420
2421 // Let's synthesize the alignment argument in case we will need it.
2422 // Since we *really* want to allocate these on stack, this is slightly ugly
2423 // because there might not be a `std::align_val_t` type.
2425 QualType AlignValT =
2427 IntegerLiteral AlignmentLiteral(
2428 Context,
2429 llvm::APInt(Context.getTypeSize(SizeTy),
2430 Alignment / Context.getCharWidth()),
2431 SizeTy, SourceLocation());
2432 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2433 CK_IntegralCast, &AlignmentLiteral,
2435
2436 // Adjust placement args by prepending conjured size and alignment exprs.
2438 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2439 CallArgs.emplace_back(AllocationSize
2440 ? static_cast<Expr *>(&AllocationSizeLiteral)
2441 : &OpaqueAllocationSize);
2442 if (PassAlignment)
2443 CallArgs.emplace_back(&DesiredAlignment);
2444 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2445
2446 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2447
2448 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2449 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2450
2451 // Warn if the type is over-aligned and is being allocated by (unaligned)
2452 // global operator new.
2453 if (PlacementArgs.empty() && !PassAlignment &&
2454 (OperatorNew->isImplicit() ||
2455 (OperatorNew->getBeginLoc().isValid() &&
2456 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2457 if (Alignment > NewAlignment)
2458 Diag(StartLoc, diag::warn_overaligned_type)
2459 << AllocType
2460 << unsigned(Alignment / Context.getCharWidth())
2461 << unsigned(NewAlignment / Context.getCharWidth());
2462 }
2463 }
2464
2465 // Array 'new' can't have any initializers except empty parentheses.
2466 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2467 // dialect distinction.
2468 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2470 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2471 Exprs.back()->getEndLoc());
2472 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2473 return ExprError();
2474 }
2475
2476 // If we can perform the initialization, and we've not already done so,
2477 // do it now.
2478 if (!AllocType->isDependentType() &&
2480 // The type we initialize is the complete type, including the array bound.
2481 QualType InitType;
2482 if (KnownArraySize)
2483 InitType = Context.getConstantArrayType(
2484 AllocType,
2485 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2486 *KnownArraySize),
2487 *ArraySize, ArraySizeModifier::Normal, 0);
2488 else if (ArraySize)
2489 InitType = Context.getIncompleteArrayType(AllocType,
2491 else
2492 InitType = AllocType;
2493
2494 InitializedEntity Entity
2495 = InitializedEntity::InitializeNew(StartLoc, InitType);
2496 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2497 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2498 if (FullInit.isInvalid())
2499 return ExprError();
2500
2501 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2502 // we don't want the initialized object to be destructed.
2503 // FIXME: We should not create these in the first place.
2504 if (CXXBindTemporaryExpr *Binder =
2505 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2506 FullInit = Binder->getSubExpr();
2507
2508 Initializer = FullInit.get();
2509
2510 // FIXME: If we have a KnownArraySize, check that the array bound of the
2511 // initializer is no greater than that constant value.
2512
2513 if (ArraySize && !*ArraySize) {
2514 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2515 if (CAT) {
2516 // FIXME: Track that the array size was inferred rather than explicitly
2517 // specified.
2518 ArraySize = IntegerLiteral::Create(
2519 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2520 } else {
2521 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2522 << Initializer->getSourceRange();
2523 }
2524 }
2525 }
2526
2527 // Mark the new and delete operators as referenced.
2528 if (OperatorNew) {
2529 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2530 return ExprError();
2531 MarkFunctionReferenced(StartLoc, OperatorNew);
2532 }
2533 if (OperatorDelete) {
2534 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2535 return ExprError();
2536 MarkFunctionReferenced(StartLoc, OperatorDelete);
2537 }
2538
2539 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2540 PassAlignment, UsualArrayDeleteWantsSize,
2541 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2542 Initializer, ResultType, AllocTypeInfo, Range,
2543 DirectInitRange);
2544}
2545
2546/// Checks that a type is suitable as the allocated type
2547/// in a new-expression.
2549 SourceRange R) {
2550 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2551 // abstract class type or array thereof.
2552 if (AllocType->isFunctionType())
2553 return Diag(Loc, diag::err_bad_new_type)
2554 << AllocType << 0 << R;
2555 else if (AllocType->isReferenceType())
2556 return Diag(Loc, diag::err_bad_new_type)
2557 << AllocType << 1 << R;
2558 else if (!AllocType->isDependentType() &&
2560 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2561 return true;
2562 else if (RequireNonAbstractType(Loc, AllocType,
2563 diag::err_allocation_of_abstract_type))
2564 return true;
2565 else if (AllocType->isVariablyModifiedType())
2566 return Diag(Loc, diag::err_variably_modified_new_type)
2567 << AllocType;
2568 else if (AllocType.getAddressSpace() != LangAS::Default &&
2569 !getLangOpts().OpenCLCPlusPlus)
2570 return Diag(Loc, diag::err_address_space_qualified_new)
2571 << AllocType.getUnqualifiedType()
2573 else if (getLangOpts().ObjCAutoRefCount) {
2574 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2575 QualType BaseAllocType = Context.getBaseElementType(AT);
2576 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2577 BaseAllocType->isObjCLifetimeType())
2578 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2579 << BaseAllocType;
2580 }
2581 }
2582
2583 return false;
2584}
2585
2588 bool &PassAlignment, FunctionDecl *&Operator,
2589 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2590 OverloadCandidateSet Candidates(R.getNameLoc(),
2592 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2593 Alloc != AllocEnd; ++Alloc) {
2594 // Even member operator new/delete are implicitly treated as
2595 // static, so don't use AddMemberCandidate.
2596 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2597
2598 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2599 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2600 /*ExplicitTemplateArgs=*/nullptr, Args,
2601 Candidates,
2602 /*SuppressUserConversions=*/false);
2603 continue;
2604 }
2605
2606 FunctionDecl *Fn = cast<FunctionDecl>(D);
2607 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2608 /*SuppressUserConversions=*/false);
2609 }
2610
2611 // Do the resolution.
2613 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2614 case OR_Success: {
2615 // Got one!
2616 FunctionDecl *FnDecl = Best->Function;
2617 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2618 Best->FoundDecl) == Sema::AR_inaccessible)
2619 return true;
2620
2621 Operator = FnDecl;
2622 return false;
2623 }
2624
2626 // C++17 [expr.new]p13:
2627 // If no matching function is found and the allocated object type has
2628 // new-extended alignment, the alignment argument is removed from the
2629 // argument list, and overload resolution is performed again.
2630 if (PassAlignment) {
2631 PassAlignment = false;
2632 AlignArg = Args[1];
2633 Args.erase(Args.begin() + 1);
2634 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2635 Operator, &Candidates, AlignArg,
2636 Diagnose);
2637 }
2638
2639 // MSVC will fall back on trying to find a matching global operator new
2640 // if operator new[] cannot be found. Also, MSVC will leak by not
2641 // generating a call to operator delete or operator delete[], but we
2642 // will not replicate that bug.
2643 // FIXME: Find out how this interacts with the std::align_val_t fallback
2644 // once MSVC implements it.
2645 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2646 S.Context.getLangOpts().MSVCCompat) {
2647 R.clear();
2650 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2651 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2652 Operator, /*Candidates=*/nullptr,
2653 /*AlignArg=*/nullptr, Diagnose);
2654 }
2655
2656 if (Diagnose) {
2657 // If this is an allocation of the form 'new (p) X' for some object
2658 // pointer p (or an expression that will decay to such a pointer),
2659 // diagnose the missing inclusion of <new>.
2660 if (!R.isClassLookup() && Args.size() == 2 &&
2661 (Args[1]->getType()->isObjectPointerType() ||
2662 Args[1]->getType()->isArrayType())) {
2663 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2664 << R.getLookupName() << Range;
2665 // Listing the candidates is unlikely to be useful; skip it.
2666 return true;
2667 }
2668
2669 // Finish checking all candidates before we note any. This checking can
2670 // produce additional diagnostics so can't be interleaved with our
2671 // emission of notes.
2672 //
2673 // For an aligned allocation, separately check the aligned and unaligned
2674 // candidates with their respective argument lists.
2677 llvm::SmallVector<Expr*, 4> AlignedArgs;
2678 if (AlignedCandidates) {
2679 auto IsAligned = [](OverloadCandidate &C) {
2680 return C.Function->getNumParams() > 1 &&
2681 C.Function->getParamDecl(1)->getType()->isAlignValT();
2682 };
2683 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2684
2685 AlignedArgs.reserve(Args.size() + 1);
2686 AlignedArgs.push_back(Args[0]);
2687 AlignedArgs.push_back(AlignArg);
2688 AlignedArgs.append(Args.begin() + 1, Args.end());
2689 AlignedCands = AlignedCandidates->CompleteCandidates(
2690 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2691
2692 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2693 R.getNameLoc(), IsUnaligned);
2694 } else {
2695 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2696 R.getNameLoc());
2697 }
2698
2699 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2700 << R.getLookupName() << Range;
2701 if (AlignedCandidates)
2702 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2703 R.getNameLoc());
2704 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2705 }
2706 return true;
2707
2708 case OR_Ambiguous:
2709 if (Diagnose) {
2710 Candidates.NoteCandidates(
2712 S.PDiag(diag::err_ovl_ambiguous_call)
2713 << R.getLookupName() << Range),
2714 S, OCD_AmbiguousCandidates, Args);
2715 }
2716 return true;
2717
2718 case OR_Deleted: {
2719 if (Diagnose)
2721 Candidates, Best->Function, Args);
2722 return true;
2723 }
2724 }
2725 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2726}
2727
2729 AllocationFunctionScope NewScope,
2730 AllocationFunctionScope DeleteScope,
2731 QualType AllocType, bool IsArray,
2732 bool &PassAlignment, MultiExprArg PlaceArgs,
2733 FunctionDecl *&OperatorNew,
2734 FunctionDecl *&OperatorDelete,
2735 bool Diagnose) {
2736 // --- Choosing an allocation function ---
2737 // C++ 5.3.4p8 - 14 & 18
2738 // 1) If looking in AFS_Global scope for allocation functions, only look in
2739 // the global scope. Else, if AFS_Class, only look in the scope of the
2740 // allocated class. If AFS_Both, look in both.
2741 // 2) If an array size is given, look for operator new[], else look for
2742 // operator new.
2743 // 3) The first argument is always size_t. Append the arguments from the
2744 // placement form.
2745
2746 SmallVector<Expr*, 8> AllocArgs;
2747 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2748
2749 // We don't care about the actual value of these arguments.
2750 // FIXME: Should the Sema create the expression and embed it in the syntax
2751 // tree? Or should the consumer just recalculate the value?
2752 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2753 QualType SizeTy = Context.getSizeType();
2754 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2755 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2756 SourceLocation());
2757 AllocArgs.push_back(&Size);
2758
2759 QualType AlignValT = Context.VoidTy;
2760 if (PassAlignment) {
2763 }
2764 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2765 if (PassAlignment)
2766 AllocArgs.push_back(&Align);
2767
2768 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2769
2770 // C++ [expr.new]p8:
2771 // If the allocated type is a non-array type, the allocation
2772 // function's name is operator new and the deallocation function's
2773 // name is operator delete. If the allocated type is an array
2774 // type, the allocation function's name is operator new[] and the
2775 // deallocation function's name is operator delete[].
2777 IsArray ? OO_Array_New : OO_New);
2778
2779 QualType AllocElemType = Context.getBaseElementType(AllocType);
2780
2781 // Find the allocation function.
2782 {
2783 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2784
2785 // C++1z [expr.new]p9:
2786 // If the new-expression begins with a unary :: operator, the allocation
2787 // function's name is looked up in the global scope. Otherwise, if the
2788 // allocated type is a class type T or array thereof, the allocation
2789 // function's name is looked up in the scope of T.
2790 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2791 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2792
2793 // We can see ambiguity here if the allocation function is found in
2794 // multiple base classes.
2795 if (R.isAmbiguous())
2796 return true;
2797
2798 // If this lookup fails to find the name, or if the allocated type is not
2799 // a class type, the allocation function's name is looked up in the
2800 // global scope.
2801 if (R.empty()) {
2802 if (NewScope == AFS_Class)
2803 return true;
2804
2806 }
2807
2808 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2809 if (PlaceArgs.empty()) {
2810 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2811 } else {
2812 Diag(StartLoc, diag::err_openclcxx_placement_new);
2813 }
2814 return true;
2815 }
2816
2817 assert(!R.empty() && "implicitly declared allocation functions not found");
2818 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2819
2820 // We do our own custom access checks below.
2822
2823 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2824 OperatorNew, /*Candidates=*/nullptr,
2825 /*AlignArg=*/nullptr, Diagnose))
2826 return true;
2827 }
2828
2829 // We don't need an operator delete if we're running under -fno-exceptions.
2830 if (!getLangOpts().Exceptions) {
2831 OperatorDelete = nullptr;
2832 return false;
2833 }
2834
2835 // Note, the name of OperatorNew might have been changed from array to
2836 // non-array by resolveAllocationOverload.
2838 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2839 ? OO_Array_Delete
2840 : OO_Delete);
2841
2842 // C++ [expr.new]p19:
2843 //
2844 // If the new-expression begins with a unary :: operator, the
2845 // deallocation function's name is looked up in the global
2846 // scope. Otherwise, if the allocated type is a class type T or an
2847 // array thereof, the deallocation function's name is looked up in
2848 // the scope of T. If this lookup fails to find the name, or if
2849 // the allocated type is not a class type or array thereof, the
2850 // deallocation function's name is looked up in the global scope.
2851 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2852 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2853 auto *RD =
2854 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2855 LookupQualifiedName(FoundDelete, RD);
2856 }
2857 if (FoundDelete.isAmbiguous())
2858 return true; // FIXME: clean up expressions?
2859
2860 // Filter out any destroying operator deletes. We can't possibly call such a
2861 // function in this context, because we're handling the case where the object
2862 // was not successfully constructed.
2863 // FIXME: This is not covered by the language rules yet.
2864 {
2865 LookupResult::Filter Filter = FoundDelete.makeFilter();
2866 while (Filter.hasNext()) {
2867 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2868 if (FD && FD->isDestroyingOperatorDelete())
2869 Filter.erase();
2870 }
2871 Filter.done();
2872 }
2873
2874 bool FoundGlobalDelete = FoundDelete.empty();
2875 if (FoundDelete.empty()) {
2876 FoundDelete.clear(LookupOrdinaryName);
2877
2878 if (DeleteScope == AFS_Class)
2879 return true;
2880
2883 }
2884
2885 FoundDelete.suppressDiagnostics();
2886
2888
2889 // Whether we're looking for a placement operator delete is dictated
2890 // by whether we selected a placement operator new, not by whether
2891 // we had explicit placement arguments. This matters for things like
2892 // struct A { void *operator new(size_t, int = 0); ... };
2893 // A *a = new A()
2894 //
2895 // We don't have any definition for what a "placement allocation function"
2896 // is, but we assume it's any allocation function whose
2897 // parameter-declaration-clause is anything other than (size_t).
2898 //
2899 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2900 // This affects whether an exception from the constructor of an overaligned
2901 // type uses the sized or non-sized form of aligned operator delete.
2902 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2903 OperatorNew->isVariadic();
2904
2905 if (isPlacementNew) {
2906 // C++ [expr.new]p20:
2907 // A declaration of a placement deallocation function matches the
2908 // declaration of a placement allocation function if it has the
2909 // same number of parameters and, after parameter transformations
2910 // (8.3.5), all parameter types except the first are
2911 // identical. [...]
2912 //
2913 // To perform this comparison, we compute the function type that
2914 // the deallocation function should have, and use that type both
2915 // for template argument deduction and for comparison purposes.
2916 QualType ExpectedFunctionType;
2917 {
2918 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2919
2920 SmallVector<QualType, 4> ArgTypes;
2921 ArgTypes.push_back(Context.VoidPtrTy);
2922 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2923 ArgTypes.push_back(Proto->getParamType(I));
2924
2926 // FIXME: This is not part of the standard's rule.
2927 EPI.Variadic = Proto->isVariadic();
2928
2929 ExpectedFunctionType
2930 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2931 }
2932
2933 for (LookupResult::iterator D = FoundDelete.begin(),
2934 DEnd = FoundDelete.end();
2935 D != DEnd; ++D) {
2936 FunctionDecl *Fn = nullptr;
2937 if (FunctionTemplateDecl *FnTmpl =
2938 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2939 // Perform template argument deduction to try to match the
2940 // expected function type.
2941 TemplateDeductionInfo Info(StartLoc);
2942 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2944 continue;
2945 } else
2946 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2947
2949 ExpectedFunctionType,
2950 /*AdjustExcpetionSpec*/true),
2951 ExpectedFunctionType))
2952 Matches.push_back(std::make_pair(D.getPair(), Fn));
2953 }
2954
2955 if (getLangOpts().CUDA)
2956 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2957 Matches);
2958 } else {
2959 // C++1y [expr.new]p22:
2960 // For a non-placement allocation function, the normal deallocation
2961 // function lookup is used
2962 //
2963 // Per [expr.delete]p10, this lookup prefers a member operator delete
2964 // without a size_t argument, but prefers a non-member operator delete
2965 // with a size_t where possible (which it always is in this case).
2967 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2968 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2969 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2970 &BestDeallocFns);
2971 if (Selected)
2972 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2973 else {
2974 // If we failed to select an operator, all remaining functions are viable
2975 // but ambiguous.
2976 for (auto Fn : BestDeallocFns)
2977 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2978 }
2979 }
2980
2981 // C++ [expr.new]p20:
2982 // [...] If the lookup finds a single matching deallocation
2983 // function, that function will be called; otherwise, no
2984 // deallocation function will be called.
2985 if (Matches.size() == 1) {
2986 OperatorDelete = Matches[0].second;
2987
2988 // C++1z [expr.new]p23:
2989 // If the lookup finds a usual deallocation function (3.7.4.2)
2990 // with a parameter of type std::size_t and that function, considered
2991 // as a placement deallocation function, would have been
2992 // selected as a match for the allocation function, the program
2993 // is ill-formed.
2994 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2995 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2996 UsualDeallocFnInfo Info(*this,
2997 DeclAccessPair::make(OperatorDelete, AS_public));
2998 // Core issue, per mail to core reflector, 2016-10-09:
2999 // If this is a member operator delete, and there is a corresponding
3000 // non-sized member operator delete, this isn't /really/ a sized
3001 // deallocation function, it just happens to have a size_t parameter.
3002 bool IsSizedDelete = Info.HasSizeT;
3003 if (IsSizedDelete && !FoundGlobalDelete) {
3004 auto NonSizedDelete =
3005 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
3006 /*WantAlign*/Info.HasAlignValT);
3007 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
3008 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
3009 IsSizedDelete = false;
3010 }
3011
3012 if (IsSizedDelete) {
3013 SourceRange R = PlaceArgs.empty()
3014 ? SourceRange()
3015 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3016 PlaceArgs.back()->getEndLoc());
3017 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3018 if (!OperatorDelete->isImplicit())
3019 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3020 << DeleteName;
3021 }
3022 }
3023
3024 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
3025 Matches[0].first);
3026 } else if (!Matches.empty()) {
3027 // We found multiple suitable operators. Per [expr.new]p20, that means we
3028 // call no 'operator delete' function, but we should at least warn the user.
3029 // FIXME: Suppress this warning if the construction cannot throw.
3030 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3031 << DeleteName << AllocElemType;
3032
3033 for (auto &Match : Matches)
3034 Diag(Match.second->getLocation(),
3035 diag::note_member_declared_here) << DeleteName;
3036 }
3037
3038 return false;
3039}
3040
3041/// DeclareGlobalNewDelete - Declare the global forms of operator new and
3042/// delete. These are:
3043/// @code
3044/// // C++03:
3045/// void* operator new(std::size_t) throw(std::bad_alloc);
3046/// void* operator new[](std::size_t) throw(std::bad_alloc);
3047/// void operator delete(void *) throw();
3048/// void operator delete[](void *) throw();
3049/// // C++11:
3050/// void* operator new(std::size_t);
3051/// void* operator new[](std::size_t);
3052/// void operator delete(void *) noexcept;
3053/// void operator delete[](void *) noexcept;
3054/// // C++1y:
3055/// void* operator new(std::size_t);
3056/// void* operator new[](std::size_t);
3057/// void operator delete(void *) noexcept;
3058/// void operator delete[](void *) noexcept;
3059/// void operator delete(void *, std::size_t) noexcept;
3060/// void operator delete[](void *, std::size_t) noexcept;
3061/// @endcode
3062/// Note that the placement and nothrow forms of new are *not* implicitly
3063/// declared. Their use requires including <new>.
3066 return;
3067
3068 // The implicitly declared new and delete operators
3069 // are not supported in OpenCL.
3070 if (getLangOpts().OpenCLCPlusPlus)
3071 return;
3072
3073 // C++ [basic.stc.dynamic.general]p2:
3074 // The library provides default definitions for the global allocation
3075 // and deallocation functions. Some global allocation and deallocation
3076 // functions are replaceable ([new.delete]); these are attached to the
3077 // global module ([module.unit]).
3078 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3079 PushGlobalModuleFragment(SourceLocation());
3080
3081 // C++ [basic.std.dynamic]p2:
3082 // [...] The following allocation and deallocation functions (18.4) are
3083 // implicitly declared in global scope in each translation unit of a
3084 // program
3085 //
3086 // C++03:
3087 // void* operator new(std::size_t) throw(std::bad_alloc);
3088 // void* operator new[](std::size_t) throw(std::bad_alloc);
3089 // void operator delete(void*) throw();
3090 // void operator delete[](void*) throw();
3091 // C++11:
3092 // void* operator new(std::size_t);
3093 // void* operator new[](std::size_t);
3094 // void operator delete(void*) noexcept;
3095 // void operator delete[](void*) noexcept;
3096 // C++1y:
3097 // void* operator new(std::size_t);
3098 // void* operator new[](std::size_t);
3099 // void operator delete(void*) noexcept;
3100 // void operator delete[](void*) noexcept;
3101 // void operator delete(void*, std::size_t) noexcept;
3102 // void operator delete[](void*, std::size_t) noexcept;
3103 //
3104 // These implicit declarations introduce only the function names operator
3105 // new, operator new[], operator delete, operator delete[].
3106 //
3107 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3108 // "std" or "bad_alloc" as necessary to form the exception specification.
3109 // However, we do not make these implicit declarations visible to name
3110 // lookup.
3111 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3112 // The "std::bad_alloc" class has not yet been declared, so build it
3113 // implicitly.
3117 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3118 getStdBadAlloc()->setImplicit(true);
3119
3120 // The implicitly declared "std::bad_alloc" should live in global module
3121 // fragment.
3122 if (TheGlobalModuleFragment) {
3125 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3126 }
3127 }
3128 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3129 // The "std::align_val_t" enum class has not yet been declared, so build it
3130 // implicitly.
3131 auto *AlignValT = EnumDecl::Create(
3133 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3134
3135 // The implicitly declared "std::align_val_t" should live in global module
3136 // fragment.
3137 if (TheGlobalModuleFragment) {
3138 AlignValT->setModuleOwnershipKind(
3140 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3141 }
3142
3143 AlignValT->setIntegerType(Context.getSizeType());
3144 AlignValT->setPromotionType(Context.getSizeType());
3145 AlignValT->setImplicit(true);
3146
3147 StdAlignValT = AlignValT;
3148 }
3149
3151
3153 QualType SizeT = Context.getSizeType();
3154
3155 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3156 QualType Return, QualType Param) {
3158 Params.push_back(Param);
3159
3160 // Create up to four variants of the function (sized/aligned).
3161 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3162 (Kind == OO_Delete || Kind == OO_Array_Delete);
3163 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3164
3165 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3166 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3167 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3168 if (Sized)
3169 Params.push_back(SizeT);
3170
3171 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3172 if (Aligned)
3173 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3174
3176 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3177
3178 if (Aligned)
3179 Params.pop_back();
3180 }
3181 }
3182 };
3183
3184 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3185 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3186 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3187 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3188
3189 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3190 PopGlobalModuleFragment();
3191}
3192
3193/// DeclareGlobalAllocationFunction - Declares a single implicit global
3194/// allocation function if it doesn't already exist.
3196 QualType Return,
3197 ArrayRef<QualType> Params) {
3199
3200 // Check if this function is already declared.
3201 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3202 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3203 Alloc != AllocEnd; ++Alloc) {
3204 // Only look at non-template functions, as it is the predefined,
3205 // non-templated allocation function we are trying to declare here.
3206 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3207 if (Func->getNumParams() == Params.size()) {
3209 for (auto *P : Func->parameters())
3210 FuncParams.push_back(
3211 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3212 if (llvm::ArrayRef(FuncParams) == Params) {
3213 // Make the function visible to name lookup, even if we found it in
3214 // an unimported module. It either is an implicitly-declared global
3215 // allocation function, or is suppressing that function.
3216 Func->setVisibleDespiteOwningModule();
3217 return;
3218 }
3219 }
3220 }
3221 }
3222
3224 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3225
3226 QualType BadAllocType;
3227 bool HasBadAllocExceptionSpec
3228 = (Name.getCXXOverloadedOperator() == OO_New ||
3229 Name.getCXXOverloadedOperator() == OO_Array_New);
3230 if (HasBadAllocExceptionSpec) {
3231 if (!getLangOpts().CPlusPlus11) {
3232 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3233 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3235 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3236 }
3237 if (getLangOpts().NewInfallible) {
3239 }
3240 } else {
3241 EPI.ExceptionSpec =
3243 }
3244
3245 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3246 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3248 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3249 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3250 true);
3251 Alloc->setImplicit();
3252 // Global allocation functions should always be visible.
3254
3255 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3256 !getLangOpts().CheckNew)
3257 Alloc->addAttr(
3258 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3259
3260 // C++ [basic.stc.dynamic.general]p2:
3261 // The library provides default definitions for the global allocation
3262 // and deallocation functions. Some global allocation and deallocation
3263 // functions are replaceable ([new.delete]); these are attached to the
3264 // global module ([module.unit]).
3265 //
3266 // In the language wording, these functions are attched to the global
3267 // module all the time. But in the implementation, the global module
3268 // is only meaningful when we're in a module unit. So here we attach
3269 // these allocation functions to global module conditionally.
3270 if (TheGlobalModuleFragment) {
3273 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3274 }
3275
3277 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3279 ? VisibilityAttr::Hidden
3281 ? VisibilityAttr::Protected
3282 : VisibilityAttr::Default));
3283
3285 for (QualType T : Params) {
3286 ParamDecls.push_back(ParmVarDecl::Create(
3287 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3288 /*TInfo=*/nullptr, SC_None, nullptr));
3289 ParamDecls.back()->setImplicit();
3290 }
3291 Alloc->setParams(ParamDecls);
3292 if (ExtraAttr)
3293 Alloc->addAttr(ExtraAttr);
3296 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3297 };
3298
3299 if (!LangOpts.CUDA)
3300 CreateAllocationFunctionDecl(nullptr);
3301 else {
3302 // Host and device get their own declaration so each can be
3303 // defined or re-declared independently.
3304 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3305 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3306 }
3307}
3308
3310 bool CanProvideSize,
3311 bool Overaligned,
3312 DeclarationName Name) {
3314
3315 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3317
3318 // FIXME: It's possible for this to result in ambiguity, through a
3319 // user-declared variadic operator delete or the enable_if attribute. We
3320 // should probably not consider those cases to be usual deallocation
3321 // functions. But for now we just make an arbitrary choice in that case.
3322 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3323 Overaligned);
3324 assert(Result.FD && "operator delete missing from global scope?");
3325 return Result.FD;
3326}
3327
3329 CXXRecordDecl *RD) {
3331
3332 FunctionDecl *OperatorDelete = nullptr;
3333 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3334 return nullptr;
3335 if (OperatorDelete)
3336 return OperatorDelete;
3337
3338 // If there's no class-specific operator delete, look up the global
3339 // non-array delete.
3341 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3342 Name);
3343}
3344
3346 DeclarationName Name,
3347 FunctionDecl *&Operator, bool Diagnose,
3348 bool WantSize, bool WantAligned) {
3349 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3350 // Try to find operator delete/operator delete[] in class scope.
3351 LookupQualifiedName(Found, RD);
3352
3353 if (Found.isAmbiguous())
3354 return true;
3355
3356 Found.suppressDiagnostics();
3357
3358 bool Overaligned =
3359 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3360
3361 // C++17 [expr.delete]p10:
3362 // If the deallocation functions have class scope, the one without a
3363 // parameter of type std::size_t is selected.
3365 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3366 /*WantAlign*/ Overaligned, &Matches);
3367
3368 // If we could find an overload, use it.
3369 if (Matches.size() == 1) {
3370 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3371
3372 // FIXME: DiagnoseUseOfDecl?
3373 if (Operator->isDeleted()) {
3374 if (Diagnose) {
3375 StringLiteral *Msg = Operator->getDeletedMessage();
3376 Diag(StartLoc, diag::err_deleted_function_use)
3377 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3378 NoteDeletedFunction(Operator);
3379 }
3380 return true;
3381 }
3382
3383 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3384 Matches[0].Found, Diagnose) == AR_inaccessible)
3385 return true;
3386
3387 return false;
3388 }
3389
3390 // We found multiple suitable operators; complain about the ambiguity.
3391 // FIXME: The standard doesn't say to do this; it appears that the intent
3392 // is that this should never happen.
3393 if (!Matches.empty()) {
3394 if (Diagnose) {
3395 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3396 << Name << RD;
3397 for (auto &Match : Matches)
3398 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3399 }
3400 return true;
3401 }
3402
3403 // We did find operator delete/operator delete[] declarations, but
3404 // none of them were suitable.
3405 if (!Found.empty()) {
3406 if (Diagnose) {
3407 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3408 << Name << RD;
3409
3410 for (NamedDecl *D : Found)
3411 Diag(D->getUnderlyingDecl()->getLocation(),
3412 diag::note_member_declared_here) << Name;
3413 }
3414 return true;
3415 }
3416
3417 Operator = nullptr;
3418 return false;
3419}
3420
3421namespace {
3422/// Checks whether delete-expression, and new-expression used for
3423/// initializing deletee have the same array form.
3424class MismatchingNewDeleteDetector {
3425public:
3426 enum MismatchResult {
3427 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3428 NoMismatch,
3429 /// Indicates that variable is initialized with mismatching form of \a new.
3430 VarInitMismatches,
3431 /// Indicates that member is initialized with mismatching form of \a new.
3432 MemberInitMismatches,
3433 /// Indicates that 1 or more constructors' definitions could not been
3434 /// analyzed, and they will be checked again at the end of translation unit.
3435 AnalyzeLater
3436 };
3437
3438 /// \param EndOfTU True, if this is the final analysis at the end of
3439 /// translation unit. False, if this is the initial analysis at the point
3440 /// delete-expression was encountered.
3441 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3442 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3443 HasUndefinedConstructors(false) {}
3444
3445 /// Checks whether pointee of a delete-expression is initialized with
3446 /// matching form of new-expression.
3447 ///
3448 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3449 /// point where delete-expression is encountered, then a warning will be
3450 /// issued immediately. If return value is \c AnalyzeLater at the point where
3451 /// delete-expression is seen, then member will be analyzed at the end of
3452 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3453 /// couldn't be analyzed. If at least one constructor initializes the member
3454 /// with matching type of new, the return value is \c NoMismatch.
3455 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3456 /// Analyzes a class member.
3457 /// \param Field Class member to analyze.
3458 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3459 /// for deleting the \p Field.
3460 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3462 /// List of mismatching new-expressions used for initialization of the pointee
3464 /// Indicates whether delete-expression was in array form.
3465 bool IsArrayForm;
3466
3467private:
3468 const bool EndOfTU;
3469 /// Indicates that there is at least one constructor without body.
3470 bool HasUndefinedConstructors;
3471 /// Returns \c CXXNewExpr from given initialization expression.
3472 /// \param E Expression used for initializing pointee in delete-expression.
3473 /// E can be a single-element \c InitListExpr consisting of new-expression.
3474 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3475 /// Returns whether member is initialized with mismatching form of
3476 /// \c new either by the member initializer or in-class initialization.
3477 ///
3478 /// If bodies of all constructors are not visible at the end of translation
3479 /// unit or at least one constructor initializes member with the matching
3480 /// form of \c new, mismatch cannot be proven, and this function will return
3481 /// \c NoMismatch.
3482 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3483 /// Returns whether variable is initialized with mismatching form of
3484 /// \c new.
3485 ///
3486 /// If variable is initialized with matching form of \c new or variable is not
3487 /// initialized with a \c new expression, this function will return true.
3488 /// If variable is initialized with mismatching form of \c new, returns false.
3489 /// \param D Variable to analyze.
3490 bool hasMatchingVarInit(const DeclRefExpr *D);
3491 /// Checks whether the constructor initializes pointee with mismatching
3492 /// form of \c new.
3493 ///
3494 /// Returns true, if member is initialized with matching form of \c new in
3495 /// member initializer list. Returns false, if member is initialized with the
3496 /// matching form of \c new in this constructor's initializer or given
3497 /// constructor isn't defined at the point where delete-expression is seen, or
3498 /// member isn't initialized by the constructor.
3499 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3500 /// Checks whether member is initialized with matching form of
3501 /// \c new in member initializer list.
3502 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3503 /// Checks whether member is initialized with mismatching form of \c new by
3504 /// in-class initializer.
3505 MismatchResult analyzeInClassInitializer();
3506};
3507}
3508
3509MismatchingNewDeleteDetector::MismatchResult
3510MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3511 NewExprs.clear();
3512 assert(DE && "Expected delete-expression");
3513 IsArrayForm = DE->isArrayForm();
3514 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3515 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3516 return analyzeMemberExpr(ME);
3517 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3518 if (!hasMatchingVarInit(D))
3519 return VarInitMismatches;
3520 }
3521 return NoMismatch;
3522}
3523
3524const CXXNewExpr *
3525MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3526 assert(E != nullptr && "Expected a valid initializer expression");
3527 E = E->IgnoreParenImpCasts();
3528 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3529 if (ILE->getNumInits() == 1)
3530 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3531 }
3532
3533 return dyn_cast_or_null<const CXXNewExpr>(E);
3534}
3535
3536bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3537 const CXXCtorInitializer *CI) {
3538 const CXXNewExpr *NE = nullptr;
3539 if (Field == CI->getMember() &&
3540 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3541 if (NE->isArray() == IsArrayForm)
3542 return true;
3543 else
3544 NewExprs.push_back(NE);
3545 }
3546 return false;
3547}
3548
3549bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3550 const CXXConstructorDecl *CD) {
3551 if (CD->isImplicit())
3552 return false;
3553 const FunctionDecl *Definition = CD;
3555 HasUndefinedConstructors = true;
3556 return EndOfTU;
3557 }
3558 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3559 if (hasMatchingNewInCtorInit(CI))
3560 return true;
3561 }
3562 return false;
3563}
3564
3565MismatchingNewDeleteDetector::MismatchResult
3566MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3567 assert(Field != nullptr && "This should be called only for members");
3568 const Expr *InitExpr = Field->getInClassInitializer();
3569 if (!InitExpr)
3570 return EndOfTU ? NoMismatch : AnalyzeLater;
3571 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3572 if (NE->isArray() != IsArrayForm) {
3573 NewExprs.push_back(NE);
3574 return MemberInitMismatches;
3575 }
3576 }
3577 return NoMismatch;
3578}
3579
3580MismatchingNewDeleteDetector::MismatchResult
3581MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3582 bool DeleteWasArrayForm) {
3583 assert(Field != nullptr && "Analysis requires a valid class member.");
3584 this->Field = Field;
3585 IsArrayForm = DeleteWasArrayForm;
3586 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3587 for (const auto *CD : RD->ctors()) {
3588 if (hasMatchingNewInCtor(CD))
3589 return NoMismatch;
3590 }
3591 if (HasUndefinedConstructors)
3592 return EndOfTU ? NoMismatch : AnalyzeLater;
3593 if (!NewExprs.empty())
3594 return MemberInitMismatches;
3595 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3596 : NoMismatch;
3597}
3598
3599MismatchingNewDeleteDetector::MismatchResult
3600MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3601 assert(ME != nullptr && "Expected a member expression");
3602 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3603 return analyzeField(F, IsArrayForm);
3604 return NoMismatch;
3605}
3606
3607bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3608 const CXXNewExpr *NE = nullptr;
3609 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3610 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3611 NE->isArray() != IsArrayForm) {
3612 NewExprs.push_back(NE);
3613 }
3614 }
3615 return NewExprs.empty();
3616}
3617
3618static void
3620 const MismatchingNewDeleteDetector &Detector) {
3621 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3622 FixItHint H;
3623 if (!Detector.IsArrayForm)
3624 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3625 else {
3627 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3628 SemaRef.getLangOpts(), true);
3629 if (RSquare.isValid())
3630 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3631 }
3632 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3633 << Detector.IsArrayForm << H;
3634
3635 for (const auto *NE : Detector.NewExprs)
3636 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3637 << Detector.IsArrayForm;
3638}
3639
3640void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3641 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3642 return;
3643 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3644 switch (Detector.analyzeDeleteExpr(DE)) {
3645 case MismatchingNewDeleteDetector::VarInitMismatches:
3646 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3647 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3648 break;
3649 }
3650 case MismatchingNewDeleteDetector::AnalyzeLater: {
3651 DeleteExprs[Detector.Field].push_back(
3652 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3653 break;
3654 }
3655 case MismatchingNewDeleteDetector::NoMismatch:
3656 break;
3657 }
3658}
3659
3660void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3661 bool DeleteWasArrayForm) {
3662 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3663 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3664 case MismatchingNewDeleteDetector::VarInitMismatches:
3665 llvm_unreachable("This analysis should have been done for class members.");
3666 case MismatchingNewDeleteDetector::AnalyzeLater:
3667 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3668 "translation unit.");
3669 case MismatchingNewDeleteDetector::MemberInitMismatches:
3670 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3671 break;
3672 case MismatchingNewDeleteDetector::NoMismatch:
3673 break;
3674 }
3675}
3676
3677/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3678/// @code ::delete ptr; @endcode
3679/// or
3680/// @code delete [] ptr; @endcode
3682Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3683 bool ArrayForm, Expr *ExE) {
3684 // C++ [expr.delete]p1:
3685 // The operand shall have a pointer type, or a class type having a single
3686 // non-explicit conversion function to a pointer type. The result has type
3687 // void.
3688 //
3689 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3690
3691 ExprResult Ex = ExE;
3692 FunctionDecl *OperatorDelete = nullptr;
3693 bool ArrayFormAsWritten = ArrayForm;
3694 bool UsualArrayDeleteWantsSize = false;
3695
3696 if (!Ex.get()->isTypeDependent()) {
3697 // Perform lvalue-to-rvalue cast, if needed.
3698 Ex = DefaultLvalueConversion(Ex.get());
3699 if (Ex.isInvalid())
3700 return ExprError();
3701
3702 QualType Type = Ex.get()->getType();
3703
3704 class DeleteConverter : public ContextualImplicitConverter {
3705 public:
3706 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3707
3708 bool match(QualType ConvType) override {
3709 // FIXME: If we have an operator T* and an operator void*, we must pick
3710 // the operator T*.
3711 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3712 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3713 return true;
3714 return false;
3715 }
3716
3717 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3718 QualType T) override {
3719 return S.Diag(Loc, diag::err_delete_operand) << T;
3720 }
3721
3722 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3723 QualType T) override {
3724 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3725 }
3726
3727 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3728 QualType T,
3729 QualType ConvTy) override {
3730 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3731 }
3732
3733 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3734 QualType ConvTy) override {
3735 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3736 << ConvTy;
3737 }
3738
3739 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3740 QualType T) override {
3741 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3742 }
3743
3744 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3745 QualType ConvTy) override {
3746 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3747 << ConvTy;
3748 }
3749
3750 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3751 QualType T,
3752 QualType ConvTy) override {
3753 llvm_unreachable("conversion functions are permitted");
3754 }
3755 } Converter;
3756
3757 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3758 if (Ex.isInvalid())
3759 return ExprError();
3760 Type = Ex.get()->getType();
3761 if (!Converter.match(Type))
3762 // FIXME: PerformContextualImplicitConversion should return ExprError
3763 // itself in this case.
3764 return ExprError();
3765
3766 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3767 QualType PointeeElem = Context.getBaseElementType(Pointee);
3768
3769 if (Pointee.getAddressSpace() != LangAS::Default &&
3770 !getLangOpts().OpenCLCPlusPlus)
3771 return Diag(Ex.get()->getBeginLoc(),
3772 diag::err_address_space_qualified_delete)
3773 << Pointee.getUnqualifiedType()
3775
3776 CXXRecordDecl *PointeeRD = nullptr;
3777 if (Pointee->isVoidType() && !isSFINAEContext()) {
3778 // The C++ standard bans deleting a pointer to a non-object type, which
3779 // effectively bans deletion of "void*". However, most compilers support
3780 // this, so we treat it as a warning unless we're in a SFINAE context.
3781 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3782 << Type << Ex.get()->getSourceRange();
3783 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3784 Pointee->isSizelessType()) {
3785 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3786 << Type << Ex.get()->getSourceRange());
3787 } else if (!Pointee->isDependentType()) {
3788 // FIXME: This can result in errors if the definition was imported from a
3789 // module but is hidden.
3790 if (!RequireCompleteType(StartLoc, Pointee,
3791 diag::warn_delete_incomplete, Ex.get())) {
3792 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3793 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3794 }
3795 }
3796
3797 if (Pointee->isArrayType() && !ArrayForm) {
3798 Diag(StartLoc, diag::warn_delete_array_type)
3799 << Type << Ex.get()->getSourceRange()
3801 ArrayForm = true;
3802 }
3803
3805 ArrayForm ? OO_Array_Delete : OO_Delete);
3806
3807 if (PointeeRD) {
3808 if (!UseGlobal &&
3809 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3810 OperatorDelete))
3811 return ExprError();
3812
3813 // If we're allocating an array of records, check whether the
3814 // usual operator delete[] has a size_t parameter.
3815 if (ArrayForm) {
3816 // If the user specifically asked to use the global allocator,
3817 // we'll need to do the lookup into the class.
3818 if (UseGlobal)
3819 UsualArrayDeleteWantsSize =
3820 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3821
3822 // Otherwise, the usual operator delete[] should be the
3823 // function we just found.
3824 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3825 UsualArrayDeleteWantsSize =
3826 UsualDeallocFnInfo(*this,
3827 DeclAccessPair::make(OperatorDelete, AS_public))
3828 .HasSizeT;
3829 }
3830
3831 if (!PointeeRD->hasIrrelevantDestructor())
3832 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3833 MarkFunctionReferenced(StartLoc,
3834 const_cast<CXXDestructorDecl*>(Dtor));
3835 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3836 return ExprError();
3837 }
3838
3839 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3840 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3841 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3842 SourceLocation());
3843 }
3844
3845 if (!OperatorDelete) {
3846 if (getLangOpts().OpenCLCPlusPlus) {
3847 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3848 return ExprError();
3849 }
3850
3851 bool IsComplete = isCompleteType(StartLoc, Pointee);
3852 bool CanProvideSize =
3853 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3854 Pointee.isDestructedType());
3855 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3856
3857 // Look for a global declaration.
3858 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3859 Overaligned, DeleteName);
3860 }
3861
3862 MarkFunctionReferenced(StartLoc, OperatorDelete);
3863
3864 // Check access and ambiguity of destructor if we're going to call it.
3865 // Note that this is required even for a virtual delete.
3866 bool IsVirtualDelete = false;
3867 if (PointeeRD) {
3868 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3869 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3870 PDiag(diag::err_access_dtor) << PointeeElem);
3871 IsVirtualDelete = Dtor->isVirtual();
3872 }
3873 }
3874
3875 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3876
3877 // Convert the operand to the type of the first parameter of operator
3878 // delete. This is only necessary if we selected a destroying operator
3879 // delete that we are going to call (non-virtually); converting to void*
3880 // is trivial and left to AST consumers to handle.
3881 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3882 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3883 Qualifiers Qs = Pointee.getQualifiers();
3884 if (Qs.hasCVRQualifiers()) {
3885 // Qualifiers are irrelevant to this conversion; we're only looking
3886 // for access and ambiguity.
3890 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3891 }
3892 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3893 if (Ex.isInvalid())
3894 return ExprError();
3895 }
3896 }
3897
3899 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3900 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3901 AnalyzeDeleteExprMismatch(Result);
3902 return Result;
3903}
3904
3906 bool IsDelete,
3907 FunctionDecl *&Operator) {
3908
3910 IsDelete ? OO_Delete : OO_New);
3911
3912 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3914 assert(!R.empty() && "implicitly declared allocation functions not found");
3915 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3916
3917 // We do our own custom access checks below.
3919
3920 SmallVector<Expr *, 8> Args(TheCall->arguments());
3921 OverloadCandidateSet Candidates(R.getNameLoc(),
3923 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3924 FnOvl != FnOvlEnd; ++FnOvl) {
3925 // Even member operator new/delete are implicitly treated as
3926 // static, so don't use AddMemberCandidate.
3927 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3928
3929 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3930 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3931 /*ExplicitTemplateArgs=*/nullptr, Args,
3932 Candidates,
3933 /*SuppressUserConversions=*/false);
3934 continue;
3935 }
3936
3937 FunctionDecl *Fn = cast<FunctionDecl>(D);
3938 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3939 /*SuppressUserConversions=*/false);
3940 }
3941
3942 SourceRange Range = TheCall->getSourceRange();
3943
3944 // Do the resolution.
3946 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3947 case OR_Success: {
3948 // Got one!
3949 FunctionDecl *FnDecl = Best->Function;
3950 assert(R.getNamingClass() == nullptr &&
3951 "class members should not be considered");
3952
3954 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3955 << (IsDelete ? 1 : 0) << Range;
3956 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3957 << R.getLookupName() << FnDecl->getSourceRange();
3958 return true;
3959 }
3960
3961 Operator = FnDecl;
3962 return false;
3963 }
3964
3966 Candidates.NoteCandidates(
3968 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3969 << R.getLookupName() << Range),
3970 S, OCD_AllCandidates, Args);
3971 return true;
3972
3973 case OR_Ambiguous:
3974 Candidates.NoteCandidates(
3976 S.PDiag(diag::err_ovl_ambiguous_call)
3977 << R.getLookupName() << Range),
3978 S, OCD_AmbiguousCandidates, Args);
3979 return true;
3980
3981 case OR_Deleted:
3983 Candidates, Best->Function, Args);
3984 return true;
3985 }
3986 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3987}
3988
3989ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3990 bool IsDelete) {
3991 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3992 if (!getLangOpts().CPlusPlus) {
3993 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3994 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3995 << "C++";
3996 return ExprError();
3997 }
3998 // CodeGen assumes it can find the global new and delete to call,
3999 // so ensure that they are declared.
4001
4002 FunctionDecl *OperatorNewOrDelete = nullptr;
4003 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4004 OperatorNewOrDelete))
4005 return ExprError();
4006 assert(OperatorNewOrDelete && "should be found");
4007
4008 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4009 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4010
4011 TheCall->setType(OperatorNewOrDelete->getReturnType());
4012 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4013 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4014 InitializedEntity Entity =
4017 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4018 if (Arg.isInvalid())
4019 return ExprError();
4020 TheCall->setArg(i, Arg.get());
4021 }
4022 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4023 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4024 "Callee expected to be implicit cast to a builtin function pointer");
4025 Callee->setType(OperatorNewOrDelete->getType());
4026
4027 return TheCallResult;
4028}
4029
4031 bool IsDelete, bool CallCanBeVirtual,
4032 bool WarnOnNonAbstractTypes,
4033 SourceLocation DtorLoc) {
4034 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4035 return;
4036
4037 // C++ [expr.delete]p3:
4038 // In the first alternative (delete object), if the static type of the
4039 // object to be deleted is different from its dynamic type, the static
4040 // type shall be a base class of the dynamic type of the object to be
4041 // deleted and the static type shall have a virtual destructor or the
4042 // behavior is undefined.
4043 //
4044 const CXXRecordDecl *PointeeRD = dtor->getParent();
4045 // Note: a final class cannot be derived from, no issue there
4046 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4047 return;
4048
4049 // If the superclass is in a system header, there's nothing that can be done.
4050 // The `delete` (where we emit the warning) can be in a system header,
4051 // what matters for this warning is where the deleted type is defined.
4052 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4053 return;
4054
4055 QualType ClassType = dtor->getFunctionObjectParameterType();
4056 if (PointeeRD->isAbstract()) {
4057 // If the class is abstract, we warn by default, because we're
4058 // sure the code has undefined behavior.
4059 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4060 << ClassType;
4061 } else if (WarnOnNonAbstractTypes) {
4062 // Otherwise, if this is not an array delete, it's a bit suspect,
4063 // but not necessarily wrong.
4064 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4065 << ClassType;
4066 }
4067 if (!IsDelete) {
4068 std::string TypeStr;
4069 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4070 Diag(DtorLoc, diag::note_delete_non_virtual)
4071 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4072 }
4073}
4074
4076 SourceLocation StmtLoc,
4077 ConditionKind CK) {
4078 ExprResult E =
4079 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4080 if (E.isInvalid())
4081 return ConditionError();
4082 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4084}
4085
4086/// Check the use of the given variable as a C++ condition in an if,
4087/// while, do-while, or switch statement.
4089 SourceLocation StmtLoc,
4090 ConditionKind CK) {
4091 if (ConditionVar->isInvalidDecl())
4092 return ExprError();
4093
4094 QualType T = ConditionVar->getType();
4095
4096 // C++ [stmt.select]p2:
4097 // The declarator shall not specify a function or an array.
4098 if (T->isFunctionType())
4099 return ExprError(Diag(ConditionVar->getLocation(),
4100 diag::err_invalid_use_of_function_type)
4101 << ConditionVar->getSourceRange());
4102 else if (T->isArrayType())
4103 return ExprError(Diag(ConditionVar->getLocation(),
4104 diag::err_invalid_use_of_array_type)
4105 << ConditionVar->getSourceRange());
4106
4108 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4109 ConditionVar->getLocation());
4110
4111 switch (CK) {
4113 return CheckBooleanCondition(StmtLoc, Condition.get());
4114
4116 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4117
4119 return CheckSwitchCondition(StmtLoc, Condition.get());
4120 }
4121
4122 llvm_unreachable("unexpected condition kind");
4123}
4124
4125/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4126ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4127 // C++11 6.4p4:
4128 // The value of a condition that is an initialized declaration in a statement
4129 // other than a switch statement is the value of the declared variable
4130 // implicitly converted to type bool. If that conversion is ill-formed, the
4131 // program is ill-formed.
4132 // The value of a condition that is an expression is the value of the
4133 // expression, implicitly converted to bool.
4134 //
4135 // C++23 8.5.2p2
4136 // If the if statement is of the form if constexpr, the value of the condition
4137 // is contextually converted to bool and the converted expression shall be
4138 // a constant expression.
4139 //
4140
4142 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4143 return E;
4144
4145 // FIXME: Return this value to the caller so they don't need to recompute it.
4146 llvm::APSInt Cond;
4148 E.get(), &Cond,
4149 diag::err_constexpr_if_condition_expression_is_not_constant);
4150 return E;
4151}
4152
4153/// Helper function to determine whether this is the (deprecated) C++
4154/// conversion from a string literal to a pointer to non-const char or
4155/// non-const wchar_t (for narrow and wide string literals,
4156/// respectively).
4157bool
4159 // Look inside the implicit cast, if it exists.
4160 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4161 From = Cast->getSubExpr();
4162
4163 // A string literal (2.13.4) that is not a wide string literal can
4164 // be converted to an rvalue of type "pointer to char"; a wide
4165 // string literal can be converted to an rvalue of type "pointer
4166 // to wchar_t" (C++ 4.2p2).
4167 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4168 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4169 if (const BuiltinType *ToPointeeType
4170 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4171 // This conversion is considered only when there is an
4172 // explicit appropriate pointer target type (C++ 4.2p2).
4173 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4174 switch (StrLit->getKind()) {
4178 // We don't allow UTF literals to be implicitly converted
4179 break;
4181 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4182 ToPointeeType->getKind() == BuiltinType::Char_S);
4185 QualType(ToPointeeType, 0));
4187 assert(false && "Unevaluated string literal in expression");
4188 break;
4189 }
4190 }
4191 }
4192
4193 return false;
4194}
4195
4197 SourceLocation CastLoc,
4198 QualType Ty,
4199 CastKind Kind,
4200 CXXMethodDecl *Method,
4201 DeclAccessPair FoundDecl,
4202 bool HadMultipleCandidates,
4203 Expr *From) {
4204 switch (Kind) {
4205 default: llvm_unreachable("Unhandled cast kind!");
4206 case CK_ConstructorConversion: {
4207 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4208 SmallVector<Expr*, 8> ConstructorArgs;
4209
4210 if (S.RequireNonAbstractType(CastLoc, Ty,
4211 diag::err_allocation_of_abstract_type))
4212 return ExprError();
4213
4214 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4215 ConstructorArgs))
4216 return ExprError();
4217
4218 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4220 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4221 return ExprError();
4222
4224 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4225 ConstructorArgs, HadMultipleCandidates,
4226 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4228 if (Result.isInvalid())
4229 return ExprError();
4230
4231 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4232 }
4233
4234 case CK_UserDefinedConversion: {
4235 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4236
4237 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4238 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4239 return ExprError();
4240
4241 // Create an implicit call expr that calls it.
4242 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4243 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4244 HadMultipleCandidates);
4245 if (Result.isInvalid())
4246 return ExprError();
4247 // Record usage of conversion in an implicit cast.
4248 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4249 CK_UserDefinedConversion, Result.get(),
4250 nullptr, Result.get()->getValueKind(),
4252
4253 return S.MaybeBindToTemporary(Result.get());
4254 }
4255 }
4256}
4257
4258/// PerformImplicitConversion - Perform an implicit conversion of the
4259/// expression From to the type ToType using the pre-computed implicit
4260/// conversion sequence ICS. Returns the converted
4261/// expression. Action is the kind of conversion we're performing,
4262/// used in the error message.
4265 const ImplicitConversionSequence &ICS,
4266 AssignmentAction Action,
4268 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4270 !From->getType()->isRecordType())
4271 return From;
4272
4273 switch (ICS.getKind()) {
4275 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4276 Action, CCK);
4277 if (Res.isInvalid())
4278 return ExprError();
4279 From = Res.get();
4280 break;
4281 }
4282
4284
4287 QualType BeforeToType;
4288 assert(FD && "no conversion function for user-defined conversion seq");
4289 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4290 CastKind = CK_UserDefinedConversion;
4291
4292 // If the user-defined conversion is specified by a conversion function,
4293 // the initial standard conversion sequence converts the source type to
4294 // the implicit object parameter of the conversion function.
4295 BeforeToType = Context.getTagDeclType(Conv->getParent());
4296 } else {
4297 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4298 CastKind = CK_ConstructorConversion;
4299 // Do no conversion if dealing with ... for the first conversion.
4301 // If the user-defined conversion is specified by a constructor, the
4302 // initial standard conversion sequence converts the source type to
4303 // the type required by the argument of the constructor
4304 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4305 }
4306 }
4307 // Watch out for ellipsis conversion.
4309 ExprResult Res =
4310 PerformImplicitConversion(From, BeforeToType,
4312 CCK);
4313 if (Res.isInvalid())
4314 return ExprError();
4315 From = Res.get();
4316 }
4317
4319 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4320 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4322
4323 if (CastArg.isInvalid())
4324 return ExprError();
4325
4326 From = CastArg.get();
4327
4328 // C++ [over.match.oper]p7:
4329 // [...] the second standard conversion sequence of a user-defined
4330 // conversion sequence is not applied.
4332 return From;
4333
4334 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4335 AA_Converting, CCK);
4336 }
4337
4339 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4340 PDiag(diag::err_typecheck_ambiguous_condition)
4341 << From->getSourceRange());
4342 return ExprError();
4343
4346 llvm_unreachable("bad conversion");
4347
4350 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4351 bool Diagnosed = DiagnoseAssignmentResult(
4352 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4353 ToType, From->getType(), From, Action);
4354 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4355 return ExprError();
4356 }
4357
4358 // Everything went well.
4359 return From;
4360}
4361
4362/// PerformImplicitConversion - Perform an implicit conversion of the
4363/// expression From to the type ToType by following the standard
4364/// conversion sequence SCS. Returns the converted
4365/// expression. Flavor is the context in which we're performing this
4366/// conversion, for use in error messages.
4369 const StandardConversionSequence& SCS,
4370 AssignmentAction Action,
4372 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4374
4375 // Overall FIXME: we are recomputing too many types here and doing far too
4376 // much extra work. What this means is that we need to keep track of more
4377 // information that is computed when we try the implicit conversion initially,
4378 // so that we don't need to recompute anything here.
4379 QualType FromType = From->getType();
4380
4381 if (SCS.CopyConstructor) {
4382 // FIXME: When can ToType be a reference type?
4383 assert(!ToType->isReferenceType());
4384 if (SCS.Second == ICK_Derived_To_Base) {
4385 SmallVector<Expr*, 8> ConstructorArgs;
4387 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4388 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4389 return ExprError();
4390 return BuildCXXConstructExpr(
4391 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4392 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4393 /*HadMultipleCandidates*/ false,
4394 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4396 }
4397 return BuildCXXConstructExpr(
4398 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4400 /*HadMultipleCandidates*/ false,
4401 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4403 }
4404
4405 // Resolve overloaded function references.
4406 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4407 DeclAccessPair Found;
4409 true, Found);
4410 if (!Fn)
4411 return ExprError();
4412
4413 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4414 return ExprError();
4415
4416 ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
4417 if (Res.isInvalid())
4418 return ExprError();
4419
4420 // We might get back another placeholder expression if we resolved to a
4421 // builtin.
4422 Res = CheckPlaceholderExpr(Res.get());
4423 if (Res.isInvalid())
4424 return ExprError();
4425
4426 From = Res.get();
4427 FromType = From->getType();
4428 }
4429
4430 // If we're converting to an atomic type, first convert to the corresponding
4431 // non-atomic type.
4432 QualType ToAtomicType;
4433 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4434 ToAtomicType = ToType;
4435 ToType = ToAtomic->getValueType();
4436 }
4437
4438 QualType InitialFromType = FromType;
4439 // Perform the first implicit conversion.
4440 switch (SCS.First) {
4441 case ICK_Identity:
4442 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4443 FromType = FromAtomic->getValueType().getUnqualifiedType();
4444 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4445 From, /*BasePath=*/nullptr, VK_PRValue,
4447 }
4448 break;
4449
4450 case ICK_Lvalue_To_Rvalue: {
4451 assert(From->getObjectKind() != OK_ObjCProperty);
4452 ExprResult FromRes = DefaultLvalueConversion(From);
4453 if (FromRes.isInvalid())
4454 return ExprError();
4455
4456 From = FromRes.get();
4457 FromType = From->getType();
4458 break;
4459 }
4460
4462 FromType = Context.getArrayDecayedType(FromType);
4463 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4464 /*BasePath=*/nullptr, CCK)
4465 .get();
4466 break;
4467
4469 FromType = Context.getArrayParameterType(FromType);
4470 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4471 /*BasePath=*/nullptr, CCK)
4472 .get();
4473 break;
4474
4476 FromType = Context.getPointerType(FromType);
4477 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4478 VK_PRValue, /*BasePath=*/nullptr, CCK)
4479 .get();
4480 break;
4481
4482 default:
4483 llvm_unreachable("Improper first standard conversion");
4484 }
4485
4486 // Perform the second implicit conversion
4487 switch (SCS.Second) {
4488 case ICK_Identity:
4489 // C++ [except.spec]p5:
4490 // [For] assignment to and initialization of pointers to functions,
4491 // pointers to member functions, and references to functions: the
4492 // target entity shall allow at least the exceptions allowed by the
4493 // source value in the assignment or initialization.
4494 switch (Action) {
4495 case AA_Assigning:
4496 case AA_Initializing:
4497 // Note, function argument passing and returning are initialization.
4498 case AA_Passing:
4499 case AA_Returning:
4500 case AA_Sending:
4502 if (CheckExceptionSpecCompatibility(From, ToType))
4503 return ExprError();
4504 break;
4505
4506 case AA_Casting:
4507 case AA_Converting:
4508 // Casts and implicit conversions are not initialization, so are not
4509 // checked for exception specification mismatches.
4510 break;
4511 }
4512 // Nothing else to do.
4513 break;
4514
4517 if (ToType->isBooleanType()) {
4518 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4520 "only enums with fixed underlying type can promote to bool");
4521 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4522 /*BasePath=*/nullptr, CCK)
4523 .get();
4524 } else {
4525 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4526 /*BasePath=*/nullptr, CCK)
4527 .get();
4528 }
4529 break;
4530
4533 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4534 /*BasePath=*/nullptr, CCK)
4535 .get();
4536 break;
4537
4540 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4541 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4542 CastKind CK;
4543 if (FromEl->isRealFloatingType()) {
4544 if (ToEl->isRealFloatingType())
4545 CK = CK_FloatingComplexCast;
4546 else
4547 CK = CK_FloatingComplexToIntegralComplex;
4548 } else if (ToEl->isRealFloatingType()) {
4549 CK = CK_IntegralComplexToFloatingComplex;
4550 } else {
4551 CK = CK_IntegralComplexCast;
4552 }
4553 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4554 CCK)
4555 .get();
4556 break;
4557 }
4558
4560 if (ToType->isRealFloatingType())
4561 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4562 /*BasePath=*/nullptr, CCK)
4563 .get();
4564 else
4565 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4566 /*BasePath=*/nullptr, CCK)
4567 .get();
4568 break;
4569
4571 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4572 "Attempting implicit fixed point conversion without a fixed "
4573 "point operand");
4574 if (FromType->isFloatingType())
4575 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4576 VK_PRValue,
4577 /*BasePath=*/nullptr, CCK).get();
4578 else if (ToType->isFloatingType())
4579 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4580 VK_PRValue,
4581 /*BasePath=*/nullptr, CCK).get();
4582 else if (FromType->isIntegralType(Context))
4583 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4584 VK_PRValue,
4585 /*BasePath=*/nullptr, CCK).get();
4586 else if (ToType->isIntegralType(Context))
4587 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4588 VK_PRValue,
4589 /*BasePath=*/nullptr, CCK).get();
4590 else if (ToType->isBooleanType())
4591 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4592 VK_PRValue,
4593 /*BasePath=*/nullptr, CCK).get();
4594 else
4595 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4596 VK_PRValue,
4597 /*BasePath=*/nullptr, CCK).get();
4598 break;
4599
4601 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4602 /*BasePath=*/nullptr, CCK).get();
4603 break;
4604
4607 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4608 // Diagnose incompatible Objective-C conversions
4609 if (Action == AA_Initializing || Action == AA_Assigning)
4610 Diag(From->getBeginLoc(),
4611 diag::ext_typecheck_convert_incompatible_pointer)
4612 << ToType << From->getType() << Action << From->getSourceRange()
4613 << 0;
4614 else
4615 Diag(From->getBeginLoc(),
4616 diag::ext_typecheck_convert_incompatible_pointer)
4617 << From->getType() << ToType << Action << From->getSourceRange()
4618 << 0;
4619
4620 if (From->getType()->isObjCObjectPointerType() &&
4621 ToType->isObjCObjectPointerType())
4623 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4625 From->getType())) {
4626 if (Action == AA_Initializing)
4627 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4628 else
4629 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4630 << (Action == AA_Casting) << From->getType() << ToType
4631 << From->getSourceRange();
4632 }
4633
4634 // Defer address space conversion to the third conversion.
4635 QualType FromPteeType = From->getType()->getPointeeType();
4636 QualType ToPteeType = ToType->getPointeeType();
4637 QualType NewToType = ToType;
4638 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4639 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4640 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4641 NewToType = Context.getAddrSpaceQualType(NewToType,
4642 FromPteeType.getAddressSpace());
4643 if (ToType->isObjCObjectPointerType())
4644 NewToType = Context.getObjCObjectPointerType(NewToType);
4645 else if (ToType->isBlockPointerType())
4646 NewToType = Context.getBlockPointerType(NewToType);
4647 else
4648 NewToType = Context.getPointerType(NewToType);
4649 }
4650
4651 CastKind Kind;
4652 CXXCastPath BasePath;
4653 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4654 return ExprError();
4655
4656 // Make sure we extend blocks if necessary.
4657 // FIXME: doing this here is really ugly.
4658 if (Kind == CK_BlockPointerToObjCPointerCast) {
4659 ExprResult E = From;
4661 From = E.get();
4662 }
4664 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4665 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4666 .get();
4667 break;
4668 }
4669
4670 case ICK_Pointer_Member: {
4671 CastKind Kind;
4672 CXXCastPath BasePath;
4673 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4674 return ExprError();
4675 if (CheckExceptionSpecCompatibility(From, ToType))
4676 return ExprError();
4677
4678 // We may not have been able to figure out what this member pointer resolved
4679 // to up until this exact point. Attempt to lock-in it's inheritance model.
4681 (void)isCompleteType(From->getExprLoc(), From->getType());
4682 (void)isCompleteType(From->getExprLoc(), ToType);
4683 }
4684
4685 From =
4686 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4687 break;
4688 }
4689
4691 // Perform half-to-boolean conversion via float.
4692 if (From->getType()->isHalfType()) {
4693 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4694 FromType = Context.FloatTy;
4695 }
4696
4697 From = ImpCastExprToType(From, Context.BoolTy,
4699 /*BasePath=*/nullptr, CCK)
4700 .get();
4701 break;
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 =
4795 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4796 LangAS AddrSpaceR =
4797 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4798 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4799 "Invalid cast");
4800 CastKind Kind =
4801 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4802 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4803 VK_PRValue, /*BasePath=*/nullptr, CCK)
4804 .get();
4805 break;
4806 }
4807
4809 ExprResult FromRes = From;
4812 if (FromRes.isInvalid())
4813 return ExprError();
4814 From = FromRes.get();
4815 assert ((ConvTy == Sema::Compatible) &&
4816 "Improper transparent union conversion");
4817 (void)ConvTy;
4818 break;
4819 }
4820
4823 From = ImpCastExprToType(From, ToType,
4824 CK_ZeroToOCLOpaqueType,
4825 From->getValueKind()).get();
4826 break;
4828 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a vector
4829 // to a smaller vector, this can only operate on arguments where the source
4830 // and destination types are ExtVectors.
4831 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4832 "HLSL vector truncation should only apply to ExtVectors");
4833 auto *FromVec = From->getType()->castAs<VectorType>();
4834 auto *ToVec = ToType->castAs<VectorType>();
4835 QualType ElType = FromVec->getElementType();
4836 QualType TruncTy =
4837 Context.getExtVectorType(ElType, ToVec->getNumElements());
4838 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4839 From->getValueKind())
4840 .get();
4841 break;
4842 }
4843
4848 case ICK_Qualification:
4853 llvm_unreachable("Improper second standard conversion");
4854 }
4855
4856 if (SCS.Element != ICK_Identity) {
4857 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4858 // vectors or matrices.
4859
4860 // TODO: Support HLSL matrices.
4861 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4862 "Element conversion for matrix types is not implemented yet.");
4863 assert(From->getType()->isVectorType() && ToType->isVectorType() &&
4864 "Element conversion is only supported for vector types.");
4865 assert(From->getType()->getAs<VectorType>()->getNumElements() ==
4866 ToType->getAs<VectorType>()->getNumElements() &&
4867 "Element conversion is only supported for vectors with the same "
4868 "element counts.");
4869 QualType FromElTy = From->getType()->getAs<VectorType>()->getElementType();
4870 unsigned NumElts = ToType->getAs<VectorType>()->getNumElements();
4871 switch (SCS.Element) {
4873 // Perform half-to-boolean conversion via float.
4874 if (FromElTy->isHalfType()) {
4875 QualType FPExtType = Context.getExtVectorType(FromElTy, NumElts);
4876 From = ImpCastExprToType(From, FPExtType, CK_FloatingCast).get();
4877 FromType = FPExtType;
4878 }
4879
4880 From =
4881 ImpCastExprToType(From, ToType, ScalarTypeToBooleanCastKind(FromElTy),
4882 VK_PRValue,
4883 /*BasePath=*/nullptr, CCK)
4884 .get();
4885 break;
4888 if (ToType->isBooleanType()) {
4889 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4891 "only enums with fixed underlying type can promote to bool");
4892 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4893 /*BasePath=*/nullptr, CCK)
4894 .get();
4895 } else {
4896 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4897 /*BasePath=*/nullptr, CCK)
4898 .get();
4899 }
4900 break;
4901
4904 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4905 /*BasePath=*/nullptr, CCK)
4906 .get();
4907 break;
4909 if (ToType->hasFloatingRepresentation())
4910 From =
4911 ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4912 /*BasePath=*/nullptr, CCK)
4913 .get();
4914 else
4915 From =
4916 ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4917 /*BasePath=*/nullptr, CCK)
4918 .get();
4919 break;
4920 case ICK_Identity:
4921 default:
4922 llvm_unreachable("Improper element standard conversion");
4923 }
4924 }
4925
4926 switch (SCS.Third) {
4927 case ICK_Identity:
4928 // Nothing to do.
4929 break;
4930
4932 // If both sides are functions (or pointers/references to them), there could
4933 // be incompatible exception declarations.
4934 if (CheckExceptionSpecCompatibility(From, ToType))
4935 return ExprError();
4936
4937 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4938 /*BasePath=*/nullptr, CCK)
4939 .get();
4940 break;
4941
4942 case ICK_Qualification: {
4943 ExprValueKind VK = From->getValueKind();
4944 CastKind CK = CK_NoOp;
4945
4946 if (ToType->isReferenceType() &&
4947 ToType->getPointeeType().getAddressSpace() !=
4948 From->getType().getAddressSpace())
4949 CK = CK_AddressSpaceConversion;
4950
4951 if (ToType->isPointerType() &&
4952 ToType->getPointeeType().getAddressSpace() !=
4954 CK = CK_AddressSpaceConversion;
4955
4956 if (!isCast(CCK) &&
4957 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4959 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4960 << InitialFromType << ToType;
4961 }
4962
4963 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4964 /*BasePath=*/nullptr, CCK)
4965 .get();
4966
4968 !getLangOpts().WritableStrings) {
4969 Diag(From->getBeginLoc(),
4971 ? diag::ext_deprecated_string_literal_conversion
4972 : diag::warn_deprecated_string_literal_conversion)
4973 << ToType.getNonReferenceType();
4974 }
4975
4976 break;
4977 }
4978
4979 default:
4980 llvm_unreachable("Improper third standard conversion");
4981 }
4982
4983 // If this conversion sequence involved a scalar -> atomic conversion, perform
4984 // that conversion now.
4985 if (!ToAtomicType.isNull()) {
4986 assert(Context.hasSameType(
4987 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4988 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4989 VK_PRValue, nullptr, CCK)
4990 .get();
4991 }
4992
4993 // Materialize a temporary if we're implicitly converting to a reference
4994 // type. This is not required by the C++ rules but is necessary to maintain
4995 // AST invariants.
4996 if (ToType->isReferenceType() && From->isPRValue()) {
4998 if (Res.isInvalid())
4999 return ExprError();
5000 From = Res.get();
5001 }
5002
5003 // If this conversion sequence succeeded and involved implicitly converting a
5004 // _Nullable type to a _Nonnull one, complain.
5005 if (!isCast(CCK))
5006 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
5007 From->getBeginLoc());
5008
5009 return From;
5010}
5011
5012/// Checks that type T is not a VLA.
5013///
5014/// @returns @c true if @p T is VLA and a diagnostic was emitted,
5015/// @c false otherwise.
5017 clang::tok::TokenKind TypeTraitID) {
5018 if (!T->getType()->isVariableArrayType())
5019 return false;
5020
5021 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
5022 << 1 << TypeTraitID;
5023 return true;
5024}
5025
5026/// Check the completeness of a type in a unary type trait.
5027///
5028/// If the particular type trait requires a complete type, tries to complete
5029/// it. If completing the type fails, a diagnostic is emitted and false
5030/// returned. If completing the type succeeds or no completion was required,
5031/// returns true.
5033 SourceLocation Loc,
5034 QualType ArgTy) {
5035 // C++0x [meta.unary.prop]p3:
5036 // For all of the class templates X declared in this Clause, instantiating
5037 // that template with a template argument that is a class template
5038 // specialization may result in the implicit instantiation of the template
5039 // argument if and only if the semantics of X require that the argument
5040 // must be a complete type.
5041 // We apply this rule to all the type trait expressions used to implement
5042 // these class templates. We also try to follow any GCC documented behavior
5043 // in these expressions to ensure portability of standard libraries.
5044 switch (UTT) {
5045 default: llvm_unreachable("not a UTT");
5046 // is_complete_type somewhat obviously cannot require a complete type.
5047 case UTT_IsCompleteType:
5048 // Fall-through
5049
5050 // These traits are modeled on the type predicates in C++0x
5051 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
5052 // requiring a complete type, as whether or not they return true cannot be
5053 // impacted by the completeness of the type.
5054 case UTT_IsVoid:
5055 case UTT_IsIntegral:
5056 case UTT_IsFloatingPoint:
5057 case UTT_IsArray:
5058 case UTT_IsBoundedArray:
5059 case UTT_IsPointer:
5060 case UTT_IsNullPointer:
5061 case UTT_IsReferenceable:
5062 case UTT_IsLvalueReference:
5063 case UTT_IsRvalueReference:
5064 case UTT_IsMemberFunctionPointer:
5065 case UTT_IsMemberObjectPointer:
5066 case UTT_IsEnum:
5067 case UTT_IsScopedEnum:
5068 case UTT_IsUnion:
5069 case UTT_IsClass:
5070 case UTT_IsFunction:
5071 case UTT_IsReference:
5072 case UTT_IsArithmetic:
5073 case UTT_IsFundamental:
5074 case UTT_IsObject:
5075 case UTT_IsScalar:
5076 case UTT_IsCompound:
5077 case UTT_IsMemberPointer:
5078 // Fall-through
5079
5080 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5081 // which requires some of its traits to have the complete type. However,
5082 // the completeness of the type cannot impact these traits' semantics, and
5083 // so they don't require it. This matches the comments on these traits in
5084 // Table 49.
5085 case UTT_IsConst:
5086 case UTT_IsVolatile:
5087 case UTT_IsSigned:
5088 case UTT_IsUnboundedArray:
5089 case UTT_IsUnsigned:
5090
5091 // This type trait always returns false, checking the type is moot.
5092 case UTT_IsInterfaceClass:
5093 return true;
5094
5095 // C++14 [meta.unary.prop]:
5096 // If T is a non-union class type, T shall be a complete type.
5097 case UTT_IsEmpty:
5098 case UTT_IsPolymorphic:
5099 case UTT_IsAbstract:
5100 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5101 if (!RD->isUnion())
5102 return !S.RequireCompleteType(
5103 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5104 return true;
5105
5106 // C++14 [meta.unary.prop]:
5107 // If T is a class type, T shall be a complete type.
5108 case UTT_IsFinal:
5109 case UTT_IsSealed:
5110 if (ArgTy->getAsCXXRecordDecl())
5111 return !S.RequireCompleteType(
5112 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5113 return true;
5114
5115 // LWG3823: T shall be an array type, a complete type, or cv void.
5116 case UTT_IsAggregate:
5117 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5118 return true;
5119
5120 return !S.RequireCompleteType(
5121 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5122
5123 // C++1z [meta.unary.prop]:
5124 // remove_all_extents_t<T> shall be a complete type or cv void.
5125 case UTT_IsTrivial:
5126 case UTT_IsTriviallyCopyable:
5127 case UTT_IsStandardLayout:
5128 case UTT_IsPOD:
5129 case UTT_IsLiteral:
5130 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5131 // impose the same constraints.
5132 case UTT_IsTriviallyRelocatable:
5133 case UTT_IsTriviallyEqualityComparable:
5134 case UTT_CanPassInRegs:
5135 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5136 // or an array of unknown bound. But GCC actually imposes the same constraints
5137 // as above.
5138 case UTT_HasNothrowAssign:
5139 case UTT_HasNothrowMoveAssign:
5140 case UTT_HasNothrowConstructor:
5141 case UTT_HasNothrowCopy:
5142 case UTT_HasTrivialAssign:
5143 case UTT_HasTrivialMoveAssign:
5144 case UTT_HasTrivialDefaultConstructor:
5145 case UTT_HasTrivialMoveConstructor:
5146 case UTT_HasTrivialCopy:
5147 case UTT_HasTrivialDestructor:
5148 case UTT_HasVirtualDestructor:
5149 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5150 [[fallthrough]];
5151
5152 // C++1z [meta.unary.prop]:
5153 // T shall be a complete type, cv void, or an array of unknown bound.
5154 case UTT_IsDestructible:
5155 case UTT_IsNothrowDestructible:
5156 case UTT_IsTriviallyDestructible:
5157 case UTT_HasUniqueObjectRepresentations:
5158 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5159 return true;
5160
5161 return !S.RequireCompleteType(
5162 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5163 }
5164}
5165
5167 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5168 bool (CXXRecordDecl::*HasTrivial)() const,
5169 bool (CXXRecordDecl::*HasNonTrivial)() const,
5170 bool (CXXMethodDecl::*IsDesiredOp)() const)
5171{
5172 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5173 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5174 return true;
5175
5176 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5177 DeclarationNameInfo NameInfo(Name, KeyLoc);
5179 if (Self.LookupQualifiedName(Res, RD)) {
5180 bool FoundOperator = false;
5181 Res.suppressDiagnostics();
5182 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5183 Op != OpEnd; ++Op) {
5184 if (isa<FunctionTemplateDecl>(*Op))
5185 continue;
5186
5187 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5188 if((Operator->*IsDesiredOp)()) {
5189 FoundOperator = true;
5190 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5191 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5192 if (!CPT || !CPT->isNothrow())
5193 return false;
5194 }
5195 }
5196 return FoundOperator;
5197 }
5198 return false;
5199}
5200
5202 SourceLocation KeyLoc,
5203 TypeSourceInfo *TInfo) {
5204 QualType T = TInfo->getType();
5205 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5206
5207 ASTContext &C = Self.Context;
5208 switch(UTT) {
5209 default: llvm_unreachable("not a UTT");
5210 // Type trait expressions corresponding to the primary type category
5211 // predicates in C++0x [meta.unary.cat].
5212 case UTT_IsVoid:
5213 return T->isVoidType();
5214 case UTT_IsIntegral:
5215 return T->isIntegralType(C);
5216 case UTT_IsFloatingPoint:
5217 return T->isFloatingType();
5218 case UTT_IsArray:
5219 return T->isArrayType();
5220 case UTT_IsBoundedArray:
5221 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5222 return false;
5223 return T->isArrayType() && !T->isIncompleteArrayType();
5224 case UTT_IsUnboundedArray:
5225 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5226 return false;
5227 return T->isIncompleteArrayType();
5228 case UTT_IsPointer:
5229 return T->isAnyPointerType();
5230 case UTT_IsNullPointer:
5231 return T->isNullPtrType();
5232 case UTT_IsLvalueReference:
5233 return T->isLValueReferenceType();
5234 case UTT_IsRvalueReference:
5235 return T->isRValueReferenceType();
5236 case UTT_IsMemberFunctionPointer:
5238 case UTT_IsMemberObjectPointer:
5239 return T->isMemberDataPointerType();
5240 case UTT_IsEnum:
5241 return T->isEnumeralType();
5242 case UTT_IsScopedEnum:
5243 return T->isScopedEnumeralType();
5244 case UTT_IsUnion:
5245 return T->isUnionType();
5246 case UTT_IsClass:
5247 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5248 case UTT_IsFunction:
5249 return T->isFunctionType();
5250
5251 // Type trait expressions which correspond to the convenient composition
5252 // predicates in C++0x [meta.unary.comp].
5253 case UTT_IsReference:
5254 return T->isReferenceType();
5255 case UTT_IsArithmetic:
5256 return T->isArithmeticType() && !T->isEnumeralType();
5257 case UTT_IsFundamental:
5258 return T->isFundamentalType();
5259 case UTT_IsObject:
5260 return T->isObjectType();
5261 case UTT_IsScalar:
5262 // Note: semantic analysis depends on Objective-C lifetime types to be
5263 // considered scalar types. However, such types do not actually behave
5264 // like scalar types at run time (since they may require retain/release
5265 // operations), so we report them as non-scalar.
5266 if (T->isObjCLifetimeType()) {
5267 switch (T.getObjCLifetime()) {
5270 return true;
5271
5275 return false;
5276 }
5277 }
5278
5279 return T->isScalarType();
5280 case UTT_IsCompound:
5281 return T->isCompoundType();
5282 case UTT_IsMemberPointer:
5283 return T->isMemberPointerType();
5284
5285 // Type trait expressions which correspond to the type property predicates
5286 // in C++0x [meta.unary.prop].
5287 case UTT_IsConst:
5288 return T.isConstQualified();
5289 case UTT_IsVolatile:
5290 return T.isVolatileQualified();
5291 case UTT_IsTrivial:
5292 return T.isTrivialType(C);
5293 case UTT_IsTriviallyCopyable:
5294 return T.isTriviallyCopyableType(C);
5295 case UTT_IsStandardLayout:
5296 return T->isStandardLayoutType();
5297 case UTT_IsPOD:
5298 return T.isPODType(C);
5299 case UTT_IsLiteral:
5300 return T->isLiteralType(C);
5301 case UTT_IsEmpty:
5302 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5303 return !RD->isUnion() && RD->isEmpty();
5304 return false;
5305 case UTT_IsPolymorphic:
5306 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5307 return !RD->isUnion() && RD->isPolymorphic();
5308 return false;
5309 case UTT_IsAbstract:
5310 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5311 return !RD->isUnion() && RD->isAbstract();
5312 return false;
5313 case UTT_IsAggregate:
5314 // Report vector extensions and complex types as aggregates because they
5315 // support aggregate initialization. GCC mirrors this behavior for vectors
5316 // but not _Complex.
5317 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5319 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5320 // even then only when it is used with the 'interface struct ...' syntax
5321 // Clang doesn't support /CLR which makes this type trait moot.
5322 case UTT_IsInterfaceClass:
5323 return false;
5324 case UTT_IsFinal:
5325 case UTT_IsSealed:
5326 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5327 return RD->hasAttr<FinalAttr>();
5328 return false;
5329 case UTT_IsSigned:
5330 // Enum types should always return false.
5331 // Floating points should always return true.
5332 return T->isFloatingType() ||
5334 case UTT_IsUnsigned:
5335 // Enum types should always return false.
5336 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5337
5338 // Type trait expressions which query classes regarding their construction,
5339 // destruction, and copying. Rather than being based directly on the
5340 // related type predicates in the standard, they are specified by both
5341 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5342 // specifications.
5343 //
5344 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5345 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5346 //
5347 // Note that these builtins do not behave as documented in g++: if a class
5348 // has both a trivial and a non-trivial special member of a particular kind,
5349 // they return false! For now, we emulate this behavior.
5350 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5351 // does not correctly compute triviality in the presence of multiple special
5352 // members of the same kind. Revisit this once the g++ bug is fixed.
5353 case UTT_HasTrivialDefaultConstructor:
5354 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5355 // If __is_pod (type) is true then the trait is true, else if type is
5356 // a cv class or union type (or array thereof) with a trivial default
5357 // constructor ([class.ctor]) then the trait is true, else it is false.
5358 if (T.isPODType(C))
5359 return true;
5360 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5361 return RD->hasTrivialDefaultConstructor() &&
5363 return false;
5364 case UTT_HasTrivialMoveConstructor:
5365 // This trait is implemented by MSVC 2012 and needed to parse the
5366 // standard library headers. Specifically this is used as the logic
5367 // behind std::is_trivially_move_constructible (20.9.4.3).
5368 if (T.isPODType(C))
5369 return true;
5370 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5372 return false;
5373 case UTT_HasTrivialCopy:
5374 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5375 // If __is_pod (type) is true or type is a reference type then
5376 // the trait is true, else if type is a cv class or union type
5377 // with a trivial copy constructor ([class.copy]) then the trait
5378 // is true, else it is false.
5379 if (T.isPODType(C) || T->isReferenceType())
5380 return true;
5381 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5382 return RD->hasTrivialCopyConstructor() &&
5384 return false;
5385 case UTT_HasTrivialMoveAssign:
5386 // This trait is implemented by MSVC 2012 and needed to parse the
5387 // standard library headers. Specifically it is used as the logic
5388 // behind std::is_trivially_move_assignable (20.9.4.3)
5389 if (T.isPODType(C))
5390 return true;
5391 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5393 return false;
5394 case UTT_HasTrivialAssign:
5395 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5396 // If type is const qualified or is a reference type then the
5397 // trait is false. Otherwise if __is_pod (type) is true then the
5398 // trait is true, else if type is a cv class or union type with
5399 // a trivial copy assignment ([class.copy]) then the trait is
5400 // true, else it is false.
5401 // Note: the const and reference restrictions are interesting,
5402 // given that const and reference members don't prevent a class
5403 // from having a trivial copy assignment operator (but do cause
5404 // errors if the copy assignment operator is actually used, q.v.
5405 // [class.copy]p12).
5406
5407 if (T.isConstQualified())
5408 return false;
5409 if (T.isPODType(C))
5410 return true;
5411 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5412 return RD->hasTrivialCopyAssignment() &&
5414 return false;
5415 case UTT_IsDestructible:
5416 case UTT_IsTriviallyDestructible:
5417 case UTT_IsNothrowDestructible:
5418 // C++14 [meta.unary.prop]:
5419 // For reference types, is_destructible<T>::value is true.
5420 if (T->isReferenceType())
5421 return true;
5422
5423 // Objective-C++ ARC: autorelease types don't require destruction.
5424 if (T->isObjCLifetimeType() &&
5425 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5426 return true;
5427
5428 // C++14 [meta.unary.prop]:
5429 // For incomplete types and function types, is_destructible<T>::value is
5430 // false.
5431 if (T->isIncompleteType() || T->isFunctionType())
5432 return false;
5433
5434 // A type that requires destruction (via a non-trivial destructor or ARC
5435 // lifetime semantics) is not trivially-destructible.
5436 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5437 return false;
5438
5439 // C++14 [meta.unary.prop]:
5440 // For object types and given U equal to remove_all_extents_t<T>, if the
5441 // expression std::declval<U&>().~U() is well-formed when treated as an
5442 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5443 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5444 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5445 if (!Destructor)
5446 return false;
5447 // C++14 [dcl.fct.def.delete]p2:
5448 // A program that refers to a deleted function implicitly or
5449 // explicitly, other than to declare it, is ill-formed.
5450 if (Destructor->isDeleted())
5451 return false;
5452 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5453 return false;
5454 if (UTT == UTT_IsNothrowDestructible) {
5455 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5456 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5457 if (!CPT || !CPT->isNothrow())
5458 return false;
5459 }
5460 }
5461 return true;
5462
5463 case UTT_HasTrivialDestructor:
5464 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5465 // If __is_pod (type) is true or type is a reference type
5466 // then the trait is true, else if type is a cv class or union
5467 // type (or array thereof) with a trivial destructor
5468 // ([class.dtor]) then the trait is true, else it is
5469 // false.
5470 if (T.isPODType(C) || T->isReferenceType())
5471 return true;
5472
5473 // Objective-C++ ARC: autorelease types don't require destruction.
5474 if (T->isObjCLifetimeType() &&
5475 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5476 return true;
5477
5478 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5479 return RD->hasTrivialDestructor();
5480 return false;
5481 // TODO: Propagate nothrowness for implicitly declared special members.
5482 case UTT_HasNothrowAssign:
5483 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5484 // If type is const qualified or is a reference type then the
5485 // trait is false. Otherwise if __has_trivial_assign (type)
5486 // is true then the trait is true, else if type is a cv class
5487 // or union type with copy assignment operators that are known
5488 // not to throw an exception then the trait is true, else it is
5489 // false.
5490 if (C.getBaseElementType(T).isConstQualified())
5491 return false;
5492 if (T->isReferenceType())
5493 return false;
5494 if (T.isPODType(C) || T->isObjCLifetimeType())
5495 return true;
5496
5497 if (const RecordType *RT = T->getAs<RecordType>())
5498 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5502 return false;
5503 case UTT_HasNothrowMoveAssign:
5504 // This trait is implemented by MSVC 2012 and needed to parse the
5505 // standard library headers. Specifically this is used as the logic
5506 // behind std::is_nothrow_move_assignable (20.9.4.3).
5507 if (T.isPODType(C))
5508 return true;
5509
5510 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5511 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5515 return false;
5516 case UTT_HasNothrowCopy:
5517 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5518 // If __has_trivial_copy (type) is true then the trait is true, else
5519 // if type is a cv class or union type with copy constructors that are
5520 // known not to throw an exception then the trait is true, else it is
5521 // false.
5522 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5523 return true;
5524 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5525 if (RD->hasTrivialCopyConstructor() &&
5527 return true;
5528
5529 bool FoundConstructor = false;
5530 unsigned FoundTQs;
5531 for (const auto *ND : Self.LookupConstructors(RD)) {
5532 // A template constructor is never a copy constructor.
5533 // FIXME: However, it may actually be selected at the actual overload
5534 // resolution point.
5535 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5536 continue;
5537 // UsingDecl itself is not a constructor
5538 if (isa<UsingDecl>(ND))
5539 continue;
5540 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5541 if (Constructor->isCopyConstructor(FoundTQs)) {
5542 FoundConstructor = true;
5543 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5544 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5545 if (!CPT)
5546 return false;
5547 // TODO: check whether evaluating default arguments can throw.
5548 // For now, we'll be conservative and assume that they can throw.
5549 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5550 return false;
5551 }
5552 }
5553
5554 return FoundConstructor;
5555 }
5556 return false;
5557 case UTT_HasNothrowConstructor:
5558 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5559 // If __has_trivial_constructor (type) is true then the trait is
5560 // true, else if type is a cv class or union type (or array
5561 // thereof) with a default constructor that is known not to
5562 // throw an exception then the trait is true, else it is false.
5563 if (T.isPODType(C) || T->isObjCLifetimeType())
5564 return true;
5565 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5566 if (RD->hasTrivialDefaultConstructor() &&
5568 return true;
5569
5570 bool FoundConstructor = false;
5571 for (const auto *ND : Self.LookupConstructors(RD)) {
5572 // FIXME: In C++0x, a constructor template can be a default constructor.
5573 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5574 continue;
5575 // UsingDecl itself is not a constructor
5576 if (isa<UsingDecl>(ND))
5577 continue;
5578 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5579 if (Constructor->isDefaultConstructor()) {
5580 FoundConstructor = true;
5581 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5582 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5583 if (!CPT)
5584 return false;
5585 // FIXME: check whether evaluating default arguments can throw.
5586 // For now, we'll be conservative and assume that they can throw.
5587 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5588 return false;
5589 }
5590 }
5591 return FoundConstructor;
5592 }
5593 return false;
5594 case UTT_HasVirtualDestructor:
5595 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5596 // If type is a class type with a virtual destructor ([class.dtor])
5597 // then the trait is true, else it is false.
5598 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5599 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5600 return Destructor->isVirtual();
5601 return false;
5602
5603 // These type trait expressions are modeled on the specifications for the
5604 // Embarcadero C++0x type trait functions:
5605 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5606 case UTT_IsCompleteType:
5607 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5608 // Returns True if and only if T is a complete type at the point of the
5609 // function call.
5610 return !T->isIncompleteType();
5611 case UTT_HasUniqueObjectRepresentations:
5612 return C.hasUniqueObjectRepresentations(T);
5613 case UTT_IsTriviallyRelocatable:
5614 return T.isTriviallyRelocatableType(C);
5615 case UTT_IsReferenceable:
5616 return T.isReferenceable();
5617 case UTT_CanPassInRegs:
5618 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5619 return RD->canPassInRegisters();
5620 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5621 return false;
5622 case UTT_IsTriviallyEqualityComparable:
5623 return T.isTriviallyEqualityComparableType(C);
5624 }
5625}
5626
5627static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5628 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5629
5631 SourceLocation KWLoc,
5633 SourceLocation RParenLoc,
5634 bool IsDependent) {
5635 if (IsDependent)
5636 return false;
5637
5638 if (Kind <= UTT_Last)
5639 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5640
5641 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5642 // alongside the IsConstructible traits to avoid duplication.
5643 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary && Kind != BTT_ReferenceConstructsFromTemporary)
5644 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5645 Args[1], RParenLoc);
5646
5647 switch (Kind) {
5648 case clang::BTT_ReferenceBindsToTemporary:
5649 case clang::BTT_ReferenceConstructsFromTemporary:
5650 case clang::TT_IsConstructible:
5651 case clang::TT_IsNothrowConstructible:
5652 case clang::TT_IsTriviallyConstructible: {
5653 // C++11 [meta.unary.prop]:
5654 // is_trivially_constructible is defined as:
5655 //
5656 // is_constructible<T, Args...>::value is true and the variable
5657 // definition for is_constructible, as defined below, is known to call
5658 // no operation that is not trivial.
5659 //
5660 // The predicate condition for a template specialization
5661 // is_constructible<T, Args...> shall be satisfied if and only if the
5662 // following variable definition would be well-formed for some invented
5663 // variable t:
5664 //
5665 // T t(create<Args>()...);
5666 assert(!Args.empty());
5667
5668 // Precondition: T and all types in the parameter pack Args shall be
5669 // complete types, (possibly cv-qualified) void, or arrays of
5670 // unknown bound.
5671 for (const auto *TSI : Args) {
5672 QualType ArgTy = TSI->getType();
5673 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5674 continue;
5675
5676 if (S.RequireCompleteType(KWLoc, ArgTy,
5677 diag::err_incomplete_type_used_in_type_trait_expr))
5678 return false;
5679 }
5680
5681 // Make sure the first argument is not incomplete nor a function type.
5682 QualType T = Args[0]->getType();
5683 if (T->isIncompleteType() || T->isFunctionType())
5684 return false;
5685
5686 // Make sure the first argument is not an abstract type.
5688 if (RD && RD->isAbstract())
5689 return false;
5690
5691 llvm::BumpPtrAllocator OpaqueExprAllocator;
5692 SmallVector<Expr *, 2> ArgExprs;
5693 ArgExprs.reserve(Args.size() - 1);
5694 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5695 QualType ArgTy = Args[I]->getType();
5696 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5697 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5698 ArgExprs.push_back(
5699 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5700 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5703 }
5704
5705 // Perform the initialization in an unevaluated context within a SFINAE
5706 // trap at translation unit scope.
5709 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5714 RParenLoc));
5715 InitializationSequence Init(S, To, InitKind, ArgExprs);
5716 if (Init.Failed())
5717 return false;
5718
5719 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5720 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5721 return false;
5722
5723 if (Kind == clang::TT_IsConstructible)
5724 return true;
5725
5726 if (Kind == clang::BTT_ReferenceBindsToTemporary || Kind == clang::BTT_ReferenceConstructsFromTemporary) {
5727 if (!T->isReferenceType())
5728 return false;
5729
5730 if (!Init.isDirectReferenceBinding())
5731 return true;
5732
5733 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5734 return false;
5735
5736 QualType U = Args[1]->getType();
5737 if (U->isReferenceType())
5738 return false;
5739
5740 TypeSourceInfo *TPtr = S.Context.CreateTypeSourceInfo(S.Context.getPointerType(S.BuiltinRemoveReference(T, UnaryTransformType::RemoveCVRef, {})));
5741 TypeSourceInfo *UPtr = S.Context.CreateTypeSourceInfo(S.Context.getPointerType(S.BuiltinRemoveReference(U, UnaryTransformType::RemoveCVRef, {})));
5742 return EvaluateBinaryTypeTrait(S, TypeTrait::BTT_IsConvertibleTo, UPtr, TPtr, RParenLoc);
5743 }
5744
5745 if (Kind == clang::TT_IsNothrowConstructible)
5746 return S.canThrow(Result.get()) == CT_Cannot;
5747
5748 if (Kind == clang::TT_IsTriviallyConstructible) {
5749 // Under Objective-C ARC and Weak, if the destination has non-trivial
5750 // Objective-C lifetime, this is a non-trivial construction.
5751 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5752 return false;
5753
5754 // The initialization succeeded; now make sure there are no non-trivial
5755 // calls.
5756 return !Result.get()->hasNonTrivialCall(S.Context);
5757 }
5758
5759 llvm_unreachable("unhandled type trait");
5760 return false;
5761 }
5762 default: llvm_unreachable("not a TT");
5763 }
5764
5765 return false;
5766}
5767
5768namespace {
5769void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5770 SourceLocation KWLoc) {
5771 TypeTrait Replacement;
5772 switch (Kind) {
5773 case UTT_HasNothrowAssign:
5774 case UTT_HasNothrowMoveAssign:
5775 Replacement = BTT_IsNothrowAssignable;
5776 break;
5777 case UTT_HasNothrowCopy:
5778 case UTT_HasNothrowConstructor:
5779 Replacement = TT_IsNothrowConstructible;
5780 break;
5781 case UTT_HasTrivialAssign:
5782 case UTT_HasTrivialMoveAssign:
5783 Replacement = BTT_IsTriviallyAssignable;
5784 break;
5785 case UTT_HasTrivialCopy:
5786 Replacement = UTT_IsTriviallyCopyable;
5787 break;
5788 case UTT_HasTrivialDefaultConstructor:
5789 case UTT_HasTrivialMoveConstructor:
5790 Replacement = TT_IsTriviallyConstructible;
5791 break;
5792 case UTT_HasTrivialDestructor:
5793 Replacement = UTT_IsTriviallyDestructible;
5794 break;
5795 default:
5796 return;
5797 }
5798 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5799 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5800}
5801}
5802
5803bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5804 if (Arity && N != Arity) {
5805 Diag(Loc, diag::err_type_trait_arity)
5806 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5807 return false;
5808 }
5809
5810 if (!Arity && N == 0) {
5811 Diag(Loc, diag::err_type_trait_arity)
5812 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5813 return false;
5814 }
5815 return true;
5816}
5817
5819 Bool,
5820};
5821
5823 return TypeTraitReturnType::Bool;
5824}
5825
5828 SourceLocation RParenLoc) {
5829 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5830 return ExprError();
5831
5833 *this, Kind, KWLoc, Args[0]->getType()))
5834 return ExprError();
5835
5836 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5837
5838 bool Dependent = false;
5839 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5840 if (Args[I]->getType()->isDependentType()) {
5841 Dependent = true;
5842 break;
5843 }
5844 }
5845
5846 switch (GetReturnType(Kind)) {
5847 case TypeTraitReturnType::Bool: {
5848 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5849 Dependent);
5851 KWLoc, Kind, Args, RParenLoc, Result);
5852 }
5853 }
5854 llvm_unreachable("unhandled type trait return type");
5855}
5856
5859 SourceLocation RParenLoc) {
5861 ConvertedArgs.reserve(Args.size());
5862
5863 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5864 TypeSourceInfo *TInfo;
5865 QualType T = GetTypeFromParser(Args[I], &TInfo);
5866 if (!TInfo)
5867 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5868
5869 ConvertedArgs.push_back(TInfo);
5870 }
5871
5872 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5873}
5874
5876 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
5877 QualType LhsT = Lhs->getType();
5878 QualType RhsT = Rhs->getType();
5879
5880 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5881 "Cannot evaluate traits of dependent types");
5882
5883 switch(BTT) {
5884 case BTT_IsBaseOf: {
5885 // C++0x [meta.rel]p2
5886 // Base is a base class of Derived without regard to cv-qualifiers or
5887 // Base and Derived are not unions and name the same class type without
5888 // regard to cv-qualifiers.
5889
5890 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5891 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5892 if (!rhsRecord || !lhsRecord) {
5893 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5894 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5895 if (!LHSObjTy || !RHSObjTy)
5896 return false;
5897
5898 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5899 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5900 if (!BaseInterface || !DerivedInterface)
5901 return false;
5902
5903 if (Self.RequireCompleteType(
5904 Rhs->getTypeLoc().getBeginLoc(), RhsT,
5905 diag::err_incomplete_type_used_in_type_trait_expr))
5906 return false;
5907
5908 return BaseInterface->isSuperClassOf(DerivedInterface);
5909 }
5910
5911 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5912 == (lhsRecord == rhsRecord));
5913
5914 // Unions are never base classes, and never have base classes.
5915 // It doesn't matter if they are complete or not. See PR#41843
5916 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5917 return false;
5918 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5919 return false;
5920
5921 if (lhsRecord == rhsRecord)
5922 return true;
5923
5924 // C++0x [meta.rel]p2:
5925 // If Base and Derived are class types and are different types
5926 // (ignoring possible cv-qualifiers) then Derived shall be a
5927 // complete type.
5928 if (Self.RequireCompleteType(
5929 Rhs->getTypeLoc().getBeginLoc(), RhsT,
5930 diag::err_incomplete_type_used_in_type_trait_expr))
5931 return false;
5932
5933 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5934 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5935 }
5936 case BTT_IsSame:
5937 return Self.Context.hasSameType(LhsT, RhsT);
5938 case BTT_TypeCompatible: {
5939 // GCC ignores cv-qualifiers on arrays for this builtin.
5940 Qualifiers LhsQuals, RhsQuals;
5941 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5942 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5943 return Self.Context.typesAreCompatible(Lhs, Rhs);
5944 }
5945 case BTT_IsConvertible:
5946 case BTT_IsConvertibleTo:
5947 case BTT_IsNothrowConvertible: {
5948 // C++0x [meta.rel]p4:
5949 // Given the following function prototype:
5950 //
5951 // template <class T>
5952 // typename add_rvalue_reference<T>::type create();
5953 //
5954 // the predicate condition for a template specialization
5955 // is_convertible<From, To> shall be satisfied if and only if
5956 // the return expression in the following code would be
5957 // well-formed, including any implicit conversions to the return
5958 // type of the function:
5959 //
5960 // To test() {
5961 // return create<From>();
5962 // }
5963 //
5964 // Access checking is performed as if in a context unrelated to To and
5965 // From. Only the validity of the immediate context of the expression
5966 // of the return-statement (including conversions to the return type)
5967 // is considered.
5968 //
5969 // We model the initialization as a copy-initialization of a temporary
5970 // of the appropriate type, which for this expression is identical to the
5971 // return statement (since NRVO doesn't apply).
5972
5973 // Functions aren't allowed to return function or array types.
5974 if (RhsT->isFunctionType() || RhsT->isArrayType())
5975 return false;
5976
5977 // A return statement in a void function must have void type.
5978 if (RhsT->isVoidType())
5979 return LhsT->isVoidType();
5980
5981 // A function definition requires a complete, non-abstract return type.
5982 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5983 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5984 return false;
5985
5986 // Compute the result of add_rvalue_reference.
5987 if (LhsT->isObjectType() || LhsT->isFunctionType())
5988 LhsT = Self.Context.getRValueReferenceType(LhsT);
5989
5990 // Build a fake source and destination for initialization.
5992 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5994 Expr *FromPtr = &From;
5996 SourceLocation()));
5997
5998 // Perform the initialization in an unevaluated context within a SFINAE
5999 // trap at translation unit scope.
6002 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6003 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6004 InitializationSequence Init(Self, To, Kind, FromPtr);
6005 if (Init.Failed())
6006 return false;
6007
6008 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
6009 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
6010 return false;
6011
6012 if (BTT != BTT_IsNothrowConvertible)
6013 return true;
6014
6015 return Self.canThrow(Result.get()) == CT_Cannot;
6016 }
6017
6018 case BTT_IsAssignable:
6019 case BTT_IsNothrowAssignable:
6020 case BTT_IsTriviallyAssignable: {
6021 // C++11 [meta.unary.prop]p3:
6022 // is_trivially_assignable is defined as:
6023 // is_assignable<T, U>::value is true and the assignment, as defined by
6024 // is_assignable, is known to call no operation that is not trivial
6025 //
6026 // is_assignable is defined as:
6027 // The expression declval<T>() = declval<U>() is well-formed when
6028 // treated as an unevaluated operand (Clause 5).
6029 //
6030 // For both, T and U shall be complete types, (possibly cv-qualified)
6031 // void, or arrays of unknown bound.
6032 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6033 Self.RequireCompleteType(
6034 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6035 diag::err_incomplete_type_used_in_type_trait_expr))
6036 return false;
6037 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6038 Self.RequireCompleteType(
6039 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6040 diag::err_incomplete_type_used_in_type_trait_expr))
6041 return false;
6042
6043 // cv void is never assignable.
6044 if (LhsT->isVoidType() || RhsT->isVoidType())
6045 return false;
6046
6047 // Build expressions that emulate the effect of declval<T>() and
6048 // declval<U>().
6049 if (LhsT->isObjectType() || LhsT->isFunctionType())
6050 LhsT = Self.Context.getRValueReferenceType(LhsT);
6051 if (RhsT->isObjectType() || RhsT->isFunctionType())
6052 RhsT = Self.Context.getRValueReferenceType(RhsT);
6053 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6055 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6057
6058 // Attempt the assignment in an unevaluated context within a SFINAE
6059 // trap at translation unit scope.
6062 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6063 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6064 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6065 &Rhs);
6066 if (Result.isInvalid())
6067 return false;
6068
6069 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6070 Self.CheckUnusedVolatileAssignment(Result.get());
6071
6072 if (SFINAE.hasErrorOccurred())
6073 return false;
6074
6075 if (BTT == BTT_IsAssignable)
6076 return true;
6077
6078 if (BTT == BTT_IsNothrowAssignable)
6079 return Self.canThrow(Result.get()) == CT_Cannot;
6080
6081 if (BTT == BTT_IsTriviallyAssignable) {
6082 // Under Objective-C ARC and Weak, if the destination has non-trivial
6083 // Objective-C lifetime, this is a non-trivial assignment.
6085 return false;
6086
6087 return !Result.get()->hasNonTrivialCall(Self.Context);
6088 }
6089
6090 llvm_unreachable("unhandled type trait");
6091 return false;
6092 }
6093 case BTT_IsLayoutCompatible: {
6094 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6095 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6096 diag::err_incomplete_type);
6097 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6098 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6099 diag::err_incomplete_type);
6100
6101 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6102 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6103
6104 return Self.IsLayoutCompatible(LhsT, RhsT);
6105 }
6106 case BTT_IsPointerInterconvertibleBaseOf: {
6107 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6108 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6109 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6110 diag::err_incomplete_type);
6111 }
6112
6114 tok::kw___is_pointer_interconvertible_base_of);
6116 tok::kw___is_pointer_interconvertible_base_of);
6117
6118 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6119 }
6120 default: llvm_unreachable("not a BTT");
6121 }
6122 llvm_unreachable("Unknown type trait or not implemented");
6123}
6124
6126 SourceLocation KWLoc,
6127 ParsedType Ty,
6128 Expr* DimExpr,
6129 SourceLocation RParen) {
6130 TypeSourceInfo *TSInfo;
6131 QualType T = GetTypeFromParser(Ty, &TSInfo);
6132 if (!TSInfo)
6134
6135 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6136}
6137
6139 QualType T, Expr *DimExpr,
6140 SourceLocation KeyLoc) {
6141 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6142
6143 switch(ATT) {
6144 case ATT_ArrayRank:
6145 if (T->isArrayType()) {
6146 unsigned Dim = 0;
6147 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6148 ++Dim;
6149 T = AT->getElementType();
6150 }
6151 return Dim;
6152 }
6153 return 0;
6154
6155 case ATT_ArrayExtent: {
6156 llvm::APSInt Value;
6157 uint64_t Dim;
6158 if (Self.VerifyIntegerConstantExpression(
6159 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6160 .isInvalid())
6161 return 0;
6162 if (Value.isSigned() && Value.isNegative()) {
6163 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6164 << DimExpr->getSourceRange();
6165 return 0;
6166 }
6167 Dim = Value.getLimitedValue();
6168
6169 if (T->isArrayType()) {
6170 unsigned D = 0;
6171 bool Matched = false;
6172 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6173 if (Dim == D) {
6174 Matched = true;
6175 break;
6176 }
6177 ++D;
6178 T = AT->getElementType();
6179 }
6180
6181 if (Matched && T->isArrayType()) {
6182 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6183 return CAT->getLimitedSize();
6184 }
6185 }
6186 return 0;
6187 }
6188 }
6189 llvm_unreachable("Unknown type trait or not implemented");
6190}
6191
6193 SourceLocation KWLoc,
6194 TypeSourceInfo *TSInfo,
6195 Expr* DimExpr,
6196 SourceLocation RParen) {
6197 QualType T = TSInfo->getType();
6198
6199 // FIXME: This should likely be tracked as an APInt to remove any host
6200 // assumptions about the width of size_t on the target.
6201 uint64_t Value = 0;
6202 if (!T->isDependentType())
6203 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6204
6205 // While the specification for these traits from the Embarcadero C++
6206 // compiler's documentation says the return type is 'unsigned int', Clang
6207 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6208 // compiler, there is no difference. On several other platforms this is an
6209 // important distinction.
6210 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6211 RParen, Context.getSizeType());
6212}
6213
6215 SourceLocation KWLoc,
6216 Expr *Queried,
6217 SourceLocation RParen) {
6218 // If error parsing the expression, ignore.
6219 if (!Queried)
6220 return ExprError();
6221
6222 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6223
6224 return Result;
6225}
6226
6228 switch (ET) {
6229 case ET_IsLValueExpr: return E->isLValue();
6230 case ET_IsRValueExpr:
6231 return E->isPRValue();
6232 }
6233 llvm_unreachable("Expression trait not covered by switch");
6234}
6235
6237 SourceLocation KWLoc,
6238 Expr *Queried,
6239 SourceLocation RParen) {
6240 if (Queried->isTypeDependent()) {
6241 // Delay type-checking for type-dependent expressions.
6242 } else if (Queried->hasPlaceholderType()) {
6243 ExprResult PE = CheckPlaceholderExpr(Queried);
6244 if (PE.isInvalid()) return ExprError();
6245 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6246 }
6247
6248 bool Value = EvaluateExpressionTrait(ET, Queried);
6249
6250 return new (Context)
6251 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6252}
6253
6255 ExprValueKind &VK,
6256 SourceLocation Loc,
6257 bool isIndirect) {
6258 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6259 "placeholders should have been weeded out by now");
6260
6261 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6262 // temporary materialization conversion otherwise.
6263 if (isIndirect)
6264 LHS = DefaultLvalueConversion(LHS.get());
6265 else if (LHS.get()->isPRValue())
6267 if (LHS.isInvalid())
6268 return QualType();
6269
6270 // The RHS always undergoes lvalue conversions.
6271 RHS = DefaultLvalueConversion(RHS.get());
6272 if (RHS.isInvalid()) return QualType();
6273
6274 const char *OpSpelling = isIndirect ? "->*" : ".*";
6275 // C++ 5.5p2
6276 // The binary operator .* [p3: ->*] binds its second operand, which shall
6277 // be of type "pointer to member of T" (where T is a completely-defined
6278 // class type) [...]
6279 QualType RHSType = RHS.get()->getType();
6280 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6281 if (!MemPtr) {
6282 Diag(Loc, diag::err_bad_memptr_rhs)
6283 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6284 return QualType();
6285 }
6286
6287 QualType Class(MemPtr->getClass(), 0);
6288
6289 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6290 // member pointer points must be completely-defined. However, there is no
6291 // reason for this semantic distinction, and the rule is not enforced by
6292 // other compilers. Therefore, we do not check this property, as it is
6293 // likely to be considered a defect.
6294
6295 // C++ 5.5p2
6296 // [...] to its first operand, which shall be of class T or of a class of
6297 // which T is an unambiguous and accessible base class. [p3: a pointer to
6298 // such a class]
6299 QualType LHSType = LHS.get()->getType();
6300 if (isIndirect) {
6301 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6302 LHSType = Ptr->getPointeeType();
6303 else {
6304 Diag(Loc, diag::err_bad_memptr_lhs)
6305 << OpSpelling << 1 << LHSType
6307 return QualType();
6308 }
6309 }
6310
6311 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6312 // If we want to check the hierarchy, we need a complete type.
6313 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6314 OpSpelling, (int)isIndirect)) {
6315 return QualType();
6316 }
6317
6318 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6319 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6320 << (int)isIndirect << LHS.get()->getType();
6321 return QualType();
6322 }
6323
6324 CXXCastPath BasePath;
6326 LHSType, Class, Loc,
6327 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6328 &BasePath))
6329 return QualType();
6330
6331 // Cast LHS to type of use.
6332 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6333 if (isIndirect)
6334 UseType = Context.getPointerType(UseType);
6335 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6336 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6337 &BasePath);
6338 }
6339
6340 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6341 // Diagnose use of pointer-to-member type which when used as
6342 // the functional cast in a pointer-to-member expression.
6343 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6344 return QualType();
6345 }
6346
6347 // C++ 5.5p2
6348 // The result is an object or a function of the type specified by the
6349 // second operand.
6350 // The cv qualifiers are the union of those in the pointer and the left side,
6351 // in accordance with 5.5p5 and 5.2.5.
6352 QualType Result = MemPtr->getPointeeType();
6354
6355 // C++0x [expr.mptr.oper]p6:
6356 // In a .* expression whose object expression is an rvalue, the program is
6357 // ill-formed if the second operand is a pointer to member function with
6358 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6359 // expression is an lvalue, the program is ill-formed if the second operand
6360 // is a pointer to member function with ref-qualifier &&.
6361 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6362 switch (Proto->getRefQualifier()) {
6363 case RQ_None:
6364 // Do nothing
6365 break;
6366
6367 case RQ_LValue:
6368 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6369 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6370 // is (exactly) 'const'.
6371 if (Proto->isConst() && !Proto->isVolatile())
6373 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6374 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6375 else
6376 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6377 << RHSType << 1 << LHS.get()->getSourceRange();
6378 }
6379 break;
6380
6381 case RQ_RValue:
6382 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6383 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6384 << RHSType << 0 << LHS.get()->getSourceRange();
6385 break;
6386 }
6387 }
6388
6389 // C++ [expr.mptr.oper]p6:
6390 // The result of a .* expression whose second operand is a pointer
6391 // to a data member is of the same value category as its
6392 // first operand. The result of a .* expression whose second
6393 // operand is a pointer to a member function is a prvalue. The
6394 // result of an ->* expression is an lvalue if its second operand
6395 // is a pointer to data member and a prvalue otherwise.
6396 if (Result->isFunctionType()) {
6397 VK = VK_PRValue;
6398 return Context.BoundMemberTy;
6399 } else if (isIndirect) {
6400 VK = VK_LValue;
6401 } else {
6402 VK = LHS.get()->getValueKind();
6403 }
6404
6405 return Result;
6406}
6407
6408/// Try to convert a type to another according to C++11 5.16p3.
6409///
6410/// This is part of the parameter validation for the ? operator. If either
6411/// value operand is a class type, the two operands are attempted to be
6412/// converted to each other. This function does the conversion in one direction.
6413/// It returns true if the program is ill-formed and has already been diagnosed
6414/// as such.
6415static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6416 SourceLocation QuestionLoc,
6417 bool &HaveConversion,
6418 QualType &ToType) {
6419 HaveConversion = false;
6420 ToType = To->getType();
6421
6422 InitializationKind Kind =
6424 // C++11 5.16p3
6425 // The process for determining whether an operand expression E1 of type T1
6426 // can be converted to match an operand expression E2 of type T2 is defined
6427 // as follows:
6428 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6429 // implicitly converted to type "lvalue reference to T2", subject to the
6430 // constraint that in the conversion the reference must bind directly to
6431 // an lvalue.
6432 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6433 // implicitly converted to the type "rvalue reference to R2", subject to
6434 // the constraint that the reference must bind directly.
6435 if (To->isGLValue()) {
6436 QualType T = Self.Context.getReferenceQualifiedType(To);
6438
6439 InitializationSequence InitSeq(Self, Entity, Kind, From);
6440 if (InitSeq.isDirectReferenceBinding()) {
6441 ToType = T;
6442 HaveConversion = true;
6443 return false;
6444 }
6445
6446 if (InitSeq.isAmbiguous())
6447 return InitSeq.Diagnose(Self, Entity, Kind, From);
6448 }
6449
6450 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6451 // -- if E1 and E2 have class type, and the underlying class types are
6452 // the same or one is a base class of the other:
6453 QualType FTy = From->getType();
6454 QualType TTy = To->getType();
6455 const RecordType *FRec = FTy->getAs<RecordType>();
6456 const RecordType *TRec = TTy->getAs<RecordType>();
6457 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6458 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6459 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6460 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6461 // E1 can be converted to match E2 if the class of T2 is the
6462 // same type as, or a base class of, the class of T1, and
6463 // [cv2 > cv1].
6464 if (FRec == TRec || FDerivedFromT) {
6465 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6467 InitializationSequence InitSeq(Self, Entity, Kind, From);
6468 if (InitSeq) {
6469 HaveConversion = true;
6470 return false;
6471 }
6472
6473 if (InitSeq.isAmbiguous())
6474 return InitSeq.Diagnose(Self, Entity, Kind, From);
6475 }
6476 }
6477
6478 return false;
6479 }
6480
6481 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6482 // implicitly converted to the type that expression E2 would have
6483 // if E2 were converted to an rvalue (or the type it has, if E2 is
6484 // an rvalue).
6485 //
6486 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6487 // to the array-to-pointer or function-to-pointer conversions.
6488 TTy = TTy.getNonLValueExprType(Self.Context);
6489
6491 InitializationSequence InitSeq(Self, Entity, Kind, From);
6492 HaveConversion = !InitSeq.Failed();
6493 ToType = TTy;
6494 if (InitSeq.isAmbiguous())
6495 return InitSeq.Diagnose(Self, Entity, Kind, From);
6496
6497 return false;
6498}
6499
6500/// Try to find a common type for two according to C++0x 5.16p5.
6501///
6502/// This is part of the parameter validation for the ? operator. If either
6503/// value operand is a class type, overload resolution is used to find a
6504/// conversion to a common type.
6506 SourceLocation QuestionLoc) {
6507 Expr *Args[2] = { LHS.get(), RHS.get() };
6508 OverloadCandidateSet CandidateSet(QuestionLoc,
6510 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6511 CandidateSet);
6512
6514 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6515 case OR_Success: {
6516 // We found a match. Perform the conversions on the arguments and move on.
6517 ExprResult LHSRes = Self.PerformImplicitConversion(
6518 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6520 if (LHSRes.isInvalid())
6521 break;
6522 LHS = LHSRes;
6523
6524 ExprResult RHSRes = Self.PerformImplicitConversion(
6525 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6527 if (RHSRes.isInvalid())
6528 break;
6529 RHS = RHSRes;
6530 if (Best->Function)
6531 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6532 return false;
6533 }
6534
6536
6537 // Emit a better diagnostic if one of the expressions is a null pointer
6538 // constant and the other is a pointer type. In this case, the user most
6539 // likely forgot to take the address of the other expression.
6540 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6541 return true;
6542
6543 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6544 << LHS.get()->getType() << RHS.get()->getType()
6545 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6546 return true;
6547
6548 case OR_Ambiguous:
6549 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6550 << LHS.get()->getType() << RHS.get()->getType()
6551 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6552 // FIXME: Print the possible common types by printing the return types of
6553 // the viable candidates.
6554 break;
6555
6556 case OR_Deleted:
6557 llvm_unreachable("Conditional operator has only built-in overloads");
6558 }
6559 return true;
6560}
6561
6562/// Perform an "extended" implicit conversion as returned by
6563/// TryClassUnification.
6566 InitializationKind Kind =
6568 Expr *Arg = E.get();
6569 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6570 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6571 if (Result.isInvalid())
6572 return true;
6573
6574 E = Result;
6575 return false;
6576}
6577
6578// Check the condition operand of ?: to see if it is valid for the GCC
6579// extension.
6581 QualType CondTy) {
6582 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6583 return false;
6584 const QualType EltTy =
6585 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6586 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6587 return EltTy->isIntegralType(Ctx);
6588}
6589
6591 QualType CondTy) {
6592 if (!CondTy->isSveVLSBuiltinType())
6593 return false;
6594 const QualType EltTy =
6595 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6596 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6597 return EltTy->isIntegralType(Ctx);
6598}
6599
6601 ExprResult &RHS,
6602 SourceLocation QuestionLoc) {
6605
6606 QualType CondType = Cond.get()->getType();
6607 const auto *CondVT = CondType->castAs<VectorType>();
6608 QualType CondElementTy = CondVT->getElementType();
6609 unsigned CondElementCount = CondVT->getNumElements();
6610 QualType LHSType = LHS.get()->getType();
6611 const auto *LHSVT = LHSType->getAs<VectorType>();
6612 QualType RHSType = RHS.get()->getType();
6613 const auto *RHSVT = RHSType->getAs<VectorType>();
6614
6615 QualType ResultType;
6616
6617
6618 if (LHSVT && RHSVT) {
6619 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6620 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6621 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6622 return {};
6623 }
6624
6625 // If both are vector types, they must be the same type.
6626 if (!Context.hasSameType(LHSType, RHSType)) {
6627 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6628 << LHSType << RHSType;
6629 return {};
6630 }
6631 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6632 } else if (LHSVT || RHSVT) {
6633 ResultType = CheckVectorOperands(
6634 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6635 /*AllowBoolConversions*/ false,
6636 /*AllowBoolOperation*/ true,
6637 /*ReportInvalid*/ true);
6638 if (ResultType.isNull())
6639 return {};
6640 } else {
6641 // Both are scalar.
6642 LHSType = LHSType.getUnqualifiedType();
6643 RHSType = RHSType.getUnqualifiedType();
6644 QualType ResultElementTy =
6645 Context.hasSameType(LHSType, RHSType)
6646 ? Context.getCommonSugaredType(LHSType, RHSType)
6647 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6649
6650 if (ResultElementTy->isEnumeralType()) {
6651 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6652 << ResultElementTy;
6653 return {};
6654 }
6655 if (CondType->isExtVectorType())
6656 ResultType =
6657 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6658 else
6659 ResultType = Context.getVectorType(
6660 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6661
6662 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6663 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6664 }
6665
6666 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6667 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6668 "Result should have been a vector type");
6669 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6670 QualType ResultElementTy = ResultVectorTy->getElementType();
6671 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6672
6673 if (ResultElementCount != CondElementCount) {
6674 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6675 << ResultType;
6676 return {};
6677 }
6678
6679 if (Context.getTypeSize(ResultElementTy) !=
6680 Context.getTypeSize(CondElementTy)) {
6681 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6682 << ResultType;
6683 return {};
6684 }
6685
6686 return ResultType;
6687}
6688
6690 ExprResult &LHS,
6691 ExprResult &RHS,
6692 SourceLocation QuestionLoc) {
6695
6696 QualType CondType = Cond.get()->getType();
6697 const auto *CondBT = CondType->castAs<BuiltinType>();
6698 QualType CondElementTy = CondBT->getSveEltType(Context);
6699 llvm::ElementCount CondElementCount =
6701
6702 QualType LHSType = LHS.get()->getType();
6703 const auto *LHSBT =
6704 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6705 QualType RHSType = RHS.get()->getType();
6706 const auto *RHSBT =
6707 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6708
6709 QualType ResultType;
6710
6711 if (LHSBT && RHSBT) {
6712 // If both are sizeless vector types, they must be the same type.
6713 if (!Context.hasSameType(LHSType, RHSType)) {
6714 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6715 << LHSType << RHSType;
6716 return QualType();
6717 }
6718 ResultType = LHSType;
6719 } else if (LHSBT || RHSBT) {
6720 ResultType = CheckSizelessVectorOperands(
6721 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6722 if (ResultType.isNull())
6723 return QualType();
6724 } else {
6725 // Both are scalar so splat
6726 QualType ResultElementTy;
6727 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6728 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6729
6730 if (Context.hasSameType(LHSType, RHSType))
6731 ResultElementTy = LHSType;
6732 else
6733 ResultElementTy =
6734 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6735
6736 if (ResultElementTy->isEnumeralType()) {
6737 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6738 << ResultElementTy;
6739 return QualType();
6740 }
6741
6742 ResultType = Context.getScalableVectorType(
6743 ResultElementTy, CondElementCount.getKnownMinValue());
6744
6745 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6746 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6747 }
6748
6749 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6750 "Result should have been a vector type");
6751 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6752 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6753 llvm::ElementCount ResultElementCount =
6754 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6755
6756 if (ResultElementCount != CondElementCount) {
6757 Diag(QuestionLoc, diag::err_conditional_vector_size)
6758 << CondType << ResultType;
6759 return QualType();
6760 }
6761
6762 if (Context.getTypeSize(ResultElementTy) !=
6763 Context.getTypeSize(CondElementTy)) {
6764 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6765 << CondType << ResultType;
6766 return QualType();
6767 }
6768
6769 return ResultType;
6770}
6771
6772/// Check the operands of ?: under C++ semantics.
6773///
6774/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6775/// extension. In this case, LHS == Cond. (But they're not aliases.)
6776///
6777/// This function also implements GCC's vector extension and the
6778/// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6779/// permit the use of a?b:c where the type of a is that of a integer vector with
6780/// the same number of elements and size as the vectors of b and c. If one of
6781/// either b or c is a scalar it is implicitly converted to match the type of
6782/// the vector. Otherwise the expression is ill-formed. If both b and c are
6783/// scalars, then b and c are checked and converted to the type of a if
6784/// possible.
6785///
6786/// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6787/// For the GCC extension, the ?: operator is evaluated as
6788/// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6789/// For the OpenCL extensions, the ?: operator is evaluated as
6790/// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
6791/// most-significant-bit-set(a[n]) ? b[n] : c[n]).
6793 ExprResult &RHS, ExprValueKind &VK,
6794 ExprObjectKind &OK,
6795 SourceLocation QuestionLoc) {
6796 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6797 // pointers.
6798
6799 // Assume r-value.
6800 VK = VK_PRValue;
6801 OK = OK_Ordinary;
6802 bool IsVectorConditional =
6804
6805 bool IsSizelessVectorConditional =
6807 Cond.get()->getType());
6808
6809 // C++11 [expr.cond]p1
6810 // The first expression is contextually converted to bool.
6811 if (!Cond.get()->isTypeDependent()) {
6812 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6814 : CheckCXXBooleanCondition(Cond.get());
6815 if (CondRes.isInvalid())
6816 return QualType();
6817 Cond = CondRes;
6818 } else {
6819 // To implement C++, the first expression typically doesn't alter the result
6820 // type of the conditional, however the GCC compatible vector extension
6821 // changes the result type to be that of the conditional. Since we cannot
6822 // know if this is a vector extension here, delay the conversion of the
6823 // LHS/RHS below until later.
6824 return Context.DependentTy;
6825 }
6826
6827
6828 // Either of the arguments dependent?
6829 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6830 return Context.DependentTy;
6831
6832 // C++11 [expr.cond]p2
6833 // If either the second or the third operand has type (cv) void, ...
6834 QualType LTy = LHS.get()->getType();
6835 QualType RTy = RHS.get()->getType();
6836 bool LVoid = LTy->isVoidType();
6837 bool RVoid = RTy->isVoidType();
6838 if (LVoid || RVoid) {
6839 // ... one of the following shall hold:
6840 // -- The second or the third operand (but not both) is a (possibly
6841 // parenthesized) throw-expression; the result is of the type
6842 // and value category of the other.
6843 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6844 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6845
6846 // Void expressions aren't legal in the vector-conditional expressions.
6847 if (IsVectorConditional) {
6848 SourceRange DiagLoc =
6849 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6850 bool IsThrow = LVoid ? LThrow : RThrow;
6851 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6852 << DiagLoc << IsThrow;
6853 return QualType();
6854 }
6855
6856 if (LThrow != RThrow) {
6857 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6858 VK = NonThrow->getValueKind();
6859 // DR (no number yet): the result is a bit-field if the
6860 // non-throw-expression operand is a bit-field.
6861 OK = NonThrow->getObjectKind();
6862 return NonThrow->getType();
6863 }
6864
6865 // -- Both the second and third operands have type void; the result is of
6866 // type void and is a prvalue.
6867 if (LVoid && RVoid)
6868 return Context.getCommonSugaredType(LTy, RTy);
6869
6870 // Neither holds, error.
6871 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6872 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6873 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6874 return QualType();
6875 }
6876
6877 // Neither is void.
6878 if (IsVectorConditional)
6879 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6880
6881 if (IsSizelessVectorConditional)
6882 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6883
6884 // WebAssembly tables are not allowed as conditional LHS or RHS.
6885 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6886 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6887 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6888 return QualType();
6889 }
6890
6891 // C++11 [expr.cond]p3
6892 // Otherwise, if the second and third operand have different types, and
6893 // either has (cv) class type [...] an attempt is made to convert each of
6894 // those operands to the type of the other.
6895 if (!Context.hasSameType(LTy, RTy) &&
6896 (LTy->isRecordType() || RTy->isRecordType())) {
6897 // These return true if a single direction is already ambiguous.
6898 QualType L2RType, R2LType;
6899 bool HaveL2R, HaveR2L;
6900 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6901 return QualType();
6902 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6903 return QualType();
6904
6905 // If both can be converted, [...] the program is ill-formed.
6906 if (HaveL2R && HaveR2L) {
6907 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6908 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6909 return QualType();
6910 }
6911
6912 // If exactly one conversion is possible, that conversion is applied to
6913 // the chosen operand and the converted operands are used in place of the
6914 // original operands for the remainder of this section.
6915 if (HaveL2R) {
6916 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6917 return QualType();
6918 LTy = LHS.get()->getType();
6919 } else if (HaveR2L) {
6920 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6921 return QualType();
6922 RTy = RHS.get()->getType();
6923 }
6924 }
6925
6926 // C++11 [expr.cond]p3
6927 // if both are glvalues of the same value category and the same type except
6928 // for cv-qualification, an attempt is made to convert each of those
6929 // operands to the type of the other.
6930 // FIXME:
6931 // Resolving a defect in P0012R1: we extend this to cover all cases where
6932 // one of the operands is reference-compatible with the other, in order
6933 // to support conditionals between functions differing in noexcept. This
6934 // will similarly cover difference in array bounds after P0388R4.
6935 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6936 // that instead?
6937 ExprValueKind LVK = LHS.get()->getValueKind();
6938 ExprValueKind RVK = RHS.get()->getValueKind();
6939 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6940 // DerivedToBase was already handled by the class-specific case above.
6941 // FIXME: Should we allow ObjC conversions here?
6942 const ReferenceConversions AllowedConversions =
6943 ReferenceConversions::Qualification |
6944 ReferenceConversions::NestedQualification |
6945 ReferenceConversions::Function;
6946
6947 ReferenceConversions RefConv;
6948 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6950 !(RefConv & ~AllowedConversions) &&
6951 // [...] subject to the constraint that the reference must bind
6952 // directly [...]
6953 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6954 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6955 RTy = RHS.get()->getType();
6956 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6958 !(RefConv & ~AllowedConversions) &&
6959 !LHS.get()->refersToBitField() &&
6960 !LHS.get()->refersToVectorElement()) {
6961 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6962 LTy = LHS.get()->getType();
6963 }
6964 }
6965
6966 // C++11 [expr.cond]p4
6967 // If the second and third operands are glvalues of the same value
6968 // category and have the same type, the result is of that type and
6969 // value category and it is a bit-field if the second or the third
6970 // operand is a bit-field, or if both are bit-fields.
6971 // We only extend this to bitfields, not to the crazy other kinds of
6972 // l-values.
6973 bool Same = Context.hasSameType(LTy, RTy);
6974 if (Same && LVK == RVK && LVK != VK_PRValue &&
6977 VK = LHS.get()->getValueKind();
6978 if (LHS.get()->getObjectKind() == OK_BitField ||
6979 RHS.get()->getObjectKind() == OK_BitField)
6980 OK = OK_BitField;
6981 return Context.getCommonSugaredType(LTy, RTy);
6982 }
6983
6984 // C++11 [expr.cond]p5
6985 // Otherwise, the result is a prvalue. If the second and third operands
6986 // do not have the same type, and either has (cv) class type, ...
6987 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6988 // ... overload resolution is used to determine the conversions (if any)
6989 // to be applied to the operands. If the overload resolution fails, the
6990 // program is ill-formed.
6991 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6992 return QualType();
6993 }
6994
6995 // C++11 [expr.cond]p6
6996 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6997 // conversions are performed on the second and third operands.
7000 if (LHS.isInvalid() || RHS.isInvalid())
7001 return QualType();
7002 LTy = LHS.get()->getType();
7003 RTy = RHS.get()->getType();
7004
7005 // After those conversions, one of the following shall hold:
7006 // -- The second and third operands have the same type; the result
7007 // is of that type. If the operands have class type, the result
7008 // is a prvalue temporary of the result type, which is
7009 // copy-initialized from either the second operand or the third
7010 // operand depending on the value of the first operand.
7011 if (Context.hasSameType(LTy, RTy)) {
7012 if (LTy->isRecordType()) {
7013 // The operands have class type. Make a temporary copy.
7016 if (LHSCopy.isInvalid())
7017 return QualType();
7018
7021 if (RHSCopy.isInvalid())
7022 return QualType();
7023
7024 LHS = LHSCopy;
7025 RHS = RHSCopy;
7026 }
7027 return Context.getCommonSugaredType(LTy, RTy);
7028 }
7029
7030 // Extension: conditional operator involving vector types.
7031 if (LTy->isVectorType() || RTy->isVectorType())
7032 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7033 /*AllowBothBool*/ true,
7034 /*AllowBoolConversions*/ false,
7035 /*AllowBoolOperation*/ false,
7036 /*ReportInvalid*/ true);
7037
7038 // -- The second and third operands have arithmetic or enumeration type;
7039 // the usual arithmetic conversions are performed to bring them to a
7040 // common type, and the result is of that type.
7041 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7042 QualType ResTy =
7043 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7044 if (LHS.isInvalid() || RHS.isInvalid())
7045 return QualType();
7046 if (ResTy.isNull()) {
7047 Diag(QuestionLoc,
7048 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7049 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7050 return QualType();
7051 }
7052
7053 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7054 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7055
7056 return ResTy;
7057 }
7058
7059 // -- The second and third operands have pointer type, or one has pointer
7060 // type and the other is a null pointer constant, or both are null
7061 // pointer constants, at least one of which is non-integral; pointer
7062 // conversions and qualification conversions are performed to bring them
7063 // to their composite pointer type. The result is of the composite
7064 // pointer type.
7065 // -- The second and third operands have pointer to member type, or one has
7066 // pointer to member type and the other is a null pointer constant;
7067 // pointer to member conversions and qualification conversions are
7068 // performed to bring them to a common type, whose cv-qualification
7069 // shall match the cv-qualification of either the second or the third
7070 // operand. The result is of the common type.
7071 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7072 if (!Composite.isNull())
7073 return Composite;
7074
7075 // Similarly, attempt to find composite type of two objective-c pointers.
7076 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7077 if (LHS.isInvalid() || RHS.isInvalid())
7078 return QualType();
7079 if (!Composite.isNull())
7080 return Composite;
7081
7082 // Check if we are using a null with a non-pointer type.
7083 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7084 return QualType();
7085
7086 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7087 << LHS.get()->getType() << RHS.get()->getType()
7088 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7089 return QualType();
7090}
7091
7092/// Find a merged pointer type and convert the two expressions to it.
7093///
7094/// This finds the composite pointer type for \p E1 and \p E2 according to
7095/// C++2a [expr.type]p3. It converts both expressions to this type and returns
7096/// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
7097/// is \c true).
7098///
7099/// \param Loc The location of the operator requiring these two expressions to
7100/// be converted to the composite pointer type.
7101///
7102/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
7104 Expr *&E1, Expr *&E2,
7105 bool ConvertArgs) {
7106 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7107
7108 // C++1z [expr]p14:
7109 // The composite pointer type of two operands p1 and p2 having types T1
7110 // and T2
7111 QualType T1 = E1->getType(), T2 = E2->getType();
7112
7113 // where at least one is a pointer or pointer to member type or
7114 // std::nullptr_t is:
7115 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7116 T1->isNullPtrType();
7117 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7118 T2->isNullPtrType();
7119 if (!T1IsPointerLike && !T2IsPointerLike)
7120 return QualType();
7121
7122 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7123 // This can't actually happen, following the standard, but we also use this
7124 // to implement the end of [expr.conv], which hits this case.
7125 //
7126 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7127 if (T1IsPointerLike &&
7129 if (ConvertArgs)
7130 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7131 ? CK_NullToMemberPointer
7132 : CK_NullToPointer).get();
7133 return T1;
7134 }
7135 if (T2IsPointerLike &&
7137 if (ConvertArgs)
7138 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7139 ? CK_NullToMemberPointer
7140 : CK_NullToPointer).get();
7141 return T2;
7142 }
7143
7144 // Now both have to be pointers or member pointers.
7145 if (!T1IsPointerLike || !T2IsPointerLike)
7146 return QualType();
7147 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7148 "nullptr_t should be a null pointer constant");
7149
7150 struct Step {
7151 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7152 // Qualifiers to apply under the step kind.
7153 Qualifiers Quals;
7154 /// The class for a pointer-to-member; a constant array type with a bound
7155 /// (if any) for an array.
7156 const Type *ClassOrBound;
7157
7158 Step(Kind K, const Type *ClassOrBound = nullptr)
7159 : K(K), ClassOrBound(ClassOrBound) {}
7160 QualType rebuild(ASTContext &Ctx, QualType T) const {
7161 T = Ctx.getQualifiedType(T, Quals);
7162 switch (K) {
7163 case Pointer:
7164 return Ctx.getPointerType(T);
7165 case MemberPointer:
7166 return Ctx.getMemberPointerType(T, ClassOrBound);
7167 case ObjCPointer:
7168 return Ctx.getObjCObjectPointerType(T);
7169 case Array:
7170 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7171 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7172 ArraySizeModifier::Normal, 0);
7173 else
7174 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7175 }
7176 llvm_unreachable("unknown step kind");
7177 }
7178 };
7179
7181
7182 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7183 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7184 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7185 // respectively;
7186 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7187 // to member of C2 of type cv2 U2" for some non-function type U, where
7188 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7189 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7190 // respectively;
7191 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7192 // T2;
7193 //
7194 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7195 // and to prepare to form the cv-combined type if so.
7196 QualType Composite1 = T1;
7197 QualType Composite2 = T2;
7198 unsigned NeedConstBefore = 0;
7199 while (true) {
7200 assert(!Composite1.isNull() && !Composite2.isNull());
7201
7202 Qualifiers Q1, Q2;
7203 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7204 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7205
7206 // Top-level qualifiers are ignored. Merge at all lower levels.
7207 if (!Steps.empty()) {
7208 // Find the qualifier union: (approximately) the unique minimal set of
7209 // qualifiers that is compatible with both types.
7211 Q2.getCVRUQualifiers());
7212
7213 // Under one level of pointer or pointer-to-member, we can change to an
7214 // unambiguous compatible address space.
7215 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7216 Quals.setAddressSpace(Q1.getAddressSpace());
7217 } else if (Steps.size() == 1) {
7218 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7219 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7220 if (MaybeQ1 == MaybeQ2) {
7221 // Exception for ptr size address spaces. Should be able to choose
7222 // either address space during comparison.
7225 MaybeQ1 = true;
7226 else
7227 return QualType(); // No unique best address space.
7228 }
7229 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7230 : Q2.getAddressSpace());
7231 } else {
7232 return QualType();
7233 }
7234
7235 // FIXME: In C, we merge __strong and none to __strong at the top level.
7236 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7237 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7238 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7239 assert(Steps.size() == 1);
7240 else
7241 return QualType();
7242
7243 // Mismatched lifetime qualifiers never compatibly include each other.
7244 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7245 Quals.setObjCLifetime(Q1.getObjCLifetime());
7246 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7247 assert(Steps.size() == 1);
7248 else
7249 return QualType();
7250
7251 Steps.back().Quals = Quals;
7252 if (Q1 != Quals || Q2 != Quals)
7253 NeedConstBefore = Steps.size() - 1;
7254 }
7255
7256 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7257
7258 const ArrayType *Arr1, *Arr2;
7259 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7260 (Arr2 = Context.getAsArrayType(Composite2))) {
7261 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7262 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7263 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7264 Composite1 = Arr1->getElementType();
7265 Composite2 = Arr2->getElementType();
7266 Steps.emplace_back(Step::Array, CAT1);
7267 continue;
7268 }
7269 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7270 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7271 if ((IAT1 && IAT2) ||
7272 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7273 ((bool)CAT1 != (bool)CAT2) &&
7274 (Steps.empty() || Steps.back().K != Step::Array))) {
7275 // In C++20 onwards, we can unify an array of N T with an array of
7276 // a different or unknown bound. But we can't form an array whose
7277 // element type is an array of unknown bound by doing so.
7278 Composite1 = Arr1->getElementType();
7279 Composite2 = Arr2->getElementType();
7280 Steps.emplace_back(Step::Array);
7281 if (CAT1 || CAT2)
7282 NeedConstBefore = Steps.size();
7283 continue;
7284 }
7285 }
7286
7287 const PointerType *Ptr1, *Ptr2;
7288 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7289 (Ptr2 = Composite2->getAs<PointerType>())) {
7290 Composite1 = Ptr1->getPointeeType();
7291 Composite2 = Ptr2->getPointeeType();
7292 Steps.emplace_back(Step::Pointer);
7293 continue;
7294 }
7295
7296 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7297 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7298 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7299 Composite1 = ObjPtr1->getPointeeType();
7300 Composite2 = ObjPtr2->getPointeeType();
7301 Steps.emplace_back(Step::ObjCPointer);
7302 continue;
7303 }
7304
7305 const MemberPointerType *MemPtr1, *MemPtr2;
7306 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7307 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7308 Composite1 = MemPtr1->getPointeeType();
7309 Composite2 = MemPtr2->getPointeeType();
7310
7311 // At the top level, we can perform a base-to-derived pointer-to-member
7312 // conversion:
7313 //
7314 // - [...] where C1 is reference-related to C2 or C2 is
7315 // reference-related to C1
7316 //
7317 // (Note that the only kinds of reference-relatedness in scope here are
7318 // "same type or derived from".) At any other level, the class must
7319 // exactly match.
7320 const Type *Class = nullptr;
7321 QualType Cls1(MemPtr1->getClass(), 0);
7322 QualType Cls2(MemPtr2->getClass(), 0);
7323 if (Context.hasSameType(Cls1, Cls2))
7324 Class = MemPtr1->getClass();
7325 else if (Steps.empty())
7326 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7327 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7328 if (!Class)
7329 return QualType();
7330
7331 Steps.emplace_back(Step::MemberPointer, Class);
7332 continue;
7333 }
7334
7335 // Special case: at the top level, we can decompose an Objective-C pointer
7336 // and a 'cv void *'. Unify the qualifiers.
7337 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7338 Composite2->isObjCObjectPointerType()) ||
7339 (Composite1->isObjCObjectPointerType() &&
7340 Composite2->isVoidPointerType()))) {
7341 Composite1 = Composite1->getPointeeType();
7342 Composite2 = Composite2->getPointeeType();
7343 Steps.emplace_back(Step::Pointer);
7344 continue;
7345 }
7346
7347 // FIXME: block pointer types?
7348
7349 // Cannot unwrap any more types.
7350 break;
7351 }
7352
7353 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7354 // "pointer to function", where the function types are otherwise the same,
7355 // "pointer to function";
7356 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7357 // type is "pointer to member of C2 of type noexcept function", and C1
7358 // is reference-related to C2 or C2 is reference-related to C1, where
7359 // the function types are otherwise the same, "pointer to member of C2 of
7360 // type function" or "pointer to member of C1 of type function",
7361 // respectively;
7362 //
7363 // We also support 'noreturn' here, so as a Clang extension we generalize the
7364 // above to:
7365 //
7366 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7367 // "pointer to member function" and the pointee types can be unified
7368 // by a function pointer conversion, that conversion is applied
7369 // before checking the following rules.
7370 //
7371 // We've already unwrapped down to the function types, and we want to merge
7372 // rather than just convert, so do this ourselves rather than calling
7373 // IsFunctionConversion.
7374 //
7375 // FIXME: In order to match the standard wording as closely as possible, we
7376 // currently only do this under a single level of pointers. Ideally, we would
7377 // allow this in general, and set NeedConstBefore to the relevant depth on
7378 // the side(s) where we changed anything. If we permit that, we should also
7379 // consider this conversion when determining type similarity and model it as
7380 // a qualification conversion.
7381 if (Steps.size() == 1) {
7382 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7383 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7384 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7385 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7386
7387 // The result is noreturn if both operands are.
7388 bool Noreturn =
7389 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7390 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7391 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7392
7393 // The result is nothrow if both operands are.
7394 SmallVector<QualType, 8> ExceptionTypeStorage;
7396 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7398
7399 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7400 FPT1->getParamTypes(), EPI1);
7401 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7402 FPT2->getParamTypes(), EPI2);
7403 }
7404 }
7405 }
7406
7407 // There are some more conversions we can perform under exactly one pointer.
7408 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7409 !Context.hasSameType(Composite1, Composite2)) {
7410 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7411 // "pointer to cv2 T", where T is an object type or void,
7412 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7413 if (Composite1->isVoidType() && Composite2->isObjectType())
7414 Composite2 = Composite1;
7415 else if (Composite2->isVoidType() && Composite1->isObjectType())
7416 Composite1 = Composite2;
7417 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7418 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7419 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7420 // T1, respectively;
7421 //
7422 // The "similar type" handling covers all of this except for the "T1 is a
7423 // base class of T2" case in the definition of reference-related.
7424 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7425 Composite1 = Composite2;
7426 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7427 Composite2 = Composite1;
7428 }
7429
7430 // At this point, either the inner types are the same or we have failed to
7431 // find a composite pointer type.
7432 if (!Context.hasSameType(Composite1, Composite2))
7433 return QualType();
7434
7435 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7436 // differing qualifier.
7437 for (unsigned I = 0; I != NeedConstBefore; ++I)
7438 Steps[I].Quals.addConst();
7439
7440 // Rebuild the composite type.
7441 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7442 for (auto &S : llvm::reverse(Steps))
7443 Composite = S.rebuild(Context, Composite);
7444
7445 if (ConvertArgs) {
7446 // Convert the expressions to the composite pointer type.
7447 InitializedEntity Entity =
7449 InitializationKind Kind =
7451
7452 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7453 if (!E1ToC)
7454 return QualType();
7455
7456 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7457 if (!E2ToC)
7458 return QualType();
7459
7460 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7461 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7462 if (E1Result.isInvalid())
7463 return QualType();
7464 E1 = E1Result.get();
7465
7466 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7467 if (E2Result.isInvalid())
7468 return QualType();
7469 E2 = E2Result.get();
7470 }
7471
7472 return Composite;
7473}
7474
7476 if (!E)
7477 return ExprError();
7478
7479 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7480
7481 // If the result is a glvalue, we shouldn't bind it.
7482 if (E->isGLValue())
7483 return E;
7484
7485 // In ARC, calls that return a retainable type can return retained,
7486 // in which case we have to insert a consuming cast.
7487 if (getLangOpts().ObjCAutoRefCount &&
7488 E->getType()->isObjCRetainableType()) {
7489
7490 bool ReturnsRetained;
7491
7492 // For actual calls, we compute this by examining the type of the
7493 // called value.
7494 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7495 Expr *Callee = Call->getCallee()->IgnoreParens();
7496 QualType T = Callee->getType();
7497
7498 if (T == Context.BoundMemberTy) {
7499 // Handle pointer-to-members.
7500 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7501 T = BinOp->getRHS()->getType();
7502 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7503 T = Mem->getMemberDecl()->getType();
7504 }
7505
7506 if (const PointerType *Ptr = T->getAs<PointerType>())
7507 T = Ptr->getPointeeType();
7508 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7509 T = Ptr->getPointeeType();
7510 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7511 T = MemPtr->getPointeeType();
7512
7513 auto *FTy = T->castAs<FunctionType>();
7514 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7515
7516 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7517 // type always produce a +1 object.
7518 } else if (isa<StmtExpr>(E)) {
7519 ReturnsRetained = true;
7520
7521 // We hit this case with the lambda conversion-to-block optimization;
7522 // we don't want any extra casts here.
7523 } else if (isa<CastExpr>(E) &&
7524 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7525 return E;
7526
7527 // For message sends and property references, we try to find an
7528 // actual method. FIXME: we should infer retention by selector in
7529 // cases where we don't have an actual method.
7530 } else {
7531 ObjCMethodDecl *D = nullptr;
7532 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7533 D = Send->getMethodDecl();
7534 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7535 D = BoxedExpr->getBoxingMethod();
7536 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7537 // Don't do reclaims if we're using the zero-element array
7538 // constant.
7539 if (ArrayLit->getNumElements() == 0 &&
7541 return E;
7542
7543 D = ArrayLit->getArrayWithObjectsMethod();
7544 } else if (ObjCDictionaryLiteral *DictLit
7545 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7546 // Don't do reclaims if we're using the zero-element dictionary
7547 // constant.
7548 if (DictLit->getNumElements() == 0 &&
7550 return E;
7551
7552 D = DictLit->getDictWithObjectsMethod();
7553 }
7554
7555 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7556
7557 // Don't do reclaims on performSelector calls; despite their
7558 // return type, the invoked method doesn't necessarily actually
7559 // return an object.
7560 if (!ReturnsRetained &&
7562 return E;
7563 }
7564
7565 // Don't reclaim an object of Class type.
7566 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7567 return E;
7568
7570
7571 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7572 : CK_ARCReclaimReturnedObject);
7573 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7575 }
7576
7579
7580 if (!getLangOpts().CPlusPlus)
7581 return E;
7582
7583 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7584 // a fast path for the common case that the type is directly a RecordType.
7586 const RecordType *RT = nullptr;
7587 while (!RT) {
7588 switch (T->getTypeClass()) {
7589 case Type::Record:
7590 RT = cast<RecordType>(T);
7591 break;
7592 case Type::ConstantArray:
7593 case Type::IncompleteArray:
7594 case Type::VariableArray:
7595 case Type::DependentSizedArray:
7596 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7597 break;
7598 default:
7599 return E;
7600 }
7601 }
7602
7603 // That should be enough to guarantee that this type is complete, if we're
7604 // not processing a decltype expression.
7605 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7606 if (RD->isInvalidDecl() || RD->isDependentContext())
7607 return E;
7608
7609 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7611 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7612
7613 if (Destructor) {
7616 PDiag(diag::err_access_dtor_temp)
7617 << E->getType());
7619 return ExprError();
7620
7621 // If destructor is trivial, we can avoid the extra copy.
7622 if (Destructor->isTrivial())
7623 return E;
7624
7625 // We need a cleanup, but we don't need to remember the temporary.
7627 }
7628
7631
7632 if (IsDecltype)
7633 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7634
7635 return Bind;
7636}
7637
7640 if (SubExpr.isInvalid())
7641 return ExprError();
7642
7643 return MaybeCreateExprWithCleanups(SubExpr.get());
7644}
7645
7647 assert(SubExpr && "subexpression can't be null!");
7648
7650
7651 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7652 assert(ExprCleanupObjects.size() >= FirstCleanup);
7653 assert(Cleanup.exprNeedsCleanups() ||
7654 ExprCleanupObjects.size() == FirstCleanup);
7656 return SubExpr;
7657
7658 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7659 ExprCleanupObjects.size() - FirstCleanup);
7660
7661 auto *E = ExprWithCleanups::Create(
7662 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7664
7665 return E;
7666}
7667
7669 assert(SubStmt && "sub-statement can't be null!");
7670
7672
7674 return SubStmt;
7675
7676 // FIXME: In order to attach the temporaries, wrap the statement into
7677 // a StmtExpr; currently this is only used for asm statements.
7678 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7679 // a new AsmStmtWithTemporaries.
7680 CompoundStmt *CompStmt =
7683 Expr *E = new (Context)
7685 /*FIXME TemplateDepth=*/0);
7687}
7688
7689/// Process the expression contained within a decltype. For such expressions,
7690/// certain semantic checks on temporaries are delayed until this point, and
7691/// are omitted for the 'topmost' call in the decltype expression. If the
7692/// topmost call bound a temporary, strip that temporary off the expression.
7694 assert(ExprEvalContexts.back().ExprContext ==
7696 "not in a decltype expression");
7697
7699 if (Result.isInvalid())
7700 return ExprError();
7701 E = Result.get();
7702
7703 // C++11 [expr.call]p11:
7704 // If a function call is a prvalue of object type,
7705 // -- if the function call is either
7706 // -- the operand of a decltype-specifier, or
7707 // -- the right operand of a comma operator that is the operand of a
7708 // decltype-specifier,
7709 // a temporary object is not introduced for the prvalue.
7710
7711 // Recursively rebuild ParenExprs and comma expressions to strip out the
7712 // outermost CXXBindTemporaryExpr, if any.
7713 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7714 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7715 if (SubExpr.isInvalid())
7716 return ExprError();
7717 if (SubExpr.get() == PE->getSubExpr())
7718 return E;
7719 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7720 }
7721 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7722 if (BO->getOpcode() == BO_Comma) {
7723 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7724 if (RHS.isInvalid())
7725 return ExprError();
7726 if (RHS.get() == BO->getRHS())
7727 return E;
7728 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7729 BO->getType(), BO->getValueKind(),
7730 BO->getObjectKind(), BO->getOperatorLoc(),
7731 BO->getFPFeatures());
7732 }
7733 }
7734
7735 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7736 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7737 : nullptr;
7738 if (TopCall)
7739 E = TopCall;
7740 else
7741 TopBind = nullptr;
7742
7743 // Disable the special decltype handling now.
7744 ExprEvalContexts.back().ExprContext =
7746
7748 if (Result.isInvalid())
7749 return ExprError();
7750 E = Result.get();
7751
7752 // In MS mode, don't perform any extra checking of call return types within a
7753 // decltype expression.
7754 if (getLangOpts().MSVCCompat)
7755 return E;
7756
7757 // Perform the semantic checks we delayed until this point.
7758 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7759 I != N; ++I) {
7760 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7761 if (Call == TopCall)
7762 continue;
7763
7764 if (CheckCallReturnType(Call->getCallReturnType(Context),
7765 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7766 return ExprError();
7767 }
7768
7769 // Now all relevant types are complete, check the destructors are accessible
7770 // and non-deleted, and annotate them on the temporaries.
7771 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7772 I != N; ++I) {
7774 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7775 if (Bind == TopBind)
7776 continue;
7777
7778 CXXTemporary *Temp = Bind->getTemporary();
7779
7780 CXXRecordDecl *RD =
7781 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7784
7785 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7786 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7787 PDiag(diag::err_access_dtor_temp)
7788 << Bind->getType());
7789 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7790 return ExprError();
7791
7792 // We need a cleanup, but we don't need to remember the temporary.
7794 }
7795
7796 // Possibly strip off the top CXXBindTemporaryExpr.
7797 return E;
7798}
7799
7800/// Note a set of 'operator->' functions that were used for a member access.
7802 ArrayRef<FunctionDecl *> OperatorArrows) {
7803 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7804 // FIXME: Make this configurable?
7805 unsigned Limit = 9;
7806 if (OperatorArrows.size() > Limit) {
7807 // Produce Limit-1 normal notes and one 'skipping' note.
7808 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7809 SkipCount = OperatorArrows.size() - (Limit - 1);
7810 }
7811
7812 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7813 if (I == SkipStart) {
7814 S.Diag(OperatorArrows[I]->getLocation(),
7815 diag::note_operator_arrows_suppressed)
7816 << SkipCount;
7817 I += SkipCount;
7818 } else {
7819 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7820 << OperatorArrows[I]->getCallResultType();
7821 ++I;
7822 }
7823 }
7824}
7825
7827 SourceLocation OpLoc,
7828 tok::TokenKind OpKind,
7829 ParsedType &ObjectType,
7830 bool &MayBePseudoDestructor) {
7831 // Since this might be a postfix expression, get rid of ParenListExprs.
7833 if (Result.isInvalid()) return ExprError();
7834 Base = Result.get();
7835
7837 if (Result.isInvalid()) return ExprError();
7838 Base = Result.get();
7839
7840 QualType BaseType = Base->getType();
7841 MayBePseudoDestructor = false;
7842 if (BaseType->isDependentType()) {
7843 // If we have a pointer to a dependent type and are using the -> operator,
7844 // the object type is the type that the pointer points to. We might still
7845 // have enough information about that type to do something useful.
7846 if (OpKind == tok::arrow)
7847 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7848 BaseType = Ptr->getPointeeType();
7849
7850 ObjectType = ParsedType::make(BaseType);
7851 MayBePseudoDestructor = true;
7852 return Base;
7853 }
7854
7855 // C++ [over.match.oper]p8:
7856 // [...] When operator->returns, the operator-> is applied to the value
7857 // returned, with the original second operand.
7858 if (OpKind == tok::arrow) {
7859 QualType StartingType = BaseType;
7860 bool NoArrowOperatorFound = false;
7861 bool FirstIteration = true;
7862 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7863 // The set of types we've considered so far.
7865 SmallVector<FunctionDecl*, 8> OperatorArrows;
7866 CTypes.insert(Context.getCanonicalType(BaseType));
7867
7868 while (BaseType->isRecordType()) {
7869 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7870 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7871 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7872 noteOperatorArrows(*this, OperatorArrows);
7873 Diag(OpLoc, diag::note_operator_arrow_depth)
7874 << getLangOpts().ArrowDepth;
7875 return ExprError();
7876 }
7877
7879 S, Base, OpLoc,
7880 // When in a template specialization and on the first loop iteration,
7881 // potentially give the default diagnostic (with the fixit in a
7882 // separate note) instead of having the error reported back to here
7883 // and giving a diagnostic with a fixit attached to the error itself.
7884 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7885 ? nullptr
7886 : &NoArrowOperatorFound);
7887 if (Result.isInvalid()) {
7888 if (NoArrowOperatorFound) {
7889 if (FirstIteration) {
7890 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7891 << BaseType << 1 << Base->getSourceRange()
7892 << FixItHint::CreateReplacement(OpLoc, ".");
7893 OpKind = tok::period;
7894 break;
7895 }
7896 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7897 << BaseType << Base->getSourceRange();
7898 CallExpr *CE = dyn_cast<CallExpr>(Base);
7899 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7900 Diag(CD->getBeginLoc(),
7901 diag::note_member_reference_arrow_from_operator_arrow);
7902 }
7903 }
7904 return ExprError();
7905 }
7906 Base = Result.get();
7907 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7908 OperatorArrows.push_back(OpCall->getDirectCallee());
7909 BaseType = Base->getType();
7910 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7911 if (!CTypes.insert(CBaseType).second) {
7912 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7913 noteOperatorArrows(*this, OperatorArrows);
7914 return ExprError();
7915 }
7916 FirstIteration = false;
7917 }
7918
7919 if (OpKind == tok::arrow) {
7920 if (BaseType->isPointerType())
7921 BaseType = BaseType->getPointeeType();
7922 else if (auto *AT = Context.getAsArrayType(BaseType))
7923 BaseType = AT->getElementType();
7924 }
7925 }
7926
7927 // Objective-C properties allow "." access on Objective-C pointer types,
7928 // so adjust the base type to the object type itself.
7929 if (BaseType->isObjCObjectPointerType())
7930 BaseType = BaseType->getPointeeType();
7931
7932 // C++ [basic.lookup.classref]p2:
7933 // [...] If the type of the object expression is of pointer to scalar
7934 // type, the unqualified-id is looked up in the context of the complete
7935 // postfix-expression.
7936 //
7937 // This also indicates that we could be parsing a pseudo-destructor-name.
7938 // Note that Objective-C class and object types can be pseudo-destructor
7939 // expressions or normal member (ivar or property) access expressions, and
7940 // it's legal for the type to be incomplete if this is a pseudo-destructor
7941 // call. We'll do more incomplete-type checks later in the lookup process,
7942 // so just skip this check for ObjC types.
7943 if (!BaseType->isRecordType()) {
7944 ObjectType = ParsedType::make(BaseType);
7945 MayBePseudoDestructor = true;
7946 return Base;
7947 }
7948
7949 // The object type must be complete (or dependent), or
7950 // C++11 [expr.prim.general]p3:
7951 // Unlike the object expression in other contexts, *this is not required to
7952 // be of complete type for purposes of class member access (5.2.5) outside
7953 // the member function body.
7954 if (!BaseType->isDependentType() &&
7956 RequireCompleteType(OpLoc, BaseType,
7957 diag::err_incomplete_member_access)) {
7958 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7959 }
7960
7961 // C++ [basic.lookup.classref]p2:
7962 // If the id-expression in a class member access (5.2.5) is an
7963 // unqualified-id, and the type of the object expression is of a class
7964 // type C (or of pointer to a class type C), the unqualified-id is looked
7965 // up in the scope of class C. [...]
7966 ObjectType = ParsedType::make(BaseType);
7967 return Base;
7968}
7969
7970static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7971 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7972 if (Base->hasPlaceholderType()) {
7974 if (result.isInvalid()) return true;
7975 Base = result.get();
7976 }
7977 ObjectType = Base->getType();
7978
7979 // C++ [expr.pseudo]p2:
7980 // The left-hand side of the dot operator shall be of scalar type. The
7981 // left-hand side of the arrow operator shall be of pointer to scalar type.
7982 // This scalar type is the object type.
7983 // Note that this is rather different from the normal handling for the
7984 // arrow operator.
7985 if (OpKind == tok::arrow) {
7986 // The operator requires a prvalue, so perform lvalue conversions.
7987 // Only do this if we might plausibly end with a pointer, as otherwise
7988 // this was likely to be intended to be a '.'.
7989 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7990 ObjectType->isFunctionType()) {
7992 if (BaseResult.isInvalid())
7993 return true;
7994 Base = BaseResult.get();
7995 ObjectType = Base->getType();
7996 }
7997
7998 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7999 ObjectType = Ptr->getPointeeType();
8000 } else if (!Base->isTypeDependent()) {
8001 // The user wrote "p->" when they probably meant "p."; fix it.
8002 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8003 << ObjectType << true
8004 << FixItHint::CreateReplacement(OpLoc, ".");
8005 if (S.isSFINAEContext())
8006 return true;
8007
8008 OpKind = tok::period;
8009 }
8010 }
8011
8012 return false;
8013}
8014
8015/// Check if it's ok to try and recover dot pseudo destructor calls on
8016/// pointer objects.
8017static bool
8019 QualType DestructedType) {
8020 // If this is a record type, check if its destructor is callable.
8021 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8022 if (RD->hasDefinition())
8024 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8025 return false;
8026 }
8027
8028 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8029 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8030 DestructedType->isVectorType();
8031}
8032
8034 SourceLocation OpLoc,
8035 tok::TokenKind OpKind,
8036 const CXXScopeSpec &SS,
8037 TypeSourceInfo *ScopeTypeInfo,
8038 SourceLocation CCLoc,
8039 SourceLocation TildeLoc,
8040 PseudoDestructorTypeStorage Destructed) {
8041 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8042
8043 QualType ObjectType;
8044 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8045 return ExprError();
8046
8047 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8048 !ObjectType->isVectorType()) {
8049 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8050 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8051 else {
8052 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8053 << ObjectType << Base->getSourceRange();
8054 return ExprError();
8055 }
8056 }
8057
8058 // C++ [expr.pseudo]p2:
8059 // [...] The cv-unqualified versions of the object type and of the type
8060 // designated by the pseudo-destructor-name shall be the same type.
8061 if (DestructedTypeInfo) {
8062 QualType DestructedType = DestructedTypeInfo->getType();
8063 SourceLocation DestructedTypeStart =
8064 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8065 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8066 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8067 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8068 // Foo *foo;
8069 // foo.~Foo();
8070 if (OpKind == tok::period && ObjectType->isPointerType() &&
8071 Context.hasSameUnqualifiedType(DestructedType,
8072 ObjectType->getPointeeType())) {
8073 auto Diagnostic =
8074 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8075 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8076
8077 // Issue a fixit only when the destructor is valid.
8079 *this, DestructedType))
8081
8082 // Recover by setting the object type to the destructed type and the
8083 // operator to '->'.
8084 ObjectType = DestructedType;
8085 OpKind = tok::arrow;
8086 } else {
8087 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8088 << ObjectType << DestructedType << Base->getSourceRange()
8089 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8090
8091 // Recover by setting the destructed type to the object type.
8092 DestructedType = ObjectType;
8093 DestructedTypeInfo =
8094 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8095 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8096 }
8097 } else if (DestructedType.getObjCLifetime() !=
8098 ObjectType.getObjCLifetime()) {
8099
8100 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8101 // Okay: just pretend that the user provided the correctly-qualified
8102 // type.
8103 } else {
8104 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8105 << ObjectType << DestructedType << Base->getSourceRange()
8106 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8107 }
8108
8109 // Recover by setting the destructed type to the object type.
8110 DestructedType = ObjectType;
8111 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8112 DestructedTypeStart);
8113 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8114 }
8115 }
8116 }
8117
8118 // C++ [expr.pseudo]p2:
8119 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8120 // form
8121 //
8122 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8123 //
8124 // shall designate the same scalar type.
8125 if (ScopeTypeInfo) {
8126 QualType ScopeType = ScopeTypeInfo->getType();
8127 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8128 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8129
8130 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8131 diag::err_pseudo_dtor_type_mismatch)
8132 << ObjectType << ScopeType << Base->getSourceRange()
8133 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8134
8135 ScopeType = QualType();
8136 ScopeTypeInfo = nullptr;
8137 }
8138 }
8139
8140 Expr *Result
8142 OpKind == tok::arrow, OpLoc,
8144 ScopeTypeInfo,
8145 CCLoc,
8146 TildeLoc,
8147 Destructed);
8148
8149 return Result;
8150}
8151
8153 SourceLocation OpLoc,
8154 tok::TokenKind OpKind,
8155 CXXScopeSpec &SS,
8156 UnqualifiedId &FirstTypeName,
8157 SourceLocation CCLoc,
8158 SourceLocation TildeLoc,
8159 UnqualifiedId &SecondTypeName) {
8160 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8161 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8162 "Invalid first type name in pseudo-destructor");
8163 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8164 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8165 "Invalid second type name in pseudo-destructor");
8166
8167 QualType ObjectType;
8168 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8169 return ExprError();
8170
8171 // Compute the object type that we should use for name lookup purposes. Only
8172 // record types and dependent types matter.
8173 ParsedType ObjectTypePtrForLookup;
8174 if (!SS.isSet()) {
8175 if (ObjectType->isRecordType())
8176 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8177 else if (ObjectType->isDependentType())
8178 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8179 }
8180
8181 // Convert the name of the type being destructed (following the ~) into a
8182 // type (with source-location information).
8183 QualType DestructedType;
8184 TypeSourceInfo *DestructedTypeInfo = nullptr;
8185 PseudoDestructorTypeStorage Destructed;
8186 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8187 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8188 SecondTypeName.StartLocation,
8189 S, &SS, true, false, ObjectTypePtrForLookup,
8190 /*IsCtorOrDtorName*/true);
8191 if (!T &&
8192 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8193 (!SS.isSet() && ObjectType->isDependentType()))) {
8194 // The name of the type being destroyed is a dependent name, and we
8195 // couldn't find anything useful in scope. Just store the identifier and
8196 // it's location, and we'll perform (qualified) name lookup again at
8197 // template instantiation time.
8198 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8199 SecondTypeName.StartLocation);
8200 } else if (!T) {
8201 Diag(SecondTypeName.StartLocation,
8202 diag::err_pseudo_dtor_destructor_non_type)
8203 << SecondTypeName.Identifier << ObjectType;
8204 if (isSFINAEContext())
8205 return ExprError();
8206
8207 // Recover by assuming we had the right type all along.
8208 DestructedType = ObjectType;
8209 } else
8210 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8211 } else {
8212 // Resolve the template-id to a type.
8213 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8214 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8215 TemplateId->NumArgs);
8217 SS,
8218 TemplateId->TemplateKWLoc,
8219 TemplateId->Template,
8220 TemplateId->Name,
8221 TemplateId->TemplateNameLoc,
8222 TemplateId->LAngleLoc,
8223 TemplateArgsPtr,
8224 TemplateId->RAngleLoc,
8225 /*IsCtorOrDtorName*/true);
8226 if (T.isInvalid() || !T.get()) {
8227 // Recover by assuming we had the right type all along.
8228 DestructedType = ObjectType;
8229 } else
8230 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8231 }
8232
8233 // If we've performed some kind of recovery, (re-)build the type source
8234 // information.
8235 if (!DestructedType.isNull()) {
8236 if (!DestructedTypeInfo)
8237 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8238 SecondTypeName.StartLocation);
8239 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8240 }
8241
8242 // Convert the name of the scope type (the type prior to '::') into a type.
8243 TypeSourceInfo *ScopeTypeInfo = nullptr;
8244 QualType ScopeType;
8245 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8246 FirstTypeName.Identifier) {
8247 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8248 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8249 FirstTypeName.StartLocation,
8250 S, &SS, true, false, ObjectTypePtrForLookup,
8251 /*IsCtorOrDtorName*/true);
8252 if (!T) {
8253 Diag(FirstTypeName.StartLocation,
8254 diag::err_pseudo_dtor_destructor_non_type)
8255 << FirstTypeName.Identifier << ObjectType;
8256
8257 if (isSFINAEContext())
8258 return ExprError();
8259
8260 // Just drop this type. It's unnecessary anyway.
8261 ScopeType = QualType();
8262 } else
8263 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8264 } else {
8265 // Resolve the template-id to a type.
8266 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8267 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8268 TemplateId->NumArgs);
8270 SS,
8271 TemplateId->TemplateKWLoc,
8272 TemplateId->Template,
8273 TemplateId->Name,
8274 TemplateId->TemplateNameLoc,
8275 TemplateId->LAngleLoc,
8276 TemplateArgsPtr,
8277 TemplateId->RAngleLoc,
8278 /*IsCtorOrDtorName*/true);
8279 if (T.isInvalid() || !T.get()) {
8280 // Recover by dropping this type.
8281 ScopeType = QualType();
8282 } else
8283 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8284 }
8285 }
8286
8287 if (!ScopeType.isNull() && !ScopeTypeInfo)
8288 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8289 FirstTypeName.StartLocation);
8290
8291
8292 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8293 ScopeTypeInfo, CCLoc, TildeLoc,
8294 Destructed);
8295}
8296
8298 SourceLocation OpLoc,
8299 tok::TokenKind OpKind,
8300 SourceLocation TildeLoc,
8301 const DeclSpec& DS) {
8302 QualType ObjectType;
8303 QualType T;
8304 TypeLocBuilder TLB;
8305 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8306 return ExprError();
8307
8308 switch (DS.getTypeSpecType()) {
8310 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8311 return true;
8312 }
8314 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8315 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8316 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8317 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8318 break;
8319 }
8322 DS.getBeginLoc(), DS.getEllipsisLoc());
8324 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8325 DS.getBeginLoc());
8327 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8328 break;
8329 }
8330 default:
8331 llvm_unreachable("Unsupported type in pseudo destructor");
8332 }
8333 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8334 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8335
8336 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8337 nullptr, SourceLocation(), TildeLoc,
8338 Destructed);
8339}
8340
8342 SourceLocation RParen) {
8343 // If the operand is an unresolved lookup expression, the expression is ill-
8344 // formed per [over.over]p1, because overloaded function names cannot be used
8345 // without arguments except in explicit contexts.
8346 ExprResult R = CheckPlaceholderExpr(Operand);
8347 if (R.isInvalid())
8348 return R;
8349
8351 if (R.isInvalid())
8352 return ExprError();
8353
8354 Operand = R.get();
8355
8356 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8357 Operand->HasSideEffects(Context, false)) {
8358 // The expression operand for noexcept is in an unevaluated expression
8359 // context, so side effects could result in unintended consequences.
8360 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8361 }
8362
8363 CanThrowResult CanThrow = canThrow(Operand);
8364 return new (Context)
8365 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8366}
8367
8369 Expr *Operand, SourceLocation RParen) {
8370 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8371}
8372
8374 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8375 DeclRefExpr *LHS = nullptr;
8376 bool IsCompoundAssign = false;
8377 bool isIncrementDecrementUnaryOp = false;
8378 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8379 if (BO->getLHS()->getType()->isDependentType() ||
8380 BO->getRHS()->getType()->isDependentType()) {
8381 if (BO->getOpcode() != BO_Assign)
8382 return;
8383 } else if (!BO->isAssignmentOp())
8384 return;
8385 else
8386 IsCompoundAssign = BO->isCompoundAssignmentOp();
8387 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8388 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8389 if (COCE->getOperator() != OO_Equal)
8390 return;
8391 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8392 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8393 if (!UO->isIncrementDecrementOp())
8394 return;
8395 isIncrementDecrementUnaryOp = true;
8396 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8397 }
8398 if (!LHS)
8399 return;
8400 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8401 if (!VD)
8402 return;
8403 // Don't decrement RefsMinusAssignments if volatile variable with compound
8404 // assignment (+=, ...) or increment/decrement unary operator to avoid
8405 // potential unused-but-set-variable warning.
8406 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8408 return;
8409 auto iter = RefsMinusAssignments.find(VD);
8410 if (iter == RefsMinusAssignments.end())
8411 return;
8412 iter->getSecond()--;
8413}
8414
8415/// Perform the conversions required for an expression used in a
8416/// context that ignores the result.
8419
8420 if (E->hasPlaceholderType()) {
8421 ExprResult result = CheckPlaceholderExpr(E);
8422 if (result.isInvalid()) return E;
8423 E = result.get();
8424 }
8425
8426 if (getLangOpts().CPlusPlus) {
8427 // The C++11 standard defines the notion of a discarded-value expression;
8428 // normally, we don't need to do anything to handle it, but if it is a
8429 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8430 // conversion.
8433 if (Res.isInvalid())
8434 return E;
8435 E = Res.get();
8436 } else {
8437 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8438 // it occurs as a discarded-value expression.
8440 }
8441
8442 // C++1z:
8443 // If the expression is a prvalue after this optional conversion, the
8444 // temporary materialization conversion is applied.
8445 //
8446 // We do not materialize temporaries by default in order to avoid creating
8447 // unnecessary temporary objects. If we skip this step, IR generation is
8448 // able to synthesize the storage for itself in the aggregate case, and
8449 // adding the extra node to the AST is just clutter.
8451 E->isPRValue() && !E->getType()->isVoidType()) {
8453 if (Res.isInvalid())
8454 return E;
8455 E = Res.get();
8456 }
8457 return E;
8458 }
8459
8460 // C99 6.3.2.1:
8461 // [Except in specific positions,] an lvalue that does not have
8462 // array type is converted to the value stored in the
8463 // designated object (and is no longer an lvalue).
8464 if (E->isPRValue()) {
8465 // In C, function designators (i.e. expressions of function type)
8466 // are r-values, but we still want to do function-to-pointer decay
8467 // on them. This is both technically correct and convenient for
8468 // some clients.
8469 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8471
8472 return E;
8473 }
8474
8475 // GCC seems to also exclude expressions of incomplete enum type.
8476 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8477 if (!T->getDecl()->isComplete()) {
8478 // FIXME: stupid workaround for a codegen bug!
8479 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8480 return E;
8481 }
8482 }
8483
8485 if (Res.isInvalid())
8486 return E;
8487 E = Res.get();
8488
8489 if (!E->getType()->isVoidType())
8491 diag::err_incomplete_type);
8492 return E;
8493}
8494
8496 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8497 // it occurs as an unevaluated operand.
8499
8500 return E;
8501}
8502
8503// If we can unambiguously determine whether Var can never be used
8504// in a constant expression, return true.
8505// - if the variable and its initializer are non-dependent, then
8506// we can unambiguously check if the variable is a constant expression.
8507// - if the initializer is not value dependent - we can determine whether
8508// it can be used to initialize a constant expression. If Init can not
8509// be used to initialize a constant expression we conclude that Var can
8510// never be a constant expression.
8511// - FXIME: if the initializer is dependent, we can still do some analysis and
8512// identify certain cases unambiguously as non-const by using a Visitor:
8513// - such as those that involve odr-use of a ParmVarDecl, involve a new
8514// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8517 if (isa<ParmVarDecl>(Var)) return true;
8518 const VarDecl *DefVD = nullptr;
8519
8520 // If there is no initializer - this can not be a constant expression.
8521 const Expr *Init = Var->getAnyInitializer(DefVD);
8522 if (!Init)
8523 return true;
8524 assert(DefVD);
8525 if (DefVD->isWeak())
8526 return false;
8527
8528 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8529 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8530 // of value-dependent expressions, and use it here to determine whether the
8531 // initializer is a potential constant expression.
8532 return false;
8533 }
8534
8536}
8537
8538/// Check if the current lambda has any potential captures
8539/// that must be captured by any of its enclosing lambdas that are ready to
8540/// capture. If there is a lambda that can capture a nested
8541/// potential-capture, go ahead and do so. Also, check to see if any
8542/// variables are uncaptureable or do not involve an odr-use so do not
8543/// need to be captured.
8544
8546 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8547
8548 assert(!S.isUnevaluatedContext());
8549 assert(S.CurContext->isDependentContext());
8550#ifndef NDEBUG
8551 DeclContext *DC = S.CurContext;
8552 while (DC && isa<CapturedDecl>(DC))
8553 DC = DC->getParent();
8554 assert(
8555 CurrentLSI->CallOperator == DC &&
8556 "The current call operator must be synchronized with Sema's CurContext");
8557#endif // NDEBUG
8558
8559 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8560
8561 // All the potentially captureable variables in the current nested
8562 // lambda (within a generic outer lambda), must be captured by an
8563 // outer lambda that is enclosed within a non-dependent context.
8564 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8565 // If the variable is clearly identified as non-odr-used and the full
8566 // expression is not instantiation dependent, only then do we not
8567 // need to check enclosing lambda's for speculative captures.
8568 // For e.g.:
8569 // Even though 'x' is not odr-used, it should be captured.
8570 // int test() {
8571 // const int x = 10;
8572 // auto L = [=](auto a) {
8573 // (void) +x + a;
8574 // };
8575 // }
8576 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8577 !IsFullExprInstantiationDependent)
8578 return;
8579
8580 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8581 if (!UnderlyingVar)
8582 return;
8583
8584 // If we have a capture-capable lambda for the variable, go ahead and
8585 // capture the variable in that lambda (and all its enclosing lambdas).
8586 if (const std::optional<unsigned> Index =
8588 S.FunctionScopes, Var, S))
8589 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8590 const bool IsVarNeverAConstantExpression =
8592 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8593 // This full expression is not instantiation dependent or the variable
8594 // can not be used in a constant expression - which means
8595 // this variable must be odr-used here, so diagnose a
8596 // capture violation early, if the variable is un-captureable.
8597 // This is purely for diagnosing errors early. Otherwise, this
8598 // error would get diagnosed when the lambda becomes capture ready.
8599 QualType CaptureType, DeclRefType;
8600 SourceLocation ExprLoc = VarExpr->getExprLoc();
8601 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8602 /*EllipsisLoc*/ SourceLocation(),
8603 /*BuildAndDiagnose*/false, CaptureType,
8604 DeclRefType, nullptr)) {
8605 // We will never be able to capture this variable, and we need
8606 // to be able to in any and all instantiations, so diagnose it.
8607 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8608 /*EllipsisLoc*/ SourceLocation(),
8609 /*BuildAndDiagnose*/true, CaptureType,
8610 DeclRefType, nullptr);
8611 }
8612 }
8613 });
8614
8615 // Check if 'this' needs to be captured.
8616 if (CurrentLSI->hasPotentialThisCapture()) {
8617 // If we have a capture-capable lambda for 'this', go ahead and capture
8618 // 'this' in that lambda (and all its enclosing lambdas).
8619 if (const std::optional<unsigned> Index =
8621 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8622 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8624 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8625 &FunctionScopeIndexOfCapturableLambda);
8626 }
8627 }
8628
8629 // Reset all the potential captures at the end of each full-expression.
8630 CurrentLSI->clearPotentialCaptures();
8631}
8632
8635 const TypoCorrection &TC) {
8636 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8637 Consumer.getLookupResult().getLookupKind());
8638 const CXXScopeSpec *SS = Consumer.getSS();
8639 CXXScopeSpec NewSS;
8640
8641 // Use an approprate CXXScopeSpec for building the expr.
8642 if (auto *NNS = TC.getCorrectionSpecifier())
8644 else if (SS && !TC.WillReplaceSpecifier())
8645 NewSS = *SS;
8646
8647 if (auto *ND = TC.getFoundDecl()) {
8648 R.setLookupName(ND->getDeclName());
8649 R.addDecl(ND);
8650 if (ND->isCXXClassMember()) {
8651 // Figure out the correct naming class to add to the LookupResult.
8652 CXXRecordDecl *Record = nullptr;
8653 if (auto *NNS = TC.getCorrectionSpecifier())
8654 Record = NNS->getAsType()->getAsCXXRecordDecl();
8655 if (!Record)
8656 Record =
8657 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8658 if (Record)
8660
8661 // Detect and handle the case where the decl might be an implicit
8662 // member.
8664 NewSS, R, Consumer.isAddressOfOperand()))
8666 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8667 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8668 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8669 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8670 Ivar->getIdentifier());
8671 }
8672 }
8673
8674 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8675 /*AcceptInvalidDecl*/ true);
8676}
8677
8678namespace {
8679class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8681
8682public:
8683 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8684 : TypoExprs(TypoExprs) {}
8685 bool VisitTypoExpr(TypoExpr *TE) {
8686 TypoExprs.insert(TE);
8687 return true;
8688 }
8689};
8690
8691class TransformTypos : public TreeTransform<TransformTypos> {
8692 typedef TreeTransform<TransformTypos> BaseTransform;
8693
8694 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8695 // process of being initialized.
8696 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8697 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8698 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8699 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8700
8701 /// Emit diagnostics for all of the TypoExprs encountered.
8702 ///
8703 /// If the TypoExprs were successfully corrected, then the diagnostics should
8704 /// suggest the corrections. Otherwise the diagnostics will not suggest
8705 /// anything (having been passed an empty TypoCorrection).
8706 ///
8707 /// If we've failed to correct due to ambiguous corrections, we need to
8708 /// be sure to pass empty corrections and replacements. Otherwise it's
8709 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8710 /// and we don't want to report those diagnostics.
8711 void EmitAllDiagnostics(bool IsAmbiguous) {
8712 for (TypoExpr *TE : TypoExprs) {
8713 auto &State = SemaRef.getTypoExprState(TE);
8714 if (State.DiagHandler) {
8715 TypoCorrection TC = IsAmbiguous
8716 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8717 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8718
8719 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8720 // TypoCorrection, replacing the existing decls. This ensures the right
8721 // NamedDecl is used in diagnostics e.g. in the case where overload
8722 // resolution was used to select one from several possible decls that
8723 // had been stored in the TypoCorrection.
8724 if (auto *ND = getDeclFromExpr(
8725 Replacement.isInvalid() ? nullptr : Replacement.get()))
8726 TC.setCorrectionDecl(ND);
8727
8728 State.DiagHandler(TC);
8729 }
8730 SemaRef.clearDelayedTypo(TE);
8731 }
8732 }
8733
8734 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8735 /// We allow advancement of the correction stream by removing it from the
8736 /// TransformCache which allows `TransformTypoExpr` to advance during the
8737 /// next transformation attempt.
8738 ///
8739 /// Any substitution attempts for the previous TypoExprs (which must have been
8740 /// finished) will need to be retried since it's possible that they will now
8741 /// be invalid given the latest advancement.
8742 ///
8743 /// We need to be sure that we're making progress - it's possible that the
8744 /// tree is so malformed that the transform never makes it to the
8745 /// `TransformTypoExpr`.
8746 ///
8747 /// Returns true if there are any untried correction combinations.
8748 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8749 for (auto *TE : TypoExprs) {
8750 auto &State = SemaRef.getTypoExprState(TE);
8751 TransformCache.erase(TE);
8752 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8753 return false;
8754 if (!State.Consumer->finished())
8755 return true;
8756 State.Consumer->resetCorrectionStream();
8757 }
8758 return false;
8759 }
8760
8762 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8763 E = OverloadResolution[OE];
8764
8765 if (!E)
8766 return nullptr;
8767 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8768 return DRE->getFoundDecl();
8769 if (auto *ME = dyn_cast<MemberExpr>(E))
8770 return ME->getFoundDecl();
8771 // FIXME: Add any other expr types that could be seen by the delayed typo
8772 // correction TreeTransform for which the corresponding TypoCorrection could
8773 // contain multiple decls.
8774 return nullptr;
8775 }
8776
8777 ExprResult TryTransform(Expr *E) {
8778 Sema::SFINAETrap Trap(SemaRef);
8779 ExprResult Res = TransformExpr(E);
8780 if (Trap.hasErrorOccurred() || Res.isInvalid())
8781 return ExprError();
8782
8783 return ExprFilter(Res.get());
8784 }
8785
8786 // Since correcting typos may intoduce new TypoExprs, this function
8787 // checks for new TypoExprs and recurses if it finds any. Note that it will
8788 // only succeed if it is able to correct all typos in the given expression.
8789 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8790 if (Res.isInvalid()) {
8791 return Res;
8792 }
8793 // Check to see if any new TypoExprs were created. If so, we need to recurse
8794 // to check their validity.
8795 Expr *FixedExpr = Res.get();
8796
8797 auto SavedTypoExprs = std::move(TypoExprs);
8798 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8799 TypoExprs.clear();
8800 AmbiguousTypoExprs.clear();
8801
8802 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8803 if (!TypoExprs.empty()) {
8804 // Recurse to handle newly created TypoExprs. If we're not able to
8805 // handle them, discard these TypoExprs.
8806 ExprResult RecurResult =
8807 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8808 if (RecurResult.isInvalid()) {
8809 Res = ExprError();
8810 // Recursive corrections didn't work, wipe them away and don't add
8811 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8812 // since we don't want to clear them twice. Note: it's possible the
8813 // TypoExprs were created recursively and thus won't be in our
8814 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8815 auto &SemaTypoExprs = SemaRef.TypoExprs;
8816 for (auto *TE : TypoExprs) {
8817 TransformCache.erase(TE);
8818 SemaRef.clearDelayedTypo(TE);
8819
8820 auto SI = find(SemaTypoExprs, TE);
8821 if (SI != SemaTypoExprs.end()) {
8822 SemaTypoExprs.erase(SI);
8823 }
8824 }
8825 } else {
8826 // TypoExpr is valid: add newly created TypoExprs since we were
8827 // able to correct them.
8828 Res = RecurResult;
8829 SavedTypoExprs.set_union(TypoExprs);
8830 }
8831 }
8832
8833 TypoExprs = std::move(SavedTypoExprs);
8834 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8835
8836 return Res;
8837 }
8838
8839 // Try to transform the given expression, looping through the correction
8840 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8841 //
8842 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8843 // true and this method immediately will return an `ExprError`.
8844 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8845 ExprResult Res;
8846 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8847 SemaRef.TypoExprs.clear();
8848
8849 while (true) {
8850 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8851
8852 // Recursion encountered an ambiguous correction. This means that our
8853 // correction itself is ambiguous, so stop now.
8854 if (IsAmbiguous)
8855 break;
8856
8857 // If the transform is still valid after checking for any new typos,
8858 // it's good to go.
8859 if (!Res.isInvalid())
8860 break;
8861
8862 // The transform was invalid, see if we have any TypoExprs with untried
8863 // correction candidates.
8864 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8865 break;
8866 }
8867
8868 // If we found a valid result, double check to make sure it's not ambiguous.
8869 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8870 auto SavedTransformCache =
8871 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8872
8873 // Ensure none of the TypoExprs have multiple typo correction candidates
8874 // with the same edit length that pass all the checks and filters.
8875 while (!AmbiguousTypoExprs.empty()) {
8876 auto TE = AmbiguousTypoExprs.back();
8877
8878 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8879 // and invalidating our TypoExprState, so always fetch it instead of storing.
8880 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8881
8882 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8883 TypoCorrection Next;
8884 do {
8885 // Fetch the next correction by erasing the typo from the cache and calling
8886 // `TryTransform` which will iterate through corrections in
8887 // `TransformTypoExpr`.
8888 TransformCache.erase(TE);
8889 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8890
8891 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8892 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8893 SavedTransformCache.erase(TE);
8894 Res = ExprError();
8895 IsAmbiguous = true;
8896 break;
8897 }
8898 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8899 Next.getEditDistance(false) == TC.getEditDistance(false));
8900
8901 if (IsAmbiguous)
8902 break;
8903
8904 AmbiguousTypoExprs.remove(TE);
8905 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8906 TransformCache[TE] = SavedTransformCache[TE];
8907 }
8908 TransformCache = std::move(SavedTransformCache);
8909 }
8910
8911 // Wipe away any newly created TypoExprs that we don't know about. Since we
8912 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8913 // possible if a `TypoExpr` is created during a transformation but then
8914 // fails before we can discover it.
8915 auto &SemaTypoExprs = SemaRef.TypoExprs;
8916 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8917 auto TE = *Iterator;
8918 auto FI = find(TypoExprs, TE);
8919 if (FI != TypoExprs.end()) {
8920 Iterator++;
8921 continue;
8922 }
8923 SemaRef.clearDelayedTypo(TE);
8924 Iterator = SemaTypoExprs.erase(Iterator);
8925 }
8926 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8927
8928 return Res;
8929 }
8930
8931public:
8932 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8933 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8934
8935 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8936 MultiExprArg Args,
8937 SourceLocation RParenLoc,
8938 Expr *ExecConfig = nullptr) {
8939 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8940 RParenLoc, ExecConfig);
8941 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8942 if (Result.isUsable()) {
8943 Expr *ResultCall = Result.get();
8944 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8945 ResultCall = BE->getSubExpr();
8946 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8947 OverloadResolution[OE] = CE->getCallee();
8948 }
8949 }
8950 return Result;
8951 }
8952
8953 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8954
8955 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8956
8957 ExprResult Transform(Expr *E) {
8958 bool IsAmbiguous = false;
8959 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8960
8961 if (!Res.isUsable())
8962 FindTypoExprs(TypoExprs).TraverseStmt(E);
8963
8964 EmitAllDiagnostics(IsAmbiguous);
8965
8966 return Res;
8967 }
8968
8969 ExprResult TransformTypoExpr(TypoExpr *E) {
8970 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8971 // cached transformation result if there is one and the TypoExpr isn't the
8972 // first one that was encountered.
8973 auto &CacheEntry = TransformCache[E];
8974 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8975 return CacheEntry;
8976 }
8977
8978 auto &State = SemaRef.getTypoExprState(E);
8979 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8980
8981 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8982 // typo correction and return it.
8983 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8984 if (InitDecl && TC.getFoundDecl() == InitDecl)
8985 continue;
8986 // FIXME: If we would typo-correct to an invalid declaration, it's
8987 // probably best to just suppress all errors from this typo correction.
8988 ExprResult NE = State.RecoveryHandler ?
8989 State.RecoveryHandler(SemaRef, E, TC) :
8990 attemptRecovery(SemaRef, *State.Consumer, TC);
8991 if (!NE.isInvalid()) {
8992 // Check whether there may be a second viable correction with the same
8993 // edit distance; if so, remember this TypoExpr may have an ambiguous
8994 // correction so it can be more thoroughly vetted later.
8995 TypoCorrection Next;
8996 if ((Next = State.Consumer->peekNextCorrection()) &&
8997 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8998 AmbiguousTypoExprs.insert(E);
8999 } else {
9000 AmbiguousTypoExprs.remove(E);
9001 }
9002 assert(!NE.isUnset() &&
9003 "Typo was transformed into a valid-but-null ExprResult");
9004 return CacheEntry = NE;
9005 }
9006 }
9007 return CacheEntry = ExprError();
9008 }
9009};
9010}
9011
9014 bool RecoverUncorrectedTypos,
9015 llvm::function_ref<ExprResult(Expr *)> Filter) {
9016 // If the current evaluation context indicates there are uncorrected typos
9017 // and the current expression isn't guaranteed to not have typos, try to
9018 // resolve any TypoExpr nodes that might be in the expression.
9019 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9020 (E->isTypeDependent() || E->isValueDependent() ||
9022 auto TyposResolved = DelayedTypos.size();
9023 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9024 TyposResolved -= DelayedTypos.size();
9025 if (Result.isInvalid() || Result.get() != E) {
9026 ExprEvalContexts.back().NumTypos -= TyposResolved;
9027 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9028 struct TyposReplace : TreeTransform<TyposReplace> {
9029 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9030 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9031 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9032 E->getEndLoc(), {});
9033 }
9034 } TT(*this);
9035 return TT.TransformExpr(E);
9036 }
9037 return Result;
9038 }
9039 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9040 }
9041 return E;
9042}
9043
9045 bool DiscardedValue, bool IsConstexpr,
9046 bool IsTemplateArgument) {
9047 ExprResult FullExpr = FE;
9048
9049 if (!FullExpr.get())
9050 return ExprError();
9051
9052 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9053 return ExprError();
9054
9055 if (DiscardedValue) {
9056 // Top-level expressions default to 'id' when we're in a debugger.
9057 if (getLangOpts().DebuggerCastResultToId &&
9058 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9060 if (FullExpr.isInvalid())
9061 return ExprError();
9062 }
9063
9065 if (FullExpr.isInvalid())
9066 return ExprError();
9067
9069 if (FullExpr.isInvalid())
9070 return ExprError();
9071
9072 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9073 }
9074
9075 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9076 /*RecoverUncorrectedTypos=*/true);
9077 if (FullExpr.isInvalid())
9078 return ExprError();
9079
9080 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9081
9082 // At the end of this full expression (which could be a deeply nested
9083 // lambda), if there is a potential capture within the nested lambda,
9084 // have the outer capture-able lambda try and capture it.
9085 // Consider the following code:
9086 // void f(int, int);
9087 // void f(const int&, double);
9088 // void foo() {
9089 // const int x = 10, y = 20;
9090 // auto L = [=](auto a) {
9091 // auto M = [=](auto b) {
9092 // f(x, b); <-- requires x to be captured by L and M
9093 // f(y, a); <-- requires y to be captured by L, but not all Ms
9094 // };
9095 // };
9096 // }
9097
9098 // FIXME: Also consider what happens for something like this that involves
9099 // the gnu-extension statement-expressions or even lambda-init-captures:
9100 // void f() {
9101 // const int n = 0;
9102 // auto L = [&](auto a) {
9103 // +n + ({ 0; a; });
9104 // };
9105 // }
9106 //
9107 // Here, we see +n, and then the full-expression 0; ends, so we don't
9108 // capture n (and instead remove it from our list of potential captures),
9109 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9110 // for us to see that we need to capture n after all.
9111
9112 LambdaScopeInfo *const CurrentLSI =
9113 getCurLambda(/*IgnoreCapturedRegions=*/true);
9114 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9115 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9116 // for an example of the code that might cause this asynchrony.
9117 // By ensuring we are in the context of a lambda's call operator
9118 // we can fix the bug (we only need to check whether we need to capture
9119 // if we are within a lambda's body); but per the comments in that
9120 // PR, a proper fix would entail :
9121 // "Alternative suggestion:
9122 // - Add to Sema an integer holding the smallest (outermost) scope
9123 // index that we are *lexically* within, and save/restore/set to
9124 // FunctionScopes.size() in InstantiatingTemplate's
9125 // constructor/destructor.
9126 // - Teach the handful of places that iterate over FunctionScopes to
9127 // stop at the outermost enclosing lexical scope."
9128 DeclContext *DC = CurContext;
9129 while (DC && isa<CapturedDecl>(DC))
9130 DC = DC->getParent();
9131 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9132 if (IsInLambdaDeclContext && CurrentLSI &&
9133 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9135 *this);
9137}
9138
9140 if (!FullStmt) return StmtError();
9141
9142 return MaybeCreateStmtWithCleanups(FullStmt);
9143}
9144
9147 CXXScopeSpec &SS,
9148 const DeclarationNameInfo &TargetNameInfo) {
9149 DeclarationName TargetName = TargetNameInfo.getName();
9150 if (!TargetName)
9151 return IER_DoesNotExist;
9152
9153 // If the name itself is dependent, then the result is dependent.
9154 if (TargetName.isDependentName())
9155 return IER_Dependent;
9156
9157 // Do the redeclaration lookup in the current scope.
9158 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9159 RedeclarationKind::NotForRedeclaration);
9160 LookupParsedName(R, S, &SS);
9162
9163 switch (R.getResultKind()) {
9168 return IER_Exists;
9169
9171 return IER_DoesNotExist;
9172
9174 return IER_Dependent;
9175 }
9176
9177 llvm_unreachable("Invalid LookupResult Kind!");
9178}
9179
9182 bool IsIfExists, CXXScopeSpec &SS,
9183 UnqualifiedId &Name) {
9184 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9185
9186 // Check for an unexpanded parameter pack.
9187 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9188 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9189 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9190 return IER_Error;
9191
9192 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9193}
9194
9196 return BuildExprRequirement(E, /*IsSimple=*/true,
9197 /*NoexceptLoc=*/SourceLocation(),
9198 /*ReturnTypeRequirement=*/{});
9199}
9200
9202 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9203 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9204 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9205 "Exactly one of TypeName and TemplateId must be specified.");
9206 TypeSourceInfo *TSI = nullptr;
9207 if (TypeName) {
9208 QualType T =
9210 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9211 &TSI, /*DeducedTSTContext=*/false);
9212 if (T.isNull())
9213 return nullptr;
9214 } else {
9215 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9216 TemplateId->NumArgs);
9217 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9218 TemplateId->TemplateKWLoc,
9219 TemplateId->Template, TemplateId->Name,
9220 TemplateId->TemplateNameLoc,
9221 TemplateId->LAngleLoc, ArgsPtr,
9222 TemplateId->RAngleLoc);
9223 if (T.isInvalid())
9224 return nullptr;
9225 if (GetTypeFromParser(T.get(), &TSI).isNull())
9226 return nullptr;
9227 }
9228 return BuildTypeRequirement(TSI);
9229}
9230
9233 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9234 /*ReturnTypeRequirement=*/{});
9235}
9236
9239 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9240 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9241 // C++2a [expr.prim.req.compound] p1.3.3
9242 // [..] the expression is deduced against an invented function template
9243 // F [...] F is a void function template with a single type template
9244 // parameter T declared with the constrained-parameter. Form a new
9245 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9246 // around the constrained-parameter. F has a single parameter whose
9247 // type-specifier is cv T followed by the abstract-declarator. [...]
9248 //
9249 // The cv part is done in the calling function - we get the concept with
9250 // arguments and the abstract declarator with the correct CV qualification and
9251 // have to synthesize T and the single parameter of F.
9252 auto &II = Context.Idents.get("expr-type");
9255 SourceLocation(), Depth,
9256 /*Index=*/0, &II,
9257 /*Typename=*/true,
9258 /*ParameterPack=*/false,
9259 /*HasTypeConstraint=*/true);
9260
9261 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9262 /*EllipsisLoc=*/SourceLocation(),
9263 /*AllowUnexpandedPack=*/true))
9264 // Just produce a requirement with no type requirements.
9265 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9266
9269 ArrayRef<NamedDecl *>(TParam),
9271 /*RequiresClause=*/nullptr);
9272 return BuildExprRequirement(
9273 E, /*IsSimple=*/false, NoexceptLoc,
9275}
9276
9279 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9282 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9284 ReturnTypeRequirement.isDependent())
9286 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9288 else if (ReturnTypeRequirement.isSubstitutionFailure())
9290 else if (ReturnTypeRequirement.isTypeConstraint()) {
9291 // C++2a [expr.prim.req]p1.3.3
9292 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9293 // be satisfied.
9295 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9296 QualType MatchedType =
9299 Args.push_back(TemplateArgument(MatchedType));
9300
9301 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9302
9303 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9304 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9305 const TypeConstraint *TC = Param->getTypeConstraint();
9306 assert(TC && "Type Constraint cannot be null here");
9307 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9308 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9309 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9310 if (Constraint.isInvalid()) {
9312 concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9313 [&](llvm::raw_ostream &OS) {
9314 IDC->printPretty(OS, /*Helper=*/nullptr,
9315 getPrintingPolicy());
9316 }),
9317 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9318 }
9319 SubstitutedConstraintExpr =
9320 cast<ConceptSpecializationExpr>(Constraint.get());
9321 if (!SubstitutedConstraintExpr->isSatisfied())
9323 }
9324 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9325 ReturnTypeRequirement, Status,
9326 SubstitutedConstraintExpr);
9327}
9328
9331 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9332 bool IsSimple, SourceLocation NoexceptLoc,
9334 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9335 IsSimple, NoexceptLoc,
9336 ReturnTypeRequirement);
9337}
9338
9342}
9343
9347 return new (Context) concepts::TypeRequirement(SubstDiag);
9348}
9349
9351 return BuildNestedRequirement(Constraint);
9352}
9353
9356 ConstraintSatisfaction Satisfaction;
9357 if (!Constraint->isInstantiationDependent() &&
9358 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9359 Constraint->getSourceRange(), Satisfaction))
9360 return nullptr;
9361 return new (Context) concepts::NestedRequirement(Context, Constraint,
9362 Satisfaction);
9363}
9364
9366Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9367 const ASTConstraintSatisfaction &Satisfaction) {
9369 InvalidConstraintEntity,
9371}
9372
9375 ArrayRef<ParmVarDecl *> LocalParameters,
9376 Scope *BodyScope) {
9377 assert(BodyScope);
9378
9380 RequiresKWLoc);
9381
9382 PushDeclContext(BodyScope, Body);
9383
9384 for (ParmVarDecl *Param : LocalParameters) {
9385 if (Param->hasDefaultArg())
9386 // C++2a [expr.prim.req] p4
9387 // [...] A local parameter of a requires-expression shall not have a
9388 // default argument. [...]
9389 Diag(Param->getDefaultArgRange().getBegin(),
9390 diag::err_requires_expr_local_parameter_default_argument);
9391 // Ignore default argument and move on
9392
9393 Param->setDeclContext(Body);
9394 // If this has an identifier, add it to the scope stack.
9395 if (Param->getIdentifier()) {
9396 CheckShadow(BodyScope, Param);
9397 PushOnScopeChains(Param, BodyScope);
9398 }
9399 }
9400 return Body;
9401}
9402
9404 assert(CurContext && "DeclContext imbalance!");
9406 assert(CurContext && "Popped translation unit!");
9407}
9408
9410 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9411 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9412 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9413 SourceLocation ClosingBraceLoc) {
9414 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9415 LocalParameters, RParenLoc, Requirements,
9416 ClosingBraceLoc);
9418 return ExprError();
9419 return RE;
9420}
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:2679
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
Definition: CGCall.cpp:110
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3174
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 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 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 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)
TypeTraitReturnType
static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool IsDependent)
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:14967
This file provides some common utility functions for processing Lambdas.
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
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
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:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2767
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:648
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:1103
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:2574
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2590
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:2140
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
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:1590
IdentifierTable & Idents
Definition: ASTContext.h:644
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:775
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1092
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:1119
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
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 getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1119
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2063
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2617
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:2340
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
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:1568
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:2151
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:757
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2179
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:1793
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:1999
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.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2371
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2344
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2846
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
QualType getElementType() const
Definition: Type.h:3526
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7185
Attr - This represents one attribute.
Definition: Attr.h:42
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5977
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
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:4781
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3345
This class is used for builtin types like 'int'.
Definition: Type.h:2977
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1485
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1048
const Expr * getSubExpr() const
Definition: ExprCXX.h:1507
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1540
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2440
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2502
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2491
bool isArrayForm() const
Definition: ExprCXX.h:2517
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2541
Expr * getArgument()
Definition: ExprCXX.h:2532
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
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:852
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl * > &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2),...
Definition: DeclCXX.cpp:2378
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2488
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isConst() const
Definition: DeclCXX.h:2112
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2466
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2234
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:245
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4095
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:2610
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:1342
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1335
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
base_class_range bases()
Definition: DeclCXX.h:619
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1302
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1279
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
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:132
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1329
capture_const_range captures() const
Definition: DeclCXX.h:1101
ctor_range ctors() const
Definition: DeclCXX.h:681
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1222
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1403
bool hasNonTrivialMoveConstructor() const
Determine whether this class has a non-trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1314
bool hasDefinition() const
Definition: DeclCXX.h:571
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1349
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1248
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1289
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2175
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:209
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:235
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:145
SourceLocation getEndLoc() const
Definition: DeclSpec.h:84
SourceRange getRange() const
Definition: DeclSpec.h:79
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents a C++ temporary.
Definition: ExprCXX.h:1453
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1466
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1043
Represents the this expression in C++.
Definition: ExprCXX.h:1148
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1519
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1202
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:1422
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
Expr * getCallee()
Definition: Expr.h:2970
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
arg_range arguments()
Definition: Expr.h:3059
Decl * getCalleeDecl()
Definition: Expr.h:2984
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:3082
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
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:3552
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:178
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:218
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:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
Captures information about "declaration specifiers".
Definition: DeclSpec.h:246
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:591
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:556
TST getTypeSpecType() const
Definition: DeclSpec.h:533
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:571
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:312
ParsedType getRepAsType() const
Definition: DeclSpec.h:543
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:619
Expr * getRepAsExpr() const
Definition: DeclSpec.h:551
static const TST TST_decltype
Definition: DeclSpec.h:310
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:578
static const TST TST_decltype_auto
Definition: DeclSpec.h:311
static const TST TST_error
Definition: DeclSpec.h:324
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:588
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
void setImplicit(bool I=true)
Definition: DeclBase.h:600
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool hasAttr() const
Definition: DeclBase.h:583
@ 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:871
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
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:822
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2396
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2045
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2082
void DropFirstTypeObject()
Definition: DeclSpec.h:2413
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2392
bool isInvalidType() const
Definition: DeclSpec.h:2712
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2080
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2087
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5943
bool isDeduced() const
Definition: Type.h:5965
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3868
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4854
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4082
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5571
EnumDecl * getDecl() const
Definition: Type.h:5578
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
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:2523
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:4133
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:3059
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
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:3279
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
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:3556
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:3918
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:2917
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3058
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1039
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2284
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2668
QualType getReturnType() const
Definition: Decl.h:2755
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2340
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2503
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:3366
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:2161
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4397
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
size_t param_size() const
Definition: Decl.h:2700
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:3203
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
unsigned getNumParams() const
Definition: Type.h:4885
QualType getParamType(unsigned i) const
Definition: Type.h:4887
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5008
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5003
Declaration of a template function.
Definition: DeclTemplate.h:958
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4437
bool getNoReturn() const
Definition: Type.h:4411
bool getProducesResult() const
Definition: Type.h:4412
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
ExtInfo getExtInfo() const
Definition: Type.h:4581
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....
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:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4847
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:8591
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3700
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9628
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:3689
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:977
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:725
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:638
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:740
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:735
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:1358
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:673
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:719
bool hasNext() const
Definition: Lookup.h:704
NamedDecl * next()
Definition: Lookup.h:708
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:603
DeclClass * getAsSingle() const
Definition: Lookup.h:556
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:662
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:747
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:632
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:4289
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3259
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
QualType getPointeeType() const
Definition: Type.h:3472
const Type * getClass() const
Definition: Type.h:3486
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:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:292
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:1808
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1053
Represents a pointer to an Objective C object.
Definition: Type.h:7004
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7016
Represents a class type in Objective C.
Definition: Type.h:6750
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6983
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:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:2112
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
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:2915
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3135
QualType getPointeeType() const
Definition: Type.h:3145
SourceManager & getSourceManager() const
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2559
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2575
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7439
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
@ DK_nontrivial_c_struct
Definition: Type.h:1523
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7537
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7355
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7481
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7395
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
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:7556
QualType getCanonicalType() const
Definition: Type.h:7407
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7449
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2828
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7401
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
The collection of all-type qualifiers we support.
Definition: Type.h:318
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:505
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
bool hasCVRQualifiers() const
Definition: Type.h:473
bool hasUnaligned() const
Definition: Type.h:497
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:564
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
unsigned getCVRUQualifiers() const
Definition: Type.h:475
void setObjCGCAttr(GC type)
Definition: Type.h:506
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:427
LangAS getAddressSpace() const
Definition: Type.h:557
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
Represents a struct/union/class.
Definition: Decl.h:4169
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4298
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
RecordDecl * getDecl() const
Definition: Type.h:5555
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents the body of a requires-expression.
Definition: DeclCXX.h:2029
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2174
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:56
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:819
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:320
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:227
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:2544
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:8056
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9508
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9538
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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:6794
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:698
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:8840
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2471
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:6365
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:7391
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7379
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7421
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:423
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
VariadicCallType
Definition: Sema.h:2013
@ VariadicDoesNotApply
Definition: Sema.h:2018
@ VariadicFunction
Definition: Sema.h:2014
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:6872
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:6877
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:6881
@ IER_Error
An error occurred.
Definition: Sema.h:6884
@ IER_Exists
The symbol exists.
Definition: Sema.h:6874
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:1561
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:998
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:20639
ConditionKind
Definition: Sema.h:5898
@ 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:807
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8148
@ AR_inaccessible
Definition: Sema.h:1074
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:3366
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:18703
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:17458
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:10529
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1420
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
FunctionDecl * 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:1499
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.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1057
ASTContext & Context
Definition: Sema.h:858
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:582
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:524
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:8135
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
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:5792
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19903
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:762
ASTContext & getASTContext() const
Definition: Sema.h:527
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:19194
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9967
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
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:645
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:6380
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:775
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
ActOnCXXThrow - Parse throw expressions.
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2206
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
EnumDecl * getStdAlignValT() const
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:10027
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:6476
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:7478
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:3448
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:224
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:10842
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:10845
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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:7493
SemaOpenACC & OpenACC()
Definition: Sema.h:1008
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
Preprocessor & PP
Definition: Sema.h:857
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:11246
const LangOptions & LangOpts
Definition: Sema.h:856
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:2360
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:8554
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:17759
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:71
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:20311
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:5188
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)
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:727
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.
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.
Definition: SemaExpr.cpp:3174
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:10779
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5185
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:10732
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:6295
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7739
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:1797
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7909
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
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:5904
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:8160
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:6287
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6091
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6093
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6172
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
ActOnCXXNew - Parsed a C++ 'new' expression.
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:5942
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:6487
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4339
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21227
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17652
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:10484
SourceManager & getSourceManager() const
Definition: Sema.h:525
@ TryCapture_Implicit
Definition: Sema.h:5276
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:6548
AssignmentAction
Definition: Sema.h:5196
@ AA_Returning
Definition: Sema.h:5199
@ AA_Passing_CFAudited
Definition: Sema.h:5204
@ AA_Initializing
Definition: Sema.h:5201
@ AA_Converting
Definition: Sema.h:5200
@ AA_Assigning
Definition: Sema.h:5197
@ AA_Passing
Definition: Sema.h:5198
@ AA_Casting
Definition: Sema.h:5203
@ AA_Sending
Definition: Sema.h:5202
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:3606
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.
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 CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
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:227
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:8374
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:60
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:11707
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:6483
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:8030
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:290
ASTConsumer & Consumer
Definition: Sema.h:859
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:5192
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16691
@ 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:9876
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20511
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
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...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21155
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:6494
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18177
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
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:860
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:527
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
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:2174
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
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:9890
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:17125
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:18360
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:6138
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:21454
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:94
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6480
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9545
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:3222
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:5885
IdentifierResolver IdResolver
Definition: Sema.h:2537
const TypoExprState & getTypoExprState(TypoExpr *TE) const
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5841
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:6655
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:6663
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:6660
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:6657
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:5584
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:6733
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:267
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:355
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:294
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:354
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:304
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:288
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:284
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4383
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
StringRef getString() const
Definition: Expr.h:1850
bool isUnion() const
Definition: Decl.h:3791
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:721
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:504
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
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:144
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:231
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3391
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:7326
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:7337
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:1828
The base class of the type hierarchy.
Definition: Type.h:1813
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:2454
bool isStructureType() const
Definition: Type.cpp:628
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isBlockPointerType() const
Definition: Type.h:7616
bool isVoidType() const
Definition: Type.h:7901
bool isBooleanType() const
Definition: Type.h:8029
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2880
bool isIncompleteArrayType() const
Definition: Type.h:7682
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:7877
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2134
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool isRValueReferenceType() const
Definition: Type.h:7628
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:7571
bool isVoidPointerType() const
Definition: Type.cpp:654
bool isArrayType() const
Definition: Type.h:7674
bool isArithmeticType() const
Definition: Type.cpp:2269
bool isPointerType() const
Definition: Type.h:7608
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7941
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8186
bool isReferenceType() const
Definition: Type.h:7620
bool isEnumeralType() const
Definition: Type.h:7706
bool isScalarType() const
Definition: Type.h:8000
bool isInterfaceType() const
Definition: Type.cpp:640
bool isVariableArrayType() const
Definition: Type.h:7686
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isExtVectorType() const
Definition: Type.h:7718
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
bool isMemberDataPointerType() const
Definition: Type.h:7667
bool isLValueReferenceType() const
Definition: Type.h:7624
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2326
bool isAnyComplexType() const
Definition: Type.h:7710
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7954
bool isHalfType() const
Definition: Type.h:7905
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1999
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:7582
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8069
bool isMemberPointerType() const
Definition: Type.h:7656
bool isMatrixType() const
Definition: Type.h:7728
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2961
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2667
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2401
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4825
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7604
bool isObjCObjectPointerType() const
Definition: Type.h:7740
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2246
bool isStructureOrClassType() const
Definition: Type.cpp:646
bool isMemberFunctionPointerType() const
Definition: Type.h:7660
bool isVectorType() const
Definition: Type.h:7714
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isFloatingType() const
Definition: Type.cpp:2237
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:2184
bool isAnyPointerType() const
Definition: Type.h:7612
bool isClassType() const
Definition: Type.cpp:622
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4831
bool isNullPtrType() const
Definition: Type.h:7934
bool isRecordType() const
Definition: Type.h:7702
bool isObjCRetainableType() const
Definition: Type.cpp:4862
bool isUnionType() const
Definition: Type.cpp:660
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:1878
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition: Type.cpp:677
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:6585
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:6605
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6604
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1082
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition: DeclSpec.h:1052
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1106
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1076
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5367
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
Represents a variable declaration or definition.
Definition: Decl.h:918
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
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:2505
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1345
Represents a GCC generic vector type.
Definition: Type.h:3965
unsigned getNumElements() const
Definition: Type.h:3980
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:752
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
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:878
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:865
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:886
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
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.
Requirement::SubstitutionDiagnostic * createSubstDiagAt(Sema &S, SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using Sema's a...
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:868
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.
@ Bind
'bind' clause, allowed on routine constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
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:97
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:178
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:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
@ 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:146
@ 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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ 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:247
@ 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_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:205
@ 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.
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:373
@ 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:2219
@ 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:442
@ 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:121
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:93
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
Definition: ASTConcept.cpp:75
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:1308
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1317
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1247
enum clang::DeclaratorChunk::@221 Kind
ArrayTypeInfo Arr
Definition: DeclSpec.h:1637
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1255
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4708
Extra information about a function prototype.
Definition: Type.h:4731
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4732
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8156
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:410
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:432
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:423
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:418
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:437