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