mangler.cpp 8.8 KB

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