formatter.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  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/shared_value_stores.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", impl_info.generic_id, id);
  189. llvm::SaveAndRestore impl_scope(scope_, inst_namer_->GetScopeFor(id));
  190. out_ << ": ";
  191. FormatName(impl_info.self_id);
  192. out_ << " as ";
  193. FormatName(impl_info.constraint_id);
  194. if (impl_info.is_defined()) {
  195. out_ << ' ';
  196. OpenBrace();
  197. FormatCodeBlock(impl_info.body_block_id);
  198. // Print the !members label even if the name scope is empty because we
  199. // always list the witness in this section.
  200. IndentLabel();
  201. out_ << "!members:\n";
  202. if (impl_info.scope_id.is_valid()) {
  203. FormatNameScope(impl_info.scope_id);
  204. }
  205. Indent();
  206. out_ << "witness = ";
  207. FormatArg(impl_info.witness_id);
  208. out_ << "\n";
  209. CloseBrace();
  210. out_ << '\n';
  211. } else {
  212. out_ << ";\n";
  213. }
  214. FormatEntityEnd(impl_info.generic_id);
  215. }
  216. // Formats a full function.
  217. auto FormatFunction(FunctionId id) -> void {
  218. const Function& fn = sem_ir_.functions().Get(id);
  219. std::string function_start;
  220. switch (fn.virtual_modifier) {
  221. case FunctionFields::VirtualModifier::Virtual:
  222. function_start += "virtual ";
  223. break;
  224. case FunctionFields::VirtualModifier::Abstract:
  225. function_start += "abstract ";
  226. break;
  227. case FunctionFields::VirtualModifier::Impl:
  228. function_start += "impl ";
  229. break;
  230. case FunctionFields::VirtualModifier::None:
  231. break;
  232. }
  233. if (fn.is_extern) {
  234. function_start += "extern ";
  235. }
  236. function_start += "fn";
  237. FormatEntityStart(function_start, fn.generic_id, id);
  238. llvm::SaveAndRestore function_scope(scope_, inst_namer_->GetScopeFor(id));
  239. FormatParamList(fn.implicit_param_patterns_id, /*is_implicit=*/true);
  240. FormatParamList(fn.param_patterns_id, /*is_implicit=*/false);
  241. if (fn.return_slot_id.is_valid()) {
  242. out_ << " -> ";
  243. auto return_info = ReturnTypeInfo::ForFunction(sem_ir_, fn);
  244. if (!fn.body_block_ids.empty() && return_info.is_valid() &&
  245. return_info.has_return_slot()) {
  246. FormatName(fn.return_slot_id);
  247. out_ << ": ";
  248. }
  249. FormatType(sem_ir_.insts().Get(fn.return_slot_id).type_id());
  250. }
  251. if (fn.builtin_function_kind != BuiltinFunctionKind::None) {
  252. out_ << " = \"";
  253. out_.write_escaped(fn.builtin_function_kind.name(),
  254. /*UseHexEscapes=*/true);
  255. out_ << "\"";
  256. }
  257. if (!fn.body_block_ids.empty()) {
  258. out_ << ' ';
  259. OpenBrace();
  260. for (auto block_id : fn.body_block_ids) {
  261. IndentLabel();
  262. FormatLabel(block_id);
  263. out_ << ":\n";
  264. FormatCodeBlock(block_id);
  265. }
  266. CloseBrace();
  267. out_ << '\n';
  268. } else {
  269. out_ << ";\n";
  270. }
  271. FormatEntityEnd(fn.generic_id);
  272. }
  273. // Helper for FormatSpecific to print regions.
  274. auto FormatSpecificRegion(const Generic& generic, const Specific& specific,
  275. GenericInstIndex::Region region,
  276. llvm::StringRef region_name) -> void {
  277. if (!specific.GetValueBlock(region).is_valid()) {
  278. return;
  279. }
  280. if (!region_name.empty()) {
  281. IndentLabel();
  282. out_ << "!" << region_name << ":\n";
  283. }
  284. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  285. sem_ir_.inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  286. sem_ir_.inst_blocks().GetOrEmpty(
  287. specific.GetValueBlock(region)))) {
  288. if (generic_inst_id && specific_inst_id &&
  289. sem_ir_.insts().Is<StructTypeField>(*generic_inst_id) &&
  290. sem_ir_.insts().Is<StructTypeField>(*specific_inst_id)) {
  291. // Skip printing struct type fields to match the way we print the
  292. // generic.
  293. continue;
  294. }
  295. Indent();
  296. if (generic_inst_id) {
  297. FormatName(*generic_inst_id);
  298. } else {
  299. out_ << "<missing>";
  300. }
  301. out_ << " => ";
  302. if (specific_inst_id) {
  303. FormatName(*specific_inst_id);
  304. } else {
  305. out_ << "<missing>";
  306. }
  307. out_ << "\n";
  308. }
  309. }
  310. // Formats a full specific.
  311. auto FormatSpecific(SpecificId id) -> void {
  312. const auto& specific = sem_ir_.specifics().Get(id);
  313. out_ << "\n";
  314. out_ << "specific ";
  315. FormatName(id);
  316. // TODO: Remove once we stop forming generic specifics with no generic
  317. // during import.
  318. if (!specific.generic_id.is_valid()) {
  319. out_ << ";\n";
  320. return;
  321. }
  322. out_ << " ";
  323. const auto& generic = sem_ir_.generics().Get(specific.generic_id);
  324. llvm::SaveAndRestore generic_scope(
  325. scope_, inst_namer_->GetScopeFor(specific.generic_id));
  326. OpenBrace();
  327. FormatSpecificRegion(generic, specific,
  328. GenericInstIndex::Region::Declaration, "");
  329. FormatSpecificRegion(generic, specific,
  330. GenericInstIndex::Region::Definition, "definition");
  331. CloseBrace();
  332. out_ << "\n";
  333. }
  334. // Handles generic-specific setup for FormatEntityStart.
  335. auto FormatGenericStart(llvm::StringRef entity_kind, GenericId generic_id)
  336. -> void {
  337. const auto& generic = sem_ir_.generics().Get(generic_id);
  338. out_ << "\n";
  339. Indent();
  340. out_ << "generic " << entity_kind << " ";
  341. FormatName(generic_id);
  342. llvm::SaveAndRestore generic_scope(scope_,
  343. inst_namer_->GetScopeFor(generic_id));
  344. FormatParamList(generic.bindings_id, /*is_implicit=*/false);
  345. out_ << " ";
  346. OpenBrace();
  347. FormatCodeBlock(generic.decl_block_id);
  348. if (generic.definition_block_id.is_valid()) {
  349. IndentLabel();
  350. out_ << "!definition:\n";
  351. FormatCodeBlock(generic.definition_block_id);
  352. }
  353. }
  354. // Provides common formatting for entities, paired with FormatEntityEnd.
  355. template <typename IdT>
  356. auto FormatEntityStart(llvm::StringRef entity_kind, GenericId generic_id,
  357. IdT entity_id) -> void {
  358. if (generic_id.is_valid()) {
  359. FormatGenericStart(entity_kind, generic_id);
  360. }
  361. out_ << "\n";
  362. Indent();
  363. out_ << entity_kind;
  364. // If there's a generic, it will have attached the name. Otherwise, add the
  365. // name here.
  366. if (!generic_id.is_valid()) {
  367. out_ << " ";
  368. FormatName(entity_id);
  369. }
  370. }
  371. // Provides common formatting for entities, paired with FormatEntityStart.
  372. auto FormatEntityEnd(GenericId generic_id) -> void {
  373. if (generic_id.is_valid()) {
  374. CloseBrace();
  375. out_ << '\n';
  376. }
  377. }
  378. // Formats parameters, eliding them completely if they're empty. Wraps in
  379. // parentheses or square brackets based on whether these are implicit
  380. // parameters.
  381. auto FormatParamList(InstBlockId param_patterns_id, bool is_implicit)
  382. -> void {
  383. if (!param_patterns_id.is_valid()) {
  384. return;
  385. }
  386. out_ << (is_implicit ? "[" : "(");
  387. llvm::ListSeparator sep;
  388. for (InstId param_id : sem_ir_.inst_blocks().Get(param_patterns_id)) {
  389. out_ << sep;
  390. if (!param_id.is_valid()) {
  391. out_ << "invalid";
  392. continue;
  393. }
  394. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  395. out_ << "addr ";
  396. param_id = addr->inner_id;
  397. }
  398. FormatName(param_id);
  399. out_ << ": ";
  400. FormatType(sem_ir_.insts().Get(param_id).type_id());
  401. }
  402. out_ << (is_implicit ? "]" : ")");
  403. }
  404. // Prints instructions for a code block.
  405. auto FormatCodeBlock(InstBlockId block_id) -> void {
  406. if (block_id.is_valid()) {
  407. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  408. }
  409. }
  410. // Prints instructions for a code block.
  411. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  412. for (const InstId inst_id : block) {
  413. FormatInst(inst_id);
  414. }
  415. }
  416. // Prints a code block with braces, intended to be used trailing after other
  417. // content on the same line. If non-empty, instructions are on separate lines.
  418. auto FormatTrailingBlock(InstBlockId block_id) -> void {
  419. out_ << ' ';
  420. OpenBrace();
  421. FormatCodeBlock(block_id);
  422. CloseBrace();
  423. }
  424. // Prints the contents of a name scope, with an optional label.
  425. auto FormatNameScope(NameScopeId id, llvm::StringRef label = "") -> void {
  426. const auto& scope = sem_ir_.name_scopes().Get(id);
  427. if (scope.names.empty() && scope.extended_scopes.empty() &&
  428. scope.import_ir_scopes.empty() && !scope.has_error) {
  429. // Name scope is empty.
  430. return;
  431. }
  432. if (!label.empty()) {
  433. IndentLabel();
  434. out_ << label;
  435. }
  436. for (auto [name_id, inst_id, access_kind] : scope.names) {
  437. Indent();
  438. out_ << ".";
  439. FormatName(name_id);
  440. switch (access_kind) {
  441. case SemIR::AccessKind::Public:
  442. break;
  443. case SemIR::AccessKind::Protected:
  444. out_ << " [protected]";
  445. break;
  446. case SemIR::AccessKind::Private:
  447. out_ << " [private]";
  448. break;
  449. }
  450. out_ << " = ";
  451. FormatName(inst_id);
  452. out_ << "\n";
  453. }
  454. for (auto extended_scope_id : scope.extended_scopes) {
  455. // TODO: Print this scope in a better way.
  456. Indent();
  457. out_ << "extend " << extended_scope_id << "\n";
  458. }
  459. // This is used to cluster all "Core//prelude/..." imports, but not
  460. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  461. // add or remove an unused prelude file, but is intended to still show the
  462. // existence of indirect imports.
  463. bool has_prelude_components = false;
  464. for (auto [import_ir_id, unused] : scope.import_ir_scopes) {
  465. auto label = GetImportIRLabel(import_ir_id);
  466. if (label.starts_with("Core//prelude/")) {
  467. if (has_prelude_components) {
  468. // Only print the existence once.
  469. continue;
  470. } else {
  471. has_prelude_components = true;
  472. label = "Core//prelude/...";
  473. }
  474. }
  475. Indent();
  476. out_ << "import " << label << "\n";
  477. }
  478. if (scope.has_error) {
  479. Indent();
  480. out_ << "has_error\n";
  481. }
  482. }
  483. auto FormatInst(InstId inst_id, Inst inst) -> void {
  484. CARBON_KIND_SWITCH(inst) {
  485. #define CARBON_SEM_IR_INST_KIND(InstT) \
  486. case CARBON_KIND(InstT typed_inst): { \
  487. FormatInst(inst_id, typed_inst); \
  488. break; \
  489. }
  490. #include "toolchain/sem_ir/inst_kind.def"
  491. }
  492. }
  493. template <typename InstT>
  494. auto FormatInst(InstId inst_id, InstT inst) -> void {
  495. Indent();
  496. FormatInstLHS(inst_id, inst);
  497. out_ << InstT::Kind.ir_name();
  498. pending_constant_value_ = sem_ir_.constant_values().Get(inst_id);
  499. pending_constant_value_is_self_ =
  500. sem_ir_.constant_values().GetInstIdIfValid(pending_constant_value_) ==
  501. inst_id;
  502. FormatInstRHS(inst);
  503. FormatPendingConstantValue(AddSpace::Before);
  504. out_ << "\n";
  505. }
  506. // Don't print a constant for ImportRefUnloaded.
  507. auto FormatInst(InstId inst_id, ImportRefUnloaded inst) -> void {
  508. Indent();
  509. FormatInstLHS(inst_id, inst);
  510. out_ << ImportRefUnloaded::Kind.ir_name();
  511. FormatInstRHS(inst);
  512. out_ << "\n";
  513. }
  514. // If there is a pending constant value attached to the current instruction,
  515. // print it now and clear it out. The constant value gets printed before the
  516. // first braced block argument, or at the end of the instruction if there are
  517. // no such arguments.
  518. auto FormatPendingConstantValue(AddSpace space_where) -> void {
  519. if (pending_constant_value_ == ConstantId::NotConstant) {
  520. return;
  521. }
  522. if (space_where == AddSpace::Before) {
  523. out_ << ' ';
  524. }
  525. out_ << '[';
  526. if (pending_constant_value_.is_valid()) {
  527. out_ << (pending_constant_value_.is_symbolic() ? "symbolic" : "template");
  528. if (!pending_constant_value_is_self_) {
  529. out_ << " = ";
  530. FormatConstant(pending_constant_value_);
  531. }
  532. } else {
  533. out_ << pending_constant_value_;
  534. }
  535. out_ << ']';
  536. if (space_where == AddSpace::After) {
  537. out_ << ' ';
  538. }
  539. pending_constant_value_ = ConstantId::NotConstant;
  540. }
  541. auto FormatInstLHS(InstId inst_id, Inst inst) -> void {
  542. switch (inst.kind().value_kind()) {
  543. case InstValueKind::Typed:
  544. FormatName(inst_id);
  545. out_ << ": ";
  546. switch (GetExprCategory(sem_ir_, inst_id)) {
  547. case ExprCategory::NotExpr:
  548. case ExprCategory::Error:
  549. case ExprCategory::Value:
  550. case ExprCategory::Mixed:
  551. break;
  552. case ExprCategory::DurableRef:
  553. case ExprCategory::EphemeralRef:
  554. out_ << "ref ";
  555. break;
  556. case ExprCategory::Initializing:
  557. out_ << "init ";
  558. break;
  559. }
  560. FormatType(inst.type_id());
  561. out_ << " = ";
  562. break;
  563. case InstValueKind::None:
  564. break;
  565. }
  566. }
  567. // Format ImportDecl with its name.
  568. auto FormatInstLHS(InstId inst_id, ImportDecl /*inst*/) -> void {
  569. FormatName(inst_id);
  570. out_ << " = ";
  571. }
  572. // Print ImportRefUnloaded with type-like semantics even though it lacks a
  573. // type_id.
  574. auto FormatInstLHS(InstId inst_id, ImportRefUnloaded /*inst*/) -> void {
  575. FormatName(inst_id);
  576. out_ << " = ";
  577. }
  578. template <typename InstT>
  579. auto FormatInstRHS(InstT inst) -> void {
  580. // By default, an instruction has a comma-separated argument list.
  581. using Info = Internal::InstLikeTypeInfo<InstT>;
  582. if constexpr (Info::NumArgs == 2) {
  583. // Several instructions have a second operand that's a specific ID. We
  584. // don't include it in the argument list if there is no corresponding
  585. // specific, that is, when we're not in a generic context.
  586. if constexpr (std::is_same_v<typename Info::template ArgType<1>,
  587. SemIR::SpecificId>) {
  588. if (!Info::template Get<1>(inst).is_valid()) {
  589. FormatArgs(Info::template Get<0>(inst));
  590. return;
  591. }
  592. }
  593. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  594. } else if constexpr (Info::NumArgs == 1) {
  595. FormatArgs(Info::template Get<0>(inst));
  596. } else {
  597. FormatArgs();
  598. }
  599. }
  600. auto FormatInstRHS(BindSymbolicName inst) -> void {
  601. // A BindSymbolicName with no value is a purely symbolic binding, such as
  602. // the `Self` in an interface. Don't print out `invalid` for the value.
  603. if (inst.value_id.is_valid()) {
  604. FormatArgs(inst.entity_name_id, inst.value_id);
  605. } else {
  606. FormatArgs(inst.entity_name_id);
  607. }
  608. }
  609. auto FormatInstRHS(BlockArg inst) -> void {
  610. out_ << " ";
  611. FormatLabel(inst.block_id);
  612. }
  613. auto FormatInstRHS(Namespace inst) -> void {
  614. if (inst.import_id.is_valid()) {
  615. FormatArgs(inst.import_id, inst.name_scope_id);
  616. } else {
  617. FormatArgs(inst.name_scope_id);
  618. }
  619. }
  620. auto FormatInst(InstId /*inst_id*/, BranchIf inst) -> void {
  621. if (!in_terminator_sequence_) {
  622. Indent();
  623. }
  624. out_ << "if ";
  625. FormatName(inst.cond_id);
  626. out_ << " " << Branch::Kind.ir_name() << " ";
  627. FormatLabel(inst.target_id);
  628. out_ << " else ";
  629. in_terminator_sequence_ = true;
  630. }
  631. auto FormatInst(InstId /*inst_id*/, BranchWithArg inst) -> void {
  632. if (!in_terminator_sequence_) {
  633. Indent();
  634. }
  635. out_ << BranchWithArg::Kind.ir_name() << " ";
  636. FormatLabel(inst.target_id);
  637. out_ << "(";
  638. FormatName(inst.arg_id);
  639. out_ << ")\n";
  640. in_terminator_sequence_ = false;
  641. }
  642. auto FormatInst(InstId /*inst_id*/, Branch inst) -> void {
  643. if (!in_terminator_sequence_) {
  644. Indent();
  645. }
  646. out_ << Branch::Kind.ir_name() << " ";
  647. FormatLabel(inst.target_id);
  648. out_ << "\n";
  649. in_terminator_sequence_ = false;
  650. }
  651. auto FormatInstRHS(Call inst) -> void {
  652. out_ << " ";
  653. FormatArg(inst.callee_id);
  654. if (!inst.args_id.is_valid()) {
  655. out_ << "(<invalid>)";
  656. return;
  657. }
  658. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  659. auto return_info = ReturnTypeInfo::ForType(sem_ir_, inst.type_id);
  660. bool has_return_slot = return_info.has_return_slot();
  661. InstId return_slot_id = InstId::Invalid;
  662. if (has_return_slot) {
  663. return_slot_id = args.back();
  664. args = args.drop_back();
  665. }
  666. llvm::ListSeparator sep;
  667. out_ << '(';
  668. for (auto inst_id : args) {
  669. out_ << sep;
  670. FormatArg(inst_id);
  671. }
  672. out_ << ')';
  673. if (has_return_slot) {
  674. FormatReturnSlot(return_slot_id);
  675. }
  676. }
  677. auto FormatInstRHS(ArrayInit inst) -> void {
  678. FormatArgs(inst.inits_id);
  679. FormatReturnSlot(inst.dest_id);
  680. }
  681. auto FormatInstRHS(InitializeFrom inst) -> void {
  682. FormatArgs(inst.src_id);
  683. FormatReturnSlot(inst.dest_id);
  684. }
  685. auto FormatInstRHS(ValueParam inst) -> void {
  686. FormatArgs(inst.runtime_index);
  687. // Omit pretty_name because it's an implementation detail of
  688. // pretty-printing.
  689. }
  690. auto FormatInstRHS(OutParam inst) -> void {
  691. FormatArgs(inst.runtime_index);
  692. // Omit pretty_name because it's an implementation detail of
  693. // pretty-printing.
  694. }
  695. auto FormatInstRHS(ReturnExpr ret) -> void {
  696. FormatArgs(ret.expr_id);
  697. if (ret.dest_id.is_valid()) {
  698. FormatReturnSlot(ret.dest_id);
  699. }
  700. }
  701. auto FormatInstRHS(ReturnSlot inst) -> void {
  702. // Omit inst.type_inst_id because it's not semantically significant.
  703. FormatArgs(inst.storage_id);
  704. }
  705. auto FormatInstRHS(ReturnSlotPattern /*inst*/) -> void {
  706. // No-op because type_id is the only semantically significant field,
  707. // and it's handled separately.
  708. }
  709. auto FormatInstRHS(StructInit init) -> void {
  710. FormatArgs(init.elements_id);
  711. FormatReturnSlot(init.dest_id);
  712. }
  713. auto FormatInstRHS(TupleInit init) -> void {
  714. FormatArgs(init.elements_id);
  715. FormatReturnSlot(init.dest_id);
  716. }
  717. auto FormatInstRHS(FunctionDecl inst) -> void {
  718. FormatArgs(inst.function_id);
  719. llvm::SaveAndRestore class_scope(
  720. scope_, inst_namer_->GetScopeFor(inst.function_id));
  721. FormatTrailingBlock(
  722. sem_ir_.functions().Get(inst.function_id).pattern_block_id);
  723. FormatTrailingBlock(inst.decl_block_id);
  724. }
  725. auto FormatInstRHS(ClassDecl inst) -> void {
  726. FormatArgs(inst.class_id);
  727. llvm::SaveAndRestore class_scope(scope_,
  728. inst_namer_->GetScopeFor(inst.class_id));
  729. FormatTrailingBlock(sem_ir_.classes().Get(inst.class_id).pattern_block_id);
  730. FormatTrailingBlock(inst.decl_block_id);
  731. }
  732. auto FormatInstRHS(ImplDecl inst) -> void {
  733. FormatArgs(inst.impl_id);
  734. llvm::SaveAndRestore class_scope(scope_,
  735. inst_namer_->GetScopeFor(inst.impl_id));
  736. FormatTrailingBlock(sem_ir_.impls().Get(inst.impl_id).pattern_block_id);
  737. FormatTrailingBlock(inst.decl_block_id);
  738. }
  739. auto FormatInstRHS(InterfaceDecl inst) -> void {
  740. FormatArgs(inst.interface_id);
  741. llvm::SaveAndRestore class_scope(
  742. scope_, inst_namer_->GetScopeFor(inst.interface_id));
  743. FormatTrailingBlock(
  744. sem_ir_.interfaces().Get(inst.interface_id).pattern_block_id);
  745. FormatTrailingBlock(inst.decl_block_id);
  746. }
  747. auto FormatInstRHS(IntValue inst) -> void {
  748. out_ << " ";
  749. sem_ir_.ints()
  750. .Get(inst.int_id)
  751. .print(out_, sem_ir_.types().IsSignedInt(inst.type_id));
  752. }
  753. auto FormatInstRHS(FloatLiteral inst) -> void {
  754. llvm::SmallVector<char, 16> buffer;
  755. sem_ir_.floats().Get(inst.float_id).toString(buffer);
  756. out_ << " " << buffer;
  757. }
  758. auto FormatInstRHS(ImportRefUnloaded inst) -> void {
  759. FormatArgs(inst.import_ir_inst_id);
  760. out_ << ", unloaded";
  761. }
  762. auto FormatInstRHS(ImportRefLoaded inst) -> void {
  763. FormatArgs(inst.import_ir_inst_id);
  764. out_ << ", loaded";
  765. }
  766. auto FormatInstRHS(SpliceBlock inst) -> void {
  767. FormatArgs(inst.result_id);
  768. FormatTrailingBlock(inst.block_id);
  769. }
  770. auto FormatInstRHS(WhereExpr inst) -> void {
  771. FormatArgs(inst.period_self_id);
  772. FormatTrailingBlock(inst.requirements_id);
  773. }
  774. // StructTypeFields are formatted as part of their StructType.
  775. auto FormatInst(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {}
  776. auto FormatInstRHS(StructType inst) -> void {
  777. out_ << " {";
  778. llvm::ListSeparator sep;
  779. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  780. out_ << sep << ".";
  781. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  782. FormatName(field.name_id);
  783. out_ << ": ";
  784. FormatType(field.field_type_id);
  785. }
  786. out_ << "}";
  787. }
  788. auto FormatArgs() -> void {}
  789. template <typename... Args>
  790. auto FormatArgs(Args... args) -> void {
  791. out_ << ' ';
  792. llvm::ListSeparator sep;
  793. FormatArgsImpl(sep, args...);
  794. }
  795. auto FormatArgsImpl(llvm::ListSeparator& /* sep */) -> void {}
  796. template <typename Arg, typename... Args>
  797. auto FormatArgsImpl(llvm::ListSeparator& sep, Arg arg, Args... args) -> void {
  798. // Suppress printing MatchingInstIds, which aren't really operands.
  799. if constexpr (!std::is_same_v<Arg, SemIR::MatchingInstId>) {
  800. out_ << sep;
  801. FormatArg(arg);
  802. }
  803. FormatArgsImpl(sep, args...);
  804. }
  805. // FormatArg variants handling printing instruction arguments. Several things
  806. // provide equivalent behavior with `FormatName`, so we provide that as the
  807. // default.
  808. template <typename IdT>
  809. auto FormatArg(IdT id) -> void {
  810. FormatName(id);
  811. }
  812. auto FormatArg(BoolValue v) -> void { out_ << v; }
  813. auto FormatArg(BuiltinInstKind kind) -> void { out_ << kind.label(); }
  814. auto FormatArg(EntityNameId id) -> void {
  815. const auto& info = sem_ir_.entity_names().Get(id);
  816. FormatName(info.name_id);
  817. if (info.bind_index.is_valid()) {
  818. out_ << ", " << info.bind_index.index;
  819. }
  820. }
  821. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  822. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  823. auto FormatArg(ImportIRId id) -> void {
  824. if (id.is_valid()) {
  825. out_ << GetImportIRLabel(id);
  826. } else {
  827. out_ << id;
  828. }
  829. }
  830. auto FormatArg(ImportIRInstId id) -> void {
  831. // Don't format the inst_id because it refers to a different IR.
  832. // TODO: Consider a better way to format the InstID from other IRs.
  833. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  834. FormatArg(import_ir_inst.ir_id);
  835. out_ << ", " << import_ir_inst.inst_id;
  836. }
  837. auto FormatArg(IntId id) -> void {
  838. // We don't know the signedness to use here. Default to unsigned.
  839. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  840. }
  841. auto FormatArg(LocId id) -> void {
  842. if (id.is_import_ir_inst_id()) {
  843. out_ << "{";
  844. FormatArg(id.import_ir_inst_id());
  845. out_ << "}";
  846. } else {
  847. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  848. // print a line number or something in order to make it less dependent on
  849. // parse?
  850. out_ << id;
  851. }
  852. }
  853. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  854. auto FormatArg(RuntimeParamIndex index) -> void { out_ << index; }
  855. auto FormatArg(NameScopeId id) -> void {
  856. OpenBrace();
  857. FormatNameScope(id);
  858. CloseBrace();
  859. }
  860. auto FormatArg(InstBlockId id) -> void {
  861. if (!id.is_valid()) {
  862. out_ << "invalid";
  863. return;
  864. }
  865. out_ << '(';
  866. llvm::ListSeparator sep;
  867. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  868. out_ << sep;
  869. FormatArg(inst_id);
  870. }
  871. out_ << ')';
  872. }
  873. auto FormatArg(RealId id) -> void {
  874. // TODO: Format with a `.` when the exponent is near zero.
  875. const auto& real = sem_ir_.reals().Get(id);
  876. real.mantissa.print(out_, /*isSigned=*/false);
  877. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  878. }
  879. auto FormatArg(StringLiteralValueId id) -> void {
  880. out_ << '"';
  881. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  882. /*UseHexEscapes=*/true);
  883. out_ << '"';
  884. }
  885. auto FormatArg(TypeId id) -> void { FormatType(id); }
  886. auto FormatArg(TypeBlockId id) -> void {
  887. out_ << '(';
  888. llvm::ListSeparator sep;
  889. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  890. out_ << sep;
  891. FormatArg(type_id);
  892. }
  893. out_ << ')';
  894. }
  895. auto FormatReturnSlot(InstId dest_id) -> void {
  896. out_ << " to ";
  897. FormatArg(dest_id);
  898. }
  899. // `FormatName` is used when we need the name from an id. Most id types use
  900. // equivalent name formatting from InstNamer, although there are a few special
  901. // formats below.
  902. template <typename IdT>
  903. auto FormatName(IdT id) -> void {
  904. out_ << inst_namer_->GetNameFor(id);
  905. }
  906. auto FormatName(NameId id) -> void {
  907. out_ << sem_ir_.names().GetFormatted(id);
  908. }
  909. auto FormatName(InstId id) -> void {
  910. out_ << inst_namer_->GetNameFor(scope_, id);
  911. }
  912. auto FormatName(AbsoluteInstId id) -> void {
  913. FormatName(static_cast<InstId>(id));
  914. }
  915. auto FormatName(SpecificId id) -> void {
  916. const auto& specific = sem_ir_.specifics().Get(id);
  917. FormatName(specific.generic_id);
  918. FormatArg(specific.args_id);
  919. }
  920. auto FormatLabel(InstBlockId id) -> void {
  921. out_ << inst_namer_->GetLabelFor(scope_, id);
  922. }
  923. auto FormatConstant(ConstantId id) -> void {
  924. if (!id.is_valid()) {
  925. out_ << "<not constant>";
  926. return;
  927. }
  928. // For a symbolic constant in a generic, list the constant value in the
  929. // generic first, and the canonical constant second.
  930. if (id.is_symbolic()) {
  931. const auto& symbolic_constant =
  932. sem_ir_.constant_values().GetSymbolicConstant(id);
  933. if (symbolic_constant.generic_id.is_valid()) {
  934. const auto& generic =
  935. sem_ir_.generics().Get(symbolic_constant.generic_id);
  936. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  937. symbolic_constant.index
  938. .region()))[symbolic_constant.index.index()]);
  939. out_ << " (";
  940. FormatName(sem_ir_.constant_values().GetInstId(id));
  941. out_ << ")";
  942. return;
  943. }
  944. }
  945. FormatName(sem_ir_.constant_values().GetInstId(id));
  946. }
  947. auto FormatType(TypeId id) -> void {
  948. if (!id.is_valid()) {
  949. out_ << "invalid";
  950. } else {
  951. // Types are formatted in the `constants` scope because they only refer to
  952. // constants.
  953. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  954. FormatConstant(sem_ir_.types().GetConstantId(id));
  955. }
  956. }
  957. // Returns the label for the indicated IR.
  958. auto GetImportIRLabel(ImportIRId id) -> std::string {
  959. CARBON_CHECK(id.is_valid(),
  960. "GetImportIRLabel should only be called where we a valid ID.");
  961. const auto& import_ir = *sem_ir_.import_irs().Get(id).sem_ir;
  962. CARBON_CHECK(import_ir.library_id().is_valid());
  963. llvm::StringRef package_name =
  964. import_ir.package_id().is_valid()
  965. ? import_ir.identifiers().Get(import_ir.package_id())
  966. : "Main";
  967. llvm::StringRef library_name =
  968. (import_ir.library_id() != LibraryNameId::Default)
  969. ? import_ir.string_literal_values().Get(
  970. import_ir.library_id().AsStringLiteralValueId())
  971. : "default";
  972. return llvm::formatv("{0}//{1}", package_name, library_name);
  973. }
  974. const File& sem_ir_;
  975. InstNamer* const inst_namer_;
  976. // The output stream. Set while formatting instructions.
  977. llvm::raw_ostream& out_;
  978. // The current scope that we are formatting within. References to names in
  979. // this scope will not have a `@scope.` prefix added.
  980. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  981. // Whether we are formatting in a terminator sequence, that is, a sequence of
  982. // branches at the end of a block. The entirety of a terminator sequence is
  983. // formatted on a single line, despite being multiple instructions.
  984. bool in_terminator_sequence_ = false;
  985. // The indent depth to use for new instructions.
  986. int indent_;
  987. // Whether we are currently formatting immediately after an open brace. If so,
  988. // a newline will be inserted before the next line indent.
  989. bool after_open_brace_ = false;
  990. // The constant value of the current instruction, if it has one that has not
  991. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  992. // there is nothing to print.
  993. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  994. // Whether `pending_constant_value_`'s instruction is the same as the
  995. // instruction currently being printed. If true, only the phase of the
  996. // constant is printed, and the value is omitted.
  997. bool pending_constant_value_is_self_ = false;
  998. };
  999. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  1000. const Parse::Tree& parse_tree, const File& sem_ir)
  1001. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  1002. Formatter::~Formatter() = default;
  1003. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  1004. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  1005. formatter.Format();
  1006. }
  1007. auto Formatter::PrintPartialTrailingCodeBlock(
  1008. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  1009. -> void {
  1010. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  1011. formatter.FormatPartialTrailingCodeBlock(block);
  1012. }
  1013. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  1014. llvm::raw_ostream& out) -> void {
  1015. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  1016. formatter.FormatInst(inst_id);
  1017. }
  1018. } // namespace Carbon::SemIR