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