Home | History | Annotate | Line # | Download | only in AST
      1 //===- NestedNameSpecifier.cpp - C++ nested name specifiers ---------------===//
      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 defines the NestedNameSpecifier class, which represents
     10 //  a C++ nested-name-specifier.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/AST/NestedNameSpecifier.h"
     15 #include "clang/AST/ASTContext.h"
     16 #include "clang/AST/Decl.h"
     17 #include "clang/AST/DeclCXX.h"
     18 #include "clang/AST/DeclTemplate.h"
     19 #include "clang/AST/DependenceFlags.h"
     20 #include "clang/AST/PrettyPrinter.h"
     21 #include "clang/AST/TemplateName.h"
     22 #include "clang/AST/Type.h"
     23 #include "clang/AST/TypeLoc.h"
     24 #include "clang/Basic/LLVM.h"
     25 #include "clang/Basic/LangOptions.h"
     26 #include "clang/Basic/SourceLocation.h"
     27 #include "llvm/ADT/FoldingSet.h"
     28 #include "llvm/ADT/SmallVector.h"
     29 #include "llvm/Support/Casting.h"
     30 #include "llvm/Support/Compiler.h"
     31 #include "llvm/Support/ErrorHandling.h"
     32 #include "llvm/Support/raw_ostream.h"
     33 #include <algorithm>
     34 #include <cassert>
     35 #include <cstdlib>
     36 #include <cstring>
     37 
     38 using namespace clang;
     39 
     40 NestedNameSpecifier *
     41 NestedNameSpecifier::FindOrInsert(const ASTContext &Context,
     42                                   const NestedNameSpecifier &Mockup) {
     43   llvm::FoldingSetNodeID ID;
     44   Mockup.Profile(ID);
     45 
     46   void *InsertPos = nullptr;
     47   NestedNameSpecifier *NNS
     48     = Context.NestedNameSpecifiers.FindNodeOrInsertPos(ID, InsertPos);
     49   if (!NNS) {
     50     NNS =
     51         new (Context, alignof(NestedNameSpecifier)) NestedNameSpecifier(Mockup);
     52     Context.NestedNameSpecifiers.InsertNode(NNS, InsertPos);
     53   }
     54 
     55   return NNS;
     56 }
     57 
     58 NestedNameSpecifier *
     59 NestedNameSpecifier::Create(const ASTContext &Context,
     60                             NestedNameSpecifier *Prefix, IdentifierInfo *II) {
     61   assert(II && "Identifier cannot be NULL");
     62   assert((!Prefix || Prefix->isDependent()) && "Prefix must be dependent");
     63 
     64   NestedNameSpecifier Mockup;
     65   Mockup.Prefix.setPointer(Prefix);
     66   Mockup.Prefix.setInt(StoredIdentifier);
     67   Mockup.Specifier = II;
     68   return FindOrInsert(Context, Mockup);
     69 }
     70 
     71 NestedNameSpecifier *
     72 NestedNameSpecifier::Create(const ASTContext &Context,
     73                             NestedNameSpecifier *Prefix,
     74                             const NamespaceDecl *NS) {
     75   assert(NS && "Namespace cannot be NULL");
     76   assert((!Prefix ||
     77           (Prefix->getAsType() == nullptr &&
     78            Prefix->getAsIdentifier() == nullptr)) &&
     79          "Broken nested name specifier");
     80   NestedNameSpecifier Mockup;
     81   Mockup.Prefix.setPointer(Prefix);
     82   Mockup.Prefix.setInt(StoredDecl);
     83   Mockup.Specifier = const_cast<NamespaceDecl *>(NS);
     84   return FindOrInsert(Context, Mockup);
     85 }
     86 
     87 NestedNameSpecifier *
     88 NestedNameSpecifier::Create(const ASTContext &Context,
     89                             NestedNameSpecifier *Prefix,
     90                             NamespaceAliasDecl *Alias) {
     91   assert(Alias && "Namespace alias cannot be NULL");
     92   assert((!Prefix ||
     93           (Prefix->getAsType() == nullptr &&
     94            Prefix->getAsIdentifier() == nullptr)) &&
     95          "Broken nested name specifier");
     96   NestedNameSpecifier Mockup;
     97   Mockup.Prefix.setPointer(Prefix);
     98   Mockup.Prefix.setInt(StoredDecl);
     99   Mockup.Specifier = Alias;
    100   return FindOrInsert(Context, Mockup);
    101 }
    102 
    103 NestedNameSpecifier *
    104 NestedNameSpecifier::Create(const ASTContext &Context,
    105                             NestedNameSpecifier *Prefix,
    106                             bool Template, const Type *T) {
    107   assert(T && "Type cannot be NULL");
    108   NestedNameSpecifier Mockup;
    109   Mockup.Prefix.setPointer(Prefix);
    110   Mockup.Prefix.setInt(Template? StoredTypeSpecWithTemplate : StoredTypeSpec);
    111   Mockup.Specifier = const_cast<Type*>(T);
    112   return FindOrInsert(Context, Mockup);
    113 }
    114 
    115 NestedNameSpecifier *
    116 NestedNameSpecifier::Create(const ASTContext &Context, IdentifierInfo *II) {
    117   assert(II && "Identifier cannot be NULL");
    118   NestedNameSpecifier Mockup;
    119   Mockup.Prefix.setPointer(nullptr);
    120   Mockup.Prefix.setInt(StoredIdentifier);
    121   Mockup.Specifier = II;
    122   return FindOrInsert(Context, Mockup);
    123 }
    124 
    125 NestedNameSpecifier *
    126 NestedNameSpecifier::GlobalSpecifier(const ASTContext &Context) {
    127   if (!Context.GlobalNestedNameSpecifier)
    128     Context.GlobalNestedNameSpecifier =
    129         new (Context, alignof(NestedNameSpecifier)) NestedNameSpecifier();
    130   return Context.GlobalNestedNameSpecifier;
    131 }
    132 
    133 NestedNameSpecifier *
    134 NestedNameSpecifier::SuperSpecifier(const ASTContext &Context,
    135                                     CXXRecordDecl *RD) {
    136   NestedNameSpecifier Mockup;
    137   Mockup.Prefix.setPointer(nullptr);
    138   Mockup.Prefix.setInt(StoredDecl);
    139   Mockup.Specifier = RD;
    140   return FindOrInsert(Context, Mockup);
    141 }
    142 
    143 NestedNameSpecifier::SpecifierKind NestedNameSpecifier::getKind() const {
    144   if (!Specifier)
    145     return Global;
    146 
    147   switch (Prefix.getInt()) {
    148   case StoredIdentifier:
    149     return Identifier;
    150 
    151   case StoredDecl: {
    152     NamedDecl *ND = static_cast<NamedDecl *>(Specifier);
    153     if (isa<CXXRecordDecl>(ND))
    154       return Super;
    155     return isa<NamespaceDecl>(ND) ? Namespace : NamespaceAlias;
    156   }
    157 
    158   case StoredTypeSpec:
    159     return TypeSpec;
    160 
    161   case StoredTypeSpecWithTemplate:
    162     return TypeSpecWithTemplate;
    163   }
    164 
    165   llvm_unreachable("Invalid NNS Kind!");
    166 }
    167 
    168 /// Retrieve the namespace stored in this nested name specifier.
    169 NamespaceDecl *NestedNameSpecifier::getAsNamespace() const {
    170   if (Prefix.getInt() == StoredDecl)
    171     return dyn_cast<NamespaceDecl>(static_cast<NamedDecl *>(Specifier));
    172 
    173   return nullptr;
    174 }
    175 
    176 /// Retrieve the namespace alias stored in this nested name specifier.
    177 NamespaceAliasDecl *NestedNameSpecifier::getAsNamespaceAlias() const {
    178   if (Prefix.getInt() == StoredDecl)
    179     return dyn_cast<NamespaceAliasDecl>(static_cast<NamedDecl *>(Specifier));
    180 
    181   return nullptr;
    182 }
    183 
    184 /// Retrieve the record declaration stored in this nested name specifier.
    185 CXXRecordDecl *NestedNameSpecifier::getAsRecordDecl() const {
    186   switch (Prefix.getInt()) {
    187   case StoredIdentifier:
    188     return nullptr;
    189 
    190   case StoredDecl:
    191     return dyn_cast<CXXRecordDecl>(static_cast<NamedDecl *>(Specifier));
    192 
    193   case StoredTypeSpec:
    194   case StoredTypeSpecWithTemplate:
    195     return getAsType()->getAsCXXRecordDecl();
    196   }
    197 
    198   llvm_unreachable("Invalid NNS Kind!");
    199 }
    200 
    201 NestedNameSpecifierDependence NestedNameSpecifier::getDependence() const {
    202   switch (getKind()) {
    203   case Identifier: {
    204     // Identifier specifiers always represent dependent types
    205     auto F = NestedNameSpecifierDependence::Dependent |
    206              NestedNameSpecifierDependence::Instantiation;
    207     // Prefix can contain unexpanded template parameters.
    208     if (getPrefix())
    209       return F | getPrefix()->getDependence();
    210     return F;
    211   }
    212 
    213   case Namespace:
    214   case NamespaceAlias:
    215   case Global:
    216     return NestedNameSpecifierDependence::None;
    217 
    218   case Super: {
    219     CXXRecordDecl *RD = static_cast<CXXRecordDecl *>(Specifier);
    220     for (const auto &Base : RD->bases())
    221       if (Base.getType()->isDependentType())
    222         // FIXME: must also be instantiation-dependent.
    223         return NestedNameSpecifierDependence::Dependent;
    224     return NestedNameSpecifierDependence::None;
    225   }
    226 
    227   case TypeSpec:
    228   case TypeSpecWithTemplate:
    229     return toNestedNameSpecifierDependendence(getAsType()->getDependence());
    230   }
    231   llvm_unreachable("Invalid NNS Kind!");
    232 }
    233 
    234 bool NestedNameSpecifier::isDependent() const {
    235   return getDependence() & NestedNameSpecifierDependence::Dependent;
    236 }
    237 
    238 bool NestedNameSpecifier::isInstantiationDependent() const {
    239   return getDependence() & NestedNameSpecifierDependence::Instantiation;
    240 }
    241 
    242 bool NestedNameSpecifier::containsUnexpandedParameterPack() const {
    243   return getDependence() & NestedNameSpecifierDependence::UnexpandedPack;
    244 }
    245 
    246 bool NestedNameSpecifier::containsErrors() const {
    247   return getDependence() & NestedNameSpecifierDependence::Error;
    248 }
    249 
    250 /// Print this nested name specifier to the given output
    251 /// stream.
    252 void NestedNameSpecifier::print(raw_ostream &OS, const PrintingPolicy &Policy,
    253                                 bool ResolveTemplateArguments) const {
    254   if (getPrefix())
    255     getPrefix()->print(OS, Policy);
    256 
    257   switch (getKind()) {
    258   case Identifier:
    259     OS << getAsIdentifier()->getName();
    260     break;
    261 
    262   case Namespace:
    263     if (getAsNamespace()->isAnonymousNamespace())
    264       return;
    265 
    266     OS << getAsNamespace()->getName();
    267     break;
    268 
    269   case NamespaceAlias:
    270     OS << getAsNamespaceAlias()->getName();
    271     break;
    272 
    273   case Global:
    274     break;
    275 
    276   case Super:
    277     OS << "__super";
    278     break;
    279 
    280   case TypeSpecWithTemplate:
    281     OS << "template ";
    282     // Fall through to print the type.
    283     LLVM_FALLTHROUGH;
    284 
    285   case TypeSpec: {
    286     const auto *Record =
    287             dyn_cast_or_null<ClassTemplateSpecializationDecl>(getAsRecordDecl());
    288     if (ResolveTemplateArguments && Record) {
    289         // Print the type trait with resolved template parameters.
    290         Record->printName(OS);
    291         printTemplateArgumentList(
    292             OS, Record->getTemplateArgs().asArray(), Policy,
    293             Record->getSpecializedTemplate()->getTemplateParameters());
    294         break;
    295     }
    296     const Type *T = getAsType();
    297 
    298     PrintingPolicy InnerPolicy(Policy);
    299     InnerPolicy.SuppressScope = true;
    300 
    301     // Nested-name-specifiers are intended to contain minimally-qualified
    302     // types. An actual ElaboratedType will not occur, since we'll store
    303     // just the type that is referred to in the nested-name-specifier (e.g.,
    304     // a TypedefType, TagType, etc.). However, when we are dealing with
    305     // dependent template-id types (e.g., Outer<T>::template Inner<U>),
    306     // the type requires its own nested-name-specifier for uniqueness, so we
    307     // suppress that nested-name-specifier during printing.
    308     assert(!isa<ElaboratedType>(T) &&
    309            "Elaborated type in nested-name-specifier");
    310     if (const TemplateSpecializationType *SpecType
    311           = dyn_cast<TemplateSpecializationType>(T)) {
    312       // Print the template name without its corresponding
    313       // nested-name-specifier.
    314       SpecType->getTemplateName().print(OS, InnerPolicy, true);
    315 
    316       // Print the template argument list.
    317       printTemplateArgumentList(OS, SpecType->template_arguments(),
    318                                 InnerPolicy);
    319     } else if (const auto *DepSpecType =
    320                    dyn_cast<DependentTemplateSpecializationType>(T)) {
    321       // Print the template name without its corresponding
    322       // nested-name-specifier.
    323       OS << DepSpecType->getIdentifier()->getName();
    324       // Print the template argument list.
    325       printTemplateArgumentList(OS, DepSpecType->template_arguments(),
    326                                 InnerPolicy);
    327     } else {
    328       // Print the type normally
    329       QualType(T, 0).print(OS, InnerPolicy);
    330     }
    331     break;
    332   }
    333   }
    334 
    335   OS << "::";
    336 }
    337 
    338 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(const LangOptions &LO) const {
    339   dump(llvm::errs(), LO);
    340 }
    341 
    342 LLVM_DUMP_METHOD void NestedNameSpecifier::dump() const { dump(llvm::errs()); }
    343 
    344 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS) const {
    345   LangOptions LO;
    346   dump(OS, LO);
    347 }
    348 
    349 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS,
    350                                                 const LangOptions &LO) const {
    351   print(OS, PrintingPolicy(LO));
    352 }
    353 
    354 unsigned
    355 NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) {
    356   assert(Qualifier && "Expected a non-NULL qualifier");
    357 
    358   // Location of the trailing '::'.
    359   unsigned Length = sizeof(unsigned);
    360 
    361   switch (Qualifier->getKind()) {
    362   case NestedNameSpecifier::Global:
    363     // Nothing more to add.
    364     break;
    365 
    366   case NestedNameSpecifier::Identifier:
    367   case NestedNameSpecifier::Namespace:
    368   case NestedNameSpecifier::NamespaceAlias:
    369   case NestedNameSpecifier::Super:
    370     // The location of the identifier or namespace name.
    371     Length += sizeof(unsigned);
    372     break;
    373 
    374   case NestedNameSpecifier::TypeSpecWithTemplate:
    375   case NestedNameSpecifier::TypeSpec:
    376     // The "void*" that points at the TypeLoc data.
    377     // Note: the 'template' keyword is part of the TypeLoc.
    378     Length += sizeof(void *);
    379     break;
    380   }
    381 
    382   return Length;
    383 }
    384 
    385 unsigned
    386 NestedNameSpecifierLoc::getDataLength(NestedNameSpecifier *Qualifier) {
    387   unsigned Length = 0;
    388   for (; Qualifier; Qualifier = Qualifier->getPrefix())
    389     Length += getLocalDataLength(Qualifier);
    390   return Length;
    391 }
    392 
    393 /// Load a (possibly unaligned) source location from a given address
    394 /// and offset.
    395 static SourceLocation LoadSourceLocation(void *Data, unsigned Offset) {
    396   unsigned Raw;
    397   memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(unsigned));
    398   return SourceLocation::getFromRawEncoding(Raw);
    399 }
    400 
    401 /// Load a (possibly unaligned) pointer from a given address and
    402 /// offset.
    403 static void *LoadPointer(void *Data, unsigned Offset) {
    404   void *Result;
    405   memcpy(&Result, static_cast<char *>(Data) + Offset, sizeof(void*));
    406   return Result;
    407 }
    408 
    409 SourceRange NestedNameSpecifierLoc::getSourceRange() const {
    410   if (!Qualifier)
    411     return SourceRange();
    412 
    413   NestedNameSpecifierLoc First = *this;
    414   while (NestedNameSpecifierLoc Prefix = First.getPrefix())
    415     First = Prefix;
    416 
    417   return SourceRange(First.getLocalSourceRange().getBegin(),
    418                      getLocalSourceRange().getEnd());
    419 }
    420 
    421 SourceRange NestedNameSpecifierLoc::getLocalSourceRange() const {
    422   if (!Qualifier)
    423     return SourceRange();
    424 
    425   unsigned Offset = getDataLength(Qualifier->getPrefix());
    426   switch (Qualifier->getKind()) {
    427   case NestedNameSpecifier::Global:
    428     return LoadSourceLocation(Data, Offset);
    429 
    430   case NestedNameSpecifier::Identifier:
    431   case NestedNameSpecifier::Namespace:
    432   case NestedNameSpecifier::NamespaceAlias:
    433   case NestedNameSpecifier::Super:
    434     return SourceRange(LoadSourceLocation(Data, Offset),
    435                        LoadSourceLocation(Data, Offset + sizeof(unsigned)));
    436 
    437   case NestedNameSpecifier::TypeSpecWithTemplate:
    438   case NestedNameSpecifier::TypeSpec: {
    439     // The "void*" that points at the TypeLoc data.
    440     // Note: the 'template' keyword is part of the TypeLoc.
    441     void *TypeData = LoadPointer(Data, Offset);
    442     TypeLoc TL(Qualifier->getAsType(), TypeData);
    443     return SourceRange(TL.getBeginLoc(),
    444                        LoadSourceLocation(Data, Offset + sizeof(void*)));
    445   }
    446   }
    447 
    448   llvm_unreachable("Invalid NNS Kind!");
    449 }
    450 
    451 TypeLoc NestedNameSpecifierLoc::getTypeLoc() const {
    452   if (Qualifier->getKind() != NestedNameSpecifier::TypeSpec &&
    453       Qualifier->getKind() != NestedNameSpecifier::TypeSpecWithTemplate)
    454     return TypeLoc();
    455 
    456   // The "void*" that points at the TypeLoc data.
    457   unsigned Offset = getDataLength(Qualifier->getPrefix());
    458   void *TypeData = LoadPointer(Data, Offset);
    459   return TypeLoc(Qualifier->getAsType(), TypeData);
    460 }
    461 
    462 static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize,
    463                    unsigned &BufferCapacity) {
    464   if (Start == End)
    465     return;
    466 
    467   if (BufferSize + (End - Start) > BufferCapacity) {
    468     // Reallocate the buffer.
    469     unsigned NewCapacity = std::max(
    470         (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2),
    471         (unsigned)(BufferSize + (End - Start)));
    472     if (!BufferCapacity) {
    473       char *NewBuffer = static_cast<char *>(llvm::safe_malloc(NewCapacity));
    474       if (Buffer)
    475         memcpy(NewBuffer, Buffer, BufferSize);
    476       Buffer = NewBuffer;
    477     } else {
    478       Buffer = static_cast<char *>(llvm::safe_realloc(Buffer, NewCapacity));
    479     }
    480     BufferCapacity = NewCapacity;
    481   }
    482   assert(Buffer && Start && End && End > Start && "Illegal memory buffer copy");
    483   memcpy(Buffer + BufferSize, Start, End - Start);
    484   BufferSize += End - Start;
    485 }
    486 
    487 /// Save a source location to the given buffer.
    488 static void SaveSourceLocation(SourceLocation Loc, char *&Buffer,
    489                                unsigned &BufferSize, unsigned &BufferCapacity) {
    490   unsigned Raw = Loc.getRawEncoding();
    491   Append(reinterpret_cast<char *>(&Raw),
    492          reinterpret_cast<char *>(&Raw) + sizeof(unsigned),
    493          Buffer, BufferSize, BufferCapacity);
    494 }
    495 
    496 /// Save a pointer to the given buffer.
    497 static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize,
    498                         unsigned &BufferCapacity) {
    499   Append(reinterpret_cast<char *>(&Ptr),
    500          reinterpret_cast<char *>(&Ptr) + sizeof(void *),
    501          Buffer, BufferSize, BufferCapacity);
    502 }
    503 
    504 NestedNameSpecifierLocBuilder::
    505 NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)
    506     : Representation(Other.Representation) {
    507   if (!Other.Buffer)
    508     return;
    509 
    510   if (Other.BufferCapacity == 0) {
    511     // Shallow copy is okay.
    512     Buffer = Other.Buffer;
    513     BufferSize = Other.BufferSize;
    514     return;
    515   }
    516 
    517   // Deep copy
    518   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
    519          BufferCapacity);
    520 }
    521 
    522 NestedNameSpecifierLocBuilder &
    523 NestedNameSpecifierLocBuilder::
    524 operator=(const NestedNameSpecifierLocBuilder &Other) {
    525   Representation = Other.Representation;
    526 
    527   if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) {
    528     // Re-use our storage.
    529     BufferSize = Other.BufferSize;
    530     memcpy(Buffer, Other.Buffer, BufferSize);
    531     return *this;
    532   }
    533 
    534   // Free our storage, if we have any.
    535   if (BufferCapacity) {
    536     free(Buffer);
    537     BufferCapacity = 0;
    538   }
    539 
    540   if (!Other.Buffer) {
    541     // Empty.
    542     Buffer = nullptr;
    543     BufferSize = 0;
    544     return *this;
    545   }
    546 
    547   if (Other.BufferCapacity == 0) {
    548     // Shallow copy is okay.
    549     Buffer = Other.Buffer;
    550     BufferSize = Other.BufferSize;
    551     return *this;
    552   }
    553 
    554   // Deep copy.
    555   BufferSize = 0;
    556   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
    557          BufferCapacity);
    558   return *this;
    559 }
    560 
    561 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
    562                                            SourceLocation TemplateKWLoc,
    563                                            TypeLoc TL,
    564                                            SourceLocation ColonColonLoc) {
    565   Representation = NestedNameSpecifier::Create(Context, Representation,
    566                                                TemplateKWLoc.isValid(),
    567                                                TL.getTypePtr());
    568 
    569   // Push source-location info into the buffer.
    570   SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity);
    571   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    572 }
    573 
    574 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
    575                                            IdentifierInfo *Identifier,
    576                                            SourceLocation IdentifierLoc,
    577                                            SourceLocation ColonColonLoc) {
    578   Representation = NestedNameSpecifier::Create(Context, Representation,
    579                                                Identifier);
    580 
    581   // Push source-location info into the buffer.
    582   SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity);
    583   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    584 }
    585 
    586 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
    587                                            NamespaceDecl *Namespace,
    588                                            SourceLocation NamespaceLoc,
    589                                            SourceLocation ColonColonLoc) {
    590   Representation = NestedNameSpecifier::Create(Context, Representation,
    591                                                Namespace);
    592 
    593   // Push source-location info into the buffer.
    594   SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity);
    595   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    596 }
    597 
    598 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
    599                                            NamespaceAliasDecl *Alias,
    600                                            SourceLocation AliasLoc,
    601                                            SourceLocation ColonColonLoc) {
    602   Representation = NestedNameSpecifier::Create(Context, Representation, Alias);
    603 
    604   // Push source-location info into the buffer.
    605   SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity);
    606   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    607 }
    608 
    609 void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context,
    610                                                SourceLocation ColonColonLoc) {
    611   assert(!Representation && "Already have a nested-name-specifier!?");
    612   Representation = NestedNameSpecifier::GlobalSpecifier(Context);
    613 
    614   // Push source-location info into the buffer.
    615   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    616 }
    617 
    618 void NestedNameSpecifierLocBuilder::MakeSuper(ASTContext &Context,
    619                                               CXXRecordDecl *RD,
    620                                               SourceLocation SuperLoc,
    621                                               SourceLocation ColonColonLoc) {
    622   Representation = NestedNameSpecifier::SuperSpecifier(Context, RD);
    623 
    624   // Push source-location info into the buffer.
    625   SaveSourceLocation(SuperLoc, Buffer, BufferSize, BufferCapacity);
    626   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
    627 }
    628 
    629 void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context,
    630                                                 NestedNameSpecifier *Qualifier,
    631                                                 SourceRange R) {
    632   Representation = Qualifier;
    633 
    634   // Construct bogus (but well-formed) source information for the
    635   // nested-name-specifier.
    636   BufferSize = 0;
    637   SmallVector<NestedNameSpecifier *, 4> Stack;
    638   for (NestedNameSpecifier *NNS = Qualifier; NNS; NNS = NNS->getPrefix())
    639     Stack.push_back(NNS);
    640   while (!Stack.empty()) {
    641     NestedNameSpecifier *NNS = Stack.pop_back_val();
    642     switch (NNS->getKind()) {
    643       case NestedNameSpecifier::Identifier:
    644       case NestedNameSpecifier::Namespace:
    645       case NestedNameSpecifier::NamespaceAlias:
    646         SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity);
    647         break;
    648 
    649       case NestedNameSpecifier::TypeSpec:
    650       case NestedNameSpecifier::TypeSpecWithTemplate: {
    651         TypeSourceInfo *TSInfo
    652         = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0),
    653                                            R.getBegin());
    654         SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize,
    655                     BufferCapacity);
    656         break;
    657       }
    658 
    659       case NestedNameSpecifier::Global:
    660       case NestedNameSpecifier::Super:
    661         break;
    662     }
    663 
    664     // Save the location of the '::'.
    665     SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(),
    666                        Buffer, BufferSize, BufferCapacity);
    667   }
    668 }
    669 
    670 void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) {
    671   if (BufferCapacity)
    672     free(Buffer);
    673 
    674   if (!Other) {
    675     Representation = nullptr;
    676     BufferSize = 0;
    677     return;
    678   }
    679 
    680   // Rather than copying the data (which is wasteful), "adopt" the
    681   // pointer (which points into the ASTContext) but set the capacity to zero to
    682   // indicate that we don't own it.
    683   Representation = Other.getNestedNameSpecifier();
    684   Buffer = static_cast<char *>(Other.getOpaqueData());
    685   BufferSize = Other.getDataLength();
    686   BufferCapacity = 0;
    687 }
    688 
    689 NestedNameSpecifierLoc
    690 NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const {
    691   if (!Representation)
    692     return NestedNameSpecifierLoc();
    693 
    694   // If we adopted our data pointer from elsewhere in the AST context, there's
    695   // no need to copy the memory.
    696   if (BufferCapacity == 0)
    697     return NestedNameSpecifierLoc(Representation, Buffer);
    698 
    699   // FIXME: After copying the source-location information, should we free
    700   // our (temporary) buffer and adopt the ASTContext-allocated memory?
    701   // Doing so would optimize repeated calls to getWithLocInContext().
    702   void *Mem = Context.Allocate(BufferSize, alignof(void *));
    703   memcpy(Mem, Buffer, BufferSize);
    704   return NestedNameSpecifierLoc(Representation, Mem);
    705 }
    706