inst_namer.cpp 47 KB

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