mangler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/lower/mangler.h"
  5. #include <string>
  6. #include "common/raw_string_ostream.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/lower/clang_global_decl.h"
  9. #include "toolchain/sem_ir/clang_decl.h"
  10. #include "toolchain/sem_ir/entry_point.h"
  11. #include "toolchain/sem_ir/ids.h"
  12. #include "toolchain/sem_ir/pattern.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Lower {
  15. auto Mangler::MangleNameId(llvm::raw_ostream& os, SemIR::NameId name_id)
  16. -> void {
  17. CARBON_CHECK(name_id.AsIdentifierId().has_value(),
  18. "Mangling non-identifier name {0}", name_id);
  19. os << names().GetAsStringIfIdentifier(name_id);
  20. }
  21. auto Mangler::MangleInverseQualifiedNameScope(llvm::raw_ostream& os,
  22. SemIR::NameScopeId name_scope_id)
  23. -> void {
  24. // Maintain a stack of names for delayed rendering of interface impls.
  25. struct NameEntry {
  26. SemIR::NameScopeId name_scope_id;
  27. SemIR::SpecificId specific_id;
  28. // The prefix emitted before this name component. If '\0', no prefix will be
  29. // emitted.
  30. // - Namespace components are separated by '.'.
  31. // - The two components of an interface are separated by ':'.
  32. char prefix;
  33. };
  34. llvm::SmallVector<NameEntry> names_to_render;
  35. names_to_render.push_back({.name_scope_id = name_scope_id,
  36. .specific_id = SemIR::SpecificId::None,
  37. .prefix = '.'});
  38. while (!names_to_render.empty()) {
  39. auto [name_scope_id, specific_id, prefix] = names_to_render.pop_back_val();
  40. if (prefix) {
  41. os << prefix;
  42. }
  43. if (name_scope_id == SemIR::NameScopeId::Package) {
  44. auto package_id = sem_ir().package_id();
  45. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  46. os << sem_ir().identifiers().Get(ident_id);
  47. } else {
  48. // TODO: Handle name conflicts between special package names and raw
  49. // identifier package names. Note that any change here will also require
  50. // a change to namespace mangling for imported packages.
  51. os << package_id.AsSpecialName();
  52. }
  53. continue;
  54. }
  55. const auto& name_scope = sem_ir().name_scopes().Get(name_scope_id);
  56. CARBON_KIND_SWITCH(sem_ir().insts().Get(name_scope.inst_id())) {
  57. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  58. const auto& impl = sem_ir().impls().Get(impl_decl.impl_id);
  59. auto facet_type = insts().GetAs<SemIR::FacetType>(
  60. constant_values().GetConstantInstId(impl.constraint_id));
  61. const auto& facet_type_info =
  62. sem_ir().facet_types().Get(facet_type.facet_type_id);
  63. CARBON_CHECK(facet_type_info.extend_constraints.size() == 1,
  64. "Mangling of an impl of something other than a single "
  65. "interface is not yet supported.");
  66. auto interface_type = facet_type_info.extend_constraints.front();
  67. const auto& interface =
  68. sem_ir().interfaces().Get(interface_type.interface_id);
  69. names_to_render.push_back({.name_scope_id = interface.scope_id,
  70. .specific_id = interface_type.specific_id,
  71. .prefix = ':'});
  72. auto self_const_inst_id =
  73. constant_values().GetConstantInstId(impl.self_id);
  74. auto self_inst = insts().Get(self_const_inst_id);
  75. CARBON_KIND_SWITCH(self_inst) {
  76. case CARBON_KIND(SemIR::ClassType class_type): {
  77. auto next_name_scope_id =
  78. sem_ir().classes().Get(class_type.class_id).scope_id;
  79. names_to_render.push_back({.name_scope_id = next_name_scope_id,
  80. .specific_id = class_type.specific_id,
  81. .prefix = '\0'});
  82. break;
  83. }
  84. case SemIR::AutoType::Kind:
  85. case SemIR::BoolType::Kind:
  86. case SemIR::BoundMethodType::Kind:
  87. case SemIR::FloatLiteralType::Kind:
  88. case SemIR::IntLiteralType::Kind:
  89. case SemIR::NamespaceType::Kind:
  90. case SemIR::RequireSpecificDefinitionType::Kind:
  91. case SemIR::SpecificFunctionType::Kind:
  92. case SemIR::TypeType::Kind:
  93. case SemIR::VtableType::Kind:
  94. case SemIR::WitnessType::Kind: {
  95. os << self_inst.kind().ir_name();
  96. break;
  97. }
  98. case CARBON_KIND(SemIR::IntType int_type): {
  99. os << (int_type.int_kind == SemIR::IntKind::Signed ? "i" : "u")
  100. << sem_ir().ints().Get(
  101. sem_ir()
  102. .insts()
  103. .GetAs<SemIR::IntValue>(int_type.bit_width_id)
  104. .int_id);
  105. break;
  106. }
  107. default: {
  108. // Fall back to including a fingerprint.
  109. llvm::write_hex(
  110. os, fingerprinter_.GetOrCompute(&sem_ir(), self_const_inst_id),
  111. llvm::HexPrintStyle::Lower, 16);
  112. break;
  113. }
  114. }
  115. // Skip the tail of the loop that adds the parent name scope to the
  116. // stack - the scope in which the impl was defined is not part of the
  117. // mangling, the constraint and interface alone uniquelify identify an
  118. // impl.
  119. continue;
  120. }
  121. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  122. MangleNameId(os, sem_ir().classes().Get(class_decl.class_id).name_id);
  123. MangleSpecificId(os, specific_id);
  124. break;
  125. }
  126. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  127. MangleNameId(
  128. os, sem_ir().interfaces().Get(interface_decl.interface_id).name_id);
  129. MangleSpecificId(os, specific_id);
  130. break;
  131. }
  132. case SemIR::Namespace::Kind: {
  133. os << names().GetIRBaseName(name_scope.name_id());
  134. break;
  135. }
  136. default:
  137. CARBON_FATAL("Attempting to mangle unsupported SemIR.");
  138. break;
  139. }
  140. if (!name_scope.is_imported_package()) {
  141. names_to_render.push_back({.name_scope_id = name_scope.parent_scope_id(),
  142. .specific_id = SemIR::SpecificId::None,
  143. .prefix = '.'});
  144. }
  145. }
  146. }
  147. auto Mangler::Mangle(SemIR::FunctionId function_id,
  148. SemIR::SpecificId specific_id) -> std::string {
  149. const auto& function = sem_ir().functions().Get(function_id);
  150. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  151. CARBON_CHECK(!specific_id.has_value(), "entry point should not be generic");
  152. return "main";
  153. }
  154. if (function.clang_decl_id.has_value()) {
  155. CARBON_CHECK(function.special_function_kind !=
  156. SemIR::Function::SpecialFunctionKind::HasCppThunk,
  157. "Shouldn't mangle C++ function that uses a thunk");
  158. const auto& clang_decl = sem_ir().clang_decls().Get(function.clang_decl_id);
  159. return MangleCppClang(cast<clang::NamedDecl>(clang_decl.key.decl));
  160. }
  161. RawStringOstream os;
  162. os << "_C";
  163. MangleNameId(os, function.name_id);
  164. // For a special function, add a marker to disambiguate.
  165. switch (function.special_function_kind) {
  166. case SemIR::Function::SpecialFunctionKind::None:
  167. break;
  168. case SemIR::Function::SpecialFunctionKind::Builtin:
  169. CARBON_FATAL("Attempting to mangle declaration of builtin function {0}",
  170. function.builtin_function_kind());
  171. case SemIR::Function::SpecialFunctionKind::Thunk:
  172. os << ":thunk";
  173. break;
  174. case SemIR::Function::SpecialFunctionKind::HasCppThunk:
  175. CARBON_FATAL("C++ functions should have been handled earlier");
  176. }
  177. // TODO: If the function is private, also include the library name as part of
  178. // the mangling.
  179. MangleInverseQualifiedNameScope(os, function.parent_scope_id);
  180. MangleSpecificId(os, specific_id);
  181. return os.TakeStr();
  182. }
  183. auto Mangler::MangleSpecificId(llvm::raw_ostream& os,
  184. SemIR::SpecificId specific_id) -> void {
  185. // TODO: Add proper support for mangling generic entities. For now we use a
  186. // fingerprint of the specific arguments, which should be stable across files,
  187. // but isn't necessarily stable across toolchain changes.
  188. if (specific_id.has_value()) {
  189. os << ".";
  190. llvm::write_hex(
  191. os,
  192. fingerprinter_.GetOrCompute(
  193. &sem_ir(), sem_ir().specifics().Get(specific_id).args_id),
  194. llvm::HexPrintStyle::Lower, 16);
  195. }
  196. }
  197. auto Mangler::MangleGlobalVariable(SemIR::InstId pattern_id) -> std::string {
  198. // Use the name of the first binding in the variable as its mangled name.
  199. auto var_name_id =
  200. SemIR::GetFirstBindingNameFromPatternId(sem_ir(), pattern_id);
  201. if (!var_name_id.has_value()) {
  202. return std::string();
  203. }
  204. SemIR::CppGlobalVarId cpp_global_var_id =
  205. sem_ir().cpp_global_vars().Lookup({.entity_name_id = var_name_id});
  206. if (cpp_global_var_id.has_value()) {
  207. SemIR::ClangDeclId clang_decl_id =
  208. sem_ir().cpp_global_vars().Get(cpp_global_var_id).clang_decl_id;
  209. CARBON_CHECK(clang_decl_id.has_value(),
  210. "CppGlobalVar should have a clang_decl_id");
  211. return MangleCppClang(cast<clang::NamedDecl>(
  212. sem_ir().clang_decls().Get(clang_decl_id).key.decl));
  213. }
  214. RawStringOstream os;
  215. os << "_C";
  216. auto var_name = sem_ir().entity_names().Get(var_name_id);
  217. MangleNameId(os, var_name.name_id);
  218. // TODO: If the variable is private, also include the library name as part of
  219. // the mangling.
  220. MangleInverseQualifiedNameScope(os, var_name.parent_scope_id);
  221. return os.TakeStr();
  222. }
  223. auto Mangler::MangleCppClang(const clang::NamedDecl* decl) -> std::string {
  224. return file_context_.cpp_code_generator()
  225. .GetMangledName(CreateGlobalDecl(decl))
  226. .str();
  227. }
  228. auto Mangler::MangleVTable(const SemIR::Class& class_info,
  229. SemIR::SpecificId specific_id) -> std::string {
  230. RawStringOstream os;
  231. os << "_C";
  232. MangleNameId(os, class_info.name_id);
  233. // TODO: If the class is private, also include the library name as part of the
  234. // mangling.
  235. MangleInverseQualifiedNameScope(os, class_info.parent_scope_id);
  236. os << ".$vtable";
  237. MangleSpecificId(os, specific_id);
  238. return os.TakeStr();
  239. }
  240. } // namespace Carbon::Lower