0.7.0
C++ to UML diagram generator based on Clang
Loading...
Searching...
No Matches
USRGeneration.cpp
Go to the documentation of this file.
1//===- USRGeneration.cpp - Routines for USR generation --------------------===//
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#include "USRGeneration.h"
10
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Attr.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/DeclVisitor.h"
16#include "clang/AST/ODRHash.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Lex/PreprocessingRecord.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/raw_ostream.h"
21
22namespace clanguml {
23// clang-format off
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// USR generation.
28//===----------------------------------------------------------------------===//
29
30/// \returns true on error.
31static bool printLoc(llvm::raw_ostream &OS, SourceLocation Loc,
32 const SourceManager &SM, bool IncludeOffset) {
33 if (Loc.isInvalid()) {
34 return true;
35 }
36 Loc = SM.getExpansionLoc(Loc);
37 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(Loc);
38 OptionalFileEntryRef FE = SM.getFileEntryRefForID(Decomposed.first);
39 if (FE) {
40 OS << llvm::sys::path::filename(FE->getName());
41 } else {
42 // This case really isn't interesting.
43 return true;
44 }
45 if (IncludeOffset) {
46 // Use the offest into the FileID to represent the location. Using
47 // a line/column can cause us to look back at the original source file,
48 // which is expensive.
49 OS << '@' << Decomposed.second;
50 }
51 return false;
52}
53
54static StringRef GetExternalSourceContainer(const NamedDecl *D) {
55 if (!D)
56 return StringRef();
57 if (auto *attr = D->getExternalSourceSymbolAttr()) {
58 return attr->getDefinedIn();
59 }
60 return StringRef();
61}
62
63namespace {
64class USRGenerator : public ConstDeclVisitor<USRGenerator> {
65 SmallVectorImpl<char> &Buf;
66 llvm::raw_svector_ostream Out;
68 ASTContext *Context;
70
71 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
72
73public:
74 explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf)
75 : Buf(Buf),
76 Out(Buf),
77 IgnoreResults(false),
78 Context(Ctx),
79 generatedLoc(false)
80 {
81 // Add the USR space prefix.
83 }
84
85 bool ignoreResults() const { return IgnoreResults; }
86
87 // Visitation methods from generating USRs from AST elements.
88 void VisitDeclContext(const DeclContext *D);
89 void VisitFieldDecl(const FieldDecl *D);
90 void VisitFunctionDecl(const FunctionDecl *D);
91 void VisitNamedDecl(const NamedDecl *D);
92 void VisitNamespaceDecl(const NamespaceDecl *D);
93 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
94 void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
95 void VisitClassTemplateDecl(const ClassTemplateDecl *D);
96 void VisitObjCContainerDecl(const ObjCContainerDecl *CD,
97 const ObjCCategoryDecl *CatD = nullptr);
98 void VisitObjCMethodDecl(const ObjCMethodDecl *MD);
99 void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
100 void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
101 void VisitTagDecl(const TagDecl *D);
102 void VisitTypedefDecl(const TypedefDecl *D);
103 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
104 void VisitVarDecl(const VarDecl *D);
105 void VisitBindingDecl(const BindingDecl *D);
106 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
107 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
108 void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
109 void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
110 void VisitConceptDecl(const ConceptDecl *D);
111
112 void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
113 IgnoreResults = true; // No USRs for linkage specs themselves.
114 }
115
116 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
117 IgnoreResults = true;
118 }
119
120 void VisitUsingDecl(const UsingDecl *D) {
121 VisitDeclContext(D->getDeclContext());
122 Out << "@UD@";
123
124 bool EmittedDeclName = !EmitDeclName(D);
125 assert(EmittedDeclName && "EmitDeclName can not fail for UsingDecls");
126 (void)EmittedDeclName;
127 }
128
129 bool ShouldGenerateLocation(const NamedDecl *D);
130
131 bool isLocal(const NamedDecl *D) {
132 return D->getParentFunctionOrMethod() != nullptr;
133 }
134
135 void GenExtSymbolContainer(const NamedDecl *D);
136
137 /// Generate the string component containing the location of the
138 /// declaration.
139 bool GenLoc(const Decl *D, bool IncludeOffset);
140
141 /// String generation methods used both by the visitation methods
142 /// and from other clients that want to directly generate USRs. These
143 /// methods do not construct complete USRs (which incorporate the parents
144 /// of an AST element), but only the fragments concerning the AST element
145 /// itself.
146
147 /// Generate a USR for an Objective-C class.
148 void GenObjCClass(StringRef cls, StringRef ExtSymDefinedIn,
149 StringRef CategoryContextExtSymbolDefinedIn) {
150 common::index::generateUSRForObjCClass(cls, Out, ExtSymDefinedIn,
151 CategoryContextExtSymbolDefinedIn);
152 }
153
154 /// Generate a USR for an Objective-C class category.
155 void GenObjCCategory(StringRef cls, StringRef cat,
156 StringRef clsExt, StringRef catExt) {
157 common::index::generateUSRForObjCCategory(cls, cat, Out, clsExt, catExt);
158 }
159
160 /// Generate a USR fragment for an Objective-C property.
161 void GenObjCProperty(StringRef prop, bool isClassProp) {
162 common::index::generateUSRForObjCProperty(prop, isClassProp, Out);
163 }
164
165 /// Generate a USR for an Objective-C protocol.
166 void GenObjCProtocol(StringRef prot, StringRef ext) {
168 }
169
170 void VisitType(QualType T);
171 void VisitTemplateParameterList(const TemplateParameterList *Params);
172 void VisitTemplateName(TemplateName Name);
173 void VisitTemplateArgument(const TemplateArgument &Arg);
174
175 void VisitMSGuidDecl(const MSGuidDecl *D);
176
177 /// Emit a Decl's name using NamedDecl::printName() and return true if
178 /// the decl had no name.
179 bool EmitDeclName(const NamedDecl *D);
180};
181} // end anonymous namespace
182
183//===----------------------------------------------------------------------===//
184// Generating USRs from ASTS.
185//===----------------------------------------------------------------------===//
186
187bool USRGenerator::EmitDeclName(const NamedDecl *D) {
188 DeclarationName N = D->getDeclName();
189 if (N.isEmpty())
190 return true;
191 Out << N;
192 return false;
193}
194
195bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
196 if (D->isExternallyVisible())
197 return false;
198 if (D->getParentFunctionOrMethod())
199 return true;
200 SourceLocation Loc = D->getLocation();
201 if (Loc.isInvalid())
202 return false;
203 const SourceManager &SM = Context->getSourceManager();
204 return !SM.isInSystemHeader(Loc);
205}
206
207void USRGenerator::VisitDeclContext(const DeclContext *DC) {
208 if (const NamedDecl *D = dyn_cast<NamedDecl>(DC))
209 Visit(D);
210 else if (isa<LinkageSpecDecl>(DC)) // Linkage specs are transparent in USRs.
211 VisitDeclContext(DC->getParent());
212}
213
214void USRGenerator::VisitFieldDecl(const FieldDecl *D) {
215 // The USR for an ivar declared in a class extension is based on the
216 // ObjCInterfaceDecl, not the ObjCCategoryDecl.
217 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
218 Visit(ID);
219 else
220 VisitDeclContext(D->getDeclContext());
221 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
222 if (EmitDeclName(D)) {
223 // Bit fields can be anonymous.
224 IgnoreResults = true;
225 return;
226 }
227}
228
229void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) {
230 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
231 return;
232
233 if (D->getType().isNull()) {
234 IgnoreResults = true;
235 return;
236 }
237
238 const unsigned StartSize = Buf.size();
239 VisitDeclContext(D->getDeclContext());
240 if (Buf.size() == StartSize)
241 GenExtSymbolContainer(D);
242
243 bool IsTemplate = false;
244 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
245 IsTemplate = true;
246 Out << "@FT@";
247 VisitTemplateParameterList(FunTmpl->getTemplateParameters());
248 } else
249 Out << "@F@";
250
251 PrintingPolicy Policy(Context->getLangOpts());
252 // Forward references can have different template argument names. Suppress the
253 // template argument names in constructors to make their USR more stable.
254 Policy.SuppressTemplateArgsInCXXConstructors = true;
255 D->getDeclName().print(Out, Policy);
256
257 ASTContext &Ctx = *Context;
258 if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) &&
259 !D->hasAttr<OverloadableAttr>())
260 return;
261
262 if (const TemplateArgumentList *
263 SpecArgs = D->getTemplateSpecializationArgs()) {
264 Out << '<';
265 for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
266 Out << '#';
267 VisitTemplateArgument(SpecArgs->get(I));
268 }
269 Out << '>';
270 }
271
272 // Mangle in type information for the arguments.
273 for (auto *PD : D->parameters()) {
274 Out << '#';
275 VisitType(PD->getType());
276 }
277 if (D->isVariadic())
278 Out << '.';
279 if (IsTemplate) {
280 // Function templates can be overloaded by return type, for example:
281 // \code
282 // template <class T> typename T::A foo() {}
283 // template <class T> typename T::B foo() {}
284 // \endcode
285 Out << '#';
286 VisitType(D->getReturnType());
287 }
288 Out << '#';
289 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
290 if (MD->isStatic())
291 Out << 'S';
292 // FIXME: OpenCL: Need to consider address spaces
293 if (unsigned quals = MD->getMethodQualifiers().getCVRUQualifiers())
294 Out << (char)('0' + quals);
295 switch (MD->getRefQualifier()) {
296 case RQ_None: break;
297 case RQ_LValue: Out << '&'; break;
298 case RQ_RValue: Out << "&&"; break;
299 }
300 }
301}
302
303void USRGenerator::VisitNamedDecl(const NamedDecl *D) {
304 VisitDeclContext(D->getDeclContext());
305 Out << "@";
306
307 if (EmitDeclName(D)) {
308 // The string can be empty if the declaration has no name; e.g., it is
309 // the ParmDecl with no name for declaration of a function pointer type,
310 // e.g.: void (*f)(void *);
311 // In this case, don't generate a USR.
312 IgnoreResults = true;
313 }
314}
315
316void USRGenerator::VisitVarDecl(const VarDecl *D) {
317 // VarDecls can be declared 'extern' within a function or method body,
318 // but their enclosing DeclContext is the function, not the TU. We need
319 // to check the storage class to correctly generate the USR.
320 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
321 return;
322
323 VisitDeclContext(D->getDeclContext());
324
325 if (VarTemplateDecl *VarTmpl = D->getDescribedVarTemplate()) {
326 Out << "@VT";
327 VisitTemplateParameterList(VarTmpl->getTemplateParameters());
328 } else if (const VarTemplatePartialSpecializationDecl *PartialSpec
329 = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
330 Out << "@VP";
331 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
332 }
333
334 // Variables always have simple names.
335 StringRef s = D->getName();
336
337 // The string can be empty if the declaration has no name; e.g., it is
338 // the ParmDecl with no name for declaration of a function pointer type, e.g.:
339 // void (*f)(void *);
340 // In this case, don't generate a USR.
341 if (s.empty())
342 IgnoreResults = true;
343 else
344 Out << '@' << s;
345
346 // For a template specialization, mangle the template arguments.
347 if (const VarTemplateSpecializationDecl *Spec
348 = dyn_cast<VarTemplateSpecializationDecl>(D)) {
349 const TemplateArgumentList &Args = Spec->getTemplateArgs();
350 Out << '>';
351 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
352 Out << '#';
353 VisitTemplateArgument(Args.get(I));
354 }
355 }
356}
357
358void USRGenerator::VisitBindingDecl(const BindingDecl *D) {
359 if (isLocal(D) && GenLoc(D, /*IncludeOffset=*/true))
360 return;
361 VisitNamedDecl(D);
362}
363
364void USRGenerator::VisitNonTypeTemplateParmDecl(
365 const NonTypeTemplateParmDecl *D) {
366 GenLoc(D, /*IncludeOffset=*/true);
367}
368
369void USRGenerator::VisitTemplateTemplateParmDecl(
370 const TemplateTemplateParmDecl *D) {
371 GenLoc(D, /*IncludeOffset=*/true);
372}
373
374void USRGenerator::VisitNamespaceDecl(const NamespaceDecl *D) {
375 if (IgnoreResults)
376 return;
377 VisitDeclContext(D->getDeclContext());
378 if (D->isAnonymousNamespace()) {
379 Out << "@aN";
380 return;
381 }
382 Out << "@N@" << D->getName();
383}
384
385void USRGenerator::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
386 VisitFunctionDecl(D->getTemplatedDecl());
387}
388
389void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
390 VisitTagDecl(D->getTemplatedDecl());
391}
392
393void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
394 VisitDeclContext(D->getDeclContext());
395 if (!IgnoreResults)
396 Out << "@NA@" << D->getName();
397}
398
399static const ObjCCategoryDecl *getCategoryContext(const NamedDecl *D) {
400 if (auto *CD = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
401 return CD;
402 if (auto *ICD = dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
403 return ICD->getCategoryDecl();
404 return nullptr;
405}
406
407void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
408 const DeclContext *container = D->getDeclContext();
409 if (const ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
410 Visit(pd);
411 }
412 else {
413 // The USR for a method declared in a class extension or category is based on
414 // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
415 const ObjCInterfaceDecl *ID = D->getClassInterface();
416 if (!ID) {
417 IgnoreResults = true;
418 return;
419 }
420 auto *CD = getCategoryContext(D);
421 VisitObjCContainerDecl(ID, CD);
422 }
423 // Ideally we would use 'GenObjCMethod', but this is such a hot path
424 // for Objective-C code that we don't want to use
425 // DeclarationName::getAsString().
426 Out << (D->isInstanceMethod() ? "(im)" : "(cm)")
427 << DeclarationName(D->getSelector());
428}
429
430void USRGenerator::VisitObjCContainerDecl(const ObjCContainerDecl *D,
431 const ObjCCategoryDecl *CatD) {
432 switch (D->getKind()) {
433 default:
434 llvm_unreachable("Invalid ObjC container.");
435 case Decl::ObjCInterface:
436 case Decl::ObjCImplementation:
437 GenObjCClass(D->getName(), GetExternalSourceContainer(D),
439 break;
440 case Decl::ObjCCategory: {
441 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
442 const ObjCInterfaceDecl *ID = CD->getClassInterface();
443 if (!ID) {
444 // Handle invalid code where the @interface might not
445 // have been specified.
446 // FIXME: We should be able to generate this USR even if the
447 // @interface isn't available.
448 IgnoreResults = true;
449 return;
450 }
451 // Specially handle class extensions, which are anonymous categories.
452 // We want to mangle in the location to uniquely distinguish them.
453 if (CD->IsClassExtension()) {
454 Out << "objc(ext)" << ID->getName() << '@';
455 GenLoc(CD, /*IncludeOffset=*/true);
456 }
457 else
458 GenObjCCategory(ID->getName(), CD->getName(),
461
462 break;
463 }
464 case Decl::ObjCCategoryImpl: {
465 const ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
466 const ObjCInterfaceDecl *ID = CD->getClassInterface();
467 if (!ID) {
468 // Handle invalid code where the @interface might not
469 // have been specified.
470 // FIXME: We should be able to generate this USR even if the
471 // @interface isn't available.
472 IgnoreResults = true;
473 return;
474 }
475 GenObjCCategory(ID->getName(), CD->getName(),
478 break;
479 }
480 case Decl::ObjCProtocol: {
481 const ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
482 GenObjCProtocol(PD->getName(), GetExternalSourceContainer(PD));
483 break;
484 }
485 }
486}
487
488void USRGenerator::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
489 // The USR for a property declared in a class extension or category is based
490 // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
491 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
492 VisitObjCContainerDecl(ID, getCategoryContext(D));
493 else
494 Visit(cast<Decl>(D->getDeclContext()));
495 GenObjCProperty(D->getName(), D->isClassProperty());
496}
497
498void USRGenerator::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
499 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
500 VisitObjCPropertyDecl(PD);
501 return;
502 }
503
504 IgnoreResults = true;
505}
506
507void USRGenerator::VisitTagDecl(const TagDecl *D) {
508 // Add the location of the tag decl to handle resolution across
509 // translation units.
510 if (!isa<EnumDecl>(D) &&
511 ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
512 return;
513
514 GenExtSymbolContainer(D);
515
516 D = D->getCanonicalDecl();
517 VisitDeclContext(D->getDeclContext());
518
519 bool AlreadyStarted = false;
520 if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
521 if(CXXRecord->isLambda()) {
522 Out << "@L";
523 printLoc(Out, CXXRecord->getBeginLoc(), Context->getSourceManager(), true);
524 }
525 else if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
526 AlreadyStarted = true;
527
528 switch (D->getTagKind()) {
529 case TagTypeKind::Interface:
530 case TagTypeKind::Class:
531 case TagTypeKind::Struct:
532 Out << "@ST";
533 break;
534 case TagTypeKind::Union:
535 Out << "@UT";
536 break;
537 case TagTypeKind::Enum:
538 llvm_unreachable("enum template");
539 }
540 VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
541 } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec
542 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
543 AlreadyStarted = true;
544
545 switch (D->getTagKind()) {
546 case TagTypeKind::Interface:
547 case TagTypeKind::Class:
548 case TagTypeKind::Struct:
549 Out << "@SP";
550 break;
551 case TagTypeKind::Union:
552 Out << "@UP";
553 break;
554 case TagTypeKind::Enum:
555 llvm_unreachable("enum partial specialization");
556 }
557 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
558 }
559 }
560
561 if (!AlreadyStarted) {
562 switch (D->getTagKind()) {
563 case TagTypeKind::Interface:
564 case TagTypeKind::Class:
565 case TagTypeKind::Struct:
566 Out << "@S";
567 break;
568 case TagTypeKind::Union:
569 Out << "@U";
570 break;
571 case TagTypeKind::Enum:
572 Out << "@E";
573 break;
574 }
575 }
576
577 Out << '@';
578 assert(Buf.size() > 0);
579 const unsigned off = Buf.size() - 1;
580
581 if (EmitDeclName(D)) {
582 if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
583 Buf[off] = 'A';
584 Out << '@' << *TD;
585 } else {
586 if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
587 printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
588 } else {
589 Buf[off] = 'a';
590 if (auto *ED = dyn_cast<EnumDecl>(D)) {
591 // Distinguish USRs of anonymous enums by using their first
592 // enumerator.
593 auto enum_range = ED->enumerators();
594 if (enum_range.begin() != enum_range.end()) {
595 Out << '@' << **enum_range.begin();
596 }
597 }
598 }
599 }
600 }
601
602 // For a class template specialization, mangle the template arguments.
603 if (const ClassTemplateSpecializationDecl *Spec
604 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
605 const TemplateArgumentList &Args = Spec->getTemplateArgs();
606 Out << '>';
607 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
608 Out << '#';
609 VisitTemplateArgument(Args.get(I));
610 }
611 }
612}
613
614void USRGenerator::VisitTypedefDecl(const TypedefDecl *D) {
615 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
616 return;
617 const DeclContext *DC = D->getDeclContext();
618 if (const NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
619 Visit(DCN);
620 Out << "@T@";
621 Out << D->getName();
622}
623
624void USRGenerator::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
625 GenLoc(D, /*IncludeOffset=*/true);
626}
627
628void USRGenerator::GenExtSymbolContainer(const NamedDecl *D) {
629 StringRef Container = GetExternalSourceContainer(D);
630 if (!Container.empty())
631 Out << "@M@" << Container;
632}
633
634bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) {
635 if (generatedLoc)
636 return IgnoreResults;
637 generatedLoc = true;
638
639 // Guard against null declarations in invalid code.
640 if (!D) {
641 IgnoreResults = true;
642 return true;
643 }
644
645 // Use the location of canonical decl.
646 D = D->getCanonicalDecl();
647
649 IgnoreResults || printLoc(Out, D->getBeginLoc(),
650 Context->getSourceManager(), IncludeOffset);
651
652 return IgnoreResults;
653}
654
655static void printQualifier(llvm::raw_ostream &Out, ASTContext &Ctx, NestedNameSpecifier *NNS) {
656 // FIXME: Encode the qualifier, don't just print it.
657 PrintingPolicy PO(Ctx.getLangOpts());
658 PO.SuppressTagKeyword = true;
659 PO.SuppressUnwrittenScope = true;
660 PO.ConstantArraySizeAsWritten = false;
661 PO.AnonymousTagLocations = false;
662 NNS->print(Out, PO);
663}
664
665void USRGenerator::VisitType(QualType T) {
666 // This method mangles in USR information for types. It can possibly
667 // just reuse the naming-mangling logic used by codegen, although the
668 // requirements for USRs might not be the same.
669 ASTContext &Ctx = *Context;
670
671 do {
672 T = Ctx.getCanonicalType(T);
673 Qualifiers Q = T.getQualifiers();
674 unsigned qVal = 0;
675 if (Q.hasConst())
676 qVal |= 0x1;
677 if (Q.hasVolatile())
678 qVal |= 0x2;
679 if (Q.hasRestrict())
680 qVal |= 0x4;
681 if(qVal)
682 Out << ((char) ('0' + qVal));
683
684 // Mangle in ObjC GC qualifiers?
685
686 if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
687 Out << 'P';
688 T = Expansion->getPattern();
689 }
690
691 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
692 switch (BT->getKind()) {
693 case BuiltinType::Void:
694 Out << 'v'; break;
695 case BuiltinType::Bool:
696 Out << 'b'; break;
697 case BuiltinType::UChar:
698 Out << 'c'; break;
699 case BuiltinType::Char8:
700 Out << 'u'; break;
701 case BuiltinType::Char16:
702 Out << 'q'; break;
703 case BuiltinType::Char32:
704 Out << 'w'; break;
705 case BuiltinType::UShort:
706 Out << 's'; break;
707 case BuiltinType::UInt:
708 Out << 'i'; break;
709 case BuiltinType::ULong:
710 Out << 'l'; break;
711 case BuiltinType::ULongLong:
712 Out << 'k'; break;
713 case BuiltinType::UInt128:
714 Out << 'j'; break;
715 case BuiltinType::Char_U:
716 case BuiltinType::Char_S:
717 Out << 'C'; break;
718 case BuiltinType::SChar:
719 Out << 'r'; break;
720 case BuiltinType::WChar_S:
721 case BuiltinType::WChar_U:
722 Out << 'W'; break;
723 case BuiltinType::Short:
724 Out << 'S'; break;
725 case BuiltinType::Int:
726 Out << 'I'; break;
727 case BuiltinType::Long:
728 Out << 'L'; break;
729 case BuiltinType::LongLong:
730 Out << 'K'; break;
731 case BuiltinType::Int128:
732 Out << 'J'; break;
733 case BuiltinType::Float16:
734 case BuiltinType::Half:
735 Out << 'h'; break;
736 case BuiltinType::Float:
737 Out << 'f'; break;
738 case BuiltinType::Double:
739 Out << 'd'; break;
740 case BuiltinType::LongDouble:
741 Out << 'D'; break;
742 case BuiltinType::Float128:
743 Out << 'Q'; break;
744 case BuiltinType::NullPtr:
745 Out << 'n'; break;
746#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
747 case BuiltinType::Id: \
748 Out << "@BT@" << #Suffix << "_" << #ImgType; break;
749#include "clang/Basic/OpenCLImageTypes.def"
750#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
751 case BuiltinType::Id: \
752 Out << "@BT@" << #ExtType; break;
753#include "clang/Basic/OpenCLExtensionTypes.def"
754 case BuiltinType::OCLEvent:
755 Out << "@BT@OCLEvent"; break;
756 case BuiltinType::OCLClkEvent:
757 Out << "@BT@OCLClkEvent"; break;
758 case BuiltinType::OCLQueue:
759 Out << "@BT@OCLQueue"; break;
760 case BuiltinType::OCLReserveID:
761 Out << "@BT@OCLReserveID"; break;
762 case BuiltinType::OCLSampler:
763 Out << "@BT@OCLSampler"; break;
764#define SVE_TYPE(Name, Id, SingletonId) \
765 case BuiltinType::Id: \
766 Out << "@BT@" << Name; break;
767#include "clang/Basic/AArch64SVEACLETypes.def"
768#define PPC_VECTOR_TYPE(Name, Id, Size) \
769 case BuiltinType::Id: \
770 Out << "@BT@" << #Name; break;
771#include "clang/Basic/PPCTypes.def"
772#define RVV_TYPE(Name, Id, SingletonId) \
773 case BuiltinType::Id: \
774 Out << "@BT@" << Name; break;
775#include "clang/Basic/RISCVVTypes.def"
776#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
777#include "clang/Basic/WebAssemblyReferenceTypes.def"
778 case BuiltinType::ShortAccum:
779 Out << "@BT@ShortAccum"; break;
780 case BuiltinType::Accum:
781 Out << "@BT@Accum"; break;
782 case BuiltinType::LongAccum:
783 Out << "@BT@LongAccum"; break;
784 case BuiltinType::UShortAccum:
785 Out << "@BT@UShortAccum"; break;
786 case BuiltinType::UAccum:
787 Out << "@BT@UAccum"; break;
788 case BuiltinType::ULongAccum:
789 Out << "@BT@ULongAccum"; break;
790 case BuiltinType::ShortFract:
791 Out << "@BT@ShortFract"; break;
792 case BuiltinType::Fract:
793 Out << "@BT@Fract"; break;
794 case BuiltinType::LongFract:
795 Out << "@BT@LongFract"; break;
796 case BuiltinType::UShortFract:
797 Out << "@BT@UShortFract"; break;
798 case BuiltinType::UFract:
799 Out << "@BT@UFract"; break;
800 case BuiltinType::ULongFract:
801 Out << "@BT@ULongFract"; break;
802 case BuiltinType::SatShortAccum:
803 Out << "@BT@SatShortAccum"; break;
804 case BuiltinType::SatAccum:
805 Out << "@BT@SatAccum"; break;
806 case BuiltinType::SatLongAccum:
807 Out << "@BT@SatLongAccum"; break;
808 case BuiltinType::SatUShortAccum:
809 Out << "@BT@SatUShortAccum"; break;
810 case BuiltinType::SatUAccum:
811 Out << "@BT@SatUAccum"; break;
812 case BuiltinType::SatULongAccum:
813 Out << "@BT@SatULongAccum"; break;
814 case BuiltinType::SatShortFract:
815 Out << "@BT@SatShortFract"; break;
816 case BuiltinType::SatFract:
817 Out << "@BT@SatFract"; break;
818 case BuiltinType::SatLongFract:
819 Out << "@BT@SatLongFract"; break;
820 case BuiltinType::SatUShortFract:
821 Out << "@BT@SatUShortFract"; break;
822 case BuiltinType::SatUFract:
823 Out << "@BT@SatUFract"; break;
824 case BuiltinType::SatULongFract:
825 Out << "@BT@SatULongFract"; break;
826 case BuiltinType::BFloat16:
827 Out << "@BT@__bf16"; break;
828 case BuiltinType::Ibm128:
829 Out << "@BT@__ibm128"; break;
830 case BuiltinType::ObjCId:
831 Out << 'o'; break;
832 case BuiltinType::ObjCClass:
833 Out << 'O'; break;
834 case BuiltinType::ObjCSel:
835 Out << 'e'; break;
836#define BUILTIN_TYPE(Id, SingletonId)
837#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
838#include "clang/AST/BuiltinTypes.def"
839 case BuiltinType::Dependent:
840 // If you're adding a new builtin type, please add its name prefixed
841 // with "@BT@" to `Out` (see cases above).
842 IgnoreResults = true;
843 break;
844 }
845 return;
846 }
847
848 // If we have already seen this (non-built-in) type, use a substitution
849 // encoding.
850 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
851 = TypeSubstitutions.find(T.getTypePtr());
852 if (Substitution != TypeSubstitutions.end()) {
853 Out << 'S' << Substitution->second << '_';
854 return;
855 } else {
856 // Record this as a substitution.
857 unsigned Number = TypeSubstitutions.size();
858 TypeSubstitutions[T.getTypePtr()] = Number;
859 }
860
861 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
862 Out << "*M";
863 T = MPT->getPointeeType();
864 continue;
865 }
866 if (const PointerType *PT = T->getAs<PointerType>()) {
867 Out << '*';
868 T = PT->getPointeeType();
869 continue;
870 }
871 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
872 Out << '*';
873 T = OPT->getPointeeType();
874 continue;
875 }
876 if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
877 Out << "&&";
878 T = RT->getPointeeType();
879 continue;
880 }
881 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
882 Out << '&';
883 T = RT->getPointeeType();
884 continue;
885 }
886 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
887 Out << 'F';
888 VisitType(FT->getReturnType());
889 Out << '(';
890 for (const auto &I : FT->param_types()) {
891 Out << '#';
892 VisitType(I);
893 }
894 Out << ')';
895 if (FT->isVariadic())
896 Out << '.';
897
898 clang::RefQualifierKind rq = FT->getRefQualifier();
899
900 switch (rq) {
901 case clang::RQ_None:
902 // No ref-qualifier
903 break;
904 case clang::RQ_LValue:
905 Out << "&&";
906 break;
907 case clang::RQ_RValue:
908 Out << '&';
909 break;
910 }
911
912 return;
913 }
914 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
915 Out << 'B';
916 T = BT->getPointeeType();
917 continue;
918 }
919 if (const ComplexType *CT = T->getAs<ComplexType>()) {
920 Out << '<';
921 T = CT->getElementType();
922 continue;
923 }
924 if (const TagType *TT = T->getAs<TagType>()) {
925 Out << '$';
926 VisitTagDecl(TT->getDecl());
927 return;
928 }
929 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
930 Out << '$';
931 VisitObjCInterfaceDecl(OIT->getDecl());
932 return;
933 }
934 if (const ObjCObjectType *OIT = T->getAs<ObjCObjectType>()) {
935 Out << 'Q';
936 VisitType(OIT->getBaseType());
937 for (auto *Prot : OIT->getProtocols())
938 VisitObjCProtocolDecl(Prot);
939 return;
940 }
941 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
942 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
943 return;
944 }
945 if (const TemplateSpecializationType *Spec
946 = T->getAs<TemplateSpecializationType>()) {
947 Out << '>';
948 VisitTemplateName(Spec->getTemplateName());
949 Out << Spec->template_arguments().size();
950 for (const auto &Arg : Spec->template_arguments())
951 VisitTemplateArgument(Arg);
952 return;
953 }
954 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
955 Out << '^';
956 printQualifier(Out, Ctx, DNT->getQualifier());
957 Out << ':' << DNT->getIdentifier()->getName();
958 return;
959 }
960 if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
961 T = InjT->getInjectedSpecializationType();
962 continue;
963 }
964 if (const auto *VT = T->getAs<VectorType>()) {
965 Out << (T->isExtVectorType() ? ']' : '[');
966 Out << VT->getNumElements();
967 T = VT->getElementType();
968 continue;
969 }
970 if (const auto *const AT = dyn_cast<ArrayType>(T)) {
971 Out << '{';
972 switch (AT->getSizeModifier()) {
973 case ArraySizeModifier::Static:
974 Out << 's';
975 break;
976 case ArraySizeModifier::Star:
977 Out << '*';
978 break;
979 case ArraySizeModifier::Normal:
980 Out << 'n';
981 break;
982 }
983 if (const auto *const CAT = dyn_cast<ConstantArrayType>(T))
984 Out << CAT->getSize();
985
986 T = AT->getElementType();
987 continue;
988 }
989
990 // Unhandled type.
991 Out << ' ';
992 break;
993 } while (true);
994}
995
996void USRGenerator::VisitTemplateParameterList(
997 const TemplateParameterList *Params) {
998 if (!Params)
999 return;
1000 Out << '>' << Params->size();
1001 for (TemplateParameterList::const_iterator P = Params->begin(),
1002 PEnd = Params->end();
1003 P != PEnd; ++P) {
1004 Out << '#';
1005 if (isa<TemplateTypeParmDecl>(*P)) {
1006 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
1007 Out<< 'p';
1008 Out << 'T';
1009 continue;
1010 }
1011
1012 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
1013 if (NTTP->isParameterPack())
1014 Out << 'p';
1015 Out << 'N';
1016 VisitType(NTTP->getType());
1017 continue;
1018 }
1019
1020 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1021 if (TTP->isParameterPack())
1022 Out << 'p';
1023 Out << 't';
1024 VisitTemplateParameterList(TTP->getTemplateParameters());
1025 }
1026}
1027
1028void USRGenerator::VisitTemplateName(TemplateName Name) {
1029 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1030 if (TemplateTemplateParmDecl *TTP
1031 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
1032 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
1033 return;
1034 }
1035
1036 Visit(Template);
1037 return;
1038 }
1039
1040 // FIXME: Visit dependent template names.
1041}
1042
1043void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
1044 switch (Arg.getKind()) {
1045 case TemplateArgument::Null:
1046 break;
1047
1048 case TemplateArgument::Declaration:
1049 Visit(Arg.getAsDecl());
1050 break;
1051
1052 case TemplateArgument::NullPtr:
1053 break;
1054
1055 case TemplateArgument::TemplateExpansion:
1056 Out << 'P'; // pack expansion of...
1057 [[fallthrough]];
1058 case TemplateArgument::Template:
1059 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
1060 break;
1061
1062 case TemplateArgument::Expression:
1063 // FIXME: Visit expressions.
1064 break;
1065
1066 case TemplateArgument::Pack:
1067 Out << 'p' << Arg.pack_size();
1068 for (const auto &P : Arg.pack_elements())
1069 VisitTemplateArgument(P);
1070 break;
1071
1072 case TemplateArgument::Type:
1073 VisitType(Arg.getAsType());
1074 break;
1075
1076 case TemplateArgument::Integral:
1077 Out << 'V';
1078 VisitType(Arg.getIntegralType());
1079 Out << Arg.getAsIntegral();
1080 break;
1081
1082 case TemplateArgument::StructuralValue: {
1083 Out << 'S';
1084 VisitType(Arg.getStructuralValueType());
1085 ODRHash Hash{};
1086 Hash.AddStructuralValue(Arg.getAsStructuralValue());
1087 Out << Hash.CalculateHash();
1088 break;
1089 }
1090 }
1091}
1092
1093void USRGenerator::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
1094 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1095 return;
1096 VisitDeclContext(D->getDeclContext());
1097 Out << "@UUV@";
1098 printQualifier(Out, D->getASTContext(), D->getQualifier());
1099 EmitDeclName(D);
1100}
1101
1102void USRGenerator::VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
1103 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1104 return;
1105 VisitDeclContext(D->getDeclContext());
1106 Out << "@UUT@";
1107 printQualifier(Out, D->getASTContext(), D->getQualifier());
1108 Out << D->getName(); // Simple name.
1109}
1110
1111void USRGenerator::VisitConceptDecl(const ConceptDecl *D) {
1112 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1113 return;
1114 VisitDeclContext(D->getDeclContext());
1115 Out << "@CT@";
1116 EmitDeclName(D);
1117}
1118
1119void USRGenerator::VisitMSGuidDecl(const MSGuidDecl *D) {
1120 VisitDeclContext(D->getDeclContext());
1121 Out << "@MG@";
1122 D->NamedDecl::printName(Out);
1123}
1124
1125//===----------------------------------------------------------------------===//
1126// USR generation functions.
1127//===----------------------------------------------------------------------===//
1128
1129static void combineClassAndCategoryExtContainers(StringRef ClsSymDefinedIn,
1130 StringRef CatSymDefinedIn,
1131 raw_ostream &OS) {
1132 if (ClsSymDefinedIn.empty() && CatSymDefinedIn.empty())
1133 return;
1134 if (CatSymDefinedIn.empty()) {
1135 OS << "@M@" << ClsSymDefinedIn << '@';
1136 return;
1137 }
1138 OS << "@CM@" << CatSymDefinedIn << '@';
1139 if (ClsSymDefinedIn != CatSymDefinedIn) {
1140 OS << ClsSymDefinedIn << '@';
1141 }
1142}
1143
1144void common::index::generateUSRForObjCClass(StringRef Cls, raw_ostream &OS,
1145 StringRef ExtSymDefinedIn,
1146 StringRef CategoryContextExtSymbolDefinedIn) {
1148 CategoryContextExtSymbolDefinedIn, OS);
1149 OS << "objc(cs)" << Cls;
1150}
1151
1152void common::index::generateUSRForObjCCategory(StringRef Cls, StringRef Cat,
1153 raw_ostream &OS,
1154 StringRef ClsSymDefinedIn,
1155 StringRef CatSymDefinedIn) {
1156 combineClassAndCategoryExtContainers(ClsSymDefinedIn, CatSymDefinedIn, OS);
1157 OS << "objc(cy)" << Cls << '@' << Cat;
1158}
1159
1160void common::index::generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS) {
1161 OS << '@' << Ivar;
1162}
1163
1165 bool IsInstanceMethod,
1166 raw_ostream &OS) {
1167 OS << (IsInstanceMethod ? "(im)" : "(cm)") << Sel;
1168}
1169
1170void common::index::generateUSRForObjCProperty(StringRef Prop, bool isClassProp,
1171 raw_ostream &OS) {
1172 OS << (isClassProp ? "(cpy)" : "(py)") << Prop;
1173}
1174
1175void common::index::generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS,
1176 StringRef ExtSymDefinedIn) {
1177 if (!ExtSymDefinedIn.empty())
1178 OS << "@M@" << ExtSymDefinedIn << '@';
1179 OS << "objc(pl)" << Prot;
1180}
1181
1182void common::index::generateUSRForGlobalEnum(StringRef EnumName, raw_ostream &OS,
1183 StringRef ExtSymDefinedIn) {
1184 if (!ExtSymDefinedIn.empty())
1185 OS << "@M@" << ExtSymDefinedIn;
1186 OS << "@E@" << EnumName;
1187}
1188
1189void common::index::generateUSRForEnumConstant(StringRef EnumConstantName,
1190 raw_ostream &OS) {
1191 OS << '@' << EnumConstantName;
1192}
1193
1194bool common::index::generateUSRForDecl(const Decl *D,
1195 SmallVectorImpl<char> &Buf) {
1196 if (!D)
1197 return true;
1198 // We don't ignore decls with invalid source locations. Implicit decls, like
1199 // C++'s operator new function, can have invalid locations but it is fine to
1200 // create USRs that can identify them.
1201
1202 // Check if the declaration has explicit external USR specified.
1203 auto *CD = D->getCanonicalDecl();
1204 if (auto *ExternalSymAttr = CD->getAttr<ExternalSourceSymbolAttr>()) {
1205 if (!ExternalSymAttr->getUSR().empty()) {
1206 llvm::raw_svector_ostream Out(Buf);
1207 Out << ExternalSymAttr->getUSR();
1208 return false;
1209 }
1210 }
1211 USRGenerator UG(&D->getASTContext(), Buf);
1212 UG.Visit(D);
1213 return UG.ignoreResults();
1214}
1215
1216bool common::index::generateUSRForMacro(const MacroDefinitionRecord *MD,
1217 const SourceManager &SM,
1218 SmallVectorImpl<char> &Buf) {
1219 if (!MD)
1220 return true;
1221 return generateUSRForMacro(MD->getName()->getName(), MD->getLocation(),
1222 SM, Buf);
1223
1224}
1225
1226bool common::index::generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
1227 const SourceManager &SM,
1228 SmallVectorImpl<char> &Buf) {
1229 if (MacroName.empty())
1230 return true;
1231
1232 llvm::raw_svector_ostream Out(Buf);
1233
1234 // Assume that system headers are sane. Don't put source location
1235 // information into the USR if the macro comes from a system header.
1236 bool ShouldGenerateLocation = Loc.isValid() && !SM.isInSystemHeader(Loc);
1237
1238 Out << getUSRSpacePrefix();
1239 if (ShouldGenerateLocation)
1240 printLoc(Out, Loc, SM, /*IncludeOffset=*/true);
1241 Out << "@macro@";
1242 Out << MacroName;
1243 return false;
1244}
1245
1246bool common::index::generateUSRForType(QualType T, ASTContext &Ctx,
1247 SmallVectorImpl<char> &Buf) {
1248 if (T.isNull())
1249 return true;
1250 T = T.getCanonicalType();
1251
1252 USRGenerator UG(&Ctx, Buf);
1253 UG.VisitType(T);
1254 return UG.ignoreResults();
1255}
1256
1257bool common::index::generateFullUSRForModule(const Module *Mod,
1258 raw_ostream &OS) {
1259 if (!Mod->Parent)
1260 return generateFullUSRForTopLevelModuleName(Mod->Name, OS);
1261 if (generateFullUSRForModule(Mod->Parent, OS))
1262 return true;
1263 return generateUSRFragmentForModule(Mod, OS);
1264}
1265
1267 raw_ostream &OS) {
1268 OS << getUSRSpacePrefix();
1269 return generateUSRFragmentForModuleName(ModName, OS);
1270}
1271
1272bool common::index::generateUSRFragmentForModule(const Module *Mod,
1273 raw_ostream &OS) {
1274 return generateUSRFragmentForModuleName(Mod->Name, OS);
1275}
1276
1278 raw_ostream &OS) {
1279 OS << "@M@" << ModName;
1280 return false;
1281}
1282
1283} // namespace clanguml