mangler.cpp 9.6 KB

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