mangler.cpp 11 KB

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