formatter.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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/formatter.h"
  5. #include "common/ostream.h"
  6. #include "llvm/ADT/Sequence.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "llvm/ADT/StringMap.h"
  9. #include "llvm/Support/SaveAndRestore.h"
  10. #include "toolchain/base/value_store.h"
  11. #include "toolchain/lex/tokenized_buffer.h"
  12. #include "toolchain/parse/tree.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/typed_insts.h"
  15. namespace Carbon::SemIR {
  16. namespace {
  17. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  18. //
  19. // TODOs / future work ideas:
  20. // - Add a documentation file for the textual format and link to the
  21. // naming section here.
  22. // - Consider representing literals as just `literal` in the IR and using the
  23. // type to distinguish.
  24. class InstNamer {
  25. public:
  26. // int32_t matches the input value size.
  27. // NOLINTNEXTLINE(performance-enum-size)
  28. enum class ScopeIndex : int32_t {
  29. None = -1,
  30. File = 0,
  31. Constants = 1,
  32. FirstFunction = 2,
  33. };
  34. static_assert(sizeof(ScopeIndex) == sizeof(FunctionId));
  35. InstNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  36. const Parse::Tree& parse_tree, const File& sem_ir)
  37. : tokenized_buffer_(tokenized_buffer),
  38. parse_tree_(parse_tree),
  39. sem_ir_(sem_ir) {
  40. insts.resize(sem_ir.insts().size());
  41. labels.resize(sem_ir.inst_blocks().size());
  42. scopes.resize(static_cast<int32_t>(ScopeIndex::FirstFunction) +
  43. sem_ir.functions().size() + sem_ir.classes().size() +
  44. sem_ir.interfaces().size());
  45. // Build the constants scope.
  46. GetScopeInfo(ScopeIndex::Constants).name =
  47. globals.AddNameUnchecked("constants");
  48. CollectNamesInBlock(ScopeIndex::Constants,
  49. sem_ir.constants().GetAsVector());
  50. // Build the file scope.
  51. GetScopeInfo(ScopeIndex::File).name = globals.AddNameUnchecked("file");
  52. CollectNamesInBlock(ScopeIndex::File, sem_ir.top_inst_block_id());
  53. // Build each function scope.
  54. for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) {
  55. auto fn_id = FunctionId(i);
  56. auto fn_scope = GetScopeFor(fn_id);
  57. // TODO: Provide a location for the function for use as a
  58. // disambiguator.
  59. auto fn_loc = Parse::NodeId::Invalid;
  60. GetScopeInfo(fn_scope).name = globals.AllocateName(
  61. *this, fn_loc, sem_ir.names().GetIRBaseName(fn.name_id).str());
  62. CollectNamesInBlock(fn_scope, fn.implicit_param_refs_id);
  63. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  64. if (fn.return_slot_id.is_valid()) {
  65. insts[fn.return_slot_id.index] = {
  66. fn_scope, GetScopeInfo(fn_scope).insts.AllocateName(
  67. *this, sem_ir.insts().GetParseNode(fn.return_slot_id),
  68. "return")};
  69. }
  70. if (!fn.body_block_ids.empty()) {
  71. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  72. }
  73. for (auto block_id : fn.body_block_ids) {
  74. CollectNamesInBlock(fn_scope, block_id);
  75. }
  76. for (auto block_id : fn.body_block_ids) {
  77. AddBlockLabel(fn_scope, block_id);
  78. }
  79. }
  80. // Build each class scope.
  81. for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) {
  82. auto class_id = ClassId(i);
  83. auto class_scope = GetScopeFor(class_id);
  84. // TODO: Provide a location for the class for use as a
  85. // disambiguator.
  86. auto class_loc = Parse::NodeId::Invalid;
  87. GetScopeInfo(class_scope).name = globals.AllocateName(
  88. *this, class_loc,
  89. sem_ir.names().GetIRBaseName(class_info.name_id).str());
  90. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  91. CollectNamesInBlock(class_scope, class_info.body_block_id);
  92. }
  93. // Build each interface scope.
  94. for (auto [i, interface_info] :
  95. llvm::enumerate(sem_ir.interfaces().array_ref())) {
  96. auto interface_id = InterfaceId(i);
  97. auto interface_scope = GetScopeFor(interface_id);
  98. // TODO: Provide a location for the interface for use as a
  99. // disambiguator.
  100. auto interface_loc = Parse::NodeId::Invalid;
  101. GetScopeInfo(interface_scope).name = globals.AllocateName(
  102. *this, interface_loc,
  103. sem_ir.names().GetIRBaseName(interface_info.name_id).str());
  104. AddBlockLabel(interface_scope, interface_info.body_block_id, "interface",
  105. interface_loc);
  106. CollectNamesInBlock(interface_scope, interface_info.body_block_id);
  107. }
  108. }
  109. // Returns the scope index corresponding to a function.
  110. auto GetScopeFor(FunctionId fn_id) -> ScopeIndex {
  111. return static_cast<ScopeIndex>(
  112. static_cast<int32_t>(ScopeIndex::FirstFunction) + fn_id.index);
  113. }
  114. // Returns the scope index corresponding to a class.
  115. auto GetScopeFor(ClassId class_id) -> ScopeIndex {
  116. return static_cast<ScopeIndex>(
  117. static_cast<int32_t>(ScopeIndex::FirstFunction) +
  118. sem_ir_.functions().size() + class_id.index);
  119. }
  120. // Returns the scope index corresponding to an interface.
  121. auto GetScopeFor(InterfaceId interface_id) -> ScopeIndex {
  122. return static_cast<ScopeIndex>(
  123. static_cast<int32_t>(ScopeIndex::FirstFunction) +
  124. sem_ir_.functions().size() + sem_ir_.classes().size() +
  125. interface_id.index);
  126. }
  127. // Returns the IR name to use for a function.
  128. auto GetNameFor(FunctionId fn_id) -> llvm::StringRef {
  129. if (!fn_id.is_valid()) {
  130. return "invalid";
  131. }
  132. return GetScopeInfo(GetScopeFor(fn_id)).name.str();
  133. }
  134. // Returns the IR name to use for a class.
  135. auto GetNameFor(ClassId class_id) -> llvm::StringRef {
  136. if (!class_id.is_valid()) {
  137. return "invalid";
  138. }
  139. return GetScopeInfo(GetScopeFor(class_id)).name.str();
  140. }
  141. // Returns the IR name to use for an interface.
  142. auto GetNameFor(InterfaceId interface_id) -> llvm::StringRef {
  143. if (!interface_id.is_valid()) {
  144. return "invalid";
  145. }
  146. return GetScopeInfo(GetScopeFor(interface_id)).name.str();
  147. }
  148. // Returns the IR name to use for an instruction, when referenced from a given
  149. // scope.
  150. auto GetNameFor(ScopeIndex scope_idx, InstId inst_id) -> std::string {
  151. if (!inst_id.is_valid()) {
  152. return "invalid";
  153. }
  154. // Check for a builtin.
  155. if (inst_id.is_builtin()) {
  156. return inst_id.builtin_kind().label().str();
  157. }
  158. if (inst_id == InstId::PackageNamespace) {
  159. return "package";
  160. }
  161. auto& [inst_scope, inst_name] = insts[inst_id.index];
  162. if (!inst_name) {
  163. // This should not happen in valid IR.
  164. std::string str;
  165. llvm::raw_string_ostream(str) << "<unexpected instref " << inst_id << ">";
  166. return str;
  167. }
  168. if (inst_scope == scope_idx) {
  169. return inst_name.str().str();
  170. }
  171. return (GetScopeInfo(inst_scope).name.str() + "." + inst_name.str()).str();
  172. }
  173. // Returns the IR name to use for a label, when referenced from a given scope.
  174. auto GetLabelFor(ScopeIndex scope_idx, InstBlockId block_id) -> std::string {
  175. if (!block_id.is_valid()) {
  176. return "!invalid";
  177. }
  178. auto& [label_scope, label_name] = labels[block_id.index];
  179. if (!label_name) {
  180. // This should not happen in valid IR.
  181. std::string str;
  182. llvm::raw_string_ostream(str)
  183. << "<unexpected instblockref " << block_id << ">";
  184. return str;
  185. }
  186. if (label_scope == scope_idx) {
  187. return label_name.str().str();
  188. }
  189. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  190. .str();
  191. }
  192. private:
  193. // A space in which unique names can be allocated.
  194. struct Namespace {
  195. // A result of a name lookup.
  196. struct NameResult;
  197. // A name in a namespace, which might be redirected to refer to another name
  198. // for disambiguation purposes.
  199. class Name {
  200. public:
  201. Name() : value_(nullptr) {}
  202. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  203. explicit operator bool() const { return value_; }
  204. auto str() const -> llvm::StringRef {
  205. llvm::StringMapEntry<NameResult>* value = value_;
  206. CARBON_CHECK(value) << "cannot print a null name";
  207. while (value->second.ambiguous && value->second.fallback) {
  208. value = value->second.fallback.value_;
  209. }
  210. return value->first();
  211. }
  212. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  213. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  214. private:
  215. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  216. };
  217. struct NameResult {
  218. bool ambiguous = false;
  219. Name fallback = Name();
  220. };
  221. llvm::StringRef prefix;
  222. llvm::StringMap<NameResult> allocated = {};
  223. int unnamed_count = 0;
  224. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  225. return Name(allocated.insert({name, NameResult()}).first);
  226. }
  227. auto AllocateName(const InstNamer& namer, Parse::NodeId node,
  228. std::string name) -> Name {
  229. // The best (shortest) name for this instruction so far, and the current
  230. // name for it.
  231. Name best;
  232. Name current;
  233. // Add `name` as a name for this entity.
  234. auto add_name = [&](bool mark_ambiguous = true) {
  235. auto [it, added] = allocated.insert({name, NameResult()});
  236. Name new_name = Name(it);
  237. if (!added) {
  238. if (mark_ambiguous) {
  239. // This name was allocated for a different instruction. Mark it as
  240. // ambiguous and keep looking for a name for this instruction.
  241. new_name.SetAmbiguous();
  242. }
  243. } else {
  244. if (!best) {
  245. best = new_name;
  246. } else {
  247. CARBON_CHECK(current);
  248. current.SetFallback(new_name);
  249. }
  250. current = new_name;
  251. }
  252. return added;
  253. };
  254. // All names start with the prefix.
  255. name.insert(0, prefix);
  256. // Use the given name if it's available and not just the prefix.
  257. if (name.size() > prefix.size()) {
  258. add_name();
  259. }
  260. // Append location information to try to disambiguate.
  261. if (node.is_valid()) {
  262. auto token = namer.parse_tree_.node_token(node);
  263. llvm::raw_string_ostream(name)
  264. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  265. add_name();
  266. llvm::raw_string_ostream(name)
  267. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  268. add_name();
  269. }
  270. // Append numbers until we find an available name.
  271. name += ".";
  272. auto name_size_without_counter = name.size();
  273. for (int counter = 1;; ++counter) {
  274. name.resize(name_size_without_counter);
  275. llvm::raw_string_ostream(name) << counter;
  276. if (add_name(/*mark_ambiguous=*/false)) {
  277. return best;
  278. }
  279. }
  280. }
  281. };
  282. // A named scope that contains named entities.
  283. struct Scope {
  284. Namespace::Name name;
  285. Namespace insts = {.prefix = "%"};
  286. Namespace labels = {.prefix = "!"};
  287. };
  288. auto GetScopeInfo(ScopeIndex scope_idx) -> Scope& {
  289. return scopes[static_cast<int>(scope_idx)];
  290. }
  291. auto AddBlockLabel(ScopeIndex scope_idx, InstBlockId block_id,
  292. std::string name = "",
  293. Parse::NodeId parse_node = Parse::NodeId::Invalid)
  294. -> void {
  295. if (!block_id.is_valid() || labels[block_id.index].second) {
  296. return;
  297. }
  298. if (!parse_node.is_valid()) {
  299. if (const auto& block = sem_ir_.inst_blocks().Get(block_id);
  300. !block.empty()) {
  301. parse_node = sem_ir_.insts().GetParseNode(block.front());
  302. }
  303. }
  304. labels[block_id.index] = {scope_idx,
  305. GetScopeInfo(scope_idx).labels.AllocateName(
  306. *this, parse_node, std::move(name))};
  307. }
  308. // Finds and adds a suitable block label for the given SemIR instruction that
  309. // represents some kind of branch.
  310. auto AddBlockLabel(ScopeIndex scope_idx, Parse::NodeId parse_node,
  311. AnyBranch branch) -> void {
  312. llvm::StringRef name;
  313. switch (parse_tree_.node_kind(parse_node)) {
  314. case Parse::NodeKind::IfExprIf:
  315. switch (branch.kind) {
  316. case BranchIf::Kind:
  317. name = "if.expr.then";
  318. break;
  319. case Branch::Kind:
  320. name = "if.expr.else";
  321. break;
  322. case BranchWithArg::Kind:
  323. name = "if.expr.result";
  324. break;
  325. default:
  326. break;
  327. }
  328. break;
  329. case Parse::NodeKind::IfCondition:
  330. switch (branch.kind) {
  331. case BranchIf::Kind:
  332. name = "if.then";
  333. break;
  334. case Branch::Kind:
  335. name = "if.else";
  336. break;
  337. default:
  338. break;
  339. }
  340. break;
  341. case Parse::NodeKind::IfStatement:
  342. name = "if.done";
  343. break;
  344. case Parse::NodeKind::ShortCircuitOperandAnd:
  345. name = branch.kind == BranchIf::Kind ? "and.rhs" : "and.result";
  346. break;
  347. case Parse::NodeKind::ShortCircuitOperandOr:
  348. name = branch.kind == BranchIf::Kind ? "or.rhs" : "or.result";
  349. break;
  350. case Parse::NodeKind::WhileConditionStart:
  351. name = "while.cond";
  352. break;
  353. case Parse::NodeKind::WhileCondition:
  354. switch (branch.kind) {
  355. case InstKind::BranchIf:
  356. name = "while.body";
  357. break;
  358. case InstKind::Branch:
  359. name = "while.done";
  360. break;
  361. default:
  362. break;
  363. }
  364. break;
  365. default:
  366. break;
  367. }
  368. AddBlockLabel(scope_idx, branch.target_id, name.str(), parse_node);
  369. }
  370. auto CollectNamesInBlock(ScopeIndex scope_idx, InstBlockId block_id) -> void {
  371. if (block_id.is_valid()) {
  372. CollectNamesInBlock(scope_idx, sem_ir_.inst_blocks().Get(block_id));
  373. }
  374. }
  375. auto CollectNamesInBlock(ScopeIndex scope_idx, llvm::ArrayRef<InstId> block)
  376. -> void {
  377. Scope& scope = GetScopeInfo(scope_idx);
  378. // Use bound names where available. Otherwise, assign a backup name.
  379. for (auto inst_id : block) {
  380. if (!inst_id.is_valid()) {
  381. continue;
  382. }
  383. auto inst = sem_ir_.insts().Get(inst_id);
  384. auto add_inst_name = [&](std::string name) {
  385. insts[inst_id.index] = {
  386. scope_idx, scope.insts.AllocateName(
  387. *this, sem_ir_.insts().GetParseNode(inst_id), name)};
  388. };
  389. auto add_inst_name_id = [&](NameId name_id, llvm::StringRef suffix = "") {
  390. add_inst_name(
  391. (sem_ir_.names().GetIRBaseName(name_id).str() + suffix).str());
  392. };
  393. if (auto branch = inst.TryAs<AnyBranch>()) {
  394. AddBlockLabel(scope_idx, sem_ir_.insts().GetParseNode(inst_id),
  395. *branch);
  396. }
  397. switch (inst.kind()) {
  398. case AddrPattern::Kind: {
  399. // TODO: We need to assign names to parameters that appear in
  400. // function declarations, which may be nested within a pattern. For
  401. // now, just look through `addr`, but we should find a better way to
  402. // visit parameters.
  403. CollectNamesInBlock(scope_idx, inst.As<AddrPattern>().inner_id);
  404. break;
  405. }
  406. case SpliceBlock::Kind: {
  407. CollectNamesInBlock(scope_idx, inst.As<SpliceBlock>().block_id);
  408. break;
  409. }
  410. case BindName::Kind:
  411. case BindSymbolicName::Kind: {
  412. add_inst_name_id(sem_ir_.bind_names()
  413. .Get(inst.As<AnyBindName>().bind_name_id)
  414. .name_id);
  415. continue;
  416. }
  417. case FunctionDecl::Kind: {
  418. add_inst_name_id(sem_ir_.functions()
  419. .Get(inst.As<FunctionDecl>().function_id)
  420. .name_id);
  421. continue;
  422. }
  423. case ClassDecl::Kind: {
  424. add_inst_name_id(
  425. sem_ir_.classes().Get(inst.As<ClassDecl>().class_id).name_id,
  426. ".decl");
  427. continue;
  428. }
  429. case ClassType::Kind: {
  430. add_inst_name_id(
  431. sem_ir_.classes().Get(inst.As<ClassType>().class_id).name_id);
  432. continue;
  433. }
  434. case Import::Kind: {
  435. add_inst_name("import");
  436. continue;
  437. }
  438. case ImportRefUnused::Kind:
  439. case ImportRefUsed::Kind: {
  440. add_inst_name("import_ref");
  441. continue;
  442. }
  443. case InterfaceDecl::Kind: {
  444. add_inst_name_id(sem_ir_.interfaces()
  445. .Get(inst.As<InterfaceDecl>().interface_id)
  446. .name_id,
  447. ".decl");
  448. continue;
  449. }
  450. case NameRef::Kind: {
  451. add_inst_name_id(inst.As<NameRef>().name_id, ".ref");
  452. continue;
  453. }
  454. case Param::Kind: {
  455. add_inst_name_id(inst.As<Param>().name_id);
  456. continue;
  457. }
  458. case VarStorage::Kind: {
  459. add_inst_name_id(inst.As<VarStorage>().name_id, ".var");
  460. continue;
  461. }
  462. default: {
  463. break;
  464. }
  465. }
  466. // Sequentially number all remaining values.
  467. if (inst.kind().value_kind() != InstValueKind::None) {
  468. add_inst_name("");
  469. }
  470. }
  471. }
  472. const Lex::TokenizedBuffer& tokenized_buffer_;
  473. const Parse::Tree& parse_tree_;
  474. const File& sem_ir_;
  475. Namespace globals = {.prefix = "@"};
  476. std::vector<std::pair<ScopeIndex, Namespace::Name>> insts;
  477. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  478. std::vector<Scope> scopes;
  479. };
  480. } // namespace
  481. // Formatter for printing textual Semantics IR.
  482. class Formatter {
  483. public:
  484. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  485. const Parse::Tree& parse_tree, const File& sem_ir,
  486. llvm::raw_ostream& out)
  487. : sem_ir_(sem_ir),
  488. out_(out),
  489. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  490. // Prints the SemIR.
  491. //
  492. // Constants are printed first and may be referenced by later sections,
  493. // including file-scoped instructions. The file scope may contain entity
  494. // declarations which are defined later, such as classes.
  495. auto Format() -> void {
  496. out_ << "--- " << sem_ir_.filename() << "\n\n";
  497. FormatConstants();
  498. out_ << "file {\n";
  499. // TODO: Handle the case where there are multiple top-level instruction
  500. // blocks. For example, there may be branching in the initializer of a
  501. // global or a type expression.
  502. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  503. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeIndex::File);
  504. FormatCodeBlock(block_id);
  505. }
  506. out_ << "}\n";
  507. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  508. FormatInterface(InterfaceId(i));
  509. }
  510. for (int i : llvm::seq(sem_ir_.classes().size())) {
  511. FormatClass(ClassId(i));
  512. }
  513. for (int i : llvm::seq(sem_ir_.functions().size())) {
  514. FormatFunction(FunctionId(i));
  515. }
  516. // End-of-file newline.
  517. out_ << "\n";
  518. }
  519. auto FormatConstants() -> void {
  520. if (!sem_ir_.constants().size()) {
  521. return;
  522. }
  523. llvm::SaveAndRestore constants_scope(scope_,
  524. InstNamer::ScopeIndex::Constants);
  525. out_ << "constants {\n";
  526. FormatCodeBlock(sem_ir_.constants().GetAsVector());
  527. out_ << "}\n\n";
  528. }
  529. auto FormatClass(ClassId id) -> void {
  530. const Class& class_info = sem_ir_.classes().Get(id);
  531. out_ << "\nclass ";
  532. FormatClassName(id);
  533. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  534. if (class_info.scope_id.is_valid()) {
  535. out_ << " {\n";
  536. FormatCodeBlock(class_info.body_block_id);
  537. out_ << "\n!members:";
  538. FormatNameScope(class_info.scope_id, "", "\n ");
  539. out_ << "\n}\n";
  540. } else {
  541. out_ << ";\n";
  542. }
  543. }
  544. auto FormatInterface(InterfaceId id) -> void {
  545. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  546. out_ << "\ninterface ";
  547. FormatInterfaceName(id);
  548. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  549. if (interface_info.scope_id.is_valid()) {
  550. out_ << " {\n";
  551. FormatCodeBlock(interface_info.body_block_id);
  552. out_ << "\n!members:";
  553. FormatNameScope(interface_info.scope_id, "", "\n ");
  554. out_ << "\n}\n";
  555. } else {
  556. out_ << ";\n";
  557. }
  558. }
  559. auto FormatFunction(FunctionId id) -> void {
  560. const Function& fn = sem_ir_.functions().Get(id);
  561. out_ << "\nfn ";
  562. FormatFunctionName(id);
  563. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  564. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  565. out_ << "[";
  566. FormatParamList(fn.implicit_param_refs_id);
  567. out_ << "]";
  568. }
  569. out_ << "(";
  570. FormatParamList(fn.param_refs_id);
  571. out_ << ")";
  572. if (fn.return_type_id.is_valid()) {
  573. out_ << " -> ";
  574. if (fn.return_slot_id.is_valid()) {
  575. FormatInstName(fn.return_slot_id);
  576. out_ << ": ";
  577. }
  578. FormatType(fn.return_type_id);
  579. }
  580. if (!fn.body_block_ids.empty()) {
  581. out_ << " {";
  582. for (auto block_id : fn.body_block_ids) {
  583. out_ << "\n";
  584. FormatLabel(block_id);
  585. out_ << ":\n";
  586. FormatCodeBlock(block_id);
  587. }
  588. out_ << "}\n";
  589. } else {
  590. out_ << ";\n";
  591. }
  592. }
  593. auto FormatParamList(InstBlockId param_refs_id) -> void {
  594. llvm::ListSeparator sep;
  595. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  596. out_ << sep;
  597. if (!param_id.is_valid()) {
  598. out_ << "invalid";
  599. continue;
  600. }
  601. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  602. out_ << "addr ";
  603. param_id = addr->inner_id;
  604. }
  605. FormatInstName(param_id);
  606. out_ << ": ";
  607. FormatType(sem_ir_.insts().Get(param_id).type_id());
  608. }
  609. }
  610. auto FormatCodeBlock(InstBlockId block_id) -> void {
  611. if (block_id.is_valid()) {
  612. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  613. }
  614. }
  615. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  616. for (const InstId inst_id : block) {
  617. FormatInstruction(inst_id);
  618. }
  619. }
  620. auto FormatNameScope(NameScopeId id, llvm::StringRef separator,
  621. llvm::StringRef prefix) -> void {
  622. const auto& scope = sem_ir_.name_scopes().Get(id);
  623. // Name scopes aren't kept in any particular order. Sort the entries before
  624. // we print them for stability and consistency.
  625. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  626. for (auto [name_id, inst_id] : scope.names) {
  627. entries.push_back({inst_id, name_id});
  628. }
  629. llvm::sort(entries,
  630. [](auto a, auto b) { return a.first.index < b.first.index; });
  631. llvm::ListSeparator sep(separator);
  632. for (auto [inst_id, name_id] : entries) {
  633. out_ << sep << prefix << ".";
  634. FormatName(name_id);
  635. out_ << " = ";
  636. FormatInstName(inst_id);
  637. }
  638. for (auto extended_scope_id : scope.extended_scopes) {
  639. // TODO: Print this scope in a better way.
  640. out_ << sep << prefix << "extend " << extended_scope_id;
  641. }
  642. if (scope.has_error) {
  643. out_ << sep << prefix << "has_error";
  644. }
  645. }
  646. auto FormatInstruction(InstId inst_id) -> void {
  647. if (!inst_id.is_valid()) {
  648. Indent();
  649. out_ << "invalid\n";
  650. return;
  651. }
  652. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  653. }
  654. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  655. switch (inst.kind()) {
  656. #define CARBON_SEM_IR_INST_KIND(InstT) \
  657. case InstT::Kind: \
  658. FormatInstruction(inst_id, inst.As<InstT>()); \
  659. break;
  660. #include "toolchain/sem_ir/inst_kind.def"
  661. }
  662. }
  663. auto Indent() -> void { out_.indent(indent_); }
  664. template <typename InstT>
  665. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  666. Indent();
  667. FormatInstructionLHS(inst_id, inst);
  668. out_ << InstT::Kind.ir_name();
  669. FormatInstructionRHS(inst);
  670. if (auto const_id = sem_ir_.constant_values().Get(inst_id);
  671. const_id.is_constant()) {
  672. out_ << (const_id.is_symbolic() ? " [symbolic" : " [template");
  673. if (const_id.inst_id() != inst_id) {
  674. out_ << " = ";
  675. FormatInstName(const_id.inst_id());
  676. }
  677. out_ << "]";
  678. }
  679. out_ << "\n";
  680. }
  681. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  682. switch (inst.kind().value_kind()) {
  683. case InstValueKind::Typed:
  684. FormatInstName(inst_id);
  685. out_ << ": ";
  686. switch (GetExprCategory(sem_ir_, inst_id)) {
  687. case ExprCategory::NotExpr:
  688. case ExprCategory::Error:
  689. case ExprCategory::Value:
  690. case ExprCategory::Mixed:
  691. break;
  692. case ExprCategory::DurableRef:
  693. case ExprCategory::EphemeralRef:
  694. out_ << "ref ";
  695. break;
  696. case ExprCategory::Initializing:
  697. out_ << "init ";
  698. break;
  699. }
  700. FormatType(inst.type_id());
  701. out_ << " = ";
  702. break;
  703. case InstValueKind::None:
  704. break;
  705. }
  706. }
  707. // Print ClassDecl with type-like semantics even though it lacks a type_id.
  708. auto FormatInstructionLHS(InstId inst_id, ClassDecl /*inst*/) -> void {
  709. FormatInstName(inst_id);
  710. out_ << " = ";
  711. }
  712. // Print InterfaceDecl with type-like semantics even though it lacks a
  713. // type_id.
  714. auto FormatInstructionLHS(InstId inst_id, InterfaceDecl /*inst*/) -> void {
  715. FormatInstName(inst_id);
  716. out_ << " = ";
  717. }
  718. // Print ImportRefUnused with type-like semantics even though it lacks a
  719. // type_id.
  720. auto FormatInstructionLHS(InstId inst_id, ImportRefUnused /*inst*/) -> void {
  721. FormatInstName(inst_id);
  722. out_ << " = ";
  723. }
  724. template <typename InstT>
  725. auto FormatInstructionRHS(InstT inst) -> void {
  726. // By default, an instruction has a comma-separated argument list.
  727. using Info = Internal::InstLikeTypeInfo<InstT>;
  728. if constexpr (Info::NumArgs == 2) {
  729. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  730. } else if constexpr (Info::NumArgs == 1) {
  731. FormatArgs(Info::template Get<0>(inst));
  732. } else {
  733. FormatArgs();
  734. }
  735. }
  736. auto FormatInstructionRHS(BlockArg inst) -> void {
  737. out_ << " ";
  738. FormatLabel(inst.block_id);
  739. }
  740. auto FormatInstructionRHS(Namespace inst) -> void {
  741. if (inst.import_id.is_valid()) {
  742. FormatArgs(inst.name_scope_id, inst.import_id);
  743. } else {
  744. FormatArgs(inst.name_scope_id);
  745. }
  746. }
  747. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  748. if (!in_terminator_sequence_) {
  749. Indent();
  750. }
  751. out_ << "if ";
  752. FormatInstName(inst.cond_id);
  753. out_ << " " << Branch::Kind.ir_name() << " ";
  754. FormatLabel(inst.target_id);
  755. out_ << " else ";
  756. in_terminator_sequence_ = true;
  757. }
  758. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  759. if (!in_terminator_sequence_) {
  760. Indent();
  761. }
  762. out_ << BranchWithArg::Kind.ir_name() << " ";
  763. FormatLabel(inst.target_id);
  764. out_ << "(";
  765. FormatInstName(inst.arg_id);
  766. out_ << ")\n";
  767. in_terminator_sequence_ = false;
  768. }
  769. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  770. if (!in_terminator_sequence_) {
  771. Indent();
  772. }
  773. out_ << Branch::Kind.ir_name() << " ";
  774. FormatLabel(inst.target_id);
  775. out_ << "\n";
  776. in_terminator_sequence_ = false;
  777. }
  778. auto FormatInstructionRHS(Call inst) -> void {
  779. out_ << " ";
  780. FormatArg(inst.callee_id);
  781. if (!inst.args_id.is_valid()) {
  782. out_ << "(<invalid>)";
  783. return;
  784. }
  785. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  786. bool has_return_slot = GetInitRepr(sem_ir_, inst.type_id).has_return_slot();
  787. InstId return_slot_id = InstId::Invalid;
  788. if (has_return_slot) {
  789. return_slot_id = args.back();
  790. args = args.drop_back();
  791. }
  792. llvm::ListSeparator sep;
  793. out_ << '(';
  794. for (auto inst_id : args) {
  795. out_ << sep;
  796. FormatArg(inst_id);
  797. }
  798. out_ << ')';
  799. if (has_return_slot) {
  800. FormatReturnSlot(return_slot_id);
  801. }
  802. }
  803. auto FormatInstructionRHS(ArrayInit inst) -> void {
  804. FormatArgs(inst.inits_id);
  805. FormatReturnSlot(inst.dest_id);
  806. }
  807. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  808. FormatArgs(inst.src_id);
  809. FormatReturnSlot(inst.dest_id);
  810. }
  811. auto FormatInstructionRHS(StructInit init) -> void {
  812. FormatArgs(init.elements_id);
  813. FormatReturnSlot(init.dest_id);
  814. }
  815. auto FormatInstructionRHS(TupleInit init) -> void {
  816. FormatArgs(init.elements_id);
  817. FormatReturnSlot(init.dest_id);
  818. }
  819. auto FormatInstructionRHS(ImportRefUnused inst) -> void {
  820. // Don't format the inst_id because it refers to a different IR.
  821. // TODO: Consider a better way to format the InstID from other IRs.
  822. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", unused";
  823. }
  824. auto FormatInstructionRHS(ImportRefUsed inst) -> void {
  825. // Don't format the inst_id because it refers to a different IR.
  826. // TODO: Consider a better way to format the InstID from other IRs.
  827. out_ << " " << inst.ir_id << ", " << inst.inst_id << ", used";
  828. }
  829. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  830. FormatArgs(inst.result_id);
  831. out_ << " {";
  832. if (!sem_ir_.inst_blocks().Get(inst.block_id).empty()) {
  833. out_ << "\n";
  834. indent_ += 2;
  835. FormatCodeBlock(inst.block_id);
  836. indent_ -= 2;
  837. Indent();
  838. }
  839. out_ << "}";
  840. }
  841. // StructTypeFields are formatted as part of their StructType.
  842. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  843. }
  844. auto FormatInstructionRHS(StructType inst) -> void {
  845. out_ << " {";
  846. llvm::ListSeparator sep;
  847. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  848. out_ << sep << ".";
  849. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  850. FormatName(field.name_id);
  851. out_ << ": ";
  852. FormatType(field.field_type_id);
  853. }
  854. out_ << "}";
  855. }
  856. auto FormatArgs() -> void {}
  857. template <typename... Args>
  858. auto FormatArgs(Args... args) -> void {
  859. out_ << ' ';
  860. llvm::ListSeparator sep;
  861. ((out_ << sep, FormatArg(args)), ...);
  862. }
  863. auto FormatArg(BoolValue v) -> void { out_ << v; }
  864. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  865. auto FormatArg(BindNameId id) -> void {
  866. FormatName(sem_ir_.bind_names().Get(id).name_id);
  867. }
  868. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  869. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  870. auto FormatArg(InterfaceId id) -> void { FormatInterfaceName(id); }
  871. auto FormatArg(ImportIRId id) -> void { out_ << id; }
  872. auto FormatArg(IntId id) -> void {
  873. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  874. }
  875. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  876. auto FormatArg(NameScopeId id) -> void {
  877. out_ << '{';
  878. FormatNameScope(id, ", ", "");
  879. out_ << '}';
  880. }
  881. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  882. auto FormatArg(InstBlockId id) -> void {
  883. out_ << '(';
  884. llvm::ListSeparator sep;
  885. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  886. out_ << sep;
  887. FormatArg(inst_id);
  888. }
  889. out_ << ')';
  890. }
  891. auto FormatArg(RealId id) -> void {
  892. // TODO: Format with a `.` when the exponent is near zero.
  893. const auto& real = sem_ir_.reals().Get(id);
  894. real.mantissa.print(out_, /*isSigned=*/false);
  895. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  896. }
  897. auto FormatArg(StringLiteralValueId id) -> void {
  898. out_ << '"';
  899. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  900. /*UseHexEscapes=*/true);
  901. out_ << '"';
  902. }
  903. auto FormatArg(NameId id) -> void { FormatName(id); }
  904. auto FormatArg(TypeId id) -> void { FormatType(id); }
  905. auto FormatArg(TypeBlockId id) -> void {
  906. out_ << '(';
  907. llvm::ListSeparator sep;
  908. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  909. out_ << sep;
  910. FormatArg(type_id);
  911. }
  912. out_ << ')';
  913. }
  914. auto FormatReturnSlot(InstId dest_id) -> void {
  915. out_ << " to ";
  916. FormatArg(dest_id);
  917. }
  918. auto FormatName(NameId id) -> void {
  919. out_ << sem_ir_.names().GetFormatted(id);
  920. }
  921. auto FormatInstName(InstId id) -> void {
  922. out_ << inst_namer_.GetNameFor(scope_, id);
  923. }
  924. auto FormatLabel(InstBlockId id) -> void {
  925. out_ << inst_namer_.GetLabelFor(scope_, id);
  926. }
  927. auto FormatFunctionName(FunctionId id) -> void {
  928. out_ << inst_namer_.GetNameFor(id);
  929. }
  930. auto FormatClassName(ClassId id) -> void {
  931. out_ << inst_namer_.GetNameFor(id);
  932. }
  933. auto FormatInterfaceName(InterfaceId id) -> void {
  934. out_ << inst_namer_.GetNameFor(id);
  935. }
  936. auto FormatType(TypeId id) -> void {
  937. if (!id.is_valid()) {
  938. out_ << "invalid";
  939. } else {
  940. out_ << sem_ir_.StringifyType(id);
  941. }
  942. }
  943. private:
  944. const File& sem_ir_;
  945. llvm::raw_ostream& out_;
  946. InstNamer inst_namer_;
  947. InstNamer::ScopeIndex scope_ = InstNamer::ScopeIndex::None;
  948. bool in_terminator_sequence_ = false;
  949. int indent_ = 2;
  950. };
  951. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  952. const Parse::Tree& parse_tree, const File& sem_ir,
  953. llvm::raw_ostream& out) -> void {
  954. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  955. }
  956. } // namespace Carbon::SemIR