mangler.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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/sem_ir/entry_point.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. #include "toolchain/sem_ir/pattern.h"
  11. namespace Carbon::Lower {
  12. auto Mangler::MangleNameId(llvm::raw_ostream& os, SemIR::NameId name_id)
  13. -> void {
  14. CARBON_CHECK(name_id.AsIdentifierId().has_value(),
  15. "Mangling non-identifier name {0}", name_id);
  16. os << names().GetAsStringIfIdentifier(name_id);
  17. }
  18. auto Mangler::MangleInverseQualifiedNameScope(llvm::raw_ostream& os,
  19. SemIR::NameScopeId name_scope_id)
  20. -> void {
  21. // Maintain a stack of names for delayed rendering of interface impls.
  22. struct NameEntry {
  23. SemIR::NameScopeId name_scope_id;
  24. // The prefix emitted before this name component. If '\0', no prefix will be
  25. // emitted.
  26. // - Namespace components are separated by '.'.
  27. // - The two components of an interface are separated by ':'.
  28. char prefix;
  29. };
  30. llvm::SmallVector<NameEntry> names_to_render;
  31. names_to_render.push_back({.name_scope_id = name_scope_id, .prefix = '.'});
  32. while (!names_to_render.empty()) {
  33. auto [name_scope_id, prefix] = names_to_render.pop_back_val();
  34. if (prefix) {
  35. os << prefix;
  36. }
  37. if (name_scope_id == SemIR::NameScopeId::Package) {
  38. auto package_id = sem_ir().package_id();
  39. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  40. os << sem_ir().identifiers().Get(ident_id);
  41. } else {
  42. // TODO: Handle name conflicts between special package names and raw
  43. // identifier package names. Note that any change here will also require
  44. // a change to namespace mangling for imported packages.
  45. os << package_id.AsSpecialName();
  46. }
  47. continue;
  48. }
  49. const auto& name_scope = sem_ir().name_scopes().Get(name_scope_id);
  50. CARBON_KIND_SWITCH(sem_ir().insts().Get(name_scope.inst_id())) {
  51. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  52. const auto& impl = sem_ir().impls().Get(impl_decl.impl_id);
  53. auto facet_type = insts().GetAs<SemIR::FacetType>(
  54. constant_values().GetConstantInstId(impl.constraint_id));
  55. const auto& facet_type_info =
  56. sem_ir().facet_types().Get(facet_type.facet_type_id);
  57. CARBON_CHECK(facet_type_info.extend_constraints.size() == 1,
  58. "Mangling of an impl of something other than a single "
  59. "interface is not yet supported.");
  60. auto interface_type = facet_type_info.extend_constraints.front();
  61. const auto& interface =
  62. sem_ir().interfaces().Get(interface_type.interface_id);
  63. names_to_render.push_back(
  64. {.name_scope_id = interface.scope_id, .prefix = ':'});
  65. auto self_const_inst_id =
  66. constant_values().GetConstantInstId(impl.self_id);
  67. auto self_inst = insts().Get(self_const_inst_id);
  68. CARBON_KIND_SWITCH(self_inst) {
  69. case CARBON_KIND(SemIR::ClassType class_type): {
  70. auto next_name_scope_id =
  71. sem_ir().classes().Get(class_type.class_id).scope_id;
  72. names_to_render.push_back(
  73. {.name_scope_id = next_name_scope_id, .prefix = '\0'});
  74. break;
  75. }
  76. case SemIR::AutoType::Kind:
  77. case SemIR::BoolType::Kind:
  78. case SemIR::BoundMethodType::Kind:
  79. case SemIR::IntLiteralType::Kind:
  80. case SemIR::LegacyFloatType::Kind:
  81. case SemIR::NamespaceType::Kind:
  82. case SemIR::SpecificFunctionType::Kind:
  83. case SemIR::StringType::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(llvm::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. }
  161. // TODO: If the function is private, also include the library name as part of
  162. // the mangling.
  163. MangleInverseQualifiedNameScope(os, function.parent_scope_id);
  164. // TODO: Add proper support for mangling generic entities. For now we use a
  165. // fingerprint of the specific arguments, which should be stable across files,
  166. // but isn't necessarily stable across toolchain changes.
  167. if (specific_id.has_value()) {
  168. os << ".";
  169. llvm::write_hex(
  170. os,
  171. fingerprinter_.GetOrCompute(
  172. &sem_ir(), sem_ir().specifics().Get(specific_id).args_id),
  173. llvm::HexPrintStyle::Lower, 16);
  174. }
  175. return os.TakeStr();
  176. }
  177. auto Mangler::MangleGlobalVariable(SemIR::InstId pattern_id) -> std::string {
  178. // Use the name of the first binding in the variable as its mangled name.
  179. auto var_name_id =
  180. SemIR::GetFirstBindingNameFromPatternId(sem_ir(), pattern_id);
  181. if (!var_name_id.has_value()) {
  182. return std::string();
  183. }
  184. RawStringOstream os;
  185. os << "_C";
  186. auto var_name = sem_ir().entity_names().Get(var_name_id);
  187. MangleNameId(os, var_name.name_id);
  188. // TODO: If the variable is private, also include the library name as part of
  189. // the mangling.
  190. MangleInverseQualifiedNameScope(os, var_name.parent_scope_id);
  191. return os.TakeStr();
  192. }
  193. auto Mangler::MangleCppClang(const clang::NamedDecl* decl) -> std::string {
  194. CARBON_CHECK(
  195. cpp_mangle_context_,
  196. "Mangling of a C++ imported declaration without a Clang `MangleContext`");
  197. RawStringOstream cpp_mangled_name;
  198. cpp_mangle_context_->mangleName(decl, cpp_mangled_name);
  199. return cpp_mangled_name.TakeStr();
  200. }
  201. auto Mangler::MangleVTable(const SemIR::Class& class_info) -> std::string {
  202. RawStringOstream os;
  203. os << "_C";
  204. MangleNameId(os, class_info.name_id);
  205. // TODO: If the class is private, also include the library name as part of the
  206. // mangling.
  207. MangleInverseQualifiedNameScope(os, class_info.parent_scope_id);
  208. os << ".$vtable";
  209. return os.TakeStr();
  210. }
  211. } // namespace Carbon::Lower