1 //===- USRGeneration.cpp - Routines for USR generation --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Index/USRGeneration.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/DeclTemplate.h"
13 #include "clang/AST/DeclVisitor.h"
14 #include "clang/Lex/PreprocessingRecord.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/raw_ostream.h"
18 using namespace clang;
19 using namespace clang::index;
21 //===----------------------------------------------------------------------===//
23 //===----------------------------------------------------------------------===//
25 /// \returns true on error.
26 static bool printLoc(llvm::raw_ostream &OS, SourceLocation Loc,
27 const SourceManager &SM, bool IncludeOffset) {
28 if (Loc.isInvalid()) {
31 Loc = SM.getExpansionLoc(Loc);
32 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(Loc);
33 const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
35 OS << llvm::sys::path::filename(FE->getName());
37 // This case really isn't interesting.
41 // Use the offest into the FileID to represent the location. Using
42 // a line/column can cause us to look back at the original source file,
43 // which is expensive.
44 OS << '@' << Decomposed.second;
49 static StringRef GetExternalSourceContainer(const NamedDecl *D) {
52 if (auto *attr = D->getExternalSourceSymbolAttr()) {
53 return attr->getDefinedIn();
59 class USRGenerator : public ConstDeclVisitor<USRGenerator> {
60 SmallVectorImpl<char> &Buf;
61 llvm::raw_svector_ostream Out;
66 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
69 explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf)
76 // Add the USR space prefix.
77 Out << getUSRSpacePrefix();
80 bool ignoreResults() const { return IgnoreResults; }
82 // Visitation methods from generating USRs from AST elements.
83 void VisitDeclContext(const DeclContext *D);
84 void VisitFieldDecl(const FieldDecl *D);
85 void VisitFunctionDecl(const FunctionDecl *D);
86 void VisitNamedDecl(const NamedDecl *D);
87 void VisitNamespaceDecl(const NamespaceDecl *D);
88 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
89 void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
90 void VisitClassTemplateDecl(const ClassTemplateDecl *D);
91 void VisitObjCContainerDecl(const ObjCContainerDecl *CD,
92 const ObjCCategoryDecl *CatD = nullptr);
93 void VisitObjCMethodDecl(const ObjCMethodDecl *MD);
94 void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
95 void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
96 void VisitTagDecl(const TagDecl *D);
97 void VisitTypedefDecl(const TypedefDecl *D);
98 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
99 void VisitVarDecl(const VarDecl *D);
100 void VisitBindingDecl(const BindingDecl *D);
101 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
102 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
103 void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
104 void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
106 void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
107 IgnoreResults = true; // No USRs for linkage specs themselves.
110 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
111 IgnoreResults = true;
114 void VisitUsingDecl(const UsingDecl *D) {
115 IgnoreResults = true;
118 bool ShouldGenerateLocation(const NamedDecl *D);
120 bool isLocal(const NamedDecl *D) {
121 return D->getParentFunctionOrMethod() != nullptr;
124 void GenExtSymbolContainer(const NamedDecl *D);
126 /// Generate the string component containing the location of the
128 bool GenLoc(const Decl *D, bool IncludeOffset);
130 /// String generation methods used both by the visitation methods
131 /// and from other clients that want to directly generate USRs. These
132 /// methods do not construct complete USRs (which incorporate the parents
133 /// of an AST element), but only the fragments concerning the AST element
136 /// Generate a USR for an Objective-C class.
137 void GenObjCClass(StringRef cls, StringRef ExtSymDefinedIn,
138 StringRef CategoryContextExtSymbolDefinedIn) {
139 generateUSRForObjCClass(cls, Out, ExtSymDefinedIn,
140 CategoryContextExtSymbolDefinedIn);
143 /// Generate a USR for an Objective-C class category.
144 void GenObjCCategory(StringRef cls, StringRef cat,
145 StringRef clsExt, StringRef catExt) {
146 generateUSRForObjCCategory(cls, cat, Out, clsExt, catExt);
149 /// Generate a USR fragment for an Objective-C property.
150 void GenObjCProperty(StringRef prop, bool isClassProp) {
151 generateUSRForObjCProperty(prop, isClassProp, Out);
154 /// Generate a USR for an Objective-C protocol.
155 void GenObjCProtocol(StringRef prot, StringRef ext) {
156 generateUSRForObjCProtocol(prot, Out, ext);
159 void VisitType(QualType T);
160 void VisitTemplateParameterList(const TemplateParameterList *Params);
161 void VisitTemplateName(TemplateName Name);
162 void VisitTemplateArgument(const TemplateArgument &Arg);
164 /// Emit a Decl's name using NamedDecl::printName() and return true if
165 /// the decl had no name.
166 bool EmitDeclName(const NamedDecl *D);
168 } // end anonymous namespace
170 //===----------------------------------------------------------------------===//
171 // Generating USRs from ASTS.
172 //===----------------------------------------------------------------------===//
174 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
175 const unsigned startSize = Buf.size();
177 const unsigned endSize = Buf.size();
178 return startSize == endSize;
181 bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
182 if (D->isExternallyVisible())
184 if (D->getParentFunctionOrMethod())
186 SourceLocation Loc = D->getLocation();
189 const SourceManager &SM = Context->getSourceManager();
190 return !SM.isInSystemHeader(Loc);
193 void USRGenerator::VisitDeclContext(const DeclContext *DC) {
194 if (const NamedDecl *D = dyn_cast<NamedDecl>(DC))
196 else if (isa<LinkageSpecDecl>(DC)) // Linkage specs are transparent in USRs.
197 VisitDeclContext(DC->getParent());
200 void USRGenerator::VisitFieldDecl(const FieldDecl *D) {
201 // The USR for an ivar declared in a class extension is based on the
202 // ObjCInterfaceDecl, not the ObjCCategoryDecl.
203 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
206 VisitDeclContext(D->getDeclContext());
207 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
208 if (EmitDeclName(D)) {
209 // Bit fields can be anonymous.
210 IgnoreResults = true;
215 void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) {
216 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
219 const unsigned StartSize = Buf.size();
220 VisitDeclContext(D->getDeclContext());
221 if (Buf.size() == StartSize)
222 GenExtSymbolContainer(D);
224 bool IsTemplate = false;
225 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
228 VisitTemplateParameterList(FunTmpl->getTemplateParameters());
232 PrintingPolicy Policy(Context->getLangOpts());
233 // Forward references can have different template argument names. Suppress the
234 // template argument names in constructors to make their USR more stable.
235 Policy.SuppressTemplateArgsInCXXConstructors = true;
236 D->getDeclName().print(Out, Policy);
238 ASTContext &Ctx = *Context;
239 if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) &&
240 !D->hasAttr<OverloadableAttr>())
243 if (const TemplateArgumentList *
244 SpecArgs = D->getTemplateSpecializationArgs()) {
246 for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
248 VisitTemplateArgument(SpecArgs->get(I));
253 // Mangle in type information for the arguments.
254 for (auto PD : D->parameters()) {
256 VisitType(PD->getType());
261 // Function templates can be overloaded by return type, for example:
263 // template <class T> typename T::A foo() {}
264 // template <class T> typename T::B foo() {}
267 VisitType(D->getReturnType());
270 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
273 // FIXME: OpenCL: Need to consider address spaces
274 if (unsigned quals = MD->getTypeQualifiers().getCVRUQualifiers())
275 Out << (char)('0' + quals);
276 switch (MD->getRefQualifier()) {
278 case RQ_LValue: Out << '&'; break;
279 case RQ_RValue: Out << "&&"; break;
284 void USRGenerator::VisitNamedDecl(const NamedDecl *D) {
285 VisitDeclContext(D->getDeclContext());
288 if (EmitDeclName(D)) {
289 // The string can be empty if the declaration has no name; e.g., it is
290 // the ParmDecl with no name for declaration of a function pointer type,
291 // e.g.: void (*f)(void *);
292 // In this case, don't generate a USR.
293 IgnoreResults = true;
297 void USRGenerator::VisitVarDecl(const VarDecl *D) {
298 // VarDecls can be declared 'extern' within a function or method body,
299 // but their enclosing DeclContext is the function, not the TU. We need
300 // to check the storage class to correctly generate the USR.
301 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
304 VisitDeclContext(D->getDeclContext());
306 if (VarTemplateDecl *VarTmpl = D->getDescribedVarTemplate()) {
308 VisitTemplateParameterList(VarTmpl->getTemplateParameters());
309 } else if (const VarTemplatePartialSpecializationDecl *PartialSpec
310 = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
312 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
315 // Variables always have simple names.
316 StringRef s = D->getName();
318 // The string can be empty if the declaration has no name; e.g., it is
319 // the ParmDecl with no name for declaration of a function pointer type, e.g.:
320 // void (*f)(void *);
321 // In this case, don't generate a USR.
323 IgnoreResults = true;
327 // For a template specialization, mangle the template arguments.
328 if (const VarTemplateSpecializationDecl *Spec
329 = dyn_cast<VarTemplateSpecializationDecl>(D)) {
330 const TemplateArgumentList &Args = Spec->getTemplateArgs();
332 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
334 VisitTemplateArgument(Args.get(I));
339 void USRGenerator::VisitBindingDecl(const BindingDecl *D) {
340 if (isLocal(D) && GenLoc(D, /*IncludeOffset=*/true))
345 void USRGenerator::VisitNonTypeTemplateParmDecl(
346 const NonTypeTemplateParmDecl *D) {
347 GenLoc(D, /*IncludeOffset=*/true);
350 void USRGenerator::VisitTemplateTemplateParmDecl(
351 const TemplateTemplateParmDecl *D) {
352 GenLoc(D, /*IncludeOffset=*/true);
355 void USRGenerator::VisitNamespaceDecl(const NamespaceDecl *D) {
356 if (D->isAnonymousNamespace()) {
361 VisitDeclContext(D->getDeclContext());
363 Out << "@N@" << D->getName();
366 void USRGenerator::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
367 VisitFunctionDecl(D->getTemplatedDecl());
370 void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
371 VisitTagDecl(D->getTemplatedDecl());
374 void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
375 VisitDeclContext(D->getDeclContext());
377 Out << "@NA@" << D->getName();
380 void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
381 const DeclContext *container = D->getDeclContext();
382 if (const ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
386 // The USR for a method declared in a class extension or category is based on
387 // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
388 const ObjCInterfaceDecl *ID = D->getClassInterface();
390 IgnoreResults = true;
393 auto getCategoryContext = [](const ObjCMethodDecl *D) ->
394 const ObjCCategoryDecl * {
395 if (auto *CD = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
397 if (auto *ICD = dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
398 return ICD->getCategoryDecl();
401 auto *CD = getCategoryContext(D);
402 VisitObjCContainerDecl(ID, CD);
404 // Ideally we would use 'GenObjCMethod', but this is such a hot path
405 // for Objective-C code that we don't want to use
406 // DeclarationName::getAsString().
407 Out << (D->isInstanceMethod() ? "(im)" : "(cm)")
408 << DeclarationName(D->getSelector());
411 void USRGenerator::VisitObjCContainerDecl(const ObjCContainerDecl *D,
412 const ObjCCategoryDecl *CatD) {
413 switch (D->getKind()) {
415 llvm_unreachable("Invalid ObjC container.");
416 case Decl::ObjCInterface:
417 case Decl::ObjCImplementation:
418 GenObjCClass(D->getName(), GetExternalSourceContainer(D),
419 GetExternalSourceContainer(CatD));
421 case Decl::ObjCCategory: {
422 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
423 const ObjCInterfaceDecl *ID = CD->getClassInterface();
425 // Handle invalid code where the @interface might not
426 // have been specified.
427 // FIXME: We should be able to generate this USR even if the
428 // @interface isn't available.
429 IgnoreResults = true;
432 // Specially handle class extensions, which are anonymous categories.
433 // We want to mangle in the location to uniquely distinguish them.
434 if (CD->IsClassExtension()) {
435 Out << "objc(ext)" << ID->getName() << '@';
436 GenLoc(CD, /*IncludeOffset=*/true);
439 GenObjCCategory(ID->getName(), CD->getName(),
440 GetExternalSourceContainer(ID),
441 GetExternalSourceContainer(CD));
445 case Decl::ObjCCategoryImpl: {
446 const ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
447 const ObjCInterfaceDecl *ID = CD->getClassInterface();
449 // Handle invalid code where the @interface might not
450 // have been specified.
451 // FIXME: We should be able to generate this USR even if the
452 // @interface isn't available.
453 IgnoreResults = true;
456 GenObjCCategory(ID->getName(), CD->getName(),
457 GetExternalSourceContainer(ID),
458 GetExternalSourceContainer(CD));
461 case Decl::ObjCProtocol: {
462 const ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
463 GenObjCProtocol(PD->getName(), GetExternalSourceContainer(PD));
469 void USRGenerator::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
470 // The USR for a property declared in a class extension or category is based
471 // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
472 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
475 Visit(cast<Decl>(D->getDeclContext()));
476 GenObjCProperty(D->getName(), D->isClassProperty());
479 void USRGenerator::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
480 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
481 VisitObjCPropertyDecl(PD);
485 IgnoreResults = true;
488 void USRGenerator::VisitTagDecl(const TagDecl *D) {
489 // Add the location of the tag decl to handle resolution across
490 // translation units.
491 if (!isa<EnumDecl>(D) &&
492 ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
495 GenExtSymbolContainer(D);
497 D = D->getCanonicalDecl();
498 VisitDeclContext(D->getDeclContext());
500 bool AlreadyStarted = false;
501 if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
502 if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
503 AlreadyStarted = true;
505 switch (D->getTagKind()) {
508 case TTK_Struct: Out << "@ST"; break;
509 case TTK_Union: Out << "@UT"; break;
510 case TTK_Enum: llvm_unreachable("enum template");
512 VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
513 } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec
514 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
515 AlreadyStarted = true;
517 switch (D->getTagKind()) {
520 case TTK_Struct: Out << "@SP"; break;
521 case TTK_Union: Out << "@UP"; break;
522 case TTK_Enum: llvm_unreachable("enum partial specialization");
524 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
528 if (!AlreadyStarted) {
529 switch (D->getTagKind()) {
532 case TTK_Struct: Out << "@S"; break;
533 case TTK_Union: Out << "@U"; break;
534 case TTK_Enum: Out << "@E"; break;
539 assert(Buf.size() > 0);
540 const unsigned off = Buf.size() - 1;
542 if (EmitDeclName(D)) {
543 if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
548 if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
549 printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
552 if (auto *ED = dyn_cast<EnumDecl>(D)) {
553 // Distinguish USRs of anonymous enums by using their first enumerator.
554 auto enum_range = ED->enumerators();
555 if (enum_range.begin() != enum_range.end()) {
556 Out << '@' << **enum_range.begin();
563 // For a class template specialization, mangle the template arguments.
564 if (const ClassTemplateSpecializationDecl *Spec
565 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
566 const TemplateArgumentList &Args = Spec->getTemplateArgs();
568 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
570 VisitTemplateArgument(Args.get(I));
575 void USRGenerator::VisitTypedefDecl(const TypedefDecl *D) {
576 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
578 const DeclContext *DC = D->getDeclContext();
579 if (const NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
585 void USRGenerator::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
586 GenLoc(D, /*IncludeOffset=*/true);
589 void USRGenerator::GenExtSymbolContainer(const NamedDecl *D) {
590 StringRef Container = GetExternalSourceContainer(D);
591 if (!Container.empty())
592 Out << "@M@" << Container;
595 bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) {
597 return IgnoreResults;
600 // Guard against null declarations in invalid code.
602 IgnoreResults = true;
606 // Use the location of canonical decl.
607 D = D->getCanonicalDecl();
610 IgnoreResults || printLoc(Out, D->getBeginLoc(),
611 Context->getSourceManager(), IncludeOffset);
613 return IgnoreResults;
616 static void printQualifier(llvm::raw_ostream &Out, ASTContext &Ctx, NestedNameSpecifier *NNS) {
617 // FIXME: Encode the qualifier, don't just print it.
618 PrintingPolicy PO(Ctx.getLangOpts());
619 PO.SuppressTagKeyword = true;
620 PO.SuppressUnwrittenScope = true;
621 PO.ConstantArraySizeAsWritten = false;
622 PO.AnonymousTagLocations = false;
626 void USRGenerator::VisitType(QualType T) {
627 // This method mangles in USR information for types. It can possibly
628 // just reuse the naming-mangling logic used by codegen, although the
629 // requirements for USRs might not be the same.
630 ASTContext &Ctx = *Context;
633 T = Ctx.getCanonicalType(T);
634 Qualifiers Q = T.getQualifiers();
643 Out << ((char) ('0' + qVal));
645 // Mangle in ObjC GC qualifiers?
647 if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
649 T = Expansion->getPattern();
652 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
653 unsigned char c = '\0';
654 switch (BT->getKind()) {
655 case BuiltinType::Void:
657 case BuiltinType::Bool:
659 case BuiltinType::UChar:
661 case BuiltinType::Char8:
662 c = 'u'; break; // FIXME: Check this doesn't collide
663 case BuiltinType::Char16:
665 case BuiltinType::Char32:
667 case BuiltinType::UShort:
669 case BuiltinType::UInt:
671 case BuiltinType::ULong:
673 case BuiltinType::ULongLong:
675 case BuiltinType::UInt128:
677 case BuiltinType::Char_U:
678 case BuiltinType::Char_S:
680 case BuiltinType::SChar:
682 case BuiltinType::WChar_S:
683 case BuiltinType::WChar_U:
685 case BuiltinType::Short:
687 case BuiltinType::Int:
689 case BuiltinType::Long:
691 case BuiltinType::LongLong:
693 case BuiltinType::Int128:
695 case BuiltinType::Float16:
696 case BuiltinType::Half:
698 case BuiltinType::Float:
700 case BuiltinType::Double:
702 case BuiltinType::LongDouble:
704 case BuiltinType::Float128:
706 case BuiltinType::NullPtr:
708 #define BUILTIN_TYPE(Id, SingletonId)
709 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
710 #include "clang/AST/BuiltinTypes.def"
711 case BuiltinType::Dependent:
712 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
713 case BuiltinType::Id:
714 #include "clang/Basic/OpenCLImageTypes.def"
715 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
716 case BuiltinType::Id:
717 #include "clang/Basic/OpenCLExtensionTypes.def"
718 case BuiltinType::OCLEvent:
719 case BuiltinType::OCLClkEvent:
720 case BuiltinType::OCLQueue:
721 case BuiltinType::OCLReserveID:
722 case BuiltinType::OCLSampler:
723 case BuiltinType::ShortAccum:
724 case BuiltinType::Accum:
725 case BuiltinType::LongAccum:
726 case BuiltinType::UShortAccum:
727 case BuiltinType::UAccum:
728 case BuiltinType::ULongAccum:
729 case BuiltinType::ShortFract:
730 case BuiltinType::Fract:
731 case BuiltinType::LongFract:
732 case BuiltinType::UShortFract:
733 case BuiltinType::UFract:
734 case BuiltinType::ULongFract:
735 case BuiltinType::SatShortAccum:
736 case BuiltinType::SatAccum:
737 case BuiltinType::SatLongAccum:
738 case BuiltinType::SatUShortAccum:
739 case BuiltinType::SatUAccum:
740 case BuiltinType::SatULongAccum:
741 case BuiltinType::SatShortFract:
742 case BuiltinType::SatFract:
743 case BuiltinType::SatLongFract:
744 case BuiltinType::SatUShortFract:
745 case BuiltinType::SatUFract:
746 case BuiltinType::SatULongFract:
747 IgnoreResults = true;
749 case BuiltinType::ObjCId:
751 case BuiltinType::ObjCClass:
753 case BuiltinType::ObjCSel:
760 // If we have already seen this (non-built-in) type, use a substitution
762 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
763 = TypeSubstitutions.find(T.getTypePtr());
764 if (Substitution != TypeSubstitutions.end()) {
765 Out << 'S' << Substitution->second << '_';
768 // Record this as a substitution.
769 unsigned Number = TypeSubstitutions.size();
770 TypeSubstitutions[T.getTypePtr()] = Number;
773 if (const PointerType *PT = T->getAs<PointerType>()) {
775 T = PT->getPointeeType();
778 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
780 T = OPT->getPointeeType();
783 if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
785 T = RT->getPointeeType();
788 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
790 T = RT->getPointeeType();
793 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
795 VisitType(FT->getReturnType());
797 for (const auto &I : FT->param_types()) {
802 if (FT->isVariadic())
806 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
808 T = BT->getPointeeType();
811 if (const ComplexType *CT = T->getAs<ComplexType>()) {
813 T = CT->getElementType();
816 if (const TagType *TT = T->getAs<TagType>()) {
818 VisitTagDecl(TT->getDecl());
821 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
823 VisitObjCInterfaceDecl(OIT->getDecl());
826 if (const ObjCObjectType *OIT = T->getAs<ObjCObjectType>()) {
828 VisitType(OIT->getBaseType());
829 for (auto *Prot : OIT->getProtocols())
830 VisitObjCProtocolDecl(Prot);
833 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
834 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
837 if (const TemplateSpecializationType *Spec
838 = T->getAs<TemplateSpecializationType>()) {
840 VisitTemplateName(Spec->getTemplateName());
841 Out << Spec->getNumArgs();
842 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
843 VisitTemplateArgument(Spec->getArg(I));
846 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
848 printQualifier(Out, Ctx, DNT->getQualifier());
849 Out << ':' << DNT->getIdentifier()->getName();
852 if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
853 T = InjT->getInjectedSpecializationType();
856 if (const auto *VT = T->getAs<VectorType>()) {
857 Out << (T->isExtVectorType() ? ']' : '[');
858 Out << VT->getNumElements();
859 T = VT->getElementType();
862 if (const auto *const AT = dyn_cast<ArrayType>(T)) {
864 switch (AT->getSizeModifier()) {
865 case ArrayType::Static:
868 case ArrayType::Star:
871 case ArrayType::Normal:
875 if (const auto *const CAT = dyn_cast<ConstantArrayType>(T))
876 Out << CAT->getSize();
878 T = AT->getElementType();
888 void USRGenerator::VisitTemplateParameterList(
889 const TemplateParameterList *Params) {
892 Out << '>' << Params->size();
893 for (TemplateParameterList::const_iterator P = Params->begin(),
894 PEnd = Params->end();
897 if (isa<TemplateTypeParmDecl>(*P)) {
898 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
904 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
905 if (NTTP->isParameterPack())
908 VisitType(NTTP->getType());
912 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
913 if (TTP->isParameterPack())
916 VisitTemplateParameterList(TTP->getTemplateParameters());
920 void USRGenerator::VisitTemplateName(TemplateName Name) {
921 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
922 if (TemplateTemplateParmDecl *TTP
923 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
924 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
932 // FIXME: Visit dependent template names.
935 void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
936 switch (Arg.getKind()) {
937 case TemplateArgument::Null:
940 case TemplateArgument::Declaration:
941 Visit(Arg.getAsDecl());
944 case TemplateArgument::NullPtr:
947 case TemplateArgument::TemplateExpansion:
948 Out << 'P'; // pack expansion of...
950 case TemplateArgument::Template:
951 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
954 case TemplateArgument::Expression:
955 // FIXME: Visit expressions.
958 case TemplateArgument::Pack:
959 Out << 'p' << Arg.pack_size();
960 for (const auto &P : Arg.pack_elements())
961 VisitTemplateArgument(P);
964 case TemplateArgument::Type:
965 VisitType(Arg.getAsType());
968 case TemplateArgument::Integral:
970 VisitType(Arg.getIntegralType());
971 Out << Arg.getAsIntegral();
976 void USRGenerator::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
977 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
979 VisitDeclContext(D->getDeclContext());
981 printQualifier(Out, D->getASTContext(), D->getQualifier());
985 void USRGenerator::VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
986 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
988 VisitDeclContext(D->getDeclContext());
990 printQualifier(Out, D->getASTContext(), D->getQualifier());
991 Out << D->getName(); // Simple name.
996 //===----------------------------------------------------------------------===//
997 // USR generation functions.
998 //===----------------------------------------------------------------------===//
1000 static void combineClassAndCategoryExtContainers(StringRef ClsSymDefinedIn,
1001 StringRef CatSymDefinedIn,
1003 if (ClsSymDefinedIn.empty() && CatSymDefinedIn.empty())
1005 if (CatSymDefinedIn.empty()) {
1006 OS << "@M@" << ClsSymDefinedIn << '@';
1009 OS << "@CM@" << CatSymDefinedIn << '@';
1010 if (ClsSymDefinedIn != CatSymDefinedIn) {
1011 OS << ClsSymDefinedIn << '@';
1015 void clang::index::generateUSRForObjCClass(StringRef Cls, raw_ostream &OS,
1016 StringRef ExtSymDefinedIn,
1017 StringRef CategoryContextExtSymbolDefinedIn) {
1018 combineClassAndCategoryExtContainers(ExtSymDefinedIn,
1019 CategoryContextExtSymbolDefinedIn, OS);
1020 OS << "objc(cs)" << Cls;
1023 void clang::index::generateUSRForObjCCategory(StringRef Cls, StringRef Cat,
1025 StringRef ClsSymDefinedIn,
1026 StringRef CatSymDefinedIn) {
1027 combineClassAndCategoryExtContainers(ClsSymDefinedIn, CatSymDefinedIn, OS);
1028 OS << "objc(cy)" << Cls << '@' << Cat;
1031 void clang::index::generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS) {
1035 void clang::index::generateUSRForObjCMethod(StringRef Sel,
1036 bool IsInstanceMethod,
1038 OS << (IsInstanceMethod ? "(im)" : "(cm)") << Sel;
1041 void clang::index::generateUSRForObjCProperty(StringRef Prop, bool isClassProp,
1043 OS << (isClassProp ? "(cpy)" : "(py)") << Prop;
1046 void clang::index::generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS,
1047 StringRef ExtSymDefinedIn) {
1048 if (!ExtSymDefinedIn.empty())
1049 OS << "@M@" << ExtSymDefinedIn << '@';
1050 OS << "objc(pl)" << Prot;
1053 void clang::index::generateUSRForGlobalEnum(StringRef EnumName, raw_ostream &OS,
1054 StringRef ExtSymDefinedIn) {
1055 if (!ExtSymDefinedIn.empty())
1056 OS << "@M@" << ExtSymDefinedIn;
1057 OS << "@E@" << EnumName;
1060 void clang::index::generateUSRForEnumConstant(StringRef EnumConstantName,
1062 OS << '@' << EnumConstantName;
1065 bool clang::index::generateUSRForDecl(const Decl *D,
1066 SmallVectorImpl<char> &Buf) {
1069 // We don't ignore decls with invalid source locations. Implicit decls, like
1070 // C++'s operator new function, can have invalid locations but it is fine to
1071 // create USRs that can identify them.
1073 USRGenerator UG(&D->getASTContext(), Buf);
1075 return UG.ignoreResults();
1078 bool clang::index::generateUSRForMacro(const MacroDefinitionRecord *MD,
1079 const SourceManager &SM,
1080 SmallVectorImpl<char> &Buf) {
1083 return generateUSRForMacro(MD->getName()->getName(), MD->getLocation(),
1088 bool clang::index::generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
1089 const SourceManager &SM,
1090 SmallVectorImpl<char> &Buf) {
1091 // Don't generate USRs for things with invalid locations.
1092 if (MacroName.empty() || Loc.isInvalid())
1095 llvm::raw_svector_ostream Out(Buf);
1097 // Assume that system headers are sane. Don't put source location
1098 // information into the USR if the macro comes from a system header.
1099 bool ShouldGenerateLocation = !SM.isInSystemHeader(Loc);
1101 Out << getUSRSpacePrefix();
1102 if (ShouldGenerateLocation)
1103 printLoc(Out, Loc, SM, /*IncludeOffset=*/true);
1109 bool clang::index::generateUSRForType(QualType T, ASTContext &Ctx,
1110 SmallVectorImpl<char> &Buf) {
1113 T = T.getCanonicalType();
1115 USRGenerator UG(&Ctx, Buf);
1117 return UG.ignoreResults();
1120 bool clang::index::generateFullUSRForModule(const Module *Mod,
1123 return generateFullUSRForTopLevelModuleName(Mod->Name, OS);
1124 if (generateFullUSRForModule(Mod->Parent, OS))
1126 return generateUSRFragmentForModule(Mod, OS);
1129 bool clang::index::generateFullUSRForTopLevelModuleName(StringRef ModName,
1131 OS << getUSRSpacePrefix();
1132 return generateUSRFragmentForModuleName(ModName, OS);
1135 bool clang::index::generateUSRFragmentForModule(const Module *Mod,
1137 return generateUSRFragmentForModuleName(Mod->Name, OS);
1140 bool clang::index::generateUSRFragmentForModuleName(StringRef ModName,
1142 OS << "@M@" << ModName;