inst_namer.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  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/sem_ir/inst_namer.h"
  5. #include <string>
  6. #include <utility>
  7. #include <variant>
  8. #include "common/ostream.h"
  9. #include "common/raw_string_ostream.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallVector.h"
  12. #include "llvm/ADT/StableHashing.h"
  13. #include "toolchain/base/kind_switch.h"
  14. #include "toolchain/base/shared_value_stores.h"
  15. #include "toolchain/base/value_ids.h"
  16. #include "toolchain/lex/tokenized_buffer.h"
  17. #include "toolchain/parse/tree.h"
  18. #include "toolchain/sem_ir/cpp_overload_set.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/function.h"
  21. #include "toolchain/sem_ir/ids.h"
  22. #include "toolchain/sem_ir/inst_kind.h"
  23. #include "toolchain/sem_ir/pattern.h"
  24. #include "toolchain/sem_ir/singleton_insts.h"
  25. #include "toolchain/sem_ir/type_info.h"
  26. #include "toolchain/sem_ir/typed_insts.h"
  27. namespace Carbon::SemIR {
  28. class InstNamer::NamingContext {
  29. public:
  30. explicit NamingContext(InstNamer* inst_namer, InstNamer::ScopeId scope_id,
  31. InstId inst_id);
  32. // Names the single instruction. Use bound names where available. Otherwise,
  33. // assign a backup name.
  34. //
  35. // Insts with a type_id are required to add names; other insts may
  36. // optionally set a name. All insts may push other insts to be named.
  37. auto NameInst() -> void;
  38. private:
  39. // Adds the instruction's name.
  40. auto AddInstName(std::string name) -> void;
  41. // Adds the instruction's name by `NameId`.
  42. auto AddInstNameId(NameId name_id, llvm::StringRef suffix = "") -> void {
  43. AddInstName((sem_ir().names().GetIRBaseName(name_id) + suffix).str());
  44. }
  45. // Names an `IntType` or `FloatType`.
  46. auto AddIntOrFloatTypeName(char type_literal_prefix, InstId bit_width_id,
  47. llvm::StringRef suffix = "") -> void;
  48. // Names an `ImplWitnessTable` instruction.
  49. auto AddWitnessTableName(InstId witness_table_inst_id, std::string name)
  50. -> void;
  51. // Pushes all instructions in a block, by ID.
  52. auto PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void {
  53. inst_namer_->PushBlockId(scope_id, block_id);
  54. }
  55. // Names the instruction as an entity. May push processing of the entity.
  56. template <typename EntityIdT>
  57. auto AddEntityNameAndMaybePush(EntityIdT id, llvm::StringRef suffix = "")
  58. -> void {
  59. AddInstName((inst_namer_->MaybePushEntity(id) + suffix).str());
  60. }
  61. auto sem_ir() -> const File& { return *inst_namer_->sem_ir_; }
  62. InstNamer* inst_namer_;
  63. ScopeId scope_id_;
  64. InstId inst_id_;
  65. Inst inst_;
  66. };
  67. InstNamer::InstNamer(const File* sem_ir, int total_ir_count)
  68. : sem_ir_(sem_ir), fingerprinter_(total_ir_count) {
  69. insts_.resize(sem_ir->insts().size(), {ScopeId::None, Namespace::Name()});
  70. labels_.resize(sem_ir->inst_blocks().size());
  71. scopes_.resize(GetScopeIdOffset(ScopeIdTypeEnum::None));
  72. generic_scopes_.resize(sem_ir->generics().size(), ScopeId::None);
  73. // We process the stack between each large block in order to reduce the
  74. // temporary size of the stack.
  75. auto process_stack = [&] {
  76. while (!inst_stack_.empty() || !inst_block_stack_.empty()) {
  77. if (inst_stack_.empty()) {
  78. auto [scope_id, block_id] = inst_block_stack_.pop_back_val();
  79. PushBlockInsts(scope_id, sem_ir_->inst_blocks().Get(block_id));
  80. }
  81. while (!inst_stack_.empty()) {
  82. auto [scope_id, inst_id] = inst_stack_.pop_back_val();
  83. NamingContext context(this, scope_id, inst_id);
  84. context.NameInst();
  85. }
  86. }
  87. };
  88. // Name each of the top-level scopes, in order. We use these as the roots of
  89. // walking the IR.
  90. PushBlockInsts(ScopeId::Constants, sem_ir->constants().array_ref());
  91. process_stack();
  92. PushBlockId(ScopeId::Imports, InstBlockId::Imports);
  93. process_stack();
  94. PushBlockId(ScopeId::File, sem_ir->top_inst_block_id());
  95. process_stack();
  96. // Global init won't have any other references, so we add it directly.
  97. if (sem_ir_->global_ctor_id().has_value()) {
  98. MaybePushEntity(sem_ir_->global_ctor_id());
  99. process_stack();
  100. }
  101. }
  102. auto InstNamer::GetScopeIdOffset(ScopeIdTypeEnum id_enum) const -> int {
  103. int offset = 0;
  104. // For each Id type, add the number of entities *above* its case; for example,
  105. // the offset for functions excludes the functions themselves. The fallthrough
  106. // handles summing to get uniqueness; order isn't special.
  107. switch (id_enum) {
  108. case ScopeIdTypeEnum::None:
  109. // `None` will be getting a full count of scopes.
  110. offset += sem_ir_->associated_constants().size();
  111. [[fallthrough]];
  112. case ScopeIdTypeEnum::For<AssociatedConstantId>:
  113. offset += sem_ir_->classes().size();
  114. [[fallthrough]];
  115. case ScopeIdTypeEnum::For<ClassId>:
  116. offset += sem_ir_->cpp_overload_sets().size();
  117. [[fallthrough]];
  118. case ScopeIdTypeEnum::For<CppOverloadSetId>:
  119. offset += sem_ir_->functions().size();
  120. [[fallthrough]];
  121. case ScopeIdTypeEnum::For<FunctionId>:
  122. offset += sem_ir_->impls().size();
  123. [[fallthrough]];
  124. case ScopeIdTypeEnum::For<ImplId>:
  125. offset += sem_ir_->interfaces().size();
  126. [[fallthrough]];
  127. case ScopeIdTypeEnum::For<InterfaceId>:
  128. offset += sem_ir_->named_constraints().size();
  129. [[fallthrough]];
  130. case ScopeIdTypeEnum::For<NamedConstraintId>:
  131. offset += sem_ir_->specific_interfaces().size();
  132. [[fallthrough]];
  133. case ScopeIdTypeEnum::For<SpecificInterfaceId>:
  134. offset += sem_ir_->vtables().size();
  135. [[fallthrough]];
  136. case ScopeIdTypeEnum::For<VtableId>:
  137. // All type-specific scopes are offset by `FirstEntityScope`.
  138. offset += static_cast<int>(ScopeId::FirstEntityScope);
  139. return offset;
  140. default:
  141. CARBON_FATAL("Unexpected ScopeIdTypeEnum: {0}", id_enum);
  142. }
  143. }
  144. auto InstNamer::GetScopeName(ScopeId scope) const -> std::string {
  145. switch (scope) {
  146. case ScopeId::None:
  147. return "<no scope>";
  148. // These are treated as SemIR keywords.
  149. case ScopeId::File:
  150. return "file";
  151. case ScopeId::Imports:
  152. return "imports";
  153. case ScopeId::Constants:
  154. return "constants";
  155. // For everything else, use an @ prefix.
  156. default:
  157. return ("@" + GetScopeInfo(scope).name.GetFullName()).str();
  158. }
  159. }
  160. auto InstNamer::GetUnscopedNameFor(InstId inst_id) const -> llvm::StringRef {
  161. if (!inst_id.has_value()) {
  162. return "";
  163. }
  164. if (IsSingletonInstId(inst_id)) {
  165. return sem_ir_->insts().Get(inst_id).kind().ir_name();
  166. }
  167. auto index = sem_ir_->insts().GetRawIndex(inst_id);
  168. const auto& inst_name = insts_[index].second;
  169. return inst_name ? inst_name.GetFullName() : "";
  170. }
  171. auto InstNamer::GetNameFor(ScopeId scope_id, InstId inst_id) const
  172. -> std::string {
  173. if (!inst_id.has_value()) {
  174. return "invalid";
  175. }
  176. // Check for a builtin.
  177. if (IsSingletonInstId(inst_id)) {
  178. return sem_ir_->insts().Get(inst_id).kind().ir_name().str();
  179. }
  180. if (inst_id == SemIR::Namespace::PackageInstId) {
  181. return "package";
  182. }
  183. auto index = sem_ir_->insts().GetRawIndex(inst_id);
  184. const auto& [inst_scope, inst_name] = insts_[index];
  185. if (!inst_name) {
  186. // This should not happen in valid IR.
  187. RawStringOstream out;
  188. out << "<unexpected>." << inst_id;
  189. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  190. // TODO: Consider handling other kinds.
  191. if (loc_id.kind() == LocId::Kind::NodeId) {
  192. const auto& tree = sem_ir_->parse_tree();
  193. auto token = tree.node_token(loc_id.node_id());
  194. out << ".loc" << tree.tokens().GetLineNumber(token) << "_"
  195. << tree.tokens().GetColumnNumber(token);
  196. }
  197. return out.TakeStr();
  198. }
  199. if (inst_scope == scope_id) {
  200. return ("%" + inst_name.GetFullName()).str();
  201. }
  202. return (GetScopeName(inst_scope) + ".%" + inst_name.GetFullName()).str();
  203. }
  204. auto InstNamer::GetUnscopedLabelFor(InstBlockId block_id) const
  205. -> llvm::StringRef {
  206. if (!block_id.has_value()) {
  207. return "";
  208. }
  209. const auto& label_name =
  210. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)].second;
  211. return label_name ? label_name.GetFullName() : "";
  212. }
  213. // Returns the IR name to use for a label, when referenced from a given scope.
  214. auto InstNamer::GetLabelFor(ScopeId scope_id, InstBlockId block_id) const
  215. -> std::string {
  216. if (!block_id.has_value()) {
  217. return "!invalid";
  218. }
  219. const auto& [label_scope, label_name] =
  220. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)];
  221. if (!label_name) {
  222. // This should not happen in valid IR.
  223. RawStringOstream out;
  224. out << "<unexpected instblockref " << block_id << ">";
  225. return out.TakeStr();
  226. }
  227. if (label_scope == scope_id) {
  228. return ("!" + label_name.GetFullName()).str();
  229. }
  230. return (GetScopeName(label_scope) + ".!" + label_name.GetFullName()).str();
  231. }
  232. auto InstNamer::Namespace::Name::GetFullName() const -> llvm::StringRef {
  233. if (!value_) {
  234. return "<null name>";
  235. }
  236. llvm::StringMapEntry<NameResult>* value = value_;
  237. while (value->second.ambiguous && value->second.fallback) {
  238. value = value->second.fallback.value_;
  239. }
  240. return value->first();
  241. }
  242. auto InstNamer::Namespace::Name::GetBaseName() const -> llvm::StringRef {
  243. if (!value_) {
  244. return "<null name>";
  245. }
  246. return value_->first().take_front(base_name_size_);
  247. }
  248. auto InstNamer::Namespace::AllocateName(
  249. const InstNamer& inst_namer,
  250. std::variant<LocId, uint64_t> loc_id_or_fingerprint, std::string name)
  251. -> Name {
  252. // The best (shortest) name for this instruction so far, and the current
  253. // name for it.
  254. Name best;
  255. Name current;
  256. const size_t base_name_size = name.size();
  257. // Add `name` as a name for this entity.
  258. auto add_name = [&](bool mark_ambiguous = true) {
  259. auto [it, added] = allocated_.insert({name, NameResult()});
  260. Name new_name = Name(it, base_name_size);
  261. if (!added) {
  262. if (mark_ambiguous) {
  263. // This name was allocated for a different instruction. Mark it as
  264. // ambiguous and keep looking for a name for this instruction.
  265. new_name.SetAmbiguous();
  266. }
  267. } else {
  268. if (!best) {
  269. best = new_name;
  270. } else {
  271. CARBON_CHECK(current);
  272. current.SetFallback(new_name);
  273. }
  274. current = new_name;
  275. }
  276. return added;
  277. };
  278. // Use the given name if it's available.
  279. if (!name.empty()) {
  280. add_name();
  281. }
  282. // Append location information to try to disambiguate.
  283. if (auto* loc_id = std::get_if<LocId>(&loc_id_or_fingerprint)) {
  284. *loc_id = inst_namer.sem_ir_->insts().GetCanonicalLocId(*loc_id);
  285. // TODO: Consider handling other kinds.
  286. if (loc_id->kind() == LocId::Kind::NodeId) {
  287. const auto& tree = inst_namer.sem_ir_->parse_tree();
  288. auto token = tree.node_token(loc_id->node_id());
  289. llvm::raw_string_ostream(name)
  290. << ".loc" << tree.tokens().GetLineNumber(token);
  291. add_name();
  292. llvm::raw_string_ostream(name)
  293. << "_" << tree.tokens().GetColumnNumber(token);
  294. add_name();
  295. }
  296. } else {
  297. uint64_t fingerprint = std::get<uint64_t>(loc_id_or_fingerprint);
  298. llvm::raw_string_ostream out(name);
  299. out << ".";
  300. // Include names with 3-6 characters from the fingerprint. Then fall back to
  301. // sequential numbering.
  302. for (int n : llvm::seq(1, 7)) {
  303. out.write_hex((fingerprint >> (64 - 4 * n)) & 0xF);
  304. if (n >= 3) {
  305. add_name();
  306. }
  307. }
  308. }
  309. // Append numbers until we find an available name.
  310. name += ".";
  311. auto name_size_without_counter = name.size();
  312. for (int counter = 1;; ++counter) {
  313. name.resize(name_size_without_counter);
  314. llvm::raw_string_ostream(name) << counter;
  315. if (add_name(/*mark_ambiguous=*/false)) {
  316. return best;
  317. }
  318. }
  319. }
  320. auto InstNamer::AddBlockLabel(
  321. ScopeId scope_id, InstBlockId block_id, std::string name,
  322. std::variant<LocId, uint64_t> loc_id_or_fingerprint) -> void {
  323. if (!block_id.has_value() ||
  324. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)].second) {
  325. return;
  326. }
  327. if (auto* loc_id = std::get_if<LocId>(&loc_id_or_fingerprint);
  328. loc_id && !loc_id->has_value()) {
  329. if (const auto& block = sem_ir_->inst_blocks().Get(block_id);
  330. !block.empty()) {
  331. loc_id_or_fingerprint = LocId(block.front());
  332. }
  333. }
  334. labels_[sem_ir_->inst_blocks().GetRawIndex(block_id)] = {
  335. scope_id, GetScopeInfo(scope_id).labels.AllocateName(
  336. *this, loc_id_or_fingerprint, std::move(name))};
  337. }
  338. // Provides names for `AddBlockLabel`.
  339. struct BranchNames {
  340. // Returns names for a branching parse node, or nullopt if not a branch.
  341. static auto For(Parse::NodeKind node_kind) -> std::optional<BranchNames> {
  342. switch (node_kind) {
  343. case Parse::NodeKind::ForHeaderStart:
  344. return {{.prefix = "for", .branch = "next"}};
  345. case Parse::NodeKind::ForHeader:
  346. return {{.prefix = "for", .branch_if = "body", .branch = "done"}};
  347. case Parse::NodeKind::IfExprIf:
  348. return {{.prefix = "if.expr",
  349. .branch_if = "then",
  350. .branch = "else",
  351. .branch_with_arg = "result"}};
  352. case Parse::NodeKind::IfCondition:
  353. return {{.prefix = "if", .branch_if = "then", .branch = "else"}};
  354. case Parse::NodeKind::IfStatement:
  355. return {{.prefix = "if", .branch = "done"}};
  356. case Parse::NodeKind::ShortCircuitOperandAnd:
  357. return {
  358. {.prefix = "and", .branch_if = "rhs", .branch_with_arg = "result"}};
  359. case Parse::NodeKind::ShortCircuitOperandOr:
  360. return {
  361. {.prefix = "or", .branch_if = "rhs", .branch_with_arg = "result"}};
  362. case Parse::NodeKind::WhileConditionStart:
  363. return {{.prefix = "while", .branch = "cond"}};
  364. case Parse::NodeKind::WhileCondition:
  365. return {{.prefix = "while", .branch_if = "body", .branch = "done"}};
  366. default:
  367. return std::nullopt;
  368. }
  369. }
  370. // Returns the provided suffix for the instruction kind, or an empty string.
  371. auto GetSuffix(InstKind inst_kind) -> llvm::StringLiteral {
  372. switch (inst_kind) {
  373. case BranchIf::Kind:
  374. return branch_if;
  375. case Branch::Kind:
  376. return branch;
  377. case BranchWithArg::Kind:
  378. return branch_with_arg;
  379. default:
  380. return "";
  381. }
  382. }
  383. // The kind of branch, based on the node kind.
  384. llvm::StringLiteral prefix;
  385. // For labeling branch instruction kinds. Only expected kinds need a value;
  386. // the empty string is for unexpected kinds.
  387. llvm::StringLiteral branch_if = "";
  388. llvm::StringLiteral branch = "";
  389. llvm::StringLiteral branch_with_arg = "";
  390. };
  391. // Finds and adds a suitable block label for the given SemIR instruction that
  392. // represents some kind of branch.
  393. auto InstNamer::AddBlockLabel(ScopeId scope_id, LocId loc_id, AnyBranch branch)
  394. -> void {
  395. std::string label;
  396. loc_id = sem_ir_->insts().GetCanonicalLocId(loc_id);
  397. if (loc_id.node_id().has_value()) {
  398. if (auto names = BranchNames::For(
  399. sem_ir_->parse_tree().node_kind(loc_id.node_id()))) {
  400. if (auto suffix = names->GetSuffix(branch.kind); !suffix.empty()) {
  401. label = llvm::formatv("{0}.{1}", names->prefix, suffix);
  402. } else {
  403. label =
  404. llvm::formatv("{0}.<unexpected {1}>", names->prefix, branch.kind);
  405. }
  406. }
  407. }
  408. AddBlockLabel(scope_id, branch.target_id, label, loc_id);
  409. }
  410. auto InstNamer::PushBlockId(ScopeId scope_id, InstBlockId block_id) -> void {
  411. if (block_id.has_value()) {
  412. inst_block_stack_.push_back({scope_id, block_id});
  413. }
  414. }
  415. auto InstNamer::PushBlockInsts(ScopeId scope_id,
  416. llvm::ArrayRef<InstId> inst_ids) -> void {
  417. for (auto inst_id : llvm::reverse(inst_ids)) {
  418. if (inst_id.has_value() && !IsSingletonInstId(inst_id)) {
  419. inst_stack_.push_back(std::make_pair(scope_id, inst_id));
  420. }
  421. }
  422. }
  423. auto InstNamer::PushGeneric(ScopeId scope_id, GenericId generic_id) -> void {
  424. if (!generic_id.has_value()) {
  425. return;
  426. }
  427. generic_scopes_[sem_ir_->generics().GetRawIndex(generic_id)] = scope_id;
  428. const auto& generic = sem_ir_->generics().Get(generic_id);
  429. // Push blocks in reverse order.
  430. PushBlockId(scope_id, generic.definition_block_id);
  431. PushBlockId(scope_id, generic.decl_block_id);
  432. }
  433. auto InstNamer::PushEntity(AssociatedConstantId associated_constant_id,
  434. ScopeId scope_id, Scope& scope) -> void {
  435. const auto& assoc_const =
  436. sem_ir_->associated_constants().Get(associated_constant_id);
  437. scope.name = globals_.AllocateName(
  438. *this, LocId(assoc_const.decl_id),
  439. sem_ir_->names().GetIRBaseName(assoc_const.name_id).str());
  440. // Push blocks in reverse order.
  441. PushGeneric(scope_id, assoc_const.generic_id);
  442. }
  443. auto InstNamer::PushEntity(ClassId class_id, ScopeId scope_id, Scope& scope)
  444. -> void {
  445. const auto& class_info = sem_ir_->classes().Get(class_id);
  446. LocId class_loc(class_info.latest_decl_id());
  447. scope.name = globals_.AllocateName(
  448. *this, class_loc,
  449. sem_ir_->names().GetIRBaseName(class_info.name_id).str());
  450. AddBlockLabel(scope_id, class_info.body_block_id, "class", class_loc);
  451. PushGeneric(scope_id, class_info.generic_id);
  452. // Push blocks in reverse order.
  453. PushBlockId(scope_id, class_info.body_block_id);
  454. PushBlockId(scope_id, class_info.pattern_block_id);
  455. }
  456. auto InstNamer::GetNameForParentNameScope(NameScopeId name_scope_id)
  457. -> llvm::StringRef {
  458. if (!name_scope_id.has_value()) {
  459. return "";
  460. }
  461. auto scope_inst =
  462. sem_ir_->insts().Get(sem_ir_->name_scopes().Get(name_scope_id).inst_id());
  463. CARBON_KIND_SWITCH(scope_inst) {
  464. case CARBON_KIND(ClassDecl class_decl): {
  465. return MaybePushEntity(class_decl.class_id);
  466. }
  467. case CARBON_KIND(ImplDecl impl): {
  468. return MaybePushEntity(impl.impl_id);
  469. }
  470. case CARBON_KIND(InterfaceDecl interface): {
  471. return MaybePushEntity(interface.interface_id);
  472. }
  473. case CARBON_KIND(NamedConstraintDecl named_constraint): {
  474. return MaybePushEntity(named_constraint.named_constraint_id);
  475. }
  476. case SemIR::Namespace::Kind: {
  477. // Only prefix type scopes.
  478. return "";
  479. }
  480. default: {
  481. return "<unsupported scope>";
  482. }
  483. }
  484. }
  485. auto InstNamer::PushEntity(FunctionId function_id, ScopeId scope_id,
  486. Scope& scope) -> void {
  487. const auto& fn = sem_ir_->functions().Get(function_id);
  488. LocId fn_loc(fn.latest_decl_id());
  489. auto scope_prefix = GetNameForParentNameScope(fn.parent_scope_id);
  490. scope.name = globals_.AllocateName(
  491. *this, fn_loc,
  492. llvm::formatv("{0}{1}{2}", scope_prefix, scope_prefix.empty() ? "" : ".",
  493. sem_ir_->names().GetIRBaseName(fn.name_id)));
  494. if (!fn.body_block_ids.empty()) {
  495. AddBlockLabel(scope_id, fn.body_block_ids.front(), "entry", fn_loc);
  496. }
  497. // Push blocks in reverse order.
  498. PushGeneric(scope_id, fn.generic_id);
  499. for (auto block_id : llvm::reverse(fn.body_block_ids)) {
  500. PushBlockId(scope_id, block_id);
  501. }
  502. PushBlockId(scope_id, fn.pattern_block_id);
  503. PushBlockId(scope_id, fn.call_params_id);
  504. }
  505. auto InstNamer::PushEntity(CppOverloadSetId cpp_overload_set_id,
  506. ScopeId /*scope_id*/, Scope& scope) -> void {
  507. const CppOverloadSet& overload_set =
  508. sem_ir_->cpp_overload_sets().Get(cpp_overload_set_id);
  509. uint64_t fingerprint =
  510. fingerprinter_.GetOrCompute(sem_ir_, cpp_overload_set_id);
  511. auto scope_prefix = GetNameForParentNameScope(overload_set.parent_scope_id);
  512. scope.name = globals_.AllocateName(
  513. *this, fingerprint,
  514. llvm::formatv("{0}{1}{2}.cpp_overload_set", scope_prefix,
  515. scope_prefix.empty() ? "" : ".",
  516. sem_ir_->names().GetIRBaseName(overload_set.name_id)));
  517. }
  518. auto InstNamer::PushEntity(ImplId impl_id, ScopeId scope_id, Scope& scope)
  519. -> void {
  520. const auto& impl = sem_ir_->impls().Get(impl_id);
  521. auto impl_fingerprint = fingerprinter_.GetOrCompute(sem_ir_, impl_id);
  522. llvm::StringRef self_name;
  523. auto self_const_id =
  524. sem_ir_->constant_values().GetConstantInstId(impl.self_id);
  525. auto index = sem_ir_->insts().GetRawIndex(self_const_id);
  526. if (IsSingletonInstId(self_const_id)) {
  527. self_name = sem_ir_->insts().Get(self_const_id).kind().ir_name();
  528. } else if (const auto& inst_name = insts_[index].second) {
  529. self_name = inst_name.GetBaseName();
  530. } else {
  531. self_name = "<unexpected self>";
  532. }
  533. llvm::StringRef interface_name;
  534. if (impl.interface.interface_id.has_value()) {
  535. interface_name = MaybePushEntity(impl.interface.interface_id);
  536. } else {
  537. interface_name = "<error>";
  538. }
  539. scope.name = globals_.AllocateName(
  540. *this, impl_fingerprint,
  541. llvm::formatv("{0}.as.{1}.impl", self_name, interface_name));
  542. AddBlockLabel(scope_id, impl.body_block_id, "impl", impl_fingerprint);
  543. // Push blocks in reverse order.
  544. PushGeneric(scope_id, impl.generic_id);
  545. PushBlockId(scope_id, impl.body_block_id);
  546. PushBlockId(scope_id, impl.pattern_block_id);
  547. }
  548. auto InstNamer::PushEntity(InterfaceId interface_id, ScopeId scope_id,
  549. Scope& scope) -> void {
  550. const auto& interface = sem_ir_->interfaces().Get(interface_id);
  551. LocId interface_loc(interface.latest_decl_id());
  552. scope.name = globals_.AllocateName(
  553. *this, interface_loc,
  554. sem_ir_->names().GetIRBaseName(interface.name_id).str());
  555. AddBlockLabel(scope_id, interface.body_block_id, "interface", interface_loc);
  556. // Push blocks in reverse order.
  557. PushGeneric(scope_id, interface.generic_id);
  558. PushBlockId(scope_id, interface.body_block_id);
  559. PushBlockId(scope_id, interface.pattern_block_id);
  560. }
  561. auto InstNamer::PushEntity(NamedConstraintId named_constraint_id,
  562. ScopeId scope_id, Scope& scope) -> void {
  563. const auto& constraint =
  564. sem_ir_->named_constraints().Get(named_constraint_id);
  565. LocId constraint_loc(constraint.latest_decl_id());
  566. scope.name = globals_.AllocateName(
  567. *this, constraint_loc,
  568. sem_ir_->names().GetIRBaseName(constraint.name_id).str());
  569. AddBlockLabel(scope_id, constraint.body_block_id, "constraint",
  570. constraint_loc);
  571. // Push blocks in reverse order.
  572. PushGeneric(scope_id, constraint.generic_id);
  573. PushBlockId(scope_id, constraint.body_block_id);
  574. PushBlockId(scope_id, constraint.pattern_block_id);
  575. }
  576. auto InstNamer::PushEntity(VtableId vtable_id, ScopeId /*scope_id*/,
  577. Scope& scope) -> void {
  578. const auto& vtable = sem_ir_->vtables().Get(vtable_id);
  579. const auto& class_info = sem_ir_->classes().Get(vtable.class_id);
  580. LocId vtable_loc(class_info.latest_decl_id());
  581. scope.name = globals_.AllocateName(
  582. *this, vtable_loc,
  583. sem_ir_->names().GetIRBaseName(class_info.name_id).str() + ".vtable");
  584. // TODO: Add support for generic vtables here and elsewhere.
  585. // PushGeneric(scope_id, vtable_info.generic_id);
  586. }
  587. InstNamer::NamingContext::NamingContext(InstNamer* inst_namer,
  588. InstNamer::ScopeId scope_id,
  589. InstId inst_id)
  590. : inst_namer_(inst_namer),
  591. scope_id_(scope_id),
  592. inst_id_(inst_id),
  593. inst_(sem_ir().insts().Get(inst_id)) {}
  594. auto InstNamer::NamingContext::AddInstName(std::string name) -> void {
  595. auto index = sem_ir().insts().GetRawIndex(inst_id_);
  596. ScopeId old_scope_id = inst_namer_->insts_[index].first;
  597. if (old_scope_id == ScopeId::None) {
  598. std::variant<LocId, uint64_t> loc_id_or_fingerprint = LocId::None;
  599. if (scope_id_ == ScopeId::Constants || scope_id_ == ScopeId::Imports) {
  600. loc_id_or_fingerprint =
  601. inst_namer_->fingerprinter_.GetOrCompute(&sem_ir(), inst_id_);
  602. } else {
  603. loc_id_or_fingerprint = LocId(inst_id_);
  604. }
  605. auto scoped_name = inst_namer_->GetScopeInfo(scope_id_).insts.AllocateName(
  606. *inst_namer_, loc_id_or_fingerprint, std::move(name));
  607. inst_namer_->insts_[index] = {scope_id_, scoped_name};
  608. } else {
  609. CARBON_CHECK(old_scope_id == scope_id_,
  610. "Attempting to name inst in multiple scopes");
  611. }
  612. }
  613. auto InstNamer::NamingContext::AddIntOrFloatTypeName(char type_literal_prefix,
  614. InstId bit_width_id,
  615. llvm::StringRef suffix)
  616. -> void {
  617. RawStringOstream out;
  618. out << type_literal_prefix;
  619. if (auto bit_width = sem_ir().insts().TryGetAs<IntValue>(bit_width_id)) {
  620. out << sem_ir().ints().Get(bit_width->int_id);
  621. } else {
  622. out << "N";
  623. }
  624. out << suffix;
  625. AddInstName(out.TakeStr());
  626. }
  627. auto InstNamer::NamingContext::AddWitnessTableName(InstId witness_table_inst_id,
  628. std::string name) -> void {
  629. auto witness_table =
  630. sem_ir().insts().GetAs<ImplWitnessTable>(witness_table_inst_id);
  631. if (!witness_table.impl_id.has_value()) {
  632. // TODO: The witness comes from a facet value. Can we get the
  633. // interface names from it? Store the facet value instruction in the
  634. // table?
  635. AddInstName(name);
  636. return;
  637. }
  638. const auto& impl = sem_ir().impls().Get(witness_table.impl_id);
  639. auto name_id = sem_ir().interfaces().Get(impl.interface.interface_id).name_id;
  640. std::string suffix = llvm::formatv(".{}", name);
  641. AddInstNameId(name_id, suffix);
  642. }
  643. auto InstNamer::NamingContext::NameInst() -> void {
  644. CARBON_KIND_SWITCH(inst_) {
  645. case AddrOf::Kind: {
  646. AddInstName("addr");
  647. return;
  648. }
  649. case ArrayType::Kind: {
  650. // TODO: Can we figure out the name of the type this is an array of?
  651. AddInstName("array_type");
  652. return;
  653. }
  654. case CARBON_KIND(AssociatedConstantDecl inst): {
  655. AddEntityNameAndMaybePush(inst.assoc_const_id);
  656. PushBlockId(inst_namer_->GetScopeFor(inst.assoc_const_id),
  657. inst.decl_block_id);
  658. return;
  659. }
  660. case CARBON_KIND(AssociatedEntity inst): {
  661. RawStringOstream out;
  662. out << "assoc" << inst.index.index;
  663. AddInstName(out.TakeStr());
  664. return;
  665. }
  666. case CARBON_KIND(AssociatedEntityType inst): {
  667. AddEntityNameAndMaybePush(inst.interface_id, ".assoc_type");
  668. return;
  669. }
  670. case AliasBinding::Kind:
  671. case RefBinding::Kind:
  672. case SymbolicBinding::Kind:
  673. case ValueBinding::Kind:
  674. case ExportDecl::Kind: {
  675. auto inst = inst_.As<AnyBindingOrExportDecl>();
  676. AddInstNameId(sem_ir().entity_names().Get(inst.entity_name_id).name_id);
  677. return;
  678. }
  679. case RefBindingPattern::Kind:
  680. case SymbolicBindingPattern::Kind:
  681. case ValueBindingPattern::Kind: {
  682. auto inst = inst_.As<AnyBindingPattern>();
  683. auto name_id = NameId::Underscore;
  684. if (inst.entity_name_id.has_value()) {
  685. name_id = sem_ir().entity_names().Get(inst.entity_name_id).name_id;
  686. }
  687. AddInstNameId(name_id, ".patt");
  688. return;
  689. }
  690. case CARBON_KIND(BoolLiteral inst): {
  691. if (inst.value.ToBool()) {
  692. AddInstName("true");
  693. } else {
  694. AddInstName("false");
  695. }
  696. return;
  697. }
  698. case CARBON_KIND(BoundMethod inst): {
  699. auto type_id = sem_ir().insts().Get(inst.function_decl_id).type_id();
  700. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  701. AddEntityNameAndMaybePush(fn_ty->function_id, ".bound");
  702. } else {
  703. AddInstName("bound_method");
  704. }
  705. return;
  706. }
  707. case Branch::Kind:
  708. case BranchIf::Kind:
  709. case BranchWithArg::Kind: {
  710. auto branch = inst_.As<AnyBranch>();
  711. inst_namer_->AddBlockLabel(scope_id_, LocId(inst_id_), branch);
  712. return;
  713. }
  714. case CARBON_KIND(Call inst): {
  715. auto callee = GetCallee(sem_ir(), inst.callee_id);
  716. if (auto* fn = std::get_if<CalleeFunction>(&callee)) {
  717. AddEntityNameAndMaybePush(fn->function_id, ".call");
  718. return;
  719. }
  720. AddInstName("");
  721. return;
  722. }
  723. case CARBON_KIND(ClassDecl inst): {
  724. AddEntityNameAndMaybePush(inst.class_id, ".decl");
  725. auto class_scope_id = inst_namer_->GetScopeFor(inst.class_id);
  726. PushBlockId(class_scope_id, inst.decl_block_id);
  727. return;
  728. }
  729. case CARBON_KIND(ClassType inst): {
  730. if (auto literal_info = TypeLiteralInfo::ForType(sem_ir(), inst);
  731. literal_info.is_valid()) {
  732. AddInstName(literal_info.GetLiteralAsString(sem_ir()));
  733. } else {
  734. AddEntityNameAndMaybePush(inst.class_id);
  735. }
  736. return;
  737. }
  738. case CompleteTypeWitness::Kind: {
  739. // TODO: Can we figure out the name of the type this is a witness for?
  740. AddInstName("complete_type");
  741. return;
  742. }
  743. case CARBON_KIND(VtableDecl inst): {
  744. const auto& vtable = sem_ir().vtables().Get(inst.vtable_id);
  745. inst_namer_->MaybePushEntity(inst.vtable_id);
  746. if (inst_namer_->GetScopeFor(vtable.class_id) == scope_id_) {
  747. inst_namer_->MaybePushEntity(vtable.class_id);
  748. AddInstName("vtable_decl");
  749. } else {
  750. AddEntityNameAndMaybePush(vtable.class_id, ".vtable_decl");
  751. }
  752. return;
  753. }
  754. case CARBON_KIND(VtablePtr inst): {
  755. const auto& vtable = sem_ir().vtables().Get(inst.vtable_id);
  756. inst_namer_->MaybePushEntity(inst.vtable_id);
  757. AddEntityNameAndMaybePush(vtable.class_id, ".vtable_ptr");
  758. return;
  759. }
  760. case ConstType::Kind: {
  761. // TODO: Can we figure out the name of the type argument?
  762. AddInstName("const");
  763. return;
  764. }
  765. case CARBON_KIND(FacetAccessType inst): {
  766. if (auto name =
  767. sem_ir().insts().TryGetAs<NameRef>(inst.facet_value_inst_id)) {
  768. AddInstNameId(name->name_id, ".as_type");
  769. } else {
  770. AddInstName("as_type");
  771. }
  772. return;
  773. }
  774. case CARBON_KIND(SymbolicBindingType inst): {
  775. auto bind =
  776. sem_ir().insts().GetAs<SymbolicBinding>(inst.facet_value_inst_id);
  777. auto name_id = sem_ir().entity_names().Get(bind.entity_name_id).name_id;
  778. if (name_id.has_value()) {
  779. AddInstNameId(name_id, ".binding.as_type");
  780. } else {
  781. AddInstName("binding.as_type");
  782. }
  783. return;
  784. }
  785. case CARBON_KIND(FacetType inst): {
  786. const auto& facet_type_info =
  787. sem_ir().facet_types().Get(inst.facet_type_id);
  788. bool has_where = facet_type_info.other_requirements ||
  789. !facet_type_info.builtin_constraint_mask.empty() ||
  790. !facet_type_info.self_impls_constraints.empty() ||
  791. !facet_type_info.rewrite_constraints.empty();
  792. if (facet_type_info.extend_constraints.size() == 1) {
  793. AddEntityNameAndMaybePush(
  794. facet_type_info.extend_constraints.front().interface_id,
  795. has_where ? "_where.type" : ".type");
  796. } else if (facet_type_info.extend_constraints.empty()) {
  797. AddInstName(has_where ? "type_where" : "type");
  798. } else {
  799. AddInstName("facet_type");
  800. }
  801. return;
  802. }
  803. case CARBON_KIND(FacetValue inst): {
  804. if (auto facet_type =
  805. sem_ir().types().TryGetAs<FacetType>(inst.type_id)) {
  806. const auto& facet_type_info =
  807. sem_ir().facet_types().Get(facet_type->facet_type_id);
  808. if (auto interface = facet_type_info.TryAsSingleInterface()) {
  809. AddEntityNameAndMaybePush(interface->interface_id, ".facet");
  810. return;
  811. }
  812. }
  813. AddInstName("facet_value");
  814. return;
  815. }
  816. case CARBON_KIND(FloatType inst): {
  817. AddIntOrFloatTypeName('f', inst.bit_width_id);
  818. return;
  819. }
  820. case FloatLiteralValue::Kind:
  821. case FloatValue::Kind: {
  822. AddInstName("float");
  823. return;
  824. }
  825. case CARBON_KIND(FunctionDecl inst): {
  826. AddEntityNameAndMaybePush(inst.function_id, ".decl");
  827. auto function_scope_id = inst_namer_->GetScopeFor(inst.function_id);
  828. PushBlockId(function_scope_id, inst.decl_block_id);
  829. return;
  830. }
  831. case CARBON_KIND(FunctionType inst): {
  832. AddEntityNameAndMaybePush(inst.function_id, ".type");
  833. return;
  834. }
  835. case CARBON_KIND(CppOverloadSetValue inst): {
  836. AddEntityNameAndMaybePush(inst.overload_set_id, ".value");
  837. return;
  838. }
  839. case CARBON_KIND(CppOverloadSetType inst): {
  840. AddEntityNameAndMaybePush(inst.overload_set_id, ".type");
  841. return;
  842. }
  843. case CARBON_KIND(GenericClassType inst): {
  844. AddEntityNameAndMaybePush(inst.class_id, ".type");
  845. return;
  846. }
  847. case CARBON_KIND(GenericInterfaceType inst): {
  848. AddEntityNameAndMaybePush(inst.interface_id, ".type");
  849. return;
  850. }
  851. case CARBON_KIND(GenericNamedConstraintType inst): {
  852. AddEntityNameAndMaybePush(inst.named_constraint_id, ".type");
  853. return;
  854. }
  855. case CARBON_KIND(ImplDecl inst): {
  856. // `impl` declarations aren't named because they aren't added to any
  857. // namespace, and so aren't referenced directly.
  858. inst_namer_->MaybePushEntity(inst.impl_id);
  859. PushBlockId(inst_namer_->GetScopeFor(inst.impl_id), inst.decl_block_id);
  860. return;
  861. }
  862. case CARBON_KIND(LookupImplWitness inst): {
  863. const auto& interface =
  864. sem_ir().specific_interfaces().Get(inst.query_specific_interface_id);
  865. AddEntityNameAndMaybePush(interface.interface_id, ".lookup_impl_witness");
  866. return;
  867. }
  868. case CARBON_KIND(ImplWitness inst): {
  869. AddWitnessTableName(inst.witness_table_id, "impl_witness");
  870. return;
  871. }
  872. case CARBON_KIND(ImplWitnessAccess inst): {
  873. // TODO: Include information about the impl?
  874. RawStringOstream out;
  875. out << "impl.elem" << inst.index.index;
  876. AddInstName(out.TakeStr());
  877. return;
  878. }
  879. case CARBON_KIND(ImplWitnessAccessSubstituted inst): {
  880. // TODO: Include information about the impl?
  881. RawStringOstream out;
  882. auto access = sem_ir().insts().GetAs<ImplWitnessAccess>(
  883. inst.impl_witness_access_id);
  884. out << "impl.elem" << access.index.index << ".subst";
  885. AddInstName(out.TakeStr());
  886. return;
  887. }
  888. case ImplWitnessAssociatedConstant::Kind: {
  889. AddInstName("impl_witness_assoc_constant");
  890. return;
  891. }
  892. case ImplWitnessTable::Kind: {
  893. AddWitnessTableName(inst_id_, "impl_witness_table");
  894. return;
  895. }
  896. case ImportCppDecl::Kind: {
  897. AddInstName("Cpp.import_cpp");
  898. return;
  899. }
  900. case CARBON_KIND(ImportDecl inst): {
  901. if (inst.package_id.has_value()) {
  902. AddInstNameId(inst.package_id, ".import");
  903. } else {
  904. AddInstName("default.import");
  905. }
  906. return;
  907. }
  908. case ImportRefUnloaded::Kind:
  909. case ImportRefLoaded::Kind: {
  910. // Build the base import name: <package>.<entity-name>
  911. RawStringOstream out;
  912. auto inst = inst_.As<AnyImportRef>();
  913. auto import_ir_inst =
  914. sem_ir().import_ir_insts().Get(inst.import_ir_inst_id);
  915. const auto& import_ir =
  916. *sem_ir().import_irs().Get(import_ir_inst.ir_id()).sem_ir;
  917. auto package_id = import_ir.package_id();
  918. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  919. out << import_ir.identifiers().Get(ident_id);
  920. } else {
  921. out << package_id.AsSpecialName();
  922. }
  923. out << ".";
  924. // Add entity name if available.
  925. if (inst.entity_name_id.has_value()) {
  926. auto name_id = sem_ir().entity_names().Get(inst.entity_name_id).name_id;
  927. out << sem_ir().names().GetIRBaseName(name_id);
  928. } else {
  929. out << "import_ref";
  930. }
  931. AddInstName(out.TakeStr());
  932. // When building import refs, we frequently add instructions without
  933. // a block. Constants that refer to them need to be separately
  934. // named.
  935. auto const_id = sem_ir().constant_values().Get(inst_id_);
  936. if (const_id.has_value() && const_id.is_concrete()) {
  937. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  938. auto index = sem_ir().insts().GetRawIndex(const_inst_id);
  939. if (!inst_namer_->insts_[index].second) {
  940. inst_namer_->PushBlockInsts(ScopeId::Imports, const_inst_id);
  941. }
  942. }
  943. return;
  944. }
  945. case CARBON_KIND(InstValue inst): {
  946. inst_namer_->PushBlockInsts(scope_id_, inst.inst_id);
  947. AddInstName(
  948. ("inst." + sem_ir().insts().Get(inst.inst_id).kind().ir_name())
  949. .str());
  950. return;
  951. }
  952. case CARBON_KIND(InterfaceDecl inst): {
  953. AddEntityNameAndMaybePush(inst.interface_id, ".decl");
  954. auto interface_scope_id = inst_namer_->GetScopeFor(inst.interface_id);
  955. PushBlockId(interface_scope_id, inst.decl_block_id);
  956. return;
  957. }
  958. case CARBON_KIND(IntType inst): {
  959. AddIntOrFloatTypeName(inst.int_kind == IntKind::Signed ? 'i' : 'u',
  960. inst.bit_width_id, ".builtin");
  961. return;
  962. }
  963. case CARBON_KIND(IntValue inst): {
  964. RawStringOstream out;
  965. out << "int_" << sem_ir().ints().Get(inst.int_id);
  966. AddInstName(out.TakeStr());
  967. return;
  968. }
  969. case CARBON_KIND(NameBindingDecl inst): {
  970. PushBlockId(scope_id_, inst.pattern_block_id);
  971. return;
  972. }
  973. case CARBON_KIND(NamedConstraintDecl inst): {
  974. AddEntityNameAndMaybePush(inst.named_constraint_id, ".decl");
  975. auto interface_scope_id =
  976. inst_namer_->GetScopeFor(inst.named_constraint_id);
  977. PushBlockId(interface_scope_id, inst.decl_block_id);
  978. return;
  979. }
  980. case CARBON_KIND(NameRef inst): {
  981. AddInstNameId(inst.name_id, ".ref");
  982. return;
  983. }
  984. // The namespace is specified here due to the name conflict.
  985. case CARBON_KIND(SemIR::Namespace inst): {
  986. AddInstNameId(sem_ir().name_scopes().Get(inst.name_scope_id).name_id());
  987. return;
  988. }
  989. case OutParam::Kind:
  990. case RefParam::Kind:
  991. case ValueParam::Kind: {
  992. AddInstNameId(inst_.As<AnyParam>().pretty_name_id, ".param");
  993. return;
  994. }
  995. case OutParamPattern::Kind:
  996. case RefParamPattern::Kind:
  997. case ValueParamPattern::Kind: {
  998. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst_id_),
  999. ".param_patt");
  1000. return;
  1001. }
  1002. case PatternType::Kind: {
  1003. AddInstName("pattern_type");
  1004. return;
  1005. }
  1006. case PointerType::Kind: {
  1007. AddInstName("ptr");
  1008. return;
  1009. }
  1010. case RequireCompleteType::Kind: {
  1011. AddInstName("require_complete");
  1012. return;
  1013. }
  1014. case ReturnSlotPattern::Kind: {
  1015. AddInstNameId(NameId::ReturnSlot, ".patt");
  1016. return;
  1017. }
  1018. case CARBON_KIND(SpecificFunction inst): {
  1019. auto type_id = sem_ir().insts().Get(inst.callee_id).type_id();
  1020. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  1021. AddEntityNameAndMaybePush(fn_ty->function_id, ".specific_fn");
  1022. } else {
  1023. AddInstName("specific_fn");
  1024. }
  1025. return;
  1026. }
  1027. case CARBON_KIND(SpecificImplFunction inst): {
  1028. auto type_id = sem_ir().insts().Get(inst.callee_id).type_id();
  1029. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(type_id)) {
  1030. AddEntityNameAndMaybePush(fn_ty->function_id, ".specific_impl_fn");
  1031. } else {
  1032. AddInstName("specific_impl_fn");
  1033. }
  1034. return;
  1035. }
  1036. case ReturnSlot::Kind: {
  1037. AddInstNameId(NameId::ReturnSlot);
  1038. return;
  1039. }
  1040. case CARBON_KIND(SpliceBlock inst): {
  1041. PushBlockId(scope_id_, inst.block_id);
  1042. AddInstName("");
  1043. return;
  1044. }
  1045. case StringLiteral::Kind: {
  1046. AddInstName("str");
  1047. return;
  1048. }
  1049. case CARBON_KIND(StructValue inst): {
  1050. if (auto fn_ty = sem_ir().types().TryGetAs<FunctionType>(inst.type_id)) {
  1051. AddEntityNameAndMaybePush(fn_ty->function_id);
  1052. } else if (auto class_ty =
  1053. sem_ir().types().TryGetAs<ClassType>(inst.type_id)) {
  1054. AddEntityNameAndMaybePush(class_ty->class_id, ".val");
  1055. } else if (auto generic_class_ty =
  1056. sem_ir().types().TryGetAs<GenericClassType>(
  1057. inst.type_id)) {
  1058. AddEntityNameAndMaybePush(generic_class_ty->class_id, ".generic");
  1059. } else if (auto generic_interface_ty =
  1060. sem_ir().types().TryGetAs<GenericInterfaceType>(
  1061. inst.type_id)) {
  1062. AddInstNameId(sem_ir()
  1063. .interfaces()
  1064. .Get(generic_interface_ty->interface_id)
  1065. .name_id,
  1066. ".generic");
  1067. } else {
  1068. if (sem_ir().inst_blocks().Get(inst.elements_id).empty()) {
  1069. AddInstName("empty_struct");
  1070. } else {
  1071. AddInstName("struct");
  1072. }
  1073. }
  1074. return;
  1075. }
  1076. case CARBON_KIND(StructType inst): {
  1077. const auto& fields = sem_ir().struct_type_fields().Get(inst.fields_id);
  1078. if (fields.empty()) {
  1079. AddInstName("empty_struct_type");
  1080. return;
  1081. }
  1082. std::string name = "struct_type";
  1083. for (auto field : fields) {
  1084. name += ".";
  1085. name += sem_ir().names().GetIRBaseName(field.name_id).str();
  1086. }
  1087. AddInstName(std::move(name));
  1088. return;
  1089. }
  1090. case CARBON_KIND(TupleAccess inst): {
  1091. RawStringOstream out;
  1092. out << "tuple.elem" << inst.index.index;
  1093. AddInstName(out.TakeStr());
  1094. return;
  1095. }
  1096. case CARBON_KIND(TupleType inst): {
  1097. if (inst.type_elements_id == InstBlockId::Empty) {
  1098. AddInstName("empty_tuple.type");
  1099. } else {
  1100. AddInstName("tuple.type");
  1101. }
  1102. return;
  1103. }
  1104. case CARBON_KIND(TupleValue inst): {
  1105. if (sem_ir().types().Is<ArrayType>(inst.type_id)) {
  1106. AddInstName("array");
  1107. } else if (inst.elements_id == InstBlockId::Empty) {
  1108. AddInstName("empty_tuple");
  1109. } else {
  1110. AddInstName("tuple");
  1111. }
  1112. return;
  1113. }
  1114. case CARBON_KIND(UnboundElementType inst): {
  1115. if (auto class_ty =
  1116. sem_ir().insts().TryGetAs<ClassType>(inst.class_type_inst_id)) {
  1117. AddEntityNameAndMaybePush(class_ty->class_id, ".elem");
  1118. } else {
  1119. AddInstName("elem_type");
  1120. }
  1121. return;
  1122. }
  1123. case VarPattern::Kind: {
  1124. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst_id_),
  1125. ".var_patt");
  1126. return;
  1127. }
  1128. case CARBON_KIND(VarStorage inst): {
  1129. if (inst.pattern_id.has_value()) {
  1130. AddInstNameId(GetPrettyNameFromPatternId(sem_ir(), inst.pattern_id),
  1131. ".var");
  1132. } else {
  1133. AddInstName("var");
  1134. }
  1135. return;
  1136. }
  1137. default: {
  1138. // Sequentially number all remaining values.
  1139. if (inst_.kind().has_type()) {
  1140. AddInstName("");
  1141. }
  1142. return;
  1143. }
  1144. }
  1145. }
  1146. auto InstNamer::has_name(InstId inst_id) const -> bool {
  1147. return static_cast<bool>(
  1148. insts_[sem_ir_->insts().GetRawIndex(inst_id)].second);
  1149. }
  1150. } // namespace Carbon::SemIR