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 *
FindOrInsert(const ASTContext & Context,const NestedNameSpecifier & Mockup)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 *
Create(const ASTContext & Context,NestedNameSpecifier * Prefix,IdentifierInfo * II)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 *
Create(const ASTContext & Context,NestedNameSpecifier * Prefix,const NamespaceDecl * NS)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 *
Create(const ASTContext & Context,NestedNameSpecifier * Prefix,NamespaceAliasDecl * Alias)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 *
Create(const ASTContext & Context,NestedNameSpecifier * Prefix,bool Template,const Type * T)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 *
Create(const ASTContext & Context,IdentifierInfo * II)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 *
GlobalSpecifier(const ASTContext & Context)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 *
SuperSpecifier(const ASTContext & Context,CXXRecordDecl * RD)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 
getKind() const143 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.
getAsNamespace() const169 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.
getAsNamespaceAlias() const177 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.
getAsRecordDecl() const185 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 
getDependence() const201 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 
isDependent() const234 bool NestedNameSpecifier::isDependent() const {
235   return getDependence() & NestedNameSpecifierDependence::Dependent;
236 }
237 
isInstantiationDependent() const238 bool NestedNameSpecifier::isInstantiationDependent() const {
239   return getDependence() & NestedNameSpecifierDependence::Instantiation;
240 }
241 
containsUnexpandedParameterPack() const242 bool NestedNameSpecifier::containsUnexpandedParameterPack() const {
243   return getDependence() & NestedNameSpecifierDependence::UnexpandedPack;
244 }
245 
containsErrors() const246 bool NestedNameSpecifier::containsErrors() const {
247   return getDependence() & NestedNameSpecifierDependence::Error;
248 }
249 
250 /// Print this nested name specifier to the given output
251 /// stream.
print(raw_ostream & OS,const PrintingPolicy & Policy,bool ResolveTemplateArguments) const252 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 
dump(const LangOptions & LO) const338 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(const LangOptions &LO) const {
339   dump(llvm::errs(), LO);
340 }
341 
dump() const342 LLVM_DUMP_METHOD void NestedNameSpecifier::dump() const { dump(llvm::errs()); }
343 
dump(llvm::raw_ostream & OS) const344 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS) const {
345   LangOptions LO;
346   dump(OS, LO);
347 }
348 
dump(llvm::raw_ostream & OS,const LangOptions & LO) const349 LLVM_DUMP_METHOD void NestedNameSpecifier::dump(llvm::raw_ostream &OS,
350                                                 const LangOptions &LO) const {
351   print(OS, PrintingPolicy(LO));
352 }
353 
354 unsigned
getLocalDataLength(NestedNameSpecifier * Qualifier)355 NestedNameSpecifierLoc::getLocalDataLength(NestedNameSpecifier *Qualifier) {
356   assert(Qualifier && "Expected a non-NULL qualifier");
357 
358   // Location of the trailing '::'.
359   unsigned Length = sizeof(SourceLocation::UIntTy);
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(SourceLocation::UIntTy);
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
getDataLength(NestedNameSpecifier * Qualifier)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.
LoadSourceLocation(void * Data,unsigned Offset)395 static SourceLocation LoadSourceLocation(void *Data, unsigned Offset) {
396   SourceLocation::UIntTy Raw;
397   memcpy(&Raw, static_cast<char *>(Data) + Offset, sizeof(Raw));
398   return SourceLocation::getFromRawEncoding(Raw);
399 }
400 
401 /// Load a (possibly unaligned) pointer from a given address and
402 /// offset.
LoadPointer(void * Data,unsigned 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 
getSourceRange() const409 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 
getLocalSourceRange() const421 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(
435         LoadSourceLocation(Data, Offset),
436         LoadSourceLocation(Data, Offset + sizeof(SourceLocation::UIntTy)));
437 
438   case NestedNameSpecifier::TypeSpecWithTemplate:
439   case NestedNameSpecifier::TypeSpec: {
440     // The "void*" that points at the TypeLoc data.
441     // Note: the 'template' keyword is part of the TypeLoc.
442     void *TypeData = LoadPointer(Data, Offset);
443     TypeLoc TL(Qualifier->getAsType(), TypeData);
444     return SourceRange(TL.getBeginLoc(),
445                        LoadSourceLocation(Data, Offset + sizeof(void*)));
446   }
447   }
448 
449   llvm_unreachable("Invalid NNS Kind!");
450 }
451 
getTypeLoc() const452 TypeLoc NestedNameSpecifierLoc::getTypeLoc() const {
453   if (Qualifier->getKind() != NestedNameSpecifier::TypeSpec &&
454       Qualifier->getKind() != NestedNameSpecifier::TypeSpecWithTemplate)
455     return TypeLoc();
456 
457   // The "void*" that points at the TypeLoc data.
458   unsigned Offset = getDataLength(Qualifier->getPrefix());
459   void *TypeData = LoadPointer(Data, Offset);
460   return TypeLoc(Qualifier->getAsType(), TypeData);
461 }
462 
Append(char * Start,char * End,char * & Buffer,unsigned & BufferSize,unsigned & BufferCapacity)463 static void Append(char *Start, char *End, char *&Buffer, unsigned &BufferSize,
464                    unsigned &BufferCapacity) {
465   if (Start == End)
466     return;
467 
468   if (BufferSize + (End - Start) > BufferCapacity) {
469     // Reallocate the buffer.
470     unsigned NewCapacity = std::max(
471         (unsigned)(BufferCapacity ? BufferCapacity * 2 : sizeof(void *) * 2),
472         (unsigned)(BufferSize + (End - Start)));
473     if (!BufferCapacity) {
474       char *NewBuffer = static_cast<char *>(llvm::safe_malloc(NewCapacity));
475       if (Buffer)
476         memcpy(NewBuffer, Buffer, BufferSize);
477       Buffer = NewBuffer;
478     } else {
479       Buffer = static_cast<char *>(llvm::safe_realloc(Buffer, NewCapacity));
480     }
481     BufferCapacity = NewCapacity;
482   }
483   assert(Buffer && Start && End && End > Start && "Illegal memory buffer copy");
484   memcpy(Buffer + BufferSize, Start, End - Start);
485   BufferSize += End - Start;
486 }
487 
488 /// Save a source location to the given buffer.
SaveSourceLocation(SourceLocation Loc,char * & Buffer,unsigned & BufferSize,unsigned & BufferCapacity)489 static void SaveSourceLocation(SourceLocation Loc, char *&Buffer,
490                                unsigned &BufferSize, unsigned &BufferCapacity) {
491   SourceLocation::UIntTy Raw = Loc.getRawEncoding();
492   Append(reinterpret_cast<char *>(&Raw),
493          reinterpret_cast<char *>(&Raw) + sizeof(Raw), Buffer, BufferSize,
494          BufferCapacity);
495 }
496 
497 /// Save a pointer to the given buffer.
SavePointer(void * Ptr,char * & Buffer,unsigned & BufferSize,unsigned & BufferCapacity)498 static void SavePointer(void *Ptr, char *&Buffer, unsigned &BufferSize,
499                         unsigned &BufferCapacity) {
500   Append(reinterpret_cast<char *>(&Ptr),
501          reinterpret_cast<char *>(&Ptr) + sizeof(void *),
502          Buffer, BufferSize, BufferCapacity);
503 }
504 
505 NestedNameSpecifierLocBuilder::
NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder & Other)506 NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other)
507     : Representation(Other.Representation) {
508   if (!Other.Buffer)
509     return;
510 
511   if (Other.BufferCapacity == 0) {
512     // Shallow copy is okay.
513     Buffer = Other.Buffer;
514     BufferSize = Other.BufferSize;
515     return;
516   }
517 
518   // Deep copy
519   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
520          BufferCapacity);
521 }
522 
523 NestedNameSpecifierLocBuilder &
524 NestedNameSpecifierLocBuilder::
operator =(const NestedNameSpecifierLocBuilder & Other)525 operator=(const NestedNameSpecifierLocBuilder &Other) {
526   Representation = Other.Representation;
527 
528   if (Buffer && Other.Buffer && BufferCapacity >= Other.BufferSize) {
529     // Re-use our storage.
530     BufferSize = Other.BufferSize;
531     memcpy(Buffer, Other.Buffer, BufferSize);
532     return *this;
533   }
534 
535   // Free our storage, if we have any.
536   if (BufferCapacity) {
537     free(Buffer);
538     BufferCapacity = 0;
539   }
540 
541   if (!Other.Buffer) {
542     // Empty.
543     Buffer = nullptr;
544     BufferSize = 0;
545     return *this;
546   }
547 
548   if (Other.BufferCapacity == 0) {
549     // Shallow copy is okay.
550     Buffer = Other.Buffer;
551     BufferSize = Other.BufferSize;
552     return *this;
553   }
554 
555   // Deep copy.
556   BufferSize = 0;
557   Append(Other.Buffer, Other.Buffer + Other.BufferSize, Buffer, BufferSize,
558          BufferCapacity);
559   return *this;
560 }
561 
Extend(ASTContext & Context,SourceLocation TemplateKWLoc,TypeLoc TL,SourceLocation ColonColonLoc)562 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
563                                            SourceLocation TemplateKWLoc,
564                                            TypeLoc TL,
565                                            SourceLocation ColonColonLoc) {
566   Representation = NestedNameSpecifier::Create(Context, Representation,
567                                                TemplateKWLoc.isValid(),
568                                                TL.getTypePtr());
569 
570   // Push source-location info into the buffer.
571   SavePointer(TL.getOpaqueData(), Buffer, BufferSize, BufferCapacity);
572   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
573 }
574 
Extend(ASTContext & Context,IdentifierInfo * Identifier,SourceLocation IdentifierLoc,SourceLocation ColonColonLoc)575 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
576                                            IdentifierInfo *Identifier,
577                                            SourceLocation IdentifierLoc,
578                                            SourceLocation ColonColonLoc) {
579   Representation = NestedNameSpecifier::Create(Context, Representation,
580                                                Identifier);
581 
582   // Push source-location info into the buffer.
583   SaveSourceLocation(IdentifierLoc, Buffer, BufferSize, BufferCapacity);
584   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
585 }
586 
Extend(ASTContext & Context,NamespaceDecl * Namespace,SourceLocation NamespaceLoc,SourceLocation ColonColonLoc)587 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
588                                            NamespaceDecl *Namespace,
589                                            SourceLocation NamespaceLoc,
590                                            SourceLocation ColonColonLoc) {
591   Representation = NestedNameSpecifier::Create(Context, Representation,
592                                                Namespace);
593 
594   // Push source-location info into the buffer.
595   SaveSourceLocation(NamespaceLoc, Buffer, BufferSize, BufferCapacity);
596   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
597 }
598 
Extend(ASTContext & Context,NamespaceAliasDecl * Alias,SourceLocation AliasLoc,SourceLocation ColonColonLoc)599 void NestedNameSpecifierLocBuilder::Extend(ASTContext &Context,
600                                            NamespaceAliasDecl *Alias,
601                                            SourceLocation AliasLoc,
602                                            SourceLocation ColonColonLoc) {
603   Representation = NestedNameSpecifier::Create(Context, Representation, Alias);
604 
605   // Push source-location info into the buffer.
606   SaveSourceLocation(AliasLoc, Buffer, BufferSize, BufferCapacity);
607   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
608 }
609 
MakeGlobal(ASTContext & Context,SourceLocation ColonColonLoc)610 void NestedNameSpecifierLocBuilder::MakeGlobal(ASTContext &Context,
611                                                SourceLocation ColonColonLoc) {
612   assert(!Representation && "Already have a nested-name-specifier!?");
613   Representation = NestedNameSpecifier::GlobalSpecifier(Context);
614 
615   // Push source-location info into the buffer.
616   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
617 }
618 
MakeSuper(ASTContext & Context,CXXRecordDecl * RD,SourceLocation SuperLoc,SourceLocation ColonColonLoc)619 void NestedNameSpecifierLocBuilder::MakeSuper(ASTContext &Context,
620                                               CXXRecordDecl *RD,
621                                               SourceLocation SuperLoc,
622                                               SourceLocation ColonColonLoc) {
623   Representation = NestedNameSpecifier::SuperSpecifier(Context, RD);
624 
625   // Push source-location info into the buffer.
626   SaveSourceLocation(SuperLoc, Buffer, BufferSize, BufferCapacity);
627   SaveSourceLocation(ColonColonLoc, Buffer, BufferSize, BufferCapacity);
628 }
629 
MakeTrivial(ASTContext & Context,NestedNameSpecifier * Qualifier,SourceRange R)630 void NestedNameSpecifierLocBuilder::MakeTrivial(ASTContext &Context,
631                                                 NestedNameSpecifier *Qualifier,
632                                                 SourceRange R) {
633   Representation = Qualifier;
634 
635   // Construct bogus (but well-formed) source information for the
636   // nested-name-specifier.
637   BufferSize = 0;
638   SmallVector<NestedNameSpecifier *, 4> Stack;
639   for (NestedNameSpecifier *NNS = Qualifier; NNS; NNS = NNS->getPrefix())
640     Stack.push_back(NNS);
641   while (!Stack.empty()) {
642     NestedNameSpecifier *NNS = Stack.pop_back_val();
643     switch (NNS->getKind()) {
644       case NestedNameSpecifier::Identifier:
645       case NestedNameSpecifier::Namespace:
646       case NestedNameSpecifier::NamespaceAlias:
647         SaveSourceLocation(R.getBegin(), Buffer, BufferSize, BufferCapacity);
648         break;
649 
650       case NestedNameSpecifier::TypeSpec:
651       case NestedNameSpecifier::TypeSpecWithTemplate: {
652         TypeSourceInfo *TSInfo
653         = Context.getTrivialTypeSourceInfo(QualType(NNS->getAsType(), 0),
654                                            R.getBegin());
655         SavePointer(TSInfo->getTypeLoc().getOpaqueData(), Buffer, BufferSize,
656                     BufferCapacity);
657         break;
658       }
659 
660       case NestedNameSpecifier::Global:
661       case NestedNameSpecifier::Super:
662         break;
663     }
664 
665     // Save the location of the '::'.
666     SaveSourceLocation(Stack.empty()? R.getEnd() : R.getBegin(),
667                        Buffer, BufferSize, BufferCapacity);
668   }
669 }
670 
Adopt(NestedNameSpecifierLoc Other)671 void NestedNameSpecifierLocBuilder::Adopt(NestedNameSpecifierLoc Other) {
672   if (BufferCapacity)
673     free(Buffer);
674 
675   if (!Other) {
676     Representation = nullptr;
677     BufferSize = 0;
678     return;
679   }
680 
681   // Rather than copying the data (which is wasteful), "adopt" the
682   // pointer (which points into the ASTContext) but set the capacity to zero to
683   // indicate that we don't own it.
684   Representation = Other.getNestedNameSpecifier();
685   Buffer = static_cast<char *>(Other.getOpaqueData());
686   BufferSize = Other.getDataLength();
687   BufferCapacity = 0;
688 }
689 
690 NestedNameSpecifierLoc
getWithLocInContext(ASTContext & Context) const691 NestedNameSpecifierLocBuilder::getWithLocInContext(ASTContext &Context) const {
692   if (!Representation)
693     return NestedNameSpecifierLoc();
694 
695   // If we adopted our data pointer from elsewhere in the AST context, there's
696   // no need to copy the memory.
697   if (BufferCapacity == 0)
698     return NestedNameSpecifierLoc(Representation, Buffer);
699 
700   // FIXME: After copying the source-location information, should we free
701   // our (temporary) buffer and adopt the ASTContext-allocated memory?
702   // Doing so would optimize repeated calls to getWithLocInContext().
703   void *Mem = Context.Allocate(BufferSize, alignof(void *));
704   memcpy(Mem, Buffer, BufferSize);
705   return NestedNameSpecifierLoc(Representation, Mem);
706 }
707