formatter.cpp 30 KB

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