clang  9.0.0svn
SemaExprCXX.cpp
Go to the documentation of this file.
1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Implements semantic analysis for C++ expressions.
11 ///
12 //===----------------------------------------------------------------------===//
13 
15 #include "TreeTransform.h"
16 #include "TypeLocBuilder.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
42 using namespace sema;
43 
44 /// Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
49  SourceLocation NameLoc,
50  IdentifierInfo &Name) {
51  NestedNameSpecifier *NNS = SS.getScopeRep();
52 
53  // Convert the nested-name-specifier into a type.
54  QualType Type;
55  switch (NNS->getKind()) {
58  Type = QualType(NNS->getAsType(), 0);
59  break;
60 
62  // Strip off the last layer of the nested-name-specifier and build a
63  // typename type for it.
64  assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65  Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66  NNS->getAsIdentifier());
67  break;
68 
73  llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74  }
75 
76  // This reference to the type is located entirely at the location of the
77  // final identifier in the qualified-id.
78  return CreateParsedType(Type,
79  Context.getTrivialTypeSourceInfo(Type, NameLoc));
80 }
81 
83  SourceLocation NameLoc,
84  Scope *S, CXXScopeSpec &SS,
85  bool EnteringContext) {
86  CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
87  assert(CurClass && &II == CurClass->getIdentifier() &&
88  "not a constructor name");
89 
90  // When naming a constructor as a member of a dependent context (eg, in a
91  // friend declaration or an inherited constructor declaration), form an
92  // unresolved "typename" type.
93  if (CurClass->isDependentContext() && !EnteringContext) {
94  QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
95  return ParsedType::make(T);
96  }
97 
98  if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
99  return ParsedType();
100 
101  // Find the injected-class-name declaration. Note that we make no attempt to
102  // diagnose cases where the injected-class-name is shadowed: the only
103  // declaration that can validly shadow the injected-class-name is a
104  // non-static data member, and if the class contains both a non-static data
105  // member and a constructor then it is ill-formed (we check that in
106  // CheckCompletedCXXClass).
107  CXXRecordDecl *InjectedClassName = nullptr;
108  for (NamedDecl *ND : CurClass->lookup(&II)) {
109  auto *RD = dyn_cast<CXXRecordDecl>(ND);
110  if (RD && RD->isInjectedClassName()) {
111  InjectedClassName = RD;
112  break;
113  }
114  }
115  if (!InjectedClassName) {
116  if (!CurClass->isInvalidDecl()) {
117  // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
118  // properly. Work around it here for now.
120  diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
121  }
122  return ParsedType();
123  }
124 
125  QualType T = Context.getTypeDeclType(InjectedClassName);
126  DiagnoseUseOfDecl(InjectedClassName, NameLoc);
127  MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
128 
129  return ParsedType::make(T);
130 }
131 
133  IdentifierInfo &II,
134  SourceLocation NameLoc,
135  Scope *S, CXXScopeSpec &SS,
136  ParsedType ObjectTypePtr,
137  bool EnteringContext) {
138  // Determine where to perform name lookup.
139 
140  // FIXME: This area of the standard is very messy, and the current
141  // wording is rather unclear about which scopes we search for the
142  // destructor name; see core issues 399 and 555. Issue 399 in
143  // particular shows where the current description of destructor name
144  // lookup is completely out of line with existing practice, e.g.,
145  // this appears to be ill-formed:
146  //
147  // namespace N {
148  // template <typename T> struct S {
149  // ~S();
150  // };
151  // }
152  //
153  // void f(N::S<int>* s) {
154  // s->N::S<int>::~S();
155  // }
156  //
157  // See also PR6358 and PR6359.
158  // For this reason, we're currently only doing the C++03 version of this
159  // code; the C++0x version has to wait until we get a proper spec.
160  QualType SearchType;
161  DeclContext *LookupCtx = nullptr;
162  bool isDependent = false;
163  bool LookInScope = false;
164 
165  if (SS.isInvalid())
166  return nullptr;
167 
168  // If we have an object type, it's because we are in a
169  // pseudo-destructor-expression or a member access expression, and
170  // we know what type we're looking for.
171  if (ObjectTypePtr)
172  SearchType = GetTypeFromParser(ObjectTypePtr);
173 
174  if (SS.isSet()) {
175  NestedNameSpecifier *NNS = SS.getScopeRep();
176 
177  bool AlreadySearched = false;
178  bool LookAtPrefix = true;
179  // C++11 [basic.lookup.qual]p6:
180  // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
181  // the type-names are looked up as types in the scope designated by the
182  // nested-name-specifier. Similarly, in a qualified-id of the form:
183  //
184  // nested-name-specifier[opt] class-name :: ~ class-name
185  //
186  // the second class-name is looked up in the same scope as the first.
187  //
188  // Here, we determine whether the code below is permitted to look at the
189  // prefix of the nested-name-specifier.
190  DeclContext *DC = computeDeclContext(SS, EnteringContext);
191  if (DC && DC->isFileContext()) {
192  AlreadySearched = true;
193  LookupCtx = DC;
194  isDependent = false;
195  } else if (DC && isa<CXXRecordDecl>(DC)) {
196  LookAtPrefix = false;
197  LookInScope = true;
198  }
199 
200  // The second case from the C++03 rules quoted further above.
201  NestedNameSpecifier *Prefix = nullptr;
202  if (AlreadySearched) {
203  // Nothing left to do.
204  } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
205  CXXScopeSpec PrefixSS;
206  PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
207  LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
208  isDependent = isDependentScopeSpecifier(PrefixSS);
209  } else if (ObjectTypePtr) {
210  LookupCtx = computeDeclContext(SearchType);
211  isDependent = SearchType->isDependentType();
212  } else {
213  LookupCtx = computeDeclContext(SS, EnteringContext);
214  isDependent = LookupCtx && LookupCtx->isDependentContext();
215  }
216  } else if (ObjectTypePtr) {
217  // C++ [basic.lookup.classref]p3:
218  // If the unqualified-id is ~type-name, the type-name is looked up
219  // in the context of the entire postfix-expression. If the type T
220  // of the object expression is of a class type C, the type-name is
221  // also looked up in the scope of class C. At least one of the
222  // lookups shall find a name that refers to (possibly
223  // cv-qualified) T.
224  LookupCtx = computeDeclContext(SearchType);
225  isDependent = SearchType->isDependentType();
226  assert((isDependent || !SearchType->isIncompleteType()) &&
227  "Caller should have completed object type");
228 
229  LookInScope = true;
230  } else {
231  // Perform lookup into the current scope (only).
232  LookInScope = true;
233  }
234 
235  TypeDecl *NonMatchingTypeDecl = nullptr;
236  LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
237  for (unsigned Step = 0; Step != 2; ++Step) {
238  // Look for the name first in the computed lookup context (if we
239  // have one) and, if that fails to find a match, in the scope (if
240  // we're allowed to look there).
241  Found.clear();
242  if (Step == 0 && LookupCtx) {
243  if (RequireCompleteDeclContext(SS, LookupCtx))
244  return nullptr;
245  LookupQualifiedName(Found, LookupCtx);
246  } else if (Step == 1 && LookInScope && S) {
247  LookupName(Found, S);
248  } else {
249  continue;
250  }
251 
252  // FIXME: Should we be suppressing ambiguities here?
253  if (Found.isAmbiguous())
254  return nullptr;
255 
256  if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
257  QualType T = Context.getTypeDeclType(Type);
258  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
259 
260  if (SearchType.isNull() || SearchType->isDependentType() ||
261  Context.hasSameUnqualifiedType(T, SearchType)) {
262  // We found our type!
263 
264  return CreateParsedType(T,
265  Context.getTrivialTypeSourceInfo(T, NameLoc));
266  }
267 
268  if (!SearchType.isNull())
269  NonMatchingTypeDecl = Type;
270  }
271 
272  // If the name that we found is a class template name, and it is
273  // the same name as the template name in the last part of the
274  // nested-name-specifier (if present) or the object type, then
275  // this is the destructor for that class.
276  // FIXME: This is a workaround until we get real drafting for core
277  // issue 399, for which there isn't even an obvious direction.
278  if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
279  QualType MemberOfType;
280  if (SS.isSet()) {
281  if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
282  // Figure out the type of the context, if it has one.
283  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
284  MemberOfType = Context.getTypeDeclType(Record);
285  }
286  }
287  if (MemberOfType.isNull())
288  MemberOfType = SearchType;
289 
290  if (MemberOfType.isNull())
291  continue;
292 
293  // We're referring into a class template specialization. If the
294  // class template we found is the same as the template being
295  // specialized, we found what we are looking for.
296  if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
298  = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
299  if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
300  Template->getCanonicalDecl())
301  return CreateParsedType(
302  MemberOfType,
303  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
304  }
305 
306  continue;
307  }
308 
309  // We're referring to an unresolved class template
310  // specialization. Determine whether we class template we found
311  // is the same as the template being specialized or, if we don't
312  // know which template is being specialized, that it at least
313  // has the same name.
314  if (const TemplateSpecializationType *SpecType
315  = MemberOfType->getAs<TemplateSpecializationType>()) {
316  TemplateName SpecName = SpecType->getTemplateName();
317 
318  // The class template we found is the same template being
319  // specialized.
320  if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
321  if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
322  return CreateParsedType(
323  MemberOfType,
324  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
325 
326  continue;
327  }
328 
329  // The class template we found has the same name as the
330  // (dependent) template name being specialized.
331  if (DependentTemplateName *DepTemplate
332  = SpecName.getAsDependentTemplateName()) {
333  if (DepTemplate->isIdentifier() &&
334  DepTemplate->getIdentifier() == Template->getIdentifier())
335  return CreateParsedType(
336  MemberOfType,
337  Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
338 
339  continue;
340  }
341  }
342  }
343  }
344 
345  if (isDependent) {
346  // We didn't find our type, but that's okay: it's dependent
347  // anyway.
348 
349  // FIXME: What if we have no nested-name-specifier?
350  QualType T = CheckTypenameType(ETK_None, SourceLocation(),
351  SS.getWithLocInContext(Context),
352  II, NameLoc);
353  return ParsedType::make(T);
354  }
355 
356  if (NonMatchingTypeDecl) {
357  QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
358  Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
359  << T << SearchType;
360  Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
361  << T;
362  } else if (ObjectTypePtr)
363  Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
364  << &II;
365  else {
366  SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
367  diag::err_destructor_class_name);
368  if (S) {
369  const DeclContext *Ctx = S->getEntity();
370  if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
371  DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
372  Class->getNameAsString());
373  }
374  }
375 
376  return nullptr;
377 }
378 
380  ParsedType ObjectType) {
382  return nullptr;
383 
385  Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
386  return nullptr;
387  }
388 
389  assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
390  "unexpected type in getDestructorType");
391  QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
392 
393  // If we know the type of the object, check that the correct destructor
394  // type was named now; we can give better diagnostics this way.
395  QualType SearchType = GetTypeFromParser(ObjectType);
396  if (!SearchType.isNull() && !SearchType->isDependentType() &&
397  !Context.hasSameUnqualifiedType(T, SearchType)) {
398  Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
399  << T << SearchType;
400  return nullptr;
401  }
402 
403  return ParsedType::make(T);
404 }
405 
407  const UnqualifiedId &Name) {
409 
410  if (!SS.isValid())
411  return false;
412 
413  switch (SS.getScopeRep()->getKind()) {
417  // Per C++11 [over.literal]p2, literal operators can only be declared at
418  // namespace scope. Therefore, this unqualified-id cannot name anything.
419  // Reject it early, because we have no AST representation for this in the
420  // case where the scope is dependent.
421  Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
422  << SS.getScopeRep();
423  return true;
424 
429  return false;
430  }
431 
432  llvm_unreachable("unknown nested name specifier kind");
433 }
434 
435 /// Build a C++ typeid expression with a type operand.
437  SourceLocation TypeidLoc,
438  TypeSourceInfo *Operand,
439  SourceLocation RParenLoc) {
440  // C++ [expr.typeid]p4:
441  // The top-level cv-qualifiers of the lvalue expression or the type-id
442  // that is the operand of typeid are always ignored.
443  // If the type of the type-id is a class type or a reference to a class
444  // type, the class shall be completely-defined.
445  Qualifiers Quals;
446  QualType T
447  = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
448  Quals);
449  if (T->getAs<RecordType>() &&
450  RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
451  return ExprError();
452 
453  if (T->isVariablyModifiedType())
454  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
455 
456  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
457  SourceRange(TypeidLoc, RParenLoc));
458 }
459 
460 /// Build a C++ typeid expression with an expression operand.
462  SourceLocation TypeidLoc,
463  Expr *E,
464  SourceLocation RParenLoc) {
465  bool WasEvaluated = false;
466  if (E && !E->isTypeDependent()) {
467  if (E->getType()->isPlaceholderType()) {
468  ExprResult result = CheckPlaceholderExpr(E);
469  if (result.isInvalid()) return ExprError();
470  E = result.get();
471  }
472 
473  QualType T = E->getType();
474  if (const RecordType *RecordT = T->getAs<RecordType>()) {
475  CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
476  // C++ [expr.typeid]p3:
477  // [...] If the type of the expression is a class type, the class
478  // shall be completely-defined.
479  if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
480  return ExprError();
481 
482  // C++ [expr.typeid]p3:
483  // When typeid is applied to an expression other than an glvalue of a
484  // polymorphic class type [...] [the] expression is an unevaluated
485  // operand. [...]
486  if (RecordD->isPolymorphic() && E->isGLValue()) {
487  // The subexpression is potentially evaluated; switch the context
488  // and recheck the subexpression.
489  ExprResult Result = TransformToPotentiallyEvaluated(E);
490  if (Result.isInvalid()) return ExprError();
491  E = Result.get();
492 
493  // We require a vtable to query the type at run time.
494  MarkVTableUsed(TypeidLoc, RecordD);
495  WasEvaluated = true;
496  }
497  }
498 
499  // C++ [expr.typeid]p4:
500  // [...] If the type of the type-id is a reference to a possibly
501  // cv-qualified type, the result of the typeid expression refers to a
502  // std::type_info object representing the cv-unqualified referenced
503  // type.
504  Qualifiers Quals;
505  QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
506  if (!Context.hasSameType(T, UnqualT)) {
507  T = UnqualT;
508  E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
509  }
510  }
511 
512  if (E->getType()->isVariablyModifiedType())
513  return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
514  << E->getType());
515  else if (!inTemplateInstantiation() &&
516  E->HasSideEffects(Context, WasEvaluated)) {
517  // The expression operand for typeid is in an unevaluated expression
518  // context, so side effects could result in unintended consequences.
519  Diag(E->getExprLoc(), WasEvaluated
520  ? diag::warn_side_effects_typeid
521  : diag::warn_side_effects_unevaluated_context);
522  }
523 
524  return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
525  SourceRange(TypeidLoc, RParenLoc));
526 }
527 
528 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
531  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
532  // OpenCL C++ 1.0 s2.9: typeid is not supported.
533  if (getLangOpts().OpenCLCPlusPlus) {
534  return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
535  << "typeid");
536  }
537 
538  // Find the std::type_info type.
539  if (!getStdNamespace())
540  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
541 
542  if (!CXXTypeInfoDecl) {
543  IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
544  LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
545  LookupQualifiedName(R, getStdNamespace());
546  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
547  // Microsoft's typeinfo doesn't have type_info in std but in the global
548  // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
549  if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
550  LookupQualifiedName(R, Context.getTranslationUnitDecl());
551  CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
552  }
553  if (!CXXTypeInfoDecl)
554  return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
555  }
556 
557  if (!getLangOpts().RTTI) {
558  return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
559  }
560 
561  QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
562 
563  if (isType) {
564  // The operand is a type; handle it as such.
565  TypeSourceInfo *TInfo = nullptr;
566  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
567  &TInfo);
568  if (T.isNull())
569  return ExprError();
570 
571  if (!TInfo)
572  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
573 
574  return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
575  }
576 
577  // The operand is an expression.
578  return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
579 }
580 
581 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
582 /// a single GUID.
583 static void
586  // Optionally remove one level of pointer, reference or array indirection.
587  const Type *Ty = QT.getTypePtr();
588  if (QT->isPointerType() || QT->isReferenceType())
589  Ty = QT->getPointeeType().getTypePtr();
590  else if (QT->isArrayType())
591  Ty = Ty->getBaseElementTypeUnsafe();
592 
593  const auto *TD = Ty->getAsTagDecl();
594  if (!TD)
595  return;
596 
597  if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
598  UuidAttrs.insert(Uuid);
599  return;
600  }
601 
602  // __uuidof can grab UUIDs from template arguments.
603  if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
604  const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
605  for (const TemplateArgument &TA : TAL.asArray()) {
606  const UuidAttr *UuidForTA = nullptr;
607  if (TA.getKind() == TemplateArgument::Type)
608  getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
609  else if (TA.getKind() == TemplateArgument::Declaration)
610  getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
611 
612  if (UuidForTA)
613  UuidAttrs.insert(UuidForTA);
614  }
615  }
616 }
617 
618 /// Build a Microsoft __uuidof expression with a type operand.
620  SourceLocation TypeidLoc,
621  TypeSourceInfo *Operand,
622  SourceLocation RParenLoc) {
623  StringRef UuidStr;
624  if (!Operand->getType()->isDependentType()) {
626  getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
627  if (UuidAttrs.empty())
628  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
629  if (UuidAttrs.size() > 1)
630  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
631  UuidStr = UuidAttrs.back()->getGuid();
632  }
633 
634  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
635  SourceRange(TypeidLoc, RParenLoc));
636 }
637 
638 /// Build a Microsoft __uuidof expression with an expression operand.
640  SourceLocation TypeidLoc,
641  Expr *E,
642  SourceLocation RParenLoc) {
643  StringRef UuidStr;
644  if (!E->getType()->isDependentType()) {
646  UuidStr = "00000000-0000-0000-0000-000000000000";
647  } else {
649  getUuidAttrOfType(*this, E->getType(), UuidAttrs);
650  if (UuidAttrs.empty())
651  return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
652  if (UuidAttrs.size() > 1)
653  return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
654  UuidStr = UuidAttrs.back()->getGuid();
655  }
656  }
657 
658  return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
659  SourceRange(TypeidLoc, RParenLoc));
660 }
661 
662 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
665  bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
666  // If MSVCGuidDecl has not been cached, do the lookup.
667  if (!MSVCGuidDecl) {
668  IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
669  LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
670  LookupQualifiedName(R, Context.getTranslationUnitDecl());
671  MSVCGuidDecl = R.getAsSingle<RecordDecl>();
672  if (!MSVCGuidDecl)
673  return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
674  }
675 
676  QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
677 
678  if (isType) {
679  // The operand is a type; handle it as such.
680  TypeSourceInfo *TInfo = nullptr;
681  QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
682  &TInfo);
683  if (T.isNull())
684  return ExprError();
685 
686  if (!TInfo)
687  TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688 
689  return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
690  }
691 
692  // The operand is an expression.
693  return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
694 }
695 
696 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
699  assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
700  "Unknown C++ Boolean value!");
701  return new (Context)
702  CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
703 }
704 
705 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
708  return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
709 }
710 
711 /// ActOnCXXThrow - Parse throw expressions.
714  bool IsThrownVarInScope = false;
715  if (Ex) {
716  // C++0x [class.copymove]p31:
717  // When certain criteria are met, an implementation is allowed to omit the
718  // copy/move construction of a class object [...]
719  //
720  // - in a throw-expression, when the operand is the name of a
721  // non-volatile automatic object (other than a function or catch-
722  // clause parameter) whose scope does not extend beyond the end of the
723  // innermost enclosing try-block (if there is one), the copy/move
724  // operation from the operand to the exception object (15.1) can be
725  // omitted by constructing the automatic object directly into the
726  // exception object
727  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
728  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
729  if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
730  for( ; S; S = S->getParent()) {
731  if (S->isDeclScope(Var)) {
732  IsThrownVarInScope = true;
733  break;
734  }
735 
736  if (S->getFlags() &
740  break;
741  }
742  }
743  }
744  }
745 
746  return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
747 }
748 
750  bool IsThrownVarInScope) {
751  // Don't report an error if 'throw' is used in system headers.
752  if (!getLangOpts().CXXExceptions &&
753  !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
754  // Delay error emission for the OpenMP device code.
755  targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
756  }
757 
758  // Exceptions aren't allowed in CUDA device code.
759  if (getLangOpts().CUDA)
760  CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
761  << "throw" << CurrentCUDATarget();
762 
763  if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
764  Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
765 
766  if (Ex && !Ex->isTypeDependent()) {
767  QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
768  if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
769  return ExprError();
770 
771  // Initialize the exception result. This implicitly weeds out
772  // abstract types or types with inaccessible copy constructors.
773 
774  // C++0x [class.copymove]p31:
775  // When certain criteria are met, an implementation is allowed to omit the
776  // copy/move construction of a class object [...]
777  //
778  // - in a throw-expression, when the operand is the name of a
779  // non-volatile automatic object (other than a function or
780  // catch-clause
781  // parameter) whose scope does not extend beyond the end of the
782  // innermost enclosing try-block (if there is one), the copy/move
783  // operation from the operand to the exception object (15.1) can be
784  // omitted by constructing the automatic object directly into the
785  // exception object
786  const VarDecl *NRVOVariable = nullptr;
787  if (IsThrownVarInScope)
788  NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
789 
791  OpLoc, ExceptionObjectTy,
792  /*NRVO=*/NRVOVariable != nullptr);
793  ExprResult Res = PerformMoveOrCopyInitialization(
794  Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
795  if (Res.isInvalid())
796  return ExprError();
797  Ex = Res.get();
798  }
799 
800  return new (Context)
801  CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
802 }
803 
804 static void
806  llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
807  llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
808  llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
809  bool ParentIsPublic) {
810  for (const CXXBaseSpecifier &BS : RD->bases()) {
811  CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
812  bool NewSubobject;
813  // Virtual bases constitute the same subobject. Non-virtual bases are
814  // always distinct subobjects.
815  if (BS.isVirtual())
816  NewSubobject = VBases.insert(BaseDecl).second;
817  else
818  NewSubobject = true;
819 
820  if (NewSubobject)
821  ++SubobjectsSeen[BaseDecl];
822 
823  // Only add subobjects which have public access throughout the entire chain.
824  bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
825  if (PublicPath)
826  PublicSubobjectsSeen.insert(BaseDecl);
827 
828  // Recurse on to each base subobject.
829  collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
830  PublicPath);
831  }
832 }
833 
836  llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
837  llvm::SmallSet<CXXRecordDecl *, 2> VBases;
838  llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
839  SubobjectsSeen[RD] = 1;
840  PublicSubobjectsSeen.insert(RD);
841  collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
842  /*ParentIsPublic=*/true);
843 
844  for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
845  // Skip ambiguous objects.
846  if (SubobjectsSeen[PublicSubobject] > 1)
847  continue;
848 
849  Objects.push_back(PublicSubobject);
850  }
851 }
852 
853 /// CheckCXXThrowOperand - Validate the operand of a throw.
855  QualType ExceptionObjectTy, Expr *E) {
856  // If the type of the exception would be an incomplete type or a pointer
857  // to an incomplete type other than (cv) void the program is ill-formed.
858  QualType Ty = ExceptionObjectTy;
859  bool isPointer = false;
860  if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
861  Ty = Ptr->getPointeeType();
862  isPointer = true;
863  }
864  if (!isPointer || !Ty->isVoidType()) {
865  if (RequireCompleteType(ThrowLoc, Ty,
866  isPointer ? diag::err_throw_incomplete_ptr
867  : diag::err_throw_incomplete,
868  E->getSourceRange()))
869  return true;
870 
871  if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
872  diag::err_throw_abstract_type, E))
873  return true;
874  }
875 
876  // If the exception has class type, we need additional handling.
877  CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
878  if (!RD)
879  return false;
880 
881  // If we are throwing a polymorphic class type or pointer thereof,
882  // exception handling will make use of the vtable.
883  MarkVTableUsed(ThrowLoc, RD);
884 
885  // If a pointer is thrown, the referenced object will not be destroyed.
886  if (isPointer)
887  return false;
888 
889  // If the class has a destructor, we must be able to call it.
890  if (!RD->hasIrrelevantDestructor()) {
891  if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
892  MarkFunctionReferenced(E->getExprLoc(), Destructor);
893  CheckDestructorAccess(E->getExprLoc(), Destructor,
894  PDiag(diag::err_access_dtor_exception) << Ty);
895  if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
896  return true;
897  }
898  }
899 
900  // The MSVC ABI creates a list of all types which can catch the exception
901  // object. This list also references the appropriate copy constructor to call
902  // if the object is caught by value and has a non-trivial copy constructor.
903  if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
904  // We are only interested in the public, unambiguous bases contained within
905  // the exception object. Bases which are ambiguous or otherwise
906  // inaccessible are not catchable types.
907  llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
908  getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
909 
910  for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
911  // Attempt to lookup the copy constructor. Various pieces of machinery
912  // will spring into action, like template instantiation, which means this
913  // cannot be a simple walk of the class's decls. Instead, we must perform
914  // lookup and overload resolution.
915  CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
916  if (!CD)
917  continue;
918 
919  // Mark the constructor referenced as it is used by this throw expression.
920  MarkFunctionReferenced(E->getExprLoc(), CD);
921 
922  // Skip this copy constructor if it is trivial, we don't need to record it
923  // in the catchable type data.
924  if (CD->isTrivial())
925  continue;
926 
927  // The copy constructor is non-trivial, create a mapping from this class
928  // type to this constructor.
929  // N.B. The selection of copy constructor is not sensitive to this
930  // particular throw-site. Lookup will be performed at the catch-site to
931  // ensure that the copy constructor is, in fact, accessible (via
932  // friendship or any other means).
933  Context.addCopyConstructorForExceptionObject(Subobject, CD);
934 
935  // We don't keep the instantiated default argument expressions around so
936  // we must rebuild them here.
937  for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
938  if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
939  return true;
940  }
941  }
942  }
943 
944  // Under the Itanium C++ ABI, memory for the exception object is allocated by
945  // the runtime with no ability for the compiler to request additional
946  // alignment. Warn if the exception type requires alignment beyond the minimum
947  // guaranteed by the target C++ runtime.
948  if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
949  CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
950  CharUnits ExnObjAlign = Context.getExnObjectAlignment();
951  if (ExnObjAlign < TypeAlign) {
952  Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
953  Diag(ThrowLoc, diag::note_throw_underaligned_obj)
954  << Ty << (unsigned)TypeAlign.getQuantity()
955  << (unsigned)ExnObjAlign.getQuantity();
956  }
957  }
958 
959  return false;
960 }
961 
963  ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
964  DeclContext *CurSemaContext, ASTContext &ASTCtx) {
965 
966  QualType ClassType = ThisTy->getPointeeType();
967  LambdaScopeInfo *CurLSI = nullptr;
968  DeclContext *CurDC = CurSemaContext;
969 
970  // Iterate through the stack of lambdas starting from the innermost lambda to
971  // the outermost lambda, checking if '*this' is ever captured by copy - since
972  // that could change the cv-qualifiers of the '*this' object.
973  // The object referred to by '*this' starts out with the cv-qualifiers of its
974  // member function. We then start with the innermost lambda and iterate
975  // outward checking to see if any lambda performs a by-copy capture of '*this'
976  // - and if so, any nested lambda must respect the 'constness' of that
977  // capturing lamdbda's call operator.
978  //
979 
980  // Since the FunctionScopeInfo stack is representative of the lexical
981  // nesting of the lambda expressions during initial parsing (and is the best
982  // place for querying information about captures about lambdas that are
983  // partially processed) and perhaps during instantiation of function templates
984  // that contain lambda expressions that need to be transformed BUT not
985  // necessarily during instantiation of a nested generic lambda's function call
986  // operator (which might even be instantiated at the end of the TU) - at which
987  // time the DeclContext tree is mature enough to query capture information
988  // reliably - we use a two pronged approach to walk through all the lexically
989  // enclosing lambda expressions:
990  //
991  // 1) Climb down the FunctionScopeInfo stack as long as each item represents
992  // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
993  // enclosed by the call-operator of the LSI below it on the stack (while
994  // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
995  // the stack represents the innermost lambda.
996  //
997  // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
998  // represents a lambda's call operator. If it does, we must be instantiating
999  // a generic lambda's call operator (represented by the Current LSI, and
1000  // should be the only scenario where an inconsistency between the LSI and the
1001  // DeclContext should occur), so climb out the DeclContexts if they
1002  // represent lambdas, while querying the corresponding closure types
1003  // regarding capture information.
1004 
1005  // 1) Climb down the function scope info stack.
1006  for (int I = FunctionScopes.size();
1007  I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1008  (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1009  cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1010  CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1011  CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1012 
1013  if (!CurLSI->isCXXThisCaptured())
1014  continue;
1015 
1016  auto C = CurLSI->getCXXThisCapture();
1017 
1018  if (C.isCopyCapture()) {
1020  if (CurLSI->CallOperator->isConst())
1021  ClassType.addConst();
1022  return ASTCtx.getPointerType(ClassType);
1023  }
1024  }
1025 
1026  // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1027  // happen during instantiation of its nested generic lambda call operator)
1028  if (isLambdaCallOperator(CurDC)) {
1029  assert(CurLSI && "While computing 'this' capture-type for a generic "
1030  "lambda, we must have a corresponding LambdaScopeInfo");
1032  "While computing 'this' capture-type for a generic lambda, when we "
1033  "run out of enclosing LSI's, yet the enclosing DC is a "
1034  "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1035  "lambda call oeprator");
1036  assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1037 
1038  auto IsThisCaptured =
1039  [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1040  IsConst = false;
1041  IsByCopy = false;
1042  for (auto &&C : Closure->captures()) {
1043  if (C.capturesThis()) {
1044  if (C.getCaptureKind() == LCK_StarThis)
1045  IsByCopy = true;
1046  if (Closure->getLambdaCallOperator()->isConst())
1047  IsConst = true;
1048  return true;
1049  }
1050  }
1051  return false;
1052  };
1053 
1054  bool IsByCopyCapture = false;
1055  bool IsConstCapture = false;
1056  CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1057  while (Closure &&
1058  IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1059  if (IsByCopyCapture) {
1061  if (IsConstCapture)
1062  ClassType.addConst();
1063  return ASTCtx.getPointerType(ClassType);
1064  }
1065  Closure = isLambdaCallOperator(Closure->getParent())
1066  ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1067  : nullptr;
1068  }
1069  }
1070  return ASTCtx.getPointerType(ClassType);
1071 }
1072 
1074  DeclContext *DC = getFunctionLevelDeclContext();
1075  QualType ThisTy = CXXThisTypeOverride;
1076 
1077  if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1078  if (method && method->isInstance())
1079  ThisTy = method->getThisType();
1080  }
1081 
1082  if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1083  inTemplateInstantiation()) {
1084 
1085  assert(isa<CXXRecordDecl>(DC) &&
1086  "Trying to get 'this' type from static method?");
1087 
1088  // This is a lambda call operator that is being instantiated as a default
1089  // initializer. DC must point to the enclosing class type, so we can recover
1090  // the 'this' type from it.
1091 
1092  QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1093  // There are no cv-qualifiers for 'this' within default initializers,
1094  // per [expr.prim.general]p4.
1095  ThisTy = Context.getPointerType(ClassTy);
1096  }
1097 
1098  // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1099  // might need to be adjusted if the lambda or any of its enclosing lambda's
1100  // captures '*this' by copy.
1101  if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1102  return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1103  CurContext, Context);
1104  return ThisTy;
1105 }
1106 
1108  Decl *ContextDecl,
1109  Qualifiers CXXThisTypeQuals,
1110  bool Enabled)
1111  : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1112 {
1113  if (!Enabled || !ContextDecl)
1114  return;
1115 
1116  CXXRecordDecl *Record = nullptr;
1117  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1118  Record = Template->getTemplatedDecl();
1119  else
1120  Record = cast<CXXRecordDecl>(ContextDecl);
1121 
1122  QualType T = S.Context.getRecordType(Record);
1123  T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1124 
1126 
1127  this->Enabled = true;
1128 }
1129 
1130 
1132  if (Enabled) {
1133  S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1134  }
1135 }
1136 
1138  QualType ThisTy, SourceLocation Loc,
1139  const bool ByCopy) {
1140 
1141  QualType AdjustedThisTy = ThisTy;
1142  // The type of the corresponding data member (not a 'this' pointer if 'by
1143  // copy').
1144  QualType CaptureThisFieldTy = ThisTy;
1145  if (ByCopy) {
1146  // If we are capturing the object referred to by '*this' by copy, ignore any
1147  // cv qualifiers inherited from the type of the member function for the type
1148  // of the closure-type's corresponding data member and any use of 'this'.
1149  CaptureThisFieldTy = ThisTy->getPointeeType();
1150  CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1151  AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1152  }
1153 
1154  FieldDecl *Field = FieldDecl::Create(
1155  Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1156  Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1157  ICIS_NoInit);
1158 
1159  Field->setImplicit(true);
1160  Field->setAccess(AS_private);
1161  RD->addDecl(Field);
1162  Expr *This =
1163  new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1164  if (ByCopy) {
1165  Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1166  UO_Deref,
1167  This).get();
1169  nullptr, CaptureThisFieldTy, Loc);
1170  InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1171  InitializationSequence Init(S, Entity, InitKind, StarThis);
1172  ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1173  if (ER.isInvalid()) return nullptr;
1174  return ER.get();
1175  }
1176  return This;
1177 }
1178 
1179 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1180  bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1181  const bool ByCopy) {
1182  // We don't need to capture this in an unevaluated context.
1183  if (isUnevaluatedContext() && !Explicit)
1184  return true;
1185 
1186  assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1187 
1188  const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1189  ? *FunctionScopeIndexToStopAt
1190  : FunctionScopes.size() - 1;
1191 
1192  // Check that we can capture the *enclosing object* (referred to by '*this')
1193  // by the capturing-entity/closure (lambda/block/etc) at
1194  // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1195 
1196  // Note: The *enclosing object* can only be captured by-value by a
1197  // closure that is a lambda, using the explicit notation:
1198  // [*this] { ... }.
1199  // Every other capture of the *enclosing object* results in its by-reference
1200  // capture.
1201 
1202  // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1203  // stack), we can capture the *enclosing object* only if:
1204  // - 'L' has an explicit byref or byval capture of the *enclosing object*
1205  // - or, 'L' has an implicit capture.
1206  // AND
1207  // -- there is no enclosing closure
1208  // -- or, there is some enclosing closure 'E' that has already captured the
1209  // *enclosing object*, and every intervening closure (if any) between 'E'
1210  // and 'L' can implicitly capture the *enclosing object*.
1211  // -- or, every enclosing closure can implicitly capture the
1212  // *enclosing object*
1213 
1214 
1215  unsigned NumCapturingClosures = 0;
1216  for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1217  if (CapturingScopeInfo *CSI =
1218  dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1219  if (CSI->CXXThisCaptureIndex != 0) {
1220  // 'this' is already being captured; there isn't anything more to do.
1221  CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1222  break;
1223  }
1224  LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1226  // This context can't implicitly capture 'this'; fail out.
1227  if (BuildAndDiagnose)
1228  Diag(Loc, diag::err_this_capture)
1229  << (Explicit && idx == MaxFunctionScopesIndex);
1230  return true;
1231  }
1232  if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1233  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1234  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1235  CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1236  (Explicit && idx == MaxFunctionScopesIndex)) {
1237  // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1238  // iteration through can be an explicit capture, all enclosing closures,
1239  // if any, must perform implicit captures.
1240 
1241  // This closure can capture 'this'; continue looking upwards.
1242  NumCapturingClosures++;
1243  continue;
1244  }
1245  // This context can't implicitly capture 'this'; fail out.
1246  if (BuildAndDiagnose)
1247  Diag(Loc, diag::err_this_capture)
1248  << (Explicit && idx == MaxFunctionScopesIndex);
1249  return true;
1250  }
1251  break;
1252  }
1253  if (!BuildAndDiagnose) return false;
1254 
1255  // If we got here, then the closure at MaxFunctionScopesIndex on the
1256  // FunctionScopes stack, can capture the *enclosing object*, so capture it
1257  // (including implicit by-reference captures in any enclosing closures).
1258 
1259  // In the loop below, respect the ByCopy flag only for the closure requesting
1260  // the capture (i.e. first iteration through the loop below). Ignore it for
1261  // all enclosing closure's up to NumCapturingClosures (since they must be
1262  // implicitly capturing the *enclosing object* by reference (see loop
1263  // above)).
1264  assert((!ByCopy ||
1265  dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1266  "Only a lambda can capture the enclosing object (referred to by "
1267  "*this) by copy");
1268  // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1269  // contexts.
1270  QualType ThisTy = getCurrentThisType();
1271  for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1272  --idx, --NumCapturingClosures) {
1273  CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1274  Expr *ThisExpr = nullptr;
1275 
1276  if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1277  // For lambda expressions, build a field and an initializing expression,
1278  // and capture the *enclosing object* by copy only if this is the first
1279  // iteration.
1280  ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1281  ByCopy && idx == MaxFunctionScopesIndex);
1282 
1283  } else if (CapturedRegionScopeInfo *RSI
1284  = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1285  ThisExpr =
1286  captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1287  false/*ByCopy*/);
1288 
1289  bool isNested = NumCapturingClosures > 1;
1290  CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1291  }
1292  return false;
1293 }
1294 
1296  /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1297  /// is a non-lvalue expression whose value is the address of the object for
1298  /// which the function is called.
1299 
1300  QualType ThisTy = getCurrentThisType();
1301  if (ThisTy.isNull())
1302  return Diag(Loc, diag::err_invalid_this_use);
1303  return BuildCXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1304 }
1305 
1307  bool IsImplicit) {
1308  auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1309  MarkThisReferenced(This);
1310  return This;
1311 }
1312 
1315 }
1316 
1318  // If we're outside the body of a member function, then we'll have a specified
1319  // type for 'this'.
1321  return false;
1322 
1323  // Determine whether we're looking into a class that's currently being
1324  // defined.
1325  CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1326  return Class && Class->isBeingDefined();
1327 }
1328 
1329 /// Parse construction of a specified type.
1330 /// Can be interpreted either as function-style casting ("int(x)")
1331 /// or class type construction ("ClassType(x,y,z)")
1332 /// or creation of a value-initialized type ("int()").
1333 ExprResult
1335  SourceLocation LParenOrBraceLoc,
1336  MultiExprArg exprs,
1337  SourceLocation RParenOrBraceLoc,
1338  bool ListInitialization) {
1339  if (!TypeRep)
1340  return ExprError();
1341 
1342  TypeSourceInfo *TInfo;
1343  QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1344  if (!TInfo)
1346 
1347  auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1348  RParenOrBraceLoc, ListInitialization);
1349  // Avoid creating a non-type-dependent expression that contains typos.
1350  // Non-type-dependent expressions are liable to be discarded without
1351  // checking for embedded typos.
1352  if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1353  !Result.get()->isTypeDependent())
1355  return Result;
1356 }
1357 
1358 ExprResult
1360  SourceLocation LParenOrBraceLoc,
1361  MultiExprArg Exprs,
1362  SourceLocation RParenOrBraceLoc,
1363  bool ListInitialization) {
1364  QualType Ty = TInfo->getType();
1365  SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1366 
1368  // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1369  // directly. We work around this by dropping the locations of the braces.
1370  SourceRange Locs = ListInitialization
1371  ? SourceRange()
1372  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1373  return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1374  Exprs, Locs.getEnd());
1375  }
1376 
1377  assert((!ListInitialization ||
1378  (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1379  "List initialization must have initializer list as expression.");
1380  SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1381 
1384  Exprs.size()
1385  ? ListInitialization
1387  TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1388  : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1389  RParenOrBraceLoc)
1390  : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1391  RParenOrBraceLoc);
1392 
1393  // C++1z [expr.type.conv]p1:
1394  // If the type is a placeholder for a deduced class type, [...perform class
1395  // template argument deduction...]
1396  DeducedType *Deduced = Ty->getContainedDeducedType();
1397  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1399  Kind, Exprs);
1400  if (Ty.isNull())
1401  return ExprError();
1402  Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1403  }
1404 
1405  // C++ [expr.type.conv]p1:
1406  // If the expression list is a parenthesized single expression, the type
1407  // conversion expression is equivalent (in definedness, and if defined in
1408  // meaning) to the corresponding cast expression.
1409  if (Exprs.size() == 1 && !ListInitialization &&
1410  !isa<InitListExpr>(Exprs[0])) {
1411  Expr *Arg = Exprs[0];
1412  return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1413  RParenOrBraceLoc);
1414  }
1415 
1416  // For an expression of the form T(), T shall not be an array type.
1417  QualType ElemTy = Ty;
1418  if (Ty->isArrayType()) {
1419  if (!ListInitialization)
1420  return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1421  << FullRange);
1422  ElemTy = Context.getBaseElementType(Ty);
1423  }
1424 
1425  // There doesn't seem to be an explicit rule against this but sanity demands
1426  // we only construct objects with object types.
1427  if (Ty->isFunctionType())
1428  return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1429  << Ty << FullRange);
1430 
1431  // C++17 [expr.type.conv]p2:
1432  // If the type is cv void and the initializer is (), the expression is a
1433  // prvalue of the specified type that performs no initialization.
1434  if (!Ty->isVoidType() &&
1435  RequireCompleteType(TyBeginLoc, ElemTy,
1436  diag::err_invalid_incomplete_type_use, FullRange))
1437  return ExprError();
1438 
1439  // Otherwise, the expression is a prvalue of the specified type whose
1440  // result object is direct-initialized (11.6) with the initializer.
1441  InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1442  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1443 
1444  if (Result.isInvalid())
1445  return Result;
1446 
1447  Expr *Inner = Result.get();
1448  if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1449  Inner = BTE->getSubExpr();
1450  if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1451  !isa<CXXScalarValueInitExpr>(Inner)) {
1452  // If we created a CXXTemporaryObjectExpr, that node also represents the
1453  // functional cast. Otherwise, create an explicit cast to represent
1454  // the syntactic form of a functional-style cast that was used here.
1455  //
1456  // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1457  // would give a more consistent AST representation than using a
1458  // CXXTemporaryObjectExpr. It's also weird that the functional cast
1459  // is sometimes handled by initialization and sometimes not.
1460  QualType ResultType = Result.get()->getType();
1461  SourceRange Locs = ListInitialization
1462  ? SourceRange()
1463  : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1465  Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1466  Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1467  }
1468 
1469  return Result;
1470 }
1471 
1473  // [CUDA] Ignore this function, if we can't call it.
1474  const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1475  if (getLangOpts().CUDA &&
1476  IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1477  return false;
1478 
1480  bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1481 
1482  if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1483  return Result;
1484 
1485  // In case of CUDA, return true if none of the 1-argument deallocator
1486  // functions are actually callable.
1487  return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1488  assert(FD->getNumParams() == 1 &&
1489  "Only single-operand functions should be in PreventedBy");
1490  return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1491  });
1492 }
1493 
1494 /// Determine whether the given function is a non-placement
1495 /// deallocation function.
1497  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1498  return S.isUsualDeallocationFunction(Method);
1499 
1500  if (FD->getOverloadedOperator() != OO_Delete &&
1501  FD->getOverloadedOperator() != OO_Array_Delete)
1502  return false;
1503 
1504  unsigned UsualParams = 1;
1505 
1506  if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1508  FD->getParamDecl(UsualParams)->getType(),
1509  S.Context.getSizeType()))
1510  ++UsualParams;
1511 
1512  if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1514  FD->getParamDecl(UsualParams)->getType(),
1516  ++UsualParams;
1517 
1518  return UsualParams == FD->getNumParams();
1519 }
1520 
1521 namespace {
1522  struct UsualDeallocFnInfo {
1523  UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1524  UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1525  : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1526  Destroying(false), HasSizeT(false), HasAlignValT(false),
1527  CUDAPref(Sema::CFP_Native) {
1528  // A function template declaration is never a usual deallocation function.
1529  if (!FD)
1530  return;
1531  unsigned NumBaseParams = 1;
1532  if (FD->isDestroyingOperatorDelete()) {
1533  Destroying = true;
1534  ++NumBaseParams;
1535  }
1536 
1537  if (NumBaseParams < FD->getNumParams() &&
1539  FD->getParamDecl(NumBaseParams)->getType(),
1540  S.Context.getSizeType())) {
1541  ++NumBaseParams;
1542  HasSizeT = true;
1543  }
1544 
1545  if (NumBaseParams < FD->getNumParams() &&
1546  FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1547  ++NumBaseParams;
1548  HasAlignValT = true;
1549  }
1550 
1551  // In CUDA, determine how much we'd like / dislike to call this.
1552  if (S.getLangOpts().CUDA)
1553  if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1554  CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1555  }
1556 
1557  explicit operator bool() const { return FD; }
1558 
1559  bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1560  bool WantAlign) const {
1561  // C++ P0722:
1562  // A destroying operator delete is preferred over a non-destroying
1563  // operator delete.
1564  if (Destroying != Other.Destroying)
1565  return Destroying;
1566 
1567  // C++17 [expr.delete]p10:
1568  // If the type has new-extended alignment, a function with a parameter
1569  // of type std::align_val_t is preferred; otherwise a function without
1570  // such a parameter is preferred
1571  if (HasAlignValT != Other.HasAlignValT)
1572  return HasAlignValT == WantAlign;
1573 
1574  if (HasSizeT != Other.HasSizeT)
1575  return HasSizeT == WantSize;
1576 
1577  // Use CUDA call preference as a tiebreaker.
1578  return CUDAPref > Other.CUDAPref;
1579  }
1580 
1581  DeclAccessPair Found;
1582  FunctionDecl *FD;
1583  bool Destroying, HasSizeT, HasAlignValT;
1585  };
1586 }
1587 
1588 /// Determine whether a type has new-extended alignment. This may be called when
1589 /// the type is incomplete (for a delete-expression with an incomplete pointee
1590 /// type), in which case it will conservatively return false if the alignment is
1591 /// not known.
1592 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1593  return S.getLangOpts().AlignedAllocation &&
1594  S.getASTContext().getTypeAlignIfKnown(AllocType) >
1596 }
1597 
1598 /// Select the correct "usual" deallocation function to use from a selection of
1599 /// deallocation functions (either global or class-scope).
1600 static UsualDeallocFnInfo resolveDeallocationOverload(
1601  Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1602  llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1603  UsualDeallocFnInfo Best;
1604 
1605  for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1606  UsualDeallocFnInfo Info(S, I.getPair());
1607  if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1608  Info.CUDAPref == Sema::CFP_Never)
1609  continue;
1610 
1611  if (!Best) {
1612  Best = Info;
1613  if (BestFns)
1614  BestFns->push_back(Info);
1615  continue;
1616  }
1617 
1618  if (Best.isBetterThan(Info, WantSize, WantAlign))
1619  continue;
1620 
1621  // If more than one preferred function is found, all non-preferred
1622  // functions are eliminated from further consideration.
1623  if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1624  BestFns->clear();
1625 
1626  Best = Info;
1627  if (BestFns)
1628  BestFns->push_back(Info);
1629  }
1630 
1631  return Best;
1632 }
1633 
1634 /// Determine whether a given type is a class for which 'delete[]' would call
1635 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1636 /// we need to store the array size (even if the type is
1637 /// trivially-destructible).
1639  QualType allocType) {
1640  const RecordType *record =
1641  allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1642  if (!record) return false;
1643 
1644  // Try to find an operator delete[] in class scope.
1645 
1646  DeclarationName deleteName =
1647  S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1648  LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1649  S.LookupQualifiedName(ops, record->getDecl());
1650 
1651  // We're just doing this for information.
1652  ops.suppressDiagnostics();
1653 
1654  // Very likely: there's no operator delete[].
1655  if (ops.empty()) return false;
1656 
1657  // If it's ambiguous, it should be illegal to call operator delete[]
1658  // on this thing, so it doesn't matter if we allocate extra space or not.
1659  if (ops.isAmbiguous()) return false;
1660 
1661  // C++17 [expr.delete]p10:
1662  // If the deallocation functions have class scope, the one without a
1663  // parameter of type std::size_t is selected.
1664  auto Best = resolveDeallocationOverload(
1665  S, ops, /*WantSize*/false,
1666  /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1667  return Best && Best.HasSizeT;
1668 }
1669 
1670 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1671 ///
1672 /// E.g.:
1673 /// @code new (memory) int[size][4] @endcode
1674 /// or
1675 /// @code ::new Foo(23, "hello") @endcode
1676 ///
1677 /// \param StartLoc The first location of the expression.
1678 /// \param UseGlobal True if 'new' was prefixed with '::'.
1679 /// \param PlacementLParen Opening paren of the placement arguments.
1680 /// \param PlacementArgs Placement new arguments.
1681 /// \param PlacementRParen Closing paren of the placement arguments.
1682 /// \param TypeIdParens If the type is in parens, the source range.
1683 /// \param D The type to be allocated, as well as array dimensions.
1684 /// \param Initializer The initializing expression or initializer-list, or null
1685 /// if there is none.
1686 ExprResult
1687 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1688  SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1689  SourceLocation PlacementRParen, SourceRange TypeIdParens,
1690  Declarator &D, Expr *Initializer) {
1691  Optional<Expr *> ArraySize;
1692  // If the specified type is an array, unwrap it and save the expression.
1693  if (D.getNumTypeObjects() > 0 &&
1695  DeclaratorChunk &Chunk = D.getTypeObject(0);
1696  if (D.getDeclSpec().hasAutoTypeSpec())
1697  return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1698  << D.getSourceRange());
1699  if (Chunk.Arr.hasStatic)
1700  return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1701  << D.getSourceRange());
1702  if (!Chunk.Arr.NumElts && !Initializer)
1703  return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1704  << D.getSourceRange());
1705 
1706  ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1707  D.DropFirstTypeObject();
1708  }
1709 
1710  // Every dimension shall be of constant size.
1711  if (ArraySize) {
1712  for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1714  break;
1715 
1717  if (Expr *NumElts = (Expr *)Array.NumElts) {
1718  if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1719  if (getLangOpts().CPlusPlus14) {
1720  // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1721  // shall be a converted constant expression (5.19) of type std::size_t
1722  // and shall evaluate to a strictly positive value.
1723  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1724  assert(IntWidth && "Builtin type of size 0?");
1725  llvm::APSInt Value(IntWidth);
1726  Array.NumElts
1728  CCEK_NewExpr)
1729  .get();
1730  } else {
1731  Array.NumElts
1732  = VerifyIntegerConstantExpression(NumElts, nullptr,
1733  diag::err_new_array_nonconst)
1734  .get();
1735  }
1736  if (!Array.NumElts)
1737  return ExprError();
1738  }
1739  }
1740  }
1741  }
1742 
1743  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1744  QualType AllocType = TInfo->getType();
1745  if (D.isInvalidType())
1746  return ExprError();
1747 
1748  SourceRange DirectInitRange;
1749  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1750  DirectInitRange = List->getSourceRange();
1751 
1752  return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1753  PlacementLParen, PlacementArgs, PlacementRParen,
1754  TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1755  Initializer);
1756 }
1757 
1759  Expr *Init) {
1760  if (!Init)
1761  return true;
1762  if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1763  return PLE->getNumExprs() == 0;
1764  if (isa<ImplicitValueInitExpr>(Init))
1765  return true;
1766  else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1767  return !CCE->isListInitialization() &&
1768  CCE->getConstructor()->isDefaultConstructor();
1769  else if (Style == CXXNewExpr::ListInit) {
1770  assert(isa<InitListExpr>(Init) &&
1771  "Shouldn't create list CXXConstructExprs for arrays.");
1772  return true;
1773  }
1774  return false;
1775 }
1776 
1777 bool
1779  if (!getLangOpts().AlignedAllocationUnavailable)
1780  return false;
1781  if (FD.isDefined())
1782  return false;
1783  bool IsAligned = false;
1784  if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1785  return true;
1786  return false;
1787 }
1788 
1789 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1790 // implemented in the standard library is selected.
1792  SourceLocation Loc) {
1794  const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1795  StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1796  getASTContext().getTargetInfo().getPlatformName());
1797 
1799  bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1800  Diag(Loc, diag::err_aligned_allocation_unavailable)
1801  << IsDelete << FD.getType().getAsString() << OSName
1802  << alignedAllocMinVersion(T.getOS()).getAsString();
1803  Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1804  }
1805 }
1806 
1807 ExprResult
1808 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1809  SourceLocation PlacementLParen,
1810  MultiExprArg PlacementArgs,
1811  SourceLocation PlacementRParen,
1812  SourceRange TypeIdParens,
1813  QualType AllocType,
1814  TypeSourceInfo *AllocTypeInfo,
1815  Optional<Expr *> ArraySize,
1816  SourceRange DirectInitRange,
1817  Expr *Initializer) {
1818  SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1819  SourceLocation StartLoc = Range.getBegin();
1820 
1822  if (DirectInitRange.isValid()) {
1823  assert(Initializer && "Have parens but no initializer.");
1824  initStyle = CXXNewExpr::CallInit;
1825  } else if (Initializer && isa<InitListExpr>(Initializer))
1826  initStyle = CXXNewExpr::ListInit;
1827  else {
1828  assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1829  isa<CXXConstructExpr>(Initializer)) &&
1830  "Initializer expression that cannot have been implicitly created.");
1831  initStyle = CXXNewExpr::NoInit;
1832  }
1833 
1834  Expr **Inits = &Initializer;
1835  unsigned NumInits = Initializer ? 1 : 0;
1836  if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1837  assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1838  Inits = List->getExprs();
1839  NumInits = List->getNumExprs();
1840  }
1841 
1842  // C++11 [expr.new]p15:
1843  // A new-expression that creates an object of type T initializes that
1844  // object as follows:
1846  // - If the new-initializer is omitted, the object is default-
1847  // initialized (8.5); if no initialization is performed,
1848  // the object has indeterminate value
1849  = initStyle == CXXNewExpr::NoInit
1851  // - Otherwise, the new-initializer is interpreted according to
1852  // the
1853  // initialization rules of 8.5 for direct-initialization.
1854  : initStyle == CXXNewExpr::ListInit
1856  TypeRange.getBegin(), Initializer->getBeginLoc(),
1857  Initializer->getEndLoc())
1859  DirectInitRange.getBegin(),
1860  DirectInitRange.getEnd());
1861 
1862  // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1863  auto *Deduced = AllocType->getContainedDeducedType();
1864  if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1865  if (ArraySize)
1866  return ExprError(
1867  Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1868  diag::err_deduced_class_template_compound_type)
1869  << /*array*/ 2
1870  << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1871 
1872  InitializedEntity Entity
1873  = InitializedEntity::InitializeNew(StartLoc, AllocType);
1875  AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1876  if (AllocType.isNull())
1877  return ExprError();
1878  } else if (Deduced) {
1879  bool Braced = (initStyle == CXXNewExpr::ListInit);
1880  if (NumInits == 1) {
1881  if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1882  Inits = p->getInits();
1883  NumInits = p->getNumInits();
1884  Braced = true;
1885  }
1886  }
1887 
1888  if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1889  return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1890  << AllocType << TypeRange);
1891  if (NumInits > 1) {
1892  Expr *FirstBad = Inits[1];
1893  return ExprError(Diag(FirstBad->getBeginLoc(),
1894  diag::err_auto_new_ctor_multiple_expressions)
1895  << AllocType << TypeRange);
1896  }
1897  if (Braced && !getLangOpts().CPlusPlus17)
1898  Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1899  << AllocType << TypeRange;
1900  Expr *Deduce = Inits[0];
1902  if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1903  return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1904  << AllocType << Deduce->getType()
1905  << TypeRange << Deduce->getSourceRange());
1906  if (DeducedType.isNull())
1907  return ExprError();
1908  AllocType = DeducedType;
1909  }
1910 
1911  // Per C++0x [expr.new]p5, the type being constructed may be a
1912  // typedef of an array type.
1913  if (!ArraySize) {
1914  if (const ConstantArrayType *Array
1915  = Context.getAsConstantArrayType(AllocType)) {
1916  ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1917  Context.getSizeType(),
1918  TypeRange.getEnd());
1919  AllocType = Array->getElementType();
1920  }
1921  }
1922 
1923  if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1924  return ExprError();
1925 
1926  // In ARC, infer 'retaining' for the allocated
1927  if (getLangOpts().ObjCAutoRefCount &&
1928  AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1929  AllocType->isObjCLifetimeType()) {
1930  AllocType = Context.getLifetimeQualifiedType(AllocType,
1931  AllocType->getObjCARCImplicitLifetime());
1932  }
1933 
1934  QualType ResultType = Context.getPointerType(AllocType);
1935 
1936  if (ArraySize && *ArraySize &&
1937  (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1938  ExprResult result = CheckPlaceholderExpr(*ArraySize);
1939  if (result.isInvalid()) return ExprError();
1940  ArraySize = result.get();
1941  }
1942  // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1943  // integral or enumeration type with a non-negative value."
1944  // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1945  // enumeration type, or a class type for which a single non-explicit
1946  // conversion function to integral or unscoped enumeration type exists.
1947  // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1948  // std::size_t.
1949  llvm::Optional<uint64_t> KnownArraySize;
1950  if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
1951  ExprResult ConvertedSize;
1952  if (getLangOpts().CPlusPlus14) {
1953  assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1954 
1955  ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
1956  AA_Converting);
1957 
1958  if (!ConvertedSize.isInvalid() &&
1959  (*ArraySize)->getType()->getAs<RecordType>())
1960  // Diagnose the compatibility of this conversion.
1961  Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1962  << (*ArraySize)->getType() << 0 << "'size_t'";
1963  } else {
1964  class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1965  protected:
1966  Expr *ArraySize;
1967 
1968  public:
1969  SizeConvertDiagnoser(Expr *ArraySize)
1970  : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1971  ArraySize(ArraySize) {}
1972 
1973  SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1974  QualType T) override {
1975  return S.Diag(Loc, diag::err_array_size_not_integral)
1976  << S.getLangOpts().CPlusPlus11 << T;
1977  }
1978 
1979  SemaDiagnosticBuilder diagnoseIncomplete(
1980  Sema &S, SourceLocation Loc, QualType T) override {
1981  return S.Diag(Loc, diag::err_array_size_incomplete_type)
1982  << T << ArraySize->getSourceRange();
1983  }
1984 
1985  SemaDiagnosticBuilder diagnoseExplicitConv(
1986  Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1987  return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1988  }
1989 
1990  SemaDiagnosticBuilder noteExplicitConv(
1991  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1992  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1993  << ConvTy->isEnumeralType() << ConvTy;
1994  }
1995 
1996  SemaDiagnosticBuilder diagnoseAmbiguous(
1997  Sema &S, SourceLocation Loc, QualType T) override {
1998  return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1999  }
2000 
2001  SemaDiagnosticBuilder noteAmbiguous(
2002  Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2003  return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2004  << ConvTy->isEnumeralType() << ConvTy;
2005  }
2006 
2007  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2008  QualType T,
2009  QualType ConvTy) override {
2010  return S.Diag(Loc,
2011  S.getLangOpts().CPlusPlus11
2012  ? diag::warn_cxx98_compat_array_size_conversion
2013  : diag::ext_array_size_conversion)
2014  << T << ConvTy->isEnumeralType() << ConvTy;
2015  }
2016  } SizeDiagnoser(*ArraySize);
2017 
2018  ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2019  SizeDiagnoser);
2020  }
2021  if (ConvertedSize.isInvalid())
2022  return ExprError();
2023 
2024  ArraySize = ConvertedSize.get();
2025  QualType SizeType = (*ArraySize)->getType();
2026 
2027  if (!SizeType->isIntegralOrUnscopedEnumerationType())
2028  return ExprError();
2029 
2030  // C++98 [expr.new]p7:
2031  // The expression in a direct-new-declarator shall have integral type
2032  // with a non-negative value.
2033  //
2034  // Let's see if this is a constant < 0. If so, we reject it out of hand,
2035  // per CWG1464. Otherwise, if it's not a constant, we must have an
2036  // unparenthesized array type.
2037  if (!(*ArraySize)->isValueDependent()) {
2038  llvm::APSInt Value;
2039  // We've already performed any required implicit conversion to integer or
2040  // unscoped enumeration type.
2041  // FIXME: Per CWG1464, we are required to check the value prior to
2042  // converting to size_t. This will never find a negative array size in
2043  // C++14 onwards, because Value is always unsigned here!
2044  if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
2045  if (Value.isSigned() && Value.isNegative()) {
2046  return ExprError(Diag((*ArraySize)->getBeginLoc(),
2047  diag::err_typecheck_negative_array_size)
2048  << (*ArraySize)->getSourceRange());
2049  }
2050 
2051  if (!AllocType->isDependentType()) {
2052  unsigned ActiveSizeBits =
2054  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2055  return ExprError(
2056  Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2057  << Value.toString(10) << (*ArraySize)->getSourceRange());
2058  }
2059 
2060  KnownArraySize = Value.getZExtValue();
2061  } else if (TypeIdParens.isValid()) {
2062  // Can't have dynamic array size when the type-id is in parentheses.
2063  Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2064  << (*ArraySize)->getSourceRange()
2065  << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2066  << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2067 
2068  TypeIdParens = SourceRange();
2069  }
2070  }
2071 
2072  // Note that we do *not* convert the argument in any way. It can
2073  // be signed, larger than size_t, whatever.
2074  }
2075 
2076  FunctionDecl *OperatorNew = nullptr;
2077  FunctionDecl *OperatorDelete = nullptr;
2078  unsigned Alignment =
2079  AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2080  unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2081  bool PassAlignment = getLangOpts().AlignedAllocation &&
2082  Alignment > NewAlignment;
2083 
2085  if (!AllocType->isDependentType() &&
2086  !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2088  StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2089  AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2090  OperatorNew, OperatorDelete))
2091  return ExprError();
2092 
2093  // If this is an array allocation, compute whether the usual array
2094  // deallocation function for the type has a size_t parameter.
2095  bool UsualArrayDeleteWantsSize = false;
2096  if (ArraySize && !AllocType->isDependentType())
2097  UsualArrayDeleteWantsSize =
2098  doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2099 
2100  SmallVector<Expr *, 8> AllPlaceArgs;
2101  if (OperatorNew) {
2102  const FunctionProtoType *Proto =
2103  OperatorNew->getType()->getAs<FunctionProtoType>();
2104  VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2106 
2107  // We've already converted the placement args, just fill in any default
2108  // arguments. Skip the first parameter because we don't have a corresponding
2109  // argument. Skip the second parameter too if we're passing in the
2110  // alignment; we've already filled it in.
2111  if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2112  PassAlignment ? 2 : 1, PlacementArgs,
2113  AllPlaceArgs, CallType))
2114  return ExprError();
2115 
2116  if (!AllPlaceArgs.empty())
2117  PlacementArgs = AllPlaceArgs;
2118 
2119  // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2120  DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2121 
2122  // FIXME: Missing call to CheckFunctionCall or equivalent
2123 
2124  // Warn if the type is over-aligned and is being allocated by (unaligned)
2125  // global operator new.
2126  if (PlacementArgs.empty() && !PassAlignment &&
2127  (OperatorNew->isImplicit() ||
2128  (OperatorNew->getBeginLoc().isValid() &&
2129  getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2130  if (Alignment > NewAlignment)
2131  Diag(StartLoc, diag::warn_overaligned_type)
2132  << AllocType
2133  << unsigned(Alignment / Context.getCharWidth())
2134  << unsigned(NewAlignment / Context.getCharWidth());
2135  }
2136  }
2137 
2138  // Array 'new' can't have any initializers except empty parentheses.
2139  // Initializer lists are also allowed, in C++11. Rely on the parser for the
2140  // dialect distinction.
2141  if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2142  SourceRange InitRange(Inits[0]->getBeginLoc(),
2143  Inits[NumInits - 1]->getEndLoc());
2144  Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2145  return ExprError();
2146  }
2147 
2148  // If we can perform the initialization, and we've not already done so,
2149  // do it now.
2150  if (!AllocType->isDependentType() &&
2152  llvm::makeArrayRef(Inits, NumInits))) {
2153  // The type we initialize is the complete type, including the array bound.
2154  QualType InitType;
2155  if (KnownArraySize)
2156  InitType = Context.getConstantArrayType(
2157  AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2158  *KnownArraySize),
2159  ArrayType::Normal, 0);
2160  else if (ArraySize)
2161  InitType =
2163  else
2164  InitType = AllocType;
2165 
2166  InitializedEntity Entity
2167  = InitializedEntity::InitializeNew(StartLoc, InitType);
2168  InitializationSequence InitSeq(*this, Entity, Kind,
2169  MultiExprArg(Inits, NumInits));
2170  ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2171  MultiExprArg(Inits, NumInits));
2172  if (FullInit.isInvalid())
2173  return ExprError();
2174 
2175  // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2176  // we don't want the initialized object to be destructed.
2177  // FIXME: We should not create these in the first place.
2178  if (CXXBindTemporaryExpr *Binder =
2179  dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2180  FullInit = Binder->getSubExpr();
2181 
2182  Initializer = FullInit.get();
2183 
2184  // FIXME: If we have a KnownArraySize, check that the array bound of the
2185  // initializer is no greater than that constant value.
2186 
2187  if (ArraySize && !*ArraySize) {
2188  auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2189  if (CAT) {
2190  // FIXME: Track that the array size was inferred rather than explicitly
2191  // specified.
2192  ArraySize = IntegerLiteral::Create(
2193  Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2194  } else {
2195  Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2196  << Initializer->getSourceRange();
2197  }
2198  }
2199  }
2200 
2201  // Mark the new and delete operators as referenced.
2202  if (OperatorNew) {
2203  if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2204  return ExprError();
2205  MarkFunctionReferenced(StartLoc, OperatorNew);
2206  }
2207  if (OperatorDelete) {
2208  if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2209  return ExprError();
2210  MarkFunctionReferenced(StartLoc, OperatorDelete);
2211  }
2212 
2213  return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2214  PassAlignment, UsualArrayDeleteWantsSize,
2215  PlacementArgs, TypeIdParens, ArraySize, initStyle,
2216  Initializer, ResultType, AllocTypeInfo, Range,
2217  DirectInitRange);
2218 }
2219 
2220 /// Checks that a type is suitable as the allocated type
2221 /// in a new-expression.
2223  SourceRange R) {
2224  // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2225  // abstract class type or array thereof.
2226  if (AllocType->isFunctionType())
2227  return Diag(Loc, diag::err_bad_new_type)
2228  << AllocType << 0 << R;
2229  else if (AllocType->isReferenceType())
2230  return Diag(Loc, diag::err_bad_new_type)
2231  << AllocType << 1 << R;
2232  else if (!AllocType->isDependentType() &&
2233  RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2234  return true;
2235  else if (RequireNonAbstractType(Loc, AllocType,
2236  diag::err_allocation_of_abstract_type))
2237  return true;
2238  else if (AllocType->isVariablyModifiedType())
2239  return Diag(Loc, diag::err_variably_modified_new_type)
2240  << AllocType;
2241  else if (AllocType.getAddressSpace() != LangAS::Default &&
2242  !getLangOpts().OpenCLCPlusPlus)
2243  return Diag(Loc, diag::err_address_space_qualified_new)
2244  << AllocType.getUnqualifiedType()
2246  else if (getLangOpts().ObjCAutoRefCount) {
2247  if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2248  QualType BaseAllocType = Context.getBaseElementType(AT);
2249  if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2250  BaseAllocType->isObjCLifetimeType())
2251  return Diag(Loc, diag::err_arc_new_array_without_ownership)
2252  << BaseAllocType;
2253  }
2254  }
2255 
2256  return false;
2257 }
2258 
2261  bool &PassAlignment, FunctionDecl *&Operator,
2262  OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2263  OverloadCandidateSet Candidates(R.getNameLoc(),
2265  for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2266  Alloc != AllocEnd; ++Alloc) {
2267  // Even member operator new/delete are implicitly treated as
2268  // static, so don't use AddMemberCandidate.
2269  NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2270 
2271  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2272  S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2273  /*ExplicitTemplateArgs=*/nullptr, Args,
2274  Candidates,
2275  /*SuppressUserConversions=*/false);
2276  continue;
2277  }
2278 
2279  FunctionDecl *Fn = cast<FunctionDecl>(D);
2280  S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2281  /*SuppressUserConversions=*/false);
2282  }
2283 
2284  // Do the resolution.
2286  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2287  case OR_Success: {
2288  // Got one!
2289  FunctionDecl *FnDecl = Best->Function;
2290  if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2291  Best->FoundDecl) == Sema::AR_inaccessible)
2292  return true;
2293 
2294  Operator = FnDecl;
2295  return false;
2296  }
2297 
2298  case OR_No_Viable_Function:
2299  // C++17 [expr.new]p13:
2300  // If no matching function is found and the allocated object type has
2301  // new-extended alignment, the alignment argument is removed from the
2302  // argument list, and overload resolution is performed again.
2303  if (PassAlignment) {
2304  PassAlignment = false;
2305  AlignArg = Args[1];
2306  Args.erase(Args.begin() + 1);
2307  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2308  Operator, &Candidates, AlignArg,
2309  Diagnose);
2310  }
2311 
2312  // MSVC will fall back on trying to find a matching global operator new
2313  // if operator new[] cannot be found. Also, MSVC will leak by not
2314  // generating a call to operator delete or operator delete[], but we
2315  // will not replicate that bug.
2316  // FIXME: Find out how this interacts with the std::align_val_t fallback
2317  // once MSVC implements it.
2318  if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2319  S.Context.getLangOpts().MSVCCompat) {
2320  R.clear();
2323  // FIXME: This will give bad diagnostics pointing at the wrong functions.
2324  return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2325  Operator, /*Candidates=*/nullptr,
2326  /*AlignArg=*/nullptr, Diagnose);
2327  }
2328 
2329  if (Diagnose) {
2330  PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2331  << R.getLookupName() << Range);
2332 
2333  // If we have aligned candidates, only note the align_val_t candidates
2334  // from AlignedCandidates and the non-align_val_t candidates from
2335  // Candidates.
2336  if (AlignedCandidates) {
2337  auto IsAligned = [](OverloadCandidate &C) {
2338  return C.Function->getNumParams() > 1 &&
2339  C.Function->getParamDecl(1)->getType()->isAlignValT();
2340  };
2341  auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2342 
2343  // This was an overaligned allocation, so list the aligned candidates
2344  // first.
2345  Args.insert(Args.begin() + 1, AlignArg);
2346  AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2347  R.getNameLoc(), IsAligned);
2348  Args.erase(Args.begin() + 1);
2349  Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2350  IsUnaligned);
2351  } else {
2352  Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2353  }
2354  }
2355  return true;
2356 
2357  case OR_Ambiguous:
2358  if (Diagnose) {
2359  Candidates.NoteCandidates(
2361  S.PDiag(diag::err_ovl_ambiguous_call)
2362  << R.getLookupName() << Range),
2363  S, OCD_ViableCandidates, Args);
2364  }
2365  return true;
2366 
2367  case OR_Deleted: {
2368  if (Diagnose) {
2369  Candidates.NoteCandidates(
2371  S.PDiag(diag::err_ovl_deleted_call)
2372  << R.getLookupName() << Range),
2373  S, OCD_AllCandidates, Args);
2374  }
2375  return true;
2376  }
2377  }
2378  llvm_unreachable("Unreachable, bad result from BestViableFunction");
2379 }
2380 
2382  AllocationFunctionScope NewScope,
2383  AllocationFunctionScope DeleteScope,
2384  QualType AllocType, bool IsArray,
2385  bool &PassAlignment, MultiExprArg PlaceArgs,
2386  FunctionDecl *&OperatorNew,
2387  FunctionDecl *&OperatorDelete,
2388  bool Diagnose) {
2389  // --- Choosing an allocation function ---
2390  // C++ 5.3.4p8 - 14 & 18
2391  // 1) If looking in AFS_Global scope for allocation functions, only look in
2392  // the global scope. Else, if AFS_Class, only look in the scope of the
2393  // allocated class. If AFS_Both, look in both.
2394  // 2) If an array size is given, look for operator new[], else look for
2395  // operator new.
2396  // 3) The first argument is always size_t. Append the arguments from the
2397  // placement form.
2398 
2399  SmallVector<Expr*, 8> AllocArgs;
2400  AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2401 
2402  // We don't care about the actual value of these arguments.
2403  // FIXME: Should the Sema create the expression and embed it in the syntax
2404  // tree? Or should the consumer just recalculate the value?
2405  // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2406  IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2408  Context.getSizeType(),
2409  SourceLocation());
2410  AllocArgs.push_back(&Size);
2411 
2412  QualType AlignValT = Context.VoidTy;
2413  if (PassAlignment) {
2415  AlignValT = Context.getTypeDeclType(getStdAlignValT());
2416  }
2417  CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2418  if (PassAlignment)
2419  AllocArgs.push_back(&Align);
2420 
2421  AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2422 
2423  // C++ [expr.new]p8:
2424  // If the allocated type is a non-array type, the allocation
2425  // function's name is operator new and the deallocation function's
2426  // name is operator delete. If the allocated type is an array
2427  // type, the allocation function's name is operator new[] and the
2428  // deallocation function's name is operator delete[].
2430  IsArray ? OO_Array_New : OO_New);
2431 
2432  QualType AllocElemType = Context.getBaseElementType(AllocType);
2433 
2434  // Find the allocation function.
2435  {
2436  LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2437 
2438  // C++1z [expr.new]p9:
2439  // If the new-expression begins with a unary :: operator, the allocation
2440  // function's name is looked up in the global scope. Otherwise, if the
2441  // allocated type is a class type T or array thereof, the allocation
2442  // function's name is looked up in the scope of T.
2443  if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2444  LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2445 
2446  // We can see ambiguity here if the allocation function is found in
2447  // multiple base classes.
2448  if (R.isAmbiguous())
2449  return true;
2450 
2451  // If this lookup fails to find the name, or if the allocated type is not
2452  // a class type, the allocation function's name is looked up in the
2453  // global scope.
2454  if (R.empty()) {
2455  if (NewScope == AFS_Class)
2456  return true;
2457 
2459  }
2460 
2461  if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2462  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2463  return true;
2464  }
2465 
2466  assert(!R.empty() && "implicitly declared allocation functions not found");
2467  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2468 
2469  // We do our own custom access checks below.
2470  R.suppressDiagnostics();
2471 
2472  if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2473  OperatorNew, /*Candidates=*/nullptr,
2474  /*AlignArg=*/nullptr, Diagnose))
2475  return true;
2476  }
2477 
2478  // We don't need an operator delete if we're running under -fno-exceptions.
2479  if (!getLangOpts().Exceptions) {
2480  OperatorDelete = nullptr;
2481  return false;
2482  }
2483 
2484  // Note, the name of OperatorNew might have been changed from array to
2485  // non-array by resolveAllocationOverload.
2487  OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2488  ? OO_Array_Delete
2489  : OO_Delete);
2490 
2491  // C++ [expr.new]p19:
2492  //
2493  // If the new-expression begins with a unary :: operator, the
2494  // deallocation function's name is looked up in the global
2495  // scope. Otherwise, if the allocated type is a class type T or an
2496  // array thereof, the deallocation function's name is looked up in
2497  // the scope of T. If this lookup fails to find the name, or if
2498  // the allocated type is not a class type or array thereof, the
2499  // deallocation function's name is looked up in the global scope.
2500  LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2501  if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2502  CXXRecordDecl *RD
2503  = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2504  LookupQualifiedName(FoundDelete, RD);
2505  }
2506  if (FoundDelete.isAmbiguous())
2507  return true; // FIXME: clean up expressions?
2508 
2509  bool FoundGlobalDelete = FoundDelete.empty();
2510  if (FoundDelete.empty()) {
2511  if (DeleteScope == AFS_Class)
2512  return true;
2513 
2516  }
2517 
2518  FoundDelete.suppressDiagnostics();
2519 
2521 
2522  // Whether we're looking for a placement operator delete is dictated
2523  // by whether we selected a placement operator new, not by whether
2524  // we had explicit placement arguments. This matters for things like
2525  // struct A { void *operator new(size_t, int = 0); ... };
2526  // A *a = new A()
2527  //
2528  // We don't have any definition for what a "placement allocation function"
2529  // is, but we assume it's any allocation function whose
2530  // parameter-declaration-clause is anything other than (size_t).
2531  //
2532  // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2533  // This affects whether an exception from the constructor of an overaligned
2534  // type uses the sized or non-sized form of aligned operator delete.
2535  bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2536  OperatorNew->isVariadic();
2537 
2538  if (isPlacementNew) {
2539  // C++ [expr.new]p20:
2540  // A declaration of a placement deallocation function matches the
2541  // declaration of a placement allocation function if it has the
2542  // same number of parameters and, after parameter transformations
2543  // (8.3.5), all parameter types except the first are
2544  // identical. [...]
2545  //
2546  // To perform this comparison, we compute the function type that
2547  // the deallocation function should have, and use that type both
2548  // for template argument deduction and for comparison purposes.
2549  QualType ExpectedFunctionType;
2550  {
2551  const FunctionProtoType *Proto
2552  = OperatorNew->getType()->getAs<FunctionProtoType>();
2553 
2554  SmallVector<QualType, 4> ArgTypes;
2555  ArgTypes.push_back(Context.VoidPtrTy);
2556  for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2557  ArgTypes.push_back(Proto->getParamType(I));
2558 
2560  // FIXME: This is not part of the standard's rule.
2561  EPI.Variadic = Proto->isVariadic();
2562 
2563  ExpectedFunctionType
2564  = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2565  }
2566 
2567  for (LookupResult::iterator D = FoundDelete.begin(),
2568  DEnd = FoundDelete.end();
2569  D != DEnd; ++D) {
2570  FunctionDecl *Fn = nullptr;
2571  if (FunctionTemplateDecl *FnTmpl =
2572  dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2573  // Perform template argument deduction to try to match the
2574  // expected function type.
2575  TemplateDeductionInfo Info(StartLoc);
2576  if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2577  Info))
2578  continue;
2579  } else
2580  Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2581 
2583  ExpectedFunctionType,
2584  /*AdjustExcpetionSpec*/true),
2585  ExpectedFunctionType))
2586  Matches.push_back(std::make_pair(D.getPair(), Fn));
2587  }
2588 
2589  if (getLangOpts().CUDA)
2590  EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2591  } else {
2592  // C++1y [expr.new]p22:
2593  // For a non-placement allocation function, the normal deallocation
2594  // function lookup is used
2595  //
2596  // Per [expr.delete]p10, this lookup prefers a member operator delete
2597  // without a size_t argument, but prefers a non-member operator delete
2598  // with a size_t where possible (which it always is in this case).
2600  UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2601  *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2602  /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2603  &BestDeallocFns);
2604  if (Selected)
2605  Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2606  else {
2607  // If we failed to select an operator, all remaining functions are viable
2608  // but ambiguous.
2609  for (auto Fn : BestDeallocFns)
2610  Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2611  }
2612  }
2613 
2614  // C++ [expr.new]p20:
2615  // [...] If the lookup finds a single matching deallocation
2616  // function, that function will be called; otherwise, no
2617  // deallocation function will be called.
2618  if (Matches.size() == 1) {
2619  OperatorDelete = Matches[0].second;
2620 
2621  // C++1z [expr.new]p23:
2622  // If the lookup finds a usual deallocation function (3.7.4.2)
2623  // with a parameter of type std::size_t and that function, considered
2624  // as a placement deallocation function, would have been
2625  // selected as a match for the allocation function, the program
2626  // is ill-formed.
2627  if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2628  isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2629  UsualDeallocFnInfo Info(*this,
2630  DeclAccessPair::make(OperatorDelete, AS_public));
2631  // Core issue, per mail to core reflector, 2016-10-09:
2632  // If this is a member operator delete, and there is a corresponding
2633  // non-sized member operator delete, this isn't /really/ a sized
2634  // deallocation function, it just happens to have a size_t parameter.
2635  bool IsSizedDelete = Info.HasSizeT;
2636  if (IsSizedDelete && !FoundGlobalDelete) {
2637  auto NonSizedDelete =
2638  resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2639  /*WantAlign*/Info.HasAlignValT);
2640  if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2641  NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2642  IsSizedDelete = false;
2643  }
2644 
2645  if (IsSizedDelete) {
2646  SourceRange R = PlaceArgs.empty()
2647  ? SourceRange()
2648  : SourceRange(PlaceArgs.front()->getBeginLoc(),
2649  PlaceArgs.back()->getEndLoc());
2650  Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2651  if (!OperatorDelete->isImplicit())
2652  Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2653  << DeleteName;
2654  }
2655  }
2656 
2657  CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2658  Matches[0].first);
2659  } else if (!Matches.empty()) {
2660  // We found multiple suitable operators. Per [expr.new]p20, that means we
2661  // call no 'operator delete' function, but we should at least warn the user.
2662  // FIXME: Suppress this warning if the construction cannot throw.
2663  Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2664  << DeleteName << AllocElemType;
2665 
2666  for (auto &Match : Matches)
2667  Diag(Match.second->getLocation(),
2668  diag::note_member_declared_here) << DeleteName;
2669  }
2670 
2671  return false;
2672 }
2673 
2674 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2675 /// delete. These are:
2676 /// @code
2677 /// // C++03:
2678 /// void* operator new(std::size_t) throw(std::bad_alloc);
2679 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2680 /// void operator delete(void *) throw();
2681 /// void operator delete[](void *) throw();
2682 /// // C++11:
2683 /// void* operator new(std::size_t);
2684 /// void* operator new[](std::size_t);
2685 /// void operator delete(void *) noexcept;
2686 /// void operator delete[](void *) noexcept;
2687 /// // C++1y:
2688 /// void* operator new(std::size_t);
2689 /// void* operator new[](std::size_t);
2690 /// void operator delete(void *) noexcept;
2691 /// void operator delete[](void *) noexcept;
2692 /// void operator delete(void *, std::size_t) noexcept;
2693 /// void operator delete[](void *, std::size_t) noexcept;
2694 /// @endcode
2695 /// Note that the placement and nothrow forms of new are *not* implicitly
2696 /// declared. Their use requires including <new>.
2699  return;
2700 
2701  // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2702  // are not supported.
2703  if (getLangOpts().OpenCLCPlusPlus)
2704  return;
2705 
2706  // C++ [basic.std.dynamic]p2:
2707  // [...] The following allocation and deallocation functions (18.4) are
2708  // implicitly declared in global scope in each translation unit of a
2709  // program
2710  //
2711  // C++03:
2712  // void* operator new(std::size_t) throw(std::bad_alloc);
2713  // void* operator new[](std::size_t) throw(std::bad_alloc);
2714  // void operator delete(void*) throw();
2715  // void operator delete[](void*) throw();
2716  // C++11:
2717  // void* operator new(std::size_t);
2718  // void* operator new[](std::size_t);
2719  // void operator delete(void*) noexcept;
2720  // void operator delete[](void*) noexcept;
2721  // C++1y:
2722  // void* operator new(std::size_t);
2723  // void* operator new[](std::size_t);
2724  // void operator delete(void*) noexcept;
2725  // void operator delete[](void*) noexcept;
2726  // void operator delete(void*, std::size_t) noexcept;
2727  // void operator delete[](void*, std::size_t) noexcept;
2728  //
2729  // These implicit declarations introduce only the function names operator
2730  // new, operator new[], operator delete, operator delete[].
2731  //
2732  // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2733  // "std" or "bad_alloc" as necessary to form the exception specification.
2734  // However, we do not make these implicit declarations visible to name
2735  // lookup.
2736  if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2737  // The "std::bad_alloc" class has not yet been declared, so build it
2738  // implicitly.
2742  &PP.getIdentifierTable().get("bad_alloc"),
2743  nullptr);
2744  getStdBadAlloc()->setImplicit(true);
2745  }
2746  if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2747  // The "std::align_val_t" enum class has not yet been declared, so build it
2748  // implicitly.
2749  auto *AlignValT = EnumDecl::Create(
2751  &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2752  AlignValT->setIntegerType(Context.getSizeType());
2753  AlignValT->setPromotionType(Context.getSizeType());
2754  AlignValT->setImplicit(true);
2755  StdAlignValT = AlignValT;
2756  }
2757 
2758  GlobalNewDeleteDeclared = true;
2759 
2761  QualType SizeT = Context.getSizeType();
2762 
2763  auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2764  QualType Return, QualType Param) {
2766  Params.push_back(Param);
2767 
2768  // Create up to four variants of the function (sized/aligned).
2769  bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2770  (Kind == OO_Delete || Kind == OO_Array_Delete);
2771  bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2772 
2773  int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2774  int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2775  for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2776  if (Sized)
2777  Params.push_back(SizeT);
2778 
2779  for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2780  if (Aligned)
2781  Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2782 
2784  Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2785 
2786  if (Aligned)
2787  Params.pop_back();
2788  }
2789  }
2790  };
2791 
2792  DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2793  DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2794  DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2795  DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2796 }
2797 
2798 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2799 /// allocation function if it doesn't already exist.
2801  QualType Return,
2802  ArrayRef<QualType> Params) {
2804 
2805  // Check if this function is already declared.
2806  DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2807  for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2808  Alloc != AllocEnd; ++Alloc) {
2809  // Only look at non-template functions, as it is the predefined,
2810  // non-templated allocation function we are trying to declare here.
2811  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2812  if (Func->getNumParams() == Params.size()) {
2813  llvm::SmallVector<QualType, 3> FuncParams;
2814  for (auto *P : Func->parameters())
2815  FuncParams.push_back(
2816  Context.getCanonicalType(P->getType().getUnqualifiedType()));
2817  if (llvm::makeArrayRef(FuncParams) == Params) {
2818  // Make the function visible to name lookup, even if we found it in
2819  // an unimported module. It either is an implicitly-declared global
2820  // allocation function, or is suppressing that function.
2821  Func->setVisibleDespiteOwningModule();
2822  return;
2823  }
2824  }
2825  }
2826  }
2827 
2829  /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2830 
2831  QualType BadAllocType;
2832  bool HasBadAllocExceptionSpec
2833  = (Name.getCXXOverloadedOperator() == OO_New ||
2834  Name.getCXXOverloadedOperator() == OO_Array_New);
2835  if (HasBadAllocExceptionSpec) {
2836  if (!getLangOpts().CPlusPlus11) {
2837  BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2838  assert(StdBadAlloc && "Must have std::bad_alloc declared");
2839  EPI.ExceptionSpec.Type = EST_Dynamic;
2840  EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2841  }
2842  } else {
2843  EPI.ExceptionSpec =
2844  getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2845  }
2846 
2847  auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2848  QualType FnType = Context.getFunctionType(Return, Params, EPI);
2850  Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2851  FnType, /*TInfo=*/nullptr, SC_None, false, true);
2852  Alloc->setImplicit();
2853  // Global allocation functions should always be visible.
2855 
2856  Alloc->addAttr(VisibilityAttr::CreateImplicit(
2857  Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2858  ? VisibilityAttr::Hidden
2860 
2862  for (QualType T : Params) {
2863  ParamDecls.push_back(ParmVarDecl::Create(
2864  Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2865  /*TInfo=*/nullptr, SC_None, nullptr));
2866  ParamDecls.back()->setImplicit();
2867  }
2868  Alloc->setParams(ParamDecls);
2869  if (ExtraAttr)
2870  Alloc->addAttr(ExtraAttr);
2872  IdResolver.tryAddTopLevelDecl(Alloc, Name);
2873  };
2874 
2875  if (!LangOpts.CUDA)
2876  CreateAllocationFunctionDecl(nullptr);
2877  else {
2878  // Host and device get their own declaration so each can be
2879  // defined or re-declared independently.
2880  CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2881  CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2882  }
2883 }
2884 
2886  bool CanProvideSize,
2887  bool Overaligned,
2888  DeclarationName Name) {
2890 
2891  LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2893 
2894  // FIXME: It's possible for this to result in ambiguity, through a
2895  // user-declared variadic operator delete or the enable_if attribute. We
2896  // should probably not consider those cases to be usual deallocation
2897  // functions. But for now we just make an arbitrary choice in that case.
2898  auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2899  Overaligned);
2900  assert(Result.FD && "operator delete missing from global scope?");
2901  return Result.FD;
2902 }
2903 
2905  CXXRecordDecl *RD) {
2907 
2908  FunctionDecl *OperatorDelete = nullptr;
2909  if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2910  return nullptr;
2911  if (OperatorDelete)
2912  return OperatorDelete;
2913 
2914  // If there's no class-specific operator delete, look up the global
2915  // non-array delete.
2917  Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2918  Name);
2919 }
2920 
2922  DeclarationName Name,
2923  FunctionDecl *&Operator, bool Diagnose) {
2924  LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2925  // Try to find operator delete/operator delete[] in class scope.
2926  LookupQualifiedName(Found, RD);
2927 
2928  if (Found.isAmbiguous())
2929  return true;
2930 
2931  Found.suppressDiagnostics();
2932 
2933  bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2934 
2935  // C++17 [expr.delete]p10:
2936  // If the deallocation functions have class scope, the one without a
2937  // parameter of type std::size_t is selected.
2939  resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2940  /*WantAlign*/ Overaligned, &Matches);
2941 
2942  // If we could find an overload, use it.
2943  if (Matches.size() == 1) {
2944  Operator = cast<CXXMethodDecl>(Matches[0].FD);
2945 
2946  // FIXME: DiagnoseUseOfDecl?
2947  if (Operator->isDeleted()) {
2948  if (Diagnose) {
2949  Diag(StartLoc, diag::err_deleted_function_use);
2950  NoteDeletedFunction(Operator);
2951  }
2952  return true;
2953  }
2954 
2955  if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2956  Matches[0].Found, Diagnose) == AR_inaccessible)
2957  return true;
2958 
2959  return false;
2960  }
2961 
2962  // We found multiple suitable operators; complain about the ambiguity.
2963  // FIXME: The standard doesn't say to do this; it appears that the intent
2964  // is that this should never happen.
2965  if (!Matches.empty()) {
2966  if (Diagnose) {
2967  Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2968  << Name << RD;
2969  for (auto &Match : Matches)
2970  Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2971  }
2972  return true;
2973  }
2974 
2975  // We did find operator delete/operator delete[] declarations, but
2976  // none of them were suitable.
2977  if (!Found.empty()) {
2978  if (Diagnose) {
2979  Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2980  << Name << RD;
2981 
2982  for (NamedDecl *D : Found)
2983  Diag(D->getUnderlyingDecl()->getLocation(),
2984  diag::note_member_declared_here) << Name;
2985  }
2986  return true;
2987  }
2988 
2989  Operator = nullptr;
2990  return false;
2991 }
2992 
2993 namespace {
2994 /// Checks whether delete-expression, and new-expression used for
2995 /// initializing deletee have the same array form.
2996 class MismatchingNewDeleteDetector {
2997 public:
2998  enum MismatchResult {
2999  /// Indicates that there is no mismatch or a mismatch cannot be proven.
3000  NoMismatch,
3001  /// Indicates that variable is initialized with mismatching form of \a new.
3002  VarInitMismatches,
3003  /// Indicates that member is initialized with mismatching form of \a new.
3004  MemberInitMismatches,
3005  /// Indicates that 1 or more constructors' definitions could not been
3006  /// analyzed, and they will be checked again at the end of translation unit.
3007  AnalyzeLater
3008  };
3009 
3010  /// \param EndOfTU True, if this is the final analysis at the end of
3011  /// translation unit. False, if this is the initial analysis at the point
3012  /// delete-expression was encountered.
3013  explicit MismatchingNewDeleteDetector(bool EndOfTU)
3014  : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3015  HasUndefinedConstructors(false) {}
3016 
3017  /// Checks whether pointee of a delete-expression is initialized with
3018  /// matching form of new-expression.
3019  ///
3020  /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3021  /// point where delete-expression is encountered, then a warning will be
3022  /// issued immediately. If return value is \c AnalyzeLater at the point where
3023  /// delete-expression is seen, then member will be analyzed at the end of
3024  /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3025  /// couldn't be analyzed. If at least one constructor initializes the member
3026  /// with matching type of new, the return value is \c NoMismatch.
3027  MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3028  /// Analyzes a class member.
3029  /// \param Field Class member to analyze.
3030  /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3031  /// for deleting the \p Field.
3032  MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3033  FieldDecl *Field;
3034  /// List of mismatching new-expressions used for initialization of the pointee
3036  /// Indicates whether delete-expression was in array form.
3037  bool IsArrayForm;
3038 
3039 private:
3040  const bool EndOfTU;
3041  /// Indicates that there is at least one constructor without body.
3042  bool HasUndefinedConstructors;
3043  /// Returns \c CXXNewExpr from given initialization expression.
3044  /// \param E Expression used for initializing pointee in delete-expression.
3045  /// E can be a single-element \c InitListExpr consisting of new-expression.
3046  const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3047  /// Returns whether member is initialized with mismatching form of
3048  /// \c new either by the member initializer or in-class initialization.
3049  ///
3050  /// If bodies of all constructors are not visible at the end of translation
3051  /// unit or at least one constructor initializes member with the matching
3052  /// form of \c new, mismatch cannot be proven, and this function will return
3053  /// \c NoMismatch.
3054  MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3055  /// Returns whether variable is initialized with mismatching form of
3056  /// \c new.
3057  ///
3058  /// If variable is initialized with matching form of \c new or variable is not
3059  /// initialized with a \c new expression, this function will return true.
3060  /// If variable is initialized with mismatching form of \c new, returns false.
3061  /// \param D Variable to analyze.
3062  bool hasMatchingVarInit(const DeclRefExpr *D);
3063  /// Checks whether the constructor initializes pointee with mismatching
3064  /// form of \c new.
3065  ///
3066  /// Returns true, if member is initialized with matching form of \c new in
3067  /// member initializer list. Returns false, if member is initialized with the
3068  /// matching form of \c new in this constructor's initializer or given
3069  /// constructor isn't defined at the point where delete-expression is seen, or
3070  /// member isn't initialized by the constructor.
3071  bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3072  /// Checks whether member is initialized with matching form of
3073  /// \c new in member initializer list.
3074  bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3075  /// Checks whether member is initialized with mismatching form of \c new by
3076  /// in-class initializer.
3077  MismatchResult analyzeInClassInitializer();
3078 };
3079 }
3080 
3081 MismatchingNewDeleteDetector::MismatchResult
3082 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3083  NewExprs.clear();
3084  assert(DE && "Expected delete-expression");
3085  IsArrayForm = DE->isArrayForm();
3086  const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3087  if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3088  return analyzeMemberExpr(ME);
3089  } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3090  if (!hasMatchingVarInit(D))
3091  return VarInitMismatches;
3092  }
3093  return NoMismatch;
3094 }
3095 
3096 const CXXNewExpr *
3097 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3098  assert(E != nullptr && "Expected a valid initializer expression");
3099  E = E->IgnoreParenImpCasts();
3100  if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3101  if (ILE->getNumInits() == 1)
3102  E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3103  }
3104 
3105  return dyn_cast_or_null<const CXXNewExpr>(E);
3106 }
3107 
3108 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3109  const CXXCtorInitializer *CI) {
3110  const CXXNewExpr *NE = nullptr;
3111  if (Field == CI->getMember() &&
3112  (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3113  if (NE->isArray() == IsArrayForm)
3114  return true;
3115  else
3116  NewExprs.push_back(NE);
3117  }
3118  return false;
3119 }
3120 
3121 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3122  const CXXConstructorDecl *CD) {
3123  if (CD->isImplicit())
3124  return false;
3125  const FunctionDecl *Definition = CD;
3126  if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3127  HasUndefinedConstructors = true;
3128  return EndOfTU;
3129  }
3130  for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3131  if (hasMatchingNewInCtorInit(CI))
3132  return true;
3133  }
3134  return false;
3135 }
3136 
3137 MismatchingNewDeleteDetector::MismatchResult
3138 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3139  assert(Field != nullptr && "This should be called only for members");
3140  const Expr *InitExpr = Field->getInClassInitializer();
3141  if (!InitExpr)
3142  return EndOfTU ? NoMismatch : AnalyzeLater;
3143  if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3144  if (NE->isArray() != IsArrayForm) {
3145  NewExprs.push_back(NE);
3146  return MemberInitMismatches;
3147  }
3148  }
3149  return NoMismatch;
3150 }
3151 
3152 MismatchingNewDeleteDetector::MismatchResult
3153 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3154  bool DeleteWasArrayForm) {
3155  assert(Field != nullptr && "Analysis requires a valid class member.");
3156  this->Field = Field;
3157  IsArrayForm = DeleteWasArrayForm;
3158  const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3159  for (const auto *CD : RD->ctors()) {
3160  if (hasMatchingNewInCtor(CD))
3161  return NoMismatch;
3162  }
3163  if (HasUndefinedConstructors)
3164  return EndOfTU ? NoMismatch : AnalyzeLater;
3165  if (!NewExprs.empty())
3166  return MemberInitMismatches;
3167  return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3168  : NoMismatch;
3169 }
3170 
3171 MismatchingNewDeleteDetector::MismatchResult
3172 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3173  assert(ME != nullptr && "Expected a member expression");
3174  if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3175  return analyzeField(F, IsArrayForm);
3176  return NoMismatch;
3177 }
3178 
3179 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3180  const CXXNewExpr *NE = nullptr;
3181  if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3182  if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3183  NE->isArray() != IsArrayForm) {
3184  NewExprs.push_back(NE);
3185  }
3186  }
3187  return NewExprs.empty();
3188 }
3189 
3190 static void
3192  const MismatchingNewDeleteDetector &Detector) {
3193  SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3194  FixItHint H;
3195  if (!Detector.IsArrayForm)
3196  H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3197  else {
3199  DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3200  SemaRef.getLangOpts(), true);
3201  if (RSquare.isValid())
3202  H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3203  }
3204  SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3205  << Detector.IsArrayForm << H;
3206 
3207  for (const auto *NE : Detector.NewExprs)
3208  SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3209  << Detector.IsArrayForm;
3210 }
3211 
3212 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3213  if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3214  return;
3215  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3216  switch (Detector.analyzeDeleteExpr(DE)) {
3217  case MismatchingNewDeleteDetector::VarInitMismatches:
3218  case MismatchingNewDeleteDetector::MemberInitMismatches: {
3219  DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3220  break;
3221  }
3222  case MismatchingNewDeleteDetector::AnalyzeLater: {
3223  DeleteExprs[Detector.Field].push_back(
3224  std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3225  break;
3226  }
3227  case MismatchingNewDeleteDetector::NoMismatch:
3228  break;
3229  }
3230 }
3231 
3232 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3233  bool DeleteWasArrayForm) {
3234  MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3235  switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3236  case MismatchingNewDeleteDetector::VarInitMismatches:
3237  llvm_unreachable("This analysis should have been done for class members.");
3238  case MismatchingNewDeleteDetector::AnalyzeLater:
3239  llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3240  "translation unit.");
3241  case MismatchingNewDeleteDetector::MemberInitMismatches:
3242  DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3243  break;
3244  case MismatchingNewDeleteDetector::NoMismatch:
3245  break;
3246  }
3247 }
3248 
3249 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3250 /// @code ::delete ptr; @endcode
3251 /// or
3252 /// @code delete [] ptr; @endcode
3253 ExprResult
3254 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3255  bool ArrayForm, Expr *ExE) {
3256  // C++ [expr.delete]p1:
3257  // The operand shall have a pointer type, or a class type having a single
3258  // non-explicit conversion function to a pointer type. The result has type
3259  // void.
3260  //
3261  // DR599 amends "pointer type" to "pointer to object type" in both cases.
3262 
3263  ExprResult Ex = ExE;
3264  FunctionDecl *OperatorDelete = nullptr;
3265  bool ArrayFormAsWritten = ArrayForm;
3266  bool UsualArrayDeleteWantsSize = false;
3267 
3268  if (!Ex.get()->isTypeDependent()) {
3269  // Perform lvalue-to-rvalue cast, if needed.
3270  Ex = DefaultLvalueConversion(Ex.get());
3271  if (Ex.isInvalid())
3272  return ExprError();
3273 
3274  QualType Type = Ex.get()->getType();
3275 
3276  class DeleteConverter : public ContextualImplicitConverter {
3277  public:
3278  DeleteConverter() : ContextualImplicitConverter(false, true) {}
3279 
3280  bool match(QualType ConvType) override {
3281  // FIXME: If we have an operator T* and an operator void*, we must pick
3282  // the operator T*.
3283  if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3284  if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3285  return true;
3286  return false;
3287  }
3288 
3289  SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3290  QualType T) override {
3291  return S.Diag(Loc, diag::err_delete_operand) << T;
3292  }
3293 
3294  SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3295  QualType T) override {
3296  return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3297  }
3298 
3299  SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3300  QualType T,
3301  QualType ConvTy) override {
3302  return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3303  }
3304 
3305  SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3306  QualType ConvTy) override {
3307  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3308  << ConvTy;
3309  }
3310 
3311  SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3312  QualType T) override {
3313  return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3314  }
3315 
3316  SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3317  QualType ConvTy) override {
3318  return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3319  << ConvTy;
3320  }
3321 
3322  SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3323  QualType T,
3324  QualType ConvTy) override {
3325  llvm_unreachable("conversion functions are permitted");
3326  }
3327  } Converter;
3328 
3329  Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3330  if (Ex.isInvalid())
3331  return ExprError();
3332  Type = Ex.get()->getType();
3333  if (!Converter.match(Type))
3334  // FIXME: PerformContextualImplicitConversion should return ExprError
3335  // itself in this case.
3336  return ExprError();
3337 
3338  QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3339  QualType PointeeElem = Context.getBaseElementType(Pointee);
3340 
3341  if (Pointee.getAddressSpace() != LangAS::Default &&
3342  !getLangOpts().OpenCLCPlusPlus)
3343  return Diag(Ex.get()->getBeginLoc(),
3344  diag::err_address_space_qualified_delete)
3345  << Pointee.getUnqualifiedType()
3347 
3348  CXXRecordDecl *PointeeRD = nullptr;
3349  if (Pointee->isVoidType() && !isSFINAEContext()) {
3350  // The C++ standard bans deleting a pointer to a non-object type, which
3351  // effectively bans deletion of "void*". However, most compilers support
3352  // this, so we treat it as a warning unless we're in a SFINAE context.
3353  Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3354  << Type << Ex.get()->getSourceRange();
3355  } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3356  return ExprError(Diag(StartLoc, diag::err_delete_operand)
3357  << Type << Ex.get()->getSourceRange());
3358  } else if (!Pointee->isDependentType()) {
3359  // FIXME: This can result in errors if the definition was imported from a
3360  // module but is hidden.
3361  if (!RequireCompleteType(StartLoc, Pointee,
3362  diag::warn_delete_incomplete, Ex.get())) {
3363  if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3364  PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3365  }
3366  }
3367 
3368  if (Pointee->isArrayType() && !ArrayForm) {
3369  Diag(StartLoc, diag::warn_delete_array_type)
3370  << Type << Ex.get()->getSourceRange()
3371  << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3372  ArrayForm = true;
3373  }
3374 
3376  ArrayForm ? OO_Array_Delete : OO_Delete);
3377 
3378  if (PointeeRD) {
3379  if (!UseGlobal &&
3380  FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3381  OperatorDelete))
3382  return ExprError();
3383 
3384  // If we're allocating an array of records, check whether the
3385  // usual operator delete[] has a size_t parameter.
3386  if (ArrayForm) {
3387  // If the user specifically asked to use the global allocator,
3388  // we'll need to do the lookup into the class.
3389  if (UseGlobal)
3390  UsualArrayDeleteWantsSize =
3391  doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3392 
3393  // Otherwise, the usual operator delete[] should be the
3394  // function we just found.
3395  else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3396  UsualArrayDeleteWantsSize =
3397  UsualDeallocFnInfo(*this,
3398  DeclAccessPair::make(OperatorDelete, AS_public))
3399  .HasSizeT;
3400  }
3401 
3402  if (!PointeeRD->hasIrrelevantDestructor())
3403  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3404  MarkFunctionReferenced(StartLoc,
3405  const_cast<CXXDestructorDecl*>(Dtor));
3406  if (DiagnoseUseOfDecl(Dtor, StartLoc))
3407  return ExprError();
3408  }
3409 
3410  CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3411  /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3412  /*WarnOnNonAbstractTypes=*/!ArrayForm,
3413  SourceLocation());
3414  }
3415 
3416  if (!OperatorDelete) {
3417  if (getLangOpts().OpenCLCPlusPlus) {
3418  Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3419  return ExprError();
3420  }
3421 
3422  bool IsComplete = isCompleteType(StartLoc, Pointee);
3423  bool CanProvideSize =
3424  IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3425  Pointee.isDestructedType());
3426  bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3427 
3428  // Look for a global declaration.
3429  OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3430  Overaligned, DeleteName);
3431  }
3432 
3433  MarkFunctionReferenced(StartLoc, OperatorDelete);
3434 
3435  // Check access and ambiguity of destructor if we're going to call it.
3436  // Note that this is required even for a virtual delete.
3437  bool IsVirtualDelete = false;
3438  if (PointeeRD) {
3439  if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3440  CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3441  PDiag(diag::err_access_dtor) << PointeeElem);
3442  IsVirtualDelete = Dtor->isVirtual();
3443  }
3444  }
3445 
3446  DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3447 
3448  // Convert the operand to the type of the first parameter of operator
3449  // delete. This is only necessary if we selected a destroying operator
3450  // delete that we are going to call (non-virtually); converting to void*
3451  // is trivial and left to AST consumers to handle.
3452  QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3453  if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3454  Qualifiers Qs = Pointee.getQualifiers();
3455  if (Qs.hasCVRQualifiers()) {
3456  // Qualifiers are irrelevant to this conversion; we're only looking
3457  // for access and ambiguity.
3458  Qs.removeCVRQualifiers();
3459  QualType Unqual = Context.getPointerType(
3461  Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3462  }
3463  Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3464  if (Ex.isInvalid())
3465  return ExprError();
3466  }
3467  }
3468 
3470  Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3471  UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3472  AnalyzeDeleteExprMismatch(Result);
3473  return Result;
3474 }
3475 
3477  bool IsDelete,
3478  FunctionDecl *&Operator) {
3479 
3481  IsDelete ? OO_Delete : OO_New);
3482 
3483  LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3485  assert(!R.empty() && "implicitly declared allocation functions not found");
3486  assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3487 
3488  // We do our own custom access checks below.
3489  R.suppressDiagnostics();
3490 
3491  SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3492  OverloadCandidateSet Candidates(R.getNameLoc(),
3494  for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3495  FnOvl != FnOvlEnd; ++FnOvl) {
3496  // Even member operator new/delete are implicitly treated as
3497  // static, so don't use AddMemberCandidate.
3498  NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3499 
3500  if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3501  S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3502  /*ExplicitTemplateArgs=*/nullptr, Args,
3503  Candidates,
3504  /*SuppressUserConversions=*/false);
3505  continue;
3506  }
3507 
3508  FunctionDecl *Fn = cast<FunctionDecl>(D);
3509  S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3510  /*SuppressUserConversions=*/false);
3511  }
3512 
3513  SourceRange Range = TheCall->getSourceRange();
3514 
3515  // Do the resolution.
3517  switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3518  case OR_Success: {
3519  // Got one!
3520  FunctionDecl *FnDecl = Best->Function;
3521  assert(R.getNamingClass() == nullptr &&
3522  "class members should not be considered");
3523 
3524  if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3525  S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3526  << (IsDelete ? 1 : 0) << Range;
3527  S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3528  << R.getLookupName() << FnDecl->getSourceRange();
3529  return true;
3530  }
3531 
3532  Operator = FnDecl;
3533  return false;
3534  }
3535 
3536  case OR_No_Viable_Function:
3537  Candidates.NoteCandidates(
3538  PartialDiagnosticAt(R.getNameLoc(),
3539  S.PDiag(diag::err_ovl_no_viable_function_in_call)
3540  << R.getLookupName() << Range),
3541  S, OCD_AllCandidates, Args);
3542  return true;
3543 
3544  case OR_Ambiguous:
3545  Candidates.NoteCandidates(
3546  PartialDiagnosticAt(R.getNameLoc(),
3547  S.PDiag(diag::err_ovl_ambiguous_call)
3548  << R.getLookupName() << Range),
3549  S, OCD_ViableCandidates, Args);
3550  return true;
3551 
3552  case OR_Deleted: {
3553  Candidates.NoteCandidates(
3554  PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3555  << R.getLookupName() << Range),
3556  S, OCD_AllCandidates, Args);
3557  return true;
3558  }
3559  }
3560  llvm_unreachable("Unreachable, bad result from BestViableFunction");
3561 }
3562 
3563 ExprResult
3564 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3565  bool IsDelete) {
3566  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3567  if (!getLangOpts().CPlusPlus) {
3568  Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3569  << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3570  << "C++";
3571  return ExprError();
3572  }
3573  // CodeGen assumes it can find the global new and delete to call,
3574  // so ensure that they are declared.
3576 
3577  FunctionDecl *OperatorNewOrDelete = nullptr;
3578  if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3579  OperatorNewOrDelete))
3580  return ExprError();
3581  assert(OperatorNewOrDelete && "should be found");
3582 
3583  DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3584  MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3585 
3586  TheCall->setType(OperatorNewOrDelete->getReturnType());
3587  for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3588  QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3589  InitializedEntity Entity =
3592  Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3593  if (Arg.isInvalid())
3594  return ExprError();
3595  TheCall->setArg(i, Arg.get());
3596  }
3597  auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3598  assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3599  "Callee expected to be implicit cast to a builtin function pointer");
3600  Callee->setType(OperatorNewOrDelete->getType());
3601 
3602  return TheCallResult;
3603 }
3604 
3606  bool IsDelete, bool CallCanBeVirtual,
3607  bool WarnOnNonAbstractTypes,
3608  SourceLocation DtorLoc) {
3609  if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3610  return;
3611 
3612  // C++ [expr.delete]p3:
3613  // In the first alternative (delete object), if the static type of the
3614  // object to be deleted is different from its dynamic type, the static
3615  // type shall be a base class of the dynamic type of the object to be
3616  // deleted and the static type shall have a virtual destructor or the
3617  // behavior is undefined.
3618  //
3619  const CXXRecordDecl *PointeeRD = dtor->getParent();
3620  // Note: a final class cannot be derived from, no issue there
3621  if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3622  return;
3623 
3624  // If the superclass is in a system header, there's nothing that can be done.
3625  // The `delete` (where we emit the warning) can be in a system header,
3626  // what matters for this warning is where the deleted type is defined.
3627  if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3628  return;
3629 
3630  QualType ClassType = dtor->getThisType()->getPointeeType();
3631  if (PointeeRD->isAbstract()) {
3632  // If the class is abstract, we warn by default, because we're
3633  // sure the code has undefined behavior.
3634  Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3635  << ClassType;
3636  } else if (WarnOnNonAbstractTypes) {
3637  // Otherwise, if this is not an array delete, it's a bit suspect,
3638  // but not necessarily wrong.
3639  Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3640  << ClassType;
3641  }
3642  if (!IsDelete) {
3643  std::string TypeStr;
3644  ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3645  Diag(DtorLoc, diag::note_delete_non_virtual)
3646  << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3647  }
3648 }
3649 
3651  SourceLocation StmtLoc,
3652  ConditionKind CK) {
3653  ExprResult E =
3654  CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3655  if (E.isInvalid())
3656  return ConditionError();
3657  return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3659 }
3660 
3661 /// Check the use of the given variable as a C++ condition in an if,
3662 /// while, do-while, or switch statement.
3664  SourceLocation StmtLoc,
3665  ConditionKind CK) {
3666  if (ConditionVar->isInvalidDecl())
3667  return ExprError();
3668 
3669  QualType T = ConditionVar->getType();
3670 
3671  // C++ [stmt.select]p2:
3672  // The declarator shall not specify a function or an array.
3673  if (T->isFunctionType())
3674  return ExprError(Diag(ConditionVar->getLocation(),
3675  diag::err_invalid_use_of_function_type)
3676  << ConditionVar->getSourceRange());
3677  else if (T->isArrayType())
3678  return ExprError(Diag(ConditionVar->getLocation(),
3679  diag::err_invalid_use_of_array_type)
3680  << ConditionVar->getSourceRange());
3681 
3682  ExprResult Condition = DeclRefExpr::Create(
3683  Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3684  /*enclosing*/ false, ConditionVar->getLocation(),
3685  ConditionVar->getType().getNonReferenceType(), VK_LValue);
3686 
3687  MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3688 
3689  switch (CK) {
3691  return CheckBooleanCondition(StmtLoc, Condition.get());
3692 
3694  return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3695 
3696  case ConditionKind::Switch:
3697  return CheckSwitchCondition(StmtLoc, Condition.get());
3698  }
3699 
3700  llvm_unreachable("unexpected condition kind");
3701 }
3702 
3703 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3704 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3705  // C++ 6.4p4:
3706  // The value of a condition that is an initialized declaration in a statement
3707  // other than a switch statement is the value of the declared variable
3708  // implicitly converted to type bool. If that conversion is ill-formed, the
3709  // program is ill-formed.
3710  // The value of a condition that is an expression is the value of the
3711  // expression, implicitly converted to bool.
3712  //
3713  // FIXME: Return this value to the caller so they don't need to recompute it.
3714  llvm::APSInt Value(/*BitWidth*/1);
3715  return (IsConstexpr && !CondExpr->isValueDependent())
3716  ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3719 }
3720 
3721 /// Helper function to determine whether this is the (deprecated) C++
3722 /// conversion from a string literal to a pointer to non-const char or
3723 /// non-const wchar_t (for narrow and wide string literals,
3724 /// respectively).
3725 bool
3727  // Look inside the implicit cast, if it exists.
3728  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3729  From = Cast->getSubExpr();
3730 
3731  // A string literal (2.13.4) that is not a wide string literal can
3732  // be converted to an rvalue of type "pointer to char"; a wide
3733  // string literal can be converted to an rvalue of type "pointer
3734  // to wchar_t" (C++ 4.2p2).
3735  if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3736  if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3737  if (const BuiltinType *ToPointeeType
3738  = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3739  // This conversion is considered only when there is an
3740  // explicit appropriate pointer target type (C++ 4.2p2).
3741  if (!ToPtrType->getPointeeType().hasQualifiers()) {
3742  switch (StrLit->getKind()) {
3743  case StringLiteral::UTF8:
3744  case StringLiteral::UTF16:
3745  case StringLiteral::UTF32:
3746  // We don't allow UTF literals to be implicitly converted
3747  break;
3748  case StringLiteral::Ascii:
3749  return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3750  ToPointeeType->getKind() == BuiltinType::Char_S);
3751  case StringLiteral::Wide:
3753  QualType(ToPointeeType, 0));
3754  }
3755  }
3756  }
3757 
3758  return false;
3759 }
3760 
3762  SourceLocation CastLoc,
3763  QualType Ty,
3764  CastKind Kind,
3765  CXXMethodDecl *Method,
3766  DeclAccessPair FoundDecl,
3767  bool HadMultipleCandidates,
3768  Expr *From) {
3769  switch (Kind) {
3770  default: llvm_unreachable("Unhandled cast kind!");
3771  case CK_ConstructorConversion: {
3772  CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3773  SmallVector<Expr*, 8> ConstructorArgs;
3774 
3775  if (S.RequireNonAbstractType(CastLoc, Ty,
3776  diag::err_allocation_of_abstract_type))
3777  return ExprError();
3778 
3779  if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3780  return ExprError();
3781 
3782  S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3784  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3785  return ExprError();
3786 
3788  CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3789  ConstructorArgs, HadMultipleCandidates,
3790  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3792  if (Result.isInvalid())
3793  return ExprError();
3794 
3795  return S.MaybeBindToTemporary(Result.getAs<Expr>());
3796  }
3797 
3798  case CK_UserDefinedConversion: {
3799  assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3800 
3801  S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3802  if (S.DiagnoseUseOfDecl(Method, CastLoc))
3803  return ExprError();
3804 
3805  // Create an implicit call expr that calls it.
3806  CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3807  ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3808  HadMultipleCandidates);
3809  if (Result.isInvalid())
3810  return ExprError();
3811  // Record usage of conversion in an implicit cast.
3812  Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3813  CK_UserDefinedConversion, Result.get(),
3814  nullptr, Result.get()->getValueKind());
3815 
3816  return S.MaybeBindToTemporary(Result.get());
3817  }
3818  }
3819 }
3820 
3821 /// PerformImplicitConversion - Perform an implicit conversion of the
3822 /// expression From to the type ToType using the pre-computed implicit
3823 /// conversion sequence ICS. Returns the converted
3824 /// expression. Action is the kind of conversion we're performing,
3825 /// used in the error message.
3826 ExprResult
3828  const ImplicitConversionSequence &ICS,
3829  AssignmentAction Action,
3830  CheckedConversionKind CCK) {
3831  // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3832  if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3833  return From;
3834 
3835  switch (ICS.getKind()) {
3837  ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3838  Action, CCK);
3839  if (Res.isInvalid())
3840  return ExprError();
3841  From = Res.get();
3842  break;
3843  }
3844 
3846 
3849  QualType BeforeToType;
3850  assert(FD && "no conversion function for user-defined conversion seq");
3851  if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3852  CastKind = CK_UserDefinedConversion;
3853 
3854  // If the user-defined conversion is specified by a conversion function,
3855  // the initial standard conversion sequence converts the source type to
3856  // the implicit object parameter of the conversion function.
3857  BeforeToType = Context.getTagDeclType(Conv->getParent());
3858  } else {
3859  const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3860  CastKind = CK_ConstructorConversion;
3861  // Do no conversion if dealing with ... for the first conversion.
3862  if (!ICS.UserDefined.EllipsisConversion) {
3863  // If the user-defined conversion is specified by a constructor, the
3864  // initial standard conversion sequence converts the source type to
3865  // the type required by the argument of the constructor
3866  BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3867  }
3868  }
3869  // Watch out for ellipsis conversion.
3870  if (!ICS.UserDefined.EllipsisConversion) {
3871  ExprResult Res =
3872  PerformImplicitConversion(From, BeforeToType,
3874  CCK);
3875  if (Res.isInvalid())
3876  return ExprError();
3877  From = Res.get();
3878  }
3879 
3880  ExprResult CastArg = BuildCXXCastArgument(
3881  *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3882  cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3884 
3885  if (CastArg.isInvalid())
3886  return ExprError();
3887 
3888  From = CastArg.get();
3889 
3890  // C++ [over.match.oper]p7:
3891  // [...] the second standard conversion sequence of a user-defined
3892  // conversion sequence is not applied.
3893  if (CCK == CCK_ForBuiltinOverloadedOp)
3894  return From;
3895 
3896  return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3897  AA_Converting, CCK);
3898  }
3899 
3901  ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3902  PDiag(diag::err_typecheck_ambiguous_condition)
3903  << From->getSourceRange());
3904  return ExprError();
3905 
3907  llvm_unreachable("Cannot perform an ellipsis conversion");
3908 
3910  bool Diagnosed =
3912  From->getType(), From, Action);
3913  assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3914  return ExprError();
3915  }
3916 
3917  // Everything went well.
3918  return From;
3919 }
3920 
3921 /// PerformImplicitConversion - Perform an implicit conversion of the
3922 /// expression From to the type ToType by following the standard
3923 /// conversion sequence SCS. Returns the converted
3924 /// expression. Flavor is the context in which we're performing this
3925 /// conversion, for use in error messages.
3926 ExprResult
3928  const StandardConversionSequence& SCS,
3929  AssignmentAction Action,
3930  CheckedConversionKind CCK) {
3931  bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3932 
3933  // Overall FIXME: we are recomputing too many types here and doing far too
3934  // much extra work. What this means is that we need to keep track of more
3935  // information that is computed when we try the implicit conversion initially,
3936  // so that we don't need to recompute anything here.
3937  QualType FromType = From->getType();
3938 
3939  if (SCS.CopyConstructor) {
3940  // FIXME: When can ToType be a reference type?
3941  assert(!ToType->isReferenceType());
3942  if (SCS.Second == ICK_Derived_To_Base) {
3943  SmallVector<Expr*, 8> ConstructorArgs;
3944  if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3945  From, /*FIXME:ConstructLoc*/SourceLocation(),
3946  ConstructorArgs))
3947  return ExprError();
3948  return BuildCXXConstructExpr(
3949  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3951  ConstructorArgs, /*HadMultipleCandidates*/ false,
3952  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3954  }
3955  return BuildCXXConstructExpr(
3956  /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3958  From, /*HadMultipleCandidates*/ false,
3959  /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3961  }
3962 
3963  // Resolve overloaded function references.
3964  if (Context.hasSameType(FromType, Context.OverloadTy)) {
3965  DeclAccessPair Found;
3967  true, Found);
3968  if (!Fn)
3969  return ExprError();
3970 
3971  if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3972  return ExprError();
3973 
3974  From = FixOverloadedFunctionReference(From, Found, Fn);
3975  FromType = From->getType();
3976  }
3977 
3978  // If we're converting to an atomic type, first convert to the corresponding
3979  // non-atomic type.
3980  QualType ToAtomicType;
3981  if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3982  ToAtomicType = ToType;
3983  ToType = ToAtomic->getValueType();
3984  }
3985 
3986  QualType InitialFromType = FromType;
3987  // Perform the first implicit conversion.
3988  switch (SCS.First) {
3989  case ICK_Identity:
3990  if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3991  FromType = FromAtomic->getValueType().getUnqualifiedType();
3992  From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3993  From, /*BasePath=*/nullptr, VK_RValue);
3994  }
3995  break;
3996 
3997  case ICK_Lvalue_To_Rvalue: {
3998  assert(From->getObjectKind() != OK_ObjCProperty);
3999  ExprResult FromRes = DefaultLvalueConversion(From);
4000  assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
4001  From = FromRes.get();
4002  FromType = From->getType();
4003  break;
4004  }
4005 
4006  case ICK_Array_To_Pointer:
4007  FromType = Context.getArrayDecayedType(FromType);
4008  From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
4009  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4010  break;
4011 
4013  FromType = Context.getPointerType(FromType);
4014  From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4015  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4016  break;
4017 
4018  default:
4019  llvm_unreachable("Improper first standard conversion");
4020  }
4021 
4022  // Perform the second implicit conversion
4023  switch (SCS.Second) {
4024  case ICK_Identity:
4025  // C++ [except.spec]p5:
4026  // [For] assignment to and initialization of pointers to functions,
4027  // pointers to member functions, and references to functions: the
4028  // target entity shall allow at least the exceptions allowed by the
4029  // source value in the assignment or initialization.
4030  switch (Action) {
4031  case AA_Assigning:
4032  case AA_Initializing:
4033  // Note, function argument passing and returning are initialization.
4034  case AA_Passing:
4035  case AA_Returning:
4036  case AA_Sending:
4037  case AA_Passing_CFAudited:
4038  if (CheckExceptionSpecCompatibility(From, ToType))
4039  return ExprError();
4040  break;
4041 
4042  case AA_Casting:
4043  case AA_Converting:
4044  // Casts and implicit conversions are not initialization, so are not
4045  // checked for exception specification mismatches.
4046  break;
4047  }
4048  // Nothing else to do.
4049  break;
4050 
4053  if (ToType->isBooleanType()) {
4054  assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4055  SCS.Second == ICK_Integral_Promotion &&
4056  "only enums with fixed underlying type can promote to bool");
4057  From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4058  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4059  } else {
4060  From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4061  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4062  }
4063  break;
4064 
4067  From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4068  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4069  break;
4070 
4071  case ICK_Complex_Promotion:
4072  case ICK_Complex_Conversion: {
4073  QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4074  QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4075  CastKind CK;
4076  if (FromEl->isRealFloatingType()) {
4077  if (ToEl->isRealFloatingType())
4078  CK = CK_FloatingComplexCast;
4079  else
4080  CK = CK_FloatingComplexToIntegralComplex;
4081  } else if (ToEl->isRealFloatingType()) {
4082  CK = CK_IntegralComplexToFloatingComplex;
4083  } else {
4084  CK = CK_IntegralComplexCast;
4085  }
4086  From = ImpCastExprToType(From, ToType, CK,
4087  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4088  break;
4089  }
4090 
4091  case ICK_Floating_Integral:
4092  if (ToType->isRealFloatingType())
4093  From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4094  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4095  else
4096  From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4097  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4098  break;
4099 
4101  From = ImpCastExprToType(From, ToType, CK_NoOp,
4102  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4103  break;
4104 
4106  case ICK_Pointer_Conversion: {
4107  if (SCS.IncompatibleObjC && Action != AA_Casting) {
4108  // Diagnose incompatible Objective-C conversions
4109  if (Action == AA_Initializing || Action == AA_Assigning)
4110  Diag(From->getBeginLoc(),
4111  diag::ext_typecheck_convert_incompatible_pointer)
4112  << ToType << From->getType() << Action << From->getSourceRange()
4113  << 0;
4114  else
4115  Diag(From->getBeginLoc(),
4116  diag::ext_typecheck_convert_incompatible_pointer)
4117  << From->getType() << ToType << Action << From->getSourceRange()
4118  << 0;
4119 
4120  if (From->getType()->isObjCObjectPointerType() &&
4121  ToType->isObjCObjectPointerType())
4125  From->getType())) {
4126  if (Action == AA_Initializing)
4127  Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4128  else
4129  Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4130  << (Action == AA_Casting) << From->getType() << ToType
4131  << From->getSourceRange();
4132  }
4133 
4134  CastKind Kind;
4135  CXXCastPath BasePath;
4136  if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4137  return ExprError();
4138 
4139  // Make sure we extend blocks if necessary.
4140  // FIXME: doing this here is really ugly.
4141  if (Kind == CK_BlockPointerToObjCPointerCast) {
4142  ExprResult E = From;
4144  From = E.get();
4145  }
4146  if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4147  CheckObjCConversion(SourceRange(), ToType, From, CCK);
4148  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4149  .get();
4150  break;
4151  }
4152 
4153  case ICK_Pointer_Member: {
4154  CastKind Kind;
4155  CXXCastPath BasePath;
4156  if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4157  return ExprError();
4158  if (CheckExceptionSpecCompatibility(From, ToType))
4159  return ExprError();
4160 
4161  // We may not have been able to figure out what this member pointer resolved
4162  // to up until this exact point. Attempt to lock-in it's inheritance model.
4164  (void)isCompleteType(From->getExprLoc(), From->getType());
4165  (void)isCompleteType(From->getExprLoc(), ToType);
4166  }
4167 
4168  From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4169  .get();
4170  break;
4171  }
4172 
4174  // Perform half-to-boolean conversion via float.
4175  if (From->getType()->isHalfType()) {
4176  From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4177  FromType = Context.FloatTy;
4178  }
4179 
4180  From = ImpCastExprToType(From, Context.BoolTy,
4181  ScalarTypeToBooleanCastKind(FromType),
4182  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4183  break;
4184 
4185  case ICK_Derived_To_Base: {
4186  CXXCastPath BasePath;
4188  From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4189  From->getSourceRange(), &BasePath, CStyle))
4190  return ExprError();
4191 
4192  From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4193  CK_DerivedToBase, From->getValueKind(),
4194  &BasePath, CCK).get();
4195  break;
4196  }
4197 
4198  case ICK_Vector_Conversion:
4199  From = ImpCastExprToType(From, ToType, CK_BitCast,
4200  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4201  break;
4202 
4203  case ICK_Vector_Splat: {
4204  // Vector splat from any arithmetic type to a vector.
4205  Expr *Elem = prepareVectorSplat(ToType, From).get();
4206  From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4207  /*BasePath=*/nullptr, CCK).get();
4208  break;
4209  }
4210 
4211  case ICK_Complex_Real:
4212  // Case 1. x -> _Complex y
4213  if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4214  QualType ElType = ToComplex->getElementType();
4215  bool isFloatingComplex = ElType->isRealFloatingType();
4216 
4217  // x -> y
4218  if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4219  // do nothing
4220  } else if (From->getType()->isRealFloatingType()) {
4221  From = ImpCastExprToType(From, ElType,
4222  isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4223  } else {
4224  assert(From->getType()->isIntegerType());
4225  From = ImpCastExprToType(From, ElType,
4226  isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4227  }
4228  // y -> _Complex y
4229  From = ImpCastExprToType(From, ToType,
4230  isFloatingComplex ? CK_FloatingRealToComplex
4231  : CK_IntegralRealToComplex).get();
4232 
4233  // Case 2. _Complex x -> y
4234  } else {
4235  const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4236  assert(FromComplex);
4237 
4238  QualType ElType = FromComplex->getElementType();
4239  bool isFloatingComplex = ElType->isRealFloatingType();
4240 
4241  // _Complex x -> x
4242  From = ImpCastExprToType(From, ElType,
4243  isFloatingComplex ? CK_FloatingComplexToReal
4244  : CK_IntegralComplexToReal,
4245  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4246 
4247  // x -> y
4248  if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4249  // do nothing
4250  } else if (ToType->isRealFloatingType()) {
4251  From = ImpCastExprToType(From, ToType,
4252  isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4253  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4254  } else {
4255  assert(ToType->isIntegerType());
4256  From = ImpCastExprToType(From, ToType,
4257  isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4258  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4259  }
4260  }
4261  break;
4262 
4264  From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4265  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4266  break;
4267  }
4268 
4270  ExprResult FromRes = From;
4271  Sema::AssignConvertType ConvTy =
4273  if (FromRes.isInvalid())
4274  return ExprError();
4275  From = FromRes.get();
4276  assert ((ConvTy == Sema::Compatible) &&
4277  "Improper transparent union conversion");
4278  (void)ConvTy;
4279  break;
4280  }
4281 
4284  From = ImpCastExprToType(From, ToType,
4285  CK_ZeroToOCLOpaqueType,
4286  From->getValueKind()).get();
4287  break;
4288 
4289  case ICK_Lvalue_To_Rvalue:
4290  case ICK_Array_To_Pointer:
4293  case ICK_Qualification:
4295  case ICK_C_Only_Conversion:
4297  llvm_unreachable("Improper second standard conversion");
4298  }
4299 
4300  switch (SCS.Third) {
4301  case ICK_Identity:
4302  // Nothing to do.
4303  break;
4304 
4306  // If both sides are functions (or pointers/references to them), there could
4307  // be incompatible exception declarations.
4308  if (CheckExceptionSpecCompatibility(From, ToType))
4309  return ExprError();
4310 
4311  From = ImpCastExprToType(From, ToType, CK_NoOp,
4312  VK_RValue, /*BasePath=*/nullptr, CCK).get();
4313  break;
4314 
4315  case ICK_Qualification: {
4316  // The qualification keeps the category of the inner expression, unless the
4317  // target type isn't a reference.
4318  ExprValueKind VK =
4319  ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4320 
4321  CastKind CK = CK_NoOp;
4322 
4323  if (ToType->isReferenceType() &&
4324  ToType->getPointeeType().getAddressSpace() !=
4325  From->getType().getAddressSpace())
4326  CK = CK_AddressSpaceConversion;
4327 
4328  if (ToType->isPointerType() &&
4329  ToType->getPointeeType().getAddressSpace() !=
4330  From->getType()->getPointeeType().getAddressSpace())
4331  CK = CK_AddressSpaceConversion;
4332 
4333  From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4334  /*BasePath=*/nullptr, CCK)
4335  .get();
4336 
4338  !getLangOpts().WritableStrings) {
4339  Diag(From->getBeginLoc(),
4340  getLangOpts().CPlusPlus11
4341  ? diag::ext_deprecated_string_literal_conversion
4342  : diag::warn_deprecated_string_literal_conversion)
4343  << ToType.getNonReferenceType();
4344  }
4345 
4346  break;
4347  }
4348 
4349  default:
4350  llvm_unreachable("Improper third standard conversion");
4351  }
4352 
4353  // If this conversion sequence involved a scalar -> atomic conversion, perform
4354  // that conversion now.
4355  if (!ToAtomicType.isNull()) {
4356  assert(Context.hasSameType(
4357  ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4358  From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4359  VK_RValue, nullptr, CCK).get();
4360  }
4361 
4362  // If this conversion sequence succeeded and involved implicitly converting a
4363  // _Nullable type to a _Nonnull one, complain.
4364  if (!isCast(CCK))
4365  diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4366  From->getBeginLoc());
4367 
4368  return From;
4369 }
4370 
4371 /// Check the completeness of a type in a unary type trait.
4372 ///
4373 /// If the particular type trait requires a complete type, tries to complete
4374 /// it. If completing the type fails, a diagnostic is emitted and false
4375 /// returned. If completing the type succeeds or no completion was required,
4376 /// returns true.
4378  SourceLocation Loc,
4379  QualType ArgTy) {
4380  // C++0x [meta.unary.prop]p3:
4381  // For all of the class templates X declared in this Clause, instantiating
4382  // that template with a template argument that is a class template
4383  // specialization may result in the implicit instantiation of the template
4384  // argument if and only if the semantics of X require that the argument
4385  // must be a complete type.
4386  // We apply this rule to all the type trait expressions used to implement
4387  // these class templates. We also try to follow any GCC documented behavior
4388  // in these expressions to ensure portability of standard libraries.
4389  switch (UTT) {
4390  default: llvm_unreachable("not a UTT");
4391  // is_complete_type somewhat obviously cannot require a complete type.
4392  case UTT_IsCompleteType:
4393  // Fall-through
4394 
4395  // These traits are modeled on the type predicates in C++0x
4396  // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4397  // requiring a complete type, as whether or not they return true cannot be
4398  // impacted by the completeness of the type.
4399  case UTT_IsVoid:
4400  case UTT_IsIntegral:
4401  case UTT_IsFloatingPoint:
4402  case UTT_IsArray:
4403  case UTT_IsPointer:
4404  case UTT_IsLvalueReference:
4405  case UTT_IsRvalueReference:
4408  case UTT_IsEnum:
4409  case UTT_IsUnion:
4410  case UTT_IsClass:
4411  case UTT_IsFunction:
4412  case UTT_IsReference:
4413  case UTT_IsArithmetic:
4414  case UTT_IsFundamental:
4415  case UTT_IsObject:
4416  case UTT_IsScalar:
4417  case UTT_IsCompound:
4418  case UTT_IsMemberPointer:
4419  // Fall-through
4420 
4421  // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4422  // which requires some of its traits to have the complete type. However,
4423  // the completeness of the type cannot impact these traits' semantics, and
4424  // so they don't require it. This matches the comments on these traits in
4425  // Table 49.
4426  case UTT_IsConst:
4427  case UTT_IsVolatile:
4428  case UTT_IsSigned:
4429  case UTT_IsUnsigned:
4430 
4431  // This type trait always returns false, checking the type is moot.
4432  case UTT_IsInterfaceClass:
4433  return true;
4434 
4435  // C++14 [meta.unary.prop]:
4436  // If T is a non-union class type, T shall be a complete type.
4437  case UTT_IsEmpty:
4438  case UTT_IsPolymorphic:
4439  case UTT_IsAbstract:
4440  if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4441  if (!RD->isUnion())
4442  return !S.RequireCompleteType(
4443  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4444  return true;
4445 
4446  // C++14 [meta.unary.prop]:
4447  // If T is a class type, T shall be a complete type.
4448  case UTT_IsFinal:
4449  case UTT_IsSealed:
4450  if (ArgTy->getAsCXXRecordDecl())
4451  return !S.RequireCompleteType(
4452  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4453  return true;
4454 
4455  // C++1z [meta.unary.prop]:
4456  // remove_all_extents_t<T> shall be a complete type or cv void.
4457  case UTT_IsAggregate:
4458  case UTT_IsTrivial:
4460  case UTT_IsStandardLayout:
4461  case UTT_IsPOD:
4462  case UTT_IsLiteral:
4463  // Per the GCC type traits documentation, T shall be a complete type, cv void,
4464  // or an array of unknown bound. But GCC actually imposes the same constraints
4465  // as above.
4466  case UTT_HasNothrowAssign:
4469  case UTT_HasNothrowCopy:
4470  case UTT_HasTrivialAssign:
4474  case UTT_HasTrivialCopy:
4477  ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4478  LLVM_FALLTHROUGH;
4479 
4480  // C++1z [meta.unary.prop]:
4481  // T shall be a complete type, cv void, or an array of unknown bound.
4482  case UTT_IsDestructible:
4486  if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4487  return true;
4488 
4489  return !S.RequireCompleteType(
4490  Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4491  }
4492 }
4493 
4495  Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4496  bool (CXXRecordDecl::*HasTrivial)() const,
4497  bool (CXXRecordDecl::*HasNonTrivial)() const,
4498  bool (CXXMethodDecl::*IsDesiredOp)() const)
4499 {
4500  CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4501  if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4502  return true;
4503 
4505  DeclarationNameInfo NameInfo(Name, KeyLoc);
4506  LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4507  if (Self.LookupQualifiedName(Res, RD)) {
4508  bool FoundOperator = false;
4509  Res.suppressDiagnostics();
4510  for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4511  Op != OpEnd; ++Op) {
4512  if (isa<FunctionTemplateDecl>(*Op))
4513  continue;
4514 
4515  CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4516  if((Operator->*IsDesiredOp)()) {
4517  FoundOperator = true;
4518  const FunctionProtoType *CPT =
4519  Operator->getType()->getAs<FunctionProtoType>();
4520  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4521  if (!CPT || !CPT->isNothrow())
4522  return false;
4523  }
4524  }
4525  return FoundOperator;
4526  }
4527  return false;
4528 }
4529 
4530 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4531  SourceLocation KeyLoc, QualType T) {
4532  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4533 
4534  ASTContext &C = Self.Context;
4535  switch(UTT) {
4536  default: llvm_unreachable("not a UTT");
4537  // Type trait expressions corresponding to the primary type category
4538  // predicates in C++0x [meta.unary.cat].
4539  case UTT_IsVoid:
4540  return T->isVoidType();
4541  case UTT_IsIntegral:
4542  return T->isIntegralType(C);
4543  case UTT_IsFloatingPoint:
4544  return T->isFloatingType();
4545  case UTT_IsArray:
4546  return T->isArrayType();
4547  case UTT_IsPointer:
4548  return T->isPointerType();
4549  case UTT_IsLvalueReference:
4550  return T->isLValueReferenceType();
4551  case UTT_IsRvalueReference:
4552  return T->isRValueReferenceType();
4554  return T->isMemberFunctionPointerType();
4556  return T->isMemberDataPointerType();
4557  case UTT_IsEnum:
4558  return T->isEnumeralType();
4559  case UTT_IsUnion:
4560  return T->isUnionType();
4561  case UTT_IsClass:
4562  return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4563  case UTT_IsFunction:
4564  return T->isFunctionType();
4565 
4566  // Type trait expressions which correspond to the convenient composition
4567  // predicates in C++0x [meta.unary.comp].
4568  case UTT_IsReference:
4569  return T->isReferenceType();
4570  case UTT_IsArithmetic:
4571  return T->isArithmeticType() && !T->isEnumeralType();
4572  case UTT_IsFundamental:
4573  return T->isFundamentalType();
4574  case UTT_IsObject:
4575  return T->isObjectType();
4576  case UTT_IsScalar:
4577  // Note: semantic analysis depends on Objective-C lifetime types to be
4578  // considered scalar types. However, such types do not actually behave
4579  // like scalar types at run time (since they may require retain/release
4580  // operations), so we report them as non-scalar.
4581  if (T->isObjCLifetimeType()) {
4582  switch (T.getObjCLifetime()) {
4583  case Qualifiers::OCL_None:
4585  return true;
4586 
4588  case Qualifiers::OCL_Weak:
4590  return false;
4591  }
4592  }
4593 
4594  return T->isScalarType();
4595  case UTT_IsCompound:
4596  return T->isCompoundType();
4597  case UTT_IsMemberPointer:
4598  return T->isMemberPointerType();
4599 
4600  // Type trait expressions which correspond to the type property predicates
4601  // in C++0x [meta.unary.prop].
4602  case UTT_IsConst:
4603  return T.isConstQualified();
4604  case UTT_IsVolatile:
4605  return T.isVolatileQualified();
4606  case UTT_IsTrivial:
4607  return T.isTrivialType(C);
4609  return T.isTriviallyCopyableType(C);
4610  case UTT_IsStandardLayout:
4611  return T->isStandardLayoutType();
4612  case UTT_IsPOD:
4613  return T.isPODType(C);
4614  case UTT_IsLiteral:
4615  return T->isLiteralType(C);
4616  case UTT_IsEmpty:
4617  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4618  return !RD->isUnion() && RD->isEmpty();
4619  return false;
4620  case UTT_IsPolymorphic:
4621  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4622  return !RD->isUnion() && RD->isPolymorphic();
4623  return false;
4624  case UTT_IsAbstract:
4625  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4626  return !RD->isUnion() && RD->isAbstract();
4627  return false;
4628  case UTT_IsAggregate:
4629  // Report vector extensions and complex types as aggregates because they
4630  // support aggregate initialization. GCC mirrors this behavior for vectors
4631  // but not _Complex.
4632  return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4633  T->isAnyComplexType();
4634  // __is_interface_class only returns true when CL is invoked in /CLR mode and
4635  // even then only when it is used with the 'interface struct ...' syntax
4636  // Clang doesn't support /CLR which makes this type trait moot.
4637  case UTT_IsInterfaceClass:
4638  return false;
4639  case UTT_IsFinal:
4640  case UTT_IsSealed:
4641  if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4642  return RD->hasAttr<FinalAttr>();
4643  return false;
4644  case UTT_IsSigned:
4645  return T->isSignedIntegerType();
4646  case UTT_IsUnsigned:
4647  return T->isUnsignedIntegerType();
4648 
4649  // Type trait expressions which query classes regarding their construction,
4650  // destruction, and copying. Rather than being based directly on the
4651  // related type predicates in the standard, they are specified by both
4652  // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4653  // specifications.
4654  //
4655  // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4656  // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4657  //
4658  // Note that these builtins do not behave as documented in g++: if a class
4659  // has both a trivial and a non-trivial special member of a particular kind,
4660  // they return false! For now, we emulate this behavior.
4661  // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4662  // does not correctly compute triviality in the presence of multiple special
4663  // members of the same kind. Revisit this once the g++ bug is fixed.
4665  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4666  // If __is_pod (type) is true then the trait is true, else if type is
4667  // a cv class or union type (or array thereof) with a trivial default
4668  // constructor ([class.ctor]) then the trait is true, else it is false.
4669  if (T.isPODType(C))
4670  return true;
4671  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4672  return RD->hasTrivialDefaultConstructor() &&
4673  !RD->hasNonTrivialDefaultConstructor();
4674  return false;
4676  // This trait is implemented by MSVC 2012 and needed to parse the
4677  // standard library headers. Specifically this is used as the logic
4678  // behind std::is_trivially_move_constructible (20.9.4.3).
4679  if (T.isPODType(C))
4680  return true;
4681  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4682  return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4683  return false;
4684  case UTT_HasTrivialCopy:
4685  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4686  // If __is_pod (type) is true or type is a reference type then
4687  // the trait is true, else if type is a cv class or union type
4688  // with a trivial copy constructor ([class.copy]) then the trait
4689  // is true, else it is false.
4690  if (T.isPODType(C) || T->isReferenceType())
4691  return true;
4692  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4693  return RD->hasTrivialCopyConstructor() &&
4694  !RD->hasNonTrivialCopyConstructor();
4695  return false;
4697  // This trait is implemented by MSVC 2012 and needed to parse the
4698  // standard library headers. Specifically it is used as the logic
4699  // behind std::is_trivially_move_assignable (20.9.4.3)
4700  if (T.isPODType(C))
4701  return true;
4702  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4703  return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4704  return false;
4705  case UTT_HasTrivialAssign:
4706  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4707  // If type is const qualified or is a reference type then the
4708  // trait is false. Otherwise if __is_pod (type) is true then the
4709  // trait is true, else if type is a cv class or union type with
4710  // a trivial copy assignment ([class.copy]) then the trait is
4711  // true, else it is false.
4712  // Note: the const and reference restrictions are interesting,
4713  // given that const and reference members don't prevent a class
4714  // from having a trivial copy assignment operator (but do cause
4715  // errors if the copy assignment operator is actually used, q.v.
4716  // [class.copy]p12).
4717 
4718  if (T.isConstQualified())
4719  return false;
4720  if (T.isPODType(C))
4721  return true;
4722  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4723  return RD->hasTrivialCopyAssignment() &&
4724  !RD->hasNonTrivialCopyAssignment();
4725  return false;
4726  case UTT_IsDestructible:
4729  // C++14 [meta.unary.prop]:
4730  // For reference types, is_destructible<T>::value is true.
4731  if (T->isReferenceType())
4732  return true;
4733 
4734  // Objective-C++ ARC: autorelease types don't require destruction.
4735  if (T->isObjCLifetimeType() &&
4737  return true;
4738 
4739  // C++14 [meta.unary.prop]:
4740  // For incomplete types and function types, is_destructible<T>::value is
4741  // false.
4742  if (T->isIncompleteType() || T->isFunctionType())
4743  return false;
4744 
4745  // A type that requires destruction (via a non-trivial destructor or ARC
4746  // lifetime semantics) is not trivially-destructible.
4748  return false;
4749 
4750  // C++14 [meta.unary.prop]:
4751  // For object types and given U equal to remove_all_extents_t<T>, if the
4752  // expression std::declval<U&>().~U() is well-formed when treated as an
4753  // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4754  if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4755  CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4756  if (!Destructor)
4757  return false;
4758  // C++14 [dcl.fct.def.delete]p2:
4759  // A program that refers to a deleted function implicitly or
4760  // explicitly, other than to declare it, is ill-formed.
4761  if (Destructor->isDeleted())
4762  return false;
4763  if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4764  return false;
4765  if (UTT == UTT_IsNothrowDestructible) {
4766  const FunctionProtoType *CPT =
4767  Destructor->getType()->getAs<FunctionProtoType>();
4768  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4769  if (!CPT || !CPT->isNothrow())
4770  return false;
4771  }
4772  }
4773  return true;
4774 
4776  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4777  // If __is_pod (type) is true or type is a reference type
4778  // then the trait is true, else if type is a cv class or union
4779  // type (or array thereof) with a trivial destructor
4780  // ([class.dtor]) then the trait is true, else it is
4781  // false.
4782  if (T.isPODType(C) || T->isReferenceType())
4783  return true;
4784 
4785  // Objective-C++ ARC: autorelease types don't require destruction.
4786  if (T->isObjCLifetimeType() &&
4788  return true;
4789 
4790  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4791  return RD->hasTrivialDestructor();
4792  return false;
4793  // TODO: Propagate nothrowness for implicitly declared special members.
4794  case UTT_HasNothrowAssign:
4795  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4796  // If type is const qualified or is a reference type then the
4797  // trait is false. Otherwise if __has_trivial_assign (type)
4798  // is true then the trait is true, else if type is a cv class
4799  // or union type with copy assignment operators that are known
4800  // not to throw an exception then the trait is true, else it is
4801  // false.
4802  if (C.getBaseElementType(T).isConstQualified())
4803  return false;
4804  if (T->isReferenceType())
4805  return false;
4806  if (T.isPODType(C) || T->isObjCLifetimeType())
4807  return true;
4808 
4809  if (const RecordType *RT = T->getAs<RecordType>())
4810  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4814  return false;
4816  // This trait is implemented by MSVC 2012 and needed to parse the
4817  // standard library headers. Specifically this is used as the logic
4818  // behind std::is_nothrow_move_assignable (20.9.4.3).
4819  if (T.isPODType(C))
4820  return true;
4821 
4822  if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4823  return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4827  return false;
4828  case UTT_HasNothrowCopy:
4829  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4830  // If __has_trivial_copy (type) is true then the trait is true, else
4831  // if type is a cv class or union type with copy constructors that are
4832  // known not to throw an exception then the trait is true, else it is
4833  // false.
4834  if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4835  return true;
4836  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4837  if (RD->hasTrivialCopyConstructor() &&
4838  !RD->hasNonTrivialCopyConstructor())
4839  return true;
4840 
4841  bool FoundConstructor = false;
4842  unsigned FoundTQs;
4843  for (const auto *ND : Self.LookupConstructors(RD)) {
4844  // A template constructor is never a copy constructor.
4845  // FIXME: However, it may actually be selected at the actual overload
4846  // resolution point.
4847  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4848  continue;
4849  // UsingDecl itself is not a constructor
4850  if (isa<UsingDecl>(ND))
4851  continue;
4852  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4853  if (Constructor->isCopyConstructor(FoundTQs)) {
4854  FoundConstructor = true;
4855  const FunctionProtoType *CPT
4856  = Constructor->getType()->getAs<FunctionProtoType>();
4857  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4858  if (!CPT)
4859  return false;
4860  // TODO: check whether evaluating default arguments can throw.
4861  // For now, we'll be conservative and assume that they can throw.
4862  if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4863  return false;
4864  }
4865  }
4866 
4867  return FoundConstructor;
4868  }
4869  return false;
4871  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4872  // If __has_trivial_constructor (type) is true then the trait is
4873  // true, else if type is a cv class or union type (or array
4874  // thereof) with a default constructor that is known not to
4875  // throw an exception then the trait is true, else it is false.
4876  if (T.isPODType(C) || T->isObjCLifetimeType())
4877  return true;
4878  if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4879  if (RD->hasTrivialDefaultConstructor() &&
4880  !RD->hasNonTrivialDefaultConstructor())
4881  return true;
4882 
4883  bool FoundConstructor = false;
4884  for (const auto *ND : Self.LookupConstructors(RD)) {
4885  // FIXME: In C++0x, a constructor template can be a default constructor.
4886  if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4887  continue;
4888  // UsingDecl itself is not a constructor
4889  if (isa<UsingDecl>(ND))
4890  continue;
4891  auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4892  if (Constructor->isDefaultConstructor()) {
4893  FoundConstructor = true;
4894  const FunctionProtoType *CPT
4895  = Constructor->getType()->getAs<FunctionProtoType>();
4896  CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4897  if (!CPT)
4898  return false;
4899  // FIXME: check whether evaluating default arguments can throw.
4900  // For now, we'll be conservative and assume that they can throw.
4901  if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4902  return false;
4903  }
4904  }
4905  return FoundConstructor;
4906  }
4907  return false;
4909  // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4910  // If type is a class type with a virtual destructor ([class.dtor])
4911  // then the trait is true, else it is false.
4912  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4913  if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4914  return Destructor->isVirtual();
4915  return false;
4916 
4917  // These type trait expressions are modeled on the specifications for the
4918  // Embarcadero C++0x type trait functions:
4919  // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4920  case UTT_IsCompleteType:
4921  // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4922  // Returns True if and only if T is a complete type at the point of the
4923  // function call.
4924  return !T->isIncompleteType();
4926  return C.hasUniqueObjectRepresentations(T);
4927  }
4928 }
4929 
4930 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4931  QualType RhsT, SourceLocation KeyLoc);
4932 
4935  SourceLocation RParenLoc) {
4936  if (Kind <= UTT_Last)
4937  return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4938 
4939  // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4940  // traits to avoid duplication.
4941  if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4942  return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4943  Args[1]->getType(), RParenLoc);
4944 
4945  switch (Kind) {
4950  // C++11 [meta.unary.prop]:
4951  // is_trivially_constructible is defined as:
4952  //
4953  // is_constructible<T, Args...>::value is true and the variable
4954  // definition for is_constructible, as defined below, is known to call
4955  // no operation that is not trivial.
4956  //
4957  // The predicate condition for a template specialization
4958  // is_constructible<T, Args...> shall be satisfied if and only if the
4959  // following variable definition would be well-formed for some invented
4960  // variable t:
4961  //
4962  // T t(create<Args>()...);
4963  assert(!Args.empty());
4964 
4965  // Precondition: T and all types in the parameter pack Args shall be
4966  // complete types, (possibly cv-qualified) void, or arrays of
4967  // unknown bound.
4968  for (const auto *TSI : Args) {
4969  QualType ArgTy = TSI->getType();
4970  if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4971  continue;
4972 
4973  if (S.RequireCompleteType(KWLoc, ArgTy,
4974  diag::err_incomplete_type_used_in_type_trait_expr))
4975  return false;
4976  }
4977 
4978  // Make sure the first argument is not incomplete nor a function type.
4979  QualType T = Args[0]->getType();
4980  if (T->isIncompleteType() || T->isFunctionType())
4981  return false;
4982 
4983  // Make sure the first argument is not an abstract type.
4984  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4985  if (RD && RD->isAbstract())
4986  return false;
4987 
4988  SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4989  SmallVector<Expr *, 2> ArgExprs;
4990  ArgExprs.reserve(Args.size() - 1);
4991  for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4992  QualType ArgTy = Args[I]->getType();
4993  if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4994  ArgTy = S.Context.getRValueReferenceType(ArgTy);
4995  OpaqueArgExprs.push_back(
4996  OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4997  ArgTy.getNonLValueExprType(S.Context),
4998  Expr::getValueKindForType(ArgTy)));
4999  }
5000  for (Expr &E : OpaqueArgExprs)
5001  ArgExprs.push_back(&E);
5002 
5003  // Perform the initialization in an unevaluated context within a SFINAE
5004  // trap at translation unit scope.
5007  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5011  RParenLoc));
5012  InitializationSequence Init(S, To, InitKind, ArgExprs);
5013  if (Init.Failed())
5014  return false;
5015 
5016  ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5017  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5018  return false;
5019 
5020  if (Kind == clang::TT_IsConstructible)
5021  return true;
5022 
5024  if (!T->isReferenceType())
5025  return false;
5026 
5027  return !Init.isDirectReferenceBinding();
5028  }
5029 
5031  return S.canThrow(Result.get()) == CT_Cannot;
5032 
5033  if (Kind == clang::TT_IsTriviallyConstructible) {
5034  // Under Objective-C ARC and Weak, if the destination has non-trivial
5035  // Objective-C lifetime, this is a non-trivial construction.
5037  return false;
5038 
5039  // The initialization succeeded; now make sure there are no non-trivial
5040  // calls.
5041  return !Result.get()->hasNonTrivialCall(S.Context);
5042  }
5043 
5044  llvm_unreachable("unhandled type trait");
5045  return false;
5046  }
5047  default: llvm_unreachable("not a TT");
5048  }
5049 
5050  return false;
5051 }
5052 
5055  SourceLocation RParenLoc) {
5056  QualType ResultType = Context.getLogicalOperationType();
5057 
5059  *this, Kind, KWLoc, Args[0]->getType()))
5060  return ExprError();
5061 
5062  bool Dependent = false;
5063  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5064  if (Args[I]->getType()->isDependentType()) {
5065  Dependent = true;
5066  break;
5067  }
5068  }
5069 
5070  bool Result = false;
5071  if (!Dependent)
5072  Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5073 
5074  return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5075  RParenLoc, Result);
5076 }
5077 
5079  ArrayRef<ParsedType> Args,
5080  SourceLocation RParenLoc) {
5081  SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5082  ConvertedArgs.reserve(Args.size());
5083 
5084  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5085  TypeSourceInfo *TInfo;
5086  QualType T = GetTypeFromParser(Args[I], &TInfo);
5087  if (!TInfo)
5088  TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5089 
5090  ConvertedArgs.push_back(TInfo);
5091  }
5092 
5093  return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5094 }
5095 
5096 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5097  QualType RhsT, SourceLocation KeyLoc) {
5098  assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5099  "Cannot evaluate traits of dependent types");
5100 
5101  switch(BTT) {
5102  case BTT_IsBaseOf: {
5103  // C++0x [meta.rel]p2
5104  // Base is a base class of Derived without regard to cv-qualifiers or
5105  // Base and Derived are not unions and name the same class type without
5106  // regard to cv-qualifiers.
5107 
5108  const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5109  const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5110  if (!rhsRecord || !lhsRecord) {
5111  const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5112  const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5113  if (!LHSObjTy || !RHSObjTy)
5114  return false;
5115 
5116  ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5117  ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5118  if (!BaseInterface || !DerivedInterface)
5119  return false;
5120 
5121  if (Self.RequireCompleteType(
5122  KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5123  return false;
5124 
5125  return BaseInterface->isSuperClassOf(DerivedInterface);
5126  }
5127 
5128  assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5129  == (lhsRecord == rhsRecord));
5130 
5131  // Unions are never base classes, and never have base classes.
5132  // It doesn't matter if they are complete or not. See PR#41843
5133  if (lhsRecord && lhsRecord->getDecl()->isUnion())
5134  return false;
5135  if (rhsRecord && rhsRecord->getDecl()->isUnion())
5136  return false;
5137 
5138  if (lhsRecord == rhsRecord)
5139  return true;
5140 
5141  // C++0x [meta.rel]p2:
5142  // If Base and Derived are class types and are different types
5143  // (ignoring possible cv-qualifiers) then Derived shall be a
5144  // complete type.
5145  if (Self.RequireCompleteType(KeyLoc, RhsT,
5146  diag::err_incomplete_type_used_in_type_trait_expr))
5147  return false;
5148 
5149  return cast<CXXRecordDecl>(rhsRecord->getDecl())
5150  ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5151  }
5152  case BTT_IsSame:
5153  return Self.Context.hasSameType(LhsT, RhsT);
5154  case BTT_TypeCompatible: {
5155  // GCC ignores cv-qualifiers on arrays for this builtin.
5156  Qualifiers LhsQuals, RhsQuals;
5157  QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5158  QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5159  return Self.Context.typesAreCompatible(Lhs, Rhs);
5160  }
5161  case BTT_IsConvertible:
5162  case BTT_IsConvertibleTo: {
5163  // C++0x [meta.rel]p4:
5164  // Given the following function prototype:
5165  //
5166  // template <class T>
5167  // typename add_rvalue_reference<T>::type create();
5168  //
5169  // the predicate condition for a template specialization
5170  // is_convertible<From, To> shall be satisfied if and only if
5171  // the return expression in the following code would be
5172  // well-formed, including any implicit conversions to the return
5173  // type of the function:
5174  //
5175  // To test() {
5176  // return create<From>();
5177  // }
5178  //
5179  // Access checking is performed as if in a context unrelated to To and
5180  // From. Only the validity of the immediate context of the expression
5181  // of the return-statement (including conversions to the return type)
5182  // is considered.
5183  //
5184  // We model the initialization as a copy-initialization of a temporary
5185  // of the appropriate type, which for this expression is identical to the
5186  // return statement (since NRVO doesn't apply).
5187 
5188  // Functions aren't allowed to return function or array types.
5189  if (RhsT->isFunctionType() || RhsT->isArrayType())
5190  return false;
5191 
5192  // A return statement in a void function must have void type.
5193  if (RhsT->isVoidType())
5194  return LhsT->isVoidType();
5195 
5196  // A function definition requires a complete, non-abstract return type.
5197  if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5198  return false;
5199 
5200  // Compute the result of add_rvalue_reference.
5201  if (LhsT->isObjectType() || LhsT->isFunctionType())
5202  LhsT = Self.Context.getRValueReferenceType(LhsT);
5203 
5204  // Build a fake source and destination for initialization.
5206  OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5208  Expr *FromPtr = &From;
5210  SourceLocation()));
5211 
5212  // Perform the initialization in an unevaluated context within a SFINAE
5213  // trap at translation unit scope.
5216  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5217  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5218  InitializationSequence Init(Self, To, Kind, FromPtr);
5219  if (Init.Failed())
5220  return false;
5221 
5222  ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5223  return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5224  }
5225 
5226  case BTT_IsAssignable:
5229  // C++11 [meta.unary.prop]p3:
5230  // is_trivially_assignable is defined as:
5231  // is_assignable<T, U>::value is true and the assignment, as defined by
5232  // is_assignable, is known to call no operation that is not trivial
5233  //
5234  // is_assignable is defined as:
5235  // The expression declval<T>() = declval<U>() is well-formed when
5236  // treated as an unevaluated operand (Clause 5).
5237  //
5238  // For both, T and U shall be complete types, (possibly cv-qualified)
5239  // void, or arrays of unknown bound.
5240  if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5241  Self.RequireCompleteType(KeyLoc, LhsT,
5242  diag::err_incomplete_type_used_in_type_trait_expr))
5243  return false;
5244  if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5245  Self.RequireCompleteType(KeyLoc, RhsT,
5246  diag::err_incomplete_type_used_in_type_trait_expr))
5247  return false;
5248 
5249  // cv void is never assignable.
5250  if (LhsT->isVoidType() || RhsT->isVoidType())
5251  return false;
5252 
5253  // Build expressions that emulate the effect of declval<T>() and
5254  // declval<U>().
5255  if (LhsT->isObjectType() || LhsT->isFunctionType())
5256  LhsT = Self.Context.getRValueReferenceType(LhsT);
5257  if (RhsT->isObjectType() || RhsT->isFunctionType())
5258  RhsT = Self.Context.getRValueReferenceType(RhsT);
5259  OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5261  OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5263 
5264  // Attempt the assignment in an unevaluated context within a SFINAE
5265  // trap at translation unit scope.
5268  Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5269  Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5270  ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5271  &Rhs);
5272  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5273  return false;
5274 
5275  if (BTT == BTT_IsAssignable)
5276  return true;
5277 
5278  if (BTT == BTT_IsNothrowAssignable)
5279  return Self.canThrow(Result.get()) == CT_Cannot;
5280 
5281  if (BTT == BTT_IsTriviallyAssignable) {
5282  // Under Objective-C ARC and Weak, if the destination has non-trivial
5283  // Objective-C lifetime, this is a non-trivial assignment.
5285  return false;
5286 
5287  return !Result.get()->hasNonTrivialCall(Self.Context);
5288  }
5289 
5290  llvm_unreachable("unhandled type trait");
5291  return false;
5292  }
5293  default: llvm_unreachable("not a BTT");
5294  }
5295  llvm_unreachable("Unknown type trait or not implemented");
5296 }
5297 
5299  SourceLocation KWLoc,
5300  ParsedType Ty,
5301  Expr* DimExpr,
5302  SourceLocation RParen) {
5303  TypeSourceInfo *TSInfo;
5304  QualType T = GetTypeFromParser(Ty, &TSInfo);
5305  if (!TSInfo)
5306  TSInfo = Context.getTrivialTypeSourceInfo(T);
5307 
5308  return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5309 }
5310 
5311 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5312  QualType T, Expr *DimExpr,
5313  SourceLocation KeyLoc) {
5314  assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5315 
5316  switch(ATT) {
5317  case ATT_ArrayRank:
5318  if (T->isArrayType()) {
5319  unsigned Dim = 0;
5320  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5321  ++Dim;
5322  T = AT->getElementType();
5323  }
5324  return Dim;
5325  }
5326  return 0;
5327 
5328  case ATT_ArrayExtent: {
5329  llvm::APSInt Value;
5330  uint64_t Dim;
5331  if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5332  diag::err_dimension_expr_not_constant_integer,
5333  false).isInvalid())
5334  return 0;
5335  if (Value.isSigned() && Value.isNegative()) {
5336  Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5337  << DimExpr->getSourceRange();
5338  return 0;
5339  }
5340  Dim = Value.getLimitedValue();
5341 
5342  if (T->isArrayType()) {
5343  unsigned D = 0;
5344  bool Matched = false;
5345  while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5346  if (Dim == D) {
5347  Matched = true;
5348  break;
5349  }
5350  ++D;
5351  T = AT->getElementType();
5352  }
5353 
5354  if (Matched && T->isArrayType()) {
5355  if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5356  return CAT->getSize().getLimitedValue();
5357  }
5358  }
5359  return 0;
5360  }
5361  }
5362  llvm_unreachable("Unknown type trait or not implemented");
5363 }
5364 
5366  SourceLocation KWLoc,
5367  TypeSourceInfo *TSInfo,
5368  Expr* DimExpr,
5369  SourceLocation RParen) {
5370  QualType T = TSInfo->getType();
5371 
5372  // FIXME: This should likely be tracked as an APInt to remove any host
5373  // assumptions about the width of size_t on the target.
5374  uint64_t Value = 0;
5375  if (!T->isDependentType())
5376  Value =