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 /// Print this nested name specifier to the given output
247 /// stream.
248 void NestedNameSpecifier::print(raw_ostream &OS, const PrintingPolicy &Policy,
249                                 bool ResolveTemplateArguments) const {
250   if (getPrefix())
251     getPrefix()->print(OS, Policy);
252 
253   switch (getKind()) {
254   case Identifier:
255     OS << getAsIdentifier()->getName();
256     break;
257 
258   case Namespace:
259     if (getAsNamespace()->isAnonymousNamespace())
260       return;
261 
262     OS << getAsNamespace()->getName();
263     break;
264 
265   case NamespaceAlias:
266     OS << getAsNamespaceAlias()->getName();
267     break;
268 
269   case Global:
270     break;
271 
272   case Super:
273     OS << "__super";
274     break;
275 
276   case TypeSpecWithTemplate:
277     OS << "template ";
278     // Fall through to print the type.
279     LLVM_FALLTHROUGH;
280 
281   case TypeSpec: {
282     const auto *Record =
283             dyn_cast_or_null<ClassTemplateSpecializationDecl>(getAsRecordDecl());
284     if (ResolveTemplateArguments && Record) {
285         // Print the type trait with resolved template parameters.
286         Record->printName(OS);
287         printTemplateArgumentList(OS, Record->getTemplateArgs().asArray(),
288                                   Policy);
289         break;
290     }
291     const Type *T = getAsType();
292 
293     PrintingPolicy InnerPolicy(Policy);
294     InnerPolicy.SuppressScope = true;
295 
296     // Nested-name-specifiers are intended to contain minimally-qualified
297     // types. An actual ElaboratedType will not occur, since we'll store
298     // just the type that is referred to in the nested-name-specifier (e.g.,
299     // a TypedefType, TagType, etc.). However, when we are dealing with
300     // dependent template-id types (e.g., Outer<T>::template Inner<U>),
301     // the type requires its own nested-name-specifier for uniqueness, so we
302     // suppress that nested-name-specifier during printing.
303     assert(!isa<ElaboratedType>(T) &&
304            "Elaborated type in nested-name-specifier");
305     if (const TemplateSpecializationType *SpecType
306           = dyn_cast<TemplateSpecializationType>(T)) {
307       // Print the template name without its corresponding
308       // nested-name-specifier.
309       SpecType->getTemplateName().print(OS, InnerPolicy, true);
310 
311       // Print the template argument list.
312       printTemplateArgumentList(OS, SpecType->template_arguments(),
313                                 InnerPolicy);
314     } else {
315       // Print the type normally
316       QualType(T, 0).print(OS, InnerPolicy);
317     }
318     break;
319   }
320   }
321 
322   OS << "::";
323 }
324 
325 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(const LangOptions &LO) const {
326   dump(llvm::errs(), LO);
327 }
328 
329 LLVM_DUMP_METHOD void NestedNameSpecifier::dump() const { dump(llvm::errs()); }
330 
331 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS) const {
332   LangOptions LO;
333   dump(OS, LO);
334 }
335 
336 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS,
337                                                 const LangOptions &LO) const {
338   print(OS, PrintingPolicy(LO));
339 }
340 
341 unsigned
342 NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) {
343   assert(Qualifier && "Expected a non-NULL qualifier");
344 
345   // Location of the trailing '::'.
346   unsigned Length = sizeof(unsigned);
347 
348   switch (Qualifier->getKind()) {
349   case NestedNameSpecifier::Global:
350     // Nothing more to add.
351     break;
352 
353   case NestedNameSpecifier::Identifier:
354   case NestedNameSpecifier::Namespace:
355   case NestedNameSpecifier::NamespaceAlias:
356   case NestedNameSpecifier::Super:
357     // The location of the identifier or namespace name.
358     Length += sizeof(unsigned);
359     break;
360 
361   case NestedNameSpecifier::TypeSpecWithTemplate:
362   case NestedNameSpecifier::TypeSpec:
363     // The "void*" that points at the TypeLoc data.
364     // Note: the 'template' keyword is part of the TypeLoc.
365     Length += sizeof(void *);
366     break;
367   }
368 
369   return Length;
370 }
371 
372 unsigned
373 NestedNameSpecifierLoc::getDataLength(NestedNameSpecifier *Qualifier) {
374   unsigned Length = 0;
375   for (; Qualifier; Qualifier = Qualifier->getPrefix())
376     Length += getLocalDataLength(Qualifier);
377   return Length;
378 }
379 
380 /// Load a (possibly unaligned) source location from a given address
381 /// and offset.
382 static SourceLocation LoadSourceLocation(void *Data, unsigned Offset) {
383   unsigned Raw;
384   memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(unsigned));
385   return SourceLocation::getFromRawEncoding(Raw);
386 }
387 
388 /// Load a (possibly unaligned) pointer from a given address and
389 /// offset.
390 static void *LoadPointer(void *Data, unsigned Offset) {
391   void *Result;
392   memcpy(&Result, static_cast<char *>(Data) + Offset, sizeof(void*));
393   return Result;
394 }
395 
396 SourceRange NestedNameSpecifierLoc::getSourceRange() const {
397   if (!Qualifier)
398     return SourceRange();
399 
400   NestedNameSpecifierLoc First = *this;
401   while (NestedNameSpecifierLoc Prefix = First.getPrefix())
402     First = Prefix;
403 
404   return SourceRange(First.getLocalSourceRange().getBegin(),
405                      getLocalSourceRange().getEnd());
406 }
407 
408 SourceRange NestedNameSpecifierLoc::getLocalSourceRange() const {
409   if (!Qualifier)
410     return SourceRange();
411 
412   unsigned Offset = getDataLength(Qualifier->getPrefix());
413   switch (Qualifier->getKind()) {
414   case NestedNameSpecifier::Global:
415     return LoadSourceLocation(Data, Offset);
416 
417   case NestedNameSpecifier::Identifier:
418   case NestedNameSpecifier::Namespace:
419   case NestedNameSpecifier::NamespaceAlias:
420   case NestedNameSpecifier::Super:
421     return SourceRange(LoadSourceLocation(Data, Offset),
422                        LoadSourceLocation(Data, Offset + sizeof(unsigned)));
423 
424   case NestedNameSpecifier::TypeSpecWithTemplate:
425   case NestedNameSpecifier::TypeSpec: {
426     // The "void*" that points at the TypeLoc data.
427     // Note: the 'template' keyword is part of the TypeLoc.
428     void *TypeData = LoadPointer(Data, Offset);
429     TypeLoc TL(Qualifier->getAsType(), TypeData);
430     return SourceRange(TL.getBeginLoc(),
431                        LoadSourceLocation(Data, Offset + sizeof(void*)));
432   }
433   }
434 
435   llvm_unreachable("Invalid NNS Kind!");
436 }
437 
438 TypeLoc NestedNameSpecifierLoc::getTypeLoc() const {
439   if (Qualifier->getKind() != NestedNameSpecifier::TypeSpec &&
440       Qualifier->getKind() != NestedNameSpecifier::TypeSpecWithTemplate)
441     return TypeLoc();
442 
443   // The "void*" that points at the TypeLoc data.
444   unsigned Offset = getDataLength(Qualifier->getPrefix());
445   void *TypeData = LoadPointer(Data, Offset);
446   return TypeLoc(Qualifier->getAsType(), TypeData);
447 }
448 
449 static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize,
450                    unsigned &BufferCapacity) {
451   if (Start == End)
452     return;
453 
454   if (BufferSize + (End - Start) > BufferCapacity) {
455     // Reallocate the buffer.
456     unsigned NewCapacity = std::max(
457         (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2),
458         (unsigned)(BufferSize + (End - Start)));
459     char *NewBuffer = static_cast<char *>(llvm::safe_malloc(NewCapacity));
460     if (Buffer) {
461       memcpy(NewBuffer, Buffer, BufferSize);
462       if (BufferCapacity)
463         free(Buffer);
464     }
465     Buffer = NewBuffer;
466     BufferCapacity = NewCapacity;
467   }
468   assert(Buffer && Start && End && End > Start && "Illegal memory buffer copy");
469   memcpy(Buffer + BufferSize, Start, End - Start);
470   BufferSize += End - Start;
471 }
472 
473 /// Save a source location to the given buffer.
474 static void SaveSourceLocation(SourceLocation Loc, char *&Buffer,
475                                unsigned &BufferSize, unsigned &BufferCapacity) {
476   unsigned Raw = Loc.getRawEncoding();
477   Append(reinterpret_cast<char *>(&Raw),
478          reinterpret_cast<char *>(&Raw) + sizeof(unsigned),
479          Buffer, BufferSize, BufferCapacity);
480 }
481 
482 /// Save a pointer to the given buffer.
483 static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize,
484                         unsigned &BufferCapacity) {
485   Append(reinterpret_cast<char *>(&Ptr),
486          reinterpret_cast<char *>(&Ptr) + sizeof(void *),
487          Buffer, BufferSize, BufferCapacity);
488 }
489 
490 NestedNameSpecifierLocBuilder::
491 NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)
492     : Representation(Other.Representation) {
493   if (!Other.Buffer)
494     return;
495 
496   if (Other.BufferCapacity == 0) {
497     // Shallow copy is okay.
498     Buffer = Other.Buffer;
499     BufferSize = Other.BufferSize;
500     return;
501   }
502 
503   // Deep copy
504   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
505          BufferCapacity);
506 }
507 
508 NestedNameSpecifierLocBuilder &
509 NestedNameSpecifierLocBuilder::
510 operator=(const NestedNameSpecifierLocBuilder &Other) {
511   Representation = Other.Representation;
512 
513   if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) {
514     // Re-use our storage.
515     BufferSize = Other.BufferSize;
516     memcpy(Buffer, Other.Buffer, BufferSize);
517     return *this;
518   }
519 
520   // Free our storage, if we have any.
521   if (BufferCapacity) {
522     free(Buffer);
523     BufferCapacity = 0;
524   }
525 
526   if (!Other.Buffer) {
527     // Empty.
528     Buffer = nullptr;
529     BufferSize = 0;
530     return *this;
531   }
532 
533   if (Other.BufferCapacity == 0) {
534     // Shallow copy is okay.
535     Buffer = Other.Buffer;
536     BufferSize = Other.BufferSize;
537     return *this;
538   }
539 
540   // Deep copy.
541   BufferSize = 0;
542   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
543          BufferCapacity);
544   return *this;
545 }
546 
547 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
548                                            SourceLocation TemplateKWLoc,
549                                            TypeLoc TL,
550                                            SourceLocation ColonColonLoc) {
551   Representation = NestedNameSpecifier::Create(Context, Representation,
552                                                TemplateKWLoc.isValid(),
553                                                TL.getTypePtr());
554 
555   // Push source-location info into the buffer.
556   SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity);
557   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
558 }
559 
560 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
561                                            IdentifierInfo *Identifier,
562                                            SourceLocation IdentifierLoc,
563                                            SourceLocation ColonColonLoc) {
564   Representation = NestedNameSpecifier::Create(Context, Representation,
565                                                Identifier);
566 
567   // Push source-location info into the buffer.
568   SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity);
569   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
570 }
571 
572 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
573                                            NamespaceDecl *Namespace,
574                                            SourceLocation NamespaceLoc,
575                                            SourceLocation ColonColonLoc) {
576   Representation = NestedNameSpecifier::Create(Context, Representation,
577                                                Namespace);
578 
579   // Push source-location info into the buffer.
580   SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity);
581   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
582 }
583 
584 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
585                                            NamespaceAliasDecl *Alias,
586                                            SourceLocation AliasLoc,
587                                            SourceLocation ColonColonLoc) {
588   Representation = NestedNameSpecifier::Create(Context, Representation, Alias);
589 
590   // Push source-location info into the buffer.
591   SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity);
592   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
593 }
594 
595 void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context,
596                                                SourceLocation ColonColonLoc) {
597   assert(!Representation && "Already have a nested-name-specifier!?");
598   Representation = NestedNameSpecifier::GlobalSpecifier(Context);
599 
600   // Push source-location info into the buffer.
601   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
602 }
603 
604 void NestedNameSpecifierLocBuilder::MakeSuper(ASTContext &Context,
605                                               CXXRecordDecl *RD,
606                                               SourceLocation SuperLoc,
607                                               SourceLocation ColonColonLoc) {
608   Representation = NestedNameSpecifier::SuperSpecifier(Context, RD);
609 
610   // Push source-location info into the buffer.
611   SaveSourceLocation(SuperLoc, Buffer, BufferSize, BufferCapacity);
612   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
613 }
614 
615 void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context,
616                                                 NestedNameSpecifier *Qualifier,
617                                                 SourceRange R) {
618   Representation = Qualifier;
619 
620   // Construct bogus (but well-formed) source information for the
621   // nested-name-specifier.
622   BufferSize = 0;
623   SmallVector<NestedNameSpecifier *, 4> Stack;
624   for (NestedNameSpecifier *NNS = Qualifier; NNS; NNS = NNS->getPrefix())
625     Stack.push_back(NNS);
626   while (!Stack.empty()) {
627     NestedNameSpecifier *NNS = Stack.pop_back_val();
628     switch (NNS->getKind()) {
629       case NestedNameSpecifier::Identifier:
630       case NestedNameSpecifier::Namespace:
631       case NestedNameSpecifier::NamespaceAlias:
632         SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity);
633         break;
634 
635       case NestedNameSpecifier::TypeSpec:
636       case NestedNameSpecifier::TypeSpecWithTemplate: {
637         TypeSourceInfo *TSInfo
638         = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0),
639                                            R.getBegin());
640         SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize,
641                     BufferCapacity);
642         break;
643       }
644 
645       case NestedNameSpecifier::Global:
646       case NestedNameSpecifier::Super:
647         break;
648     }
649 
650     // Save the location of the '::'.
651     SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(),
652                        Buffer, BufferSize, BufferCapacity);
653   }
654 }
655 
656 void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) {
657   if (BufferCapacity)
658     free(Buffer);
659 
660   if (!Other) {
661     Representation = nullptr;
662     BufferSize = 0;
663     return;
664   }
665 
666   // Rather than copying the data (which is wasteful), "adopt" the
667   // pointer (which points into the ASTContext) but set the capacity to zero to
668   // indicate that we don't own it.
669   Representation = Other.getNestedNameSpecifier();
670   Buffer = static_cast<char *>(Other.getOpaqueData());
671   BufferSize = Other.getDataLength();
672   BufferCapacity = 0;
673 }
674 
675 NestedNameSpecifierLoc
676 NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const {
677   if (!Representation)
678     return NestedNameSpecifierLoc();
679 
680   // If we adopted our data pointer from elsewhere in the AST context, there's
681   // no need to copy the memory.
682   if (BufferCapacity == 0)
683     return NestedNameSpecifierLoc(Representation, Buffer);
684 
685   // FIXME: After copying the source-location information, should we free
686   // our (temporary) buffer and adopt the ASTContext-allocated memory?
687   // Doing so would optimize repeated calls to getWithLocInContext().
688   void *Mem = Context.Allocate(BufferSize, alignof(void *));
689   memcpy(Mem, Buffer, BufferSize);
690   return NestedNameSpecifierLoc(Representation, Mem);
691 }
692