1//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//
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// This file implements the C++ related Decl classes.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTUnresolvedSet.h"
18#include "clang/AST/Attr.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DeclarationName.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/LambdaCapture.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/ODRHash.h"
28#include "clang/AST/Type.h"
29#include "clang/AST/TypeLoc.h"
30#include "clang/AST/UnresolvedSet.h"
31#include "clang/Basic/Diagnostic.h"
32#include "clang/Basic/IdentifierTable.h"
33#include "clang/Basic/LLVM.h"
34#include "clang/Basic/LangOptions.h"
35#include "clang/Basic/OperatorKinds.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/None.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/iterator_range.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/Format.h"
46#include "llvm/Support/raw_ostream.h"
47#include <algorithm>
48#include <cassert>
49#include <cstddef>
50#include <cstdint>
51
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Decl Allocation/Deallocation Method Implementations
56//===----------------------------------------------------------------------===//
57
58void AccessSpecDecl::anchor() {}
59
60AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
61  return new (C, ID) AccessSpecDecl(EmptyShell());
62}
63
64void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {
65  ExternalASTSource *Source = C.getExternalSource();
66  assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");
67  assert(Source && "getFromExternalSource with no external source");
68
69  for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)
70    I.setDecl(cast<NamedDecl>(Source->GetExternalDecl(
71        reinterpret_cast<uintptr_t>(I.getDecl()) >> 2)));
72  Impl.Decls.setLazy(false);
73}
74
75CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)
76    : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),
77      Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),
78      Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),
79      HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),
80      HasPrivateFields(false), HasProtectedFields(false),
81      HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),
82      HasOnlyCMembers(true), HasInClassInitializer(false),
83      HasUninitializedReferenceMember(false), HasUninitializedFields(false),
84      HasInheritedConstructor(false), HasInheritedAssignment(false),
85      NeedOverloadResolutionForCopyConstructor(false),
86      NeedOverloadResolutionForMoveConstructor(false),
87      NeedOverloadResolutionForCopyAssignment(false),
88      NeedOverloadResolutionForMoveAssignment(false),
89      NeedOverloadResolutionForDestructor(false),
90      DefaultedCopyConstructorIsDeleted(false),
91      DefaultedMoveConstructorIsDeleted(false),
92      DefaultedCopyAssignmentIsDeleted(false),
93      DefaultedMoveAssignmentIsDeleted(false),
94      DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),
95      HasTrivialSpecialMembersForCall(SMF_All),
96      DeclaredNonTrivialSpecialMembers(0),
97      DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),
98      HasConstexprNonCopyMoveConstructor(false),
99      HasDefaultedDefaultConstructor(false),
100      DefaultedDefaultConstructorIsConstexpr(true),
101      HasConstexprDefaultConstructor(false),
102      DefaultedDestructorIsConstexpr(true),
103      HasNonLiteralTypeFieldsOrBases(false),
104      UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),
105      ImplicitCopyConstructorCanHaveConstParamForVBase(true),
106      ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),
107      ImplicitCopyAssignmentHasConstParam(true),
108      HasDeclaredCopyConstructorWithConstParam(false),
109      HasDeclaredCopyAssignmentWithConstParam(false), IsLambda(false),
110      IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),
111      HasODRHash(false), Definition(D) {}
112
113CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {
114  return Bases.get(Definition->getASTContext().getExternalSource());
115}
116
117CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {
118  return VBases.get(Definition->getASTContext().getExternalSource());
119}
120
121CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,
122                             DeclContext *DC, SourceLocation StartLoc,
123                             SourceLocation IdLoc, IdentifierInfo *Id,
124                             CXXRecordDecl *PrevDecl)
125    : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),
126      DefinitionData(PrevDecl ? PrevDecl->DefinitionData
127                              : nullptr) {}
128
129CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,
130                                     DeclContext *DC, SourceLocation StartLoc,
131                                     SourceLocation IdLoc, IdentifierInfo *Id,
132                                     CXXRecordDecl *PrevDecl,
133                                     bool DelayTypeCreation) {
134  auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,
135                                      PrevDecl);
136  R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
137
138  // FIXME: DelayTypeCreation seems like such a hack
139  if (!DelayTypeCreation)
140    C.getTypeDeclType(R, PrevDecl);
141  return R;
142}
143
144CXXRecordDecl *
145CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,
146                            TypeSourceInfo *Info, SourceLocation Loc,
147                            bool Dependent, bool IsGeneric,
148                            LambdaCaptureDefault CaptureDefault) {
149  auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TTK_Class, C, DC, Loc, Loc,
150                                      nullptr, nullptr);
151  R->setBeingDefined(true);
152  R->DefinitionData =
153      new (C) struct LambdaDefinitionData(R, Info, Dependent, IsGeneric,
154                                          CaptureDefault);
155  R->setMayHaveOutOfDateDef(false);
156  R->setImplicit(true);
157  C.getTypeDeclType(R, /*PrevDecl=*/nullptr);
158  return R;
159}
160
161CXXRecordDecl *
162CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
163  auto *R = new (C, ID) CXXRecordDecl(
164      CXXRecord, TTK_Struct, C, nullptr, SourceLocation(), SourceLocation(),
165      nullptr, nullptr);
166  R->setMayHaveOutOfDateDef(false);
167  return R;
168}
169
170/// Determine whether a class has a repeated base class. This is intended for
171/// use when determining if a class is standard-layout, so makes no attempt to
172/// handle virtual bases.
173static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {
174  llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;
175  SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};
176  while (!WorkList.empty()) {
177    const CXXRecordDecl *RD = WorkList.pop_back_val();
178    for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {
179      if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {
180        if (!SeenBaseTypes.insert(B).second)
181          return true;
182        WorkList.push_back(B);
183      }
184    }
185  }
186  return false;
187}
188
189void
190CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
191                        unsigned NumBases) {
192  ASTContext &C = getASTContext();
193
194  if (!data().Bases.isOffset() && data().NumBases > 0)
195    C.Deallocate(data().getBases());
196
197  if (NumBases) {
198    if (!C.getLangOpts().CPlusPlus17) {
199      // C++ [dcl.init.aggr]p1:
200      //   An aggregate is [...] a class with [...] no base classes [...].
201      data().Aggregate = false;
202    }
203
204    // C++ [class]p4:
205    //   A POD-struct is an aggregate class...
206    data().PlainOldData = false;
207  }
208
209  // The set of seen virtual base types.
210  llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;
211
212  // The virtual bases of this class.
213  SmallVector<const CXXBaseSpecifier *, 8> VBases;
214
215  data().Bases = new(C) CXXBaseSpecifier [NumBases];
216  data().NumBases = NumBases;
217  for (unsigned i = 0; i < NumBases; ++i) {
218    data().getBases()[i] = *Bases[i];
219    // Keep track of inherited vbases for this base class.
220    const CXXBaseSpecifier *Base = Bases[i];
221    QualType BaseType = Base->getType();
222    // Skip dependent types; we can't do any checking on them now.
223    if (BaseType->isDependentType())
224      continue;
225    auto *BaseClassDecl =
226        cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());
227
228    // C++2a [class]p7:
229    //   A standard-layout class is a class that:
230    //    [...]
231    //    -- has all non-static data members and bit-fields in the class and
232    //       its base classes first declared in the same class
233    if (BaseClassDecl->data().HasBasesWithFields ||
234        !BaseClassDecl->field_empty()) {
235      if (data().HasBasesWithFields)
236        // Two bases have members or bit-fields: not standard-layout.
237        data().IsStandardLayout = false;
238      data().HasBasesWithFields = true;
239    }
240
241    // C++11 [class]p7:
242    //   A standard-layout class is a class that:
243    //     -- [...] has [...] at most one base class with non-static data
244    //        members
245    if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||
246        BaseClassDecl->hasDirectFields()) {
247      if (data().HasBasesWithNonStaticDataMembers)
248        data().IsCXX11StandardLayout = false;
249      data().HasBasesWithNonStaticDataMembers = true;
250    }
251
252    if (!BaseClassDecl->isEmpty()) {
253      // C++14 [meta.unary.prop]p4:
254      //   T is a class type [...] with [...] no base class B for which
255      //   is_empty<B>::value is false.
256      data().Empty = false;
257    }
258
259    // C++1z [dcl.init.agg]p1:
260    //   An aggregate is a class with [...] no private or protected base classes
261    if (Base->getAccessSpecifier() != AS_public)
262      data().Aggregate = false;
263
264    // C++ [class.virtual]p1:
265    //   A class that declares or inherits a virtual function is called a
266    //   polymorphic class.
267    if (BaseClassDecl->isPolymorphic()) {
268      data().Polymorphic = true;
269
270      //   An aggregate is a class with [...] no virtual functions.
271      data().Aggregate = false;
272    }
273
274    // C++0x [class]p7:
275    //   A standard-layout class is a class that: [...]
276    //    -- has no non-standard-layout base classes
277    if (!BaseClassDecl->isStandardLayout())
278      data().IsStandardLayout = false;
279    if (!BaseClassDecl->isCXX11StandardLayout())
280      data().IsCXX11StandardLayout = false;
281
282    // Record if this base is the first non-literal field or base.
283    if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
284      data().HasNonLiteralTypeFieldsOrBases = true;
285
286    // Now go through all virtual bases of this base and add them.
287    for (const auto &VBase : BaseClassDecl->vbases()) {
288      // Add this base if it's not already in the list.
289      if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {
290        VBases.push_back(&VBase);
291
292        // C++11 [class.copy]p8:
293        //   The implicitly-declared copy constructor for a class X will have
294        //   the form 'X::X(const X&)' if each [...] virtual base class B of X
295        //   has a copy constructor whose first parameter is of type
296        //   'const B&' or 'const volatile B&' [...]
297        if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())
298          if (!VBaseDecl->hasCopyConstructorWithConstParam())
299            data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
300
301        // C++1z [dcl.init.agg]p1:
302        //   An aggregate is a class with [...] no virtual base classes
303        data().Aggregate = false;
304      }
305    }
306
307    if (Base->isVirtual()) {
308      // Add this base if it's not already in the list.
309      if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)
310        VBases.push_back(Base);
311
312      // C++14 [meta.unary.prop] is_empty:
313      //   T is a class type, but not a union type, with ... no virtual base
314      //   classes
315      data().Empty = false;
316
317      // C++1z [dcl.init.agg]p1:
318      //   An aggregate is a class with [...] no virtual base classes
319      data().Aggregate = false;
320
321      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
322      //   A [default constructor, copy/move constructor, or copy/move assignment
323      //   operator for a class X] is trivial [...] if:
324      //    -- class X has [...] no virtual base classes
325      data().HasTrivialSpecialMembers &= SMF_Destructor;
326      data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
327
328      // C++0x [class]p7:
329      //   A standard-layout class is a class that: [...]
330      //    -- has [...] no virtual base classes
331      data().IsStandardLayout = false;
332      data().IsCXX11StandardLayout = false;
333
334      // C++20 [dcl.constexpr]p3:
335      //   In the definition of a constexpr function [...]
336      //    -- if the function is a constructor or destructor,
337      //       its class shall not have any virtual base classes
338      data().DefaultedDefaultConstructorIsConstexpr = false;
339      data().DefaultedDestructorIsConstexpr = false;
340
341      // C++1z [class.copy]p8:
342      //   The implicitly-declared copy constructor for a class X will have
343      //   the form 'X::X(const X&)' if each potentially constructed subobject
344      //   has a copy constructor whose first parameter is of type
345      //   'const B&' or 'const volatile B&' [...]
346      if (!BaseClassDecl->hasCopyConstructorWithConstParam())
347        data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;
348    } else {
349      // C++ [class.ctor]p5:
350      //   A default constructor is trivial [...] if:
351      //    -- all the direct base classes of its class have trivial default
352      //       constructors.
353      if (!BaseClassDecl->hasTrivialDefaultConstructor())
354        data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
355
356      // C++0x [class.copy]p13:
357      //   A copy/move constructor for class X is trivial if [...]
358      //    [...]
359      //    -- the constructor selected to copy/move each direct base class
360      //       subobject is trivial, and
361      if (!BaseClassDecl->hasTrivialCopyConstructor())
362        data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
363
364      if (!BaseClassDecl->hasTrivialCopyConstructorForCall())
365        data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
366
367      // If the base class doesn't have a simple move constructor, we'll eagerly
368      // declare it and perform overload resolution to determine which function
369      // it actually calls. If it does have a simple move constructor, this
370      // check is correct.
371      if (!BaseClassDecl->hasTrivialMoveConstructor())
372        data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
373
374      if (!BaseClassDecl->hasTrivialMoveConstructorForCall())
375        data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
376
377      // C++0x [class.copy]p27:
378      //   A copy/move assignment operator for class X is trivial if [...]
379      //    [...]
380      //    -- the assignment operator selected to copy/move each direct base
381      //       class subobject is trivial, and
382      if (!BaseClassDecl->hasTrivialCopyAssignment())
383        data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
384      // If the base class doesn't have a simple move assignment, we'll eagerly
385      // declare it and perform overload resolution to determine which function
386      // it actually calls. If it does have a simple move assignment, this
387      // check is correct.
388      if (!BaseClassDecl->hasTrivialMoveAssignment())
389        data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
390
391      // C++11 [class.ctor]p6:
392      //   If that user-written default constructor would satisfy the
393      //   requirements of a constexpr constructor, the implicitly-defined
394      //   default constructor is constexpr.
395      if (!BaseClassDecl->hasConstexprDefaultConstructor())
396        data().DefaultedDefaultConstructorIsConstexpr = false;
397
398      // C++1z [class.copy]p8:
399      //   The implicitly-declared copy constructor for a class X will have
400      //   the form 'X::X(const X&)' if each potentially constructed subobject
401      //   has a copy constructor whose first parameter is of type
402      //   'const B&' or 'const volatile B&' [...]
403      if (!BaseClassDecl->hasCopyConstructorWithConstParam())
404        data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
405    }
406
407    // C++ [class.ctor]p3:
408    //   A destructor is trivial if all the direct base classes of its class
409    //   have trivial destructors.
410    if (!BaseClassDecl->hasTrivialDestructor())
411      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
412
413    if (!BaseClassDecl->hasTrivialDestructorForCall())
414      data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
415
416    if (!BaseClassDecl->hasIrrelevantDestructor())
417      data().HasIrrelevantDestructor = false;
418
419    // C++11 [class.copy]p18:
420    //   The implicitly-declared copy assignment operator for a class X will
421    //   have the form 'X& X::operator=(const X&)' if each direct base class B
422    //   of X has a copy assignment operator whose parameter is of type 'const
423    //   B&', 'const volatile B&', or 'B' [...]
424    if (!BaseClassDecl->hasCopyAssignmentWithConstParam())
425      data().ImplicitCopyAssignmentHasConstParam = false;
426
427    // A class has an Objective-C object member if... or any of its bases
428    // has an Objective-C object member.
429    if (BaseClassDecl->hasObjectMember())
430      setHasObjectMember(true);
431
432    if (BaseClassDecl->hasVolatileMember())
433      setHasVolatileMember(true);
434
435    if (BaseClassDecl->getArgPassingRestrictions() ==
436        RecordDecl::APK_CanNeverPassInRegs)
437      setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
438
439    // Keep track of the presence of mutable fields.
440    if (BaseClassDecl->hasMutableFields())
441      data().HasMutableFields = true;
442
443    if (BaseClassDecl->hasUninitializedReferenceMember())
444      data().HasUninitializedReferenceMember = true;
445
446    if (!BaseClassDecl->allowConstDefaultInit())
447      data().HasUninitializedFields = true;
448
449    addedClassSubobject(BaseClassDecl);
450  }
451
452  // C++2a [class]p7:
453  //   A class S is a standard-layout class if it:
454  //     -- has at most one base class subobject of any given type
455  //
456  // Note that we only need to check this for classes with more than one base
457  // class. If there's only one base class, and it's standard layout, then
458  // we know there are no repeated base classes.
459  if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))
460    data().IsStandardLayout = false;
461
462  if (VBases.empty()) {
463    data().IsParsingBaseSpecifiers = false;
464    return;
465  }
466
467  // Create base specifier for any direct or indirect virtual bases.
468  data().VBases = new (C) CXXBaseSpecifier[VBases.size()];
469  data().NumVBases = VBases.size();
470  for (int I = 0, E = VBases.size(); I != E; ++I) {
471    QualType Type = VBases[I]->getType();
472    if (!Type->isDependentType())
473      addedClassSubobject(Type->getAsCXXRecordDecl());
474    data().getVBases()[I] = *VBases[I];
475  }
476
477  data().IsParsingBaseSpecifiers = false;
478}
479
480unsigned CXXRecordDecl::getODRHash() const {
481  assert(hasDefinition() && "ODRHash only for records with definitions");
482
483  // Previously calculated hash is stored in DefinitionData.
484  if (DefinitionData->HasODRHash)
485    return DefinitionData->ODRHash;
486
487  // Only calculate hash on first call of getODRHash per record.
488  ODRHash Hash;
489  Hash.AddCXXRecordDecl(getDefinition());
490  DefinitionData->HasODRHash = true;
491  DefinitionData->ODRHash = Hash.CalculateHash();
492
493  return DefinitionData->ODRHash;
494}
495
496void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {
497  // C++11 [class.copy]p11:
498  //   A defaulted copy/move constructor for a class X is defined as
499  //   deleted if X has:
500  //    -- a direct or virtual base class B that cannot be copied/moved [...]
501  //    -- a non-static data member of class type M (or array thereof)
502  //       that cannot be copied or moved [...]
503  if (!Subobj->hasSimpleCopyConstructor())
504    data().NeedOverloadResolutionForCopyConstructor = true;
505  if (!Subobj->hasSimpleMoveConstructor())
506    data().NeedOverloadResolutionForMoveConstructor = true;
507
508  // C++11 [class.copy]p23:
509  //   A defaulted copy/move assignment operator for a class X is defined as
510  //   deleted if X has:
511  //    -- a direct or virtual base class B that cannot be copied/moved [...]
512  //    -- a non-static data member of class type M (or array thereof)
513  //        that cannot be copied or moved [...]
514  if (!Subobj->hasSimpleCopyAssignment())
515    data().NeedOverloadResolutionForCopyAssignment = true;
516  if (!Subobj->hasSimpleMoveAssignment())
517    data().NeedOverloadResolutionForMoveAssignment = true;
518
519  // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:
520  //   A defaulted [ctor or dtor] for a class X is defined as
521  //   deleted if X has:
522  //    -- any direct or virtual base class [...] has a type with a destructor
523  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
524  //    -- any non-static data member has a type with a destructor
525  //       that is deleted or inaccessible from the defaulted [ctor or dtor].
526  if (!Subobj->hasSimpleDestructor()) {
527    data().NeedOverloadResolutionForCopyConstructor = true;
528    data().NeedOverloadResolutionForMoveConstructor = true;
529    data().NeedOverloadResolutionForDestructor = true;
530  }
531
532  // C++2a [dcl.constexpr]p4:
533  //   The definition of a constexpr destructor [shall] satisfy the
534  //   following requirement:
535  //   -- for every subobject of class type or (possibly multi-dimensional)
536  //      array thereof, that class type shall have a constexpr destructor
537  if (!Subobj->hasConstexprDestructor())
538    data().DefaultedDestructorIsConstexpr = false;
539}
540
541bool CXXRecordDecl::hasConstexprDestructor() const {
542  auto *Dtor = getDestructor();
543  return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();
544}
545
546bool CXXRecordDecl::hasAnyDependentBases() const {
547  if (!isDependentContext())
548    return false;
549
550  return !forallBases([](const CXXRecordDecl *) { return true; });
551}
552
553bool CXXRecordDecl::isTriviallyCopyable() const {
554  // C++0x [class]p5:
555  //   A trivially copyable class is a class that:
556  //   -- has no non-trivial copy constructors,
557  if (hasNonTrivialCopyConstructor()) return false;
558  //   -- has no non-trivial move constructors,
559  if (hasNonTrivialMoveConstructor()) return false;
560  //   -- has no non-trivial copy assignment operators,
561  if (hasNonTrivialCopyAssignment()) return false;
562  //   -- has no non-trivial move assignment operators, and
563  if (hasNonTrivialMoveAssignment()) return false;
564  //   -- has a trivial destructor.
565  if (!hasTrivialDestructor()) return false;
566
567  return true;
568}
569
570void CXXRecordDecl::markedVirtualFunctionPure() {
571  // C++ [class.abstract]p2:
572  //   A class is abstract if it has at least one pure virtual function.
573  data().Abstract = true;
574}
575
576bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(
577    ASTContext &Ctx, const CXXRecordDecl *XFirst) {
578  if (!getNumBases())
579    return false;
580
581  llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;
582  llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;
583  SmallVector<const CXXRecordDecl*, 8> WorkList;
584
585  // Visit a type that we have determined is an element of M(S).
586  auto Visit = [&](const CXXRecordDecl *RD) -> bool {
587    RD = RD->getCanonicalDecl();
588
589    // C++2a [class]p8:
590    //   A class S is a standard-layout class if it [...] has no element of the
591    //   set M(S) of types as a base class.
592    //
593    // If we find a subobject of an empty type, it might also be a base class,
594    // so we'll need to walk the base classes to check.
595    if (!RD->data().HasBasesWithFields) {
596      // Walk the bases the first time, stopping if we find the type. Build a
597      // set of them so we don't need to walk them again.
598      if (Bases.empty()) {
599        bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {
600          Base = Base->getCanonicalDecl();
601          if (RD == Base)
602            return false;
603          Bases.insert(Base);
604          return true;
605        });
606        if (RDIsBase)
607          return true;
608      } else {
609        if (Bases.count(RD))
610          return true;
611      }
612    }
613
614    if (M.insert(RD).second)
615      WorkList.push_back(RD);
616    return false;
617  };
618
619  if (Visit(XFirst))
620    return true;
621
622  while (!WorkList.empty()) {
623    const CXXRecordDecl *X = WorkList.pop_back_val();
624
625    // FIXME: We don't check the bases of X. That matches the standard, but
626    // that sure looks like a wording bug.
627
628    //   -- If X is a non-union class type with a non-static data member
629    //      [recurse to each field] that is either of zero size or is the
630    //      first non-static data member of X
631    //   -- If X is a union type, [recurse to union members]
632    bool IsFirstField = true;
633    for (auto *FD : X->fields()) {
634      // FIXME: Should we really care about the type of the first non-static
635      // data member of a non-union if there are preceding unnamed bit-fields?
636      if (FD->isUnnamedBitfield())
637        continue;
638
639      if (!IsFirstField && !FD->isZeroSize(Ctx))
640        continue;
641
642      //   -- If X is n array type, [visit the element type]
643      QualType T = Ctx.getBaseElementType(FD->getType());
644      if (auto *RD = T->getAsCXXRecordDecl())
645        if (Visit(RD))
646          return true;
647
648      if (!X->isUnion())
649        IsFirstField = false;
650    }
651  }
652
653  return false;
654}
655
656bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {
657  assert(isLambda() && "not a lambda");
658
659  // C++2a [expr.prim.lambda.capture]p11:
660  //   The closure type associated with a lambda-expression has no default
661  //   constructor if the lambda-expression has a lambda-capture and a
662  //   defaulted default constructor otherwise. It has a deleted copy
663  //   assignment operator if the lambda-expression has a lambda-capture and
664  //   defaulted copy and move assignment operators otherwise.
665  //
666  // C++17 [expr.prim.lambda]p21:
667  //   The closure type associated with a lambda-expression has no default
668  //   constructor and a deleted copy assignment operator.
669  if (getLambdaCaptureDefault() != LCD_None || capture_size() != 0)
670    return false;
671  return getASTContext().getLangOpts().CPlusPlus20;
672}
673
674void CXXRecordDecl::addedMember(Decl *D) {
675  if (!D->isImplicit() &&
676      !isa<FieldDecl>(D) &&
677      !isa<IndirectFieldDecl>(D) &&
678      (!isa<TagDecl>(D) || cast<TagDecl>(D)->getTagKind() == TTK_Class ||
679        cast<TagDecl>(D)->getTagKind() == TTK_Interface))
680    data().HasOnlyCMembers = false;
681
682  // Ignore friends and invalid declarations.
683  if (D->getFriendObjectKind() || D->isInvalidDecl())
684    return;
685
686  auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
687  if (FunTmpl)
688    D = FunTmpl->getTemplatedDecl();
689
690  // FIXME: Pass NamedDecl* to addedMember?
691  Decl *DUnderlying = D;
692  if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {
693    DUnderlying = ND->getUnderlyingDecl();
694    if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))
695      DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();
696  }
697
698  if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
699    if (Method->isVirtual()) {
700      // C++ [dcl.init.aggr]p1:
701      //   An aggregate is an array or a class with [...] no virtual functions.
702      data().Aggregate = false;
703
704      // C++ [class]p4:
705      //   A POD-struct is an aggregate class...
706      data().PlainOldData = false;
707
708      // C++14 [meta.unary.prop]p4:
709      //   T is a class type [...] with [...] no virtual member functions...
710      data().Empty = false;
711
712      // C++ [class.virtual]p1:
713      //   A class that declares or inherits a virtual function is called a
714      //   polymorphic class.
715      data().Polymorphic = true;
716
717      // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
718      //   A [default constructor, copy/move constructor, or copy/move
719      //   assignment operator for a class X] is trivial [...] if:
720      //    -- class X has no virtual functions [...]
721      data().HasTrivialSpecialMembers &= SMF_Destructor;
722      data().HasTrivialSpecialMembersForCall &= SMF_Destructor;
723
724      // C++0x [class]p7:
725      //   A standard-layout class is a class that: [...]
726      //    -- has no virtual functions
727      data().IsStandardLayout = false;
728      data().IsCXX11StandardLayout = false;
729    }
730  }
731
732  // Notify the listener if an implicit member was added after the definition
733  // was completed.
734  if (!isBeingDefined() && D->isImplicit())
735    if (ASTMutationListener *L = getASTMutationListener())
736      L->AddedCXXImplicitMember(data().Definition, D);
737
738  // The kind of special member this declaration is, if any.
739  unsigned SMKind = 0;
740
741  // Handle constructors.
742  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
743    if (Constructor->isInheritingConstructor()) {
744      // Ignore constructor shadow declarations. They are lazily created and
745      // so shouldn't affect any properties of the class.
746    } else {
747      if (!Constructor->isImplicit()) {
748        // Note that we have a user-declared constructor.
749        data().UserDeclaredConstructor = true;
750
751        // C++ [class]p4:
752        //   A POD-struct is an aggregate class [...]
753        // Since the POD bit is meant to be C++03 POD-ness, clear it even if
754        // the type is technically an aggregate in C++0x since it wouldn't be
755        // in 03.
756        data().PlainOldData = false;
757      }
758
759      if (Constructor->isDefaultConstructor()) {
760        SMKind |= SMF_DefaultConstructor;
761
762        if (Constructor->isUserProvided())
763          data().UserProvidedDefaultConstructor = true;
764        if (Constructor->isConstexpr())
765          data().HasConstexprDefaultConstructor = true;
766        if (Constructor->isDefaulted())
767          data().HasDefaultedDefaultConstructor = true;
768      }
769
770      if (!FunTmpl) {
771        unsigned Quals;
772        if (Constructor->isCopyConstructor(Quals)) {
773          SMKind |= SMF_CopyConstructor;
774
775          if (Quals & Qualifiers::Const)
776            data().HasDeclaredCopyConstructorWithConstParam = true;
777        } else if (Constructor->isMoveConstructor())
778          SMKind |= SMF_MoveConstructor;
779      }
780
781      // C++11 [dcl.init.aggr]p1: DR1518
782      //   An aggregate is an array or a class with no user-provided [or]
783      //   explicit [...] constructors
784      // C++20 [dcl.init.aggr]p1:
785      //   An aggregate is an array or a class with no user-declared [...]
786      //   constructors
787      if (getASTContext().getLangOpts().CPlusPlus20
788              ? !Constructor->isImplicit()
789              : (Constructor->isUserProvided() || Constructor->isExplicit()))
790        data().Aggregate = false;
791    }
792  }
793
794  // Handle constructors, including those inherited from base classes.
795  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {
796    // Record if we see any constexpr constructors which are neither copy
797    // nor move constructors.
798    // C++1z [basic.types]p10:
799    //   [...] has at least one constexpr constructor or constructor template
800    //   (possibly inherited from a base class) that is not a copy or move
801    //   constructor [...]
802    if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())
803      data().HasConstexprNonCopyMoveConstructor = true;
804  }
805
806  // Handle destructors.
807  if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
808    SMKind |= SMF_Destructor;
809
810    if (DD->isUserProvided())
811      data().HasIrrelevantDestructor = false;
812    // If the destructor is explicitly defaulted and not trivial or not public
813    // or if the destructor is deleted, we clear HasIrrelevantDestructor in
814    // finishedDefaultedOrDeletedMember.
815
816    // C++11 [class.dtor]p5:
817    //   A destructor is trivial if [...] the destructor is not virtual.
818    if (DD->isVirtual()) {
819      data().HasTrivialSpecialMembers &= ~SMF_Destructor;
820      data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
821    }
822  }
823
824  // Handle member functions.
825  if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
826    if (Method->isCopyAssignmentOperator()) {
827      SMKind |= SMF_CopyAssignment;
828
829      const auto *ParamTy =
830          Method->getParamDecl(0)->getType()->getAs<ReferenceType>();
831      if (!ParamTy || ParamTy->getPointeeType().isConstQualified())
832        data().HasDeclaredCopyAssignmentWithConstParam = true;
833    }
834
835    if (Method->isMoveAssignmentOperator())
836      SMKind |= SMF_MoveAssignment;
837
838    // Keep the list of conversion functions up-to-date.
839    if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {
840      // FIXME: We use the 'unsafe' accessor for the access specifier here,
841      // because Sema may not have set it yet. That's really just a misdesign
842      // in Sema. However, LLDB *will* have set the access specifier correctly,
843      // and adds declarations after the class is technically completed,
844      // so completeDefinition()'s overriding of the access specifiers doesn't
845      // work.
846      AccessSpecifier AS = Conversion->getAccessUnsafe();
847
848      if (Conversion->getPrimaryTemplate()) {
849        // We don't record specializations.
850      } else {
851        ASTContext &Ctx = getASTContext();
852        ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);
853        NamedDecl *Primary =
854            FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);
855        if (Primary->getPreviousDecl())
856          Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),
857                              Primary, AS);
858        else
859          Conversions.addDecl(Ctx, Primary, AS);
860      }
861    }
862
863    if (SMKind) {
864      // If this is the first declaration of a special member, we no longer have
865      // an implicit trivial special member.
866      data().HasTrivialSpecialMembers &=
867          data().DeclaredSpecialMembers | ~SMKind;
868      data().HasTrivialSpecialMembersForCall &=
869          data().DeclaredSpecialMembers | ~SMKind;
870
871      if (!Method->isImplicit() && !Method->isUserProvided()) {
872        // This method is user-declared but not user-provided. We can't work out
873        // whether it's trivial yet (not until we get to the end of the class).
874        // We'll handle this method in finishedDefaultedOrDeletedMember.
875      } else if (Method->isTrivial()) {
876        data().HasTrivialSpecialMembers |= SMKind;
877        data().HasTrivialSpecialMembersForCall |= SMKind;
878      } else if (Method->isTrivialForCall()) {
879        data().HasTrivialSpecialMembersForCall |= SMKind;
880        data().DeclaredNonTrivialSpecialMembers |= SMKind;
881      } else {
882        data().DeclaredNonTrivialSpecialMembers |= SMKind;
883        // If this is a user-provided function, do not set
884        // DeclaredNonTrivialSpecialMembersForCall here since we don't know
885        // yet whether the method would be considered non-trivial for the
886        // purpose of calls (attribute "trivial_abi" can be dropped from the
887        // class later, which can change the special method's triviality).
888        if (!Method->isUserProvided())
889          data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
890      }
891
892      // Note when we have declared a declared special member, and suppress the
893      // implicit declaration of this special member.
894      data().DeclaredSpecialMembers |= SMKind;
895
896      if (!Method->isImplicit()) {
897        data().UserDeclaredSpecialMembers |= SMKind;
898
899        // C++03 [class]p4:
900        //   A POD-struct is an aggregate class that has [...] no user-defined
901        //   copy assignment operator and no user-defined destructor.
902        //
903        // Since the POD bit is meant to be C++03 POD-ness, and in C++03,
904        // aggregates could not have any constructors, clear it even for an
905        // explicitly defaulted or deleted constructor.
906        // type is technically an aggregate in C++0x since it wouldn't be in 03.
907        //
908        // Also, a user-declared move assignment operator makes a class non-POD.
909        // This is an extension in C++03.
910        data().PlainOldData = false;
911      }
912    }
913
914    return;
915  }
916
917  // Handle non-static data members.
918  if (const auto *Field = dyn_cast<FieldDecl>(D)) {
919    ASTContext &Context = getASTContext();
920
921    // C++2a [class]p7:
922    //   A standard-layout class is a class that:
923    //    [...]
924    //    -- has all non-static data members and bit-fields in the class and
925    //       its base classes first declared in the same class
926    if (data().HasBasesWithFields)
927      data().IsStandardLayout = false;
928
929    // C++ [class.bit]p2:
930    //   A declaration for a bit-field that omits the identifier declares an
931    //   unnamed bit-field. Unnamed bit-fields are not members and cannot be
932    //   initialized.
933    if (Field->isUnnamedBitfield()) {
934      // C++ [meta.unary.prop]p4: [LWG2358]
935      //   T is a class type [...] with [...] no unnamed bit-fields of non-zero
936      //   length
937      if (data().Empty && !Field->isZeroLengthBitField(Context) &&
938          Context.getLangOpts().getClangABICompat() >
939              LangOptions::ClangABI::Ver6)
940        data().Empty = false;
941      return;
942    }
943
944    // C++11 [class]p7:
945    //   A standard-layout class is a class that:
946    //    -- either has no non-static data members in the most derived class
947    //       [...] or has no base classes with non-static data members
948    if (data().HasBasesWithNonStaticDataMembers)
949      data().IsCXX11StandardLayout = false;
950
951    // C++ [dcl.init.aggr]p1:
952    //   An aggregate is an array or a class (clause 9) with [...] no
953    //   private or protected non-static data members (clause 11).
954    //
955    // A POD must be an aggregate.
956    if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {
957      data().Aggregate = false;
958      data().PlainOldData = false;
959    }
960
961    // Track whether this is the first field. We use this when checking
962    // whether the class is standard-layout below.
963    bool IsFirstField = !data().HasPrivateFields &&
964                        !data().HasProtectedFields && !data().HasPublicFields;
965
966    // C++0x [class]p7:
967    //   A standard-layout class is a class that:
968    //    [...]
969    //    -- has the same access control for all non-static data members,
970    switch (D->getAccess()) {
971    case AS_private:    data().HasPrivateFields = true;   break;
972    case AS_protected:  data().HasProtectedFields = true; break;
973    case AS_public:     data().HasPublicFields = true;    break;
974    case AS_none:       llvm_unreachable("Invalid access specifier");
975    };
976    if ((data().HasPrivateFields + data().HasProtectedFields +
977         data().HasPublicFields) > 1) {
978      data().IsStandardLayout = false;
979      data().IsCXX11StandardLayout = false;
980    }
981
982    // Keep track of the presence of mutable fields.
983    if (Field->isMutable())
984      data().HasMutableFields = true;
985
986    // C++11 [class.union]p8, DR1460:
987    //   If X is a union, a non-static data member of X that is not an anonymous
988    //   union is a variant member of X.
989    if (isUnion() && !Field->isAnonymousStructOrUnion())
990      data().HasVariantMembers = true;
991
992    // C++0x [class]p9:
993    //   A POD struct is a class that is both a trivial class and a
994    //   standard-layout class, and has no non-static data members of type
995    //   non-POD struct, non-POD union (or array of such types).
996    //
997    // Automatic Reference Counting: the presence of a member of Objective-C pointer type
998    // that does not explicitly have no lifetime makes the class a non-POD.
999    QualType T = Context.getBaseElementType(Field->getType());
1000    if (T->isObjCRetainableType() || T.isObjCGCStrong()) {
1001      if (T.hasNonTrivialObjCLifetime()) {
1002        // Objective-C Automatic Reference Counting:
1003        //   If a class has a non-static data member of Objective-C pointer
1004        //   type (or array thereof), it is a non-POD type and its
1005        //   default constructor (if any), copy constructor, move constructor,
1006        //   copy assignment operator, move assignment operator, and destructor are
1007        //   non-trivial.
1008        setHasObjectMember(true);
1009        struct DefinitionData &Data = data();
1010        Data.PlainOldData = false;
1011        Data.HasTrivialSpecialMembers = 0;
1012
1013        // __strong or __weak fields do not make special functions non-trivial
1014        // for the purpose of calls.
1015        Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();
1016        if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)
1017          data().HasTrivialSpecialMembersForCall = 0;
1018
1019        // Structs with __weak fields should never be passed directly.
1020        if (LT == Qualifiers::OCL_Weak)
1021          setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
1022
1023        Data.HasIrrelevantDestructor = false;
1024
1025        if (isUnion()) {
1026          data().DefaultedCopyConstructorIsDeleted = true;
1027          data().DefaultedMoveConstructorIsDeleted = true;
1028          data().DefaultedCopyAssignmentIsDeleted = true;
1029          data().DefaultedMoveAssignmentIsDeleted = true;
1030          data().DefaultedDestructorIsDeleted = true;
1031          data().NeedOverloadResolutionForCopyConstructor = true;
1032          data().NeedOverloadResolutionForMoveConstructor = true;
1033          data().NeedOverloadResolutionForCopyAssignment = true;
1034          data().NeedOverloadResolutionForMoveAssignment = true;
1035          data().NeedOverloadResolutionForDestructor = true;
1036        }
1037      } else if (!Context.getLangOpts().ObjCAutoRefCount) {
1038        setHasObjectMember(true);
1039      }
1040    } else if (!T.isCXX98PODType(Context))
1041      data().PlainOldData = false;
1042
1043    if (T->isReferenceType()) {
1044      if (!Field->hasInClassInitializer())
1045        data().HasUninitializedReferenceMember = true;
1046
1047      // C++0x [class]p7:
1048      //   A standard-layout class is a class that:
1049      //    -- has no non-static data members of type [...] reference,
1050      data().IsStandardLayout = false;
1051      data().IsCXX11StandardLayout = false;
1052
1053      // C++1z [class.copy.ctor]p10:
1054      //   A defaulted copy constructor for a class X is defined as deleted if X has:
1055      //    -- a non-static data member of rvalue reference type
1056      if (T->isRValueReferenceType())
1057        data().DefaultedCopyConstructorIsDeleted = true;
1058    }
1059
1060    if (!Field->hasInClassInitializer() && !Field->isMutable()) {
1061      if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {
1062        if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())
1063          data().HasUninitializedFields = true;
1064      } else {
1065        data().HasUninitializedFields = true;
1066      }
1067    }
1068
1069    // Record if this field is the first non-literal or volatile field or base.
1070    if (!T->isLiteralType(Context) || T.isVolatileQualified())
1071      data().HasNonLiteralTypeFieldsOrBases = true;
1072
1073    if (Field->hasInClassInitializer() ||
1074        (Field->isAnonymousStructOrUnion() &&
1075         Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {
1076      data().HasInClassInitializer = true;
1077
1078      // C++11 [class]p5:
1079      //   A default constructor is trivial if [...] no non-static data member
1080      //   of its class has a brace-or-equal-initializer.
1081      data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1082
1083      // C++11 [dcl.init.aggr]p1:
1084      //   An aggregate is a [...] class with [...] no
1085      //   brace-or-equal-initializers for non-static data members.
1086      //
1087      // This rule was removed in C++14.
1088      if (!getASTContext().getLangOpts().CPlusPlus14)
1089        data().Aggregate = false;
1090
1091      // C++11 [class]p10:
1092      //   A POD struct is [...] a trivial class.
1093      data().PlainOldData = false;
1094    }
1095
1096    // C++11 [class.copy]p23:
1097    //   A defaulted copy/move assignment operator for a class X is defined
1098    //   as deleted if X has:
1099    //    -- a non-static data member of reference type
1100    if (T->isReferenceType()) {
1101      data().DefaultedCopyAssignmentIsDeleted = true;
1102      data().DefaultedMoveAssignmentIsDeleted = true;
1103    }
1104
1105    // Bitfields of length 0 are also zero-sized, but we already bailed out for
1106    // those because they are always unnamed.
1107    bool IsZeroSize = Field->isZeroSize(Context);
1108
1109    if (const auto *RecordTy = T->getAs<RecordType>()) {
1110      auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());
1111      if (FieldRec->getDefinition()) {
1112        addedClassSubobject(FieldRec);
1113
1114        // We may need to perform overload resolution to determine whether a
1115        // field can be moved if it's const or volatile qualified.
1116        if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {
1117          // We need to care about 'const' for the copy constructor because an
1118          // implicit copy constructor might be declared with a non-const
1119          // parameter.
1120          data().NeedOverloadResolutionForCopyConstructor = true;
1121          data().NeedOverloadResolutionForMoveConstructor = true;
1122          data().NeedOverloadResolutionForCopyAssignment = true;
1123          data().NeedOverloadResolutionForMoveAssignment = true;
1124        }
1125
1126        // C++11 [class.ctor]p5, C++11 [class.copy]p11:
1127        //   A defaulted [special member] for a class X is defined as
1128        //   deleted if:
1129        //    -- X is a union-like class that has a variant member with a
1130        //       non-trivial [corresponding special member]
1131        if (isUnion()) {
1132          if (FieldRec->hasNonTrivialCopyConstructor())
1133            data().DefaultedCopyConstructorIsDeleted = true;
1134          if (FieldRec->hasNonTrivialMoveConstructor())
1135            data().DefaultedMoveConstructorIsDeleted = true;
1136          if (FieldRec->hasNonTrivialCopyAssignment())
1137            data().DefaultedCopyAssignmentIsDeleted = true;
1138          if (FieldRec->hasNonTrivialMoveAssignment())
1139            data().DefaultedMoveAssignmentIsDeleted = true;
1140          if (FieldRec->hasNonTrivialDestructor())
1141            data().DefaultedDestructorIsDeleted = true;
1142        }
1143
1144        // For an anonymous union member, our overload resolution will perform
1145        // overload resolution for its members.
1146        if (Field->isAnonymousStructOrUnion()) {
1147          data().NeedOverloadResolutionForCopyConstructor |=
1148              FieldRec->data().NeedOverloadResolutionForCopyConstructor;
1149          data().NeedOverloadResolutionForMoveConstructor |=
1150              FieldRec->data().NeedOverloadResolutionForMoveConstructor;
1151          data().NeedOverloadResolutionForCopyAssignment |=
1152              FieldRec->data().NeedOverloadResolutionForCopyAssignment;
1153          data().NeedOverloadResolutionForMoveAssignment |=
1154              FieldRec->data().NeedOverloadResolutionForMoveAssignment;
1155          data().NeedOverloadResolutionForDestructor |=
1156              FieldRec->data().NeedOverloadResolutionForDestructor;
1157        }
1158
1159        // C++0x [class.ctor]p5:
1160        //   A default constructor is trivial [...] if:
1161        //    -- for all the non-static data members of its class that are of
1162        //       class type (or array thereof), each such class has a trivial
1163        //       default constructor.
1164        if (!FieldRec->hasTrivialDefaultConstructor())
1165          data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;
1166
1167        // C++0x [class.copy]p13:
1168        //   A copy/move constructor for class X is trivial if [...]
1169        //    [...]
1170        //    -- for each non-static data member of X that is of class type (or
1171        //       an array thereof), the constructor selected to copy/move that
1172        //       member is trivial;
1173        if (!FieldRec->hasTrivialCopyConstructor())
1174          data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;
1175
1176        if (!FieldRec->hasTrivialCopyConstructorForCall())
1177          data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;
1178
1179        // If the field doesn't have a simple move constructor, we'll eagerly
1180        // declare the move constructor for this class and we'll decide whether
1181        // it's trivial then.
1182        if (!FieldRec->hasTrivialMoveConstructor())
1183          data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;
1184
1185        if (!FieldRec->hasTrivialMoveConstructorForCall())
1186          data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;
1187
1188        // C++0x [class.copy]p27:
1189        //   A copy/move assignment operator for class X is trivial if [...]
1190        //    [...]
1191        //    -- for each non-static data member of X that is of class type (or
1192        //       an array thereof), the assignment operator selected to
1193        //       copy/move that member is trivial;
1194        if (!FieldRec->hasTrivialCopyAssignment())
1195          data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;
1196        // If the field doesn't have a simple move assignment, we'll eagerly
1197        // declare the move assignment for this class and we'll decide whether
1198        // it's trivial then.
1199        if (!FieldRec->hasTrivialMoveAssignment())
1200          data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;
1201
1202        if (!FieldRec->hasTrivialDestructor())
1203          data().HasTrivialSpecialMembers &= ~SMF_Destructor;
1204        if (!FieldRec->hasTrivialDestructorForCall())
1205          data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;
1206        if (!FieldRec->hasIrrelevantDestructor())
1207          data().HasIrrelevantDestructor = false;
1208        if (FieldRec->hasObjectMember())
1209          setHasObjectMember(true);
1210        if (FieldRec->hasVolatileMember())
1211          setHasVolatileMember(true);
1212        if (FieldRec->getArgPassingRestrictions() ==
1213            RecordDecl::APK_CanNeverPassInRegs)
1214          setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
1215
1216        // C++0x [class]p7:
1217        //   A standard-layout class is a class that:
1218        //    -- has no non-static data members of type non-standard-layout
1219        //       class (or array of such types) [...]
1220        if (!FieldRec->isStandardLayout())
1221          data().IsStandardLayout = false;
1222        if (!FieldRec->isCXX11StandardLayout())
1223          data().IsCXX11StandardLayout = false;
1224
1225        // C++2a [class]p7:
1226        //   A standard-layout class is a class that:
1227        //    [...]
1228        //    -- has no element of the set M(S) of types as a base class.
1229        if (data().IsStandardLayout &&
1230            (isUnion() || IsFirstField || IsZeroSize) &&
1231            hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))
1232          data().IsStandardLayout = false;
1233
1234        // C++11 [class]p7:
1235        //   A standard-layout class is a class that:
1236        //    -- has no base classes of the same type as the first non-static
1237        //       data member
1238        if (data().IsCXX11StandardLayout && IsFirstField) {
1239          // FIXME: We should check all base classes here, not just direct
1240          // base classes.
1241          for (const auto &BI : bases()) {
1242            if (Context.hasSameUnqualifiedType(BI.getType(), T)) {
1243              data().IsCXX11StandardLayout = false;
1244              break;
1245            }
1246          }
1247        }
1248
1249        // Keep track of the presence of mutable fields.
1250        if (FieldRec->hasMutableFields())
1251          data().HasMutableFields = true;
1252
1253        if (Field->isMutable()) {
1254          // Our copy constructor/assignment might call something other than
1255          // the subobject's copy constructor/assignment if it's mutable and of
1256          // class type.
1257          data().NeedOverloadResolutionForCopyConstructor = true;
1258          data().NeedOverloadResolutionForCopyAssignment = true;
1259        }
1260
1261        // C++11 [class.copy]p13:
1262        //   If the implicitly-defined constructor would satisfy the
1263        //   requirements of a constexpr constructor, the implicitly-defined
1264        //   constructor is constexpr.
1265        // C++11 [dcl.constexpr]p4:
1266        //    -- every constructor involved in initializing non-static data
1267        //       members [...] shall be a constexpr constructor
1268        if (!Field->hasInClassInitializer() &&
1269            !FieldRec->hasConstexprDefaultConstructor() && !isUnion())
1270          // The standard requires any in-class initializer to be a constant
1271          // expression. We consider this to be a defect.
1272          data().DefaultedDefaultConstructorIsConstexpr = false;
1273
1274        // C++11 [class.copy]p8:
1275        //   The implicitly-declared copy constructor for a class X will have
1276        //   the form 'X::X(const X&)' if each potentially constructed subobject
1277        //   of a class type M (or array thereof) has a copy constructor whose
1278        //   first parameter is of type 'const M&' or 'const volatile M&'.
1279        if (!FieldRec->hasCopyConstructorWithConstParam())
1280          data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;
1281
1282        // C++11 [class.copy]p18:
1283        //   The implicitly-declared copy assignment oeprator for a class X will
1284        //   have the form 'X& X::operator=(const X&)' if [...] for all the
1285        //   non-static data members of X that are of a class type M (or array
1286        //   thereof), each such class type has a copy assignment operator whose
1287        //   parameter is of type 'const M&', 'const volatile M&' or 'M'.
1288        if (!FieldRec->hasCopyAssignmentWithConstParam())
1289          data().ImplicitCopyAssignmentHasConstParam = false;
1290
1291        if (FieldRec->hasUninitializedReferenceMember() &&
1292            !Field->hasInClassInitializer())
1293          data().HasUninitializedReferenceMember = true;
1294
1295        // C++11 [class.union]p8, DR1460:
1296        //   a non-static data member of an anonymous union that is a member of
1297        //   X is also a variant member of X.
1298        if (FieldRec->hasVariantMembers() &&
1299            Field->isAnonymousStructOrUnion())
1300          data().HasVariantMembers = true;
1301      }
1302    } else {
1303      // Base element type of field is a non-class type.
1304      if (!T->isLiteralType(Context) ||
1305          (!Field->hasInClassInitializer() && !isUnion() &&
1306           !Context.getLangOpts().CPlusPlus20))
1307        data().DefaultedDefaultConstructorIsConstexpr = false;
1308
1309      // C++11 [class.copy]p23:
1310      //   A defaulted copy/move assignment operator for a class X is defined
1311      //   as deleted if X has:
1312      //    -- a non-static data member of const non-class type (or array
1313      //       thereof)
1314      if (T.isConstQualified()) {
1315        data().DefaultedCopyAssignmentIsDeleted = true;
1316        data().DefaultedMoveAssignmentIsDeleted = true;
1317      }
1318    }
1319
1320    // C++14 [meta.unary.prop]p4:
1321    //   T is a class type [...] with [...] no non-static data members other
1322    //   than subobjects of zero size
1323    if (data().Empty && !IsZeroSize)
1324      data().Empty = false;
1325  }
1326
1327  // Handle using declarations of conversion functions.
1328  if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {
1329    if (Shadow->getDeclName().getNameKind()
1330          == DeclarationName::CXXConversionFunctionName) {
1331      ASTContext &Ctx = getASTContext();
1332      data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());
1333    }
1334  }
1335
1336  if (const auto *Using = dyn_cast<UsingDecl>(D)) {
1337    if (Using->getDeclName().getNameKind() ==
1338        DeclarationName::CXXConstructorName) {
1339      data().HasInheritedConstructor = true;
1340      // C++1z [dcl.init.aggr]p1:
1341      //  An aggregate is [...] a class [...] with no inherited constructors
1342      data().Aggregate = false;
1343    }
1344
1345    if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)
1346      data().HasInheritedAssignment = true;
1347  }
1348}
1349
1350void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {
1351  assert(!D->isImplicit() && !D->isUserProvided());
1352
1353  // The kind of special member this declaration is, if any.
1354  unsigned SMKind = 0;
1355
1356  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1357    if (Constructor->isDefaultConstructor()) {
1358      SMKind |= SMF_DefaultConstructor;
1359      if (Constructor->isConstexpr())
1360        data().HasConstexprDefaultConstructor = true;
1361    }
1362    if (Constructor->isCopyConstructor())
1363      SMKind |= SMF_CopyConstructor;
1364    else if (Constructor->isMoveConstructor())
1365      SMKind |= SMF_MoveConstructor;
1366    else if (Constructor->isConstexpr())
1367      // We may now know that the constructor is constexpr.
1368      data().HasConstexprNonCopyMoveConstructor = true;
1369  } else if (isa<CXXDestructorDecl>(D)) {
1370    SMKind |= SMF_Destructor;
1371    if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())
1372      data().HasIrrelevantDestructor = false;
1373  } else if (D->isCopyAssignmentOperator())
1374    SMKind |= SMF_CopyAssignment;
1375  else if (D->isMoveAssignmentOperator())
1376    SMKind |= SMF_MoveAssignment;
1377
1378  // Update which trivial / non-trivial special members we have.
1379  // addedMember will have skipped this step for this member.
1380  if (D->isTrivial())
1381    data().HasTrivialSpecialMembers |= SMKind;
1382  else
1383    data().DeclaredNonTrivialSpecialMembers |= SMKind;
1384}
1385
1386void CXXRecordDecl::setCaptures(ArrayRef<LambdaCapture> Captures) {
1387  ASTContext &Context = getASTContext();
1388  CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();
1389
1390  // Copy captures.
1391  Data.NumCaptures = Captures.size();
1392  Data.NumExplicitCaptures = 0;
1393  Data.Captures = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *
1394                                                    Captures.size());
1395  LambdaCapture *ToCapture = Data.Captures;
1396  for (unsigned I = 0, N = Captures.size(); I != N; ++I) {
1397    if (Captures[I].isExplicit())
1398      ++Data.NumExplicitCaptures;
1399
1400    *ToCapture++ = Captures[I];
1401  }
1402
1403  if (!lambdaIsDefaultConstructibleAndAssignable())
1404    Data.DefaultedCopyAssignmentIsDeleted = true;
1405}
1406
1407void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {
1408  unsigned SMKind = 0;
1409
1410  if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1411    if (Constructor->isCopyConstructor())
1412      SMKind = SMF_CopyConstructor;
1413    else if (Constructor->isMoveConstructor())
1414      SMKind = SMF_MoveConstructor;
1415  } else if (isa<CXXDestructorDecl>(D))
1416    SMKind = SMF_Destructor;
1417
1418  if (D->isTrivialForCall())
1419    data().HasTrivialSpecialMembersForCall |= SMKind;
1420  else
1421    data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;
1422}
1423
1424bool CXXRecordDecl::isCLike() const {
1425  if (getTagKind() == TTK_Class || getTagKind() == TTK_Interface ||
1426      !TemplateOrInstantiation.isNull())
1427    return false;
1428  if (!hasDefinition())
1429    return true;
1430
1431  return isPOD() && data().HasOnlyCMembers;
1432}
1433
1434bool CXXRecordDecl::isGenericLambda() const {
1435  if (!isLambda()) return false;
1436  return getLambdaData().IsGenericLambda;
1437}
1438
1439#ifndef NDEBUG
1440static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {
1441  for (auto *D : R)
1442    if (!declaresSameEntity(D, R.front()))
1443      return false;
1444  return true;
1445}
1446#endif
1447
1448static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {
1449  if (!RD.isLambda()) return nullptr;
1450  DeclarationName Name =
1451    RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);
1452  DeclContext::lookup_result Calls = RD.lookup(Name);
1453
1454  assert(!Calls.empty() && "Missing lambda call operator!");
1455  assert(allLookupResultsAreTheSame(Calls) &&
1456         "More than one lambda call operator!");
1457  return Calls.front();
1458}
1459
1460FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {
1461  NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1462  return  dyn_cast_or_null<FunctionTemplateDecl>(CallOp);
1463}
1464
1465CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {
1466  NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);
1467
1468  if (CallOp == nullptr)
1469    return nullptr;
1470
1471  if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))
1472    return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());
1473
1474  return cast<CXXMethodDecl>(CallOp);
1475}
1476
1477CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {
1478  if (!isLambda()) return nullptr;
1479  DeclarationName Name =
1480    &getASTContext().Idents.get(getLambdaStaticInvokerName());
1481  DeclContext::lookup_result Invoker = lookup(Name);
1482  if (Invoker.empty()) return nullptr;
1483  assert(allLookupResultsAreTheSame(Invoker) &&
1484         "More than one static invoker operator!");
1485  NamedDecl *InvokerFun = Invoker.front();
1486  if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(InvokerFun))
1487    return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());
1488
1489  return cast<CXXMethodDecl>(InvokerFun);
1490}
1491
1492void CXXRecordDecl::getCaptureFields(
1493       llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1494       FieldDecl *&ThisCapture) const {
1495  Captures.clear();
1496  ThisCapture = nullptr;
1497
1498  LambdaDefinitionData &Lambda = getLambdaData();
1499  RecordDecl::field_iterator Field = field_begin();
1500  for (const LambdaCapture *C = Lambda.Captures, *CEnd = C + Lambda.NumCaptures;
1501       C != CEnd; ++C, ++Field) {
1502    if (C->capturesThis())
1503      ThisCapture = *Field;
1504    else if (C->capturesVariable())
1505      Captures[C->getCapturedVar()] = *Field;
1506  }
1507  assert(Field == field_end());
1508}
1509
1510TemplateParameterList *
1511CXXRecordDecl::getGenericLambdaTemplateParameterList() const {
1512  if (!isGenericLambda()) return nullptr;
1513  CXXMethodDecl *CallOp = getLambdaCallOperator();
1514  if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())
1515    return Tmpl->getTemplateParameters();
1516  return nullptr;
1517}
1518
1519ArrayRef<NamedDecl *>
1520CXXRecordDecl::getLambdaExplicitTemplateParameters() const {
1521  TemplateParameterList *List = getGenericLambdaTemplateParameterList();
1522  if (!List)
1523    return {};
1524
1525  assert(std::is_partitioned(List->begin(), List->end(),
1526                             [](const NamedDecl *D) { return !D->isImplicit(); })
1527         && "Explicit template params should be ordered before implicit ones");
1528
1529  const auto ExplicitEnd = llvm::partition_point(
1530      *List, [](const NamedDecl *D) { return !D->isImplicit(); });
1531  return llvm::makeArrayRef(List->begin(), ExplicitEnd);
1532}
1533
1534Decl *CXXRecordDecl::getLambdaContextDecl() const {
1535  assert(isLambda() && "Not a lambda closure type!");
1536  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1537  return getLambdaData().ContextDecl.get(Source);
1538}
1539
1540static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {
1541  QualType T =
1542      cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())
1543          ->getConversionType();
1544  return Context.getCanonicalType(T);
1545}
1546
1547/// Collect the visible conversions of a base class.
1548///
1549/// \param Record a base class of the class we're considering
1550/// \param InVirtual whether this base class is a virtual base (or a base
1551///   of a virtual base)
1552/// \param Access the access along the inheritance path to this base
1553/// \param ParentHiddenTypes the conversions provided by the inheritors
1554///   of this base
1555/// \param Output the set to which to add conversions from non-virtual bases
1556/// \param VOutput the set to which to add conversions from virtual bases
1557/// \param HiddenVBaseCs the set of conversions which were hidden in a
1558///   virtual base along some inheritance path
1559static void CollectVisibleConversions(
1560    ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,
1561    AccessSpecifier Access,
1562    const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,
1563    ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,
1564    llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {
1565  // The set of types which have conversions in this class or its
1566  // subclasses.  As an optimization, we don't copy the derived set
1567  // unless it might change.
1568  const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;
1569  llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;
1570
1571  // Collect the direct conversions and figure out which conversions
1572  // will be hidden in the subclasses.
1573  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1574  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1575  if (ConvI != ConvE) {
1576    HiddenTypesBuffer = ParentHiddenTypes;
1577    HiddenTypes = &HiddenTypesBuffer;
1578
1579    for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {
1580      CanQualType ConvType(GetConversionType(Context, I.getDecl()));
1581      bool Hidden = ParentHiddenTypes.count(ConvType);
1582      if (!Hidden)
1583        HiddenTypesBuffer.insert(ConvType);
1584
1585      // If this conversion is hidden and we're in a virtual base,
1586      // remember that it's hidden along some inheritance path.
1587      if (Hidden && InVirtual)
1588        HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));
1589
1590      // If this conversion isn't hidden, add it to the appropriate output.
1591      else if (!Hidden) {
1592        AccessSpecifier IAccess
1593          = CXXRecordDecl::MergeAccess(Access, I.getAccess());
1594
1595        if (InVirtual)
1596          VOutput.addDecl(I.getDecl(), IAccess);
1597        else
1598          Output.addDecl(Context, I.getDecl(), IAccess);
1599      }
1600    }
1601  }
1602
1603  // Collect information recursively from any base classes.
1604  for (const auto &I : Record->bases()) {
1605    const auto *RT = I.getType()->getAs<RecordType>();
1606    if (!RT) continue;
1607
1608    AccessSpecifier BaseAccess
1609      = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());
1610    bool BaseInVirtual = InVirtual || I.isVirtual();
1611
1612    auto *Base = cast<CXXRecordDecl>(RT->getDecl());
1613    CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,
1614                              *HiddenTypes, Output, VOutput, HiddenVBaseCs);
1615  }
1616}
1617
1618/// Collect the visible conversions of a class.
1619///
1620/// This would be extremely straightforward if it weren't for virtual
1621/// bases.  It might be worth special-casing that, really.
1622static void CollectVisibleConversions(ASTContext &Context,
1623                                      const CXXRecordDecl *Record,
1624                                      ASTUnresolvedSet &Output) {
1625  // The collection of all conversions in virtual bases that we've
1626  // found.  These will be added to the output as long as they don't
1627  // appear in the hidden-conversions set.
1628  UnresolvedSet<8> VBaseCs;
1629
1630  // The set of conversions in virtual bases that we've determined to
1631  // be hidden.
1632  llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;
1633
1634  // The set of types hidden by classes derived from this one.
1635  llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;
1636
1637  // Go ahead and collect the direct conversions and add them to the
1638  // hidden-types set.
1639  CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();
1640  CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();
1641  Output.append(Context, ConvI, ConvE);
1642  for (; ConvI != ConvE; ++ConvI)
1643    HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));
1644
1645  // Recursively collect conversions from base classes.
1646  for (const auto &I : Record->bases()) {
1647    const auto *RT = I.getType()->getAs<RecordType>();
1648    if (!RT) continue;
1649
1650    CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),
1651                              I.isVirtual(), I.getAccessSpecifier(),
1652                              HiddenTypes, Output, VBaseCs, HiddenVBaseCs);
1653  }
1654
1655  // Add any unhidden conversions provided by virtual bases.
1656  for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();
1657         I != E; ++I) {
1658    if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))
1659      Output.addDecl(Context, I.getDecl(), I.getAccess());
1660  }
1661}
1662
1663/// getVisibleConversionFunctions - get all conversion functions visible
1664/// in current class; including conversion function templates.
1665llvm::iterator_range<CXXRecordDecl::conversion_iterator>
1666CXXRecordDecl::getVisibleConversionFunctions() const {
1667  ASTContext &Ctx = getASTContext();
1668
1669  ASTUnresolvedSet *Set;
1670  if (bases_begin() == bases_end()) {
1671    // If root class, all conversions are visible.
1672    Set = &data().Conversions.get(Ctx);
1673  } else {
1674    Set = &data().VisibleConversions.get(Ctx);
1675    // If visible conversion list is not evaluated, evaluate it.
1676    if (!data().ComputedVisibleConversions) {
1677      CollectVisibleConversions(Ctx, this, *Set);
1678      data().ComputedVisibleConversions = true;
1679    }
1680  }
1681  return llvm::make_range(Set->begin(), Set->end());
1682}
1683
1684void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {
1685  // This operation is O(N) but extremely rare.  Sema only uses it to
1686  // remove UsingShadowDecls in a class that were followed by a direct
1687  // declaration, e.g.:
1688  //   class A : B {
1689  //     using B::operator int;
1690  //     operator int();
1691  //   };
1692  // This is uncommon by itself and even more uncommon in conjunction
1693  // with sufficiently large numbers of directly-declared conversions
1694  // that asymptotic behavior matters.
1695
1696  ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());
1697  for (unsigned I = 0, E = Convs.size(); I != E; ++I) {
1698    if (Convs[I].getDecl() == ConvDecl) {
1699      Convs.erase(I);
1700      assert(llvm::find(Convs, ConvDecl) == Convs.end() &&
1701             "conversion was found multiple times in unresolved set");
1702      return;
1703    }
1704  }
1705
1706  llvm_unreachable("conversion not found in set!");
1707}
1708
1709CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {
1710  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1711    return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());
1712
1713  return nullptr;
1714}
1715
1716MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {
1717  return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
1718}
1719
1720void
1721CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,
1722                                             TemplateSpecializationKind TSK) {
1723  assert(TemplateOrInstantiation.isNull() &&
1724         "Previous template or instantiation?");
1725  assert(!isa<ClassTemplatePartialSpecializationDecl>(this));
1726  TemplateOrInstantiation
1727    = new (getASTContext()) MemberSpecializationInfo(RD, TSK);
1728}
1729
1730ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {
1731  return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();
1732}
1733
1734void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {
1735  TemplateOrInstantiation = Template;
1736}
1737
1738TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{
1739  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))
1740    return Spec->getSpecializationKind();
1741
1742  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())
1743    return MSInfo->getTemplateSpecializationKind();
1744
1745  return TSK_Undeclared;
1746}
1747
1748void
1749CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
1750  if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1751    Spec->setSpecializationKind(TSK);
1752    return;
1753  }
1754
1755  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1756    MSInfo->setTemplateSpecializationKind(TSK);
1757    return;
1758  }
1759
1760  llvm_unreachable("Not a class template or member class specialization");
1761}
1762
1763const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {
1764  auto GetDefinitionOrSelf =
1765      [](const CXXRecordDecl *D) -> const CXXRecordDecl * {
1766    if (auto *Def = D->getDefinition())
1767      return Def;
1768    return D;
1769  };
1770
1771  // If it's a class template specialization, find the template or partial
1772  // specialization from which it was instantiated.
1773  if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {
1774    auto From = TD->getInstantiatedFrom();
1775    if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) {
1776      while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
1777        if (NewCTD->isMemberSpecialization())
1778          break;
1779        CTD = NewCTD;
1780      }
1781      return GetDefinitionOrSelf(CTD->getTemplatedDecl());
1782    }
1783    if (auto *CTPSD =
1784            From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
1785      while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
1786        if (NewCTPSD->isMemberSpecialization())
1787          break;
1788        CTPSD = NewCTPSD;
1789      }
1790      return GetDefinitionOrSelf(CTPSD);
1791    }
1792  }
1793
1794  if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
1795    if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
1796      const CXXRecordDecl *RD = this;
1797      while (auto *NewRD = RD->getInstantiatedFromMemberClass())
1798        RD = NewRD;
1799      return GetDefinitionOrSelf(RD);
1800    }
1801  }
1802
1803  assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&
1804         "couldn't find pattern for class template instantiation");
1805  return nullptr;
1806}
1807
1808CXXDestructorDecl *CXXRecordDecl::getDestructor() const {
1809  ASTContext &Context = getASTContext();
1810  QualType ClassType = Context.getTypeDeclType(this);
1811
1812  DeclarationName Name
1813    = Context.DeclarationNames.getCXXDestructorName(
1814                                          Context.getCanonicalType(ClassType));
1815
1816  DeclContext::lookup_result R = lookup(Name);
1817
1818  return R.empty() ? nullptr : dyn_cast<CXXDestructorDecl>(R.front());
1819}
1820
1821bool CXXRecordDecl::isAnyDestructorNoReturn() const {
1822  // Destructor is noreturn.
1823  if (const CXXDestructorDecl *Destructor = getDestructor())
1824    if (Destructor->isNoReturn())
1825      return true;
1826
1827  // Check base classes destructor for noreturn.
1828  for (const auto &Base : bases())
1829    if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl())
1830      if (RD->isAnyDestructorNoReturn())
1831        return true;
1832
1833  // Check fields for noreturn.
1834  for (const auto *Field : fields())
1835    if (const CXXRecordDecl *RD =
1836            Field->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl())
1837      if (RD->isAnyDestructorNoReturn())
1838        return true;
1839
1840  // All destructors are not noreturn.
1841  return false;
1842}
1843
1844static bool isDeclContextInNamespace(const DeclContext *DC) {
1845  while (!DC->isTranslationUnit()) {
1846    if (DC->isNamespace())
1847      return true;
1848    DC = DC->getParent();
1849  }
1850  return false;
1851}
1852
1853bool CXXRecordDecl::isInterfaceLike() const {
1854  assert(hasDefinition() && "checking for interface-like without a definition");
1855  // All __interfaces are inheritently interface-like.
1856  if (isInterface())
1857    return true;
1858
1859  // Interface-like types cannot have a user declared constructor, destructor,
1860  // friends, VBases, conversion functions, or fields.  Additionally, lambdas
1861  // cannot be interface types.
1862  if (isLambda() || hasUserDeclaredConstructor() ||
1863      hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||
1864      getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)
1865    return false;
1866
1867  // No interface-like type can have a method with a definition.
1868  for (const auto *const Method : methods())
1869    if (Method->isDefined() && !Method->isImplicit())
1870      return false;
1871
1872  // Check "Special" types.
1873  const auto *Uuid = getAttr<UuidAttr>();
1874  // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an
1875  // extern C++ block directly in the TU.  These are only valid if in one
1876  // of these two situations.
1877  if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&
1878      !isDeclContextInNamespace(getDeclContext()) &&
1879      ((getName() == "IUnknown" &&
1880        Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||
1881       (getName() == "IDispatch" &&
1882        Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {
1883    if (getNumBases() > 0)
1884      return false;
1885    return true;
1886  }
1887
1888  // FIXME: Any access specifiers is supposed to make this no longer interface
1889  // like.
1890
1891  // If this isn't a 'special' type, it must have a single interface-like base.
1892  if (getNumBases() != 1)
1893    return false;
1894
1895  const auto BaseSpec = *bases_begin();
1896  if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)
1897    return false;
1898  const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();
1899  if (Base->isInterface() || !Base->isInterfaceLike())
1900    return false;
1901  return true;
1902}
1903
1904void CXXRecordDecl::completeDefinition() {
1905  completeDefinition(nullptr);
1906}
1907
1908void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {
1909  RecordDecl::completeDefinition();
1910
1911  // If the class may be abstract (but hasn't been marked as such), check for
1912  // any pure final overriders.
1913  if (mayBeAbstract()) {
1914    CXXFinalOverriderMap MyFinalOverriders;
1915    if (!FinalOverriders) {
1916      getFinalOverriders(MyFinalOverriders);
1917      FinalOverriders = &MyFinalOverriders;
1918    }
1919
1920    bool Done = false;
1921    for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(),
1922                                     MEnd = FinalOverriders->end();
1923         M != MEnd && !Done; ++M) {
1924      for (OverridingMethods::iterator SO = M->second.begin(),
1925                                    SOEnd = M->second.end();
1926           SO != SOEnd && !Done; ++SO) {
1927        assert(SO->second.size() > 0 &&
1928               "All virtual functions have overriding virtual functions");
1929
1930        // C++ [class.abstract]p4:
1931        //   A class is abstract if it contains or inherits at least one
1932        //   pure virtual function for which the final overrider is pure
1933        //   virtual.
1934        if (SO->second.front().Method->isPure()) {
1935          data().Abstract = true;
1936          Done = true;
1937          break;
1938        }
1939      }
1940    }
1941  }
1942
1943  // Set access bits correctly on the directly-declared conversions.
1944  for (conversion_iterator I = conversion_begin(), E = conversion_end();
1945       I != E; ++I)
1946    I.setAccess((*I)->getAccess());
1947}
1948
1949bool CXXRecordDecl::mayBeAbstract() const {
1950  if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||
1951      isDependentContext())
1952    return false;
1953
1954  for (const auto &B : bases()) {
1955    const auto *BaseDecl =
1956        cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());
1957    if (BaseDecl->isAbstract())
1958      return true;
1959  }
1960
1961  return false;
1962}
1963
1964bool CXXRecordDecl::isEffectivelyFinal() const {
1965  auto *Def = getDefinition();
1966  if (!Def)
1967    return false;
1968  if (Def->hasAttr<FinalAttr>())
1969    return true;
1970  if (const auto *Dtor = Def->getDestructor())
1971    if (Dtor->hasAttr<FinalAttr>())
1972      return true;
1973  return false;
1974}
1975
1976void CXXDeductionGuideDecl::anchor() {}
1977
1978bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {
1979  if ((getKind() != Other.getKind() ||
1980       getKind() == ExplicitSpecKind::Unresolved)) {
1981    if (getKind() == ExplicitSpecKind::Unresolved &&
1982        Other.getKind() == ExplicitSpecKind::Unresolved) {
1983      ODRHash SelfHash, OtherHash;
1984      SelfHash.AddStmt(getExpr());
1985      OtherHash.AddStmt(Other.getExpr());
1986      return SelfHash.CalculateHash() == OtherHash.CalculateHash();
1987    } else
1988      return false;
1989  }
1990  return true;
1991}
1992
1993ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {
1994  switch (Function->getDeclKind()) {
1995  case Decl::Kind::CXXConstructor:
1996    return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();
1997  case Decl::Kind::CXXConversion:
1998    return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();
1999  case Decl::Kind::CXXDeductionGuide:
2000    return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();
2001  default:
2002    return {};
2003  }
2004}
2005
2006CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(
2007    ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2008    ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2009    TypeSourceInfo *TInfo, SourceLocation EndLocation) {
2010  return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T,
2011                                           TInfo, EndLocation);
2012}
2013
2014CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C,
2015                                                                 unsigned ID) {
2016  return new (C, ID) CXXDeductionGuideDecl(
2017      C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(),
2018      QualType(), nullptr, SourceLocation());
2019}
2020
2021RequiresExprBodyDecl *RequiresExprBodyDecl::Create(
2022    ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {
2023  return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);
2024}
2025
2026RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C,
2027                                                               unsigned ID) {
2028  return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());
2029}
2030
2031void CXXMethodDecl::anchor() {}
2032
2033bool CXXMethodDecl::isStatic() const {
2034  const CXXMethodDecl *MD = getCanonicalDecl();
2035
2036  if (MD->getStorageClass() == SC_Static)
2037    return true;
2038
2039  OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();
2040  return isStaticOverloadedOperator(OOK);
2041}
2042
2043static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,
2044                                 const CXXMethodDecl *BaseMD) {
2045  for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {
2046    if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())
2047      return true;
2048    if (recursivelyOverrides(MD, BaseMD))
2049      return true;
2050  }
2051  return false;
2052}
2053
2054CXXMethodDecl *
2055CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2056                                                     bool MayBeBase) {
2057  if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())
2058    return this;
2059
2060  // Lookup doesn't work for destructors, so handle them separately.
2061  if (isa<CXXDestructorDecl>(this)) {
2062    CXXMethodDecl *MD = RD->getDestructor();
2063    if (MD) {
2064      if (recursivelyOverrides(MD, this))
2065        return MD;
2066      if (MayBeBase && recursivelyOverrides(this, MD))
2067        return MD;
2068    }
2069    return nullptr;
2070  }
2071
2072  for (auto *ND : RD->lookup(getDeclName())) {
2073    auto *MD = dyn_cast<CXXMethodDecl>(ND);
2074    if (!MD)
2075      continue;
2076    if (recursivelyOverrides(MD, this))
2077      return MD;
2078    if (MayBeBase && recursivelyOverrides(this, MD))
2079      return MD;
2080  }
2081
2082  return nullptr;
2083}
2084
2085CXXMethodDecl *
2086CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2087                                             bool MayBeBase) {
2088  if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))
2089    return MD;
2090
2091  llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;
2092  auto AddFinalOverrider = [&](CXXMethodDecl *D) {
2093    // If this function is overridden by a candidate final overrider, it is not
2094    // a final overrider.
2095    for (CXXMethodDecl *OtherD : FinalOverriders) {
2096      if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))
2097        return;
2098    }
2099
2100    // Other candidate final overriders might be overridden by this function.
2101    FinalOverriders.erase(
2102        std::remove_if(FinalOverriders.begin(), FinalOverriders.end(),
2103                       [&](CXXMethodDecl *OtherD) {
2104                         return recursivelyOverrides(D, OtherD);
2105                       }),
2106        FinalOverriders.end());
2107
2108    FinalOverriders.push_back(D);
2109  };
2110
2111  for (const auto &I : RD->bases()) {
2112    const RecordType *RT = I.getType()->getAs<RecordType>();
2113    if (!RT)
2114      continue;
2115    const auto *Base = cast<CXXRecordDecl>(RT->getDecl());
2116    if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))
2117      AddFinalOverrider(D);
2118  }
2119
2120  return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;
2121}
2122
2123CXXMethodDecl *CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD,
2124                                     SourceLocation StartLoc,
2125                                     const DeclarationNameInfo &NameInfo,
2126                                     QualType T, TypeSourceInfo *TInfo,
2127                                     StorageClass SC, bool isInline,
2128                                     ConstexprSpecKind ConstexprKind,
2129                                     SourceLocation EndLocation,
2130                                     Expr *TrailingRequiresClause) {
2131  return new (C, RD)
2132      CXXMethodDecl(CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC,
2133                    isInline, ConstexprKind, EndLocation,
2134                    TrailingRequiresClause);
2135}
2136
2137CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2138  return new (C, ID) CXXMethodDecl(
2139      CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(),
2140      QualType(), nullptr, SC_None, false, CSK_unspecified, SourceLocation(),
2141      nullptr);
2142}
2143
2144CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,
2145                                                     bool IsAppleKext) {
2146  assert(isVirtual() && "this method is expected to be virtual");
2147
2148  // When building with -fapple-kext, all calls must go through the vtable since
2149  // the kernel linker can do runtime patching of vtables.
2150  if (IsAppleKext)
2151    return nullptr;
2152
2153  // If the member function is marked 'final', we know that it can't be
2154  // overridden and can therefore devirtualize it unless it's pure virtual.
2155  if (hasAttr<FinalAttr>())
2156    return isPure() ? nullptr : this;
2157
2158  // If Base is unknown, we cannot devirtualize.
2159  if (!Base)
2160    return nullptr;
2161
2162  // If the base expression (after skipping derived-to-base conversions) is a
2163  // class prvalue, then we can devirtualize.
2164  Base = Base->getBestDynamicClassTypeExpr();
2165  if (Base->isRValue() && Base->getType()->isRecordType())
2166    return this;
2167
2168  // If we don't even know what we would call, we can't devirtualize.
2169  const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
2170  if (!BestDynamicDecl)
2171    return nullptr;
2172
2173  // There may be a method corresponding to MD in a derived class.
2174  CXXMethodDecl *DevirtualizedMethod =
2175      getCorrespondingMethodInClass(BestDynamicDecl);
2176
2177  // If there final overrider in the dynamic type is ambiguous, we can't
2178  // devirtualize this call.
2179  if (!DevirtualizedMethod)
2180    return nullptr;
2181
2182  // If that method is pure virtual, we can't devirtualize. If this code is
2183  // reached, the result would be UB, not a direct call to the derived class
2184  // function, and we can't assume the derived class function is defined.
2185  if (DevirtualizedMethod->isPure())
2186    return nullptr;
2187
2188  // If that method is marked final, we can devirtualize it.
2189  if (DevirtualizedMethod->hasAttr<FinalAttr>())
2190    return DevirtualizedMethod;
2191
2192  // Similarly, if the class itself or its destructor is marked 'final',
2193  // the class can't be derived from and we can therefore devirtualize the
2194  // member function call.
2195  if (BestDynamicDecl->isEffectivelyFinal())
2196    return DevirtualizedMethod;
2197
2198  if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
2199    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2200      if (VD->getType()->isRecordType())
2201        // This is a record decl. We know the type and can devirtualize it.
2202        return DevirtualizedMethod;
2203
2204    return nullptr;
2205  }
2206
2207  // We can devirtualize calls on an object accessed by a class member access
2208  // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2209  // a derived class object constructed in the same location.
2210  if (const auto *ME = dyn_cast<MemberExpr>(Base)) {
2211    const ValueDecl *VD = ME->getMemberDecl();
2212    return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;
2213  }
2214
2215  // Likewise for calls on an object accessed by a (non-reference) pointer to
2216  // member access.
2217  if (auto *BO = dyn_cast<BinaryOperator>(Base)) {
2218    if (BO->isPtrMemOp()) {
2219      auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();
2220      if (MPT->getPointeeType()->isRecordType())
2221        return DevirtualizedMethod;
2222    }
2223  }
2224
2225  // We can't devirtualize the call.
2226  return nullptr;
2227}
2228
2229bool CXXMethodDecl::isUsualDeallocationFunction(
2230    SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {
2231  assert(PreventedBy.empty() && "PreventedBy is expected to be empty");
2232  if (getOverloadedOperator() != OO_Delete &&
2233      getOverloadedOperator() != OO_Array_Delete)
2234    return false;
2235
2236  // C++ [basic.stc.dynamic.deallocation]p2:
2237  //   A template instance is never a usual deallocation function,
2238  //   regardless of its signature.
2239  if (getPrimaryTemplate())
2240    return false;
2241
2242  // C++ [basic.stc.dynamic.deallocation]p2:
2243  //   If a class T has a member deallocation function named operator delete
2244  //   with exactly one parameter, then that function is a usual (non-placement)
2245  //   deallocation function. [...]
2246  if (getNumParams() == 1)
2247    return true;
2248  unsigned UsualParams = 1;
2249
2250  // C++ P0722:
2251  //   A destroying operator delete is a usual deallocation function if
2252  //   removing the std::destroying_delete_t parameter and changing the
2253  //   first parameter type from T* to void* results in the signature of
2254  //   a usual deallocation function.
2255  if (isDestroyingOperatorDelete())
2256    ++UsualParams;
2257
2258  // C++ <=14 [basic.stc.dynamic.deallocation]p2:
2259  //   [...] If class T does not declare such an operator delete but does
2260  //   declare a member deallocation function named operator delete with
2261  //   exactly two parameters, the second of which has type std::size_t (18.1),
2262  //   then this function is a usual deallocation function.
2263  //
2264  // C++17 says a usual deallocation function is one with the signature
2265  //   (void* [, size_t] [, std::align_val_t] [, ...])
2266  // and all such functions are usual deallocation functions. It's not clear
2267  // that allowing varargs functions was intentional.
2268  ASTContext &Context = getASTContext();
2269  if (UsualParams < getNumParams() &&
2270      Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),
2271                                     Context.getSizeType()))
2272    ++UsualParams;
2273
2274  if (UsualParams < getNumParams() &&
2275      getParamDecl(UsualParams)->getType()->isAlignValT())
2276    ++UsualParams;
2277
2278  if (UsualParams != getNumParams())
2279    return false;
2280
2281  // In C++17 onwards, all potential usual deallocation functions are actual
2282  // usual deallocation functions. Honor this behavior when post-C++14
2283  // deallocation functions are offered as extensions too.
2284  // FIXME(EricWF): Destrying Delete should be a language option. How do we
2285  // handle when destroying delete is used prior to C++17?
2286  if (Context.getLangOpts().CPlusPlus17 ||
2287      Context.getLangOpts().AlignedAllocation ||
2288      isDestroyingOperatorDelete())
2289    return true;
2290
2291  // This function is a usual deallocation function if there are no
2292  // single-parameter deallocation functions of the same kind.
2293  DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());
2294  bool Result = true;
2295  for (const auto *D : R) {
2296    if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2297      if (FD->getNumParams() == 1) {
2298        PreventedBy.push_back(FD);
2299        Result = false;
2300      }
2301    }
2302  }
2303  return Result;
2304}
2305
2306bool CXXMethodDecl::isCopyAssignmentOperator() const {
2307  // C++0x [class.copy]p17:
2308  //  A user-declared copy assignment operator X::operator= is a non-static
2309  //  non-template member function of class X with exactly one parameter of
2310  //  type X, X&, const X&, volatile X& or const volatile X&.
2311  if (/*operator=*/getOverloadedOperator() != OO_Equal ||
2312      /*non-static*/ isStatic() ||
2313      /*non-template*/getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2314      getNumParams() != 1)
2315    return false;
2316
2317  QualType ParamType = getParamDecl(0)->getType();
2318  if (const auto *Ref = ParamType->getAs<LValueReferenceType>())
2319    ParamType = Ref->getPointeeType();
2320
2321  ASTContext &Context = getASTContext();
2322  QualType ClassType
2323    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2324  return Context.hasSameUnqualifiedType(ClassType, ParamType);
2325}
2326
2327bool CXXMethodDecl::isMoveAssignmentOperator() const {
2328  // C++0x [class.copy]p19:
2329  //  A user-declared move assignment operator X::operator= is a non-static
2330  //  non-template member function of class X with exactly one parameter of type
2331  //  X&&, const X&&, volatile X&&, or const volatile X&&.
2332  if (getOverloadedOperator() != OO_Equal || isStatic() ||
2333      getPrimaryTemplate() || getDescribedFunctionTemplate() ||
2334      getNumParams() != 1)
2335    return false;
2336
2337  QualType ParamType = getParamDecl(0)->getType();
2338  if (!isa<RValueReferenceType>(ParamType))
2339    return false;
2340  ParamType = ParamType->getPointeeType();
2341
2342  ASTContext &Context = getASTContext();
2343  QualType ClassType
2344    = Context.getCanonicalType(Context.getTypeDeclType(getParent()));
2345  return Context.hasSameUnqualifiedType(ClassType, ParamType);
2346}
2347
2348void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {
2349  assert(MD->isCanonicalDecl() && "Method is not canonical!");
2350  assert(!MD->getParent()->isDependentContext() &&
2351         "Can't add an overridden method to a class template!");
2352  assert(MD->isVirtual() && "Method is not virtual!");
2353
2354  getASTContext().addOverriddenMethod(this, MD);
2355}
2356
2357CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {
2358  if (isa<CXXConstructorDecl>(this)) return nullptr;
2359  return getASTContext().overridden_methods_begin(this);
2360}
2361
2362CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {
2363  if (isa<CXXConstructorDecl>(this)) return nullptr;
2364  return getASTContext().overridden_methods_end(this);
2365}
2366
2367unsigned CXXMethodDecl::size_overridden_methods() const {
2368  if (isa<CXXConstructorDecl>(this)) return 0;
2369  return getASTContext().overridden_methods_size(this);
2370}
2371
2372CXXMethodDecl::overridden_method_range
2373CXXMethodDecl::overridden_methods() const {
2374  if (isa<CXXConstructorDecl>(this))
2375    return overridden_method_range(nullptr, nullptr);
2376  return getASTContext().overridden_methods(this);
2377}
2378
2379static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,
2380                                  const CXXRecordDecl *Decl) {
2381  QualType ClassTy = C.getTypeDeclType(Decl);
2382  return C.getQualifiedType(ClassTy, FPT->getMethodQuals());
2383}
2384
2385QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,
2386                                    const CXXRecordDecl *Decl) {
2387  ASTContext &C = Decl->getASTContext();
2388  QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);
2389  return C.getPointerType(ObjectTy);
2390}
2391
2392QualType CXXMethodDecl::getThisObjectType(const FunctionProtoType *FPT,
2393                                          const CXXRecordDecl *Decl) {
2394  ASTContext &C = Decl->getASTContext();
2395  return ::getThisObjectType(C, FPT, Decl);
2396}
2397
2398QualType CXXMethodDecl::getThisType() const {
2399  // C++ 9.3.2p1: The type of this in a member function of a class X is X*.
2400  // If the member function is declared const, the type of this is const X*,
2401  // if the member function is declared volatile, the type of this is
2402  // volatile X*, and if the member function is declared const volatile,
2403  // the type of this is const volatile X*.
2404  assert(isInstance() && "No 'this' for static methods!");
2405  return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),
2406                                    getParent());
2407}
2408
2409QualType CXXMethodDecl::getThisObjectType() const {
2410  // Ditto getThisType.
2411  assert(isInstance() && "No 'this' for static methods!");
2412  return CXXMethodDecl::getThisObjectType(
2413      getType()->castAs<FunctionProtoType>(), getParent());
2414}
2415
2416bool CXXMethodDecl::hasInlineBody() const {
2417  // If this function is a template instantiation, look at the template from
2418  // which it was instantiated.
2419  const FunctionDecl *CheckFn = getTemplateInstantiationPattern();
2420  if (!CheckFn)
2421    CheckFn = this;
2422
2423  const FunctionDecl *fn;
2424  return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&
2425         (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());
2426}
2427
2428bool CXXMethodDecl::isLambdaStaticInvoker() const {
2429  const CXXRecordDecl *P = getParent();
2430  if (P->isLambda()) {
2431    if (const CXXMethodDecl *StaticInvoker = P->getLambdaStaticInvoker()) {
2432      if (StaticInvoker == this) return true;
2433      if (P->isGenericLambda() && this->isFunctionTemplateSpecialization())
2434        return StaticInvoker == this->getPrimaryTemplate()->getTemplatedDecl();
2435    }
2436  }
2437  return false;
2438}
2439
2440CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2441                                       TypeSourceInfo *TInfo, bool IsVirtual,
2442                                       SourceLocation L, Expr *Init,
2443                                       SourceLocation R,
2444                                       SourceLocation EllipsisLoc)
2445    : Initializee(TInfo), MemberOrEllipsisLocation(EllipsisLoc), Init(Init),
2446      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),
2447      IsWritten(false), SourceOrder(0) {}
2448
2449CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2450                                       FieldDecl *Member,
2451                                       SourceLocation MemberLoc,
2452                                       SourceLocation L, Expr *Init,
2453                                       SourceLocation R)
2454    : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
2455      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2456      IsWritten(false), SourceOrder(0) {}
2457
2458CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2459                                       IndirectFieldDecl *Member,
2460                                       SourceLocation MemberLoc,
2461                                       SourceLocation L, Expr *Init,
2462                                       SourceLocation R)
2463    : Initializee(Member), MemberOrEllipsisLocation(MemberLoc), Init(Init),
2464      LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),
2465      IsWritten(false), SourceOrder(0) {}
2466
2467CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,
2468                                       TypeSourceInfo *TInfo,
2469                                       SourceLocation L, Expr *Init,
2470                                       SourceLocation R)
2471    : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),
2472      IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}
2473
2474int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {
2475  return Context.getAllocator()
2476                .identifyKnownAlignedObject<CXXCtorInitializer>(this);
2477}
2478
2479TypeLoc CXXCtorInitializer::getBaseClassLoc() const {
2480  if (isBaseInitializer())
2481    return Initializee.get<TypeSourceInfo*>()->getTypeLoc();
2482  else
2483    return {};
2484}
2485
2486const Type *CXXCtorInitializer::getBaseClass() const {
2487  if (isBaseInitializer())
2488    return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();
2489  else
2490    return nullptr;
2491}
2492
2493SourceLocation CXXCtorInitializer::getSourceLocation() const {
2494  if (isInClassMemberInitializer())
2495    return getAnyMember()->getLocation();
2496
2497  if (isAnyMemberInitializer())
2498    return getMemberLocation();
2499
2500  if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())
2501    return TSInfo->getTypeLoc().getLocalSourceRange().getBegin();
2502
2503  return {};
2504}
2505
2506SourceRange CXXCtorInitializer::getSourceRange() const {
2507  if (isInClassMemberInitializer()) {
2508    FieldDecl *D = getAnyMember();
2509    if (Expr *I = D->getInClassInitializer())
2510      return I->getSourceRange();
2511    return {};
2512  }
2513
2514  return SourceRange(getSourceLocation(), getRParenLoc());
2515}
2516
2517CXXConstructorDecl::CXXConstructorDecl(
2518    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2519    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2520    ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2521    ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited,
2522    Expr *TrailingRequiresClause)
2523    : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
2524                    SC_None, isInline, ConstexprKind, SourceLocation(),
2525                    TrailingRequiresClause) {
2526  setNumCtorInitializers(0);
2527  setInheritingConstructor(static_cast<bool>(Inherited));
2528  setImplicit(isImplicitlyDeclared);
2529  CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;
2530  if (Inherited)
2531    *getTrailingObjects<InheritedConstructor>() = Inherited;
2532  setExplicitSpecifier(ES);
2533}
2534
2535void CXXConstructorDecl::anchor() {}
2536
2537CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,
2538                                                           unsigned ID,
2539                                                           uint64_t AllocKind) {
2540  bool hasTraillingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);
2541  bool isInheritingConstructor =
2542      static_cast<bool>(AllocKind & TAKInheritsConstructor);
2543  unsigned Extra =
2544      additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2545          isInheritingConstructor, hasTraillingExplicit);
2546  auto *Result = new (C, ID, Extra)
2547      CXXConstructorDecl(C, nullptr, SourceLocation(), DeclarationNameInfo(),
2548                         QualType(), nullptr, ExplicitSpecifier(), false, false,
2549                         CSK_unspecified, InheritedConstructor(), nullptr);
2550  Result->setInheritingConstructor(isInheritingConstructor);
2551  Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =
2552      hasTraillingExplicit;
2553  Result->setExplicitSpecifier(ExplicitSpecifier());
2554  return Result;
2555}
2556
2557CXXConstructorDecl *CXXConstructorDecl::Create(
2558    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2559    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2560    ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2561    ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited,
2562    Expr *TrailingRequiresClause) {
2563  assert(NameInfo.getName().getNameKind()
2564         == DeclarationName::CXXConstructorName &&
2565         "Name must refer to a constructor");
2566  unsigned Extra =
2567      additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(
2568          Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);
2569  return new (C, RD, Extra)
2570      CXXConstructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, ES, isInline,
2571                         isImplicitlyDeclared, ConstexprKind, Inherited,
2572                         TrailingRequiresClause);
2573}
2574
2575CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {
2576  return CtorInitializers.get(getASTContext().getExternalSource());
2577}
2578
2579CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {
2580  assert(isDelegatingConstructor() && "Not a delegating constructor!");
2581  Expr *E = (*init_begin())->getInit()->IgnoreImplicit();
2582  if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))
2583    return Construct->getConstructor();
2584
2585  return nullptr;
2586}
2587
2588bool CXXConstructorDecl::isDefaultConstructor() const {
2589  // C++ [class.default.ctor]p1:
2590  //   A default constructor for a class X is a constructor of class X for
2591  //   which each parameter that is not a function parameter pack has a default
2592  //   argument (including the case of a constructor with no parameters)
2593  return getMinRequiredArguments() == 0;
2594}
2595
2596bool
2597CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {
2598  return isCopyOrMoveConstructor(TypeQuals) &&
2599         getParamDecl(0)->getType()->isLValueReferenceType();
2600}
2601
2602bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {
2603  return isCopyOrMoveConstructor(TypeQuals) &&
2604         getParamDecl(0)->getType()->isRValueReferenceType();
2605}
2606
2607/// Determine whether this is a copy or move constructor.
2608bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {
2609  // C++ [class.copy]p2:
2610  //   A non-template constructor for class X is a copy constructor
2611  //   if its first parameter is of type X&, const X&, volatile X& or
2612  //   const volatile X&, and either there are no other parameters
2613  //   or else all other parameters have default arguments (8.3.6).
2614  // C++0x [class.copy]p3:
2615  //   A non-template constructor for class X is a move constructor if its
2616  //   first parameter is of type X&&, const X&&, volatile X&&, or
2617  //   const volatile X&&, and either there are no other parameters or else
2618  //   all other parameters have default arguments.
2619  if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||
2620      getDescribedFunctionTemplate() != nullptr)
2621    return false;
2622
2623  const ParmVarDecl *Param = getParamDecl(0);
2624
2625  // Do we have a reference type?
2626  const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();
2627  if (!ParamRefType)
2628    return false;
2629
2630  // Is it a reference to our class type?
2631  ASTContext &Context = getASTContext();
2632
2633  CanQualType PointeeType
2634    = Context.getCanonicalType(ParamRefType->getPointeeType());
2635  CanQualType ClassTy
2636    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2637  if (PointeeType.getUnqualifiedType() != ClassTy)
2638    return false;
2639
2640  // FIXME: other qualifiers?
2641
2642  // We have a copy or move constructor.
2643  TypeQuals = PointeeType.getCVRQualifiers();
2644  return true;
2645}
2646
2647bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {
2648  // C++ [class.conv.ctor]p1:
2649  //   A constructor declared without the function-specifier explicit
2650  //   that can be called with a single parameter specifies a
2651  //   conversion from the type of its first parameter to the type of
2652  //   its class. Such a constructor is called a converting
2653  //   constructor.
2654  if (isExplicit() && !AllowExplicit)
2655    return false;
2656
2657  // FIXME: This has nothing to do with the definition of converting
2658  // constructor, but is convenient for how we use this function in overload
2659  // resolution.
2660  return getNumParams() == 0
2661             ? getType()->castAs<FunctionProtoType>()->isVariadic()
2662             : getMinRequiredArguments() <= 1;
2663}
2664
2665bool CXXConstructorDecl::isSpecializationCopyingObject() const {
2666  if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)
2667    return false;
2668
2669  const ParmVarDecl *Param = getParamDecl(0);
2670
2671  ASTContext &Context = getASTContext();
2672  CanQualType ParamType = Context.getCanonicalType(Param->getType());
2673
2674  // Is it the same as our class type?
2675  CanQualType ClassTy
2676    = Context.getCanonicalType(Context.getTagDeclType(getParent()));
2677  if (ParamType.getUnqualifiedType() != ClassTy)
2678    return false;
2679
2680  return true;
2681}
2682
2683void CXXDestructorDecl::anchor() {}
2684
2685CXXDestructorDecl *
2686CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2687  return new (C, ID)
2688      CXXDestructorDecl(C, nullptr, SourceLocation(), DeclarationNameInfo(),
2689                        QualType(), nullptr, false, false, CSK_unspecified,
2690                        nullptr);
2691}
2692
2693CXXDestructorDecl *CXXDestructorDecl::Create(
2694    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2695    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2696    bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2697    Expr *TrailingRequiresClause) {
2698  assert(NameInfo.getName().getNameKind()
2699         == DeclarationName::CXXDestructorName &&
2700         "Name must refer to a destructor");
2701  return new (C, RD)
2702      CXXDestructorDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline,
2703                        isImplicitlyDeclared, ConstexprKind,
2704                        TrailingRequiresClause);
2705}
2706
2707void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {
2708  auto *First = cast<CXXDestructorDecl>(getFirstDecl());
2709  if (OD && !First->OperatorDelete) {
2710    First->OperatorDelete = OD;
2711    First->OperatorDeleteThisArg = ThisArg;
2712    if (auto *L = getASTMutationListener())
2713      L->ResolvedOperatorDelete(First, OD, ThisArg);
2714  }
2715}
2716
2717void CXXConversionDecl::anchor() {}
2718
2719CXXConversionDecl *
2720CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2721  return new (C, ID) CXXConversionDecl(
2722      C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,
2723      false, ExplicitSpecifier(), CSK_unspecified, SourceLocation(), nullptr);
2724}
2725
2726CXXConversionDecl *CXXConversionDecl::Create(
2727    ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2728    const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2729    bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2730    SourceLocation EndLocation, Expr *TrailingRequiresClause) {
2731  assert(NameInfo.getName().getNameKind()
2732         == DeclarationName::CXXConversionFunctionName &&
2733         "Name must refer to a conversion function");
2734  return new (C, RD)
2735      CXXConversionDecl(C, RD, StartLoc, NameInfo, T, TInfo, isInline, ES,
2736                        ConstexprKind, EndLocation, TrailingRequiresClause);
2737}
2738
2739bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {
2740  return isImplicit() && getParent()->isLambda() &&
2741         getConversionType()->isBlockPointerType();
2742}
2743
2744LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2745                                 SourceLocation LangLoc, LanguageIDs lang,
2746                                 bool HasBraces)
2747    : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
2748      ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {
2749  setLanguage(lang);
2750  LinkageSpecDeclBits.HasBraces = HasBraces;
2751}
2752
2753void LinkageSpecDecl::anchor() {}
2754
2755LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
2756                                         DeclContext *DC,
2757                                         SourceLocation ExternLoc,
2758                                         SourceLocation LangLoc,
2759                                         LanguageIDs Lang,
2760                                         bool HasBraces) {
2761  return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
2762}
2763
2764LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,
2765                                                     unsigned ID) {
2766  return new (C, ID) LinkageSpecDecl(nullptr, SourceLocation(),
2767                                     SourceLocation(), lang_c, false);
2768}
2769
2770void UsingDirectiveDecl::anchor() {}
2771
2772UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,
2773                                               SourceLocation L,
2774                                               SourceLocation NamespaceLoc,
2775                                           NestedNameSpecifierLoc QualifierLoc,
2776                                               SourceLocation IdentLoc,
2777                                               NamedDecl *Used,
2778                                               DeclContext *CommonAncestor) {
2779  if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))
2780    Used = NS->getOriginalNamespace();
2781  return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,
2782                                        IdentLoc, Used, CommonAncestor);
2783}
2784
2785UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,
2786                                                           unsigned ID) {
2787  return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),
2788                                        SourceLocation(),
2789                                        NestedNameSpecifierLoc(),
2790                                        SourceLocation(), nullptr, nullptr);
2791}
2792
2793NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {
2794  if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))
2795    return NA->getNamespace();
2796  return cast_or_null<NamespaceDecl>(NominatedNamespace);
2797}
2798
2799NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
2800                             SourceLocation StartLoc, SourceLocation IdLoc,
2801                             IdentifierInfo *Id, NamespaceDecl *PrevDecl)
2802    : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),
2803      redeclarable_base(C), LocStart(StartLoc),
2804      AnonOrFirstNamespaceAndInline(nullptr, Inline) {
2805  setPreviousDecl(PrevDecl);
2806
2807  if (PrevDecl)
2808    AnonOrFirstNamespaceAndInline.setPointer(PrevDecl->getOriginalNamespace());
2809}
2810
2811NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
2812                                     bool Inline, SourceLocation StartLoc,
2813                                     SourceLocation IdLoc, IdentifierInfo *Id,
2814                                     NamespaceDecl *PrevDecl) {
2815  return new (C, DC) NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id,
2816                                   PrevDecl);
2817}
2818
2819NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2820  return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),
2821                                   SourceLocation(), nullptr, nullptr);
2822}
2823
2824NamespaceDecl *NamespaceDecl::getOriginalNamespace() {
2825  if (isFirstDecl())
2826    return this;
2827
2828  return AnonOrFirstNamespaceAndInline.getPointer();
2829}
2830
2831const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const {
2832  if (isFirstDecl())
2833    return this;
2834
2835  return AnonOrFirstNamespaceAndInline.getPointer();
2836}
2837
2838bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); }
2839
2840NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {
2841  return getNextRedeclaration();
2842}
2843
2844NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {
2845  return getPreviousDecl();
2846}
2847
2848NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {
2849  return getMostRecentDecl();
2850}
2851
2852void NamespaceAliasDecl::anchor() {}
2853
2854NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {
2855  return getNextRedeclaration();
2856}
2857
2858NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {
2859  return getPreviousDecl();
2860}
2861
2862NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {
2863  return getMostRecentDecl();
2864}
2865
2866NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,
2867                                               SourceLocation UsingLoc,
2868                                               SourceLocation AliasLoc,
2869                                               IdentifierInfo *Alias,
2870                                           NestedNameSpecifierLoc QualifierLoc,
2871                                               SourceLocation IdentLoc,
2872                                               NamedDecl *Namespace) {
2873  // FIXME: Preserve the aliased namespace as written.
2874  if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))
2875    Namespace = NS->getOriginalNamespace();
2876  return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,
2877                                        QualifierLoc, IdentLoc, Namespace);
2878}
2879
2880NamespaceAliasDecl *
2881NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2882  return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),
2883                                        SourceLocation(), nullptr,
2884                                        NestedNameSpecifierLoc(),
2885                                        SourceLocation(), nullptr);
2886}
2887
2888void LifetimeExtendedTemporaryDecl::anchor() {}
2889
2890/// Retrieve the storage duration for the materialized temporary.
2891StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {
2892  const ValueDecl *ExtendingDecl = getExtendingDecl();
2893  if (!ExtendingDecl)
2894    return SD_FullExpression;
2895  // FIXME: This is not necessarily correct for a temporary materialized
2896  // within a default initializer.
2897  if (isa<FieldDecl>(ExtendingDecl))
2898    return SD_Automatic;
2899  // FIXME: This only works because storage class specifiers are not allowed
2900  // on decomposition declarations.
2901  if (isa<BindingDecl>(ExtendingDecl))
2902    return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic
2903                                                                 : SD_Static;
2904  return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
2905}
2906
2907APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {
2908  assert(getStorageDuration() == SD_Static &&
2909         "don't need to cache the computed value for this temporary");
2910  if (MayCreate && !Value) {
2911    Value = (new (getASTContext()) APValue);
2912    getASTContext().addDestruction(Value);
2913  }
2914  assert(Value && "may not be null");
2915  return Value;
2916}
2917
2918void UsingShadowDecl::anchor() {}
2919
2920UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,
2921                                 SourceLocation Loc, UsingDecl *Using,
2922                                 NamedDecl *Target)
2923    : NamedDecl(K, DC, Loc, Using ? Using->getDeclName() : DeclarationName()),
2924      redeclarable_base(C), UsingOrNextShadow(cast<NamedDecl>(Using)) {
2925  if (Target)
2926    setTargetDecl(Target);
2927  setImplicit();
2928}
2929
2930UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)
2931    : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),
2932      redeclarable_base(C) {}
2933
2934UsingShadowDecl *
2935UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2936  return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());
2937}
2938
2939UsingDecl *UsingShadowDecl::getUsingDecl() const {
2940  const UsingShadowDecl *Shadow = this;
2941  while (const auto *NextShadow =
2942             dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))
2943    Shadow = NextShadow;
2944  return cast<UsingDecl>(Shadow->UsingOrNextShadow);
2945}
2946
2947void ConstructorUsingShadowDecl::anchor() {}
2948
2949ConstructorUsingShadowDecl *
2950ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,
2951                                   SourceLocation Loc, UsingDecl *Using,
2952                                   NamedDecl *Target, bool IsVirtual) {
2953  return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,
2954                                                IsVirtual);
2955}
2956
2957ConstructorUsingShadowDecl *
2958ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2959  return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());
2960}
2961
2962CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {
2963  return getUsingDecl()->getQualifier()->getAsRecordDecl();
2964}
2965
2966void UsingDecl::anchor() {}
2967
2968void UsingDecl::addShadowDecl(UsingShadowDecl *S) {
2969  assert(std::find(shadow_begin(), shadow_end(), S) == shadow_end() &&
2970         "declaration already in set");
2971  assert(S->getUsingDecl() == this);
2972
2973  if (FirstUsingShadow.getPointer())
2974    S->UsingOrNextShadow = FirstUsingShadow.getPointer();
2975  FirstUsingShadow.setPointer(S);
2976}
2977
2978void UsingDecl::removeShadowDecl(UsingShadowDecl *S) {
2979  assert(std::find(shadow_begin(), shadow_end(), S) != shadow_end() &&
2980         "declaration not in set");
2981  assert(S->getUsingDecl() == this);
2982
2983  // Remove S from the shadow decl chain. This is O(n) but hopefully rare.
2984
2985  if (FirstUsingShadow.getPointer() == S) {
2986    FirstUsingShadow.setPointer(
2987      dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));
2988    S->UsingOrNextShadow = this;
2989    return;
2990  }
2991
2992  UsingShadowDecl *Prev = FirstUsingShadow.getPointer();
2993  while (Prev->UsingOrNextShadow != S)
2994    Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);
2995  Prev->UsingOrNextShadow = S->UsingOrNextShadow;
2996  S->UsingOrNextShadow = this;
2997}
2998
2999UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,
3000                             NestedNameSpecifierLoc QualifierLoc,
3001                             const DeclarationNameInfo &NameInfo,
3002                             bool HasTypename) {
3003  return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);
3004}
3005
3006UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3007  return new (C, ID) UsingDecl(nullptr, SourceLocation(),
3008                               NestedNameSpecifierLoc(), DeclarationNameInfo(),
3009                               false);
3010}
3011
3012SourceRange UsingDecl::getSourceRange() const {
3013  SourceLocation Begin = isAccessDeclaration()
3014    ? getQualifierLoc().getBeginLoc() : UsingLocation;
3015  return SourceRange(Begin, getNameInfo().getEndLoc());
3016}
3017
3018void UsingPackDecl::anchor() {}
3019
3020UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,
3021                                     NamedDecl *InstantiatedFrom,
3022                                     ArrayRef<NamedDecl *> UsingDecls) {
3023  size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());
3024  return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);
3025}
3026
3027UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3028                                                 unsigned NumExpansions) {
3029  size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);
3030  auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, None);
3031  Result->NumExpansions = NumExpansions;
3032  auto *Trail = Result->getTrailingObjects<NamedDecl *>();
3033  for (unsigned I = 0; I != NumExpansions; ++I)
3034    new (Trail + I) NamedDecl*(nullptr);
3035  return Result;
3036}
3037
3038void UnresolvedUsingValueDecl::anchor() {}
3039
3040UnresolvedUsingValueDecl *
3041UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,
3042                                 SourceLocation UsingLoc,
3043                                 NestedNameSpecifierLoc QualifierLoc,
3044                                 const DeclarationNameInfo &NameInfo,
3045                                 SourceLocation EllipsisLoc) {
3046  return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,
3047                                              QualifierLoc, NameInfo,
3048                                              EllipsisLoc);
3049}
3050
3051UnresolvedUsingValueDecl *
3052UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3053  return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),
3054                                              SourceLocation(),
3055                                              NestedNameSpecifierLoc(),
3056                                              DeclarationNameInfo(),
3057                                              SourceLocation());
3058}
3059
3060SourceRange UnresolvedUsingValueDecl::getSourceRange() const {
3061  SourceLocation Begin = isAccessDeclaration()
3062    ? getQualifierLoc().getBeginLoc() : UsingLocation;
3063  return SourceRange(Begin, getNameInfo().getEndLoc());
3064}
3065
3066void UnresolvedUsingTypenameDecl::anchor() {}
3067
3068UnresolvedUsingTypenameDecl *
3069UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,
3070                                    SourceLocation UsingLoc,
3071                                    SourceLocation TypenameLoc,
3072                                    NestedNameSpecifierLoc QualifierLoc,
3073                                    SourceLocation TargetNameLoc,
3074                                    DeclarationName TargetName,
3075                                    SourceLocation EllipsisLoc) {
3076  return new (C, DC) UnresolvedUsingTypenameDecl(
3077      DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,
3078      TargetName.getAsIdentifierInfo(), EllipsisLoc);
3079}
3080
3081UnresolvedUsingTypenameDecl *
3082UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3083  return new (C, ID) UnresolvedUsingTypenameDecl(
3084      nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),
3085      SourceLocation(), nullptr, SourceLocation());
3086}
3087
3088void StaticAssertDecl::anchor() {}
3089
3090StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,
3091                                           SourceLocation StaticAssertLoc,
3092                                           Expr *AssertExpr,
3093                                           StringLiteral *Message,
3094                                           SourceLocation RParenLoc,
3095                                           bool Failed) {
3096  return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,
3097                                      RParenLoc, Failed);
3098}
3099
3100StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,
3101                                                       unsigned ID) {
3102  return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,
3103                                      nullptr, SourceLocation(), false);
3104}
3105
3106void BindingDecl::anchor() {}
3107
3108BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,
3109                                 SourceLocation IdLoc, IdentifierInfo *Id) {
3110  return new (C, DC) BindingDecl(DC, IdLoc, Id);
3111}
3112
3113BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3114  return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);
3115}
3116
3117ValueDecl *BindingDecl::getDecomposedDecl() const {
3118  ExternalASTSource *Source =
3119      Decomp.isOffset() ? getASTContext().getExternalSource() : nullptr;
3120  return cast_or_null<ValueDecl>(Decomp.get(Source));
3121}
3122
3123VarDecl *BindingDecl::getHoldingVar() const {
3124  Expr *B = getBinding();
3125  if (!B)
3126    return nullptr;
3127  auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());
3128  if (!DRE)
3129    return nullptr;
3130
3131  auto *VD = cast<VarDecl>(DRE->getDecl());
3132  assert(VD->isImplicit() && "holding var for binding decl not implicit");
3133  return VD;
3134}
3135
3136void DecompositionDecl::anchor() {}
3137
3138DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,
3139                                             SourceLocation StartLoc,
3140                                             SourceLocation LSquareLoc,
3141                                             QualType T, TypeSourceInfo *TInfo,
3142                                             StorageClass SC,
3143                                             ArrayRef<BindingDecl *> Bindings) {
3144  size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());
3145  return new (C, DC, Extra)
3146      DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);
3147}
3148
3149DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,
3150                                                         unsigned ID,
3151                                                         unsigned NumBindings) {
3152  size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);
3153  auto *Result = new (C, ID, Extra)
3154      DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),
3155                        QualType(), nullptr, StorageClass(), None);
3156  // Set up and clean out the bindings array.
3157  Result->NumBindings = NumBindings;
3158  auto *Trail = Result->getTrailingObjects<BindingDecl *>();
3159  for (unsigned I = 0; I != NumBindings; ++I)
3160    new (Trail + I) BindingDecl*(nullptr);
3161  return Result;
3162}
3163
3164void DecompositionDecl::printName(llvm::raw_ostream &os) const {
3165  os << '[';
3166  bool Comma = false;
3167  for (const auto *B : bindings()) {
3168    if (Comma)
3169      os << ", ";
3170    B->printName(os);
3171    Comma = true;
3172  }
3173  os << ']';
3174}
3175
3176void MSPropertyDecl::anchor() {}
3177
3178MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,
3179                                       SourceLocation L, DeclarationName N,
3180                                       QualType T, TypeSourceInfo *TInfo,
3181                                       SourceLocation StartL,
3182                                       IdentifierInfo *Getter,
3183                                       IdentifierInfo *Setter) {
3184  return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);
3185}
3186
3187MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
3188                                                   unsigned ID) {
3189  return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),
3190                                    DeclarationName(), QualType(), nullptr,
3191                                    SourceLocation(), nullptr, nullptr);
3192}
3193
3194void MSGuidDecl::anchor() {}
3195
3196MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)
3197    : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),
3198      PartVal(P), APVal() {}
3199
3200MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {
3201  DeclContext *DC = C.getTranslationUnitDecl();
3202  return new (C, DC) MSGuidDecl(DC, T, P);
3203}
3204
3205MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3206  return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());
3207}
3208
3209void MSGuidDecl::printName(llvm::raw_ostream &OS) const {
3210  OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",
3211                     PartVal.Part1, PartVal.Part2, PartVal.Part3);
3212  unsigned I = 0;
3213  for (uint8_t Byte : PartVal.Part4And5) {
3214    OS << llvm::format("%02" PRIx8, Byte);
3215    if (++I == 2)
3216      OS << '-';
3217  }
3218  OS << '}';
3219}
3220
3221/// Determine if T is a valid 'struct _GUID' of the shape that we expect.
3222static bool isValidStructGUID(ASTContext &Ctx, QualType T) {
3223  // FIXME: We only need to check this once, not once each time we compute a
3224  // GUID APValue.
3225  using MatcherRef = llvm::function_ref<bool(QualType)>;
3226
3227  auto IsInt = [&Ctx](unsigned N) {
3228    return [&Ctx, N](QualType T) {
3229      return T->isUnsignedIntegerOrEnumerationType() &&
3230             Ctx.getIntWidth(T) == N;
3231    };
3232  };
3233
3234  auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {
3235    return [&Ctx, Elem, N](QualType T) {
3236      const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);
3237      return CAT && CAT->getSize() == N && Elem(CAT->getElementType());
3238    };
3239  };
3240
3241  auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {
3242    return [Fields](QualType T) {
3243      const RecordDecl *RD = T->getAsRecordDecl();
3244      if (!RD || RD->isUnion())
3245        return false;
3246      RD = RD->getDefinition();
3247      if (!RD)
3248        return false;
3249      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3250        if (CXXRD->getNumBases())
3251          return false;
3252      auto MatcherIt = Fields.begin();
3253      for (const FieldDecl *FD : RD->fields()) {
3254        if (FD->isUnnamedBitfield()) continue;
3255        if (FD->isBitField() || MatcherIt == Fields.end() ||
3256            !(*MatcherIt)(FD->getType()))
3257          return false;
3258        ++MatcherIt;
3259      }
3260      return MatcherIt == Fields.end();
3261    };
3262  };
3263
3264  // We expect an {i32, i16, i16, [8 x i8]}.
3265  return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);
3266}
3267
3268APValue &MSGuidDecl::getAsAPValue() const {
3269  if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {
3270    using llvm::APInt;
3271    using llvm::APSInt;
3272    APVal = APValue(APValue::UninitStruct(), 0, 4);
3273    APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));
3274    APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));
3275    APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));
3276    APValue &Arr = APVal.getStructField(3) =
3277        APValue(APValue::UninitArray(), 8, 8);
3278    for (unsigned I = 0; I != 8; ++I) {
3279      Arr.getArrayInitializedElt(I) =
3280          APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));
3281    }
3282    // Register this APValue to be destroyed if necessary. (Note that the
3283    // MSGuidDecl destructor is never run.)
3284    getASTContext().addDestruction(&APVal);
3285  }
3286
3287  return APVal;
3288}
3289
3290static const char *getAccessName(AccessSpecifier AS) {
3291  switch (AS) {
3292    case AS_none:
3293      llvm_unreachable("Invalid access specifier!");
3294    case AS_public:
3295      return "public";
3296    case AS_private:
3297      return "private";
3298    case AS_protected:
3299      return "protected";
3300  }
3301  llvm_unreachable("Invalid access specifier!");
3302}
3303
3304const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
3305                                           AccessSpecifier AS) {
3306  return DB << getAccessName(AS);
3307}
3308
3309const PartialDiagnostic &clang::operator<<(const PartialDiagnostic &DB,
3310                                           AccessSpecifier AS) {
3311  return DB << getAccessName(AS);
3312}
3313