formatter.cpp 32 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/Support/SaveAndRestore.h"
  9. #include "toolchain/base/kind_switch.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/builtin_function_kind.h"
  14. #include "toolchain/sem_ir/function.h"
  15. #include "toolchain/sem_ir/ids.h"
  16. #include "toolchain/sem_ir/inst_namer.h"
  17. #include "toolchain/sem_ir/name_scope.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::SemIR {
  20. // Formatter for printing textual Semantics IR.
  21. class FormatterImpl {
  22. public:
  23. explicit FormatterImpl(const File& sem_ir, InstNamer* inst_namer,
  24. llvm::raw_ostream& out, int indent)
  25. : sem_ir_(sem_ir), inst_namer_(inst_namer), out_(out), indent_(indent) {}
  26. // Prints the SemIR.
  27. //
  28. // Constants are printed first and may be referenced by later sections,
  29. // including file-scoped instructions. The file scope may contain entity
  30. // declarations which are defined later, such as classes.
  31. auto Format() -> void {
  32. out_ << "--- " << sem_ir_.filename() << "\n\n";
  33. FormatScope(InstNamer::ScopeId::Constants, sem_ir_.constants().array_ref());
  34. FormatScope(InstNamer::ScopeId::ImportRefs,
  35. sem_ir_.inst_blocks().Get(InstBlockId::ImportRefs));
  36. out_ << inst_namer_->GetScopeName(InstNamer::ScopeId::File) << " ";
  37. OpenBrace();
  38. // TODO: Handle the case where there are multiple top-level instruction
  39. // blocks. For example, there may be branching in the initializer of a
  40. // global or a type expression.
  41. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  42. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::File);
  43. FormatCodeBlock(block_id);
  44. }
  45. CloseBrace();
  46. out_ << '\n';
  47. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  48. FormatInterface(InterfaceId(i));
  49. }
  50. for (int i : llvm::seq(sem_ir_.impls().size())) {
  51. FormatImpl(ImplId(i));
  52. }
  53. for (int i : llvm::seq(sem_ir_.classes().size())) {
  54. FormatClass(ClassId(i));
  55. }
  56. for (int i : llvm::seq(sem_ir_.functions().size())) {
  57. FormatFunction(FunctionId(i));
  58. }
  59. for (int i : llvm::seq(sem_ir_.specifics().size())) {
  60. FormatSpecific(SpecificId(i));
  61. }
  62. // End-of-file newline.
  63. out_ << "\n";
  64. }
  65. // Prints a code block.
  66. auto FormatPartialTrailingCodeBlock(llvm::ArrayRef<SemIR::InstId> block)
  67. -> void {
  68. out_ << ' ';
  69. OpenBrace();
  70. constexpr int NumPrintedOnSkip = 9;
  71. // Avoid only skipping one item.
  72. if (block.size() > NumPrintedOnSkip + 1) {
  73. Indent();
  74. out_ << "... skipping " << (block.size() - NumPrintedOnSkip)
  75. << " insts ...\n";
  76. block = block.take_back(NumPrintedOnSkip);
  77. }
  78. FormatCodeBlock(block);
  79. CloseBrace();
  80. }
  81. // Prints a single instruction.
  82. auto FormatInst(InstId inst_id) -> void {
  83. if (!inst_id.is_valid()) {
  84. Indent();
  85. out_ << "invalid\n";
  86. return;
  87. }
  88. FormatInst(inst_id, sem_ir_.insts().Get(inst_id));
  89. }
  90. private:
  91. enum class AddSpace : bool { Before, After };
  92. // Begins a braced block. Writes an open brace, and prepares to insert a
  93. // newline after it if the braced block is non-empty.
  94. auto OpenBrace() -> void {
  95. // Put the constant value of an instruction before any braced block, rather
  96. // than at the end.
  97. FormatPendingConstantValue(AddSpace::After);
  98. out_ << '{';
  99. indent_ += 2;
  100. after_open_brace_ = true;
  101. }
  102. // Ends a braced block by writing a close brace.
  103. auto CloseBrace() -> void {
  104. indent_ -= 2;
  105. if (!after_open_brace_) {
  106. Indent();
  107. }
  108. out_ << '}';
  109. after_open_brace_ = false;
  110. }
  111. // Adds beginning-of-line indentation. If we're at the start of a braced
  112. // block, first starts a new line.
  113. auto Indent(int offset = 0) -> void {
  114. if (after_open_brace_) {
  115. out_ << '\n';
  116. after_open_brace_ = false;
  117. }
  118. out_.indent(indent_ + offset);
  119. }
  120. // Adds beginning-of-label indentation. This is one level less than normal
  121. // indentation. Labels also get a preceding blank line unless they're at the
  122. // start of a block.
  123. auto IndentLabel() -> void {
  124. CARBON_CHECK(indent_ >= 2);
  125. if (!after_open_brace_) {
  126. out_ << '\n';
  127. }
  128. Indent(-2);
  129. }
  130. // Formats a top-level scope, particularly Constants and ImportRefs.
  131. auto FormatScope(InstNamer::ScopeId scope_id, llvm::ArrayRef<InstId> block)
  132. -> void {
  133. if (block.empty()) {
  134. return;
  135. }
  136. llvm::SaveAndRestore scope(scope_, scope_id);
  137. out_ << inst_namer_->GetScopeName(scope_id) << " ";
  138. OpenBrace();
  139. FormatCodeBlock(block);
  140. CloseBrace();
  141. out_ << "\n\n";
  142. }
  143. // Formats a full class.
  144. auto FormatClass(ClassId id) -> void {
  145. const Class& class_info = sem_ir_.classes().Get(id);
  146. FormatEntityStart("class", class_info.generic_id, id);
  147. llvm::SaveAndRestore class_scope(scope_, inst_namer_->GetScopeFor(id));
  148. if (class_info.scope_id.is_valid()) {
  149. out_ << ' ';
  150. OpenBrace();
  151. FormatCodeBlock(class_info.body_block_id);
  152. FormatNameScope(class_info.scope_id, "!members:\n");
  153. CloseBrace();
  154. out_ << '\n';
  155. } else {
  156. out_ << ";\n";
  157. }
  158. FormatEntityEnd(class_info.generic_id);
  159. }
  160. // Formats a full interface.
  161. auto FormatInterface(InterfaceId id) -> void {
  162. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  163. FormatEntityStart("interface", interface_info.generic_id, id);
  164. llvm::SaveAndRestore interface_scope(scope_, inst_namer_->GetScopeFor(id));
  165. if (interface_info.scope_id.is_valid()) {
  166. out_ << ' ';
  167. OpenBrace();
  168. FormatCodeBlock(interface_info.body_block_id);
  169. // Always include the !members label because we always list the witness in
  170. // this section.
  171. IndentLabel();
  172. out_ << "!members:\n";
  173. FormatNameScope(interface_info.scope_id);
  174. Indent();
  175. out_ << "witness = ";
  176. FormatArg(interface_info.associated_entities_id);
  177. out_ << "\n";
  178. CloseBrace();
  179. out_ << '\n';
  180. } else {
  181. out_ << ";\n";
  182. }
  183. FormatEntityEnd(interface_info.generic_id);
  184. }
  185. // Formats a full impl.
  186. auto FormatImpl(ImplId id) -> void {
  187. const Impl& impl_info = sem_ir_.impls().Get(id);
  188. FormatEntityStart("impl", SemIR::GenericId::Invalid, id);
  189. out_ << ": ";
  190. // TODO: Include the deduced parameter list if present.
  191. FormatType(impl_info.self_id);
  192. out_ << " as ";
  193. FormatType(impl_info.constraint_id);
  194. llvm::SaveAndRestore impl_scope(scope_, inst_namer_->GetScopeFor(id));
  195. if (impl_info.is_defined()) {
  196. out_ << ' ';
  197. OpenBrace();
  198. FormatCodeBlock(impl_info.body_block_id);
  199. // Print the !members label even if the name scope is empty because we
  200. // always list the witness in this section.
  201. IndentLabel();
  202. out_ << "!members:\n";
  203. if (impl_info.scope_id.is_valid()) {
  204. FormatNameScope(impl_info.scope_id);
  205. }
  206. Indent();
  207. out_ << "witness = ";
  208. FormatArg(impl_info.witness_id);
  209. out_ << "\n";
  210. CloseBrace();
  211. out_ << '\n';
  212. } else {
  213. out_ << ";\n";
  214. }
  215. }
  216. // Formats a full function.
  217. auto FormatFunction(FunctionId id) -> void {
  218. const Function& fn = sem_ir_.functions().Get(id);
  219. FormatEntityStart(fn.is_extern ? "extern fn" : "fn", fn.generic_id, id);
  220. llvm::SaveAndRestore function_scope(scope_, inst_namer_->GetScopeFor(id));
  221. FormatParamList(fn.implicit_param_refs_id, /*is_implicit=*/true);
  222. FormatParamList(fn.param_refs_id, /*is_implicit=*/false);
  223. if (fn.return_storage_id.is_valid()) {
  224. out_ << " -> ";
  225. auto return_info = ReturnTypeInfo::ForFunction(sem_ir_, fn);
  226. if (!fn.body_block_ids.empty() && return_info.is_valid() &&
  227. return_info.has_return_slot()) {
  228. FormatName(fn.return_storage_id);
  229. out_ << ": ";
  230. }
  231. FormatType(sem_ir_.insts().Get(fn.return_storage_id).type_id());
  232. }
  233. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  234. out_ << " = \"";
  235. out_.write_escaped(fn.builtin_function_kind.name(),
  236. /*UseHexEscapes=*/true);
  237. out_ << "\"";
  238. }
  239. if (!fn.body_block_ids.empty()) {
  240. out_ << ' ';
  241. OpenBrace();
  242. for (auto block_id : fn.body_block_ids) {
  243. IndentLabel();
  244. FormatLabel(block_id);
  245. out_ << ":\n";
  246. FormatCodeBlock(block_id);
  247. }
  248. CloseBrace();
  249. out_ << '\n';
  250. } else {
  251. out_ << ";\n";
  252. }
  253. FormatEntityEnd(fn.generic_id);
  254. }
  255. // Helper for FormatSpecific to print regions.
  256. auto FormatSpecificRegion(const Generic& generic, const Specific& specific,
  257. GenericInstIndex::Region region,
  258. llvm::StringRef region_name) -> void {
  259. if (!specific.GetValueBlock(region).is_valid()) {
  260. return;
  261. }
  262. if (!region_name.empty()) {
  263. IndentLabel();
  264. out_ << "!" << region_name << ":\n";
  265. }
  266. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  267. sem_ir_.inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  268. sem_ir_.inst_blocks().GetOrEmpty(
  269. specific.GetValueBlock(region)))) {
  270. if (generic_inst_id && specific_inst_id &&
  271. sem_ir_.insts().Is<StructTypeField>(*generic_inst_id) &&
  272. sem_ir_.insts().Is<StructTypeField>(*specific_inst_id)) {
  273. // Skip printing struct type fields to match the way we print the
  274. // generic.
  275. continue;
  276. }
  277. Indent();
  278. if (generic_inst_id) {
  279. FormatName(*generic_inst_id);
  280. } else {
  281. out_ << "<missing>";
  282. }
  283. out_ << " => ";
  284. if (specific_inst_id) {
  285. FormatName(*specific_inst_id);
  286. } else {
  287. out_ << "<missing>";
  288. }
  289. out_ << "\n";
  290. }
  291. }
  292. // Formats a full specific.
  293. auto FormatSpecific(SpecificId id) -> void {
  294. const auto& specific = sem_ir_.specifics().Get(id);
  295. out_ << "\n";
  296. out_ << "specific ";
  297. FormatName(id);
  298. // TODO: Remove once we stop forming generic specifics with no generic
  299. // during import.
  300. if (!specific.generic_id.is_valid()) {
  301. out_ << ";\n";
  302. return;
  303. }
  304. out_ << " ";
  305. const auto& generic = sem_ir_.generics().Get(specific.generic_id);
  306. llvm::SaveAndRestore generic_scope(
  307. scope_, inst_namer_->GetScopeFor(specific.generic_id));
  308. OpenBrace();
  309. FormatSpecificRegion(generic, specific,
  310. GenericInstIndex::Region::Declaration, "");
  311. FormatSpecificRegion(generic, specific,
  312. GenericInstIndex::Region::Definition, "definition");
  313. CloseBrace();
  314. out_ << "\n";
  315. }
  316. // Handles generic-specific setup for FormatEntityStart.
  317. auto FormatGenericStart(llvm::StringRef entity_kind, GenericId generic_id)
  318. -> void {
  319. const auto& generic = sem_ir_.generics().Get(generic_id);
  320. out_ << "\n";
  321. Indent();
  322. out_ << "generic " << entity_kind << " ";
  323. FormatName(generic_id);
  324. llvm::SaveAndRestore generic_scope(scope_,
  325. inst_namer_->GetScopeFor(generic_id));
  326. FormatParamList(generic.bindings_id, /*is_implicit=*/false);
  327. out_ << " ";
  328. OpenBrace();
  329. FormatCodeBlock(generic.decl_block_id);
  330. if (generic.definition_block_id.is_valid()) {
  331. IndentLabel();
  332. out_ << "!definition:\n";
  333. FormatCodeBlock(generic.definition_block_id);
  334. }
  335. }
  336. // Provides common formatting for entities, paired with FormatEntityEnd.
  337. template <typename IdT>
  338. auto FormatEntityStart(llvm::StringRef entity_kind, GenericId generic_id,
  339. IdT entity_id) -> void {
  340. if (generic_id.is_valid()) {
  341. FormatGenericStart(entity_kind, generic_id);
  342. }
  343. out_ << "\n";
  344. Indent();
  345. out_ << entity_kind;
  346. // If there's a generic, it will have attached the name. Otherwise, add the
  347. // name here.
  348. if (!generic_id.is_valid()) {
  349. out_ << " ";
  350. FormatName(entity_id);
  351. }
  352. }
  353. // Provides common formatting for entities, paired with FormatEntityStart.
  354. auto FormatEntityEnd(GenericId generic_id) -> void {
  355. if (generic_id.is_valid()) {
  356. CloseBrace();
  357. out_ << '\n';
  358. }
  359. }
  360. // Formats parameters, eliding them completely if they're empty. Wraps in
  361. // parentheses or square brackets based on whether these are implicit
  362. // parameters.
  363. auto FormatParamList(InstBlockId param_refs_id, bool is_implicit) -> void {
  364. if (!param_refs_id.is_valid()) {
  365. return;
  366. }
  367. out_ << (is_implicit ? "[" : "(");
  368. llvm::ListSeparator sep;
  369. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  370. out_ << sep;
  371. if (!param_id.is_valid()) {
  372. out_ << "invalid";
  373. continue;
  374. }
  375. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  376. out_ << "addr ";
  377. param_id = addr->inner_id;
  378. }
  379. FormatName(param_id);
  380. out_ << ": ";
  381. FormatType(sem_ir_.insts().Get(param_id).type_id());
  382. }
  383. out_ << (is_implicit ? "]" : ")");
  384. }
  385. // Prints instructions for a code block.
  386. auto FormatCodeBlock(InstBlockId block_id) -> void {
  387. if (block_id.is_valid()) {
  388. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  389. }
  390. }
  391. // Prints instructions for a code block.
  392. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  393. for (const InstId inst_id : block) {
  394. FormatInst(inst_id);
  395. }
  396. }
  397. // Prints a code block with braces, intended to be used trailing after other
  398. // content on the same line. If non-empty, instructions are on separate lines.
  399. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  400. out_ << ' ';
  401. OpenBrace();
  402. FormatCodeBlock(block_id);
  403. CloseBrace();
  404. }
  405. // Prints the contents of a name scope, with an optional label.
  406. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  407. const auto& scope = sem_ir_.name_scopes().Get(id);
  408. if (scope.names.empty() && scope.extended_scopes.empty() &&
  409. scope.import_ir_scopes.empty() && !scope.has_error) {
  410. // Name scope is empty.
  411. return;
  412. }
  413. if (!label.empty()) {
  414. IndentLabel();
  415. out_ << label;
  416. }
  417. for (auto [name_id, inst_id, access_kind] : scope.names) {
  418. Indent();
  419. out_ << ".";
  420. FormatName(name_id);
  421. switch (access_kind) {
  422. case SemIR::AccessKind::Public:
  423. break;
  424. case SemIR::AccessKind::Protected:
  425. out_ << " [protected]";
  426. break;
  427. case SemIR::AccessKind::Private:
  428. out_ << " [private]";
  429. break;
  430. }
  431. out_ << " = ";
  432. FormatName(inst_id);
  433. out_ << "\n";
  434. }
  435. for (auto extended_scope_id : scope.extended_scopes) {
  436. // TODO: Print this scope in a better way.
  437. Indent();
  438. out_ << "extend " << extended_scope_id << "\n";
  439. }
  440. for (auto [import_ir_id, unused] : scope.import_ir_scopes) {
  441. Indent();
  442. out_ << "import ";
  443. FormatArg(import_ir_id);
  444. out_ << "\n";
  445. }
  446. if (scope.has_error) {
  447. Indent();
  448. out_ << "has_error\n";
  449. }
  450. }
  451. auto FormatInst(InstId inst_id, Inst inst) -> void {
  452. CARBON_KIND_SWITCH(inst) {
  453. #define CARBON_SEM_IR_INST_KIND(InstT) \
  454. case CARBON_KIND(InstT typed_inst): { \
  455. FormatInst(inst_id, typed_inst); \
  456. break; \
  457. }
  458. #include "toolchain/sem_ir/inst_kind.def"
  459. }
  460. }
  461. template <typename InstT>
  462. auto FormatInst(InstId inst_id, InstT inst) -> void {
  463. Indent();
  464. FormatInstLHS(inst_id, inst);
  465. out_ << InstT::Kind.ir_name();
  466. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  467. pending_constant_value_is_self_ =
  468. sem_ir_.constant_values().GetInstIdIfValid(pending_constant_value_) ==
  469. inst_id;
  470. FormatInstRHS(inst);
  471. FormatPendingConstantValue(AddSpace::Before);
  472. out_ << "\n";
  473. }
  474. // Don't print a constant for ImportRefUnloaded.
  475. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  476. Indent();
  477. FormatInstLHS(inst_id, inst);
  478. out_ << ImportRefUnloaded::Kind.ir_name();
  479. FormatInstRHS(inst);
  480. out_ << "\n";
  481. }
  482. // If there is a pending constant value attached to the current instruction,
  483. // print it now and clear it out. The constant value gets printed before the
  484. // first braced block argument, or at the end of the instruction if there are
  485. // no such arguments.
  486. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  487. if (pending_constant_value_ == ConstantId::NotConstant) {
  488. return;
  489. }
  490. if (space_where == AddSpace::Before) {
  491. out_ << ' ';
  492. }
  493. out_ << '[';
  494. if (pending_constant_value_.is_valid()) {
  495. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  496. if (!pending_constant_value_is_self_) {
  497. out_ << " = ";
  498. FormatConstant(pending_constant_value_);
  499. }
  500. } else {
  501. out_ << pending_constant_value_;
  502. }
  503. out_ << ']';
  504. if (space_where == AddSpace::After) {
  505. out_ << ' ';
  506. }
  507. pending_constant_value_ = ConstantId::NotConstant;
  508. }
  509. auto FormatInstLHS(InstId inst_id, Inst inst) -> void {
  510. switch (inst.kind().value_kind()) {
  511. case InstValueKind::Typed:
  512. FormatName(inst_id);
  513. out_ << ": ";
  514. switch (GetExprCategory(sem_ir_, inst_id)) {
  515. case ExprCategory::NotExpr:
  516. case ExprCategory::Error:
  517. case ExprCategory::Value:
  518. case ExprCategory::Mixed:
  519. break;
  520. case ExprCategory::DurableRef:
  521. case ExprCategory::EphemeralRef:
  522. out_ << "ref ";
  523. break;
  524. case ExprCategory::Initializing:
  525. out_ << "init ";
  526. break;
  527. }
  528. FormatType(inst.type_id());
  529. out_ << " = ";
  530. break;
  531. case InstValueKind::None:
  532. break;
  533. }
  534. }
  535. // Format ImportDecl with its name.
  536. auto FormatInstLHS(InstId inst_id, ImportDecl /*inst*/) -> void {
  537. FormatName(inst_id);
  538. out_ << " = ";
  539. }
  540. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  541. // type_id.
  542. auto FormatInstLHS(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  543. FormatName(inst_id);
  544. out_ << " = ";
  545. }
  546. template <typename InstT>
  547. auto FormatInstRHS(InstT inst) -> void {
  548. // By default, an instruction has a comma-separated argument list.
  549. using Info = Internal::InstLikeTypeInfo<InstT>;
  550. if constexpr (Info::NumArgs == 2) {
  551. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  552. } else if constexpr (Info::NumArgs == 1) {
  553. FormatArgs(Info::template Get<0>(inst));
  554. } else {
  555. FormatArgs();
  556. }
  557. }
  558. auto FormatInstRHS(BindSymbolicName inst) -> void {
  559. // A BindSymbolicName with no value is a purely symbolic binding, such as
  560. // the `Self` in an interface. Don't print out `invalid` for the value.
  561. if (inst.value_id.is_valid()) {
  562. FormatArgs(inst.entity_name_id, inst.value_id);
  563. } else {
  564. FormatArgs(inst.entity_name_id);
  565. }
  566. }
  567. auto FormatInstRHS(BlockArg inst) -> void {
  568. out_ << " ";
  569. FormatLabel(inst.block_id);
  570. }
  571. auto FormatInstRHS(Namespace inst) -> void {
  572. if (inst.import_id.is_valid()) {
  573. FormatArgs(inst.import_id, inst.name_scope_id);
  574. } else {
  575. FormatArgs(inst.name_scope_id);
  576. }
  577. }
  578. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  579. if (!in_terminator_sequence_) {
  580. Indent();
  581. }
  582. out_ << "if ";
  583. FormatName(inst.cond_id);
  584. out_ << " " << Branch::Kind.ir_name() << " ";
  585. FormatLabel(inst.target_id);
  586. out_ << " else ";
  587. in_terminator_sequence_ = true;
  588. }
  589. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  590. if (!in_terminator_sequence_) {
  591. Indent();
  592. }
  593. out_ << BranchWithArg::Kind.ir_name() << " ";
  594. FormatLabel(inst.target_id);
  595. out_ << "(";
  596. FormatName(inst.arg_id);
  597. out_ << ")\n";
  598. in_terminator_sequence_ = false;
  599. }
  600. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  601. if (!in_terminator_sequence_) {
  602. Indent();
  603. }
  604. out_ << Branch::Kind.ir_name() << " ";
  605. FormatLabel(inst.target_id);
  606. out_ << "\n";
  607. in_terminator_sequence_ = false;
  608. }
  609. auto FormatInstRHS(Call inst) -> void {
  610. out_ << " ";
  611. FormatArg(inst.callee_id);
  612. if (!inst.args_id.is_valid()) {
  613. out_ << "(<invalid>)";
  614. return;
  615. }
  616. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  617. auto return_info = ReturnTypeInfo::ForType(sem_ir_, inst.type_id);
  618. bool has_return_slot = return_info.has_return_slot();
  619. InstId return_slot_id = InstId::Invalid;
  620. if (has_return_slot) {
  621. return_slot_id = args.back();
  622. args = args.drop_back();
  623. }
  624. llvm::ListSeparator sep;
  625. out_ << '(';
  626. for (auto inst_id : args) {
  627. out_ << sep;
  628. FormatArg(inst_id);
  629. }
  630. out_ << ')';
  631. if (has_return_slot) {
  632. FormatReturnSlot(return_slot_id);
  633. }
  634. }
  635. auto FormatInstRHS(ArrayInit inst) -> void {
  636. FormatArgs(inst.inits_id);
  637. FormatReturnSlot(inst.dest_id);
  638. }
  639. auto FormatInstRHS(InitializeFrom inst) -> void {
  640. FormatArgs(inst.src_id);
  641. FormatReturnSlot(inst.dest_id);
  642. }
  643. auto FormatInstRHS(ReturnExpr ret) -> void {
  644. FormatArgs(ret.expr_id);
  645. if (ret.dest_id.is_valid()) {
  646. FormatReturnSlot(ret.dest_id);
  647. }
  648. }
  649. auto FormatInstRHS(StructInit init) -> void {
  650. FormatArgs(init.elements_id);
  651. FormatReturnSlot(init.dest_id);
  652. }
  653. auto FormatInstRHS(TupleInit init) -> void {
  654. FormatArgs(init.elements_id);
  655. FormatReturnSlot(init.dest_id);
  656. }
  657. auto FormatInstRHS(FunctionDecl inst) -> void {
  658. FormatArgs(inst.function_id);
  659. FormatTrailingBlock(inst.decl_block_id);
  660. }
  661. auto FormatInstRHS(FunctionType inst) -> void {
  662. if (inst.specific_id.is_valid()) {
  663. FormatArgs(inst.function_id, inst.specific_id);
  664. } else {
  665. FormatArgs(inst.function_id);
  666. }
  667. }
  668. auto FormatInstRHS(ClassDecl inst) -> void {
  669. FormatArgs(inst.class_id);
  670. FormatTrailingBlock(inst.decl_block_id);
  671. }
  672. auto FormatInstRHS(ClassType inst) -> void {
  673. if (inst.specific_id.is_valid()) {
  674. FormatArgs(inst.class_id, inst.specific_id);
  675. } else {
  676. FormatArgs(inst.class_id);
  677. }
  678. }
  679. auto FormatInstRHS(ImplDecl inst) -> void {
  680. FormatArgs(inst.impl_id);
  681. FormatTrailingBlock(inst.decl_block_id);
  682. }
  683. auto FormatInstRHS(InterfaceDecl inst) -> void {
  684. FormatArgs(inst.interface_id);
  685. FormatTrailingBlock(inst.decl_block_id);
  686. }
  687. auto FormatInstRHS(InterfaceType inst) -> void {
  688. if (inst.specific_id.is_valid()) {
  689. FormatArgs(inst.interface_id, inst.specific_id);
  690. } else {
  691. FormatArgs(inst.interface_id);
  692. }
  693. }
  694. auto FormatInstRHS(IntLiteral inst) -> void {
  695. out_ << " ";
  696. sem_ir_.ints()
  697. .Get(inst.int_id)
  698. .print(out_, sem_ir_.types().IsSignedInt(inst.type_id));
  699. }
  700. auto FormatInstRHS(FloatLiteral inst) -> void {
  701. llvm::SmallVector<char, 16> buffer;
  702. sem_ir_.floats().Get(inst.float_id).toString(buffer);
  703. out_ << " " << buffer;
  704. }
  705. auto FormatInstRHS(ImportRefUnloaded inst) -> void {
  706. FormatArgs(inst.import_ir_inst_id);
  707. out_ << ", unloaded";
  708. }
  709. auto FormatInstRHS(ImportRefLoaded inst) -> void {
  710. FormatArgs(inst.import_ir_inst_id);
  711. out_ << ", loaded";
  712. }
  713. auto FormatInstRHS(SpliceBlock inst) -> void {
  714. FormatArgs(inst.result_id);
  715. FormatTrailingBlock(inst.block_id);
  716. }
  717. // StructTypeFields are formatted as part of their StructType.
  718. auto FormatInst(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {}
  719. auto FormatInstRHS(StructType inst) -> void {
  720. out_ << " {";
  721. llvm::ListSeparator sep;
  722. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  723. out_ << sep << ".";
  724. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  725. FormatName(field.name_id);
  726. out_ << ": ";
  727. FormatType(field.field_type_id);
  728. }
  729. out_ << "}";
  730. }
  731. auto FormatArgs() -> void {}
  732. template <typename... Args>
  733. auto FormatArgs(Args... args) -> void {
  734. out_ << ' ';
  735. llvm::ListSeparator sep;
  736. ((out_ << sep, FormatArg(args)), ...);
  737. }
  738. // FormatArg variants handling printing instruction arguments. Several things
  739. // provide equivalent behavior with `FormatName`, so we provide that as the
  740. // default.
  741. template <typename IdT>
  742. auto FormatArg(IdT id) -> void {
  743. FormatName(id);
  744. }
  745. auto FormatArg(BoolValue v) -> void { out_ << v; }
  746. auto FormatArg(BuiltinInstKind kind) -> void { out_ << kind.label(); }
  747. auto FormatArg(EntityNameId id) -> void {
  748. const auto& info = sem_ir_.entity_names().Get(id);
  749. FormatName(info.name_id);
  750. if (info.bind_index.is_valid()) {
  751. out_ << " " << info.bind_index.index;
  752. }
  753. }
  754. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  755. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  756. auto FormatArg(ImportIRId id) -> void {
  757. if (!id.is_valid()) {
  758. out_ << id;
  759. return;
  760. }
  761. const auto& import_ir = *sem_ir_.import_irs().Get(id).sem_ir;
  762. if (import_ir.package_id().is_valid()) {
  763. out_ << import_ir.identifiers().Get(import_ir.package_id());
  764. } else {
  765. out_ << "Main";
  766. }
  767. out_ << "//";
  768. CARBON_CHECK(import_ir.library_id().is_valid());
  769. if (import_ir.library_id() == LibraryNameId::Default) {
  770. out_ << "default";
  771. } else {
  772. out_ << import_ir.string_literal_values().Get(
  773. import_ir.library_id().AsStringLiteralValueId());
  774. }
  775. }
  776. auto FormatArg(ImportIRInstId id) -> void {
  777. // Don't format the inst_id because it refers to a different IR.
  778. // TODO: Consider a better way to format the InstID from other IRs.
  779. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  780. FormatArg(import_ir_inst.ir_id);
  781. out_ << ", " << import_ir_inst.inst_id;
  782. }
  783. auto FormatArg(IntId id) -> void {
  784. // We don't know the signedness to use here. Default to unsigned.
  785. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  786. }
  787. auto FormatArg(LocId id) -> void {
  788. if (id.is_import_ir_inst_id()) {
  789. out_ << "{";
  790. FormatArg(id.import_ir_inst_id());
  791. out_ << "}";
  792. } else {
  793. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  794. // print a line number or something in order to make it less dependent on
  795. // parse?
  796. out_ << id;
  797. }
  798. }
  799. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  800. auto FormatArg(NameScopeId id) -> void {
  801. OpenBrace();
  802. FormatNameScope(id);
  803. CloseBrace();
  804. }
  805. auto FormatArg(InstBlockId id) -> void {
  806. if (!id.is_valid()) {
  807. out_ << "invalid";
  808. return;
  809. }
  810. out_ << '(';
  811. llvm::ListSeparator sep;
  812. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  813. out_ << sep;
  814. FormatArg(inst_id);
  815. }
  816. out_ << ')';
  817. }
  818. auto FormatArg(RealId id) -> void {
  819. // TODO: Format with a `.` when the exponent is near zero.
  820. const auto& real = sem_ir_.reals().Get(id);
  821. real.mantissa.print(out_, /*isSigned=*/false);
  822. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  823. }
  824. auto FormatArg(StringLiteralValueId id) -> void {
  825. out_ << '"';
  826. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  827. /*UseHexEscapes=*/true);
  828. out_ << '"';
  829. }
  830. auto FormatArg(TypeId id) -> void { FormatType(id); }
  831. auto FormatArg(TypeBlockId id) -> void {
  832. out_ << '(';
  833. llvm::ListSeparator sep;
  834. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  835. out_ << sep;
  836. FormatArg(type_id);
  837. }
  838. out_ << ')';
  839. }
  840. auto FormatReturnSlot(InstId dest_id) -> void {
  841. out_ << " to ";
  842. FormatArg(dest_id);
  843. }
  844. // `FormatName` is used when we need the name from an id. Most id types use
  845. // equivalent name formatting from InstNamer, although there are a few special
  846. // formats below.
  847. template <typename IdT>
  848. auto FormatName(IdT id) -> void {
  849. out_ << inst_namer_->GetNameFor(id);
  850. }
  851. auto FormatName(NameId id) -> void {
  852. out_ << sem_ir_.names().GetFormatted(id);
  853. }
  854. auto FormatName(InstId id) -> void {
  855. out_ << inst_namer_->GetNameFor(scope_, id);
  856. }
  857. auto FormatName(SpecificId id) -> void {
  858. const auto& specific = sem_ir_.specifics().Get(id);
  859. FormatName(specific.generic_id);
  860. FormatArg(specific.args_id);
  861. }
  862. auto FormatLabel(InstBlockId id) -> void {
  863. out_ << inst_namer_->GetLabelFor(scope_, id);
  864. }
  865. auto FormatConstant(ConstantId id) -> void {
  866. if (!id.is_valid()) {
  867. out_ << "<not constant>";
  868. return;
  869. }
  870. // For a symbolic constant in a generic, list the constant value in the
  871. // generic first, and the canonical constant second.
  872. if (id.is_symbolic()) {
  873. const auto& symbolic_constant =
  874. sem_ir_.constant_values().GetSymbolicConstant(id);
  875. if (symbolic_constant.generic_id.is_valid()) {
  876. const auto& generic =
  877. sem_ir_.generics().Get(symbolic_constant.generic_id);
  878. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  879. symbolic_constant.index
  880. .region()))[symbolic_constant.index.index()]);
  881. out_ << " (";
  882. FormatName(sem_ir_.constant_values().GetInstId(id));
  883. out_ << ")";
  884. return;
  885. }
  886. }
  887. FormatName(sem_ir_.constant_values().GetInstId(id));
  888. }
  889. auto FormatType(TypeId id) -> void {
  890. if (!id.is_valid()) {
  891. out_ << "invalid";
  892. } else {
  893. // Types are formatted in the `constants` scope because they only refer to
  894. // constants.
  895. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  896. FormatConstant(sem_ir_.types().GetConstantId(id));
  897. }
  898. }
  899. const File& sem_ir_;
  900. InstNamer* const inst_namer_;
  901. // The output stream. Set while formatting instructions.
  902. llvm::raw_ostream& out_;
  903. // The current scope that we are formatting within. References to names in
  904. // this scope will not have a `@scope.` prefix added.
  905. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  906. // Whether we are formatting in a terminator sequence, that is, a sequence of
  907. // branches at the end of a block. The entirety of a terminator sequence is
  908. // formatted on a single line, despite being multiple instructions.
  909. bool in_terminator_sequence_ = false;
  910. // The indent depth to use for new instructions.
  911. int indent_;
  912. // Whether we are currently formatting immediately after an open brace. If so,
  913. // a newline will be inserted before the next line indent.
  914. bool after_open_brace_ = false;
  915. // The constant value of the current instruction, if it has one that has not
  916. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  917. // there is nothing to print.
  918. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  919. // Whether `pending_constant_value_`'s instruction is the same as the
  920. // instruction currently being printed. If true, only the phase of the
  921. // constant is printed, and the value is omitted.
  922. bool pending_constant_value_is_self_ = false;
  923. };
  924. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  925. const Parse::Tree& parse_tree, const File& sem_ir)
  926. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  927. Formatter::~Formatter() = default;
  928. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  929. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  930. formatter.Format();
  931. }
  932. auto Formatter::PrintPartialTrailingCodeBlock(
  933. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  934. -> void {
  935. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  936. formatter.FormatPartialTrailingCodeBlock(block);
  937. }
  938. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  939. llvm::raw_ostream& out) -> void {
  940. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  941. formatter.FormatInst(inst_id);
  942. }
  943. } // namespace Carbon::SemIR