clang  8.0.0
SemaExprCXX.cpp
Go to the documentation of this file.
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// Implements semantic analysis for C++ expressions.
12 ///
13 //===----------------------------------------------------------------------===//
14 
16 #include "TreeTransform.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTLambda.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
33 #include "clang/Sema/Lookup.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaLambda.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace clang;
43 using namespace sema;
44 
45 /// Handle the result of the special case name lookup for inheriting
46 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47 /// constructor names in member using declarations, even if 'X' is not the
48 /// name of the corresponding type.
50  SourceLocation NameLoc,
51  IdentifierInfo &Name) {
52  NestedNameSpecifier *NNS = SS.getScopeRep();
53 
54  // Convert the nested-name-specifier into a type.
55  QualType Type;
56  switch (NNS->getKind()) {
59  Type = QualType(NNS->getAsType(), 0);
60  break;
61 
63  // Strip off the last layer of the nested-name-specifier and build a
64  // typename type for it.
65  assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66  Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67  NNS->getAsIdentifier());
68  break;
69 
74  llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75  }
76 
77  // This reference to the type is located entirely at the location of the
78  // final identifier in the qualified-id.
79  return CreateParsedType(Type,
80  Context.getTrivialTypeSourceInfo(Type, NameLoc));
81 }
82 
84  SourceLocation NameLoc,
85  Scope *S, CXXScopeSpec &SS,
86  bool EnteringContext) {
87  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88  assert(CurClass && &II == CurClass->getIdentifier() &&
89  "not a constructor name");
90 
91  // When naming a constructor as a member of a dependent context (eg, in a
92  // friend declaration or an inherited constructor declaration), form an
93  // unresolved "typename" type.
94  if (CurClass->isDependentContext() && !EnteringContext) {
95  QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96  return ParsedType::make(T);
97  }
98 
99  if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100  return ParsedType();
101 
102  // Find the injected-class-name declaration. Note that we make no attempt to
103  // diagnose cases where the injected-class-name is shadowed: the only
104  // declaration that can validly shadow the injected-class-name is a
105  // non-static data member, and if the class contains both a non-static data
106  // member and a constructor then it is ill-formed (we check that in
107  // CheckCompletedCXXClass).
108  CXXRecordDecl *InjectedClassName = nullptr;
109  for (NamedDecl *ND : CurClass->lookup(&II)) {
110  auto *RD = dyn_cast<CXXRecordDecl>(ND);
111  if (RD && RD->isInjectedClassName()) {
112  InjectedClassName = RD;
113  break;
114  }
115  }
116  if (!InjectedClassName) {
117  if (!CurClass->isInvalidDecl()) {
118  // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119  // properly. Work around it here for now.
121  diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122  }
123  return ParsedType();
124  }
125 
126  QualType T = Context.getTypeDeclType(InjectedClassName);
127  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129 
130  return ParsedType::make(T);
131 }
132 
134  IdentifierInfo &II,
135  SourceLocation NameLoc,
136  Scope *S, CXXScopeSpec &SS,
137  ParsedType ObjectTypePtr,
138  bool EnteringContext) {
139  // Determine where to perform name lookup.
140 
141  // FIXME: This area of the standard is very messy, and the current
142  // wording is rather unclear about which scopes we search for the
143  // destructor name; see core issues 399 and 555. Issue 399 in
144  // particular shows where the current description of destructor name
145  // lookup is completely out of line with existing practice, e.g.,
146  // this appears to be ill-formed:
147  //
148  // namespace N {
149  // template <typename T> struct S {
150  // ~S();
151  // };
152  // }
153  //
154  // void f(N::S<int>* s) {
155  // s->N::S<int>::~S();
156  // }
157  //
158  // See also PR6358 and PR6359.
159  // For this reason, we're currently only doing the C++03 version of this
160  // code; the C++0x version has to wait until we get a proper spec.
161  QualType SearchType;
162  DeclContext *LookupCtx = nullptr;
163  bool isDependent = false;
164  bool LookInScope = false;
165 
166  if (SS.isInvalid())
167  return nullptr;
168 
169  // If we have an object type, it's because we are in a
170  // pseudo-destructor-expression or a member access expression, and
171  // we know what type we're looking for.
172  if (ObjectTypePtr)
173  SearchType = GetTypeFromParser(ObjectTypePtr);
174 
175  if (SS.isSet()) {
176  NestedNameSpecifier *NNS = SS.getScopeRep();
177 
178  bool AlreadySearched = false;
179  bool LookAtPrefix = true;
180  // C++11 [basic.lookup.qual]p6:
181  // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
182  // the type-names are looked up as types in the scope designated by the
183  // nested-name-specifier. Similarly, in a qualified-id of the form:
184  //
185  // nested-name-specifier[opt] class-name :: ~ class-name
186  //
187  // the second class-name is looked up in the same scope as the first.
188  //
189  // Here, we determine whether the code below is permitted to look at the
190  // prefix of the nested-name-specifier.
191  DeclContext *DC = computeDeclContext(SS, EnteringContext);
192  if (DC && DC->isFileContext()) {
193  AlreadySearched = true;
194  LookupCtx = DC;
195  isDependent = false;
196  } else if (DC && isa<CXXRecordDecl>(DC)) {
197  LookAtPrefix = false;
198  LookInScope = true;
199  }
200 
201  // The second case from the C++03 rules quoted further above.
202  NestedNameSpecifier *Prefix = nullptr;
203  if (AlreadySearched) {
204  // Nothing left to do.
205  } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206  CXXScopeSpec PrefixSS;
207  PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
208  LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209  isDependent = isDependentScopeSpecifier(PrefixSS);
210  } else if (ObjectTypePtr) {
211  LookupCtx = computeDeclContext(SearchType);
212  isDependent = SearchType->isDependentType();
213  } else {
214  LookupCtx = computeDeclContext(SS, EnteringContext);
215  isDependent = LookupCtx && LookupCtx->isDependentContext();
216  }
217  } else if (ObjectTypePtr) {
218  // C++ [basic.lookup.classref]p3:
219  // If the unqualified-id is ~type-name, the type-name is looked up
220  // in the context of the entire postfix-expression. If the type T
221  // of the object expression is of a class type C, the type-name is
222  // also looked up in the scope of class C. At least one of the
223  // lookups shall find a name that refers to (possibly
224  // cv-qualified) T.
225  LookupCtx = computeDeclContext(SearchType);
226  isDependent = SearchType->isDependentType();
227  assert((isDependent || !SearchType->isIncompleteType()) &&
228  "Caller should have completed object type");
229 
230  LookInScope = true;
231  } else {
232  // Perform lookup into the current scope (only).
233  LookInScope = true;
234  }
235 
236  TypeDecl *NonMatchingTypeDecl = nullptr;
237  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238  for (unsigned Step = 0; Step != 2; ++Step) {
239  // Look for the name first in the computed lookup context (if we
240  // have one) and, if that fails to find a match, in the scope (if
241  // we're allowed to look there).
242  Found.clear();
243  if (Step == 0 && LookupCtx) {
244  if (RequireCompleteDeclContext(SS, LookupCtx))
245  return nullptr;
246  LookupQualifiedName(Found, LookupCtx);
247  } else if (Step == 1 && LookInScope && S) {
248  LookupName(Found, S);
249  } else {
250  continue;
251  }
252 
253  // FIXME: Should we be suppressing ambiguities here?
254  if (Found.isAmbiguous())
255  return nullptr;
256 
257  if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258  QualType T = Context.getTypeDeclType(Type);
259  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
260 
261  if (SearchType.isNull() || SearchType->isDependentType() ||
262  Context.hasSameUnqualifiedType(T, SearchType)) {
263  // We found our type!
264 
265  return CreateParsedType(T,
266  Context.getTrivialTypeSourceInfo(T, NameLoc));
267  }
268 
269  if (!SearchType.isNull())
270  NonMatchingTypeDecl = Type;
271  }
272 
273  // If the name that we found is a class template name, and it is
274  // the same name as the template name in the last part of the
275  // nested-name-specifier (if present) or the object type, then
276  // this is the destructor for that class.
277  // FIXME: This is a workaround until we get real drafting for core
278  // issue 399, for which there isn't even an obvious direction.
279  if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280  QualType MemberOfType;
281  if (SS.isSet()) {
282  if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283  // Figure out the type of the context, if it has one.
284  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285  MemberOfType = Context.getTypeDeclType(Record);
286  }
287  }
288  if (MemberOfType.isNull())
289  MemberOfType = SearchType;
290 
291  if (MemberOfType.isNull())
292  continue;
293 
294  // We're referring into a class template specialization. If the
295  // class template we found is the same as the template being
296  // specialized, we found what we are looking for.
297  if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
299  = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300  if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301  Template->getCanonicalDecl())
302  return CreateParsedType(
303  MemberOfType,
304  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
305  }
306 
307  continue;
308  }
309 
310  // We're referring to an unresolved class template
311  // specialization. Determine whether we class template we found
312  // is the same as the template being specialized or, if we don't
313  // know which template is being specialized, that it at least
314  // has the same name.
315  if (const TemplateSpecializationType *SpecType
316  = MemberOfType->getAs<TemplateSpecializationType>()) {
317  TemplateName SpecName = SpecType->getTemplateName();
318 
319  // The class template we found is the same template being
320  // specialized.
321  if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322  if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
323  return CreateParsedType(
324  MemberOfType,
325  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
326 
327  continue;
328  }
329 
330  // The class template we found has the same name as the
331  // (dependent) template name being specialized.
332  if (DependentTemplateName *DepTemplate
333  = SpecName.getAsDependentTemplateName()) {
334  if (DepTemplate->isIdentifier() &&
335  DepTemplate->getIdentifier() == Template->getIdentifier())
336  return CreateParsedType(
337  MemberOfType,
338  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
339 
340  continue;
341  }
342  }
343  }
344  }
345 
346  if (isDependent) {
347  // We didn't find our type, but that's okay: it's dependent
348  // anyway.
349 
350  // FIXME: What if we have no nested-name-specifier?
351  QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352  SS.getWithLocInContext(Context),
353  II, NameLoc);
354  return ParsedType::make(T);
355  }
356 
357  if (NonMatchingTypeDecl) {
358  QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359  Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360  << T << SearchType;
361  Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362  << T;
363  } else if (ObjectTypePtr)
364  Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
365  << &II;
366  else {
367  SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368  diag::err_destructor_class_name);
369  if (S) {
370  const DeclContext *Ctx = S->getEntity();
371  if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372  DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373  Class->getNameAsString());
374  }
375  }
376 
377  return nullptr;
378 }
379 
381  ParsedType ObjectType) {
383  return nullptr;
384 
386  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387  return nullptr;
388  }
389 
390  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391  "unexpected type in getDestructorType");
392  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393 
394  // If we know the type of the object, check that the correct destructor
395  // type was named now; we can give better diagnostics this way.
396  QualType SearchType = GetTypeFromParser(ObjectType);
397  if (!SearchType.isNull() && !SearchType->isDependentType() &&
398  !Context.hasSameUnqualifiedType(T, SearchType)) {
399  Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400  << T << SearchType;
401  return nullptr;
402  }
403 
404  return ParsedType::make(T);
405 }
406 
408  const UnqualifiedId &Name) {
410 
411  if (!SS.isValid())
412  return false;
413 
414  switch (SS.getScopeRep()->getKind()) {
418  // Per C++11 [over.literal]p2, literal operators can only be declared at
419  // namespace scope. Therefore, this unqualified-id cannot name anything.
420  // Reject it early, because we have no AST representation for this in the
421  // case where the scope is dependent.
422  Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423  << SS.getScopeRep();
424  return true;
425 
430  return false;
431  }
432 
433  llvm_unreachable("unknown nested name specifier kind");
434 }
435 
436 /// Build a C++ typeid expression with a type operand.
438  SourceLocation TypeidLoc,
439  TypeSourceInfo *Operand,
440  SourceLocation RParenLoc) {
441  // C++ [expr.typeid]p4:
442  // The top-level cv-qualifiers of the lvalue expression or the type-id
443  // that is the operand of typeid are always ignored.
444  // If the type of the type-id is a class type or a reference to a class
445  // type, the class shall be completely-defined.
446  Qualifiers Quals;
447  QualType T
448  = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449  Quals);
450  if (T->getAs<RecordType>() &&
451  RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452  return ExprError();
453 
454  if (T->isVariablyModifiedType())
455  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456 
457  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458  SourceRange(TypeidLoc, RParenLoc));
459 }
460 
461 /// Build a C++ typeid expression with an expression operand.
463  SourceLocation TypeidLoc,
464  Expr *E,
465  SourceLocation RParenLoc) {
466  bool WasEvaluated = false;
467  if (E && !E->isTypeDependent()) {
468  if (E->getType()->isPlaceholderType()) {
469  ExprResult result = CheckPlaceholderExpr(E);
470  if (result.isInvalid()) return ExprError();
471  E = result.get();
472  }
473 
474  QualType T = E->getType();
475  if (const RecordType *RecordT = T->getAs<RecordType>()) {
476  CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477  // C++ [expr.typeid]p3:
478  // [...] If the type of the expression is a class type, the class
479  // shall be completely-defined.
480  if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481  return ExprError();
482 
483  // C++ [expr.typeid]p3:
484  // When typeid is applied to an expression other than an glvalue of a
485  // polymorphic class type [...] [the] expression is an unevaluated
486  // operand. [...]
487  if (RecordD->isPolymorphic() && E->isGLValue()) {
488  // The subexpression is potentially evaluated; switch the context
489  // and recheck the subexpression.
490  ExprResult Result = TransformToPotentiallyEvaluated(E);
491  if (Result.isInvalid()) return ExprError();
492  E = Result.get();
493 
494  // We require a vtable to query the type at run time.
495  MarkVTableUsed(TypeidLoc, RecordD);
496  WasEvaluated = true;
497  }
498  }
499 
500  // C++ [expr.typeid]p4:
501  // [...] If the type of the type-id is a reference to a possibly
502  // cv-qualified type, the result of the typeid expression refers to a
503  // std::type_info object representing the cv-unqualified referenced
504  // type.
505  Qualifiers Quals;
506  QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507  if (!Context.hasSameType(T, UnqualT)) {
508  T = UnqualT;
509  E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
510  }
511  }
512 
513  if (E->getType()->isVariablyModifiedType())
514  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515  << E->getType());
516  else if (!inTemplateInstantiation() &&
517  E->HasSideEffects(Context, WasEvaluated)) {
518  // The expression operand for typeid is in an unevaluated expression
519  // context, so side effects could result in unintended consequences.
520  Diag(E->getExprLoc(), WasEvaluated
521  ? diag::warn_side_effects_typeid
522  : diag::warn_side_effects_unevaluated_context);
523  }
524 
525  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526  SourceRange(TypeidLoc, RParenLoc));
527 }
528 
529 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
532  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
533  // OpenCL C++ 1.0 s2.9: typeid is not supported.
534  if (getLangOpts().OpenCLCPlusPlus) {
535  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536  << "typeid");
537  }
538 
539  // Find the std::type_info type.
540  if (!getStdNamespace())
541  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
542 
543  if (!CXXTypeInfoDecl) {
544  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546  LookupQualifiedName(R, getStdNamespace());
547  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
548  // Microsoft's typeinfo doesn't have type_info in std but in the global
549  // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
550  if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
551  LookupQualifiedName(R, Context.getTranslationUnitDecl());
552  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553  }
554  if (!CXXTypeInfoDecl)
555  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556  }
557 
558  if (!getLangOpts().RTTI) {
559  return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560  }
561 
562  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
563 
564  if (isType) {
565  // The operand is a type; handle it as such.
566  TypeSourceInfo *TInfo = nullptr;
567  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568  &TInfo);
569  if (T.isNull())
570  return ExprError();
571 
572  if (!TInfo)
573  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
574 
575  return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
576  }
577 
578  // The operand is an expression.
579  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
580 }
581 
582 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583 /// a single GUID.
584 static void
587  // Optionally remove one level of pointer, reference or array indirection.
588  const Type *Ty = QT.getTypePtr();
589  if (QT->isPointerType() || QT->isReferenceType())
590  Ty = QT->getPointeeType().getTypePtr();
591  else if (QT->isArrayType())
592  Ty = Ty->getBaseElementTypeUnsafe();
593 
594  const auto *TD = Ty->getAsTagDecl();
595  if (!TD)
596  return;
597 
598  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
599  UuidAttrs.insert(Uuid);
600  return;
601  }
602 
603  // __uuidof can grab UUIDs from template arguments.
604  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
605  const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606  for (const TemplateArgument &TA : TAL.asArray()) {
607  const UuidAttr *UuidForTA = nullptr;
608  if (TA.getKind() == TemplateArgument::Type)
609  getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610  else if (TA.getKind() == TemplateArgument::Declaration)
611  getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612 
613  if (UuidForTA)
614  UuidAttrs.insert(UuidForTA);
615  }
616  }
617 }
618 
619 /// Build a Microsoft __uuidof expression with a type operand.
621  SourceLocation TypeidLoc,
622  TypeSourceInfo *Operand,
623  SourceLocation RParenLoc) {
624  StringRef UuidStr;
625  if (!Operand->getType()->isDependentType()) {
627  getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628  if (UuidAttrs.empty())
629  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630  if (UuidAttrs.size() > 1)
631  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
632  UuidStr = UuidAttrs.back()->getGuid();
633  }
634 
635  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
636  SourceRange(TypeidLoc, RParenLoc));
637 }
638 
639 /// Build a Microsoft __uuidof expression with an expression operand.
641  SourceLocation TypeidLoc,
642  Expr *E,
643  SourceLocation RParenLoc) {
644  StringRef UuidStr;
645  if (!E->getType()->isDependentType()) {
647  UuidStr = "00000000-0000-0000-0000-000000000000";
648  } else {
650  getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651  if (UuidAttrs.empty())
652  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
653  if (UuidAttrs.size() > 1)
654  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
655  UuidStr = UuidAttrs.back()->getGuid();
656  }
657  }
658 
659  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
660  SourceRange(TypeidLoc, RParenLoc));
661 }
662 
663 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
666  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
667  // If MSVCGuidDecl has not been cached, do the lookup.
668  if (!MSVCGuidDecl) {
669  IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670  LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671  LookupQualifiedName(R, Context.getTranslationUnitDecl());
672  MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673  if (!MSVCGuidDecl)
674  return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
675  }
676 
677  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
678 
679  if (isType) {
680  // The operand is a type; handle it as such.
681  TypeSourceInfo *TInfo = nullptr;
682  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683  &TInfo);
684  if (T.isNull())
685  return ExprError();
686 
687  if (!TInfo)
688  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689 
690  return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691  }
692 
693  // The operand is an expression.
694  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695 }
696 
697 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
700  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
701  "Unknown C++ Boolean value!");
702  return new (Context)
703  CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
704 }
705 
706 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
709  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
710 }
711 
712 /// ActOnCXXThrow - Parse throw expressions.
715  bool IsThrownVarInScope = false;
716  if (Ex) {
717  // C++0x [class.copymove]p31:
718  // When certain criteria are met, an implementation is allowed to omit the
719  // copy/move construction of a class object [...]
720  //
721  // - in a throw-expression, when the operand is the name of a
722  // non-volatile automatic object (other than a function or catch-
723  // clause parameter) whose scope does not extend beyond the end of the
724  // innermost enclosing try-block (if there is one), the copy/move
725  // operation from the operand to the exception object (15.1) can be
726  // omitted by constructing the automatic object directly into the
727  // exception object
728  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730  if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731  for( ; S; S = S->getParent()) {
732  if (S->isDeclScope(Var)) {
733  IsThrownVarInScope = true;
734  break;
735  }
736 
737  if (S->getFlags() &
741  break;
742  }
743  }
744  }
745  }
746 
747  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748 }
749 
751  bool IsThrownVarInScope) {
752  // Don't report an error if 'throw' is used in system headers.
753  if (!getLangOpts().CXXExceptions &&
754  !getSourceManager().isInSystemHeader(OpLoc) &&
755  (!getLangOpts().OpenMPIsDevice ||
756  !getLangOpts().OpenMPHostCXXExceptions ||
757  isInOpenMPTargetExecutionDirective() ||
758  isInOpenMPDeclareTargetContext()))
759  Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
760 
761  // Exceptions aren't allowed in CUDA device code.
762  if (getLangOpts().CUDA)
763  CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764  << "throw" << CurrentCUDATarget();
765 
766  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767  Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768 
769  if (Ex && !Ex->isTypeDependent()) {
770  QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771  if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
772  return ExprError();
773 
774  // Initialize the exception result. This implicitly weeds out
775  // abstract types or types with inaccessible copy constructors.
776 
777  // C++0x [class.copymove]p31:
778  // When certain criteria are met, an implementation is allowed to omit the
779  // copy/move construction of a class object [...]
780  //
781  // - in a throw-expression, when the operand is the name of a
782  // non-volatile automatic object (other than a function or
783  // catch-clause
784  // parameter) whose scope does not extend beyond the end of the
785  // innermost enclosing try-block (if there is one), the copy/move
786  // operation from the operand to the exception object (15.1) can be
787  // omitted by constructing the automatic object directly into the
788  // exception object
789  const VarDecl *NRVOVariable = nullptr;
790  if (IsThrownVarInScope)
791  NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
792 
794  OpLoc, ExceptionObjectTy,
795  /*NRVO=*/NRVOVariable != nullptr);
796  ExprResult Res = PerformMoveOrCopyInitialization(
797  Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798  if (Res.isInvalid())
799  return ExprError();
800  Ex = Res.get();
801  }
802 
803  return new (Context)
804  CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
805 }
806 
807 static void
809  llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810  llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811  llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812  bool ParentIsPublic) {
813  for (const CXXBaseSpecifier &BS : RD->bases()) {
814  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815  bool NewSubobject;
816  // Virtual bases constitute the same subobject. Non-virtual bases are
817  // always distinct subobjects.
818  if (BS.isVirtual())
819  NewSubobject = VBases.insert(BaseDecl).second;
820  else
821  NewSubobject = true;
822 
823  if (NewSubobject)
824  ++SubobjectsSeen[BaseDecl];
825 
826  // Only add subobjects which have public access throughout the entire chain.
827  bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828  if (PublicPath)
829  PublicSubobjectsSeen.insert(BaseDecl);
830 
831  // Recurse on to each base subobject.
832  collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833  PublicPath);
834  }
835 }
836 
839  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842  SubobjectsSeen[RD] = 1;
843  PublicSubobjectsSeen.insert(RD);
844  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845  /*ParentIsPublic=*/true);
846 
847  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848  // Skip ambiguous objects.
849  if (SubobjectsSeen[PublicSubobject] > 1)
850  continue;
851 
852  Objects.push_back(PublicSubobject);
853  }
854 }
855 
856 /// CheckCXXThrowOperand - Validate the operand of a throw.
858  QualType ExceptionObjectTy, Expr *E) {
859  // If the type of the exception would be an incomplete type or a pointer
860  // to an incomplete type other than (cv) void the program is ill-formed.
861  QualType Ty = ExceptionObjectTy;
862  bool isPointer = false;
863  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
864  Ty = Ptr->getPointeeType();
865  isPointer = true;
866  }
867  if (!isPointer || !Ty->isVoidType()) {
868  if (RequireCompleteType(ThrowLoc, Ty,
869  isPointer ? diag::err_throw_incomplete_ptr
870  : diag::err_throw_incomplete,
871  E->getSourceRange()))
872  return true;
873 
874  if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
875  diag::err_throw_abstract_type, E))
876  return true;
877  }
878 
879  // If the exception has class type, we need additional handling.
880  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881  if (!RD)
882  return false;
883 
884  // If we are throwing a polymorphic class type or pointer thereof,
885  // exception handling will make use of the vtable.
886  MarkVTableUsed(ThrowLoc, RD);
887 
888  // If a pointer is thrown, the referenced object will not be destroyed.
889  if (isPointer)
890  return false;
891 
892  // If the class has a destructor, we must be able to call it.
893  if (!RD->hasIrrelevantDestructor()) {
894  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895  MarkFunctionReferenced(E->getExprLoc(), Destructor);
896  CheckDestructorAccess(E->getExprLoc(), Destructor,
897  PDiag(diag::err_access_dtor_exception) << Ty);
898  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
899  return true;
900  }
901  }
902 
903  // The MSVC ABI creates a list of all types which can catch the exception
904  // object. This list also references the appropriate copy constructor to call
905  // if the object is caught by value and has a non-trivial copy constructor.
906  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
907  // We are only interested in the public, unambiguous bases contained within
908  // the exception object. Bases which are ambiguous or otherwise
909  // inaccessible are not catchable types.
910  llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911  getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
912 
913  for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
914  // Attempt to lookup the copy constructor. Various pieces of machinery
915  // will spring into action, like template instantiation, which means this
916  // cannot be a simple walk of the class's decls. Instead, we must perform
917  // lookup and overload resolution.
918  CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919  if (!CD)
920  continue;
921 
922  // Mark the constructor referenced as it is used by this throw expression.
923  MarkFunctionReferenced(E->getExprLoc(), CD);
924 
925  // Skip this copy constructor if it is trivial, we don't need to record it
926  // in the catchable type data.
927  if (CD->isTrivial())
928  continue;
929 
930  // The copy constructor is non-trivial, create a mapping from this class
931  // type to this constructor.
932  // N.B. The selection of copy constructor is not sensitive to this
933  // particular throw-site. Lookup will be performed at the catch-site to
934  // ensure that the copy constructor is, in fact, accessible (via
935  // friendship or any other means).
936  Context.addCopyConstructorForExceptionObject(Subobject, CD);
937 
938  // We don't keep the instantiated default argument expressions around so
939  // we must rebuild them here.
940  for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
941  if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942  return true;
943  }
944  }
945  }
946 
947  return false;
948 }
949 
951  ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952  DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953 
954  QualType ClassType = ThisTy->getPointeeType();
955  LambdaScopeInfo *CurLSI = nullptr;
956  DeclContext *CurDC = CurSemaContext;
957 
958  // Iterate through the stack of lambdas starting from the innermost lambda to
959  // the outermost lambda, checking if '*this' is ever captured by copy - since
960  // that could change the cv-qualifiers of the '*this' object.
961  // The object referred to by '*this' starts out with the cv-qualifiers of its
962  // member function. We then start with the innermost lambda and iterate
963  // outward checking to see if any lambda performs a by-copy capture of '*this'
964  // - and if so, any nested lambda must respect the 'constness' of that
965  // capturing lamdbda's call operator.
966  //
967 
968  // Since the FunctionScopeInfo stack is representative of the lexical
969  // nesting of the lambda expressions during initial parsing (and is the best
970  // place for querying information about captures about lambdas that are
971  // partially processed) and perhaps during instantiation of function templates
972  // that contain lambda expressions that need to be transformed BUT not
973  // necessarily during instantiation of a nested generic lambda's function call
974  // operator (which might even be instantiated at the end of the TU) - at which
975  // time the DeclContext tree is mature enough to query capture information
976  // reliably - we use a two pronged approach to walk through all the lexically
977  // enclosing lambda expressions:
978  //
979  // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980  // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981  // enclosed by the call-operator of the LSI below it on the stack (while
982  // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983  // the stack represents the innermost lambda.
984  //
985  // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986  // represents a lambda's call operator. If it does, we must be instantiating
987  // a generic lambda's call operator (represented by the Current LSI, and
988  // should be the only scenario where an inconsistency between the LSI and the
989  // DeclContext should occur), so climb out the DeclContexts if they
990  // represent lambdas, while querying the corresponding closure types
991  // regarding capture information.
992 
993  // 1) Climb down the function scope info stack.
994  for (int I = FunctionScopes.size();
995  I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996  (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997  cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
998  CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999  CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1000 
1001  if (!CurLSI->isCXXThisCaptured())
1002  continue;
1003 
1004  auto C = CurLSI->getCXXThisCapture();
1005 
1006  if (C.isCopyCapture()) {
1008  if (CurLSI->CallOperator->isConst())
1009  ClassType.addConst();
1010  return ASTCtx.getPointerType(ClassType);
1011  }
1012  }
1013 
1014  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015  // happen during instantiation of its nested generic lambda call operator)
1016  if (isLambdaCallOperator(CurDC)) {
1017  assert(CurLSI && "While computing 'this' capture-type for a generic "
1018  "lambda, we must have a corresponding LambdaScopeInfo");
1020  "While computing 'this' capture-type for a generic lambda, when we "
1021  "run out of enclosing LSI's, yet the enclosing DC is a "
1022  "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023  "lambda call oeprator");
1024  assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1025 
1026  auto IsThisCaptured =
1027  [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028  IsConst = false;
1029  IsByCopy = false;
1030  for (auto &&C : Closure->captures()) {
1031  if (C.capturesThis()) {
1032  if (C.getCaptureKind() == LCK_StarThis)
1033  IsByCopy = true;
1034  if (Closure->getLambdaCallOperator()->isConst())
1035  IsConst = true;
1036  return true;
1037  }
1038  }
1039  return false;
1040  };
1041 
1042  bool IsByCopyCapture = false;
1043  bool IsConstCapture = false;
1044  CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045  while (Closure &&
1046  IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047  if (IsByCopyCapture) {
1049  if (IsConstCapture)
1050  ClassType.addConst();
1051  return ASTCtx.getPointerType(ClassType);
1052  }
1053  Closure = isLambdaCallOperator(Closure->getParent())
1054  ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055  : nullptr;
1056  }
1057  }
1058  return ASTCtx.getPointerType(ClassType);
1059 }
1060 
1062  DeclContext *DC = getFunctionLevelDeclContext();
1063  QualType ThisTy = CXXThisTypeOverride;
1064 
1065  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066  if (method && method->isInstance())
1067  ThisTy = method->getThisType();
1068  }
1069 
1070  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1071  inTemplateInstantiation()) {
1072 
1073  assert(isa<CXXRecordDecl>(DC) &&
1074  "Trying to get 'this' type from static method?");
1075 
1076  // This is a lambda call operator that is being instantiated as a default
1077  // initializer. DC must point to the enclosing class type, so we can recover
1078  // the 'this' type from it.
1079 
1080  QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081  // There are no cv-qualifiers for 'this' within default initializers,
1082  // per [expr.prim.general]p4.
1083  ThisTy = Context.getPointerType(ClassTy);
1084  }
1085 
1086  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087  // might need to be adjusted if the lambda or any of its enclosing lambda's
1088  // captures '*this' by copy.
1089  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090  return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091  CurContext, Context);
1092  return ThisTy;
1093 }
1094 
1096  Decl *ContextDecl,
1097  Qualifiers CXXThisTypeQuals,
1098  bool Enabled)
1099  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100 {
1101  if (!Enabled || !ContextDecl)
1102  return;
1103 
1104  CXXRecordDecl *Record = nullptr;
1105  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106  Record = Template->getTemplatedDecl();
1107  else
1108  Record = cast<CXXRecordDecl>(ContextDecl);
1109 
1110  QualType T = S.Context.getRecordType(Record);
1111  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1112 
1114 
1115  this->Enabled = true;
1116 }
1117 
1118 
1120  if (Enabled) {
1121  S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1122  }
1123 }
1124 
1126  QualType ThisTy, SourceLocation Loc,
1127  const bool ByCopy) {
1128 
1129  QualType AdjustedThisTy = ThisTy;
1130  // The type of the corresponding data member (not a 'this' pointer if 'by
1131  // copy').
1132  QualType CaptureThisFieldTy = ThisTy;
1133  if (ByCopy) {
1134  // If we are capturing the object referred to by '*this' by copy, ignore any
1135  // cv qualifiers inherited from the type of the member function for the type
1136  // of the closure-type's corresponding data member and any use of 'this'.
1137  CaptureThisFieldTy = ThisTy->getPointeeType();
1138  CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1139  AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1140  }
1141 
1142  FieldDecl *Field = FieldDecl::Create(
1143  Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1144  Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1145  ICIS_NoInit);
1146 
1147  Field->setImplicit(true);
1148  Field->setAccess(AS_private);
1149  RD->addDecl(Field);
1150  Expr *This =
1151  new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1152  if (ByCopy) {
1153  Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1154  UO_Deref,
1155  This).get();
1157  nullptr, CaptureThisFieldTy, Loc);
1158  InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1159  InitializationSequence Init(S, Entity, InitKind, StarThis);
1160  ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1161  if (ER.isInvalid()) return nullptr;
1162  return ER.get();
1163  }
1164  return This;
1165 }
1166 
1167 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1168  bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1169  const bool ByCopy) {
1170  // We don't need to capture this in an unevaluated context.
1171  if (isUnevaluatedContext() && !Explicit)
1172  return true;
1173 
1174  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1175 
1176  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1177  ? *FunctionScopeIndexToStopAt
1178  : FunctionScopes.size() - 1;
1179 
1180  // Check that we can capture the *enclosing object* (referred to by '*this')
1181  // by the capturing-entity/closure (lambda/block/etc) at
1182  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1183 
1184  // Note: The *enclosing object* can only be captured by-value by a
1185  // closure that is a lambda, using the explicit notation:
1186  // [*this] { ... }.
1187  // Every other capture of the *enclosing object* results in its by-reference
1188  // capture.
1189 
1190  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1191  // stack), we can capture the *enclosing object* only if:
1192  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1193  // - or, 'L' has an implicit capture.
1194  // AND
1195  // -- there is no enclosing closure
1196  // -- or, there is some enclosing closure 'E' that has already captured the
1197  // *enclosing object*, and every intervening closure (if any) between 'E'
1198  // and 'L' can implicitly capture the *enclosing object*.
1199  // -- or, every enclosing closure can implicitly capture the
1200  // *enclosing object*
1201 
1202 
1203  unsigned NumCapturingClosures = 0;
1204  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1205  if (CapturingScopeInfo *CSI =
1206  dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1207  if (CSI->CXXThisCaptureIndex != 0) {
1208  // 'this' is already being captured; there isn't anything more to do.
1209  CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1210  break;
1211  }
1212  LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1214  // This context can't implicitly capture 'this'; fail out.
1215  if (BuildAndDiagnose)
1216  Diag(Loc, diag::err_this_capture)
1217  << (Explicit && idx == MaxFunctionScopesIndex);
1218  return true;
1219  }
1220  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1221  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1222  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1223  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1224  (Explicit && idx == MaxFunctionScopesIndex)) {
1225  // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1226  // iteration through can be an explicit capture, all enclosing closures,
1227  // if any, must perform implicit captures.
1228 
1229  // This closure can capture 'this'; continue looking upwards.
1230  NumCapturingClosures++;
1231  continue;
1232  }
1233  // This context can't implicitly capture 'this'; fail out.
1234  if (BuildAndDiagnose)
1235  Diag(Loc, diag::err_this_capture)
1236  << (Explicit && idx == MaxFunctionScopesIndex);
1237  return true;
1238  }
1239  break;
1240  }
1241  if (!BuildAndDiagnose) return false;
1242 
1243  // If we got here, then the closure at MaxFunctionScopesIndex on the
1244  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1245  // (including implicit by-reference captures in any enclosing closures).
1246 
1247  // In the loop below, respect the ByCopy flag only for the closure requesting
1248  // the capture (i.e. first iteration through the loop below). Ignore it for
1249  // all enclosing closure's up to NumCapturingClosures (since they must be
1250  // implicitly capturing the *enclosing object* by reference (see loop
1251  // above)).
1252  assert((!ByCopy ||
1253  dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1254  "Only a lambda can capture the enclosing object (referred to by "
1255  "*this) by copy");
1256  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1257  // contexts.
1258  QualType ThisTy = getCurrentThisType();
1259  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1260  --idx, --NumCapturingClosures) {
1261  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1262  Expr *ThisExpr = nullptr;
1263 
1264  if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1265  // For lambda expressions, build a field and an initializing expression,
1266  // and capture the *enclosing object* by copy only if this is the first
1267  // iteration.
1268  ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1269  ByCopy && idx == MaxFunctionScopesIndex);
1270 
1271  } else if (CapturedRegionScopeInfo *RSI
1272  = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1273  ThisExpr =
1274  captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1275  false/*ByCopy*/);
1276 
1277  bool isNested = NumCapturingClosures > 1;
1278  CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1279  }
1280  return false;
1281 }
1282 
1284  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1285  /// is a non-lvalue expression whose value is the address of the object for
1286  /// which the function is called.
1287 
1288  QualType ThisTy = getCurrentThisType();
1289  if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1290 
1291  CheckCXXThisCapture(Loc);
1292  return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1293 }
1294 
1296  // If we're outside the body of a member function, then we'll have a specified
1297  // type for 'this'.
1299  return false;
1300 
1301  // Determine whether we're looking into a class that's currently being
1302  // defined.
1303  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1304  return Class && Class->isBeingDefined();
1305 }
1306 
1307 /// Parse construction of a specified type.
1308 /// Can be interpreted either as function-style casting ("int(x)")
1309 /// or class type construction ("ClassType(x,y,z)")
1310 /// or creation of a value-initialized type ("int()").
1311 ExprResult
1313  SourceLocation LParenOrBraceLoc,
1314  MultiExprArg exprs,
1315  SourceLocation RParenOrBraceLoc,
1316  bool ListInitialization) {
1317  if (!TypeRep)
1318  return ExprError();
1319 
1320  TypeSourceInfo *TInfo;
1321  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1322  if (!TInfo)
1324 
1325  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1326  RParenOrBraceLoc, ListInitialization);
1327  // Avoid creating a non-type-dependent expression that contains typos.
1328  // Non-type-dependent expressions are liable to be discarded without
1329  // checking for embedded typos.
1330  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1331  !Result.get()->isTypeDependent())
1333  return Result;
1334 }
1335 
1336 ExprResult
1338  SourceLocation LParenOrBraceLoc,
1339  MultiExprArg Exprs,
1340  SourceLocation RParenOrBraceLoc,
1341  bool ListInitialization) {
1342  QualType Ty = TInfo->getType();
1343  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1344 
1346  // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1347  // directly. We work around this by dropping the locations of the braces.
1348  SourceRange Locs = ListInitialization
1349  ? SourceRange()
1350  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1351  return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1352  Exprs, Locs.getEnd());
1353  }
1354 
1355  assert((!ListInitialization ||
1356  (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1357  "List initialization must have initializer list as expression.");
1358  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1359 
1362  Exprs.size()
1363  ? ListInitialization
1365  TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1366  : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1367  RParenOrBraceLoc)
1368  : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1369  RParenOrBraceLoc);
1370 
1371  // C++1z [expr.type.conv]p1:
1372  // If the type is a placeholder for a deduced class type, [...perform class
1373  // template argument deduction...]
1374  DeducedType *Deduced = Ty->getContainedDeducedType();
1375  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1377  Kind, Exprs);
1378  if (Ty.isNull())
1379  return ExprError();
1380  Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1381  }
1382 
1383  // C++ [expr.type.conv]p1:
1384  // If the expression list is a parenthesized single expression, the type
1385  // conversion expression is equivalent (in definedness, and if defined in
1386  // meaning) to the corresponding cast expression.
1387  if (Exprs.size() == 1 && !ListInitialization &&
1388  !isa<InitListExpr>(Exprs[0])) {
1389  Expr *Arg = Exprs[0];
1390  return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1391  RParenOrBraceLoc);
1392  }
1393 
1394  // For an expression of the form T(), T shall not be an array type.
1395  QualType ElemTy = Ty;
1396  if (Ty->isArrayType()) {
1397  if (!ListInitialization)
1398  return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1399  << FullRange);
1400  ElemTy = Context.getBaseElementType(Ty);
1401  }
1402 
1403  // There doesn't seem to be an explicit rule against this but sanity demands
1404  // we only construct objects with object types.
1405  if (Ty->isFunctionType())
1406  return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1407  << Ty << FullRange);
1408 
1409  // C++17 [expr.type.conv]p2:
1410  // If the type is cv void and the initializer is (), the expression is a
1411  // prvalue of the specified type that performs no initialization.
1412  if (!Ty->isVoidType() &&
1413  RequireCompleteType(TyBeginLoc, ElemTy,
1414  diag::err_invalid_incomplete_type_use, FullRange))
1415  return ExprError();
1416 
1417  // Otherwise, the expression is a prvalue of the specified type whose
1418  // result object is direct-initialized (11.6) with the initializer.
1419  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1420  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1421 
1422  if (Result.isInvalid())
1423  return Result;
1424 
1425  Expr *Inner = Result.get();
1426  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1427  Inner = BTE->getSubExpr();
1428  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1429  !isa<CXXScalarValueInitExpr>(Inner)) {
1430  // If we created a CXXTemporaryObjectExpr, that node also represents the
1431  // functional cast. Otherwise, create an explicit cast to represent
1432  // the syntactic form of a functional-style cast that was used here.
1433  //
1434  // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1435  // would give a more consistent AST representation than using a
1436  // CXXTemporaryObjectExpr. It's also weird that the functional cast
1437  // is sometimes handled by initialization and sometimes not.
1438  QualType ResultType = Result.get()->getType();
1439  SourceRange Locs = ListInitialization
1440  ? SourceRange()
1441  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1443  Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1444  Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1445  }
1446 
1447  return Result;
1448 }
1449 
1451  // [CUDA] Ignore this function, if we can't call it.
1452  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1453  if (getLangOpts().CUDA &&
1454  IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1455  return false;
1456 
1458  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1459 
1460  if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1461  return Result;
1462 
1463  // In case of CUDA, return true if none of the 1-argument deallocator
1464  // functions are actually callable.
1465  return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1466  assert(FD->getNumParams() == 1 &&
1467  "Only single-operand functions should be in PreventedBy");
1468  return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1469  });
1470 }
1471 
1472 /// Determine whether the given function is a non-placement
1473 /// deallocation function.
1475  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1476  return S.isUsualDeallocationFunction(Method);
1477 
1478  if (FD->getOverloadedOperator() != OO_Delete &&
1479  FD->getOverloadedOperator() != OO_Array_Delete)
1480  return false;
1481 
1482  unsigned UsualParams = 1;
1483 
1484  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1486  FD->getParamDecl(UsualParams)->getType(),
1487  S.Context.getSizeType()))
1488  ++UsualParams;
1489 
1490  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1492  FD->getParamDecl(UsualParams)->getType(),
1494  ++UsualParams;
1495 
1496  return UsualParams == FD->getNumParams();
1497 }
1498 
1499 namespace {
1500  struct UsualDeallocFnInfo {
1501  UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1502  UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1503  : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1504  Destroying(false), HasSizeT(false), HasAlignValT(false),
1505  CUDAPref(Sema::CFP_Native) {
1506  // A function template declaration is never a usual deallocation function.
1507  if (!FD)
1508  return;
1509  unsigned NumBaseParams = 1;
1510  if (FD->isDestroyingOperatorDelete()) {
1511  Destroying = true;
1512  ++NumBaseParams;
1513  }
1514 
1515  if (NumBaseParams < FD->getNumParams() &&
1517  FD->getParamDecl(NumBaseParams)->getType(),
1518  S.Context.getSizeType())) {
1519  ++NumBaseParams;
1520  HasSizeT = true;
1521  }
1522 
1523  if (NumBaseParams < FD->getNumParams() &&
1524  FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1525  ++NumBaseParams;
1526  HasAlignValT = true;
1527  }
1528 
1529  // In CUDA, determine how much we'd like / dislike to call this.
1530  if (S.getLangOpts().CUDA)
1531  if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1532  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1533  }
1534 
1535  explicit operator bool() const { return FD; }
1536 
1537  bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1538  bool WantAlign) const {
1539  // C++ P0722:
1540  // A destroying operator delete is preferred over a non-destroying
1541  // operator delete.
1542  if (Destroying != Other.Destroying)
1543  return Destroying;
1544 
1545  // C++17 [expr.delete]p10:
1546  // If the type has new-extended alignment, a function with a parameter
1547  // of type std::align_val_t is preferred; otherwise a function without
1548  // such a parameter is preferred
1549  if (HasAlignValT != Other.HasAlignValT)
1550  return HasAlignValT == WantAlign;
1551 
1552  if (HasSizeT != Other.HasSizeT)
1553  return HasSizeT == WantSize;
1554 
1555  // Use CUDA call preference as a tiebreaker.
1556  return CUDAPref > Other.CUDAPref;
1557  }
1558 
1559  DeclAccessPair Found;
1560  FunctionDecl *FD;
1561  bool Destroying, HasSizeT, HasAlignValT;
1563  };
1564 }
1565 
1566 /// Determine whether a type has new-extended alignment. This may be called when
1567 /// the type is incomplete (for a delete-expression with an incomplete pointee
1568 /// type), in which case it will conservatively return false if the alignment is
1569 /// not known.
1570 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1571  return S.getLangOpts().AlignedAllocation &&
1572  S.getASTContext().getTypeAlignIfKnown(AllocType) >
1574 }
1575 
1576 /// Select the correct "usual" deallocation function to use from a selection of
1577 /// deallocation functions (either global or class-scope).
1578 static UsualDeallocFnInfo resolveDeallocationOverload(
1579  Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1580  llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1581  UsualDeallocFnInfo Best;
1582 
1583  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1584  UsualDeallocFnInfo Info(S, I.getPair());
1585  if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1586  Info.CUDAPref == Sema::CFP_Never)
1587  continue;
1588 
1589  if (!Best) {
1590  Best = Info;
1591  if (BestFns)
1592  BestFns->push_back(Info);
1593  continue;
1594  }
1595 
1596  if (Best.isBetterThan(Info, WantSize, WantAlign))
1597  continue;
1598 
1599  // If more than one preferred function is found, all non-preferred
1600  // functions are eliminated from further consideration.
1601  if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1602  BestFns->clear();
1603 
1604  Best = Info;
1605  if (BestFns)
1606  BestFns->push_back(Info);
1607  }
1608 
1609  return Best;
1610 }
1611 
1612 /// Determine whether a given type is a class for which 'delete[]' would call
1613 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1614 /// we need to store the array size (even if the type is
1615 /// trivially-destructible).
1617  QualType allocType) {
1618  const RecordType *record =
1619  allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1620  if (!record) return false;
1621 
1622  // Try to find an operator delete[] in class scope.
1623 
1624  DeclarationName deleteName =
1625  S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1626  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1627  S.LookupQualifiedName(ops, record->getDecl());
1628 
1629  // We're just doing this for information.
1630  ops.suppressDiagnostics();
1631 
1632  // Very likely: there's no operator delete[].
1633  if (ops.empty()) return false;
1634 
1635  // If it's ambiguous, it should be illegal to call operator delete[]
1636  // on this thing, so it doesn't matter if we allocate extra space or not.
1637  if (ops.isAmbiguous()) return false;
1638 
1639  // C++17 [expr.delete]p10:
1640  // If the deallocation functions have class scope, the one without a
1641  // parameter of type std::size_t is selected.
1642  auto Best = resolveDeallocationOverload(
1643  S, ops, /*WantSize*/false,
1644  /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1645  return Best && Best.HasSizeT;
1646 }
1647 
1648 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1649 ///
1650 /// E.g.:
1651 /// @code new (memory) int[size][4] @endcode
1652 /// or
1653 /// @code ::new Foo(23, "hello") @endcode
1654 ///
1655 /// \param StartLoc The first location of the expression.
1656 /// \param UseGlobal True if 'new' was prefixed with '::'.
1657 /// \param PlacementLParen Opening paren of the placement arguments.
1658 /// \param PlacementArgs Placement new arguments.
1659 /// \param PlacementRParen Closing paren of the placement arguments.
1660 /// \param TypeIdParens If the type is in parens, the source range.
1661 /// \param D The type to be allocated, as well as array dimensions.
1662 /// \param Initializer The initializing expression or initializer-list, or null
1663 /// if there is none.
1664 ExprResult
1665 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1666  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1667  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1668  Declarator &D, Expr *Initializer) {
1669  Expr *ArraySize = nullptr;
1670  // If the specified type is an array, unwrap it and save the expression.
1671  if (D.getNumTypeObjects() > 0 &&
1673  DeclaratorChunk &Chunk = D.getTypeObject(0);
1674  if (D.getDeclSpec().hasAutoTypeSpec())
1675  return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1676  << D.getSourceRange());
1677  if (Chunk.Arr.hasStatic)
1678  return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1679  << D.getSourceRange());
1680  if (!Chunk.Arr.NumElts)
1681  return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1682  << D.getSourceRange());
1683 
1684  ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1685  D.DropFirstTypeObject();
1686  }
1687 
1688  // Every dimension shall be of constant size.
1689  if (ArraySize) {
1690  for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1692  break;
1693 
1695  if (Expr *NumElts = (Expr *)Array.NumElts) {
1696  if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1697  if (getLangOpts().CPlusPlus14) {
1698  // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1699  // shall be a converted constant expression (5.19) of type std::size_t
1700  // and shall evaluate to a strictly positive value.
1701  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1702  assert(IntWidth && "Builtin type of size 0?");
1703  llvm::APSInt Value(IntWidth);
1704  Array.NumElts
1706  CCEK_NewExpr)
1707  .get();
1708  } else {
1709  Array.NumElts
1710  = VerifyIntegerConstantExpression(NumElts, nullptr,
1711  diag::err_new_array_nonconst)
1712  .get();
1713  }
1714  if (!Array.NumElts)
1715  return ExprError();
1716  }
1717  }
1718  }
1719  }
1720 
1721  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1722  QualType AllocType = TInfo->getType();
1723  if (D.isInvalidType())
1724  return ExprError();
1725 
1726  SourceRange DirectInitRange;
1727  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1728  DirectInitRange = List->getSourceRange();
1729 
1730  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1731  PlacementLParen, PlacementArgs, PlacementRParen,
1732  TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1733  Initializer);
1734 }
1735 
1737  Expr *Init) {
1738  if (!Init)
1739  return true;
1740  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1741  return PLE->getNumExprs() == 0;
1742  if (isa<ImplicitValueInitExpr>(Init))
1743  return true;
1744  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1745  return !CCE->isListInitialization() &&
1746  CCE->getConstructor()->isDefaultConstructor();
1747  else if (Style == CXXNewExpr::ListInit) {
1748  assert(isa<InitListExpr>(Init) &&
1749  "Shouldn't create list CXXConstructExprs for arrays.");
1750  return true;
1751  }
1752  return false;
1753 }
1754 
1755 bool
1757  if (!getLangOpts().AlignedAllocationUnavailable)
1758  return false;
1759  if (FD.isDefined())
1760  return false;
1761  bool IsAligned = false;
1762  if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1763  return true;
1764  return false;
1765 }
1766 
1767 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1768 // implemented in the standard library is selected.
1770  SourceLocation Loc) {
1772  const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1773  StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1774  getASTContext().getTargetInfo().getPlatformName());
1775 
1777  bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1778  Diag(Loc, diag::err_aligned_allocation_unavailable)
1779  << IsDelete << FD.getType().getAsString() << OSName
1780  << alignedAllocMinVersion(T.getOS()).getAsString();
1781  Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1782  }
1783 }
1784 
1785 ExprResult
1786 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1787  SourceLocation PlacementLParen,
1788  MultiExprArg PlacementArgs,
1789  SourceLocation PlacementRParen,
1790  SourceRange TypeIdParens,
1791  QualType AllocType,
1792  TypeSourceInfo *AllocTypeInfo,
1793  Expr *ArraySize,
1794  SourceRange DirectInitRange,
1795  Expr *Initializer) {
1796  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1797  SourceLocation StartLoc = Range.getBegin();
1798 
1800  if (DirectInitRange.isValid()) {
1801  assert(Initializer && "Have parens but no initializer.");
1802  initStyle = CXXNewExpr::CallInit;
1803  } else if (Initializer && isa<InitListExpr>(Initializer))
1804  initStyle = CXXNewExpr::ListInit;
1805  else {
1806  assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1807  isa<CXXConstructExpr>(Initializer)) &&
1808  "Initializer expression that cannot have been implicitly created.");
1809  initStyle = CXXNewExpr::NoInit;
1810  }
1811 
1812  Expr **Inits = &Initializer;
1813  unsigned NumInits = Initializer ? 1 : 0;
1814  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1815  assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1816  Inits = List->getExprs();
1817  NumInits = List->getNumExprs();
1818  }
1819 
1820  // C++11 [expr.new]p15:
1821  // A new-expression that creates an object of type T initializes that
1822  // object as follows:
1824  // - If the new-initializer is omitted, the object is default-
1825  // initialized (8.5); if no initialization is performed,
1826  // the object has indeterminate value
1827  = initStyle == CXXNewExpr::NoInit
1829  // - Otherwise, the new-initializer is interpreted according to
1830  // the
1831  // initialization rules of 8.5 for direct-initialization.
1832  : initStyle == CXXNewExpr::ListInit
1834  TypeRange.getBegin(), Initializer->getBeginLoc(),
1835  Initializer->getEndLoc())
1837  DirectInitRange.getBegin(),
1838  DirectInitRange.getEnd());
1839 
1840  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1841  auto *Deduced = AllocType->getContainedDeducedType();
1842  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1843  if (ArraySize)
1844  return ExprError(Diag(ArraySize->getExprLoc(),
1845  diag::err_deduced_class_template_compound_type)
1846  << /*array*/ 2 << ArraySize->getSourceRange());
1847 
1848  InitializedEntity Entity
1849  = InitializedEntity::InitializeNew(StartLoc, AllocType);
1851  AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1852  if (AllocType.isNull())
1853  return ExprError();
1854  } else if (Deduced) {
1855  bool Braced = (initStyle == CXXNewExpr::ListInit);
1856  if (NumInits == 1) {
1857  if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1858  Inits = p->getInits();
1859  NumInits = p->getNumInits();
1860  Braced = true;
1861  }
1862  }
1863 
1864  if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1865  return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1866  << AllocType << TypeRange);
1867  if (NumInits > 1) {
1868  Expr *FirstBad = Inits[1];
1869  return ExprError(Diag(FirstBad->getBeginLoc(),
1870  diag::err_auto_new_ctor_multiple_expressions)
1871  << AllocType << TypeRange);
1872  }
1873  if (Braced && !getLangOpts().CPlusPlus17)
1874  Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1875  << AllocType << TypeRange;
1877  if (DeduceAutoType(AllocTypeInfo, Inits[0], DeducedType) == DAR_Failed)
1878  return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1879  << AllocType << Inits[0]->getType()
1880  << TypeRange << Inits[0]->getSourceRange());
1881  if (DeducedType.isNull())
1882  return ExprError();
1883  AllocType = DeducedType;
1884  }
1885 
1886  // Per C++0x [expr.new]p5, the type being constructed may be a
1887  // typedef of an array type.
1888  if (!ArraySize) {
1889  if (const ConstantArrayType *Array
1890  = Context.getAsConstantArrayType(AllocType)) {
1891  ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1892  Context.getSizeType(),
1893  TypeRange.getEnd());
1894  AllocType = Array->getElementType();
1895  }
1896  }
1897 
1898  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1899  return ExprError();
1900 
1901  // In ARC, infer 'retaining' for the allocated
1902  if (getLangOpts().ObjCAutoRefCount &&
1903  AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1904  AllocType->isObjCLifetimeType()) {
1905  AllocType = Context.getLifetimeQualifiedType(AllocType,
1906  AllocType->getObjCARCImplicitLifetime());
1907  }
1908 
1909  QualType ResultType = Context.getPointerType(AllocType);
1910 
1911  if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1912  ExprResult result = CheckPlaceholderExpr(ArraySize);
1913  if (result.isInvalid()) return ExprError();
1914  ArraySize = result.get();
1915  }
1916  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1917  // integral or enumeration type with a non-negative value."
1918  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1919  // enumeration type, or a class type for which a single non-explicit
1920  // conversion function to integral or unscoped enumeration type exists.
1921  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1922  // std::size_t.
1923  llvm::Optional<uint64_t> KnownArraySize;
1924  if (ArraySize && !ArraySize->isTypeDependent()) {
1925  ExprResult ConvertedSize;
1926  if (getLangOpts().CPlusPlus14) {
1927  assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1928 
1929  ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1930  AA_Converting);
1931 
1932  if (!ConvertedSize.isInvalid() &&
1933  ArraySize->getType()->getAs<RecordType>())
1934  // Diagnose the compatibility of this conversion.
1935  Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1936  << ArraySize->getType() << 0 << "'size_t'";
1937  } else {
1938  class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1939  protected:
1940  Expr *ArraySize;
1941 
1942  public:
1943  SizeConvertDiagnoser(Expr *ArraySize)
1944  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1945  ArraySize(ArraySize) {}
1946 
1947  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1948  QualType T) override {
1949  return S.Diag(Loc, diag::err_array_size_not_integral)
1950  << S.getLangOpts().CPlusPlus11 << T;
1951  }
1952 
1953  SemaDiagnosticBuilder diagnoseIncomplete(
1954  Sema &S, SourceLocation Loc, QualType T) override {
1955  return S.Diag(Loc, diag::err_array_size_incomplete_type)
1956  << T << ArraySize->getSourceRange();
1957  }
1958 
1959  SemaDiagnosticBuilder diagnoseExplicitConv(
1960  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1961  return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1962  }
1963 
1964  SemaDiagnosticBuilder noteExplicitConv(
1965  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1966  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967  << ConvTy->isEnumeralType() << ConvTy;
1968  }
1969 
1970  SemaDiagnosticBuilder diagnoseAmbiguous(
1971  Sema &S, SourceLocation Loc, QualType T) override {
1972  return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1973  }
1974 
1975  SemaDiagnosticBuilder noteAmbiguous(
1976  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1977  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1978  << ConvTy->isEnumeralType() << ConvTy;
1979  }
1980 
1981  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1982  QualType T,
1983  QualType ConvTy) override {
1984  return S.Diag(Loc,
1985  S.getLangOpts().CPlusPlus11
1986  ? diag::warn_cxx98_compat_array_size_conversion
1987  : diag::ext_array_size_conversion)
1988  << T << ConvTy->isEnumeralType() << ConvTy;
1989  }
1990  } SizeDiagnoser(ArraySize);
1991 
1992  ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1993  SizeDiagnoser);
1994  }
1995  if (ConvertedSize.isInvalid())
1996  return ExprError();
1997 
1998  ArraySize = ConvertedSize.get();
1999  QualType SizeType = ArraySize->getType();
2000 
2001  if (!SizeType->isIntegralOrUnscopedEnumerationType())
2002  return ExprError();
2003 
2004  // C++98 [expr.new]p7:
2005  // The expression in a direct-new-declarator shall have integral type
2006  // with a non-negative value.
2007  //
2008  // Let's see if this is a constant < 0. If so, we reject it out of hand,
2009  // per CWG1464. Otherwise, if it's not a constant, we must have an
2010  // unparenthesized array type.
2011  if (!ArraySize->isValueDependent()) {
2012  llvm::APSInt Value;
2013  // We've already performed any required implicit conversion to integer or
2014  // unscoped enumeration type.
2015  // FIXME: Per CWG1464, we are required to check the value prior to
2016  // converting to size_t. This will never find a negative array size in
2017  // C++14 onwards, because Value is always unsigned here!
2018  if (ArraySize->isIntegerConstantExpr(Value, Context)) {
2019  if (Value.isSigned() && Value.isNegative()) {
2020  return ExprError(Diag(ArraySize->getBeginLoc(),
2021  diag::err_typecheck_negative_array_size)
2022  << ArraySize->getSourceRange());
2023  }
2024 
2025  if (!AllocType->isDependentType()) {
2026  unsigned ActiveSizeBits =
2028  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2029  return ExprError(
2030  Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2031  << Value.toString(10) << ArraySize->getSourceRange());
2032  }
2033 
2034  KnownArraySize = Value.getZExtValue();
2035  } else if (TypeIdParens.isValid()) {
2036  // Can't have dynamic array size when the type-id is in parentheses.
2037  Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2038  << ArraySize->getSourceRange()
2039  << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2040  << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2041 
2042  TypeIdParens = SourceRange();
2043  }
2044  }
2045 
2046  // Note that we do *not* convert the argument in any way. It can
2047  // be signed, larger than size_t, whatever.
2048  }
2049 
2050  FunctionDecl *OperatorNew = nullptr;
2051  FunctionDecl *OperatorDelete = nullptr;
2052  unsigned Alignment =
2053  AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2054  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2055  bool PassAlignment = getLangOpts().AlignedAllocation &&
2056  Alignment > NewAlignment;
2057 
2059  if (!AllocType->isDependentType() &&
2060  !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2061  FindAllocationFunctions(StartLoc,
2062  SourceRange(PlacementLParen, PlacementRParen),
2063  Scope, Scope, AllocType, ArraySize, PassAlignment,
2064  PlacementArgs, OperatorNew, OperatorDelete))
2065  return ExprError();
2066 
2067  // If this is an array allocation, compute whether the usual array
2068  // deallocation function for the type has a size_t parameter.
2069  bool UsualArrayDeleteWantsSize = false;
2070  if (ArraySize && !AllocType->isDependentType())
2071  UsualArrayDeleteWantsSize =
2072  doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2073 
2074  SmallVector<Expr *, 8> AllPlaceArgs;
2075  if (OperatorNew) {
2076  const FunctionProtoType *Proto =
2077  OperatorNew->getType()->getAs<FunctionProtoType>();
2078  VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2080 
2081  // We've already converted the placement args, just fill in any default
2082  // arguments. Skip the first parameter because we don't have a corresponding
2083  // argument. Skip the second parameter too if we're passing in the
2084  // alignment; we've already filled it in.
2085  if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2086  PassAlignment ? 2 : 1, PlacementArgs,
2087  AllPlaceArgs, CallType))
2088  return ExprError();
2089 
2090  if (!AllPlaceArgs.empty())
2091  PlacementArgs = AllPlaceArgs;
2092 
2093  // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2094  DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2095 
2096  // FIXME: Missing call to CheckFunctionCall or equivalent
2097 
2098  // Warn if the type is over-aligned and is being allocated by (unaligned)
2099  // global operator new.
2100  if (PlacementArgs.empty() && !PassAlignment &&
2101  (OperatorNew->isImplicit() ||
2102  (OperatorNew->getBeginLoc().isValid() &&
2103  getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2104  if (Alignment > NewAlignment)
2105  Diag(StartLoc, diag::warn_overaligned_type)
2106  << AllocType
2107  << unsigned(Alignment / Context.getCharWidth())
2108  << unsigned(NewAlignment / Context.getCharWidth());
2109  }
2110  }
2111 
2112  // Array 'new' can't have any initializers except empty parentheses.
2113  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2114  // dialect distinction.
2115  if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2116  SourceRange InitRange(Inits[0]->getBeginLoc(),
2117  Inits[NumInits - 1]->getEndLoc());
2118  Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2119  return ExprError();
2120  }
2121 
2122  // If we can perform the initialization, and we've not already done so,
2123  // do it now.
2124  if (!AllocType->isDependentType() &&
2126  llvm::makeArrayRef(Inits, NumInits))) {
2127  // The type we initialize is the complete type, including the array bound.
2128  QualType InitType;
2129  if (KnownArraySize)
2130  InitType = Context.getConstantArrayType(
2131  AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2132  *KnownArraySize),
2133  ArrayType::Normal, 0);
2134  else if (ArraySize)
2135  InitType =
2137  else
2138  InitType = AllocType;
2139 
2140  InitializedEntity Entity
2141  = InitializedEntity::InitializeNew(StartLoc, InitType);
2142  InitializationSequence InitSeq(*this, Entity, Kind,
2143  MultiExprArg(Inits, NumInits));
2144  ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2145  MultiExprArg(Inits, NumInits));
2146  if (FullInit.isInvalid())
2147  return ExprError();
2148 
2149  // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2150  // we don't want the initialized object to be destructed.
2151  // FIXME: We should not create these in the first place.
2152  if (CXXBindTemporaryExpr *Binder =
2153  dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2154  FullInit = Binder->getSubExpr();
2155 
2156  Initializer = FullInit.get();
2157  }
2158 
2159  // Mark the new and delete operators as referenced.
2160  if (OperatorNew) {
2161  if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2162  return ExprError();
2163  MarkFunctionReferenced(StartLoc, OperatorNew);
2164  }
2165  if (OperatorDelete) {
2166  if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2167  return ExprError();
2168  MarkFunctionReferenced(StartLoc, OperatorDelete);
2169  }
2170 
2171  // C++0x [expr.new]p17:
2172  // If the new expression creates an array of objects of class type,
2173  // access and ambiguity control are done for the destructor.
2174  QualType BaseAllocType = Context.getBaseElementType(AllocType);
2175  if (ArraySize && !BaseAllocType->isDependentType()) {
2176  if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2177  if (CXXDestructorDecl *dtor = LookupDestructor(
2178  cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2179  MarkFunctionReferenced(StartLoc, dtor);
2180  CheckDestructorAccess(StartLoc, dtor,
2181  PDiag(diag::err_access_dtor)
2182  << BaseAllocType);
2183  if (DiagnoseUseOfDecl(dtor, StartLoc))
2184  return ExprError();
2185  }
2186  }
2187  }
2188 
2189  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2190  PassAlignment, UsualArrayDeleteWantsSize,
2191  PlacementArgs, TypeIdParens, ArraySize, initStyle,
2192  Initializer, ResultType, AllocTypeInfo, Range,
2193  DirectInitRange);
2194 }
2195 
2196 /// Checks that a type is suitable as the allocated type
2197 /// in a new-expression.
2199  SourceRange R) {
2200  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2201  // abstract class type or array thereof.
2202  if (AllocType->isFunctionType())
2203  return Diag(Loc, diag::err_bad_new_type)
2204  << AllocType << 0 << R;
2205  else if (AllocType->isReferenceType())
2206  return Diag(Loc, diag::err_bad_new_type)
2207  << AllocType << 1 << R;
2208  else if (!AllocType->isDependentType() &&
2209  RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2210  return true;
2211  else if (RequireNonAbstractType(Loc, AllocType,
2212  diag::err_allocation_of_abstract_type))
2213  return true;
2214  else if (AllocType->isVariablyModifiedType())
2215  return Diag(Loc, diag::err_variably_modified_new_type)
2216  << AllocType;
2217  else if (AllocType.getAddressSpace() != LangAS::Default &&
2218  !getLangOpts().OpenCLCPlusPlus)
2219  return Diag(Loc, diag::err_address_space_qualified_new)
2220  << AllocType.getUnqualifiedType()
2222  else if (getLangOpts().ObjCAutoRefCount) {
2223  if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2224  QualType BaseAllocType = Context.getBaseElementType(AT);
2225  if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2226  BaseAllocType->isObjCLifetimeType())
2227  return Diag(Loc, diag::err_arc_new_array_without_ownership)
2228  << BaseAllocType;
2229  }
2230  }
2231 
2232  return false;
2233 }
2234 
2237  bool &PassAlignment, FunctionDecl *&Operator,
2238  OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2239  OverloadCandidateSet Candidates(R.getNameLoc(),
2241  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2242  Alloc != AllocEnd; ++Alloc) {
2243  // Even member operator new/delete are implicitly treated as
2244  // static, so don't use AddMemberCandidate.
2245  NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2246 
2247  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2248  S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2249  /*ExplicitTemplateArgs=*/nullptr, Args,
2250  Candidates,
2251  /*SuppressUserConversions=*/false);
2252  continue;
2253  }
2254 
2255  FunctionDecl *Fn = cast<FunctionDecl>(D);
2256  S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2257  /*SuppressUserConversions=*/false);
2258  }
2259 
2260  // Do the resolution.
2262  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2263  case OR_Success: {
2264  // Got one!
2265  FunctionDecl *FnDecl = Best->Function;
2266  if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2267  Best->FoundDecl) == Sema::AR_inaccessible)
2268  return true;
2269 
2270  Operator = FnDecl;
2271  return false;
2272  }
2273 
2274  case OR_No_Viable_Function:
2275  // C++17 [expr.new]p13:
2276  // If no matching function is found and the allocated object type has
2277  // new-extended alignment, the alignment argument is removed from the
2278  // argument list, and overload resolution is performed again.
2279  if (PassAlignment) {
2280  PassAlignment = false;
2281  AlignArg = Args[1];
2282  Args.erase(Args.begin() + 1);
2283  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2284  Operator, &Candidates, AlignArg,
2285  Diagnose);
2286  }
2287 
2288  // MSVC will fall back on trying to find a matching global operator new
2289  // if operator new[] cannot be found. Also, MSVC will leak by not
2290  // generating a call to operator delete or operator delete[], but we
2291  // will not replicate that bug.
2292  // FIXME: Find out how this interacts with the std::align_val_t fallback
2293  // once MSVC implements it.
2294  if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2295  S.Context.getLangOpts().MSVCCompat) {
2296  R.clear();
2299  // FIXME: This will give bad diagnostics pointing at the wrong functions.
2300  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2301  Operator, /*Candidates=*/nullptr,
2302  /*AlignArg=*/nullptr, Diagnose);
2303  }
2304 
2305  if (Diagnose) {
2306  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2307  << R.getLookupName() << Range;
2308 
2309  // If we have aligned candidates, only note the align_val_t candidates
2310  // from AlignedCandidates and the non-align_val_t candidates from
2311  // Candidates.
2312  if (AlignedCandidates) {
2313  auto IsAligned = [](OverloadCandidate &C) {
2314  return C.Function->getNumParams() > 1 &&
2315  C.Function->getParamDecl(1)->getType()->isAlignValT();
2316  };
2317  auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2318 
2319  // This was an overaligned allocation, so list the aligned candidates
2320  // first.
2321  Args.insert(Args.begin() + 1, AlignArg);
2322  AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2323  R.getNameLoc(), IsAligned);
2324  Args.erase(Args.begin() + 1);
2325  Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2326  IsUnaligned);
2327  } else {
2328  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2329  }
2330  }
2331  return true;
2332 
2333  case OR_Ambiguous:
2334  if (Diagnose) {
2335  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2336  << R.getLookupName() << Range;
2337  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2338  }
2339  return true;
2340 
2341  case OR_Deleted: {
2342  if (Diagnose) {
2343  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2344  << Best->Function->isDeleted() << R.getLookupName()
2345  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2346  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2347  }
2348  return true;
2349  }
2350  }
2351  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2352 }
2353 
2355  AllocationFunctionScope NewScope,
2356  AllocationFunctionScope DeleteScope,
2357  QualType AllocType, bool IsArray,
2358  bool &PassAlignment, MultiExprArg PlaceArgs,
2359  FunctionDecl *&OperatorNew,
2360  FunctionDecl *&OperatorDelete,
2361  bool Diagnose) {
2362  // --- Choosing an allocation function ---
2363  // C++ 5.3.4p8 - 14 & 18
2364  // 1) If looking in AFS_Global scope for allocation functions, only look in
2365  // the global scope. Else, if AFS_Class, only look in the scope of the
2366  // allocated class. If AFS_Both, look in both.
2367  // 2) If an array size is given, look for operator new[], else look for
2368  // operator new.
2369  // 3) The first argument is always size_t. Append the arguments from the
2370  // placement form.
2371 
2372  SmallVector<Expr*, 8> AllocArgs;
2373  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2374 
2375  // We don't care about the actual value of these arguments.
2376  // FIXME: Should the Sema create the expression and embed it in the syntax
2377  // tree? Or should the consumer just recalculate the value?
2378  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2379  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2381  Context.getSizeType(),
2382  SourceLocation());
2383  AllocArgs.push_back(&Size);
2384 
2385  QualType AlignValT = Context.VoidTy;
2386  if (PassAlignment) {
2388  AlignValT = Context.getTypeDeclType(getStdAlignValT());
2389  }
2390  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2391  if (PassAlignment)
2392  AllocArgs.push_back(&Align);
2393 
2394  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2395 
2396  // C++ [expr.new]p8:
2397  // If the allocated type is a non-array type, the allocation
2398  // function's name is operator new and the deallocation function's
2399  // name is operator delete. If the allocated type is an array
2400  // type, the allocation function's name is operator new[] and the
2401  // deallocation function's name is operator delete[].
2403  IsArray ? OO_Array_New : OO_New);
2404 
2405  QualType AllocElemType = Context.getBaseElementType(AllocType);
2406 
2407  // Find the allocation function.
2408  {
2409  LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2410 
2411  // C++1z [expr.new]p9:
2412  // If the new-expression begins with a unary :: operator, the allocation
2413  // function's name is looked up in the global scope. Otherwise, if the
2414  // allocated type is a class type T or array thereof, the allocation
2415  // function's name is looked up in the scope of T.
2416  if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2417  LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2418 
2419  // We can see ambiguity here if the allocation function is found in
2420  // multiple base classes.
2421  if (R.isAmbiguous())
2422  return true;
2423 
2424  // If this lookup fails to find the name, or if the allocated type is not
2425  // a class type, the allocation function's name is looked up in the
2426  // global scope.
2427  if (R.empty()) {
2428  if (NewScope == AFS_Class)
2429  return true;
2430 
2432  }
2433 
2434  if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2435  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2436  return true;
2437  }
2438 
2439  assert(!R.empty() && "implicitly declared allocation functions not found");
2440  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2441 
2442  // We do our own custom access checks below.
2443  R.suppressDiagnostics();
2444 
2445  if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2446  OperatorNew, /*Candidates=*/nullptr,
2447  /*AlignArg=*/nullptr, Diagnose))
2448  return true;
2449  }
2450 
2451  // We don't need an operator delete if we're running under -fno-exceptions.
2452  if (!getLangOpts().Exceptions) {
2453  OperatorDelete = nullptr;
2454  return false;
2455  }
2456 
2457  // Note, the name of OperatorNew might have been changed from array to
2458  // non-array by resolveAllocationOverload.
2460  OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2461  ? OO_Array_Delete
2462  : OO_Delete);
2463 
2464  // C++ [expr.new]p19:
2465  //
2466  // If the new-expression begins with a unary :: operator, the
2467  // deallocation function's name is looked up in the global
2468  // scope. Otherwise, if the allocated type is a class type T or an
2469  // array thereof, the deallocation function's name is looked up in
2470  // the scope of T. If this lookup fails to find the name, or if
2471  // the allocated type is not a class type or array thereof, the
2472  // deallocation function's name is looked up in the global scope.
2473  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2474  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2475  CXXRecordDecl *RD
2476  = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2477  LookupQualifiedName(FoundDelete, RD);
2478  }
2479  if (FoundDelete.isAmbiguous())
2480  return true; // FIXME: clean up expressions?
2481 
2482  bool FoundGlobalDelete = FoundDelete.empty();
2483  if (FoundDelete.empty()) {
2484  if (DeleteScope == AFS_Class)
2485  return true;
2486 
2489  }
2490 
2491  FoundDelete.suppressDiagnostics();
2492 
2494 
2495  // Whether we're looking for a placement operator delete is dictated
2496  // by whether we selected a placement operator new, not by whether
2497  // we had explicit placement arguments. This matters for things like
2498  // struct A { void *operator new(size_t, int = 0); ... };
2499  // A *a = new A()
2500  //
2501  // We don't have any definition for what a "placement allocation function"
2502  // is, but we assume it's any allocation function whose
2503  // parameter-declaration-clause is anything other than (size_t).
2504  //
2505  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2506  // This affects whether an exception from the constructor of an overaligned
2507  // type uses the sized or non-sized form of aligned operator delete.
2508  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2509  OperatorNew->isVariadic();
2510 
2511  if (isPlacementNew) {
2512  // C++ [expr.new]p20:
2513  // A declaration of a placement deallocation function matches the
2514  // declaration of a placement allocation function if it has the
2515  // same number of parameters and, after parameter transformations
2516  // (8.3.5), all parameter types except the first are
2517  // identical. [...]
2518  //
2519  // To perform this comparison, we compute the function type that
2520  // the deallocation function should have, and use that type both
2521  // for template argument deduction and for comparison purposes.
2522  QualType ExpectedFunctionType;
2523  {
2524  const FunctionProtoType *Proto
2525  = OperatorNew->getType()->getAs<FunctionProtoType>();
2526 
2527  SmallVector<QualType, 4> ArgTypes;
2528  ArgTypes.push_back(Context.VoidPtrTy);
2529  for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2530  ArgTypes.push_back(Proto->getParamType(I));
2531 
2533  // FIXME: This is not part of the standard's rule.
2534  EPI.Variadic = Proto->isVariadic();
2535 
2536  ExpectedFunctionType
2537  = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2538  }
2539 
2540  for (LookupResult::iterator D = FoundDelete.begin(),
2541  DEnd = FoundDelete.end();
2542  D != DEnd; ++D) {
2543  FunctionDecl *Fn = nullptr;
2544  if (FunctionTemplateDecl *FnTmpl =
2545  dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2546  // Perform template argument deduction to try to match the
2547  // expected function type.
2548  TemplateDeductionInfo Info(StartLoc);
2549  if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2550  Info))
2551  continue;
2552  } else
2553  Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2554 
2556  ExpectedFunctionType,
2557  /*AdjustExcpetionSpec*/true),
2558  ExpectedFunctionType))
2559  Matches.push_back(std::make_pair(D.getPair(), Fn));
2560  }
2561 
2562  if (getLangOpts().CUDA)
2563  EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2564  } else {
2565  // C++1y [expr.new]p22:
2566  // For a non-placement allocation function, the normal deallocation
2567  // function lookup is used
2568  //
2569  // Per [expr.delete]p10, this lookup prefers a member operator delete
2570  // without a size_t argument, but prefers a non-member operator delete
2571  // with a size_t where possible (which it always is in this case).
2573  UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2574  *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2575  /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2576  &BestDeallocFns);
2577  if (Selected)
2578  Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2579  else {
2580  // If we failed to select an operator, all remaining functions are viable
2581  // but ambiguous.
2582  for (auto Fn : BestDeallocFns)
2583  Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2584  }
2585  }
2586 
2587  // C++ [expr.new]p20:
2588  // [...] If the lookup finds a single matching deallocation
2589  // function, that function will be called; otherwise, no
2590  // deallocation function will be called.
2591  if (Matches.size() == 1) {
2592  OperatorDelete = Matches[0].second;
2593 
2594  // C++1z [expr.new]p23:
2595  // If the lookup finds a usual deallocation function (3.7.4.2)
2596  // with a parameter of type std::size_t and that function, considered
2597  // as a placement deallocation function, would have been
2598  // selected as a match for the allocation function, the program
2599  // is ill-formed.
2600  if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2601  isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2602  UsualDeallocFnInfo Info(*this,
2603  DeclAccessPair::make(OperatorDelete, AS_public));
2604  // Core issue, per mail to core reflector, 2016-10-09:
2605  // If this is a member operator delete, and there is a corresponding
2606  // non-sized member operator delete, this isn't /really/ a sized
2607  // deallocation function, it just happens to have a size_t parameter.
2608  bool IsSizedDelete = Info.HasSizeT;
2609  if (IsSizedDelete && !FoundGlobalDelete) {
2610  auto NonSizedDelete =
2611  resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2612  /*WantAlign*/Info.HasAlignValT);
2613  if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2614  NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2615  IsSizedDelete = false;
2616  }
2617 
2618  if (IsSizedDelete) {
2619  SourceRange R = PlaceArgs.empty()
2620  ? SourceRange()
2621  : SourceRange(PlaceArgs.front()->getBeginLoc(),
2622  PlaceArgs.back()->getEndLoc());
2623  Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2624  if (!OperatorDelete->isImplicit())
2625  Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2626  << DeleteName;
2627  }
2628  }
2629 
2630  CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2631  Matches[0].first);
2632  } else if (!Matches.empty()) {
2633  // We found multiple suitable operators. Per [expr.new]p20, that means we
2634  // call no 'operator delete' function, but we should at least warn the user.
2635  // FIXME: Suppress this warning if the construction cannot throw.
2636  Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2637  << DeleteName << AllocElemType;
2638 
2639  for (auto &Match : Matches)
2640  Diag(Match.second->getLocation(),
2641  diag::note_member_declared_here) << DeleteName;
2642  }
2643 
2644  return false;
2645 }
2646 
2647 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2648 /// delete. These are:
2649 /// @code
2650 /// // C++03:
2651 /// void* operator new(std::size_t) throw(std::bad_alloc);
2652 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2653 /// void operator delete(void *) throw();
2654 /// void operator delete[](void *) throw();
2655 /// // C++11:
2656 /// void* operator new(std::size_t);
2657 /// void* operator new[](std::size_t);
2658 /// void operator delete(void *) noexcept;
2659 /// void operator delete[](void *) noexcept;
2660 /// // C++1y:
2661 /// void* operator new(std::size_t);
2662 /// void* operator new[](std::size_t);
2663 /// void operator delete(void *) noexcept;
2664 /// void operator delete[](void *) noexcept;
2665 /// void operator delete(void *, std::size_t) noexcept;
2666 /// void operator delete[](void *, std::size_t) noexcept;
2667 /// @endcode
2668 /// Note that the placement and nothrow forms of new are *not* implicitly
2669 /// declared. Their use requires including <new>.
2672  return;
2673 
2674  // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2675  // are not supported.
2676  if (getLangOpts().OpenCLCPlusPlus)
2677  return;
2678 
2679  // C++ [basic.std.dynamic]p2:
2680  // [...] The following allocation and deallocation functions (18.4) are
2681  // implicitly declared in global scope in each translation unit of a
2682  // program
2683  //
2684  // C++03:
2685  // void* operator new(std::size_t) throw(std::bad_alloc);
2686  // void* operator new[](std::size_t) throw(std::bad_alloc);
2687  // void operator delete(void*) throw();
2688  // void operator delete[](void*) throw();
2689  // C++11:
2690  // void* operator new(std::size_t);
2691  // void* operator new[](std::size_t);
2692  // void operator delete(void*) noexcept;
2693  // void operator delete[](void*) noexcept;
2694  // C++1y:
2695  // void* operator new(std::size_t);
2696  // void* operator new[](std::size_t);
2697  // void operator delete(void*) noexcept;
2698  // void operator delete[](void*) noexcept;
2699  // void operator delete(void*, std::size_t) noexcept;
2700  // void operator delete[](void*, std::size_t) noexcept;
2701  //
2702  // These implicit declarations introduce only the function names operator
2703  // new, operator new[], operator delete, operator delete[].
2704  //
2705  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2706  // "std" or "bad_alloc" as necessary to form the exception specification.
2707  // However, we do not make these implicit declarations visible to name
2708  // lookup.
2709  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2710  // The "std::bad_alloc" class has not yet been declared, so build it
2711  // implicitly.
2715  &PP.getIdentifierTable().get("bad_alloc"),
2716  nullptr);
2717  getStdBadAlloc()->setImplicit(true);
2718  }
2719  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2720  // The "std::align_val_t" enum class has not yet been declared, so build it
2721  // implicitly.
2722  auto *AlignValT = EnumDecl::Create(
2724  &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2725  AlignValT->setIntegerType(Context.getSizeType());
2726  AlignValT->setPromotionType(Context.getSizeType());
2727  AlignValT->setImplicit(true);
2728  StdAlignValT = AlignValT;
2729  }
2730 
2731  GlobalNewDeleteDeclared = true;
2732 
2734  QualType SizeT = Context.getSizeType();
2735 
2736  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2737  QualType Return, QualType Param) {
2739  Params.push_back(Param);
2740 
2741  // Create up to four variants of the function (sized/aligned).
2742  bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2743  (Kind == OO_Delete || Kind == OO_Array_Delete);
2744  bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2745 
2746  int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2747  int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2748  for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2749  if (Sized)
2750  Params.push_back(SizeT);
2751 
2752  for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2753  if (Aligned)
2754  Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2755 
2757  Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2758 
2759  if (Aligned)
2760  Params.pop_back();
2761  }
2762  }
2763  };
2764 
2765  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2766  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2767  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2768  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2769 }
2770 
2771 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2772 /// allocation function if it doesn't already exist.
2774  QualType Return,
2775  ArrayRef<QualType> Params) {
2777 
2778  // Check if this function is already declared.
2779  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2780  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2781  Alloc != AllocEnd; ++Alloc) {
2782  // Only look at non-template functions, as it is the predefined,
2783  // non-templated allocation function we are trying to declare here.
2784  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2785  if (Func->getNumParams() == Params.size()) {
2786  llvm::SmallVector<QualType, 3> FuncParams;
2787  for (auto *P : Func->parameters())
2788  FuncParams.push_back(
2789  Context.getCanonicalType(P->getType().getUnqualifiedType()));
2790  if (llvm::makeArrayRef(FuncParams) == Params) {
2791  // Make the function visible to name lookup, even if we found it in
2792  // an unimported module. It either is an implicitly-declared global
2793  // allocation function, or is suppressing that function.
2794  Func->setVisibleDespiteOwningModule();
2795  return;
2796  }
2797  }
2798  }
2799  }
2800 
2802 
2803  QualType BadAllocType;
2804  bool HasBadAllocExceptionSpec
2805  = (Name.getCXXOverloadedOperator() == OO_New ||
2806  Name.getCXXOverloadedOperator() == OO_Array_New);
2807  if (HasBadAllocExceptionSpec) {
2808  if (!getLangOpts().CPlusPlus11) {
2809  BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2810  assert(StdBadAlloc && "Must have std::bad_alloc declared");
2812  EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2813  }
2814  } else {
2815  EPI.ExceptionSpec =
2816  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2817  }
2818 
2819  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2820  QualType FnType = Context.getFunctionType(Return, Params, EPI);
2822  Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2823  FnType, /*TInfo=*/nullptr, SC_None, false, true);
2824  Alloc->setImplicit();
2825  // Global allocation functions should always be visible.
2827 
2828  Alloc->addAttr(VisibilityAttr::CreateImplicit(
2829  Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2830  ? VisibilityAttr::Hidden
2832 
2834  for (QualType T : Params) {
2835  ParamDecls.push_back(ParmVarDecl::Create(
2836  Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2837  /*TInfo=*/nullptr, SC_None, nullptr));
2838  ParamDecls.back()->setImplicit();
2839  }
2840  Alloc->setParams(ParamDecls);
2841  if (ExtraAttr)
2842  Alloc->addAttr(ExtraAttr);
2844  IdResolver.tryAddTopLevelDecl(Alloc, Name);
2845  };
2846 
2847  if (!LangOpts.CUDA)
2848  CreateAllocationFunctionDecl(nullptr);
2849  else {
2850  // Host and device get their own declaration so each can be
2851  // defined or re-declared independently.
2852  CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2853  CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2854  }
2855 }
2856 
2858  bool CanProvideSize,
2859  bool Overaligned,
2860  DeclarationName Name) {
2862 
2863  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2865 
2866  // FIXME: It's possible for this to result in ambiguity, through a
2867  // user-declared variadic operator delete or the enable_if attribute. We
2868  // should probably not consider those cases to be usual deallocation
2869  // functions. But for now we just make an arbitrary choice in that case.
2870  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2871  Overaligned);
2872  assert(Result.FD && "operator delete missing from global scope?");
2873  return Result.FD;
2874 }
2875 
2877  CXXRecordDecl *RD) {
2879 
2880  FunctionDecl *OperatorDelete = nullptr;
2881  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2882  return nullptr;
2883  if (OperatorDelete)
2884  return OperatorDelete;
2885 
2886  // If there's no class-specific operator delete, look up the global
2887  // non-array delete.
2889  Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2890  Name);
2891 }
2892 
2894  DeclarationName Name,
2895  FunctionDecl *&Operator, bool Diagnose) {
2896  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2897  // Try to find operator delete/operator delete[] in class scope.
2898  LookupQualifiedName(Found, RD);
2899 
2900  if (Found.isAmbiguous())
2901  return true;
2902 
2903  Found.suppressDiagnostics();
2904 
2905  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2906 
2907  // C++17 [expr.delete]p10:
2908  // If the deallocation functions have class scope, the one without a
2909  // parameter of type std::size_t is selected.
2911  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2912  /*WantAlign*/ Overaligned, &Matches);
2913 
2914  // If we could find an overload, use it.
2915  if (Matches.size() == 1) {
2916  Operator = cast<CXXMethodDecl>(Matches[0].FD);
2917 
2918  // FIXME: DiagnoseUseOfDecl?
2919  if (Operator->isDeleted()) {
2920  if (Diagnose) {
2921  Diag(StartLoc, diag::err_deleted_function_use);
2922  NoteDeletedFunction(Operator);
2923  }
2924  return true;
2925  }
2926 
2927  if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2928  Matches[0].Found, Diagnose) == AR_inaccessible)
2929  return true;
2930 
2931  return false;
2932  }
2933 
2934  // We found multiple suitable operators; complain about the ambiguity.
2935  // FIXME: The standard doesn't say to do this; it appears that the intent
2936  // is that this should never happen.
2937  if (!Matches.empty()) {
2938  if (Diagnose) {
2939  Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2940  << Name << RD;
2941  for (auto &Match : Matches)
2942  Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2943  }
2944  return true;
2945  }
2946 
2947  // We did find operator delete/operator delete[] declarations, but
2948  // none of them were suitable.
2949  if (!Found.empty()) {
2950  if (Diagnose) {
2951  Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2952  << Name << RD;
2953 
2954  for (NamedDecl *D : Found)
2955  Diag(D->getUnderlyingDecl()->getLocation(),
2956  diag::note_member_declared_here) << Name;
2957  }
2958  return true;
2959  }
2960 
2961  Operator = nullptr;
2962  return false;
2963 }
2964 
2965 namespace {
2966 /// Checks whether delete-expression, and new-expression used for
2967 /// initializing deletee have the same array form.
2968 class MismatchingNewDeleteDetector {
2969 public:
2970  enum MismatchResult {
2971  /// Indicates that there is no mismatch or a mismatch cannot be proven.
2972  NoMismatch,
2973  /// Indicates that variable is initialized with mismatching form of \a new.
2974  VarInitMismatches,
2975  /// Indicates that member is initialized with mismatching form of \a new.
2976  MemberInitMismatches,
2977  /// Indicates that 1 or more constructors' definitions could not been
2978  /// analyzed, and they will be checked again at the end of translation unit.
2979  AnalyzeLater
2980  };
2981 
2982  /// \param EndOfTU True, if this is the final analysis at the end of
2983  /// translation unit. False, if this is the initial analysis at the point
2984  /// delete-expression was encountered.
2985  explicit MismatchingNewDeleteDetector(bool EndOfTU)
2986  : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2987  HasUndefinedConstructors(false) {}
2988 
2989  /// Checks whether pointee of a delete-expression is initialized with
2990  /// matching form of new-expression.
2991  ///
2992  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2993  /// point where delete-expression is encountered, then a warning will be
2994  /// issued immediately. If return value is \c AnalyzeLater at the point where
2995  /// delete-expression is seen, then member will be analyzed at the end of
2996  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2997  /// couldn't be analyzed. If at least one constructor initializes the member
2998  /// with matching type of new, the return value is \c NoMismatch.
2999  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3000  /// Analyzes a class member.
3001  /// \param Field Class member to analyze.
3002  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3003  /// for deleting the \p Field.
3004  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3005  FieldDecl *Field;
3006  /// List of mismatching new-expressions used for initialization of the pointee
3008  /// Indicates whether delete-expression was in array form.
3009  bool IsArrayForm;
3010 
3011 private:
3012  const bool EndOfTU;
3013  /// Indicates that there is at least one constructor without body.
3014  bool HasUndefinedConstructors;
3015  /// Returns \c CXXNewExpr from given initialization expression.
3016  /// \param E Expression used for initializing pointee in delete-expression.
3017  /// E can be a single-element \c InitListExpr consisting of new-expression.
3018  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3019  /// Returns whether member is initialized with mismatching form of
3020  /// \c new either by the member initializer or in-class initialization.
3021  ///
3022  /// If bodies of all constructors are not visible at the end of translation
3023  /// unit or at least one constructor initializes member with the matching
3024  /// form of \c new, mismatch cannot be proven, and this function will return
3025  /// \c NoMismatch.
3026  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3027  /// Returns whether variable is initialized with mismatching form of
3028  /// \c new.
3029  ///
3030  /// If variable is initialized with matching form of \c new or variable is not
3031  /// initialized with a \c new expression, this function will return true.
3032  /// If variable is initialized with mismatching form of \c new, returns false.
3033  /// \param D Variable to analyze.
3034  bool hasMatchingVarInit(const DeclRefExpr *D);
3035  /// Checks whether the constructor initializes pointee with mismatching
3036  /// form of \c new.
3037  ///
3038  /// Returns true, if member is initialized with matching form of \c new in
3039  /// member initializer list. Returns false, if member is initialized with the
3040  /// matching form of \c new in this constructor's initializer or given
3041  /// constructor isn't defined at the point where delete-expression is seen, or
3042  /// member isn't initialized by the constructor.
3043  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3044  /// Checks whether member is initialized with matching form of
3045  /// \c new in member initializer list.
3046  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3047  /// Checks whether member is initialized with mismatching form of \c new by
3048  /// in-class initializer.
3049  MismatchResult analyzeInClassInitializer();
3050 };
3051 }
3052 
3053 MismatchingNewDeleteDetector::MismatchResult
3054 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3055  NewExprs.clear();
3056  assert(DE && "Expected delete-expression");
3057  IsArrayForm = DE->isArrayForm();
3058  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3059  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3060  return analyzeMemberExpr(ME);
3061  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3062  if (!hasMatchingVarInit(D))
3063  return VarInitMismatches;
3064  }
3065  return NoMismatch;
3066 }
3067 
3068 const CXXNewExpr *
3069 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3070  assert(E != nullptr && "Expected a valid initializer expression");
3071  E = E->IgnoreParenImpCasts();
3072  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3073  if (ILE->getNumInits() == 1)
3074  E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3075  }
3076 
3077  return dyn_cast_or_null<const CXXNewExpr>(E);
3078 }
3079 
3080 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3081  const CXXCtorInitializer *CI) {
3082  const CXXNewExpr *NE = nullptr;
3083  if (Field == CI->getMember() &&
3084  (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3085  if (NE->isArray() == IsArrayForm)
3086  return true;
3087  else
3088  NewExprs.push_back(NE);
3089  }
3090  return false;
3091 }
3092 
3093 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3094  const CXXConstructorDecl *CD) {
3095  if (CD->isImplicit())
3096  return false;
3097  const FunctionDecl *Definition = CD;
3098  if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3099  HasUndefinedConstructors = true;
3100  return EndOfTU;
3101  }
3102  for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3103  if (hasMatchingNewInCtorInit(CI))
3104  return true;
3105  }
3106  return false;
3107 }
3108 
3109 MismatchingNewDeleteDetector::MismatchResult
3110 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3111  assert(Field != nullptr && "This should be called only for members");
3112  const Expr *InitExpr = Field->getInClassInitializer();
3113  if (!InitExpr)
3114  return EndOfTU ? NoMismatch : AnalyzeLater;
3115  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3116  if (NE->isArray() != IsArrayForm) {
3117  NewExprs.push_back(NE);
3118  return MemberInitMismatches;
3119  }
3120  }
3121  return NoMismatch;
3122 }
3123 
3124 MismatchingNewDeleteDetector::MismatchResult
3125 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3126  bool DeleteWasArrayForm) {
3127  assert(Field != nullptr && "Analysis requires a valid class member.");
3128  this->Field = Field;
3129  IsArrayForm = DeleteWasArrayForm;
3130  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3131  for (const auto *CD : RD->ctors()) {
3132  if (hasMatchingNewInCtor(CD))
3133  return NoMismatch;
3134  }
3135  if (HasUndefinedConstructors)
3136  return EndOfTU ? NoMismatch : AnalyzeLater;
3137  if (!NewExprs.empty())
3138  return MemberInitMismatches;
3139  return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3140  : NoMismatch;
3141 }
3142 
3143 MismatchingNewDeleteDetector::MismatchResult
3144 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3145  assert(ME != nullptr && "Expected a member expression");
3146  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3147  return analyzeField(F, IsArrayForm);
3148  return NoMismatch;
3149 }
3150 
3151 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3152  const CXXNewExpr *NE = nullptr;
3153  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3154  if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3155  NE->isArray() != IsArrayForm) {
3156  NewExprs.push_back(NE);
3157  }
3158  }
3159  return NewExprs.empty();
3160 }
3161 
3162 static void
3164  const MismatchingNewDeleteDetector &Detector) {
3165  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3166  FixItHint H;
3167  if (!Detector.IsArrayForm)
3168  H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3169  else {
3171  DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3172  SemaRef.getLangOpts(), true);
3173  if (RSquare.isValid())
3174  H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3175  }
3176  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3177  << Detector.IsArrayForm << H;
3178 
3179  for (const auto *NE : Detector.NewExprs)
3180  SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3181  << Detector.IsArrayForm;
3182 }
3183 
3184 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3185  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3186  return;
3187  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3188  switch (Detector.analyzeDeleteExpr(DE)) {
3189  case MismatchingNewDeleteDetector::VarInitMismatches:
3190  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3191  DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3192  break;
3193  }
3194  case MismatchingNewDeleteDetector::AnalyzeLater: {
3195  DeleteExprs[Detector.Field].push_back(
3196  std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3197  break;
3198  }
3199  case MismatchingNewDeleteDetector::NoMismatch:
3200  break;
3201  }
3202 }
3203 
3204 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3205  bool DeleteWasArrayForm) {
3206  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3207  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3208  case MismatchingNewDeleteDetector::VarInitMismatches:
3209  llvm_unreachable("This analysis should have been done for class members.");
3210  case MismatchingNewDeleteDetector::AnalyzeLater:
3211  llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3212  "translation unit.");
3213  case MismatchingNewDeleteDetector::MemberInitMismatches:
3214  DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3215  break;
3216  case MismatchingNewDeleteDetector::NoMismatch:
3217  break;
3218  }
3219 }
3220 
3221 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3222 /// @code ::delete ptr; @endcode
3223 /// or
3224 /// @code delete [] ptr; @endcode
3225 ExprResult
3226 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3227  bool ArrayForm, Expr *ExE) {
3228  // C++ [expr.delete]p1:
3229  // The operand shall have a pointer type, or a class type having a single
3230  // non-explicit conversion function to a pointer type. The result has type
3231  // void.
3232  //
3233  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3234 
3235  ExprResult Ex = ExE;
3236  FunctionDecl *OperatorDelete = nullptr;
3237  bool ArrayFormAsWritten = ArrayForm;
3238  bool UsualArrayDeleteWantsSize = false;
3239 
3240  if (!Ex.get()->isTypeDependent()) {
3241  // Perform lvalue-to-rvalue cast, if needed.
3242  Ex = DefaultLvalueConversion(Ex.get());
3243  if (Ex.isInvalid())
3244  return ExprError();
3245 
3246  QualType Type = Ex.get()->getType();
3247 
3248  class DeleteConverter : public ContextualImplicitConverter {
3249  public:
3250  DeleteConverter() : ContextualImplicitConverter(false, true) {}
3251 
3252  bool match(QualType ConvType) override {
3253  // FIXME: If we have an operator T* and an operator void*, we must pick
3254  // the operator T*.
3255  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3256  if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3257  return true;
3258  return false;
3259  }
3260 
3261  SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3262  QualType T) override {
3263  return S.Diag(Loc, diag::err_delete_operand) << T;
3264  }
3265 
3266  SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3267  QualType T) override {
3268  return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3269  }
3270 
3271  SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3272  QualType T,
3273  QualType ConvTy) override {
3274  return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3275  }
3276 
3277  SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3278  QualType ConvTy) override {
3279  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3280  << ConvTy;
3281  }
3282 
3283  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3284  QualType T) override {
3285  return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3286  }
3287 
3288  SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3289  QualType ConvTy) override {
3290  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3291  << ConvTy;
3292  }
3293 
3294  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3295  QualType T,
3296  QualType ConvTy) override {
3297  llvm_unreachable("conversion functions are permitted");
3298  }
3299  } Converter;
3300 
3301  Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3302  if (Ex.isInvalid())
3303  return ExprError();
3304  Type = Ex.get()->getType();
3305  if (!Converter.match(Type))
3306  // FIXME: PerformContextualImplicitConversion should return ExprError
3307  // itself in this case.
3308  return ExprError();
3309 
3310  QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3311  QualType PointeeElem = Context.getBaseElementType(Pointee);
3312 
3313  if (Pointee.getAddressSpace() != LangAS::Default &&
3314  !getLangOpts().OpenCLCPlusPlus)
3315  return Diag(Ex.get()->getBeginLoc(),
3316  diag::err_address_space_qualified_delete)
3317  << Pointee.getUnqualifiedType()
3319 
3320  CXXRecordDecl *PointeeRD = nullptr;
3321  if (Pointee->isVoidType() && !isSFINAEContext()) {
3322  // The C++ standard bans deleting a pointer to a non-object type, which
3323  // effectively bans deletion of "void*". However, most compilers support
3324  // this, so we treat it as a warning unless we're in a SFINAE context.
3325  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3326  << Type << Ex.get()->getSourceRange();
3327  } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3328  return ExprError(Diag(StartLoc, diag::err_delete_operand)
3329  << Type << Ex.get()->getSourceRange());
3330  } else if (!Pointee->isDependentType()) {
3331  // FIXME: This can result in errors if the definition was imported from a
3332  // module but is hidden.
3333  if (!RequireCompleteType(StartLoc, Pointee,
3334  diag::warn_delete_incomplete, Ex.get())) {
3335  if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3336  PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3337  }
3338  }
3339 
3340  if (Pointee->isArrayType() && !ArrayForm) {
3341  Diag(StartLoc, diag::warn_delete_array_type)
3342  << Type << Ex.get()->getSourceRange()
3343  << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3344  ArrayForm = true;
3345  }
3346 
3348  ArrayForm ? OO_Array_Delete : OO_Delete);
3349 
3350  if (PointeeRD) {
3351  if (!UseGlobal &&
3352  FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3353  OperatorDelete))
3354  return ExprError();
3355 
3356  // If we're allocating an array of records, check whether the
3357  // usual operator delete[] has a size_t parameter.
3358  if (ArrayForm) {
3359  // If the user specifically asked to use the global allocator,
3360  // we'll need to do the lookup into the class.
3361  if (UseGlobal)
3362  UsualArrayDeleteWantsSize =
3363  doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3364 
3365  // Otherwise, the usual operator delete[] should be the
3366  // function we just found.
3367  else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3368  UsualArrayDeleteWantsSize =
3369  UsualDeallocFnInfo(*this,
3370  DeclAccessPair::make(OperatorDelete, AS_public))
3371  .HasSizeT;
3372  }
3373 
3374  if (!PointeeRD->hasIrrelevantDestructor())
3375  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3376  MarkFunctionReferenced(StartLoc,
3377  const_cast<CXXDestructorDecl*>(Dtor));
3378  if (DiagnoseUseOfDecl(Dtor, StartLoc))
3379  return ExprError();
3380  }
3381 
3382  CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3383  /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3384  /*WarnOnNonAbstractTypes=*/!ArrayForm,
3385  SourceLocation());
3386  }
3387 
3388  if (!OperatorDelete) {
3389  if (getLangOpts().OpenCLCPlusPlus) {
3390  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3391  return ExprError();
3392  }
3393 
3394  bool IsComplete = isCompleteType(StartLoc, Pointee);
3395  bool CanProvideSize =
3396  IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3397  Pointee.isDestructedType());
3398  bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3399 
3400  // Look for a global declaration.
3401  OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3402  Overaligned, DeleteName);
3403  }
3404 
3405  MarkFunctionReferenced(StartLoc, OperatorDelete);
3406 
3407  // Check access and ambiguity of destructor if we're going to call it.
3408  // Note that this is required even for a virtual delete.
3409  bool IsVirtualDelete = false;
3410  if (PointeeRD) {
3411  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3412  CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3413  PDiag(diag::err_access_dtor) << PointeeElem);
3414  IsVirtualDelete = Dtor->isVirtual();
3415  }
3416  }
3417 
3418  DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3419 
3420  // Convert the operand to the type of the first parameter of operator
3421  // delete. This is only necessary if we selected a destroying operator
3422  // delete that we are going to call (non-virtually); converting to void*
3423  // is trivial and left to AST consumers to handle.
3424  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3425  if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3426  Qualifiers Qs = Pointee.getQualifiers();
3427  if (Qs.hasCVRQualifiers()) {
3428  // Qualifiers are irrelevant to this conversion; we're only looking
3429  // for access and ambiguity.
3430  Qs.removeCVRQualifiers();
3431  QualType Unqual = Context.getPointerType(
3433  Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3434  }
3435  Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3436  if (Ex.isInvalid())
3437  return ExprError();
3438  }
3439  }
3440 
3442  Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3443  UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3444  AnalyzeDeleteExprMismatch(Result);
3445  return Result;
3446 }
3447 
3449  bool IsDelete,
3450  FunctionDecl *&Operator) {
3451 
3453  IsDelete ? OO_Delete : OO_New);
3454 
3455  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3457  assert(!R.empty() && "implicitly declared allocation functions not found");
3458  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3459 
3460  // We do our own custom access checks below.
3461  R.suppressDiagnostics();
3462 
3463  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3464  OverloadCandidateSet Candidates(R.getNameLoc(),
3466  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3467  FnOvl != FnOvlEnd; ++FnOvl) {
3468  // Even member operator new/delete are implicitly treated as
3469  // static, so don't use AddMemberCandidate.
3470  NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3471 
3472  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3473  S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3474  /*ExplicitTemplateArgs=*/nullptr, Args,
3475  Candidates,
3476  /*SuppressUserConversions=*/false);
3477  continue;
3478  }
3479 
3480  FunctionDecl *Fn = cast<FunctionDecl>(D);
3481  S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3482  /*SuppressUserConversions=*/false);
3483  }
3484 
3485  SourceRange Range = TheCall->getSourceRange();
3486 
3487  // Do the resolution.
3489  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3490  case OR_Success: {
3491  // Got one!
3492  FunctionDecl *FnDecl = Best->Function;
3493  assert(R.getNamingClass() == nullptr &&
3494  "class members should not be considered");
3495 
3496  if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3497  S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3498  << (IsDelete ? 1 : 0) << Range;
3499  S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3500  << R.getLookupName() << FnDecl->getSourceRange();
3501  return true;
3502  }
3503 
3504  Operator = FnDecl;
3505  return false;
3506  }
3507 
3508  case OR_No_Viable_Function:
3509  S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3510  << R.getLookupName() << Range;
3511  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3512  return true;
3513 
3514  case OR_Ambiguous:
3515  S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3516  << R.getLookupName() << Range;
3517  Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3518  return true;
3519 
3520  case OR_Deleted: {
3521  S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3522  << Best->Function->isDeleted() << R.getLookupName()
3523  << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3524  Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3525  return true;
3526  }
3527  }
3528  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3529 }
3530 
3531 ExprResult
3532 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3533  bool IsDelete) {
3534  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3535  if (!getLangOpts().CPlusPlus) {
3536  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3537  << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3538  << "C++";
3539  return ExprError();
3540  }
3541  // CodeGen assumes it can find the global new and delete to call,
3542  // so ensure that they are declared.
3544 
3545  FunctionDecl *OperatorNewOrDelete = nullptr;
3546  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3547  OperatorNewOrDelete))
3548  return ExprError();
3549  assert(OperatorNewOrDelete && "should be found");
3550 
3551  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3552  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3553 
3554  TheCall->setType(OperatorNewOrDelete->getReturnType());
3555  for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3556  QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3557  InitializedEntity Entity =
3560  Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3561  if (Arg.isInvalid())
3562  return ExprError();
3563  TheCall->setArg(i, Arg.get());
3564  }
3565  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3566  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3567  "Callee expected to be implicit cast to a builtin function pointer");
3568  Callee->setType(OperatorNewOrDelete->getType());
3569 
3570  return TheCallResult;
3571 }
3572 
3574  bool IsDelete, bool CallCanBeVirtual,
3575  bool WarnOnNonAbstractTypes,
3576  SourceLocation DtorLoc) {
3577  if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3578  return;
3579 
3580  // C++ [expr.delete]p3:
3581  // In the first alternative (delete object), if the static type of the
3582  // object to be deleted is different from its dynamic type, the static
3583  // type shall be a base class of the dynamic type of the object to be
3584  // deleted and the static type shall have a virtual destructor or the
3585  // behavior is undefined.
3586  //
3587  const CXXRecordDecl *PointeeRD = dtor->getParent();
3588  // Note: a final class cannot be derived from, no issue there
3589  if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3590  return;
3591 
3592  // If the superclass is in a system header, there's nothing that can be done.
3593  // The `delete` (where we emit the warning) can be in a system header,
3594  // what matters for this warning is where the deleted type is defined.
3595  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3596  return;
3597 
3598  QualType ClassType = dtor->getThisType()->getPointeeType();
3599  if (PointeeRD->isAbstract()) {
3600  // If the class is abstract, we warn by default, because we're
3601  // sure the code has undefined behavior.
3602  Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3603  << ClassType;
3604  } else if (WarnOnNonAbstractTypes) {
3605  // Otherwise, if this is not an array delete, it's a bit suspect,
3606  // but not necessarily wrong.
3607  Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3608  << ClassType;
3609  }
3610  if (!IsDelete) {
3611  std::string TypeStr;
3612  ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3613  Diag(DtorLoc, diag::note_delete_non_virtual)
3614  << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3615  }
3616 }
3617 
3619  SourceLocation StmtLoc,
3620  ConditionKind CK) {
3621  ExprResult E =
3622  CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3623  if (E.isInvalid())
3624  return ConditionError();
3625  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3627 }
3628 
3629 /// Check the use of the given variable as a C++ condition in an if,
3630 /// while, do-while, or switch statement.
3632  SourceLocation StmtLoc,
3633  ConditionKind CK) {
3634  if (ConditionVar->isInvalidDecl())
3635  return ExprError();
3636 
3637  QualType T = ConditionVar->getType();
3638 
3639  // C++ [stmt.select]p2:
3640  // The declarator shall not specify a function or an array.
3641  if (T->isFunctionType())
3642  return ExprError(Diag(ConditionVar->getLocation(),
3643  diag::err_invalid_use_of_function_type)
3644  << ConditionVar->getSourceRange());
3645  else if (T->isArrayType())
3646  return ExprError(Diag(ConditionVar->getLocation(),
3647  diag::err_invalid_use_of_array_type)
3648  << ConditionVar->getSourceRange());
3649 
3650  ExprResult Condition = DeclRefExpr::Create(
3651  Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3652  /*enclosing*/ false, ConditionVar->getLocation(),
3653  ConditionVar->getType().getNonReferenceType(), VK_LValue);
3654 
3655  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3656 
3657  switch (CK) {
3659  return CheckBooleanCondition(StmtLoc, Condition.get());
3660 
3662  return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3663 
3664  case ConditionKind::Switch:
3665  return CheckSwitchCondition(StmtLoc, Condition.get());
3666  }
3667 
3668  llvm_unreachable("unexpected condition kind");
3669 }
3670 
3671 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3672 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3673  // C++ 6.4p4:
3674  // The value of a condition that is an initialized declaration in a statement
3675  // other than a switch statement is the value of the declared variable
3676  // implicitly converted to type bool. If that conversion is ill-formed, the
3677  // program is ill-formed.
3678  // The value of a condition that is an expression is the value of the
3679  // expression, implicitly converted to bool.
3680  //
3681  // FIXME: Return this value to the caller so they don't need to recompute it.
3682  llvm::APSInt Value(/*BitWidth*/1);
3683  return (IsConstexpr && !CondExpr->isValueDependent())
3684  ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3687 }
3688 
3689 /// Helper function to determine whether this is the (deprecated) C++
3690 /// conversion from a string literal to a pointer to non-const char or
3691 /// non-const wchar_t (for narrow and wide string literals,
3692 /// respectively).
3693 bool
3695  // Look inside the implicit cast, if it exists.
3696  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3697  From = Cast->getSubExpr();
3698 
3699  // A string literal (2.13.4) that is not a wide string literal can
3700  // be converted to an rvalue of type "pointer to char"; a wide
3701  // string literal can be converted to an rvalue of type "pointer
3702  // to wchar_t" (C++ 4.2p2).
3703  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3704  if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3705  if (const BuiltinType *ToPointeeType
3706  = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3707  // This conversion is considered only when there is an
3708  // explicit appropriate pointer target type (C++ 4.2p2).
3709  if (!ToPtrType->getPointeeType().hasQualifiers()) {
3710  switch (StrLit->getKind()) {
3711  case StringLiteral::UTF8:
3712  case StringLiteral::UTF16:
3713  case StringLiteral::UTF32:
3714  // We don't allow UTF literals to be implicitly converted
3715  break;
3716  case StringLiteral::Ascii:
3717  return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3718  ToPointeeType->getKind() == BuiltinType::Char_S);
3719  case StringLiteral::Wide:
3721  QualType(ToPointeeType, 0));
3722  }
3723  }
3724  }
3725 
3726  return false;
3727 }
3728 
3730  SourceLocation CastLoc,
3731  QualType Ty,
3732  CastKind Kind,
3733  CXXMethodDecl *Method,
3734  DeclAccessPair FoundDecl,
3735  bool HadMultipleCandidates,
3736  Expr *From) {
3737  switch (Kind) {
3738  default: llvm_unreachable("Unhandled cast kind!");
3739  case CK_ConstructorConversion: {
3740  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3741  SmallVector<Expr*, 8> ConstructorArgs;
3742 
3743  if (S.RequireNonAbstractType(CastLoc, Ty,
3744  diag::err_allocation_of_abstract_type))
3745  return ExprError();
3746 
3747  if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3748  return ExprError();
3749 
3750  S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3752  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3753  return ExprError();
3754 
3756  CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3757  ConstructorArgs, HadMultipleCandidates,
3758  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3760  if (Result.isInvalid())
3761  return ExprError();
3762 
3763  return S.MaybeBindToTemporary(Result.getAs<Expr>());
3764  }
3765 
3766  case CK_UserDefinedConversion: {
3767  assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3768 
3769  S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3770  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3771  return ExprError();
3772 
3773  // Create an implicit call expr that calls it.
3774  CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3775  ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3776  HadMultipleCandidates);
3777  if (Result.isInvalid())
3778  return ExprError();
3779  // Record usage of conversion in an implicit cast.
3780  Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3781  CK_UserDefinedConversion, Result.get(),
3782  nullptr, Result.get()->getValueKind());
3783 
3784  return S.MaybeBindToTemporary(Result.get());
3785  }
3786  }
3787 }
3788 
3789 /// PerformImplicitConversion - Perform an implicit conversion of the
3790 /// expression From to the type ToType using the pre-computed implicit
3791 /// conversion sequence ICS. Returns the converted
3792 /// expression. Action is the kind of conversion we're performing,
3793 /// used in the error message.
3794 ExprResult
3796  const ImplicitConversionSequence &ICS,
3797  AssignmentAction Action,
3798  CheckedConversionKind CCK) {
3799  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3800  if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3801  return From;
3802 
3803  switch (ICS.getKind()) {
3805  ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3806  Action, CCK);
3807  if (Res.isInvalid())
3808  return ExprError();
3809  From = Res.get();
3810  break;
3811  }
3812 
3814 
3817  QualType BeforeToType;
3818  assert(FD && "no conversion function for user-defined conversion seq");
3819  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3820  CastKind = CK_UserDefinedConversion;
3821 
3822  // If the user-defined conversion is specified by a conversion function,
3823  // the initial standard conversion sequence converts the source type to
3824  // the implicit object parameter of the conversion function.
3825  BeforeToType = Context.getTagDeclType(Conv->getParent());
3826  } else {
3827  const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3828  CastKind = CK_ConstructorConversion;
3829  // Do no conversion if dealing with ... for the first conversion.
3830  if (!ICS.UserDefined.EllipsisConversion) {
3831  // If the user-defined conversion is specified by a constructor, the
3832  // initial standard conversion sequence converts the source type to
3833  // the type required by the argument of the constructor
3834  BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3835  }
3836  }
3837  // Watch out for ellipsis conversion.
3838  if (!ICS.UserDefined.EllipsisConversion) {
3839  ExprResult Res =
3840  PerformImplicitConversion(From, BeforeToType,
3842  CCK);
3843  if (Res.isInvalid())
3844  return ExprError();
3845  From = Res.get();
3846  }
3847 
3848  ExprResult CastArg = BuildCXXCastArgument(
3849  *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3850  cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3852 
3853  if (CastArg.isInvalid())
3854  return ExprError();
3855 
3856  From = CastArg.get();
3857 
3858  // C++ [over.match.oper]p7:
3859  // [...] the second standard conversion sequence of a user-defined
3860  // conversion sequence is not applied.
3861  if (CCK == CCK_ForBuiltinOverloadedOp)
3862  return From;
3863 
3864  return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3865  AA_Converting, CCK);
3866  }
3867 
3869  ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3870  PDiag(diag::err_typecheck_ambiguous_condition)
3871  << From->getSourceRange());
3872  return ExprError();
3873 
3875  llvm_unreachable("Cannot perform an ellipsis conversion");
3876 
3878  bool Diagnosed =
3880  From->getType(), From, Action);
3881  assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3882  return ExprError();
3883  }
3884 
3885  // Everything went well.
3886  return From;
3887 }
3888 
3889 /// PerformImplicitConversion - Perform an implicit conversion of the
3890 /// expression From to the type ToType by following the standard
3891 /// conversion sequence SCS. Returns the converted
3892 /// expression. Flavor is the context in which we're performing this
3893 /// conversion, for use in error messages.
3894 ExprResult
3896  const StandardConversionSequence& SCS,
3897  AssignmentAction Action,
3898  CheckedConversionKind CCK) {
3899  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3900 
3901  // Overall FIXME: we are recomputing too many types here and doing far too
3902  // much extra work. What this means is that we need to keep track of more
3903  // information that is computed when we try the implicit conversion initially,
3904  // so that we don't need to recompute anything here.
3905  QualType FromType = From->getType();
3906 
3907  if (SCS.CopyConstructor) {
3908  // FIXME: When can ToType be a reference type?
3909  assert(!ToType->isReferenceType());
3910  if (SCS.Second == ICK_Derived_To_Base) {
3911  SmallVector<Expr*, 8> ConstructorArgs;
3912  if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3913  From, /*FIXME:ConstructLoc*/SourceLocation(),
3914  ConstructorArgs))
3915  return ExprError();
3916  return BuildCXXConstructExpr(
3917  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3919  ConstructorArgs, /*HadMultipleCandidates*/ false,
3920  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3922  }
3923  return BuildCXXConstructExpr(
3924  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3926  From, /*HadMultipleCandidates*/ false,
3927  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3929  }
3930 
3931  // Resolve overloaded function references.
3932  if (Context.hasSameType(FromType, Context.OverloadTy)) {
3933  DeclAccessPair Found;
3935  true, Found);
3936  if (!Fn)
3937  return ExprError();
3938 
3939  if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3940  return ExprError();
3941 
3942  From = FixOverloadedFunctionReference(From, Found, Fn);
3943  FromType = From->getType();
3944  }
3945 
3946  // If we're converting to an atomic type, first convert to the corresponding
3947  // non-atomic type.
3948  QualType ToAtomicType;
3949  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3950  ToAtomicType = ToType;
3951  ToType = ToAtomic->getValueType();
3952  }
3953 
3954  QualType InitialFromType = FromType;
3955  // Perform the first implicit conversion.
3956  switch (SCS.First) {
3957  case ICK_Identity:
3958  if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3959  FromType = FromAtomic->getValueType().getUnqualifiedType();
3960  From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3961  From, /*BasePath=*/nullptr, VK_RValue);
3962  }
3963  break;
3964 
3965  case ICK_Lvalue_To_Rvalue: {
3966  assert(From->getObjectKind() != OK_ObjCProperty);
3967  ExprResult FromRes = DefaultLvalueConversion(From);
3968  assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3969  From = FromRes.get();
3970  FromType = From->getType();
3971  break;
3972  }
3973 
3974  case ICK_Array_To_Pointer:
3975  FromType = Context.getArrayDecayedType(FromType);
3976  From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3977  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3978  break;
3979 
3981  FromType = Context.getPointerType(FromType);
3982  From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3983  VK_RValue, /*BasePath=*/nullptr, CCK).get();
3984  break;
3985 
3986  default:
3987  llvm_unreachable("Improper first standard conversion");
3988  }
3989 
3990  // Perform the second implicit conversion
3991  switch (SCS.Second) {
3992  case ICK_Identity:
3993  // C++ [except.spec]p5:
3994  // [For] assignment to and initialization of pointers to functions,
3995  // pointers to member functions, and references to functions: the
3996  // target entity shall allow at least the exceptions allowed by the
3997  // source value in the assignment or initialization.
3998  switch (Action) {
3999  case AA_Assigning:
4000  case AA_Initializing:
4001  // Note, function argument passing and returning are initialization.
4002  case AA_Passing:
4003  case AA_Returning:
4004  case AA_Sending:
4005  case AA_Passing_CFAudited:
4006  if (CheckExceptionSpecCompatibility(From, ToType))
4007  return ExprError();
4008  break;
4009 
4010  case AA_Casting:
4011  case AA_Converting:
4012  // Casts and implicit conversions are not initialization, so are not
4013  // checked for exception specification mismatches.
4014  break;
4015  }
4016  // Nothing else to do.
4017  break;
4018 
4021  if (ToType->isBooleanType()) {
4022  assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4023  SCS.Second == ICK_Integral_Promotion &&
4024  "only enums with fixed underlying type can promote to bool");
4025  From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4026  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4027  } else {
4028  From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4029  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4030  }
4031  break;
4032 
4035  From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4036  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4037  break;
4038 
4039  case ICK_Complex_Promotion:
4040  case ICK_Complex_Conversion: {
4041  QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4042  QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4043  CastKind CK;
4044  if (FromEl->isRealFloatingType()) {
4045  if (ToEl->isRealFloatingType())
4046  CK = CK_FloatingComplexCast;
4047  else
4048  CK = CK_FloatingComplexToIntegralComplex;
4049  } else if (ToEl->isRealFloatingType()) {
4050  CK = CK_IntegralComplexToFloatingComplex;
4051  } else {
4052  CK = CK_IntegralComplexCast;
4053  }
4054  From = ImpCastExprToType(From, ToType, CK,
4055  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4056  break;
4057  }
4058 
4059  case ICK_Floating_Integral:
4060  if (ToType->isRealFloatingType())
4061  From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4062  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4063  else
4064  From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4065  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4066  break;
4067 
4069  From = ImpCastExprToType(From, ToType, CK_NoOp,
4070  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4071  break;
4072 
4074  case ICK_Pointer_Conversion: {
4075  if (SCS.IncompatibleObjC && Action != AA_Casting) {
4076  // Diagnose incompatible Objective-C conversions
4077  if (Action == AA_Initializing || Action == AA_Assigning)
4078  Diag(From->getBeginLoc(),
4079  diag::ext_typecheck_convert_incompatible_pointer)
4080  << ToType << From->getType() << Action << From->getSourceRange()
4081  << 0;
4082  else
4083  Diag(From->getBeginLoc(),
4084  diag::ext_typecheck_convert_incompatible_pointer)
4085  << From->getType() << ToType << Action << From->getSourceRange()
4086  << 0;
4087 
4088  if (From->getType()->isObjCObjectPointerType() &&
4089  ToType->isObjCObjectPointerType())
4093  From->getType())) {
4094  if (Action == AA_Initializing)
4095  Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4096  else
4097  Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4098  << (Action == AA_Casting) << From->getType() << ToType
4099  << From->getSourceRange();
4100  }
4101 
4102  CastKind Kind;
4103  CXXCastPath BasePath;
4104  if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4105  return ExprError();
4106 
4107  // Make sure we extend blocks if necessary.
4108  // FIXME: doing this here is really ugly.
4109  if (Kind == CK_BlockPointerToObjCPointerCast) {
4110  ExprResult E = From;
4112  From = E.get();
4113  }
4114  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4115  CheckObjCConversion(SourceRange(), ToType, From, CCK);
4116  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4117  .get();
4118  break;
4119  }
4120 
4121  case ICK_Pointer_Member: {
4122  CastKind Kind;
4123  CXXCastPath BasePath;
4124  if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4125  return ExprError();
4126  if (CheckExceptionSpecCompatibility(From, ToType))
4127  return ExprError();
4128 
4129  // We may not have been able to figure out what this member pointer resolved
4130  // to up until this exact point. Attempt to lock-in it's inheritance model.
4132  (void)isCompleteType(From->getExprLoc(), From->getType());
4133  (void)isCompleteType(From->getExprLoc(), ToType);
4134  }
4135 
4136  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4137  .get();
4138  break;
4139  }
4140 
4142  // Perform half-to-boolean conversion via float.
4143  if (From->getType()->isHalfType()) {
4144  From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4145  FromType = Context.FloatTy;
4146  }
4147 
4148  From = ImpCastExprToType(From, Context.BoolTy,
4149  ScalarTypeToBooleanCastKind(FromType),
4150  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4151  break;
4152 
4153  case ICK_Derived_To_Base: {
4154  CXXCastPath BasePath;
4156  From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4157  From->getSourceRange(), &BasePath, CStyle))
4158  return ExprError();
4159 
4160  From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4161  CK_DerivedToBase, From->getValueKind(),
4162  &BasePath, CCK).get();
4163  break;
4164  }
4165 
4166  case ICK_Vector_Conversion:
4167  From = ImpCastExprToType(From, ToType, CK_BitCast,
4168  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4169  break;
4170 
4171  case ICK_Vector_Splat: {
4172  // Vector splat from any arithmetic type to a vector.
4173  Expr *Elem = prepareVectorSplat(ToType, From).get();
4174  From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4175  /*BasePath=*/nullptr, CCK).get();
4176  break;
4177  }
4178 
4179  case ICK_Complex_Real:
4180  // Case 1. x -> _Complex y
4181  if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4182  QualType ElType = ToComplex->getElementType();
4183  bool isFloatingComplex = ElType->isRealFloatingType();
4184 
4185  // x -> y
4186  if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4187  // do nothing
4188  } else if (From->getType()->isRealFloatingType()) {
4189  From = ImpCastExprToType(From, ElType,
4190  isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4191  } else {
4192  assert(From->getType()->isIntegerType());
4193  From = ImpCastExprToType(From, ElType,
4194  isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4195  }
4196  // y -> _Complex y
4197  From = ImpCastExprToType(From, ToType,
4198  isFloatingComplex ? CK_FloatingRealToComplex
4199  : CK_IntegralRealToComplex).get();
4200 
4201  // Case 2. _Complex x -> y
4202  } else {
4203  const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4204  assert(FromComplex);
4205 
4206  QualType ElType = FromComplex->getElementType();
4207  bool isFloatingComplex = ElType->isRealFloatingType();
4208 
4209  // _Complex x -> x
4210  From = ImpCastExprToType(From, ElType,
4211  isFloatingComplex ? CK_FloatingComplexToReal
4212  : CK_IntegralComplexToReal,
4213  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4214 
4215  // x -> y
4216  if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4217  // do nothing
4218  } else if (ToType->isRealFloatingType()) {
4219  From = ImpCastExprToType(From, ToType,
4220  isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4221  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4222  } else {
4223  assert(ToType->isIntegerType());
4224  From = ImpCastExprToType(From, ToType,
4225  isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4226  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4227  }
4228  }
4229  break;
4230 
4232  From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4233  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4234  break;
4235  }
4236 
4238  ExprResult FromRes = From;
4239  Sema::AssignConvertType ConvTy =
4241  if (FromRes.isInvalid())
4242  return ExprError();
4243  From = FromRes.get();
4244  assert ((ConvTy == Sema::Compatible) &&
4245  "Improper transparent union conversion");
4246  (void)ConvTy;
4247  break;
4248  }
4249 
4252  From = ImpCastExprToType(From, ToType,
4253  CK_ZeroToOCLOpaqueType,
4254  From->getValueKind()).get();
4255  break;
4256 
4257  case ICK_Lvalue_To_Rvalue:
4258  case ICK_Array_To_Pointer:
4261  case ICK_Qualification:
4263  case ICK_C_Only_Conversion:
4265  llvm_unreachable("Improper second standard conversion");
4266  }
4267 
4268  switch (SCS.Third) {
4269  case ICK_Identity:
4270  // Nothing to do.
4271  break;
4272 
4274  // If both sides are functions (or pointers/references to them), there could
4275  // be incompatible exception declarations.
4276  if (CheckExceptionSpecCompatibility(From, ToType))
4277  return ExprError();
4278 
4279  From = ImpCastExprToType(From, ToType, CK_NoOp,
4280  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4281  break;
4282 
4283  case ICK_Qualification: {
4284  // The qualification keeps the category of the inner expression, unless the
4285  // target type isn't a reference.
4286  ExprValueKind VK =
4287  ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4288 
4289  CastKind CK = CK_NoOp;
4290 
4291  if (ToType->isReferenceType() &&
4292  ToType->getPointeeType().getAddressSpace() !=
4293  From->getType().getAddressSpace())
4294  CK = CK_AddressSpaceConversion;
4295 
4296  if (ToType->isPointerType() &&
4297  ToType->getPointeeType().getAddressSpace() !=
4298  From->getType()->getPointeeType().getAddressSpace())
4299  CK = CK_AddressSpaceConversion;
4300 
4301  From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4302  /*BasePath=*/nullptr, CCK)
4303  .get();
4304 
4306  !getLangOpts().WritableStrings) {
4307  Diag(From->getBeginLoc(),
4308  getLangOpts().CPlusPlus11
4309  ? diag::ext_deprecated_string_literal_conversion
4310  : diag::warn_deprecated_string_literal_conversion)
4311  << ToType.getNonReferenceType();
4312  }
4313 
4314  break;
4315  }
4316 
4317  default:
4318  llvm_unreachable("Improper third standard conversion");
4319  }
4320 
4321  // If this conversion sequence involved a scalar -> atomic conversion, perform
4322  // that conversion now.
4323  if (!ToAtomicType.isNull()) {
4324  assert(Context.hasSameType(
4325  ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4326  From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4327  VK_RValue, nullptr, CCK).get();
4328  }
4329 
4330  // If this conversion sequence succeeded and involved implicitly converting a
4331  // _Nullable type to a _Nonnull one, complain.
4332  if (!isCast(CCK))
4333  diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4334  From->getBeginLoc());
4335 
4336  return From;
4337 }
4338 
4339 /// Check the completeness of a type in a unary type trait.
4340 ///
4341 /// If the particular type trait requires a complete type, tries to complete
4342 /// it. If completing the type fails, a diagnostic is emitted and false
4343 /// returned. If completing the type succeeds or no completion was required,
4344 /// returns true.
4346  SourceLocation Loc,
4347  QualType ArgTy) {
4348  // C++0x [meta.unary.prop]p3:
4349  // For all of the class templates X declared in this Clause, instantiating
4350  // that template with a template argument that is a class template
4351  // specialization may result in the implicit instantiation of the template
4352  // argument if and only if the semantics of X require that the argument
4353  // must be a complete type.
4354  // We apply this rule to all the type trait expressions used to implement
4355  // these class templates. We also try to follow any GCC documented behavior
4356  // in these expressions to ensure portability of standard libraries.
4357  switch (UTT) {
4358  default: llvm_unreachable("not a UTT");
4359  // is_complete_type somewhat obviously cannot require a complete type.
4360  case UTT_IsCompleteType:
4361  // Fall-through
4362 
4363  // These traits are modeled on the type predicates in C++0x
4364  // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4365  // requiring a complete type, as whether or not they return true cannot be
4366  // impacted by the completeness of the type.
4367  case UTT_IsVoid:
4368  case UTT_IsIntegral:
4369  case UTT_IsFloatingPoint:
4370  case UTT_IsArray:
4371  case UTT_IsPointer:
4372  case UTT_IsLvalueReference:
4373  case UTT_IsRvalueReference:
4376  case UTT_IsEnum:
4377  case UTT_IsUnion:
4378  case UTT_IsClass:
4379  case UTT_IsFunction:
4380  case UTT_IsReference:
4381  case UTT_IsArithmetic:
4382  case UTT_IsFundamental:
4383  case UTT_IsObject:
4384  case UTT_IsScalar:
4385  case UTT_IsCompound:
4386  case UTT_IsMemberPointer:
4387  // Fall-through
4388 
4389  // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4390  // which requires some of its traits to have the complete type. However,
4391  // the completeness of the type cannot impact these traits' semantics, and
4392  // so they don't require it. This matches the comments on these traits in
4393  // Table 49.
4394  case UTT_IsConst:
4395  case UTT_IsVolatile:
4396  case UTT_IsSigned:
4397  case UTT_IsUnsigned:
4398 
4399  // This type trait always returns false, checking the type is moot.
4400  case UTT_IsInterfaceClass:
4401  return true;
4402 
4403  // C++14 [meta.unary.prop]:
4404  // If T is a non-union class type, T shall be a complete type.
4405  case UTT_IsEmpty:
4406  case UTT_IsPolymorphic:
4407  case UTT_IsAbstract:
4408  if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4409  if (!RD->isUnion())
4410  return !S.RequireCompleteType(
4411  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4412  return true;
4413 
4414  // C++14 [meta.unary.prop]:
4415  // If T is a class type, T shall be a complete type.
4416  case UTT_IsFinal:
4417  case UTT_IsSealed:
4418  if (ArgTy->getAsCXXRecordDecl())
4419  return !S.RequireCompleteType(
4420  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4421  return true;
4422 
4423  // C++1z [meta.unary.prop]:
4424  // remove_all_extents_t<T> shall be a complete type or cv void.
4425  case UTT_IsAggregate:
4426  case UTT_IsTrivial:
4428  case UTT_IsStandardLayout:
4429  case UTT_IsPOD:
4430  case UTT_IsLiteral:
4431  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4432  // or an array of unknown bound. But GCC actually imposes the same constraints
4433  // as above.
4434  case UTT_HasNothrowAssign:
4437  case UTT_HasNothrowCopy:
4438  case UTT_HasTrivialAssign:
4442  case UTT_HasTrivialCopy:
4445  ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4446  LLVM_FALLTHROUGH;
4447 
4448  // C++1z [meta.unary.prop]:
4449  // T shall be a complete type, cv void, or an array of unknown bound.
4450  case UTT_IsDestructible:
4454  if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4455  return true;
4456 
4457  return !S.RequireCompleteType(
4458  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4459  }
4460 }
4461 
4463  Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4464  bool (CXXRecordDecl::*HasTrivial)() const,
4465  bool (CXXRecordDecl::*HasNonTrivial)() const,
4466  bool (CXXMethodDecl::*IsDesiredOp)() const)
4467 {
4468  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4469  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4470  return true;
4471 
4473  DeclarationNameInfo NameInfo(Name, KeyLoc);
4474  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4475  if (Self.LookupQualifiedName(Res, RD)) {
4476  bool FoundOperator = false;
4477  Res.suppressDiagnostics();
4478  for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4479  Op != OpEnd; ++Op) {
4480  if (isa<FunctionTemplateDecl>(*Op))
4481  continue;
4482 
4483  CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4484  if((Operator->*IsDesiredOp)()) {
4485  FoundOperator = true;
4486  const FunctionProtoType *CPT =
4487  Operator->getType()->getAs<FunctionProtoType>();
4488  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4489  if (!CPT || !CPT->isNothrow())
4490  return false;
4491  }
4492  }
4493  return FoundOperator;
4494  }
4495  return false;
4496 }
4497 
4498 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4499  SourceLocation KeyLoc, QualType T) {
4500  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4501 
4502  ASTContext &C = Self.Context;
4503  switch(UTT) {
4504  default: llvm_unreachable("not a UTT");
4505  // Type trait expressions corresponding to the primary type category
4506  // predicates in C++0x [meta.unary.cat].
4507  case UTT_IsVoid:
4508  return T->isVoidType();
4509  case UTT_IsIntegral:
4510  return T->isIntegralType(C);
4511  case UTT_IsFloatingPoint:
4512  return T->isFloatingType();
4513  case UTT_IsArray:
4514  return T->isArrayType();
4515  case UTT_IsPointer:
4516  return T->isPointerType();
4517  case UTT_IsLvalueReference:
4518  return T->isLValueReferenceType();
4519  case UTT_IsRvalueReference:
4520  return T->isRValueReferenceType();
4522  return T->isMemberFunctionPointerType();
4524  return T->isMemberDataPointerType();
4525  case UTT_IsEnum:
4526  return T->isEnumeralType();
4527  case UTT_IsUnion:
4528  return T->isUnionType();
4529  case UTT_IsClass:
4530  return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4531  case UTT_IsFunction:
4532  return T->isFunctionType();
4533 
4534  // Type trait expressions which correspond to the convenient composition
4535  // predicates in C++0x [meta.unary.comp].
4536  case UTT_IsReference:
4537  return T->isReferenceType();
4538  case UTT_IsArithmetic:
4539  return T->isArithmeticType() && !T->isEnumeralType();
4540  case UTT_IsFundamental:
4541  return T->isFundamentalType();
4542  case UTT_IsObject:
4543  return T->isObjectType();
4544  case UTT_IsScalar:
4545  // Note: semantic analysis depends on Objective-C lifetime types to be
4546  // considered scalar types. However, such types do not actually behave
4547  // like scalar types at run time (since they may require retain/release
4548  // operations), so we report them as non-scalar.
4549  if (T->isObjCLifetimeType()) {
4550  switch (T.getObjCLifetime()) {
4551  case Qualifiers::OCL_None:
4553  return true;
4554 
4556  case Qualifiers::OCL_Weak:
4558  return false;
4559  }
4560  }
4561 
4562  return T->isScalarType();
4563  case UTT_IsCompound:
4564  return T->isCompoundType();
4565  case UTT_IsMemberPointer:
4566  return T->isMemberPointerType();
4567 
4568  // Type trait expressions which correspond to the type property predicates
4569  // in C++0x [meta.unary.prop].
4570  case UTT_IsConst:
4571  return T.isConstQualified();
4572  case UTT_IsVolatile:
4573  return T.isVolatileQualified();
4574  case UTT_IsTrivial:
4575  return T.isTrivialType(C);
4577  return T.isTriviallyCopyableType(C);
4578  case UTT_IsStandardLayout:
4579  return T->isStandardLayoutType();
4580  case UTT_IsPOD:
4581  return T.isPODType(C);
4582  case UTT_IsLiteral:
4583  return T->isLiteralType(C);
4584  case UTT_IsEmpty:
4585  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4586  return !RD->isUnion() && RD->isEmpty();
4587  return false;
4588  case UTT_IsPolymorphic:
4589  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4590  return !RD->isUnion() && RD->isPolymorphic();
4591  return false;
4592  case UTT_IsAbstract:
4593  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4594  return !RD->isUnion() && RD->isAbstract();
4595  return false;
4596  case UTT_IsAggregate:
4597  // Report vector extensions and complex types as aggregates because they
4598  // support aggregate initialization. GCC mirrors this behavior for vectors
4599  // but not _Complex.
4600  return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4601  T->isAnyComplexType();
4602  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4603  // even then only when it is used with the 'interface struct ...' syntax
4604  // Clang doesn't support /CLR which makes this type trait moot.
4605  case UTT_IsInterfaceClass:
4606  return false;
4607  case UTT_IsFinal:
4608  case UTT_IsSealed:
4609  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4610  return RD->hasAttr<FinalAttr>();
4611  return false;
4612  case UTT_IsSigned:
4613  return T->isSignedIntegerType();
4614  case UTT_IsUnsigned:
4615  return T->isUnsignedIntegerType();
4616 
4617  // Type trait expressions which query classes regarding their construction,
4618  // destruction, and copying. Rather than being based directly on the
4619  // related type predicates in the standard, they are specified by both
4620  // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4621  // specifications.
4622  //
4623  // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4624  // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4625  //
4626  // Note that these builtins do not behave as documented in g++: if a class
4627  // has both a trivial and a non-trivial special member of a particular kind,
4628  // they return false! For now, we emulate this behavior.
4629  // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4630  // does not correctly compute triviality in the presence of multiple special
4631  // members of the same kind. Revisit this once the g++ bug is fixed.
4633  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4634  // If __is_pod (type) is true then the trait is true, else if type is
4635  // a cv class or union type (or array thereof) with a trivial default
4636  // constructor ([class.ctor]) then the trait is true, else it is false.
4637  if (T.isPODType(C))
4638  return true;
4639  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4640  return RD->hasTrivialDefaultConstructor() &&
4641  !RD->hasNonTrivialDefaultConstructor();
4642  return false;
4644  // This trait is implemented by MSVC 2012 and needed to parse the
4645  // standard library headers. Specifically this is used as the logic
4646  // behind std::is_trivially_move_constructible (20.9.4.3).
4647  if (T.isPODType(C))
4648  return true;
4649  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4650  return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4651  return false;
4652  case UTT_HasTrivialCopy:
4653  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4654  // If __is_pod (type) is true or type is a reference type then
4655  // the trait is true, else if type is a cv class or union type
4656  // with a trivial copy constructor ([class.copy]) then the trait
4657  // is true, else it is false.
4658  if (T.isPODType(C) || T->isReferenceType())
4659  return true;
4660  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4661  return RD->hasTrivialCopyConstructor() &&
4662  !RD->hasNonTrivialCopyConstructor();
4663  return false;
4665  // This trait is implemented by MSVC 2012 and needed to parse the
4666  // standard library headers. Specifically it is used as the logic
4667  // behind std::is_trivially_move_assignable (20.9.4.3)
4668  if (T.isPODType(C))
4669  return true;
4670  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4671  return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4672  return false;
4673  case UTT_HasTrivialAssign:
4674  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4675  // If type is const qualified or is a reference type then the
4676  // trait is false. Otherwise if __is_pod (type) is true then the
4677  // trait is true, else if type is a cv class or union type with
4678  // a trivial copy assignment ([class.copy]) then the trait is
4679  // true, else it is false.
4680  // Note: the const and reference restrictions are interesting,
4681  // given that const and reference members don't prevent a class
4682  // from having a trivial copy assignment operator (but do cause
4683  // errors if the copy assignment operator is actually used, q.v.
4684  // [class.copy]p12).
4685 
4686  if (T.isConstQualified())
4687  return false;
4688  if (T.isPODType(C))
4689  return true;
4690  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4691  return RD->hasTrivialCopyAssignment() &&
4692  !RD->hasNonTrivialCopyAssignment();
4693  return false;
4694  case UTT_IsDestructible:
4697  // C++14 [meta.unary.prop]:
4698  // For reference types, is_destructible<T>::value is true.
4699  if (T->isReferenceType())
4700  return true;
4701 
4702  // Objective-C++ ARC: autorelease types don't require destruction.
4703  if (T->isObjCLifetimeType() &&
4705  return true;
4706 
4707  // C++14 [meta.unary.prop]:
4708  // For incomplete types and function types, is_destructible<T>::value is
4709  // false.
4710  if (T->isIncompleteType() || T->isFunctionType())
4711  return false;
4712 
4713  // A type that requires destruction (via a non-trivial destructor or ARC
4714  // lifetime semantics) is not trivially-destructible.
4716  return false;
4717 
4718  // C++14 [meta.unary.prop]:
4719  // For object types and given U equal to remove_all_extents_t<T>, if the
4720  // expression std::declval<U&>().~U() is well-formed when treated as an
4721  // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4722  if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4723  CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4724  if (!Destructor)
4725  return false;
4726  // C++14 [dcl.fct.def.delete]p2:
4727  // A program that refers to a deleted function implicitly or
4728  // explicitly, other than to declare it, is ill-formed.
4729  if (Destructor->isDeleted())
4730  return false;
4731  if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4732  return false;
4733  if (UTT == UTT_IsNothrowDestructible) {
4734  const FunctionProtoType *CPT =
4735  Destructor->getType()->getAs<FunctionProtoType>();
4736  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4737  if (!CPT || !CPT->isNothrow())
4738  return false;
4739  }
4740  }
4741  return true;
4742 
4744  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4745  // If __is_pod (type) is true or type is a reference type
4746  // then the trait is true, else if type is a cv class or union
4747  // type (or array thereof) with a trivial destructor
4748  // ([class.dtor]) then the trait is true, else it is
4749  // false.
4750  if (T.isPODType(C) || T->isReferenceType())
4751  return true;
4752 
4753  // Objective-C++ ARC: autorelease types don't require destruction.
4754  if (T->isObjCLifetimeType() &&
4756  return true;
4757 
4758  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4759  return RD->hasTrivialDestructor();
4760  return false;
4761  // TODO: Propagate nothrowness for implicitly declared special members.
4762  case UTT_HasNothrowAssign:
4763  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4764  // If type is const qualified or is a reference type then the
4765  // trait is false. Otherwise if __has_trivial_assign (type)
4766  // is true then the trait is true, else if type is a cv class
4767  // or union type with copy assignment operators that are known
4768  // not to throw an exception then the trait is true, else it is
4769  // false.
4770  if (C.getBaseElementType(T).isConstQualified())
4771  return false;
4772  if (T->isReferenceType())
4773  return false;
4774  if (T.isPODType(C) || T->isObjCLifetimeType())
4775  return true;
4776 
4777  if (const RecordType *RT = T->getAs<RecordType>())
4778  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4782  return false;
4784  // This trait is implemented by MSVC 2012 and needed to parse the
4785  // standard library headers. Specifically this is used as the logic
4786  // behind std::is_nothrow_move_assignable (20.9.4.3).
4787  if (T.isPODType(C))
4788  return true;
4789 
4790  if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4791  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4795  return false;
4796  case UTT_HasNothrowCopy:
4797  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4798  // If __has_trivial_copy (type) is true then the trait is true, else
4799  // if type is a cv class or union type with copy constructors that are
4800  // known not to throw an exception then the trait is true, else it is
4801  // false.
4802  if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4803  return true;
4804  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4805  if (RD->hasTrivialCopyConstructor() &&
4806  !RD->hasNonTrivialCopyConstructor())
4807  return true;
4808 
4809  bool FoundConstructor = false;
4810  unsigned FoundTQs;
4811  for (const auto *ND : Self.LookupConstructors(RD)) {
4812  // A template constructor is never a copy constructor.
4813  // FIXME: However, it may actually be selected at the actual overload
4814  // resolution point.
4815  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4816  continue;
4817  // UsingDecl itself is not a constructor
4818  if (isa<UsingDecl>(ND))
4819  continue;
4820  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4821  if (Constructor->isCopyConstructor(FoundTQs)) {
4822  FoundConstructor = true;
4823  const FunctionProtoType *CPT
4824  = Constructor->getType()->getAs<FunctionProtoType>();
4825  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4826  if (!CPT)
4827  return false;
4828  // TODO: check whether evaluating default arguments can throw.
4829  // For now, we'll be conservative and assume that they can throw.
4830  if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4831  return false;
4832  }
4833  }
4834 
4835  return FoundConstructor;
4836  }
4837  return false;
4839  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4840  // If __has_trivial_constructor (type) is true then the trait is
4841  // true, else if type is a cv class or union type (or array
4842  // thereof) with a default constructor that is known not to
4843  // throw an exception then the trait is true, else it is false.
4844  if (T.isPODType(C) || T->isObjCLifetimeType())
4845  return true;
4846  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4847  if (RD->hasTrivialDefaultConstructor() &&
4848  !RD->hasNonTrivialDefaultConstructor())
4849  return true;
4850 
4851  bool FoundConstructor = false;
4852  for (const auto *ND : Self.LookupConstructors(RD)) {
4853  // FIXME: In C++0x, a constructor template can be a default constructor.
4854  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4855  continue;
4856  // UsingDecl itself is not a constructor
4857  if (isa<UsingDecl>(ND))
4858  continue;
4859  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4860  if (Constructor->isDefaultConstructor()) {
4861  FoundConstructor = true;
4862  const FunctionProtoType *CPT
4863  = Constructor->getType()->getAs<FunctionProtoType>();
4864  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4865  if (!CPT)
4866  return false;
4867  // FIXME: check whether evaluating default arguments can throw.
4868  // For now, we'll be conservative and assume that they can throw.
4869  if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4870  return false;
4871  }
4872  }
4873  return FoundConstructor;
4874  }
4875  return false;
4877  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4878  // If type is a class type with a virtual destructor ([class.dtor])
4879  // then the trait is true, else it is false.
4880  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4881  if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4882  return Destructor->isVirtual();
4883  return false;
4884 
4885  // These type trait expressions are modeled on the specifications for the
4886  // Embarcadero C++0x type trait functions:
4887  // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4888  case UTT_IsCompleteType:
4889  // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4890  // Returns True if and only if T is a complete type at the point of the
4891  // function call.
4892  return !T->isIncompleteType();
4894  return C.hasUniqueObjectRepresentations(T);
4895  }
4896 }
4897 
4898 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4899  QualType RhsT, SourceLocation KeyLoc);
4900 
4903  SourceLocation RParenLoc) {
4904  if (Kind <= UTT_Last)
4905  return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4906 
4907  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4908  // traits to avoid duplication.
4909  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4910  return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4911  Args[1]->getType(), RParenLoc);
4912 
4913  switch (Kind) {
4918  // C++11 [meta.unary.prop]:
4919  // is_trivially_constructible is defined as:
4920  //
4921  // is_constructible<T, Args...>::value is true and the variable
4922  // definition for is_constructible, as defined below, is known to call
4923  // no operation that is not trivial.
4924  //
4925  // The predicate condition for a template specialization
4926  // is_constructible<T, Args...> shall be satisfied if and only if the
4927  // following variable definition would be well-formed for some invented
4928  // variable t:
4929  //
4930  // T t(create<Args>()...);
4931  assert(!Args.empty());
4932 
4933  // Precondition: T and all types in the parameter pack Args shall be
4934  // complete types, (possibly cv-qualified) void, or arrays of
4935  // unknown bound.
4936  for (const auto *TSI : Args) {
4937  QualType ArgTy = TSI->getType();
4938  if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4939  continue;
4940 
4941  if (S.RequireCompleteType(KWLoc, ArgTy,
4942  diag::err_incomplete_type_used_in_type_trait_expr))
4943  return false;
4944  }
4945 
4946  // Make sure the first argument is not incomplete nor a function type.
4947  QualType T = Args[0]->getType();
4948  if (T->isIncompleteType() || T->isFunctionType())
4949  return false;
4950 
4951  // Make sure the first argument is not an abstract type.
4952  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4953  if (RD && RD->isAbstract())
4954  return false;
4955 
4956  SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4957  SmallVector<Expr *, 2> ArgExprs;
4958  ArgExprs.reserve(Args.size() - 1);
4959  for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4960  QualType ArgTy = Args[I]->getType();
4961  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4962  ArgTy = S.Context.getRValueReferenceType(ArgTy);
4963  OpaqueArgExprs.push_back(
4964  OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4965  ArgTy.getNonLValueExprType(S.Context),
4966  Expr::getValueKindForType(ArgTy)));
4967  }
4968  for (Expr &E : OpaqueArgExprs)
4969  ArgExprs.push_back(&E);
4970 
4971  // Perform the initialization in an unevaluated context within a SFINAE
4972  // trap at translation unit scope.
4975  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4979  RParenLoc));
4980  InitializationSequence Init(S, To, InitKind, ArgExprs);
4981  if (Init.Failed())
4982  return false;
4983 
4984  ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4985  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4986  return false;
4987 
4988  if (Kind == clang::TT_IsConstructible)
4989  return true;
4990 
4992  if (!T->isReferenceType())
4993  return false;
4994 
4995  return !Init.isDirectReferenceBinding();
4996  }
4997 
4999  return S.canThrow(Result.get()) == CT_Cannot;
5000 
5001  if (Kind == clang::TT_IsTriviallyConstructible) {
5002  // Under Objective-C ARC and Weak, if the destination has non-trivial
5003  // Objective-C lifetime, this is a non-trivial construction.
5005  return false;
5006 
5007  // The initialization succeeded; now make sure there are no non-trivial
5008  // calls.
5009  return !Result.get()->hasNonTrivialCall(S.Context);
5010  }
5011 
5012  llvm_unreachable("unhandled type trait");
5013  return false;
5014  }
5015  default: llvm_unreachable("not a TT");
5016  }
5017 
5018  return false;
5019 }
5020 
5023  SourceLocation RParenLoc) {
5024  QualType ResultType = Context.getLogicalOperationType();
5025 
5027  *this, Kind, KWLoc, Args[0]->getType()))
5028  return ExprError();
5029 
5030  bool Dependent = false;
5031  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5032  if (Args[I]->getType()->isDependentType()) {
5033  Dependent = true;
5034  break;
5035  }
5036  }
5037 
5038  bool Result = false;
5039  if (!Dependent)
5040  Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5041 
5042  return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5043  RParenLoc, Result);
5044 }
5045 
5047  ArrayRef<ParsedType> Args,
5048  SourceLocation RParenLoc) {
5049  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5050  ConvertedArgs.reserve(Args.size());
5051 
5052  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5053  TypeSourceInfo *TInfo;
5054  QualType T = GetTypeFromParser(Args[I], &TInfo);
5055  if (!TInfo)
5056  TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5057 
5058  ConvertedArgs.push_back(TInfo);
5059  }
5060 
5061  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5062 }
5063 
5064 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5065  QualType RhsT, SourceLocation KeyLoc) {
5066  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5067  "Cannot evaluate traits of dependent types");
5068 
5069  switch(BTT) {
5070  case BTT_IsBaseOf: {
5071  // C++0x [meta.rel]p2
5072  // Base is a base class of Derived without regard to cv-qualifiers or
5073  // Base and Derived are not unions and name the same class type without
5074  // regard to cv-qualifiers.
5075 
5076  const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5077  const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5078  if (!rhsRecord || !lhsRecord) {
5079  const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5080  const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5081  if (!LHSObjTy || !RHSObjTy)
5082  return false;
5083 
5084  ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5085  ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5086  if (!BaseInterface || !DerivedInterface)
5087  return false;
5088 
5089  if (Self.RequireCompleteType(
5090  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5091  return false;
5092 
5093  return BaseInterface->isSuperClassOf(DerivedInterface);
5094  }
5095 
5096  assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5097  == (lhsRecord == rhsRecord));
5098 
5099  if (lhsRecord == rhsRecord)
5100  return !lhsRecord->getDecl()->isUnion();
5101 
5102  // C++0x [meta.rel]p2:
5103  // If Base and Derived are class types and are different types
5104  // (ignoring possible cv-qualifiers) then Derived shall be a
5105  // complete type.
5106  if (Self.RequireCompleteType(KeyLoc, RhsT,
5107  diag::err_incomplete_type_used_in_type_trait_expr))
5108  return false;
5109 
5110  return cast<CXXRecordDecl>(rhsRecord->getDecl())
5111  ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5112  }
5113  case BTT_IsSame:
5114  return Self.Context.hasSameType(LhsT, RhsT);
5115  case BTT_TypeCompatible: {
5116  // GCC ignores cv-qualifiers on arrays for this builtin.
5117  Qualifiers LhsQuals, RhsQuals;
5118  QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5119  QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5120  return Self.Context.typesAreCompatible(Lhs, Rhs);
5121  }
5122  case BTT_IsConvertible:
5123  case BTT_IsConvertibleTo: {
5124  // C++0x [meta.rel]p4:
5125  // Given the following function prototype:
5126  //
5127  // template <class T>
5128  // typename add_rvalue_reference<T>::type create();
5129  //
5130  // the predicate condition for a template specialization
5131  // is_convertible<From, To> shall be satisfied if and only if
5132  // the return expression in the following code would be
5133  // well-formed, including any implicit conversions to the return
5134  // type of the function:
5135  //
5136  // To test() {
5137  // return create<From>();
5138  // }
5139  //
5140  // Access checking is performed as if in a context unrelated to To and
5141  // From. Only the validity of the immediate context of the expression
5142  // of the return-statement (including conversions to the return type)
5143  // is considered.
5144  //
5145  // We model the initialization as a copy-initialization of a temporary
5146  // of the appropriate type, which for this expression is identical to the
5147  // return statement (since NRVO doesn't apply).
5148 
5149  // Functions aren't allowed to return function or array types.
5150  if (RhsT->isFunctionType() || RhsT->isArrayType())
5151  return false;
5152 
5153  // A return statement in a void function must have void type.
5154  if (RhsT->isVoidType())
5155  return LhsT->isVoidType();
5156 
5157  // A function definition requires a complete, non-abstract return type.
5158  if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5159  return false;
5160 
5161  // Compute the result of add_rvalue_reference.
5162  if (LhsT->isObjectType() || LhsT->isFunctionType())
5163  LhsT = Self.Context.getRValueReferenceType(LhsT);
5164 
5165  // Build a fake source and destination for initialization.
5167  OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5169  Expr *FromPtr = &From;
5171  SourceLocation()));
5172 
5173  // Perform the initialization in an unevaluated context within a SFINAE
5174  // trap at translation unit scope.
5177  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5178  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5179  InitializationSequence Init(Self, To, Kind, FromPtr);
5180  if (Init.Failed())
5181  return false;
5182 
5183  ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5184  return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5185  }
5186 
5187  case BTT_IsAssignable:
5190  // C++11 [meta.unary.prop]p3:
5191  // is_trivially_assignable is defined as:
5192  // is_assignable<T, U>::value is true and the assignment, as defined by
5193  // is_assignable, is known to call no operation that is not trivial
5194  //
5195  // is_assignable is defined as:
5196  // The expression declval<T>() = declval<U>() is well-formed when
5197  // treated as an unevaluated operand (Clause 5).
5198  //
5199  // For both, T and U shall be complete types, (possibly cv-qualified)
5200  // void, or arrays of unknown bound.
5201  if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5202  Self.RequireCompleteType(KeyLoc, LhsT,
5203  diag::err_incomplete_type_used_in_type_trait_expr))
5204  return false;
5205  if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5206  Self.RequireCompleteType(KeyLoc, RhsT,
5207  diag::err_incomplete_type_used_in_type_trait_expr))
5208  return false;
5209 
5210  // cv void is never assignable.
5211  if (LhsT->isVoidType() || RhsT->isVoidType())
5212  return false;
5213 
5214  // Build expressions that emulate the effect of declval<T>() and
5215  // declval<U>().
5216  if (LhsT->isObjectType() || LhsT->isFunctionType())
5217  LhsT = Self.Context.getRValueReferenceType(LhsT);
5218  if (RhsT->isObjectType() || RhsT->isFunctionType())
5219  RhsT = Self.Context.getRValueReferenceType(RhsT);
5220  OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5222  OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5224 
5225  // Attempt the assignment in an unevaluated context within a SFINAE
5226  // trap at translation unit scope.
5229  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5230  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5231  ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5232  &Rhs);
5233  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5234  return false;
5235 
5236  if (BTT == BTT_IsAssignable)
5237  return true;
5238 
5239  if (BTT == BTT_IsNothrowAssignable)
5240  return Self.canThrow(Result.get()) == CT_Cannot;
5241 
5242  if (BTT == BTT_IsTriviallyAssignable) {
5243  // Under Objective-C ARC and Weak, if the destination has non-trivial
5244  // Objective-C lifetime, this is a non-trivial assignment.
5246  return false;
5247 
5248  return !Result.get()->hasNonTrivialCall(Self.Context);
5249  }
5250 
5251  llvm_unreachable("unhandled type trait");
5252  return false;
5253  }
5254  default: llvm_unreachable("not a BTT");
5255  }
5256  llvm_unreachable("Unknown type trait or not implemented");
5257 }
5258 
5260  SourceLocation KWLoc,
5261  ParsedType Ty,
5262  Expr* DimExpr,
5263  SourceLocation RParen) {
5264  TypeSourceInfo *TSInfo;
5265  QualType T = GetTypeFromParser(Ty, &TSInfo);
5266  if (!TSInfo)
5267  TSInfo = Context.getTrivialTypeSourceInfo(T);
5268 
5269  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5270 }
5271 
5272 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5273  QualType T, Expr *DimExpr,
5274  SourceLocation KeyLoc) {
5275  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5276 
5277  switch(ATT) {
5278  case ATT_ArrayRank:
5279  if (T->isArrayType()) {
5280  unsigned Dim = 0;
5281  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5282  ++Dim;
5283  T = AT->getElementType();
5284  }
5285  return Dim;
5286  }
5287  return 0;
5288 
5289  case ATT_ArrayExtent: {
5290  llvm::APSInt Value;
5291  uint64_t Dim;
5292  if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5293  diag::err_dimension_expr_not_constant_integer,
5294  false).isInvalid())
5295  return 0;
5296  if (Value.isSigned() && Value.isNegative()) {
5297  Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5298  << DimExpr->getSourceRange();
5299  return 0;
5300  }
5301  Dim = Value.getLimitedValue();
5302 
5303  if (T->isArrayType()) {
5304  unsigned D = 0;
5305  bool Matched = false;
5306  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5307  if (Dim == D) {
5308  Matched = true;
5309  break;
5310  }
5311  ++D;
5312  T = AT->getElementType();
5313  }
5314 
5315  if (Matched && T->isArrayType()) {
5316  if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5317  return CAT->getSize().getLimitedValue();
5318  }
5319  }
5320  return 0;
5321  }
5322  }
5323  llvm_unreachable("Unknown type trait or not implemented");
5324 }
5325 
5327  SourceLocation KWLoc,
5328  TypeSourceInfo *TSInfo,
5329  Expr* DimExpr,
5330  SourceLocation RParen) {
5331  QualType T = TSInfo->getType();
5332 
5333  // FIXME: This should likely be tracked as an APInt to remove any host
5334  // assumptions about the width of size_t on the target.
5335  uint64_t Value = 0;
5336  if (!T->isDependentType())
5337  Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5338 
5339  // While the specification for these traits from the Embarcadero C++
5340  // compiler's documentation says the return type is 'unsigned int', Clang
5341  // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5342  // compiler, there is no difference. On several other platforms this is an
5343  // important distinction.
5344  return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5345  RParen, Context.getSizeType());
5346 }
5347 
5349  SourceLocation KWLoc,
5350  Expr *Queried,
5351  SourceLocation RParen) {
5352  // If error parsing the expression, ignore.
5353  if (!Queried)
5354  return ExprError();
5355 
5356  ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5357 
5358  return Result;
5359 }
5360 
5362  switch (ET) {
5363  case ET_IsLValueExpr: return E->isLValue();
5364  case ET_IsRValueExpr: return E->isRValue();
5365  }
5366  llvm_unreachable("Expression trait not covered by switch");
5367 }
5368 
5370  SourceLocation KWLoc,
5371  Expr *Queried,
5372  SourceLocation RParen) {
5373  if (Queried->isTypeDependent()) {
5374  // Delay type-checking for type-dependent expressions.
5375  } else if (Queried->getType()->isPlaceholderType()) {
5376  ExprResult PE = CheckPlaceholderExpr(Queried);
5377  if (PE.isInvalid()) return ExprError();
5378  return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5379  }
5380 
5381  bool Value = EvaluateExpressionTrait(ET, Queried);
5382 
5383  return new (Context)
5384  ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5385 }
5386 
5388  ExprValueKind &VK,
5389  SourceLocation Loc,
5390  bool isIndirect) {
5391  assert(!LHS.get()->getType()->isPlaceholderType() &&
5392  !RHS.get()->getType()->isPlaceholderType() &&
5393  "placeholders should have been weeded out by now");
5394 
5395  // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5396  // temporary materialization conversion otherwise.
5397  if (isIndirect)
5398  LHS = DefaultLvalueConversion(LHS.get());
5399  else if (LHS.get()->isRValue())
5401  if (LHS.isInvalid())
5402  return QualType();
5403 
5404  // The RHS always undergoes lvalue conversions.
5405  RHS = DefaultLvalueConversion(RHS.get());
5406  if (RHS.isInvalid()) return QualType();
5407 
5408  const char *OpSpelling = isIndirect ? "->*" : ".*";
5409  // C++ 5.5p2
5410  // The binary operator .* [p3: ->*] binds its second operand, which shall
5411  // be of type "pointer to member of T" (where T is a completely-defined
5412  // class type) [...]
5413  QualType RHSType = RHS.get()->getType();
5414  const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5415  if (!MemPtr) {
5416  Diag(Loc, diag::err_bad_memptr_rhs)
5417  << OpSpelling << RHSType << RHS.get()->getSourceRange();
5418  return QualType();
5419  }
5420 
5421  QualType Class(MemPtr->getClass(), 0);
5422 
5423  // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5424  // member pointer points must be completely-defined. However, there is no
5425  // reason for this semantic distinction, and the rule is not enforced by
5426  // other compilers. Therefore, we do not check this property, as it is
5427  // likely to be considered a defect.
5428 
5429  // C++ 5.5p2
5430  // [...] to its first operand, which shall be of class T or of a class of
5431  // which T is an unambiguous and accessible base class. [p3: a pointer to
5432  // such a class]
5433  QualType LHSType = LHS.get()->getType();
5434  if (isIndirect) {
5435  if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5436  LHSType = Ptr->getPointeeType();
5437  else {
5438  Diag(Loc, diag::err_bad_memptr_lhs)
5439  << OpSpelling << 1 << LHSType
5441  return QualType();
5442  }
5443  }
5444 
5445  if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5446  // If we want to check the hierarchy, we need a complete type.
5447  if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5448  OpSpelling, (int)isIndirect)) {
5449  return QualType();
5450  }
5451 
5452  if (!IsDerivedFrom(Loc, LHSType, Class)) {
5453  Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5454  << (int)isIndirect << LHS.get()->getType();
5455  return QualType();
5456  }
5457 
5458  CXXCastPath BasePath;
5460  LHSType, Class, Loc,
5461  SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5462  &BasePath))
5463  return QualType();
5464 
5465  // Cast LHS to type of use.
5466  QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5467  if (isIndirect)
5468  UseType = Context.getPointerType(UseType);
5469  ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5470  LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5471  &BasePath);
5472  }
5473 
5474  if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5475  // Diagnose use of pointer-to-member type which when used as
5476  // the functional cast in a pointer-to-member expression.
5477  Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5478  return QualType();
5479  }
5480 
5481  // C++ 5.5p2
5482  // The result is an object or a function of the type specified by the
5483  // second operand.
5484  // The cv qualifiers are the union of those in the pointer and the left side,
5485  // in accordance with 5.5p5 and 5.2.5.
5486  QualType Result = MemPtr->getPointeeType();
5487  Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5488 
5489  // C++0x [expr.mptr.oper]p6:
5490  // In a .* expression whose object expression is an rvalue, the program is
5491  // ill-formed if the second operand is a pointer to member function with
5492  // ref-qualifier &. In a ->* expression or in a .* expression whose object
5493  // expression is an lvalue, the program is ill-formed if the second operand
5494  // is a pointer to member function with ref-qualifier &&.
5495  if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5496  switch (Proto->getRefQualifier()) {
5497  case RQ_None:
5498  // Do nothing
5499  break;
5500 
5501  case RQ_LValue:
5502  if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5503  // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5504  // is (exactly) 'const'.
5505  if (Proto->isConst() && !Proto->isVolatile())
5506  Diag(Loc, getLangOpts().CPlusPlus2a
5507  ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5508  : diag::ext_pointer_to_const_ref_member_on_rvalue);
5509  else
5510  Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5511  << RHSType << 1 << LHS.get()->getSourceRange();
5512  }
5513  break;
5514 
5515  case RQ_RValue:
5516  if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5517  Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5518  << RHSType << 0 << LHS.get()->getSourceRange();
5519  break;
5520  }
5521  }
5522 
5523  // C++ [expr.mptr.oper]p6:
5524  // The result of a .* expression whose second operand is a pointer
5525  // to a data member is of the same value category as its
5526  // first operand. The result of a .* expression whose second
5527  // operand is a pointer to a member function is a prvalue. The
5528  // result of an ->* expression is an lvalue if its second operand
5529  // is a pointer to data member and a prvalue otherwise.
5530  if (Result->isFunctionType()) {
5531  VK = VK_RValue;
5532  return Context.BoundMemberTy;
5533  } else if (isIndirect) {
5534  VK = VK_LValue;
5535  } else {
5536  VK = LHS.get()->getValueKind();
5537  }
5538 
5539  return Result;
5540 }
5541 
5542 /// Try to convert a type to another according to C++11 5.16p3.
5543 ///
5544 /// This is part of the parameter validation for the ? operator. If either
5545 /// value operand is a class type, the two operands are attempted to be
5546 /// converted to each other. This function does the conversion in one direction.
5547 /// It returns true if the program is ill-formed and has already been diagnosed
5548 /// as such.
5549 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5550  SourceLocation QuestionLoc,
5551  bool &HaveConversion,
5552  QualType &ToType) {
5553  HaveConversion = false;
5554  ToType = To->getType();
5555 
5558  // C++11 5.16p3
5559  // The process for determining whether an operand expression E1 of type T1
5560  // can be converted to match an operand expression E2 of type T2 is defined
5561  // as follows:
5562  // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5563  // implicitly converted to type "lvalue reference to T2", subject to the
5564  // constraint that in the conversion the reference must bind directly to
5565  // an lvalue.
5566  // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5567  // implicitly converted to the type "rvalue reference to R2", subject to
5568  // the constraint that the reference must bind directly.
5569  if (To->isLValue() || To->isXValue()) {
5570  QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5571  : Self.Context.getRValueReferenceType(ToType);
5572 
5574 
5575  InitializationSequence InitSeq(Self, Entity, Kind, From);
5576  if (InitSeq.isDirectReferenceBinding()) {
5577  ToType = T;
5578  HaveConversion = true;
5579  return false;
5580  }
5581 
5582  if (InitSeq.isAmbiguous())
5583  return InitSeq.Diagnose(Self, Entity, Kind, From);
5584  }
5585 
5586  // -- If E2 is an rvalue, or if the conversion above cannot be done:
5587  // -- if E1 and E2 have class type, and the underlying class types are
5588  // the same or one is a base class of the other:
5589  QualType FTy = From->getType();
5590  QualType TTy = To->getType();
5591  const RecordType *FRec = FTy->getAs<RecordType>();
5592  const RecordType *TRec = TTy->getAs<RecordType>();
5593  bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5594  Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5595  if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5596  Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5597  // E1 can be converted to match E2 if the class of T2 is the
5598  // same type as, or a base class of, the class of T1, and
5599  // [cv2 > cv1].
5600  if (FRec == TRec || FDerivedFromT) {
5601  if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5603  InitializationSequence InitSeq(Self, Entity, Kind, From);
5604  if (InitSeq) {
5605  HaveConversion = true;
5606  return false;
5607  }
5608 
5609  if (InitSeq.isAmbiguous())
5610  return InitSeq.Diagnose(Self, Entity, Kind, From);
5611  }
5612  }
5613 
5614  return false;
5615  }
5616 
5617  // -- Otherwise: E1 can be converted to match E2 if E1 can be
5618  // implicitly converted to the type that expression E2 would have
5619  // if E2 were converted to an rvalue (or the type it has, if E2 is
5620  // an rvalue).
5621  //
5622  // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5623  // to the array-to-pointer or function-to-pointer conversions.
5624  TTy = TTy.getNonLValueExprType(Self.Context);
5625 
5627  InitializationSequence InitSeq(Self, Entity, Kind, From);
5628  HaveConversion = !InitSeq.Failed();
5629  ToType = TTy;
5630  if (InitSeq.isAmbiguous())
5631  return InitSeq.Diagnose(Self, Entity, Kind, From);
5632 
5633  return false;
5634 }
5635 
5636 /// Try to find a common type for two according to C++0x 5.16p5.
5637 ///
5638 /// This is part of the parameter validation for the ? operator. If either
5639 /// value operand is a class type, overload resolution is used to find a
5640 /// conversion to a common type.
5641 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5642  SourceLocation QuestionLoc) {
5643  Expr *Args[2] = { LHS.get(), RHS.get() };
5644  OverloadCandidateSet CandidateSet(QuestionLoc,
5646  Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5647  CandidateSet);
5648 
5650  switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5651  case OR_Success: {
5652  // We found a match. Perform the conversions on the arguments and move on.
5653  ExprResult LHSRes = Self.PerformImplicitConversion(
5654  LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5656  if (LHSRes.isInvalid())
5657  break;
5658  LHS = LHSRes;
5659 
5660  ExprResult RHSRes = Self.PerformImplicitConversion(
5661  RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5663  if (RHSRes.isInvalid())
5664  break;
5665  RHS = RHSRes;
5666  if (Best->Function)
5667  Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5668  return false;
5669  }
5670 
5671  case OR_No_Viable_Function:
5672 
5673  // Emit a better diagnostic if one of the expressions is a null pointer
5674  // constant and the other is a pointer type. In this case, the user most
5675  // likely forgot to take the address of the other expression.
5676  if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5677  return true;
5678 
5679  Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5680  << LHS.get()->getType() << RHS.get()->getType()
5681  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5682  return true;
5683 
5684  case OR_Ambiguous:
5685  Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5686  << LHS.get()->getType() << RHS.get()->getType()
5687  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5688  // FIXME: Print the possible common types by printing the return types of
5689  // the viable candidates.
5690  break;
5691 
5692  case OR_Deleted:
5693  llvm_unreachable("Conditional operator has only built-in overloads");
5694  }
5695  return true;
5696 }
5697 
5698 /// Perform an "extended" implicit conversion as returned by
5699 /// TryClassUnification.
5700 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5703  InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5704  Expr *Arg = E.get();
5705  InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5706  ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5707  if (Result.isInvalid())
5708  return true;
5709 
5710  E = Result;
5711  return false;
5712 }
5713 
5714 /// Check the operands of ?: under C++ semantics.
5715 ///
5716 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5717 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5719  ExprResult &RHS, ExprValueKind &VK,
5720  ExprObjectKind &OK,
5721  SourceLocation QuestionLoc) {
5722  // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5723  // interface pointers.
5724 
5725  // C++11 [expr.cond]p1
5726  // The first expression is contextually converted to bool.
5727  //
5728  // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5729  // a is that of a integer vector with the same number of elements and
5730  // size as the vectors of b and c. If one of either b or c is a scalar
5731  // it is implicitly converted to match the type of the vector.
5732  // Otherwise the expression is ill-formed. If both b and c are scalars,
5733  // then b and c are checked and converted to the type of a if possible.
5734  // Unlike the OpenCL ?: operator, the expression is evaluated as
5735  // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5736  if (!Cond.get()->isTypeDependent()) {
5737  ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5738  if (CondRes.isInvalid())
5739  return QualType();
5740  Cond = CondRes;
5741  }
5742 
5743  // Assume r-value.
5744  VK = VK_RValue;
5745  OK = OK_Ordinary;
5746 
5747  // Either of the arguments dependent?
5748  if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5749  return Context.DependentTy;
5750 
5751  // C++11 [expr.cond]p2
5752  // If either the second or the third operand has type (cv) void, ...
5753  QualType LTy = LHS.get()->getType();
5754  QualType RTy = RHS.get()->getType();
5755  bool LVoid = LTy->isVoidType();
5756  bool RVoid = RTy->isVoidType();
5757  if (LVoid || RVoid) {
5758  // ... one of the following shall hold:
5759  // -- The second or the third operand (but not both) is a (possibly
5760  // parenthesized) throw-expression; the result is of the type
5761  // and value category of the other.
5762  bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5763  bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5764  if (LThrow != RThrow) {
5765  Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5766  VK = NonThrow->getValueKind();
5767  // DR (no number yet): the result is a bit-field if the
5768  // non-throw-expression operand is a bit-field.
5769  OK = NonThrow->getObjectKind();
5770  return NonThrow->getType();
5771  }
5772 
5773  // -- Both the second and third operands have type void; the result is of
5774  // type void and is a prvalue.
5775  if (LVoid && RVoid)
5776  return Context.VoidTy;
5777 
5778  // Neither holds, error.
5779  Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5780  << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5781  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5782  return QualType();
5783  }
5784 
5785  // Neither is void.
5786 
5787  // C++11 [expr.cond]p3
5788  // Otherwise, if the second and third operand have different types, and
5789  // either has (cv) class type [...] an attempt is made to convert each of
5790  // those operands to the type of the other.
5791  if (!Context.hasSameType(LTy, RTy) &&
5792  (LTy->isRecordType() || RTy->isRecordType())) {
5793  // These return true if a single direction is already ambiguous.
5794  QualType L2RType, R2LType;
5795  bool HaveL2R, HaveR2L;
5796  if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5797  return QualType();
5798  if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5799  return QualType();
5800 
5801  // If both can be converted, [...] the program is ill-formed.
5802  if (HaveL2R && HaveR2L) {
5803  Diag(QuestionLoc, diag::err_conditional_ambiguous)
5804  << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5805  return QualType();
5806  }
5807 
5808  // If exactly one conversion is possible, that conversion is applied to
5809  // the chosen operand and the converted operands are used in place of the
5810  // original operands for the remainder of this section.
5811  if (HaveL2R) {
5812  if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5813  return QualType();
5814  LTy = LHS.get()->getType();
5815  } else if (HaveR2L) {
5816  if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5817  return QualType();
5818  RTy = RHS.get()->getType();
5819  }
5820  }
5821 
5822  // C++11 [expr.cond]p3
5823  // if both are glvalues of the same value category and the same type except
5824  // for cv-qualification, an attempt is made to convert each of those
5825  // operands to the type of the other.
5826  // FIXME:
5827  // Resolving a defect in P0012R1: we extend this to cover all cases where
5828  // one of the operands is reference-compatible with the other, in order
5829  // to support conditionals between functions differing in noexcept.
5830  ExprValueKind LVK = LHS.get()->getValueKind();
5831  ExprValueKind RVK = RHS.get()->getValueKind();
5832  if (!Context.hasSameType(LTy, RTy) &&
5833  LVK == RVK && LVK != VK_RValue) {
5834  // DerivedToBase was already handled by the class-specific case above.
5835  // FIXME: Should we allow ObjC conversions here?
5836  bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5838  QuestionLoc, LTy, RTy, DerivedToBase,
5839  ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5840  !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5841  // [...] subject to the constraint that the reference must bind
5842  // directly [...]
5843  !RHS.get()->refersToBitField() &&
5844  !RHS.get()->refersToVectorElement()) {
5845  RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5846  RTy = RHS.get()->getType();
5847  } else if (CompareReferenceRelationship(
5848  QuestionLoc, RTy, LTy, DerivedToBase,
5849  ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5850  !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5851  !LHS.get()->refersToBitField() &&
5852  !LHS.get()->refersToVectorElement()) {
5853  LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5854  LTy = LHS.get()->getType();
5855  }
5856  }
5857 
5858  // C++11 [expr.cond]p4
5859  // If the second and third operands are glvalues of the same value
5860  // category and have the same type, the result is of that type and
5861  // value category and it is a bit-field if the second or the third
5862  // operand is a bit-field, or if both are bit-fields.
5863  // We only extend this to bitfields, not to the crazy other kinds of
5864  // l-values.
5865  bool Same = Context.hasSameType(LTy, RTy);
5866  if (Same && LVK == RVK && LVK != VK_RValue &&
5867  LHS.get()->isOrdinaryOrBitFieldObject() &&
5868  RHS.get()->isOrdinaryOrBitFieldObject()) {
5869  VK = LHS.get()->getValueKind();
5870  if (LHS.get()->getObjectKind() == OK_BitField ||
5871  RHS.get()->getObjectKind() == OK_BitField)
5872  OK = OK_BitField;
5873 
5874  // If we have function pointer types, unify them anyway to unify their
5875  // exception specifications, if any.
5876  if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5877  Qualifiers Qs = LTy.getQualifiers();
5878  LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5879  /*ConvertArgs*/false);
5880  LTy = Context.getQualifiedType(LTy, Qs);
5881 
5882  assert(!LTy.isNull() && "failed to find composite pointer type for "
5883  "canonically equivalent function ptr types");
5884  assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5885  }
5886 
5887  return LTy;
5888  }
5889 
5890  // C++11 [expr.cond]p5
5891  // Otherwise, the result is a prvalue. If the second and third operands
5892  // do not have the same type, and either has (cv) class type, ...
5893  if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5894  // ... overload resolution is used to determine the conversions (if any)
5895  // to be applied to the operands. If the overload resolution fails, the
5896  // program is ill-formed.
5897  if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5898  return QualType();
5899  }
5900 
5901  // C++11 [expr.cond]p6
5902  // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5903  // conversions are performed on the second and third operands.
5905  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5906  if (LHS.isInvalid() || RHS.isInvalid())
5907  return QualType();
5908  LTy = LHS.get()->getType();
5909  RTy = RHS.get()->getType();
5910 
5911  // After those conversions, one of the following shall hold:
5912  // -- The second and third operands have the same type; the result
5913  // is of that type. If the operands have class type, the result
5914  // is a prvalue temporary of the result type, which is
5915  // copy-initialized from either the second operand or the third
5916  // operand depending on the value of the first operand.
5917  if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5918  if (LTy->isRecordType()) {
5919  // The operands have class type. Make a temporary copy.
5921 
5922  ExprResult LHSCopy = PerformCopyInitialization(Entity,
5923  SourceLocation(),
5924  LHS);
5925  if (LHSCopy.isInvalid())
5926  return QualType();
5927 
5928  ExprResult RHSCopy = PerformCopyInitialization(Entity,
5929  SourceLocation(),
5930  RHS);
5931  if (RHSCopy.isInvalid())
5932  return QualType();
5933 
5934  LHS = LHSCopy;
5935  RHS = RHSCopy;
5936  }
5937 
5938  // If we have function pointer types, unify them anyway to unify their
5939  // exception specifications, if any.
5940  if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5941  LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5942  assert(!LTy.isNull() && "failed to find composite pointer type for "
5943  "canonically equivalent function ptr types");
5944  }
5945 
5946  return LTy;
5947  }
5948 
5949  // Extension: conditional operator involving vector types.
5950  if (LTy->isVectorType() || RTy->isVectorType())
5951  return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5952  /*AllowBothBool*/true,
5953  /*AllowBoolConversions*/false);
5954 
5955  // -- The second and third operands have arithmetic or enumeration type;
5956  // the usual arithmetic conversions are performed to bring them to a
5957  // common type, and the result is of that type.
5958  if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5959  QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5960  if (LHS.isInvalid() || RHS.isInvalid())
5961  return QualType();
5962  if (ResTy.isNull()) {
5963  Diag(QuestionLoc,
5964  diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5965  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5966  return QualType();
5967  }
5968 
5969  LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5970  RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5971 
5972  return ResTy;
5973  }
5974 
5975  // -- The second and third operands have pointer type, or one has pointer
5976  // type and the other is a null pointer constant, or both are null
5977  // pointer constants, at least one of which is non-integral; pointer
5978  // conversions and qualification conversions are performed to bring them
5979  // to their composite pointer type. The result is of the composite
5980  // pointer type.
5981  // -- The second and third operands have pointer to member type, or one has
5982  // pointer to member type and the other is a null pointer constant;
5983  // pointer to member conversions and qualification conversions are
5984  // performed to bring them to a common type, whose cv-qualification
5985  // shall match the cv-qualification of either the second or the third
5986  // operand. The result is of the common type.
5987  QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5988  if (!Composite.isNull())
5989  return Composite;
5990 
5991  // Similarly, attempt to find composite type of two objective-c pointers.
5992  Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5993  if (!Composite.isNull())
5994  return Composite;
5995 
5996  // Check if we are using a null with a non-pointer type.
5997  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5998  return QualType();
5999 
6000  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6001  << LHS.get()->getType() << RHS.get()->getType()
6002  << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6003  return QualType();
6004 }
6005 
6009  SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6010  ExceptionSpecificationType EST1 = ESI1.Type;
6011  ExceptionSpecificationType EST2 = ESI2.Type;
6012 
6013  // If either of them can throw anything, that is the result.
6014  if (EST1 == EST_None) return ESI1;
6015  if (EST2 == EST_None) return ESI2;
6016  if (EST1 == EST_MSAny) return ESI1;
6017  if (EST2 == EST_MSAny) return ESI2;
6018  if (EST1 == EST_NoexceptFalse) return ESI1;
6019  if (EST2 == EST_NoexceptFalse) return ESI2;
6020 
6021  // If either of them is non-throwing, the result is the other.
6022  if (EST1 == EST_DynamicNone) return ESI2;
6023  if (EST2 == EST_DynamicNone) return ESI1;
6024  if (EST1 == EST_BasicNoexcept) return ESI2;
6025  if (EST2 == EST_BasicNoexcept) return ESI1;
6026  if (EST1 == EST_NoexceptTrue) return ESI2;
6027  if (EST2 == EST_NoexceptTrue) return ESI1;
6028 
6029  // If we're left with value-dependent computed noexcept expressions, we're
6030  // stuck. Before C++17, we can just drop the exception specification entirely,
6031  // since it's not actually part of the canonical type. And this should never
6032  // happen in C++17, because it would mean we were computing the composite
6033  // pointer type of dependent types, which should never happen.
6034  if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6035  assert(!S.getLangOpts().CPlusPlus17 &&
6036  "computing composite pointer type of dependent types");
6038  }
6039 
6040  // Switch over the possibilities so that people adding new values know to
6041  // update this function.
6042  switch (EST1) {
6043  case EST_None:
6044  case EST_DynamicNone:
6045  case EST_MSAny:
6046  case EST_BasicNoexcept:
6047  case EST_DependentNoexcept:
6048  case EST_NoexceptFalse:
6049  case EST_NoexceptTrue:
6050  llvm_unreachable("handled above");
6051 
6052  case EST_Dynamic: {
6053  // This is the fun case: both exception specifications are dynamic. Form
6054  // the union of the two lists.
6055  assert(EST2 == EST_Dynamic && "other cases should already be handled");
6056  llvm::SmallPtrSet<QualType, 8> Found;
6057  for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6058  for (QualType E : Exceptions)
6059  if (Found.insert(S.Context.getCanonicalType(E)).second)
6060  ExceptionTypeStorage.push_back(E);
6061 
6063  Result.Exceptions = ExceptionTypeStorage;
6064  return Result;
6065  }
6066 
6067  case EST_Unevaluated:
6068  case EST_Uninstantiated:
6069  case EST_Unparsed:
6070  llvm_unreachable("shouldn't see unresolved exception specifications here");
6071  }
6072 
6073  llvm_unreachable("invalid ExceptionSpecificationType");
6074 }
6075 
6076 /// Find a merged pointer type and convert the two expressions to it.
6077 ///
6078 /// This finds the composite pointer type (or member pointer type) for @p E1
6079 /// and @p E2 according to C++1z 5p14. It converts both expressions to this
6080 /// type and returns it.
6081 /// It does not emit diagnostics.
6082 ///
6083 /// \param Loc The location of the operator requiring these two expressions to
6084 /// be converted to the composite pointer type.
6085 ///
6086 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6088  Expr *&E1, Expr *&E2,
6089  bool ConvertArgs) {
6090  assert(getLangOpts().CPlusPlus && "This function assumes C++");
6091 
6092  // C++1z [expr]p14:
6093  // The composite pointer type of two operands p1 and p2 having types T1
6094  // and T2
6095  QualType T1 = E1->getType(), T2 = E2->getType();
6096 
6097  // where at least one is a pointer or pointer to member type or
6098  // std::nullptr_t is:
6099  bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6100  T1->isNullPtrType();
6101  bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6102  T2->isNullPtrType();
6103  if (!T1IsPointerLike && !T2IsPointerLike)
6104  return QualType();
6105 
6106  // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6107  // This can't actually happen, following the standard, but we also use this
6108  // to implement the end of [expr.conv], which hits this case.
6109  //
6110  // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6111  if (T1IsPointerLike &&
6113  if (ConvertArgs)
6114  E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6115  ? CK_NullToMemberPointer
6116  : CK_NullToPointer).get();
6117  return T1;
6118  }
6119  if (T2IsPointerLike &&
6121  if (ConvertArgs)
6122  E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6123  ? CK_NullToMemberPointer
6124  : CK_NullToPointer).get();
6125  return T2;
6126  }
6127 
6128  // Now both have to be pointers or member pointers.
6129  if (!T1IsPointerLike || !T2IsPointerLike)
6130  return QualType();
6131  assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6132  "nullptr_t should be a null pointer constant");
6133 
6134  // - if T1 or T2 is "pointer to cv1 void" and the other type is
6135  // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6136  // the union of cv1 and cv2;
6137  // - if T1 or T2 is "pointer to noexcept function" and the other type is
6138  // "pointer to function", where the function types are otherwise the same,
6139  // "pointer to function";
6140  // FIXME: This rule is defective: it should also permit removing noexcept
6141  // from a pointer to member function. As a Clang extension, we also
6142  // permit removing 'noreturn', so we generalize this rule to;
6143  // - [Clang] If T1 and T2 are both of type "pointer to function" or
6144  // "pointer to member function" and the pointee types can be unified
6145  // by a function pointer conversion, that conversion is applied
6146  // before checking the following rules.
6147  // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6148  // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6149  // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6150  // respectively;
6151  // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6152  // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6153  // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6154  // T1 or the cv-combined type of T1 and T2, respectively;
6155  // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6156  // T2;
6157  //
6158  // If looked at in the right way, these bullets all do the same thing.
6159  // What we do here is, we build the two possible cv-combined types, and try
6160  // the conversions in both directions. If only one works, or if the two
6161  // composite types are the same, we have succeeded.
6162  // FIXME: extended qualifiers?
6163  //
6164  // Note that this will fail to find a composite pointer type for "pointer
6165  // to void" and "pointer to function". We can't actually perform the final
6166  // conversion in this case, even though a composite pointer type formally
6167  // exists.
6168  SmallVector<unsigned, 4> QualifierUnion;
6170  QualType Composite1 = T1;
6171  QualType Composite2 = T2;
6172  unsigned NeedConstBefore = 0;
6173  while (true) {
6174  const PointerType *Ptr1, *Ptr2;
6175  if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6176  (Ptr2 = Composite2->getAs<PointerType>())) {
6177  Composite1 = Ptr1->getPointeeType();
6178  Composite2 = Ptr2->getPointeeType();
6179 
6180  // If we're allowed to create a non-standard composite type, keep track
6181  // of where we need to fill in additional 'const' qualifiers.
6182  if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6183  NeedConstBefore = QualifierUnion.size();
6184 
6185  QualifierUnion.push_back(
6186  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6187  MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
6188  continue;
6189  }
6190 
6191  const MemberPointerType *MemPtr1, *MemPtr2;
6192  if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6193  (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6194  Composite1 = MemPtr1->getPointeeType();
6195  Composite2 = MemPtr2->getPointeeType();
6196 
6197  // If we're allowed to create a non-standard composite type, keep track
6198  // of where we need to fill in additional 'const' qualifiers.
6199  if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6200  NeedConstBefore = QualifierUnion.size();
6201 
6202  QualifierUnion.push_back(
6203  Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6204  MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6205  MemPtr2->getClass()));
6206  continue;
6207  }
6208 
6209  // FIXME: block pointer types?
6210 
6211  // Cannot unwrap any more types.
6212  break;
6213  }
6214 
6215  // Apply the function pointer conversion to unify the types. We've already
6216  // unwrapped down to the function types, and we want to merge rather than
6217  // just convert, so do this ourselves rather than calling
6218  // IsFunctionConversion.
6219  //
6220  // FIXME: In order to match the standard wording as closely as possible, we
6221  // currently only do this under a single level of pointers. Ideally, we would
6222  // allow this in general, and set NeedConstBefore to the relevant depth on
6223  // the side(s) where we changed anything.
6224  if (QualifierUnion.size() == 1) {
6225  if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6226  if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6227  FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6228  FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6229 
6230  // The result is noreturn if both operands are.
6231  bool Noreturn =
6232  EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6233  EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6234  EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6235 
6236  // The result is nothrow if both operands are.
6237  SmallVector<QualType, 8> ExceptionTypeStorage;
6238  EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6240  ExceptionTypeStorage);
6241 
6242  Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6243  FPT1->getParamTypes(), EPI1);
6244  Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6245  FPT2->getParamTypes(), EPI2);
6246  }
6247  }
6248  }
6249 
6250  if (NeedConstBefore) {
6251  // Extension: Add 'const' to qualifiers that come before the first qualifier
6252  // mismatch, so that our (non-standard!) composite type meets the
6253  // requirements of C++ [conv.qual]p4 bullet 3.
6254  for (unsigned I = 0; I != NeedConstBefore; ++I)
6255  if ((QualifierUnion[I] & Qualifiers::Const) == 0)
6256  QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
6257  }
6258 
6259  // Rewrap the composites as pointers or member pointers with the union CVRs.
6260  auto MOC = MemberOfClass.rbegin();
6261  for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6262  Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6263  auto Classes = *MOC++;
6264  if (Classes.first && Classes.second) {
6265  // Rebuild member pointer type
6266  Composite1 = Context.getMemberPointerType(
6267  Context.getQualifiedType(Composite1, Quals), Classes.first);
6268  Composite2 = Context.getMemberPointerType(
6269  Context.getQualifiedType(Composite2, Quals), Classes.second);
6270  } else {
6271  // Rebuild pointer type
6272  Composite1 =
6273  Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6274  Composite2 =
6275  Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
6276  }
6277  }
6278 
6279  struct Conversion {
6280  Sema &S;
6281  Expr *&E1, *&E2;
6282  QualType Composite;
6283  InitializedEntity Entity;
6285  InitializationSequence E1ToC, E2ToC;
6286  bool Viable;
6287 
6288  Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6289  QualType Composite)
6290  : S(S), E1(E1), E2(E2), Composite(Composite),
6291  Entity(InitializedEntity::InitializeTemporary(Composite)),
6293  E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6294  Viable(E1ToC && E2ToC) {}
6295 
6296  bool perform() {
6297  ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6298  if (E1Result.isInvalid())
6299  return true;
6300  E1 = E1Result.getAs<Expr>();
6301 
6302  ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6303  if (E2Result.isInvalid())
6304  return true;
6305  E2 = E2Result.getAs<Expr>();
6306 
6307  return false;
6308  }
6309  };
6310 
6311  // Try to convert to each composite pointer type.
6312  Conversion C1(*this, Loc, E1, E2, Composite1);
6313  if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6314  if (ConvertArgs && C1.perform())
6315  return QualType();
6316  return C1.Composite;
6317  }
6318  Conversion C2(*this, Loc, E1, E2, Composite2);
6319 
6320  if (C1.Viable == C2.Viable) {
6321  // Either Composite1 and Composite2 are viable and are different, or
6322  // neither is viable.
6323  // FIXME: How both be viable and different?
6324  return QualType();
6325  }
6326 
6327  // Convert to the chosen type.
6328  if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6329  return QualType();
6330 
6331  return C1.Viable ? C1.Composite : C2.Composite;
6332 }
6333 
6335  if (!E)
6336  return ExprError();
6337 
6338  assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6339 
6340  // If the result is a glvalue, we shouldn't bind it.
6341  if (!E->isRValue())
6342  return E;
6343 
6344  // In ARC, calls that return a retainable type can return retained,
6345  // in which case we have to insert a consuming cast.
6346  if (getLangOpts().ObjCAutoRefCount &&
6347  E->getType()->isObjCRetainableType()) {
6348 
6349  bool ReturnsRetained;
6350 
6351  // For actual calls, we compute this by examining the type of the
6352  // called value.
6353  if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6354  Expr *Callee = Call->getCallee()->IgnoreParens();
6355  QualType T = Callee->getType();
6356 
6357  if (T == Context.BoundMemberTy) {
6358  // Handle pointer-to-members.
6359  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6360  T = BinOp->getRHS()->getType();
6361  else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6362  T = Mem->getMemberDecl()->getType();
6363  }
6364 
6365  if (const PointerType *Ptr = T->getAs<PointerType>())
6366  T = Ptr->getPointeeType();
6367  else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6368  T = Ptr->getPointeeType();
6369  else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6370  T = MemPtr->getPointeeType();
6371 
6372  const FunctionType *FTy = T->getAs<FunctionType>();
6373  assert(FTy && "call to value not of function type?");
6374  ReturnsRetained = FTy->getExtInfo().getProducesResult();
6375 
6376  // ActOnStmtExpr arranges things so that StmtExprs of retainable
6377  // type always produce a +1 object.
6378  } else if (isa<StmtExpr>(E)) {
6379  ReturnsRetained = true;
6380 
6381  // We hit this case with the lambda conversion-to-block optimization;
6382  // we don't want any extra casts here.
6383  } else if (isa<CastExpr>(E) &&
6384  isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6385  return E;
6386 
6387  // For message sends and property references, we try to find an
6388  // actual method. FIXME: we should infer retention by selector in
6389  // cases where we don't have an actual method.
6390  } else {
6391  ObjCMethodDecl *D = nullptr;
6392  if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6393  D = Send->getMethodDecl();
6394  } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6395  D = BoxedExpr->getBoxingMethod();
6396  } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6397  // Don't do reclaims if we're using the zero-element array
6398  // constant.
6399  if (ArrayLit->getNumElements() == 0 &&
6401  return E;
6402 
6403  D = ArrayLit->getArrayWithObjectsMethod();
6404  } else if (ObjCDictionaryLiteral *DictLit
6405  = dyn_cast<ObjCDictionaryLiteral>(E)) {
6406  // Don't do reclaims if we're using the zero-element dictionary
6407  // constant.
6408  if (DictLit->getNumElements() == 0 &&
6410  return E;
6411 
6412  D = DictLit->getDictWithObjectsMethod();
6413  }
6414 
6415  ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6416 
6417  // Don't do reclaims on performSelector calls; despite their
6418  // return type, the invoked method doesn't necessarily actually
6419  // return an object.
6420  if (!ReturnsRetained &&
6421  D && D->getMethodFamily() == OMF_performSelector)
6422  return E;
6423  }
6424 
6425  // Don't reclaim an object of Class type.
6426  if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6427  return E;
6428 
6430 
6431  CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6432  : CK_ARCReclaimReturnedObject);
6433  return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6434  VK_RValue);
6435  }
6436 
6437  if (!getLangOpts().CPlusPlus)
6438  return E;
6439 
6440  // Search for the base element type (cf. ASTContext::getBaseElementType) with
6441  // a fast path for the common case that the type is directly a RecordType.
6442  const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6443  const RecordType *RT = nullptr;
6444  while (!RT) {
6445  switch (T->getTypeClass()) {
6446  case Type::Record:
6447  RT = cast<RecordType>(T);
6448  break;
6449  case Type::ConstantArray:
6450  case Type::IncompleteArray:
6451  case Type::VariableArray:
6452  case Type::DependentSizedArray:
6453  T = cast<ArrayType>(T)->getElementType().getTypePtr();
6454  break;
6455  default:
6456  return E;
6457  }
6458  }
6459 
6460  // That should be enough to guarantee that this type is complete, if we're
6461  // not processing a decltype expression.
6462  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6463  if (RD->isInvalidDecl() || RD->isDependentContext())
6464  return E;
6465 
6466  bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6468  CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6469 
6470  if (Destructor) {
6471  MarkFunctionReferenced(E->getExprLoc(), Destructor);
6472  CheckDestructorAccess(E->getExprLoc(), Destructor,
6473  PDiag(diag::err_access_dtor_temp)
6474  << E->getType());
6475  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6476  return ExprError();
6477 
6478  // If destructor is trivial, we can avoid the extra copy.
6479  if (Destructor->isTrivial())
6480  return E;
6481 
6482  // We need a cleanup, but we don't need to remember the temporary.
6484  }
6485 
6486  CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6488 
6489  if (IsDecltype)
6490  ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6491 
6492  return Bind;
6493 }
6494 
6495 ExprResult
6497  if (SubExpr.isInvalid())
6498  return ExprError();
6499 
6500  return MaybeCreateExprWithCleanups(SubExpr.get());
6501 }
6502 
6504  assert(SubExpr && "subexpression can't be null!");
6505 
6507 
6508  unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6509  assert(ExprCleanupObjects.size() >= FirstCleanup);
6510  assert(Cleanup.exprNeedsCleanups() ||
6511  ExprCleanupObjects.size() == FirstCleanup);
6512  if (!Cleanup.exprNeedsCleanups())
6513  return SubExpr;
6514 
6515  auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6516  ExprCleanupObjects.size() - FirstCleanup);
6517 
6518  auto *E = ExprWithCleanups::Create(
6519  Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6521 
6522  return E;
6523 }
6524 
6526  assert(SubStmt && "sub-statement can't be null!");
6527 
6529 
6530  if (!Cleanup.exprNeedsCleanups())
6531  return SubStmt;
6532 
6533  // FIXME: In order to attach the temporaries, wrap the statement into
6534  // a StmtExpr; currently this is only used for asm statements.
6535  // This is hacky, either create a new CXXStmtWithTemporaries statement or
6536  // a new AsmStmtWithTemporaries.
6537  CompoundStmt *CompStmt = CompoundStmt::Create(
6538  Context, SubStmt, SourceLocation(), SourceLocation());
6539  Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6540  SourceLocation());
6541  return MaybeCreateExprWithCleanups(E);
6542 }
6543 
6544 /// Process the expression contained within a decltype. For such expressions,
6545 /// certain semantic checks on temporaries are delayed until this point, and
6546 /// are omitted for the 'topmost' call in the decltype expression. If the
6547 /// topmost call bound a temporary, strip that temporary off the expression.
6549  assert(ExprEvalContexts.back().ExprContext ==
6551  "not in a decltype expression");
6552 
6554  if (Result.isInvalid())
6555  return ExprError();
6556  E = Result.get();
6557 
6558  // C++11 [expr.call]p11:
6559  // If a function call is a prvalue of object type,
6560  // -- if the function call is either
6561  // -- the operand of a decltype-specifier, or
6562  // -- the right operand of a comma operator that is the operand of a
6563  // decltype-specifier,
6564  // a temporary object is not introduced for the prvalue.
6565 
6566  // Recursively rebuild ParenExprs and comma expressions to strip out the
6567  // outermost CXXBindTemporaryExpr, if any.
6568  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6569  ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6570  if (SubExpr.isInvalid())
6571  return ExprError();
6572  if (SubExpr.get() == PE->getSubExpr())
6573  return E;
6574  return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6575  }
6576  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6577  if (BO->getOpcode() == BO_Comma) {
6578  ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6579  if (RHS.isInvalid())
6580  return ExprError();
6581  if (RHS.get() == BO->getRHS())
6582  return E;
6583  return new (Context) BinaryOperator(
6584  BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6585  BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6586  }
6587  }
6588 
6589  CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6590  CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6591  : nullptr;
6592  if (TopCall)
6593  E = TopCall;
6594  else
6595  TopBind = nullptr;
6596 
6597  // Disable the special decltype handling now.
6598  ExprEvalContexts.back().ExprContext =
6600 
6601  // In MS mode, don't perform any extra checking of call return types within a
6602  // decltype expression.
6603  if (getLangOpts().MSVCCompat)
6604  return E;
6605 
6606  // Perform the semantic checks we delayed until this point.
6607  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6608  I != N; ++I) {
6609  CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6610  if (Call == TopCall)
6611  continue;
6612 
6614  Call->getBeginLoc(), Call, Call->getDirectCallee()))
6615  return ExprError();
6616  }
6617 
6618  // Now all relevant types are complete, check the destructors are accessible
6619  // and non-deleted, and annotate them on the temporaries.
6620  for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6621  I != N; ++I) {
6622  CXXBindTemporaryExpr *Bind =
6623  ExprEvalContexts.back().DelayedDecltypeBinds[I];
6624  if (Bind == TopBind)
6625  continue;
6626 
6627  CXXTemporary *Temp = Bind->getTemporary();
6628 
6629  CXXRecordDecl *RD =
6631  CXXDestructorDecl *Destructor = LookupDestructor(RD);
6632  Temp->setDestructor(Destructor);
6633 
6634  MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6635  CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6636  PDiag(diag::err_access_dtor_temp)
6637  << Bind->getType());
6638  if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6639  return ExprError();
6640 
6641  // We need a cleanup, but we don't need to remember the temporary.
6643  }
6644 
6645  // Possibly strip off the top CXXBindTemporaryExpr.
6646  return E;
6647 }
6648 
6649 /// Note a set of 'operator->' functions that were used for a member access.
6650 static void noteOperatorArrows(Sema &S,
6651  ArrayRef<FunctionDecl *> OperatorArrows) {
6652  unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6653  // FIXME: Make this configurable?
6654  unsigned Limit = 9;
6655  if (OperatorArrows.size() > Limit) {
6656  // Produce Limit-1 normal notes and one 'skipping' note.
6657  SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6658  SkipCount = OperatorArrows.size() - (Limit - 1);
6659  }
6660 
6661  for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6662  if (I == SkipStart) {
6663  S.Diag(OperatorArrows[I]->getLocation(),
6664  diag::note_operator_arrows_suppressed)
6665  << SkipCount;
6666  I += SkipCount;
6667  } else {
6668  S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6669  << OperatorArrows[I]->getCallResultType();
6670  ++I;
6671  }
6672  }
6673 }
6674 
6676  SourceLocation OpLoc,
6677  tok::TokenKind OpKind,
6678  ParsedType &ObjectType,
6679  bool &MayBePseudoDestructor) {
6680  // Since this might be a postfix expression, get rid of ParenListExprs.
6682  if (Result.isInvalid()) return ExprError();
6683  Base = Result.get();
6684 
6685  Result = CheckPlaceholderExpr(Base);
6686  if (Result.isInvalid()) return ExprError();
6687  Base = Result.get();
6688 
6689  QualType BaseType = Base->getType();
6690  MayBePseudoDestructor = false;
6691  if (BaseType->isDependentType()) {
6692  // If we have a pointer to a dependent type and are using the -> operator,
6693  // the object type is the type that the pointer points to. We might still
6694  // have enough information about that type to do something useful.
6695  if (OpKind == tok::arrow)
6696  if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6697  BaseType = Ptr->getPointeeType();
6698 
6699  ObjectType = ParsedType::make(BaseType);
6700  MayBePseudoDestructor = true;
6701  return Base;
6702  }
6703 
6704  // C++ [over.match.oper]p8:
6705  // [...] When operator->returns, the operator-> is applied to the value
6706  // returned, with the original second operand.
6707  if (OpKind == tok::arrow) {
6708  QualType StartingType = BaseType;
6709  bool NoArrowOperatorFound = false;
6710  bool FirstIteration = true;
6711  FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6712  // The set of types we've considered so far.
6713  llvm::SmallPtrSet<CanQualType,8> CTypes;
6714  SmallVector<FunctionDecl*, 8> OperatorArrows;
6715  CTypes.insert(Context.getCanonicalType(BaseType));
6716 
6717  while (BaseType->isRecordType()) {
6718  if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6719  Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6720  << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6721  noteOperatorArrows(*this, OperatorArrows);
6722  Diag(OpLoc, diag::note_operator_arrow_depth)
6723  << getLangOpts().ArrowDepth;
6724  return ExprError();
6725  }
6726 
6727  Result = BuildOverloadedArrowExpr(
6728  S, Base, OpLoc,
6729  // When in a template specialization and on the first loop iteration,
6730  // potentially give the default diagnostic (with the fixit in a
6731  // separate note) instead of having the error reported back to here
6732  // and giving a diagnostic with a fixit attached to the error itself.
6733  (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6734  ? nullptr
6735  : &NoArrowOperatorFound);
6736  if (Result.isInvalid()) {
6737  if (NoArrowOperatorFound) {
6738  if (FirstIteration) {
6739  Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6740  << BaseType << 1 << Base->getSourceRange()
6741  << FixItHint::CreateReplacement(OpLoc, ".");
6742  OpKind = tok::period;
6743  break;
6744  }
6745  Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6746  << BaseType << Base->getSourceRange();
6747  CallExpr *CE = dyn_cast<CallExpr>(Base);
6748  if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6749  Diag(CD->getBeginLoc(),
6750  diag::note_member_reference_arrow_from_operator_arrow);
6751  }
6752  }
6753  return ExprError();
6754  }
6755  Base = Result.get();
6756  if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6757  OperatorArrows.push_back(OpCall->getDirectCallee());
6758  BaseType = Base->getType();
6759  CanQualType CBaseType = Context.getCanonicalType(BaseType);
6760  if (!CTypes.insert(CBaseType).second) {
6761  Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6762  noteOperatorArrows(*this, OperatorArrows);
6763  return ExprError();
6764  }
6765  FirstIteration = false;
6766  }
6767 
6768  if (OpKind == tok::arrow &&
6769  (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6770  BaseType = BaseType->getPointeeType();
6771  }
6772 
6773  // Objective-C properties allow "." access on Objective-C pointer types,
6774  // so adjust the base type to the object type itself.
6775  if (BaseType->isObjCObjectPointerType())
6776  BaseType = BaseType->getPointeeType();
6777 
6778  // C++ [basic.lookup.classref]p2:
6779  // [...] If the type of the object expression is of pointer to scalar
6780  // type, the unqualified-id is looked up in the context of the complete
6781  // postfix-expression.
6782  //
6783  // This also indicates that we could be parsing a pseudo-destructor-name.
6784  // Note that Objective-C class and object types can be pseudo-destructor
6785  // expressions or normal member (ivar or property) access expressions, and
6786  // it's legal for the type to be incomplete if this is a pseudo-destructor
6787  // call. We'll do more incomplete-type checks later in the lookup process,
6788  // so just skip this check for ObjC types.
6789  if (BaseType->isObjCObjectOrInterfaceType()) {
6790  ObjectType = ParsedType::make(BaseType);
6791  MayBePseudoDestructor = true;
6792  return Base;
6793  } else if (!BaseType->isRecordType()) {
6794  ObjectType = nullptr;
6795  MayBePseudoDestructor = true;
6796  return Base;
6797  }
6798 
6799  // The object type must be complete (or dependent), or
6800  // C++11 [expr.prim.general]p3:
6801  // Unlike the object expression in other contexts, *this is not required to
6802  // be of complete type for purposes of class member access (5.2.5) outside
6803  // the member function body.
6804  if (!BaseType->isDependentType() &&
6805  !isThisOutsideMemberFunctionBody(BaseType) &&
6806  RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6807  return ExprError();
6808 
6809  // C++ [basic.lookup.classref]p2:
6810  // If the id-expression in a class member access (5.2.5) is an
6811  // unqualified-id, and the type of the object expression is of a class
6812  // type C (or of pointer to a class type C), the unqualified-id is looked
6813  // up in the scope of class C. [...]
6814  ObjectType = ParsedType::make(BaseType);
6815  return Base;
6816 }
6817 
6818 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6819  tok::TokenKind& OpKind, SourceLocation OpLoc) {
6820  if (Base->hasPlaceholderType()) {
6821  ExprResult result = S.CheckPlaceholderExpr(Base);
6822  if (result.isInvalid()) return true;
6823  Base = result.get();
6824  }
6825  ObjectType = Base->getType();
6826 
6827  // C++ [expr.pseudo]p2:
6828  // The left-hand side of the dot operator shall be of scalar type. The
6829  // left-hand side of the arrow operator shall be of pointer to scalar type.
6830  // This scalar type is the object type.
6831  // Note that this is rather different from the normal handling for the
6832  // arrow operator.
6833  if (OpKind == tok::arrow) {
6834  if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6835  ObjectType = Ptr->getPointeeType();
6836  } else if (!Base->isTypeDependent()) {
6837  // The user wrote "p->" when they probably meant "p."; fix it.
6838  S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6839  << ObjectType << true
6840  << FixItHint::CreateReplacement(OpLoc, ".");
6841  if (S.isSFINAEContext())
6842  return true;
6843 
6844  OpKind = tok::period;
6845  }
6846  }
6847 
6848  return false;
6849 }
6850 
6851 /// Check if it's ok to try and recover dot pseudo destructor calls on
6852 /// pointer objects.
6853 static bool
6855  QualType DestructedType) {
6856  // If this is a record type, check if its destructor is callable.
6857  if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6858  if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6859  return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6860  return false;
6861  }
6862 
6863  // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6864  return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6865  DestructedType->isVectorType();
6866 }
6867 
6869  SourceLocation OpLoc,
6870  tok::TokenKind OpKind,
6871  const CXXScopeSpec &SS,
6872  TypeSourceInfo *ScopeTypeInfo,
6873  SourceLocation CCLoc,
6874  SourceLocation TildeLoc,
6875  PseudoDestructorTypeStorage Destructed) {
6876  TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6877 
6878  QualType ObjectType;
6879  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6880  return ExprError();
6881 
6882  if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6883  !ObjectType->isVectorType()) {
6884  if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6885  Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6886  else {
6887  Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6888  << ObjectType << Base->getSourceRange();
6889  return ExprError();
6890  }
6891  }
6892 
6893  // C++ [expr.pseudo]p2:
6894  // [...] The cv-unqualified versions of the object type and of the type
6895  // designated by the pseudo-destructor-name shall be the same type.
6896  if (DestructedTypeInfo) {
6897  QualType DestructedType = DestructedTypeInfo->getType();
6898  SourceLocation DestructedTypeStart
6899  = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6900  if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6901  if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6902  // Detect dot pseudo destructor calls on pointer objects, e.g.:
6903  // Foo *foo;
6904  // foo.~Foo();
6905  if (OpKind == tok::period && ObjectType->isPointerType() &&
6906  Context.hasSameUnqualifiedType(DestructedType,
6907  ObjectType->getPointeeType())) {
6908  auto Diagnostic =
6909  Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6910  << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6911 
6912  // Issue a fixit only when the destructor is valid.
6914  *this, DestructedType))
6915  Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6916 
6917  // Recover by setting the object type to the destructed type and the
6918  // operator to '->'.
6919  ObjectType = DestructedType;
6920  OpKind = tok::arrow;
6921  } else {
6922  Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6923  << ObjectType << DestructedType << Base->getSourceRange()
6924  << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6925 
6926  // Recover by setting the destructed type to the object type.
6927  DestructedType = ObjectType;
6928  DestructedTypeInfo =
6929  Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6930  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6931  }
6932  } else if (DestructedType.getObjCLifetime() !=
6933  ObjectType.getObjCLifetime()) {
6934 
6935  if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6936  // Okay: just pretend that the user provided the correctly-qualified
6937  // type.
6938  } else {
6939  Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6940  << ObjectType << DestructedType << Base->getSourceRange()
6941  << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6942  }
6943 
6944  // Recover by setting the destructed type to the object type.
6945  DestructedType = ObjectType;
6946  DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6947  DestructedTypeStart);
6948  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6949  }
6950  }
6951  }
6952 
6953  // C++ [expr.pseudo]p2:
6954  // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6955  // form
6956  //
6957  // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6958  //
6959  // shall designate the same scalar type.
6960  if (ScopeTypeInfo) {
6961  QualType ScopeType = ScopeTypeInfo->getType();
6962  if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6963  !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6964 
6965  Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6966  diag::err_pseudo_dtor_type_mismatch)
6967  << ObjectType << ScopeType << Base->getSourceRange()
6968  << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6969 
6970  ScopeType = QualType();
6971  ScopeTypeInfo = nullptr;
6972  }
6973  }
6974 
6975  Expr *Result
6976  = new (Context) CXXPseudoDestructorExpr(Context, Base,
6977  OpKind == tok::arrow, OpLoc,
6979  ScopeTypeInfo,
6980  CCLoc,
6981  TildeLoc,
6982  Destructed);
6983 
6984  return Result;
6985 }
6986 
6988  SourceLocation OpLoc,
6989  tok::TokenKind OpKind,
6990  CXXScopeSpec &SS,
6991  UnqualifiedId &FirstTypeName,
6992  SourceLocation CCLoc,
6993  SourceLocation TildeLoc,
6994  UnqualifiedId &SecondTypeName) {
6995  assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6996  FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
6997  "Invalid first type name in pseudo-destructor");
6998  assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6999  SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7000  "Invalid second type name in pseudo-destructor");
7001 
7002  QualType ObjectType;
7003  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7004  return ExprError();
7005 
7006  // Compute the object type that we should use for name lookup purposes. Only
7007  // record types and dependent types matter.
7008  ParsedType ObjectTypePtrForLookup;
7009  if (!SS.isSet()) {
7010  if (ObjectType->isRecordType())
7011  ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7012  else if (ObjectType->isDependentType())
7013  ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7014  }
7015 
7016  // Convert the name of the type being destructed (following the ~) into a
7017  // type (with source-location information).
7018  QualType DestructedType;
7019  TypeSourceInfo *DestructedTypeInfo = nullptr;
7020  PseudoDestructorTypeStorage Destructed;
7021  if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7022  ParsedType T = getTypeName(*SecondTypeName.Identifier,
7023  SecondTypeName.StartLocation,
7024  S, &SS, true, false, ObjectTypePtrForLookup,
7025  /*IsCtorOrDtorName*/true);
7026  if (!T &&
7027  ((SS.isSet() && !computeDeclContext(SS, false)) ||
7028  (!SS.isSet() && ObjectType->isDependentType()))) {
7029  // The name of the type being destroyed is a dependent name, and we
7030  // couldn't find anything useful in scope. Just store the identifier and
7031  // it's location, and we'll perform (qualified) name lookup again at
7032  // template instantiation time.
7033  Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7034  SecondTypeName.StartLocation);
7035  } else if (!T) {
7036  Diag(SecondTypeName.StartLocation,
7037  diag::err_pseudo_dtor_destructor_non_type)
7038  << SecondTypeName.Identifier << ObjectType;
7039  if (isSFINAEContext())
7040  return ExprError();
7041 
7042  // Recover by assuming we had the right type all along.
7043  DestructedType = ObjectType;
7044  } else
7045  DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7046  } else {
7047  // Resolve the template-id to a type.
7048  TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7049  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7050  TemplateId->NumArgs);
7051  TypeResult T = ActOnTemplateIdType(TemplateId->SS,
7052  TemplateId->TemplateKWLoc,
7053  TemplateId->Template,
7054  TemplateId->Name,
7055  TemplateId->TemplateNameLoc,
7056  TemplateId->LAngleLoc,
7057  TemplateArgsPtr,
7058  TemplateId->RAngleLoc,
7059  /*IsCtorOrDtorName*/true);
7060  if (T.isInvalid() || !T.get()) {
7061  // Recover by assuming we had the right type all along.
7062  DestructedType = ObjectType;
7063  } else
7064  DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7065  }
7066 
7067  // If we've performed some kind of recovery, (re-)build the type source
7068  // information.
7069  if (!DestructedType.isNull()) {
7070  if (!DestructedTypeInfo)
7071  DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7072  SecondTypeName.StartLocation);
7073  Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7074  }
7075 
7076  // Convert the name of the scope type (the type prior to '::') into a type.
7077  TypeSourceInfo *ScopeTypeInfo = nullptr;
7078  QualType ScopeType;
7079  if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7080  FirstTypeName.Identifier) {
7081  if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7082  ParsedType T = getTypeName(*FirstTypeName.Identifier,
7083  FirstTypeName.StartLocation,
7084  S, &SS, true, false, ObjectTypePtrForLookup,
7085  /*IsCtorOrDtorName*/true);
7086  if (!T) {
7087  Diag(FirstTypeName.StartLocation,
7088  diag::err_pseudo_dtor_destructor_non_type)
7089  << FirstTypeName.Identifier << ObjectType;
7090 
7091  if (isSFINAEContext())
7092  return ExprError();
7093 
7094  // Just drop this type. It's unnecessary anyway.
7095  ScopeType = QualType();
7096  } else
7097  ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7098  } else {
7099  // Resolve the template-id to a type.
7100  TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7101  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7102  TemplateId->NumArgs);
7103  TypeResult T = ActOnTemplateIdType(TemplateId->SS,
7104  TemplateId->TemplateKWLoc,
7105  TemplateId->Template,
7106  TemplateId->Name,
7107  TemplateId->TemplateNameLoc,
7108  TemplateId->LAngleLoc,
7109  TemplateArgsPtr,
7110  TemplateId->RAngleLoc,
7111  /*IsCtorOrDtorName*/true);
7112  if (T.isInvalid() || !T.get()) {
7113  // Recover by dropping this type.
7114  ScopeType = QualType();
7115  } else
7116  ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7117  }
7118  }
7119 
7120  if (!ScopeType.isNull() && !ScopeTypeInfo)
7121  ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7122  FirstTypeName.StartLocation);
7123 
7124 
7125  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7126  ScopeTypeInfo, CCLoc, TildeLoc,
7127  Destructed);
7128 }
7129 
7131  SourceLocation OpLoc,
7132  tok::TokenKind OpKind,
7133  SourceLocation TildeLoc,
7134  const DeclSpec& DS) {
7135  QualType ObjectType;
7136  if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7137  return ExprError();
7138 
7140  false);
7141 
7142  TypeLocBuilder TLB;
7143  DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7144  DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7145  TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7146  PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7147 
7148  return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7149  nullptr, SourceLocation(), TildeLoc,
7150  Destructed);
7151 }
7152 
7154  CXXConversionDecl *Method,
7155  bool HadMultipleCandidates) {
7156  // Convert the expression to match the conversion function's implicit object
7157  // parameter.
7158  ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7159  FoundDecl, Method);
7160  if (Exp.isInvalid())
7161  return true;
7162 
7163  if (Method->getParent()->isLambda() &&
7164  Method->getConversionType()->isBlockPointerType()) {
7165  // This is a lambda coversion to block pointer; check if the argument
7166  // was a LambdaExpr.
7167  Expr *SubE = E;
7168  CastExpr *CE = dyn_cast<CastExpr>(SubE);
7169  if (CE && CE->getCastKind() == CK_NoOp)
7170  SubE = CE->getSubExpr();
7171  SubE = SubE->IgnoreParens();
7172  if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7173  SubE = BE->getSubExpr();
7174  if (isa<LambdaExpr>(SubE)) {
7175  // For the conversion to block pointer on a lambda expression, we
7176  // construct a special BlockLiteral instead; this doesn't really make
7177  // a difference in ARC, but outside of ARC the resulting block literal
7178  // follows the normal lifetime rules for block literals instead of being
7179  // autoreleased.
7180  DiagnosticErrorTrap Trap(Diags);
7184  Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7186 
7187  if (BlockExp.isInvalid())
7188  Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7189  return BlockExp;
7190  }
7191  }
7192 
7193  MemberExpr *ME = new (Context) MemberExpr(
7194  Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7196  if (HadMultipleCandidates)
7197  ME->setHadMultipleCandidates(true);
7199 
7200  QualType ResultType = Method->getReturnType();
7201  ExprValueKind VK = Expr::getValueKindForType(ResultType);
7202  ResultType = ResultType.getNonLValueExprType(Context);
7203 
7205  Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
7206 
7207  if (CheckFunctionCall(Method, CE,
7208  Method->getType()->castAs<FunctionProtoType>()))
7209  return ExprError();
7210 
7211  return CE;
7212 }
7213 
7215  SourceLocation RParen) {
7216  // If the operand is an unresolved lookup expression, the expression is ill-
7217  // formed per [over.over]p1, because overloaded function names cannot be used
7218  // without arguments except in explicit contexts.
7219  ExprResult R = CheckPlaceholderExpr(Operand);
7220  if (R.isInvalid())
7221  return R;
7222 
7223  // The operand may have been modified when checking the placeholder type.
7224  Operand = R.get();
7225 
7226  if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7227  // The expression operand for noexcept is in an unevaluated expression
7228  // context, so side effects could result in unintended consequences.
7229  Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7230  }
7231 
7232  CanThrowResult CanThrow = canThrow(Operand);
7233  return new (Context)
7234  CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7235 }
7236 
7238  Expr *Operand, SourceLocation RParen) {
7239  return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7240 }
7241 
7243  // In C++11, discarded-value expressions of a certain form are special,
7244  // according to [expr]p10:
7245  // The lvalue-to-rvalue conversion (4.1) is applied only if the
7246  // expression is an lvalue of volatile-qualified type and it has
7247  // one of the following forms:
7248  E = E->IgnoreParens();
7249 
7250  // - id-expression (5.1.1),
7251  if (isa<DeclRefExpr>(E))
7252  return true;
7253 
7254  // - subscripting (5.2.1),
7255  if (isa<ArraySubscriptExpr>(E))
7256  return true;
7257 
7258  // - class member access (5.2.5),
7259  if (isa<MemberExpr>(E))
7260  return true;
7261 
7262  // - indirection (5.3.1),
7263  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7264  if (UO->getOpcode() == UO_Deref)
7265  return true;
7266 
7267  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7268  // - pointer-to-member operation (5.5),
7269  if (BO->isPtrMemOp())
7270  return true;
7271 
7272  // - comma expression (5.18) where the right operand is one of the above.
7273  if (BO->getOpcode() == BO_Comma)
7274  return IsSpecialDiscardedValue(BO->getRHS());
7275  }
7276 
7277  // - conditional expression (5.16) where both the second and the third
7278  // operands are one of the above, or
7279  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7280  return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7281  IsSpecialDiscardedValue(CO->getFalseExpr());
7282  // The related edge case of "*x ?: *x".
7283  if (BinaryConditionalOperator *BCO =
7284  dyn_cast<BinaryConditionalOperator>(E)) {
7285  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7286  return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7287  IsSpecialDiscardedValue(BCO->getFalseExpr());
7288  }
7289 
7290  // Objective-C++ extensions to the rule.
7291  if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7292  return true;
7293 
7294  return false;
7295 }
7296 
7297 /// Perform the conversions required for an expression used in a
7298 /// context that ignores the result.
7300  if (E->hasPlaceholderType()) {
7301  ExprResult result = CheckPlaceholderExpr(E);
7302  if (result.isInvalid()) return E;
7303  E = result.get();
7304  }
7305 
7306  // C99 6.3.2.1:
7307  // [Except in specific positions,] an lvalue that does not have
7308  // array type is converted to the value stored in the
7309  // designated object (and is no longer an lvalue).
7310  if (E->isRValue()) {
7311  // In C, function designators (i.e. expressions of function type)
7312  // are r-values, but we still want to do function-to-pointer decay
7313  // on them. This is both technically correct and convenient for
7314  // some clients.
7315  if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7317 
7318  return E;
7319  }
7320 
7321  if (getLangOpts().CPlusPlus) {
7322  // The C++11 standard defines the notion of a discarded-value expression;
7323  // normally, we don't need to do anything to handle it, but if it is a
7324  // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7325  // conversion.
7326  if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7327  E->getType().isVolatileQualified() &&
7330  if (Res.isInvalid())
7331  return E;
7332  E = Res.get();
7333  }
7334 
7335  // C++1z:
7336  // If the expression is a prvalue after this optional conversion, the
7337  // temporary materialization conversion is applied.
7338  //
7339  // We skip this step: IR generation is able to synthesize the storage for
7340  // itself in the aggregate case, and adding the extra node to the AST is
7341  // just clutter.
7342  // FIXME: We don't emit lifetime markers for the temporaries due to this.
7343  // FIXME: Do any other AST consumers care about this?
7344  return E;
7345  }
7346 
7347  // GCC seems to also exclude expressions of incomplete enum type.
7348  if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7349  if (!T->getDecl()->isComplete()) {
7350  // FIXME: stupid workaround for a codegen bug!
7351  E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7352  return E;
7353  }
7354  }
7355 
7357  if (Res.isInvalid())
7358  return E;
7359  E = Res.get();
7360 
7361  if (!E->getType()->isVoidType())
7363  diag::err_incomplete_type);
7364  return E;
7365 }
7366 
7367 // If we can unambiguously determine whether Var can never be used
7368 // in a constant expression, return true.
7369 // - if the variable and its initializer are non-dependent, then
7370 // we can unambiguously check if the variable is a constant expression.
7371 // - if the initializer is not value dependent - we can determine whether
7372 // it can be used to initialize a constant expression. If Init can not
7373 // be used to initialize a constant expression we conclude that Var can
7374 // never be a constant expression.
7375 // - FXIME: if the initializer is dependent, we can still do some analysis and
7376 // identify certain cases unambiguously as non-const by using a Visitor:
7377 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7378 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7380  ASTContext &Context) {
7381  if (isa<ParmVarDecl>(Var)) return true;
7382  const VarDecl *DefVD = nullptr;
7383 
7384  // If there is no initializer - this can not be a constant expression.
7385  if (!Var->getAnyInitializer(DefVD)) return true;
7386  assert(DefVD);
7387  if (DefVD->isWeak()) return false;
7388  EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7389 
7390  Expr *Init = cast<Expr>(Eval->Value);
7391 
7392  if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7393  // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7394  // of value-dependent expressions, and use it here to determine whether the
7395  // initializer is a potential constant expression.
7396  return false;
7397  }
7398 
7399  return !IsVariableAConstantExpression(Var, Context);
7400 }
7401 
7402 /// Check if the current lambda has any potential captures
7403 /// that must be captured by any of its enclosing lambdas that are ready to
7404 /// capture. If there is a lambda that can capture a nested
7405 /// potential-capture, go ahead and do so. Also, check to see if any
7406 /// variables are uncaptureable or do not involve an odr-use so do not
7407 /// need to be captured.
7408 
7410  Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7411 
7412  assert(!S.isUnevaluatedContext());
7413  assert(S.CurContext->isDependentContext());
7414 #ifndef NDEBUG
7415  DeclContext *DC = S.CurContext;
7416  while (DC && isa<CapturedDecl>(DC))
7417  DC = DC->getParent();
7418  assert(
7419  CurrentLSI->CallOperator == DC &&
7420  "The current call operator must be synchronized with Sema's CurContext");
7421 #endif // NDEBUG
7422 
7423  const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7424 
7425  // All the potentially captureable variables in the current nested
7426  // lambda (within a generic outer lambda), must be captured by an
7427  // outer lambda that is enclosed within a non-dependent context.
7428  const unsigned NumPotentialCaptures =
7429  CurrentLSI->getNumPotentialVariableCaptures();
7430  for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7431  Expr *VarExpr = nullptr;
7432  VarDecl *Var = nullptr;
7433  CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7434  // If the variable is clearly identified as non-odr-used and the full
7435  // expression is not instantiation dependent, only then do we not
7436  // need to check enclosing lambda's for speculative captures.
7437  // For e.g.:
7438  // Even though 'x' is not odr-used, it should be captured.
7439  // int test() {
7440  // const int x = 10;
7441  // auto L = [=](auto a) {
7442  // (void) +x + a;
7443  // };
7444  // }
7445  if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7446  !IsFullExprInstantiationDependent)
7447  continue;
7448 
7449  // If we have a capture-capable lambda for the variable, go ahead and
7450  // capture the variable in that lambda (and all its enclosing lambdas).
7451  if (const Optional<unsigned> Index =
7453  S.FunctionScopes, Var, S)) {
7454  const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7455  MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7456  &FunctionScopeIndexOfCapturableLambda);
7457  }
7458  const bool IsVarNeverAConstantExpression =
7460  if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7461  // This full expression is not instantiation dependent or the variable
7462  // can not be used in a constant expression - which means
7463  // this variable must be odr-used here, so diagnose a
7464  // capture violation early, if the variable is un-captureable.
7465  // This is purely for diagnosing errors early. Otherwise, this
7466  // error would get diagnosed when the lambda becomes capture ready.
7467  QualType CaptureType, DeclRefType;
7468  SourceLocation ExprLoc = VarExpr->getExprLoc();
7469  if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7470  /*EllipsisLoc*/ SourceLocation(),
7471  /*BuildAndDiagnose*/false, CaptureType,
7472  DeclRefType, nullptr)) {
7473  // We will never be able to capture this variable, and we need
7474  // to be able to in any and all instantiations, so diagnose it.
7475  S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7476  /*EllipsisLoc*/ SourceLocation(),
7477  /*BuildAndDiagnose*/true, CaptureType,
7478  DeclRefType, nullptr);
7479  }
7480  }
7481  }
7482 
7483  // Check if 'this' needs to be captured.
7484  if (CurrentLSI->hasPotentialThisCapture()) {
7485  // If we have a capture-capable lambda for 'this', go ahead and capture
7486  // 'this' in that lambda (and all its enclosing lambdas).
7487  if (const Optional<unsigned> Index =
7489  S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7490  const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7492  /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7493  &FunctionScopeIndexOfCapturableLambda);
7494  }
7495  }
7496 
7497  // Reset all the potential captures at the end of each full-expression.
7498  CurrentLSI->clearPotentialCaptures();
7499 }
7500 
7503  const TypoCorrection &TC) {
7504  LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7505  Consumer.getLookupResult().getLookupKind());
7506  const CXXScopeSpec *SS = Consumer.getSS();
7507  CXXScopeSpec NewSS;
7508 
7509  // Use an approprate CXXScopeSpec for building the expr.
7510  if (auto *NNS = TC.getCorrectionSpecifier())
7511  NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7512  else if (SS && !TC.WillReplaceSpecifier())
7513  NewSS = *SS;
7514 
7515  if (auto *ND = TC.getFoundDecl()) {
7516  R.setLookupName(ND->getDeclName());
7517  R.addDecl(ND);
7518  if (ND->isCXXClassMember()) {
7519  // Figure out the correct naming class to add to the LookupResult.
7520  CXXRecordDecl *Record = nullptr;
7521  if (auto *NNS = TC.getCorrectionSpecifier())
7522  Record = NNS->getAsType()->getAsCXXRecordDecl();
7523  if (!Record)
7524  Record =
7525  dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7526  if (Record)
7527  R.setNamingClass(Record);
7528 
7529  // Detect and handle the case where the decl might be an implicit
7530  // member.
7531  bool MightBeImplicitMember;
7532  if (!Consumer.isAddressOfOperand())
7533  MightBeImplicitMember = true;
7534  else if (!NewSS.isEmpty())
7535  MightBeImplicitMember = false;
7536  else if (R.isOverloadedResult())
7537  MightBeImplicitMember = false;
7538  else if (R.isUnresolvableResult())
7539  MightBeImplicitMember = true;
7540  else
7541  MightBeImplicitMember = isa<FieldDecl>(ND) ||
7542  isa<IndirectFieldDecl>(ND) ||
7543  isa<MSPropertyDecl>(ND);
7544 
7545  if (MightBeImplicitMember)
7546  return SemaRef.BuildPossibleImplicitMemberExpr(
7547  NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7548  /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7549  } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7550  return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7551  Ivar->getIdentifier());
7552  }
7553  }
7554 
7555  return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7556  /*AcceptInvalidDecl*/ true);
7557 }
7558 
7559 namespace {
7560 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7562 
7563 public:
7564  explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7565  : TypoExprs(TypoExprs) {}
7566  bool VisitTypoExpr(TypoExpr *TE) {
7567  TypoExprs.insert(TE);
7568  return true;
7569  }
7570 };
7571 
7572 class TransformTypos : public TreeTransform<TransformTypos> {
7573  typedef TreeTransform<TransformTypos> BaseTransform;
7574 
7575  VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7576  // process of being initialized.
7577  llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7578  llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7579  llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7580  llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7581 
7582  /// Emit diagnostics for all of the TypoExprs encountered.
7583  /// If the TypoExprs were successfully corrected, then the diagnostics should
7584  /// suggest the corrections. Otherwise the diagnostics will not suggest
7585  /// anything (having been passed an empty TypoCorrection).
7586  void EmitAllDiagnostics() {
7587  for (TypoExpr *TE : TypoExprs) {
7588  auto &State = SemaRef.getTypoExprState(TE);
7589  if (State.DiagHandler) {
7590  TypoCorrection TC = State.Consumer->getCurrentCorrection();
7591  ExprResult Replacement = TransformCache[TE];
7592 
7593  // Extract the NamedDecl from the transformed TypoExpr and add it to the
7594  // TypoCorrection, replacing the existing decls. This ensures the right
7595  // NamedDecl is used in diagnostics e.g. in the case where overload
7596  // resolution was used to select one from several possible decls that
7597  // had been stored in the TypoCorrection.
7598  if (auto *ND = getDeclFromExpr(
7599  Replacement.isInvalid() ? nullptr : Replacement.get()))
7600  TC.setCorrectionDecl(ND);
7601 
7602  State.DiagHandler(TC);
7603  }
7604  SemaRef.clearDelayedTypo(TE);
7605  }
7606  }
7607 
7608  /// If corrections for the first TypoExpr have been exhausted for a
7609  /// given combination of the other TypoExprs, retry those corrections against
7610  /// the next combination of substitutions for the other TypoExprs by advancing
7611  /// to the next potential correction of the second TypoExpr. For the second
7612  /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7613  /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7614  /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7615  /// TransformCache). Returns true if there is still any untried combinations
7616  /// of corrections.
7617  bool CheckAndAdvanceTypoExprCorrectionStreams() {
7618  for (auto TE : TypoExprs) {
7619  auto &State = SemaRef.getTypoExprState(TE);
7620  TransformCache.erase(TE);
7621  if (!State.Consumer->finished())
7622  return true;
7623  State.Consumer->resetCorrectionStream();
7624  }
7625  return false;
7626  }
7627 
7629  if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7630  E = OverloadResolution[OE];
7631 
7632  if (!E)
7633  return nullptr;
7634  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7635  return DRE->getFoundDecl();
7636  if (auto *ME = dyn_cast<MemberExpr>(E))
7637  return ME->getFoundDecl();
7638  // FIXME: Add any other expr types that could be be seen by the delayed typo
7639  // correction TreeTransform for which the corresponding TypoCorrection could
7640  // contain multiple decls.
7641  return nullptr;
7642  }
7643 
7644  ExprResult TryTransform(Expr *E) {
7645  Sema::SFINAETrap Trap(SemaRef);
7646  ExprResult Res = TransformExpr(E);
7647  if (Trap.hasErrorOccurred() || Res.isInvalid())
7648  return ExprError();
7649 
7650  return ExprFilter(Res.get());
7651  }
7652 
7653 public:
7654  TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7655  : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7656 
7657  ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7658  MultiExprArg Args,
7659  SourceLocation RParenLoc,
7660  Expr *ExecConfig = nullptr) {
7661  auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7662  RParenLoc, ExecConfig);
7663  if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7664  if (Result.isUsable()) {
7665  Expr *ResultCall = Result.get();
7666  if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7667  ResultCall = BE->getSubExpr();
7668  if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7669  OverloadResolution[OE] = CE->getCallee();
7670  }
7671  }
7672  return Result;
7673  }
7674 
7675  ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7676 
7677  ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7678 
7679  ExprResult Transform(Expr *E) {
7680  ExprResult Res;
7681  while (true) {
7682  Res = TryTransform(E);
7683 
7684  // Exit if either the transform was valid or if there were no TypoExprs
7685  // to transform that still have any untried correction candidates..
7686  if (!Res.isInvalid() ||
7687  !CheckAndAdvanceTypoExprCorrectionStreams())
7688  break;
7689  }
7690 
7691  // Ensure none of the TypoExprs have multiple typo correction candidates
7692  // with the same edit length that pass all the checks and filters.
7693  // TODO: Properly handle various permutations of possible corrections when
7694  // there is more than one potentially ambiguous typo correction.
7695  // Also, disable typo correction while attempting the transform when
7696  // handling potentially ambiguous typo corrections as any new TypoExprs will
7697  // have been introduced by the application of one of the correction
7698  // candidates and add little to no value if corrected.
7699  SemaRef.DisableTypoCorrection = true;
7700  while (!AmbiguousTypoExprs.empty()) {
7701  auto TE = AmbiguousTypoExprs.back();
7702  auto Cached = TransformCache[TE];
7703  auto &State = SemaRef.getTypoExprState(TE);
7704  State.Consumer->saveCurrentPosition();
7705  TransformCache.erase(TE);
7706  if (!TryTransform(E).isInvalid()) {
7707  State.Consumer->resetCorrectionStream();
7708  TransformCache.erase(TE);
7709  Res = ExprError();
7710  break;
7711  }
7712  AmbiguousTypoExprs.remove(TE);
7713  State.Consumer->restoreSavedPosition();
7714  TransformCache[TE] = Cached;
7715  }
7716  SemaRef.DisableTypoCorrection = false;
7717 
7718  // Ensure that all of the TypoExprs within the current Expr have been found.
7719  if (!Res.isUsable())
7720  FindTypoExprs(TypoExprs).TraverseStmt(E);
7721 
7722  EmitAllDiagnostics();
7723 
7724  return Res;
7725  }
7726 
7727  ExprResult TransformTypoExpr(TypoExpr *E) {
7728  // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7729  // cached transformation result if there is one and the TypoExpr isn't the
7730  // first one that was encountered.
7731  auto &CacheEntry = TransformCache[E];
7732  if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7733  return CacheEntry;
7734  }
7735 
7736  auto &State = SemaRef.getTypoExprState(E);
7737  assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7738 
7739  // For the first TypoExpr and an uncached TypoExpr, find the next likely
7740  // typo correction and return it.
7741  while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7742  if (InitDecl && TC.getFoundDecl() == InitDecl)
7743  continue;
7744  // FIXME: If we would typo-correct to an invalid declaration, it's
7745  // probably best to just suppress all errors from this typo correction.
7746  ExprResult NE = State.RecoveryHandler ?
7747  State.RecoveryHandler(SemaRef, E, TC) :
7748  attemptRecovery(SemaRef, *State.Consumer, TC);
7749  if (!NE.isInvalid()) {
7750  // Check whether there may be a second viable correction with the same
7751  // edit distance; if so, remember this TypoExpr may have an ambiguous
7752  // correction so it can be more thoroughly vetted later.
7753  TypoCorrection Next;
7754  if ((Next = State.Consumer->peekNextCorrection()) &&
7755  Next.getEditDistance(false) == TC.getEditDistance(false)) {
7756  AmbiguousTypoExprs.insert(E);
7757  } else {
7758  AmbiguousTypoExprs.remove(E);
7759  }
7760  assert(!NE.isUnset() &&
7761  "Typo was transformed into a valid-but-null ExprResult");
7762  return CacheEntry = NE;
7763  }
7764  }
7765  return CacheEntry = ExprError();
7766  }
7767 };
7768 }
7769 
7770 ExprResult
7772  llvm::function_ref<ExprResult(Expr *)> Filter) {
7773  // If the current evaluation context indicates there are uncorrected typos
7774  // and the current expression isn't guaranteed to not have typos, try to
7775  // resolve any TypoExpr nodes that might be in the expression.
7776  if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7777  (E->isTypeDependent() || E->isValueDependent() ||
7778  E->isInstantiationDependent())) {
7779  auto TyposResolved = DelayedTypos.size();
7780  auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7781  TyposResolved -= DelayedTypos.size();
7782  if (Result.isInvalid() || Result.get() != E) {
7783  ExprEvalContexts.back().NumTypos -= TyposResolved;
7784  return Result;
7785  }
7786  assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
7787  }
7788  return E;
7789 }
7790 
7792  bool DiscardedValue,
7793  bool IsConstexpr) {
7794  ExprResult FullExpr = FE;
7795 
7796  if (!FullExpr.get())
7797  return ExprError();
7798 
7799  if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
7800  return ExprError();
7801 
7802  if (DiscardedValue) {
7803  // Top-level expressions default to 'id' when we're in a debugger.
7804  if (getLangOpts().DebuggerCastResultToId &&
7805  FullExpr.get()->getType() == Context.UnknownAnyTy) {
7806  FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7807  if (FullExpr.isInvalid())
7808  return ExprError();
7809  }
7810 
7811  FullExpr = CheckPlaceholderExpr(FullExpr.get());
7812  if (FullExpr.isInvalid())
7813  return ExprError();
7814 
7815  FullExpr = IgnoredValueConversions(FullExpr.get());
7816  if (FullExpr.isInvalid())
7817  return ExprError();
7818 
7819  DiagnoseUnusedExprResult(FullExpr.get());
7820  }
7821 
7822  FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7823  if (FullExpr.isInvalid())
7824  return ExprError();
7825 
7826  CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7827 
7828  // At the end of this full expression (which could be a deeply nested
7829  // lambda), if there is a potential capture within the nested lambda,
7830  // have the outer capture-able lambda try and capture it.
7831  // Consider the following code:
7832  // void f(int, int);
7833  // void f(const int&, double);
7834  // void foo() {
7835  // const int x = 10, y = 20;
7836  // auto L = [=](auto a) {
7837  // auto M = [=](auto b) {
7838  // f(x, b); <-- requires x to be captured by L and M
7839  // f(y, a); <-- requires y to be captured by L, but not all Ms
7840  // };
7841  // };
7842  // }
7843 
7844  // FIXME: Also consider what happens for something like this that involves
7845  // the gnu-extension statement-expressions or even lambda-init-captures:
7846  // void f() {
7847  // const int n = 0;
7848  // auto L = [&](auto a) {
7849  // +n + ({ 0; a; });
7850  // };
7851  // }
7852  //
7853  // Here, we see +n, and then the full-expression 0; ends, so we don't
7854  // capture n (and instead remove it from our list of potential captures),
7855  // and then the full-expression +n + ({ 0; }); ends, but it's too late
7856  // for us to see that we need to capture n after all.
7857 
7858  LambdaScopeInfo *const CurrentLSI =
7859  getCurLambda(/*IgnoreCapturedRegions=*/true);
7860  // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7861  // even if CurContext is not a lambda call operator. Refer to that Bug Report
7862  // for an example of the code that might cause this asynchrony.
7863  // By ensuring we are in the context of a lambda's call operator
7864  // we can fix the bug (we only need to check whether we need to capture
7865  // if we are within a lambda's body); but per the comments in that
7866  // PR, a proper fix would entail :
7867  // "Alternative suggestion:
7868  // - Add to Sema an integer holding the smallest (outermost) scope
7869  // index that we are *lexically* within, and save/restore/set to
7870  // FunctionScopes.size() in InstantiatingTemplate's
7871  // constructor/destructor.
7872  // - Teach the handful of places that iterate over FunctionScopes to
7873  // stop at the outermost enclosing lexical scope."
7874  DeclContext *DC = CurContext;
7875  while (DC && isa<CapturedDecl>(DC))
7876  DC = DC->getParent();
7877  const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7878  if (IsInLambdaDeclContext && CurrentLSI &&
7879  CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7881  *this);
7882  return MaybeCreateExprWithCleanups(FullExpr);
7883 }
7884 
7886  if (!FullStmt) return StmtError();
7887 
7888  return MaybeCreateStmtWithCleanups(FullStmt);
7889 }
7890 
7893  CXXScopeSpec &SS,
7894  const DeclarationNameInfo &TargetNameInfo) {
7895  DeclarationName TargetName = TargetNameInfo.getName();
7896  if (!TargetName)
7897  return IER_DoesNotExist;
7898 
7899  // If the name itself is dependent, then the result is dependent.
7900  if (TargetName.isDependentName())
7901  return IER_Dependent;
7902 
7903  // Do the redeclaration lookup in the current scope.
7904  LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7906  LookupParsedName(R, S, &SS);
7907  R.suppressDiagnostics();
7908 
7909  switch (R.getResultKind()) {
7910  case LookupResult::Found:
7914  return IER_Exists;
7915 
7917  return IER_DoesNotExist;
7918 
7920  return IER_Dependent;
7921  }
7922 
7923  llvm_unreachable("Invalid LookupResult Kind!");
7924 }
7925 
7928  bool IsIfExists, CXXScopeSpec &SS,
7929  UnqualifiedId &Name) {
7930  DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7931 
7932  // Check for an unexpanded parameter pack.
7933  auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7934  if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7935  DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7936  return IER_Error;
7937 
7938  return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7939 }
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, tok::TokenKind &OpKind, SourceLocation OpLoc)
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:78
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:93
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:383
Defines the clang::ASTContext interface.
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable...
VariadicCallType
Definition: Sema.h:9462
CanThrowResult canThrow(const Expr *E)
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:250
QualType getCurrentThisType()
Try to retrieve the type of the &#39;this&#39; pointer.
This is the scope of a C++ try statement.
Definition: Scope.h:102
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:596
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void setImplicit(bool I=true)
Definition: DeclBase.h:548
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:70
Represents a function declaration or definition.
Definition: Decl.h:1738
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:64
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.
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ...
Definition: Overload.h:364
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2454
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E)
SourceRange getCorrectionRange() const
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
no exception specification
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:1849
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:136
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:14423
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2537
QualType getPointeeType() const
Definition: Type.h:2550
CanQualType VoidPtrTy
Definition: ASTContext.h:1044
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2235
A (possibly-)qualified type.
Definition: Type.h:638
ASTConsumer & Consumer
Definition: Sema.h:325
bool isBlockPointerType() const
Definition: Type.h:6304
This is a scope that corresponds to the parameters within a function prototype.
Definition: Scope.h:82
Simple class containing the result of Sema::CorrectTypo.
void addThisCapture(bool isNested, SourceLocation Loc, Expr *Cpy, bool ByCopy)
Definition: ScopeInfo.h:1008
static bool IsSpecialDiscardedValue(Expr *E)
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2101
base_class_range bases()
Definition: DeclCXX.h:823
bool isArrayType() const
Definition: Type.h:6345
bool isMemberPointerType() const
Definition: Type.h:6327
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:2773
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2553
void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const
Definition: ScopeInfo.cpp:235
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type, bool NRVO)
Create the initialization entity for an exception object.
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:992
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2179
bool isMemberDataPointerType() const
Definition: Type.h:6338
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&#39;t alre...
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:3055
IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:246
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
static ConditionResult ConditionError()
Definition: Sema.h:9919
QualType CXXThisTypeOverride
When non-NULL, the C++ &#39;this&#39; expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:5112
bool isArithmeticType() const
Definition: Type.cpp:1952
Stmt - This represents one statement.
Definition: Stmt.h:66
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:962
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2540
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3355
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:3689
Provides information about an attempted template argument deduction, whose success or failure was des...
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 getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:505
Microsoft __if_not_exists.
Definition: Sema.h:6646
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:949
Vector conversions.
Definition: Overload.h:135
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1937
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:472
QualType getThisType() const
Returns the type of the this pointer.
Definition: DeclCXX.cpp:2184
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:807
Microsoft&#39;s &#39;__super&#39; specifier, stored as a CXXRecordDecl* of the class it appeared in...
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:114
bool isRecordType() const
Definition: Type.h:6369
unsigned getTypeAlignIfKnown(QualType T) const
Return the ABI-specified alignment of a type, in bits, or 0 if the type is incomplete and we cannot d...
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:530
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1933
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.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1308
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1514
bool DiagnoseConditionalForNull(Expr *LHSExpr, 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:6520
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4002
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
bool isVirtual() const
Definition: DeclCXX.h:2086
bool isExtVectorType() const
Definition: Type.h:6385
void setType(QualType t)
Definition: Expr.h:129
AssignConvertType
AssignConvertType - All of the &#39;assignment&#39; semantic checks return this enum to indicate whether the ...
Definition: Sema.h:9522
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
Microsoft __if_exists.
Definition: Sema.h:6643
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
StringRef P
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1844
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:6245
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:16632
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2763
The base class of the type hierarchy.
Definition: Type.h:1407
This indicates that the scope corresponds to a function, which means that labels are set here...
Definition: Scope.h:48
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:258
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1148
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2812
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:64
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
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 ...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1262
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:395
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent...
Definition: ExprCXX.h:2514
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1891
Ambiguous candidates found.
Definition: Overload.h:60
QualType withConst() const
Definition: Type.h:810
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST...
Definition: Sema.h:9586
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:690
A container of type source information.
Definition: Decl.h:87
static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo *> Args, SourceLocation RParenLoc)
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5983
QualType getLogicalOperationType() const
The result type of logical operations, &#39;<&#39;, &#39;>&#39;, &#39;!=&#39;, etc.
Definition: ASTContext.h:1785
capture_const_range captures() const
Definition: DeclCXX.h:1248
Conversions between compatible types in C99.
Definition: Overload.h:129
bool isDefined(const FunctionDecl *&Definition) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:2720
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, SourceLocation LPLoc, SourceLocation RPLoc)
Definition: ExprCXX.cpp:809
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1210
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2800
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2484
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:543
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, C99 6.9p3)
Definition: SemaExpr.cpp:14628
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition: ScopeInfo.h:961
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2714
size_t param_size() const
Definition: Decl.h:2278
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2091
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Definition: Type.cpp:2157
bool DisableTypoCorrection
Tracks whether we are in a context where typo correction is disabled.
Definition: Sema.h:7620
An identifier, stored as an IdentifierInfo*.
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:1884
This file provides some common utility functions for processing Lambda related AST Constructs...
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:125
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10853
Represents a variable declaration or definition.
Definition: Decl.h:813
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:25
bool isStructureType() const
Definition: Type.cpp:443
bool hasPotentialThisCapture() const
Definition: ScopeInfo.h:913
ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
static ExprResult attemptRecovery(Sema &SemaRef, const TypoCorrectionConsumer &Consumer, const TypoCorrection &TC)
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition: Sema.h:4511
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:533
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:241
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1765
QualType getReturnType() const
Definition: Decl.h:2302
DiagnosticsEngine & Diags
Definition: Sema.h:326
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo *> FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
unsigned getNumParams() const
Definition: Type.h:3888
bool isEnumeralType() const
Definition: Type.h:6373
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3529
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6748
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init.ref]).
Definition: SemaInit.cpp:3277
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2178
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Extra information about a function prototype.
Definition: Type.h:3767
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD)
Retrieve the message suffix that should be added to a diagnostic complaining about the given function...
Definition: SemaExpr.cpp:327
CUDAFunctionPreference
Definition: Sema.h:10180
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType)
Determine whether a type has new-extended alignment.
RAII class that determines when any errors have occurred between the time the instance was created an...
Definition: Diagnostic.h:999
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:432
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:5349
bool isAmbiguous() const
Definition: Lookup.h:290
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
A namespace, stored as a NamespaceDecl*.
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 ...
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:369
bool isInvalidDecl() const
Definition: DeclBase.h:542
static InitializationKind CreateDirectList(SourceLocation InitLoc)
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
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, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type...
Definition: SemaDecl.cpp:277
bool tryCaptureVariable(VarDecl *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:15276
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1015
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, QualType allocType)
Determine whether a given type is a class for which &#39;delete[]&#39; would call a member &#39;operator delete[]...
Defines the clang::Expr interface and subclasses for C++ expressions.
bool isUnset() const
Definition: Ownership.h:172
noexcept(expression), value-dependent
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2352
The collection of all-type qualifiers we support.
Definition: Type.h:141
Information about a template-id annotation token.
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:6401
bool isXValue() const
Definition: Expr.h:251
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit=false)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType...
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2124
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, TypeSourceInfo *Type, SourceLocation LParenLoc, ArrayRef< Expr *> Args, SourceLocation RParenLoc)
Definition: ExprCXX.cpp:1283
Expr * FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
Represents a struct/union/class.
Definition: Decl.h:3593
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:7152
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T)
Perform an "extended" implicit conversion as returned by TryClassUnification.
uint64_t getPointerWidth(unsigned AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:348
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.
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:986
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:298
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:126
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3768
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3489
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1018
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:74
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:4936
Step
Definition: OpenMPClause.h:152
void DiagnoseUnusedExprResult(const Stmt *S)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused...
Definition: SemaStmt.cpp:199
bool isConst() const
Definition: DeclCXX.h:2083
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:3997
Represents a class type in Objective C.
Definition: Type.h:5538
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:155
void DropFirstTypeObject()
Definition: DeclSpec.h:2196
A C++ nested-name-specifier augmented with source location information.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7520
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:423
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1187
LineState State
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:515
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:294
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3941
A C-style cast.
Definition: Sema.h:9395
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:877
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:1956
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:288
Represents a member of a struct/union/class.
Definition: Decl.h:2579
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
The current expression is potentially evaluated at run time, which means that code may be generated t...
Identity conversion (no conversion)
Definition: Overload.h:81
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with &#39;::operator new(size_t)&#39; is g...
Definition: TargetInfo.h:537
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:773
bool isAbstractType(SourceLocation Loc, QualType T)
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:231
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:527
Floating point conversions (C++ [conv.double].
Definition: Overload.h:111
bool isReferenceType() const
Definition: Type.h:6308
CXXRecordDecl * getStdBadAlloc() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:2563
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1463
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
static const TST TST_error
Definition: DeclSpec.h:310
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
Definition: Expr.cpp:406
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse &#39;nullptr&#39;.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr *> &Args, bool &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:248
LookupResultKind getResultKind() const
Definition: Lookup.h:310
Expr * getSubExpr()
Definition: Expr.h:3050
ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:739
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
Definition: ExprObjC.h:171
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:439
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:14486
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:6226
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:56
A user-defined literal name, e.g., operator "" _i.
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:100
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:110
bool isInvalidType() const
Definition: DeclSpec.h:2443
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
bool getProducesResult() const
Definition: Type.h:3513
DeclClass * getAsSingle() const
Definition: Lookup.h:496
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:102
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
bool isGLValue() const
Definition: Expr.h:252
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
bool isReplaceableGlobalAllocationFunction(bool *IsAligned=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:2818
Describes an C or C++ initializer list.
Definition: Expr.h:4185
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:669
This is a scope that corresponds to a block/closure object.
Definition: Scope.h:72
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
ActOnCXXThrow - Parse throw expressions.
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:934
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:54
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1655
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:521
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace...
Represents the results of name lookup.
Definition: Lookup.h:47
PtrTy get() const
Definition: Ownership.h:174
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1363
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
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:6495
Microsoft throw(...) extension.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
Succeeded, but refers to a deleted function.
Definition: Overload.h:63
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:9781
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2205
ArrayTypeInfo Arr
Definition: DeclSpec.h:1519
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, 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...
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of &#39;this&#39; is actually available in the current context, if it is a potentially ev...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2175
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:15749
StmtResult StmtError()
Definition: Ownership.h:284
Represents a declaration of a type.
Definition: Decl.h:2874
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3287
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6142
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt *> Stmts, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:332
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion, integral conversion, floating point conversion, floating-integral conversion, pointer conversion, pointer-to-member conversion, or boolean conversion.
Definition: Overload.h:241
QualType getExceptionObjectType(QualType T) const
A conversion for an operand of a builtin overloaded operator.
Definition: Sema.h:9401
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
const Type * getClass() const
Definition: Type.h:2790
bool isRValueReferenceType() const
Definition: Type.h:6316
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:9391
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...
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:835
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1196
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:71
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
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:7284
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:1928
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6072
New-expression has a C++98 paren-delimited initializer.
Definition: ExprCXX.h:1971
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:5562
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:96
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:111
ExprResult ActOnCXXThis(SourceLocation loc)
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:2998
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:629
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1217
ArrayTypeTrait
Names for the array type traits.
Definition: TypeTraits.h:91
CXXTemporary * getTemporary()
Definition: ExprCXX.h:1236
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1649
Preprocessor & PP
Definition: Sema.h:323
const LangOptions & getLangOpts() const
Definition: Sema.h:1231
static FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage)
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value &#39;V&#39; and type &#39;type&#39;.
Definition: Expr.cpp:792
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:167
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:649
bool isScalarType() const
Definition: Type.h:6629
An ordinary object is located at an address in memory.
Definition: Specifiers.h:126
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
The number of conversion kinds.
Definition: Overload.h:165
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1697
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:7549
Represents an ObjC class declaration.
Definition: DeclObjC.h:1172
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2392
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:5978
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:5773
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:245
bool getNoReturn() const
Definition: Type.h:3512
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1344
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:2797
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
Integral promotions (C++ [conv.prom])
Definition: Overload.h:99
const LangOptions & LangOpts
Definition: Sema.h:322
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified=false, bool hasWrittenPrototype=true, bool isConstexprSpecified=false)
Definition: Decl.h:1875
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
This object can be modified without requiring retains or releases.
Definition: Type.h:162
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
Represents the this expression in C++.
Definition: ExprCXX.h:976
C-only conversion between pointers with incompatible types.
Definition: Overload.h:162
arg_iterator arg_end()
Definition: Expr.h:2593
New-expression has no initializer as written.
Definition: ExprCXX.h:1968
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1595
TypeTrait
Names for traits that operate specifically on types.
Definition: TypeTraits.h:21
SourceLocation LAngleLoc
The location of the &#39;<&#39; before the template argument list.
bool isArrayForm() const
Definition: ExprCXX.h:2197
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:7558
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1772
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3288
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7257
bool isHalfType() const
Definition: Type.h:6550
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:218
bool hasAttr() const
Definition: DeclBase.h:531
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:3582
An error occurred.
Definition: Sema.h:4523
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:278
enum clang::DeclaratorChunk::@215 Kind
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2286
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1241
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1613
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3687
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
A functional-style cast.
Definition: Sema.h:9397
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:12176
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1137
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...
Definition: Decl.cpp:3300
Transparent Union Conversions.
Definition: Overload.h:147
Retains information about a captured region.
Definition: ScopeInfo.h:737
CastKind
CastKind - The kind of operation required for a conversion.
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:157
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
Definition: Expr.cpp:1844
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:569
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...
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:6538
Defines a function that returns the minimum OS versions supporting C++17&#39;s aligned allocation functio...
SourceRange getRange() const
Definition: DeclSpec.h:68
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:865
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
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...
TST getTypeSpecType() const
Definition: DeclSpec.h:483
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:3101
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:136
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
unsigned hasStatic
True if this dimension included the &#39;static&#39; keyword.
Definition: DeclSpec.h:1204
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:190
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type...
Definition: ExprCXX.h:1871
CXXMethodDecl * CallOperator
The lambda&#39;s compiler-generated operator().
Definition: ScopeInfo.h:791
QualType getElementType() const
Definition: Type.h:2490
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
Definition: Decl.cpp:4394
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:2777
This represents one expression.
Definition: Expr.h:106
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:1611
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:107
static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, DeclAccessPair FoundDecl, bool HadMultipleCandidates, Expr *From)
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2689
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:51
bool isDeclScope(Decl *D)
isDeclScope - Return true if this is the scope that the specified decl is declared in...
Definition: Scope.h:321
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
unsigned getIntWidth() const
getIntWidth/Align - Return the size of &#39;signed int&#39; and &#39;unsigned int&#39; for this target, in bits.
Definition: TargetInfo.h:383
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:3883
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, SourceLocation KeyLoc, QualType T)
DeclContext * getEntity() const
Definition: Scope.h:325
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:1263
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion...
Definition: Overload.h:373
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6811
bool isObjCRetainableType() const
Definition: Type.cpp:3921
Inits[]
Definition: OpenMPClause.h:151
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5177
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2706
New-expression has a C++11 list-initializer.
Definition: ExprCXX.h:1974
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...
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:240
Expr * getCallee()
Definition: Expr.h:2514
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1983
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:547
Zero constant to queue.
Definition: Overload.h:156
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
Defines the clang::Preprocessor interface.
bool isNullPtrType() const
Definition: Type.h:6569
bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaInternal.h:44
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:14233
#define bool
Definition: stdbool.h:31
bool isFileContext() const
Definition: DeclBase.h:1818
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:301
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:288
DeclContext * getDeclContext()
Definition: DeclBase.h:427
Overload resolution succeeded.
Definition: Overload.h:54
bool isAnyComplexType() const
Definition: Type.h:6377
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:13986
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:264
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:16704
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2532
Represents a C++ template name within the type system.
Definition: TemplateName.h:179
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:7598
Defines the clang::TypeLoc interface and its subclasses.
A namespace alias, stored as a NamespaceAliasDecl*.
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:117
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1016
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7)...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:14551
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2440
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:715
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
Definition: Type.cpp:1844
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1337
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, QualType RhsT, SourceLocation KeyLoc)
QualType getType() const
Definition: Expr.h:128
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
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:1621
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:552
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1154
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence...
Definition: Overload.h:526
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:207
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type...
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1752
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
static void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl *> &VBases, llvm::SetVector< CXXRecordDecl *> &PublicSubobjectsSeen, bool ParentIsPublic)
A boolean condition, from &#39;if&#39;, &#39;while&#39;, &#39;for&#39;, or &#39;do&#39;.
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:904
QualType getRecordType(const RecordDecl *Decl) const
ConditionKind
Definition: Sema.h:9921
bool isInvalid() const
Definition: Ownership.h:170
SourceLocation getEnd() const
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1896
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, QualType T, Expr *DimExpr, SourceLocation KeyLoc)
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:1380
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition: CFG.cpp:2407
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.
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
Definition: SemaExprCXX.cpp:49
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1078
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:15565
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4709
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:6688
The symbol exists.
Definition: Sema.h:4513
ValueDecl * getDecl()
Definition: Expr.h:1114
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ &#39;delete&#39; expression.
bool isUsable() const
Definition: Ownership.h:171
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2768
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:1396
The result type of a method or function.
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2026
bool isUnionType() const
Definition: Type.cpp:475
const Expr * getSubExpr() const
Definition: ExprCXX.h:1240
void removeLocalCVRQualifiers(unsigned Mask)
Definition: Type.h:6178
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:703
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class.copy]p25)
Definition: DeclCXX.h:1470
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:404
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:281
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:301
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:6105
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
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:124
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:412
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3537
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:84
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:3613
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6131
RecordDecl * getDecl() const
Definition: Type.h:4380
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr *> Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8235
noexcept(expression), evals to &#39;false&#39;
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void EraseUnwantedCUDAMatches(const FunctionDecl *Caller, 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:214
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
Expr * getArgument()
Definition: ExprCXX.h:2212
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1565
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
CanThrowResult
Possible results from evaluation of a noexcept expression.
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
CanQualType OverloadTy
Definition: ASTContext.h:1045
There is no lifetime qualification on this type.
Definition: Type.h:158
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Definition: Expr.h:945
llvm::cl::opt< std::string > Filter
Integral conversions (C++ [conv.integral])
Definition: Overload.h:108
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:924
Complex promotions (Clang extension)
Definition: Overload.h:105
#define false
Definition: stdbool.h:33
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor...
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:169
Kind
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:924
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:487
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:157
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3743
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
LookupInObjCMethod - The parser has read a name in, and Sema has detected that we&#39;re currently inside...
Definition: SemaExpr.cpp:2413
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
Definition: Expr.h:191
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:730
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef< Expr *> PlacementArgs, SourceRange TypeIdParens, Expr *ArraySize, InitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange)
Create a c++ new expression.
Definition: ExprCXX.cpp:179
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:839
ASTContext & getASTContext() const
Definition: Sema.h:1238
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1450
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:3438
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:4396
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:5963
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6188
Represents a C++ temporary.
Definition: ExprCXX.h:1185
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2095
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:788
CastKind getCastKind() const
Definition: Expr.h:3044
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2287
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)"...
Definition: ExprCXX.h:1914
DeclarationName getName() const
getName - Returns the embedded declaration name.
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:277
Represents a call to a member function that may be written either with member call syntax (e...
Definition: ExprCXX.h:171
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9196
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:823
A vector splat from an arithmetic type.
Definition: Overload.h:138
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl *> &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or delete[] operator with a particular signature.
Definition: DeclCXX.cpp:2031
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:124
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1759
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2041
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:237
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1250
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2413
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:553
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
No ref-qualifier was provided.
Definition: Type.h:1360
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:5229
CanQualType FloatTy
Definition: ASTContext.h:1028
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1198
Objective-C ARC writeback conversion.
Definition: Overload.h:150
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2285
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:69
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:9404
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
CanQualType VoidTy
Definition: ASTContext.h:1016
bool isArray() const
Definition: ExprCXX.h:2038
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
Describes the kind of initialization being performed, along with location information for tokens rela...
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:149
static void getUnambiguousPublicSubobjects(CXXRecordDecl *RD, llvm::SmallVectorImpl< CXXRecordDecl *> &Objects)
Look up any declaration with any name.
Definition: Sema.h:3095
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:8155
bool isMemberFunctionPointerType() const
Definition: Type.h:6331
bool isAnyPointerType() const
Definition: Type.h:6300
bool isObjCObjectPointerType() const
Definition: Type.h:6393
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...
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:120
const TypoExprState & getTypoExprState(TypoExpr *TE) const
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax...
Definition: Overload.h:848
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Expr *ArraySize, SourceRange DirectInitRange, Expr *Initializer)
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3115
static bool VariableCanNeverBeAConstantExpression(VarDecl *Var, ASTContext &Context)
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after...
Definition: Type.h:1152
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language...
Definition: Expr.h:249
Requests that all candidates be shown.
Definition: Overload.h:69
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:212
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:1810
No entity found met the criteria.
Definition: Lookup.h:51
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=None)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
TypeClass getTypeClass() const
Definition: Type.h:1811
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...
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1958
The name is a dependent name, so the results will differ from one instantiation to the next...
Definition: Sema.h:4520
An expression trait intrinsic.
Definition: ExprCXX.h:2580
EnumDecl * getDecl() const
Definition: Type.h:4403
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:132
bool isVectorType() const
Definition: Type.h:6381
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:141
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1366
Assigning into this object requires a lifetime extension.
Definition: Type.h:175
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:3801
static Expr * captureThis(Sema &S, ASTContext &Context, RecordDecl *RD, QualType ThisTy, SourceLocation Loc, const bool ByCopy)
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:117
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13...
Definition: Overload.h:837
Constant expression in a noptr-new-declarator.
Definition: Sema.h:2643
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
ActOnCXXNew - Parsed a C++ &#39;new&#39; expression.
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, SourceLocation Loc, QualType ArgTy)
Check the completeness of a type in a unary type trait.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2293
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:215
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
A POD class for pairing a NamedDecl* with an access specifier.
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists), where Base is an expression of class type and Member is the name of the member we&#39;re trying to find.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
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:6518
The scope of a struct/union/class definition.
Definition: Scope.h:66
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1889
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array&#39;s size can require, which limits the maximu...
Definition: Type.cpp:146
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:15762
Represents a template argument.
Definition: TemplateBase.h:51
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9125
static const TST TST_decltype_auto
Definition: DeclSpec.h:301
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
This file provides some common utility functions for processing Lambdas.
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:302
static bool isInvalid(LocType Loc, bool *Invalid)
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2535
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:2653
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1362
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1723
ExtInfo getExtInfo() const
Definition: Type.h:3624
not evaluated yet, for special member function
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn&#39;t...
CanQualType NullPtrTy
Definition: ASTContext.h:1044
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
Represents a delete expression for memory deallocation and destructor calls, e.g. ...
Definition: ExprCXX.h:2170
static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, Expr *Init)
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl *> OperatorArrows)
Note a set of &#39;operator->&#39; functions that were used for a member access.
static const TST TST_decltype
Definition: DeclSpec.h:300
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:22
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:226
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type &#39;Type&#39;, insert an implicit cast.
Definition: Sema.cpp:474
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
CXXScopeSpec SS
The nested-name-specifier that precedes the template name.
SourceLocation RAngleLoc
The location of the &#39;>&#39; after the template argument list.
Optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:173
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:118
AccessSpecifier getAccess() const
Definition: DeclBase.h:462
Conversions allowed in C, but not C++.
Definition: Overload.h:159
A constant boolean condition from &#39;if constexpr&#39;.
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:87
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2251
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared...
Definition: Sema.h:909
The name of a declaration.
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition: Overload.h:356
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:971
const CXXRecordDecl * getParent() const
Returns the parent of this method declaration, which is the class in which this method is defined...
Definition: DeclCXX.h:2166
bool isBooleanType() const
Definition: Type.h:6657
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:6270
AllocationFunctionScope
The scope in which to find allocation functions.
Definition: Sema.h:5224
Requests that only viable candidates be shown.
Definition: Overload.h:72
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2756
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2103
IdentifierResolver IdResolver
Definition: Sema.h:823
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type. ...
Definition: Type.cpp:2007
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:529
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1396
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:25
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the &#39;template&#39; keyword, stored as a Type*.
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:3975
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:4996
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class.copy]p11, C++11 [class.copy]p25)
Definition: DeclCXX.h:1456
bool hasCVRQualifiers() const
Definition: Type.h:273
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2693
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Definition: Sema.h:582
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:378
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression&#39;s result is syntactically ignored, perform any conversions that are required.
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:3719
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:151
Pointer to a block type.
Definition: Type.h:2639
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:60
static void DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, const MismatchingNewDeleteDetector &Detector)
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2221
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:83
bool isIncompleteArrayType() const
Definition: Type.h:6353
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a method that was resolved from an overloaded...
Definition: Expr.h:2900
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4370
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:27
Complex values, per C99 6.2.5p11.
Definition: Type.h:2477
CanQualType UnknownAnyTy
Definition: ASTContext.h:1045
The lookup is a reference to this name that is not for the purpose of redeclaring the name...
Definition: Sema.h:3103
CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition: SemaCUDA.cpp:163
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2256
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:6578
Look for allocation functions in both the global scope and in the scope of the allocated class...
Definition: Sema.h:5232
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1062
arg_iterator arg_begin()
Definition: Expr.h:2590
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2074
CanQualType DependentTy
Definition: ASTContext.h:1045
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
bool isFunctionType() const
Definition: Type.h:6292
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where &#39;this&#39; may be allowed (when enabled), using the given declaration (which ...
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:8138
CanQualType BoundMemberTy
Definition: ASTContext.h:1045
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2269
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1041
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl)
Checks access to an overloaded member operator, including conversion operators.
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional< unsigned > DependentDeductionDepth=None)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:12867
The template argument is a type.
Definition: TemplateBase.h:60
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
ExceptionSpecificationType
The various types of exception specifications that exist in C++11.
Block Pointer conversions.
Definition: Overload.h:144
Holds information about the various types of exception specification.
Definition: Type.h:3741
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:92
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1507
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:251
The "class" keyword.
Definition: Type.h:5042
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2806
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:29
SmallVector< BlockDecl *, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:538
Represents a base class of a C++ class.
Definition: DeclCXX.h:192
unsigned getNumPotentialVariableCaptures() const
Definition: ScopeInfo.h:976
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:129
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2591
Capture & getCXXThisCapture()
Retrieve the capture of C++ &#39;this&#39;, if it has been captured.
Definition: ScopeInfo.h:677
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1866
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2070
Condition in a constexpr if statement.
Definition: Sema.h:2644
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:3746
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:2031
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...
bool isClassType() const
Definition: Type.cpp:437
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.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2253
EnumDecl * getStdAlignValT() const
A template argument list.
Definition: DeclTemplate.h:210
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
bool isLValueReferenceType() const
Definition: Type.h:6312
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:2762
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:238
CXXRecordDecl * getNamingClass() const
Returns the &#39;naming class&#39; for this lookup, i.e.
Definition: Lookup.h:392
Reading or writing from this object requires a barrier call.
Definition: Type.h:172
An integral condition for a &#39;switch&#39; statement.
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr *> Args, QualType Ty, ExprValueKind VK, SourceLocation RP, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:615
QualType getParamType(unsigned i) const
Definition: Type.h:3890
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups, surround it with a ExprWithCleanups node.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:90
bool Failed() const
Determine whether the initialization sequence is invalid.
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1009
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2682
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
Describes the sequence of initializations required to initialize a given object or reference with a s...
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
ActionResult< Expr * > ExprResult
Definition: Ownership.h:267
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6152
Only look for allocation functions in the global scope.
Definition: Sema.h:5226
Represents a C++ struct/union/class.
Definition: DeclCXX.h:300
Compatible - the types are compatible according to the standard.
Definition: Sema.h:9524
bool isValid() const
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 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 BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo *> Args, SourceLocation RParenLoc)
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type...
bool isVoidType() const
Definition: Type.h:6544
static bool hasAnyTypeDependentArguments(ArrayRef< Expr *> Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:2886
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:3655
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:919
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1212
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)
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6099
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1854
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:336
bool isCXXThisCaptured() const
Determine whether the C++ &#39;this&#39; is captured.
Definition: ScopeInfo.h:674
bool isRValue() const
Definition: Expr.h:250
Declaration of a class template.
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:3877
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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:129
This class is used for builtin types like &#39;int&#39;.
Definition: Type.h:2391
void addAttr(Attr *A)
Definition: DeclBase.cpp:840
SourceManager & getSourceManager() const
Definition: Sema.h:1236
iterator end() const
Definition: Lookup.h:325
A template-id, e.g., f<int>.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:276
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1316
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1566
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2396
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion)
type checking for vector binary operators.
Definition: SemaExpr.cpp:8665
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3637
ExprResult ExprError()
Definition: Ownership.h:283
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:234
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type...
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
static OpaquePtr make(QualType P)
Definition: Ownership.h:61
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:6260
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2079
static bool canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, QualType DestructedType)
Check if it&#39;s ok to try and recover dot pseudo destructor calls on pointer objects.
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1041
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:819
bool isUnion() const
Definition: Decl.h:3252
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4841
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2136
bool isPointerType() const
Definition: Type.h:6296
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:153
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:359
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion...
Definition: Overload.h:235
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:66
No viable function found.
Definition: Overload.h:57
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:572
QualType getType() const
Definition: Decl.h:648
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:114
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:328
bool isFloatingType() const
Definition: Type.cpp:1921
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:324
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1428
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we&#39;re implicitly casting from a _Nullable pointer type to a _Nonnull one. ...
Definition: Sema.cpp:432
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:16113
This represents a decl that may have a name.
Definition: Decl.h:249
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:562
Expr * getRepAsExpr() const
Definition: DeclSpec.h:500
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:457
CanQualType BoolTy
Definition: ASTContext.h:1017
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression&#39;s return type is complete.
Definition: SemaExpr.cpp:15985
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:887
No keyword precedes the qualified type name.
Definition: Type.h:5071
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1550
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:12751
iterator begin() const
Definition: Lookup.h:324
bool isInterfaceType() const
Definition: Type.cpp:455
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:123
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:595
Describes an entity that is being initialized.
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:3762
unsigned NumArgs
NumArgs - The number of template arguments.
void DiagnoseSentinelCalls(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:339
The global specifier &#39;::&#39;. There is no stored value.
Decl * getCalleeDecl()
Definition: Expr.h:2526
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, bool IsDelete, FunctionDecl *&Operator)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3055
ctor_range ctors() const
Definition: DeclCXX.h:885
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:92
SourceLocation getBegin() const
AssignmentAction
Definition: Sema.h:2525
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:707
void WillReplaceSpecifier(bool ForceReplacement)
No in-class initializer.
Definition: Specifiers.h:230
void NoteCandidates(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...
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2872
This scope corresponds to an Objective-C method body.
Definition: Scope.h:96
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3773
The symbol does not exist.
Definition: Sema.h:4516
Declaration of a template function.
Definition: DeclTemplate.h:969
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals)
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals...
Attr - This represents one attribute.
Definition: Attr.h:44
SourceLocation getLocation() const
Definition: DeclBase.h:418
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign=false)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6...
Definition: SemaExpr.cpp:1257
QualType getPointeeType() const
Definition: Type.h:2776
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5165
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:98
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3189
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
noexcept(expression), evals to &#39;true&#39;
Helper class that creates diagnostics with optional template instantiation stacks.
Definition: Sema.h:1261
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form, which contains extra information on the evaluated value of the initializer.
Definition: Decl.cpp:2244
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2560
QualType getIncompleteArrayType(QualType EltTy, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type...
const FormatStyle & Style
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:7589
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1058
Structure used to store a statement, the constant value to which it was evaluated (if any)...
Definition: Decl.h:784
A RAII object to temporarily push a declaration context.
Definition: Sema.h:728
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:6270
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3.1.1).
Definition: Overload.h:230