formatter.cpp 33 KB

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