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