formatter.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  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. if (import_ir.library_id().is_valid()) {
  769. out_ << import_ir.string_literal_values().Get(import_ir.library_id());
  770. } else {
  771. out_ << "default";
  772. }
  773. }
  774. auto FormatArg(ImportIRInstId id) -> void {
  775. // Don't format the inst_id because it refers to a different IR.
  776. // TODO: Consider a better way to format the InstID from other IRs.
  777. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  778. FormatArg(import_ir_inst.ir_id);
  779. out_ << ", " << import_ir_inst.inst_id;
  780. }
  781. auto FormatArg(IntId id) -> void {
  782. // We don't know the signedness to use here. Default to unsigned.
  783. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  784. }
  785. auto FormatArg(LocId id) -> void {
  786. if (id.is_import_ir_inst_id()) {
  787. out_ << "{";
  788. FormatArg(id.import_ir_inst_id());
  789. out_ << "}";
  790. } else {
  791. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  792. // print a line number or something in order to make it less dependent on
  793. // parse?
  794. out_ << id;
  795. }
  796. }
  797. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  798. auto FormatArg(NameScopeId id) -> void {
  799. OpenBrace();
  800. FormatNameScope(id);
  801. CloseBrace();
  802. }
  803. auto FormatArg(InstBlockId id) -> void {
  804. if (!id.is_valid()) {
  805. out_ << "invalid";
  806. return;
  807. }
  808. out_ << '(';
  809. llvm::ListSeparator sep;
  810. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  811. out_ << sep;
  812. FormatArg(inst_id);
  813. }
  814. out_ << ')';
  815. }
  816. auto FormatArg(RealId id) -> void {
  817. // TODO: Format with a `.` when the exponent is near zero.
  818. const auto& real = sem_ir_.reals().Get(id);
  819. real.mantissa.print(out_, /*isSigned=*/false);
  820. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  821. }
  822. auto FormatArg(StringLiteralValueId id) -> void {
  823. out_ << '"';
  824. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  825. /*UseHexEscapes=*/true);
  826. out_ << '"';
  827. }
  828. auto FormatArg(TypeId id) -> void { FormatType(id); }
  829. auto FormatArg(TypeBlockId id) -> void {
  830. out_ << '(';
  831. llvm::ListSeparator sep;
  832. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  833. out_ << sep;
  834. FormatArg(type_id);
  835. }
  836. out_ << ')';
  837. }
  838. auto FormatReturnSlot(InstId dest_id) -> void {
  839. out_ << " to ";
  840. FormatArg(dest_id);
  841. }
  842. // `FormatName` is used when we need the name from an id. Most id types use
  843. // equivalent name formatting from InstNamer, although there are a few special
  844. // formats below.
  845. template <typename IdT>
  846. auto FormatName(IdT id) -> void {
  847. out_ << inst_namer_->GetNameFor(id);
  848. }
  849. auto FormatName(NameId id) -> void {
  850. out_ << sem_ir_.names().GetFormatted(id);
  851. }
  852. auto FormatName(InstId id) -> void {
  853. out_ << inst_namer_->GetNameFor(scope_, id);
  854. }
  855. auto FormatName(SpecificId id) -> void {
  856. const auto& specific = sem_ir_.specifics().Get(id);
  857. FormatName(specific.generic_id);
  858. FormatArg(specific.args_id);
  859. }
  860. auto FormatLabel(InstBlockId id) -> void {
  861. out_ << inst_namer_->GetLabelFor(scope_, id);
  862. }
  863. auto FormatConstant(ConstantId id) -> void {
  864. if (!id.is_valid()) {
  865. out_ << "<not constant>";
  866. return;
  867. }
  868. // For a symbolic constant in a generic, list the constant value in the
  869. // generic first, and the canonical constant second.
  870. if (id.is_symbolic()) {
  871. const auto& symbolic_constant =
  872. sem_ir_.constant_values().GetSymbolicConstant(id);
  873. if (symbolic_constant.generic_id.is_valid()) {
  874. const auto& generic =
  875. sem_ir_.generics().Get(symbolic_constant.generic_id);
  876. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  877. symbolic_constant.index
  878. .region()))[symbolic_constant.index.index()]);
  879. out_ << " (";
  880. FormatName(sem_ir_.constant_values().GetInstId(id));
  881. out_ << ")";
  882. return;
  883. }
  884. }
  885. FormatName(sem_ir_.constant_values().GetInstId(id));
  886. }
  887. auto FormatType(TypeId id) -> void {
  888. if (!id.is_valid()) {
  889. out_ << "invalid";
  890. } else {
  891. // Types are formatted in the `constants` scope because they only refer to
  892. // constants.
  893. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  894. FormatConstant(sem_ir_.types().GetConstantId(id));
  895. }
  896. }
  897. const File& sem_ir_;
  898. InstNamer* const inst_namer_;
  899. // The output stream. Set while formatting instructions.
  900. llvm::raw_ostream& out_;
  901. // The current scope that we are formatting within. References to names in
  902. // this scope will not have a `@scope.` prefix added.
  903. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  904. // Whether we are formatting in a terminator sequence, that is, a sequence of
  905. // branches at the end of a block. The entirety of a terminator sequence is
  906. // formatted on a single line, despite being multiple instructions.
  907. bool in_terminator_sequence_ = false;
  908. // The indent depth to use for new instructions.
  909. int indent_;
  910. // Whether we are currently formatting immediately after an open brace. If so,
  911. // a newline will be inserted before the next line indent.
  912. bool after_open_brace_ = false;
  913. // The constant value of the current instruction, if it has one that has not
  914. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  915. // there is nothing to print.
  916. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  917. // Whether `pending_constant_value_`'s instruction is the same as the
  918. // instruction currently being printed. If true, only the phase of the
  919. // constant is printed, and the value is omitted.
  920. bool pending_constant_value_is_self_ = false;
  921. };
  922. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  923. const Parse::Tree& parse_tree, const File& sem_ir)
  924. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  925. Formatter::~Formatter() = default;
  926. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  927. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  928. formatter.Format();
  929. }
  930. auto Formatter::PrintPartialTrailingCodeBlock(
  931. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  932. -> void {
  933. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  934. formatter.FormatPartialTrailingCodeBlock(block);
  935. }
  936. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  937. llvm::raw_ostream& out) -> void {
  938. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  939. formatter.FormatInst(inst_id);
  940. }
  941. } // namespace Carbon::SemIR