USRGeneration.cpp 37 KB

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