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