USRGeneration.cpp 37 KB

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