formatter.cpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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(FacetTypeId id) -> void {
  822. const auto& info = sem_ir_.facet_types().Get(id);
  823. out_ << "<facet-type ";
  824. FormatType(info.base_facet_type_id);
  825. if (info.requirement_block_id.is_valid()) {
  826. // TODO: include specifics
  827. out_ << "+requirements";
  828. }
  829. out_ << ">";
  830. }
  831. auto FormatArg(IntKind k) -> void { k.Print(out_); }
  832. auto FormatArg(FloatKind k) -> void { k.Print(out_); }
  833. auto FormatArg(ImportIRId id) -> void {
  834. if (id.is_valid()) {
  835. out_ << GetImportIRLabel(id);
  836. } else {
  837. out_ << id;
  838. }
  839. }
  840. auto FormatArg(ImportIRInstId id) -> void {
  841. // Don't format the inst_id because it refers to a different IR.
  842. // TODO: Consider a better way to format the InstID from other IRs.
  843. auto import_ir_inst = sem_ir_.import_ir_insts().Get(id);
  844. FormatArg(import_ir_inst.ir_id);
  845. out_ << ", " << import_ir_inst.inst_id;
  846. }
  847. auto FormatArg(IntId id) -> void {
  848. // We don't know the signedness to use here. Default to unsigned.
  849. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  850. }
  851. auto FormatArg(LocId id) -> void {
  852. if (id.is_import_ir_inst_id()) {
  853. out_ << "{";
  854. FormatArg(id.import_ir_inst_id());
  855. out_ << "}";
  856. } else {
  857. // TODO: For a NodeId, this prints the index of the node. Do we want it to
  858. // print a line number or something in order to make it less dependent on
  859. // parse?
  860. out_ << id;
  861. }
  862. }
  863. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  864. auto FormatArg(RuntimeParamIndex index) -> void { out_ << index; }
  865. auto FormatArg(NameScopeId id) -> void {
  866. OpenBrace();
  867. FormatNameScope(id);
  868. CloseBrace();
  869. }
  870. auto FormatArg(InstBlockId id) -> void {
  871. if (!id.is_valid()) {
  872. out_ << "invalid";
  873. return;
  874. }
  875. out_ << '(';
  876. llvm::ListSeparator sep;
  877. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  878. out_ << sep;
  879. FormatArg(inst_id);
  880. }
  881. out_ << ')';
  882. }
  883. auto FormatArg(RealId id) -> void {
  884. // TODO: Format with a `.` when the exponent is near zero.
  885. const auto& real = sem_ir_.reals().Get(id);
  886. real.mantissa.print(out_, /*isSigned=*/false);
  887. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  888. }
  889. auto FormatArg(StringLiteralValueId id) -> void {
  890. out_ << '"';
  891. out_.write_escaped(sem_ir_.string_literal_values().Get(id),
  892. /*UseHexEscapes=*/true);
  893. out_ << '"';
  894. }
  895. auto FormatArg(TypeId id) -> void { FormatType(id); }
  896. auto FormatArg(TypeBlockId id) -> void {
  897. out_ << '(';
  898. llvm::ListSeparator sep;
  899. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  900. out_ << sep;
  901. FormatArg(type_id);
  902. }
  903. out_ << ')';
  904. }
  905. auto FormatReturnSlot(InstId dest_id) -> void {
  906. out_ << " to ";
  907. FormatArg(dest_id);
  908. }
  909. // `FormatName` is used when we need the name from an id. Most id types use
  910. // equivalent name formatting from InstNamer, although there are a few special
  911. // formats below.
  912. template <typename IdT>
  913. auto FormatName(IdT id) -> void {
  914. out_ << inst_namer_->GetNameFor(id);
  915. }
  916. auto FormatName(NameId id) -> void {
  917. out_ << sem_ir_.names().GetFormatted(id);
  918. }
  919. auto FormatName(InstId id) -> void {
  920. out_ << inst_namer_->GetNameFor(scope_, id);
  921. }
  922. auto FormatName(AbsoluteInstId id) -> void {
  923. FormatName(static_cast<InstId>(id));
  924. }
  925. auto FormatName(SpecificId id) -> void {
  926. const auto& specific = sem_ir_.specifics().Get(id);
  927. FormatName(specific.generic_id);
  928. FormatArg(specific.args_id);
  929. }
  930. auto FormatLabel(InstBlockId id) -> void {
  931. out_ << inst_namer_->GetLabelFor(scope_, id);
  932. }
  933. auto FormatConstant(ConstantId id) -> void {
  934. if (!id.is_valid()) {
  935. out_ << "<not constant>";
  936. return;
  937. }
  938. // For a symbolic constant in a generic, list the constant value in the
  939. // generic first, and the canonical constant second.
  940. if (id.is_symbolic()) {
  941. const auto& symbolic_constant =
  942. sem_ir_.constant_values().GetSymbolicConstant(id);
  943. if (symbolic_constant.generic_id.is_valid()) {
  944. const auto& generic =
  945. sem_ir_.generics().Get(symbolic_constant.generic_id);
  946. FormatName(sem_ir_.inst_blocks().Get(generic.GetEvalBlock(
  947. symbolic_constant.index
  948. .region()))[symbolic_constant.index.index()]);
  949. out_ << " (";
  950. FormatName(sem_ir_.constant_values().GetInstId(id));
  951. out_ << ")";
  952. return;
  953. }
  954. }
  955. FormatName(sem_ir_.constant_values().GetInstId(id));
  956. }
  957. auto FormatType(TypeId id) -> void {
  958. if (!id.is_valid()) {
  959. out_ << "invalid";
  960. } else {
  961. // Types are formatted in the `constants` scope because they only refer to
  962. // constants.
  963. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  964. FormatConstant(sem_ir_.types().GetConstantId(id));
  965. }
  966. }
  967. // Returns the label for the indicated IR.
  968. auto GetImportIRLabel(ImportIRId id) -> std::string {
  969. CARBON_CHECK(id.is_valid(),
  970. "GetImportIRLabel should only be called where we a valid ID.");
  971. const auto& import_ir = *sem_ir_.import_irs().Get(id).sem_ir;
  972. CARBON_CHECK(import_ir.library_id().is_valid());
  973. llvm::StringRef package_name =
  974. import_ir.package_id().is_valid()
  975. ? import_ir.identifiers().Get(import_ir.package_id())
  976. : "Main";
  977. llvm::StringRef library_name =
  978. (import_ir.library_id() != LibraryNameId::Default)
  979. ? import_ir.string_literal_values().Get(
  980. import_ir.library_id().AsStringLiteralValueId())
  981. : "default";
  982. return llvm::formatv("{0}//{1}", package_name, library_name);
  983. }
  984. const File& sem_ir_;
  985. InstNamer* const inst_namer_;
  986. // The output stream. Set while formatting instructions.
  987. llvm::raw_ostream& out_;
  988. // The current scope that we are formatting within. References to names in
  989. // this scope will not have a `@scope.` prefix added.
  990. InstNamer::ScopeId scope_ = InstNamer::ScopeId::None;
  991. // Whether we are formatting in a terminator sequence, that is, a sequence of
  992. // branches at the end of a block. The entirety of a terminator sequence is
  993. // formatted on a single line, despite being multiple instructions.
  994. bool in_terminator_sequence_ = false;
  995. // The indent depth to use for new instructions.
  996. int indent_;
  997. // Whether we are currently formatting immediately after an open brace. If so,
  998. // a newline will be inserted before the next line indent.
  999. bool after_open_brace_ = false;
  1000. // The constant value of the current instruction, if it has one that has not
  1001. // yet been printed. The value `NotConstant` is used as a sentinel to indicate
  1002. // there is nothing to print.
  1003. ConstantId pending_constant_value_ = ConstantId::NotConstant;
  1004. // Whether `pending_constant_value_`'s instruction is the same as the
  1005. // instruction currently being printed. If true, only the phase of the
  1006. // constant is printed, and the value is omitted.
  1007. bool pending_constant_value_is_self_ = false;
  1008. };
  1009. Formatter::Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  1010. const Parse::Tree& parse_tree, const File& sem_ir)
  1011. : sem_ir_(sem_ir), inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  1012. Formatter::~Formatter() = default;
  1013. auto Formatter::Print(llvm::raw_ostream& out) -> void {
  1014. FormatterImpl formatter(sem_ir_, &inst_namer_, out, /*indent=*/0);
  1015. formatter.Format();
  1016. }
  1017. auto Formatter::PrintPartialTrailingCodeBlock(
  1018. llvm::ArrayRef<SemIR::InstId> block, int indent, llvm::raw_ostream& out)
  1019. -> void {
  1020. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  1021. formatter.FormatPartialTrailingCodeBlock(block);
  1022. }
  1023. auto Formatter::PrintInst(SemIR::InstId inst_id, int indent,
  1024. llvm::raw_ostream& out) -> void {
  1025. FormatterImpl formatter(sem_ir_, &inst_namer_, out, indent);
  1026. formatter.FormatInst(inst_id);
  1027. }
  1028. } // namespace Carbon::SemIR