formatter.cpp 32 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 "llvm/ADT/Sequence.h"
  6. #include "llvm/ADT/StringExtras.h"
  7. #include "llvm/ADT/StringMap.h"
  8. #include "llvm/Support/SaveAndRestore.h"
  9. #include "toolchain/base/value_store.h"
  10. #include "toolchain/lex/tokenized_buffer.h"
  11. #include "toolchain/parse/tree.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::SemIR {
  15. namespace {
  16. // Assigns names to instructions, blocks, and scopes in the Semantics IR.
  17. //
  18. // TODOs / future work ideas:
  19. // - Add a documentation file for the textual format and link to the
  20. // naming section here.
  21. // - Consider representing literals as just `literal` in the IR and using the
  22. // type to distinguish.
  23. class InstNamer {
  24. public:
  25. // int32_t matches the input value size.
  26. // NOLINTNEXTLINE(performance-enum-size)
  27. enum class ScopeIndex : int32_t {
  28. None = -1,
  29. File = 0,
  30. Constants = 1,
  31. FirstFunction = 2,
  32. };
  33. static_assert(sizeof(ScopeIndex) == sizeof(FunctionId));
  34. InstNamer(const Lex::TokenizedBuffer& tokenized_buffer,
  35. const Parse::Tree& parse_tree, const File& sem_ir)
  36. : tokenized_buffer_(tokenized_buffer),
  37. parse_tree_(parse_tree),
  38. sem_ir_(sem_ir) {
  39. insts.resize(sem_ir.insts().size());
  40. labels.resize(sem_ir.inst_blocks().size());
  41. scopes.resize(static_cast<int32_t>(ScopeIndex::FirstFunction) +
  42. sem_ir.functions().size() + sem_ir.classes().size() +
  43. sem_ir.interfaces().size());
  44. // Build the constants scope.
  45. GetScopeInfo(ScopeIndex::Constants).name =
  46. globals.AddNameUnchecked("constants");
  47. CollectNamesInBlock(ScopeIndex::Constants, sem_ir.constants().array_ref());
  48. // Build the file scope.
  49. GetScopeInfo(ScopeIndex::File).name = globals.AddNameUnchecked("file");
  50. CollectNamesInBlock(ScopeIndex::File, sem_ir.top_inst_block_id());
  51. // Build each function scope.
  52. for (auto [i, fn] : llvm::enumerate(sem_ir.functions().array_ref())) {
  53. auto fn_id = FunctionId(i);
  54. auto fn_scope = GetScopeFor(fn_id);
  55. // TODO: Provide a location for the function for use as a
  56. // disambiguator.
  57. auto fn_loc = Parse::NodeId::Invalid;
  58. GetScopeInfo(fn_scope).name = globals.AllocateName(
  59. *this, fn_loc, sem_ir.names().GetIRBaseName(fn.name_id).str());
  60. CollectNamesInBlock(fn_scope, fn.implicit_param_refs_id);
  61. CollectNamesInBlock(fn_scope, fn.param_refs_id);
  62. if (fn.return_slot_id.is_valid()) {
  63. insts[fn.return_slot_id.index] = {
  64. fn_scope,
  65. GetScopeInfo(fn_scope).insts.AllocateName(
  66. *this, sem_ir.insts().Get(fn.return_slot_id).parse_node(),
  67. "return")};
  68. }
  69. if (!fn.body_block_ids.empty()) {
  70. AddBlockLabel(fn_scope, fn.body_block_ids.front(), "entry", fn_loc);
  71. }
  72. for (auto block_id : fn.body_block_ids) {
  73. CollectNamesInBlock(fn_scope, block_id);
  74. }
  75. for (auto block_id : fn.body_block_ids) {
  76. AddBlockLabel(fn_scope, block_id);
  77. }
  78. }
  79. // Build each class scope.
  80. for (auto [i, class_info] : llvm::enumerate(sem_ir.classes().array_ref())) {
  81. auto class_id = ClassId(i);
  82. auto class_scope = GetScopeFor(class_id);
  83. // TODO: Provide a location for the class for use as a
  84. // disambiguator.
  85. auto class_loc = Parse::NodeId::Invalid;
  86. GetScopeInfo(class_scope).name = globals.AllocateName(
  87. *this, class_loc,
  88. sem_ir.names().GetIRBaseName(class_info.name_id).str());
  89. AddBlockLabel(class_scope, class_info.body_block_id, "class", class_loc);
  90. CollectNamesInBlock(class_scope, class_info.body_block_id);
  91. }
  92. // Build each interface scope.
  93. for (auto [i, interface_info] :
  94. llvm::enumerate(sem_ir.interfaces().array_ref())) {
  95. auto interface_id = InterfaceId(i);
  96. auto interface_scope = GetScopeFor(interface_id);
  97. // TODO: Provide a location for the interface for use as a
  98. // disambiguator.
  99. auto interface_loc = Parse::NodeId::Invalid;
  100. GetScopeInfo(interface_scope).name = globals.AllocateName(
  101. *this, interface_loc,
  102. sem_ir.names().GetIRBaseName(interface_info.name_id).str());
  103. AddBlockLabel(interface_scope, interface_info.body_block_id, "interface",
  104. interface_loc);
  105. CollectNamesInBlock(interface_scope, interface_info.body_block_id);
  106. }
  107. }
  108. // Returns the scope index corresponding to a function.
  109. auto GetScopeFor(FunctionId fn_id) -> ScopeIndex {
  110. return static_cast<ScopeIndex>(
  111. static_cast<int32_t>(ScopeIndex::FirstFunction) + fn_id.index);
  112. }
  113. // Returns the scope index corresponding to a class.
  114. auto GetScopeFor(ClassId class_id) -> ScopeIndex {
  115. return static_cast<ScopeIndex>(
  116. static_cast<int32_t>(ScopeIndex::FirstFunction) +
  117. sem_ir_.functions().size() + class_id.index);
  118. }
  119. // Returns the scope index corresponding to an interface.
  120. auto GetScopeFor(InterfaceId interface_id) -> ScopeIndex {
  121. return static_cast<ScopeIndex>(
  122. static_cast<int32_t>(ScopeIndex::FirstFunction) +
  123. sem_ir_.functions().size() + sem_ir_.classes().size() +
  124. interface_id.index);
  125. }
  126. // Returns the IR name to use for a function.
  127. auto GetNameFor(FunctionId fn_id) -> llvm::StringRef {
  128. if (!fn_id.is_valid()) {
  129. return "invalid";
  130. }
  131. return GetScopeInfo(GetScopeFor(fn_id)).name.str();
  132. }
  133. // Returns the IR name to use for a class.
  134. auto GetNameFor(ClassId class_id) -> llvm::StringRef {
  135. if (!class_id.is_valid()) {
  136. return "invalid";
  137. }
  138. return GetScopeInfo(GetScopeFor(class_id)).name.str();
  139. }
  140. // Returns the IR name to use for an interface.
  141. auto GetNameFor(InterfaceId interface_id) -> llvm::StringRef {
  142. if (!interface_id.is_valid()) {
  143. return "invalid";
  144. }
  145. return GetScopeInfo(GetScopeFor(interface_id)).name.str();
  146. }
  147. // Returns the IR name to use for an instruction, when referenced from a given
  148. // scope.
  149. auto GetNameFor(ScopeIndex scope_idx, InstId inst_id) -> std::string {
  150. if (!inst_id.is_valid()) {
  151. return "invalid";
  152. }
  153. // Check for a builtin.
  154. if (inst_id.index < BuiltinKind::ValidCount) {
  155. return BuiltinKind::FromInt(inst_id.index).label().str();
  156. }
  157. if (inst_id == InstId::PackageNamespace) {
  158. return "package";
  159. }
  160. auto& [inst_scope, inst_name] = insts[inst_id.index];
  161. if (!inst_name) {
  162. // This should not happen in valid IR.
  163. std::string str;
  164. llvm::raw_string_ostream(str) << "<unexpected instref " << inst_id << ">";
  165. return str;
  166. }
  167. if (inst_scope == scope_idx) {
  168. return inst_name.str().str();
  169. }
  170. return (GetScopeInfo(inst_scope).name.str() + "." + inst_name.str()).str();
  171. }
  172. // Returns the IR name to use for a label, when referenced from a given scope.
  173. auto GetLabelFor(ScopeIndex scope_idx, InstBlockId block_id) -> std::string {
  174. if (!block_id.is_valid()) {
  175. return "!invalid";
  176. }
  177. auto& [label_scope, label_name] = labels[block_id.index];
  178. if (!label_name) {
  179. // This should not happen in valid IR.
  180. std::string str;
  181. llvm::raw_string_ostream(str)
  182. << "<unexpected instblockref " << block_id << ">";
  183. return str;
  184. }
  185. if (label_scope == scope_idx) {
  186. return label_name.str().str();
  187. }
  188. return (GetScopeInfo(label_scope).name.str() + "." + label_name.str())
  189. .str();
  190. }
  191. private:
  192. // A space in which unique names can be allocated.
  193. struct Namespace {
  194. // A result of a name lookup.
  195. struct NameResult;
  196. // A name in a namespace, which might be redirected to refer to another name
  197. // for disambiguation purposes.
  198. class Name {
  199. public:
  200. Name() : value_(nullptr) {}
  201. explicit Name(llvm::StringMapIterator<NameResult> it) : value_(&*it) {}
  202. explicit operator bool() const { return value_; }
  203. auto str() const -> llvm::StringRef {
  204. llvm::StringMapEntry<NameResult>* value = value_;
  205. CARBON_CHECK(value) << "cannot print a null name";
  206. while (value->second.ambiguous && value->second.fallback) {
  207. value = value->second.fallback.value_;
  208. }
  209. return value->first();
  210. }
  211. auto SetFallback(Name name) -> void { value_->second.fallback = name; }
  212. auto SetAmbiguous() -> void { value_->second.ambiguous = true; }
  213. private:
  214. llvm::StringMapEntry<NameResult>* value_ = nullptr;
  215. };
  216. struct NameResult {
  217. bool ambiguous = false;
  218. Name fallback = Name();
  219. };
  220. llvm::StringRef prefix;
  221. llvm::StringMap<NameResult> allocated = {};
  222. int unnamed_count = 0;
  223. auto AddNameUnchecked(llvm::StringRef name) -> Name {
  224. return Name(allocated.insert({name, NameResult()}).first);
  225. }
  226. auto AllocateName(const InstNamer& namer, Parse::NodeId node,
  227. std::string name = "") -> Name {
  228. // The best (shortest) name for this instruction so far, and the current
  229. // name for it.
  230. Name best;
  231. Name current;
  232. // Add `name` as a name for this entity.
  233. auto add_name = [&](bool mark_ambiguous = true) {
  234. auto [it, added] = allocated.insert({name, NameResult()});
  235. Name new_name = Name(it);
  236. if (!added) {
  237. if (mark_ambiguous) {
  238. // This name was allocated for a different instruction. Mark it as
  239. // ambiguous and keep looking for a name for this instruction.
  240. new_name.SetAmbiguous();
  241. }
  242. } else {
  243. if (!best) {
  244. best = new_name;
  245. } else {
  246. CARBON_CHECK(current);
  247. current.SetFallback(new_name);
  248. }
  249. current = new_name;
  250. }
  251. return added;
  252. };
  253. // All names start with the prefix.
  254. name.insert(0, prefix);
  255. // Use the given name if it's available and not just the prefix.
  256. if (name.size() > prefix.size()) {
  257. add_name();
  258. }
  259. // Append location information to try to disambiguate.
  260. if (node.is_valid()) {
  261. auto token = namer.parse_tree_.node_token(node);
  262. llvm::raw_string_ostream(name)
  263. << ".loc" << namer.tokenized_buffer_.GetLineNumber(token);
  264. add_name();
  265. llvm::raw_string_ostream(name)
  266. << "_" << namer.tokenized_buffer_.GetColumnNumber(token);
  267. add_name();
  268. }
  269. // Append numbers until we find an available name.
  270. name += ".";
  271. auto name_size_without_counter = name.size();
  272. for (int counter = 1;; ++counter) {
  273. name.resize(name_size_without_counter);
  274. llvm::raw_string_ostream(name) << counter;
  275. if (add_name(/*mark_ambiguous=*/false)) {
  276. return best;
  277. }
  278. }
  279. }
  280. };
  281. // A named scope that contains named entities.
  282. struct Scope {
  283. Namespace::Name name;
  284. Namespace insts = {.prefix = "%"};
  285. Namespace labels = {.prefix = "!"};
  286. };
  287. auto GetScopeInfo(ScopeIndex scope_idx) -> Scope& {
  288. return scopes[static_cast<int>(scope_idx)];
  289. }
  290. auto AddBlockLabel(ScopeIndex scope_idx, InstBlockId block_id,
  291. std::string name = "",
  292. Parse::NodeId parse_node = Parse::NodeId::Invalid)
  293. -> void {
  294. if (!block_id.is_valid() || labels[block_id.index].second) {
  295. return;
  296. }
  297. if (parse_node == Parse::NodeId::Invalid) {
  298. if (const auto& block = sem_ir_.inst_blocks().Get(block_id);
  299. !block.empty()) {
  300. parse_node = sem_ir_.insts().Get(block.front()).parse_node();
  301. }
  302. }
  303. labels[block_id.index] = {scope_idx,
  304. GetScopeInfo(scope_idx).labels.AllocateName(
  305. *this, parse_node, std::move(name))};
  306. }
  307. // Finds and adds a suitable block label for the given SemIR instruction that
  308. // represents some kind of branch.
  309. auto AddBlockLabel(ScopeIndex scope_idx, InstBlockId block_id, Inst inst)
  310. -> void {
  311. llvm::StringRef name;
  312. switch (parse_tree_.node_kind(inst.parse_node())) {
  313. case Parse::NodeKind::IfExprIf:
  314. switch (inst.kind()) {
  315. case BranchIf::Kind:
  316. name = "if.expr.then";
  317. break;
  318. case Branch::Kind:
  319. name = "if.expr.else";
  320. break;
  321. case BranchWithArg::Kind:
  322. name = "if.expr.result";
  323. break;
  324. default:
  325. break;
  326. }
  327. break;
  328. case Parse::NodeKind::IfCondition:
  329. switch (inst.kind()) {
  330. case BranchIf::Kind:
  331. name = "if.then";
  332. break;
  333. case Branch::Kind:
  334. name = "if.else";
  335. break;
  336. default:
  337. break;
  338. }
  339. break;
  340. case Parse::NodeKind::IfStatement:
  341. name = "if.done";
  342. break;
  343. case Parse::NodeKind::ShortCircuitOperandAnd:
  344. name = inst.Is<BranchIf>() ? "and.rhs" : "and.result";
  345. break;
  346. case Parse::NodeKind::ShortCircuitOperandOr:
  347. name = inst.Is<BranchIf>() ? "or.rhs" : "or.result";
  348. break;
  349. case Parse::NodeKind::WhileConditionStart:
  350. name = "while.cond";
  351. break;
  352. case Parse::NodeKind::WhileCondition:
  353. switch (inst.kind()) {
  354. case InstKind::BranchIf:
  355. name = "while.body";
  356. break;
  357. case InstKind::Branch:
  358. name = "while.done";
  359. break;
  360. default:
  361. break;
  362. }
  363. break;
  364. default:
  365. break;
  366. }
  367. AddBlockLabel(scope_idx, block_id, name.str(), inst.parse_node());
  368. }
  369. auto CollectNamesInBlock(ScopeIndex scope_idx, InstBlockId block_id) -> void {
  370. if (block_id.is_valid()) {
  371. CollectNamesInBlock(scope_idx, sem_ir_.inst_blocks().Get(block_id));
  372. }
  373. }
  374. auto CollectNamesInBlock(ScopeIndex scope_idx, llvm::ArrayRef<InstId> block)
  375. -> void {
  376. Scope& scope = GetScopeInfo(scope_idx);
  377. // Use bound names where available. Otherwise, assign a backup name.
  378. for (auto inst_id : block) {
  379. if (!inst_id.is_valid()) {
  380. continue;
  381. }
  382. auto inst = sem_ir_.insts().Get(inst_id);
  383. auto add_inst_name = [&](std::string name) {
  384. insts[inst_id.index] = {scope_idx, scope.insts.AllocateName(
  385. *this, inst.parse_node(), name)};
  386. };
  387. auto add_inst_name_id = [&](NameId name_id, llvm::StringRef suffix = "") {
  388. add_inst_name(
  389. (sem_ir_.names().GetIRBaseName(name_id).str() + suffix).str());
  390. };
  391. switch (inst.kind()) {
  392. case AddrPattern::Kind: {
  393. // TODO: We need to assign names to parameters that appear in
  394. // function declarations, which may be nested within a pattern. For
  395. // now, just look through `addr`, but we should find a better way to
  396. // visit parameters.
  397. CollectNamesInBlock(scope_idx, inst.As<AddrPattern>().inner_id);
  398. break;
  399. }
  400. case Branch::Kind: {
  401. AddBlockLabel(scope_idx, inst.As<Branch>().target_id, inst);
  402. break;
  403. }
  404. case BranchIf::Kind: {
  405. AddBlockLabel(scope_idx, inst.As<BranchIf>().target_id, inst);
  406. break;
  407. }
  408. case BranchWithArg::Kind: {
  409. AddBlockLabel(scope_idx, inst.As<BranchWithArg>().target_id, inst);
  410. break;
  411. }
  412. case SpliceBlock::Kind: {
  413. CollectNamesInBlock(scope_idx, inst.As<SpliceBlock>().block_id);
  414. break;
  415. }
  416. case BindName::Kind: {
  417. add_inst_name_id(inst.As<BindName>().name_id);
  418. continue;
  419. }
  420. case FunctionDecl::Kind: {
  421. add_inst_name_id(sem_ir_.functions()
  422. .Get(inst.As<FunctionDecl>().function_id)
  423. .name_id);
  424. continue;
  425. }
  426. case ClassDecl::Kind: {
  427. add_inst_name_id(
  428. sem_ir_.classes().Get(inst.As<ClassDecl>().class_id).name_id,
  429. ".decl");
  430. continue;
  431. }
  432. case ClassType::Kind: {
  433. add_inst_name_id(
  434. sem_ir_.classes().Get(inst.As<ClassType>().class_id).name_id);
  435. continue;
  436. }
  437. case Import::Kind: {
  438. add_inst_name("import");
  439. continue;
  440. }
  441. case InterfaceDecl::Kind: {
  442. add_inst_name_id(sem_ir_.interfaces()
  443. .Get(inst.As<InterfaceDecl>().interface_id)
  444. .name_id,
  445. ".decl");
  446. continue;
  447. }
  448. case LazyImportRef::Kind: {
  449. add_inst_name("lazy_import_ref");
  450. continue;
  451. }
  452. case NameRef::Kind: {
  453. add_inst_name_id(inst.As<NameRef>().name_id, ".ref");
  454. continue;
  455. }
  456. case Param::Kind: {
  457. add_inst_name_id(inst.As<Param>().name_id);
  458. continue;
  459. }
  460. case VarStorage::Kind: {
  461. add_inst_name_id(inst.As<VarStorage>().name_id, ".var");
  462. continue;
  463. }
  464. default: {
  465. break;
  466. }
  467. }
  468. // Sequentially number all remaining values.
  469. if (inst.kind().value_kind() != InstValueKind::None) {
  470. add_inst_name("");
  471. }
  472. }
  473. }
  474. const Lex::TokenizedBuffer& tokenized_buffer_;
  475. const Parse::Tree& parse_tree_;
  476. const File& sem_ir_;
  477. Namespace globals = {.prefix = "@"};
  478. std::vector<std::pair<ScopeIndex, Namespace::Name>> insts;
  479. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  480. std::vector<Scope> scopes;
  481. };
  482. } // namespace
  483. // Formatter for printing textual Semantics IR.
  484. class Formatter {
  485. public:
  486. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  487. const Parse::Tree& parse_tree, const File& sem_ir,
  488. llvm::raw_ostream& out)
  489. : sem_ir_(sem_ir),
  490. out_(out),
  491. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  492. // Prints the SemIR.
  493. //
  494. // Constants are printed first and may be referenced by later sections,
  495. // including file-scoped instructions. The file scope may contain entity
  496. // declarations which are defined later, such as classes.
  497. auto Format() -> void {
  498. out_ << "--- " << sem_ir_.filename() << "\n\n";
  499. FormatConstants();
  500. out_ << "file {\n";
  501. // TODO: Handle the case where there are multiple top-level instruction
  502. // blocks. For example, there may be branching in the initializer of a
  503. // global or a type expression.
  504. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  505. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeIndex::File);
  506. FormatCodeBlock(block_id);
  507. }
  508. out_ << "}\n";
  509. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  510. FormatInterface(InterfaceId(i));
  511. }
  512. for (int i : llvm::seq(sem_ir_.classes().size())) {
  513. FormatClass(ClassId(i));
  514. }
  515. for (int i : llvm::seq(sem_ir_.functions().size())) {
  516. FormatFunction(FunctionId(i));
  517. }
  518. // End-of-file newline.
  519. out_ << "\n";
  520. }
  521. auto FormatConstants() -> void {
  522. if (!sem_ir_.constants().size()) {
  523. return;
  524. }
  525. llvm::SaveAndRestore constants_scope(scope_,
  526. InstNamer::ScopeIndex::Constants);
  527. out_ << "constants {\n";
  528. FormatCodeBlock(sem_ir_.constants().array_ref());
  529. out_ << "}\n\n";
  530. }
  531. auto FormatClass(ClassId id) -> void {
  532. const Class& class_info = sem_ir_.classes().Get(id);
  533. out_ << "\nclass ";
  534. FormatClassName(id);
  535. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  536. if (class_info.scope_id.is_valid()) {
  537. out_ << " {\n";
  538. FormatCodeBlock(class_info.body_block_id);
  539. out_ << "\n!members:";
  540. FormatNameScope(class_info.scope_id, "", "\n ");
  541. out_ << "\n}\n";
  542. } else {
  543. out_ << ";\n";
  544. }
  545. }
  546. auto FormatInterface(InterfaceId id) -> void {
  547. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  548. out_ << "\ninterface ";
  549. FormatInterfaceName(id);
  550. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  551. if (interface_info.scope_id.is_valid()) {
  552. out_ << " {\n";
  553. FormatCodeBlock(interface_info.body_block_id);
  554. out_ << "\n!members:";
  555. FormatNameScope(interface_info.scope_id, "", "\n ");
  556. out_ << "\n}\n";
  557. } else {
  558. out_ << ";\n";
  559. }
  560. }
  561. auto FormatFunction(FunctionId id) -> void {
  562. const Function& fn = sem_ir_.functions().Get(id);
  563. out_ << "\nfn ";
  564. FormatFunctionName(id);
  565. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  566. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  567. out_ << "[";
  568. FormatParamList(fn.implicit_param_refs_id);
  569. out_ << "]";
  570. }
  571. out_ << "(";
  572. FormatParamList(fn.param_refs_id);
  573. out_ << ")";
  574. if (fn.return_type_id.is_valid()) {
  575. out_ << " -> ";
  576. if (fn.return_slot_id.is_valid()) {
  577. FormatInstName(fn.return_slot_id);
  578. out_ << ": ";
  579. }
  580. FormatType(fn.return_type_id);
  581. }
  582. if (!fn.body_block_ids.empty()) {
  583. out_ << " {";
  584. for (auto block_id : fn.body_block_ids) {
  585. out_ << "\n";
  586. FormatLabel(block_id);
  587. out_ << ":\n";
  588. FormatCodeBlock(block_id);
  589. }
  590. out_ << "}\n";
  591. } else {
  592. out_ << ";\n";
  593. }
  594. }
  595. auto FormatParamList(InstBlockId param_refs_id) -> void {
  596. llvm::ListSeparator sep;
  597. for (InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  598. out_ << sep;
  599. if (!param_id.is_valid()) {
  600. out_ << "invalid";
  601. continue;
  602. }
  603. if (auto addr = sem_ir_.insts().TryGetAs<SemIR::AddrPattern>(param_id)) {
  604. out_ << "addr ";
  605. param_id = addr->inner_id;
  606. }
  607. FormatInstName(param_id);
  608. out_ << ": ";
  609. FormatType(sem_ir_.insts().Get(param_id).type_id());
  610. }
  611. }
  612. auto FormatCodeBlock(InstBlockId block_id) -> void {
  613. if (block_id.is_valid()) {
  614. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  615. }
  616. }
  617. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  618. for (const InstId inst_id : block) {
  619. FormatInstruction(inst_id);
  620. }
  621. }
  622. auto FormatNameScope(NameScopeId id, llvm::StringRef separator,
  623. llvm::StringRef prefix) -> void {
  624. const auto& scope = sem_ir_.name_scopes().Get(id);
  625. // Name scopes aren't kept in any particular order. Sort the entries before
  626. // we print them for stability and consistency.
  627. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  628. for (auto [name_id, inst_id] : scope.names) {
  629. entries.push_back({inst_id, name_id});
  630. }
  631. llvm::sort(entries,
  632. [](auto a, auto b) { return a.first.index < b.first.index; });
  633. llvm::ListSeparator sep(separator);
  634. for (auto [inst_id, name_id] : entries) {
  635. out_ << sep << prefix << ".";
  636. FormatName(name_id);
  637. out_ << " = ";
  638. FormatInstName(inst_id);
  639. }
  640. for (auto extended_scope_id : scope.extended_scopes) {
  641. // TODO: Print this scope in a better way.
  642. out_ << sep << prefix << "extend " << extended_scope_id;
  643. }
  644. if (scope.has_error) {
  645. out_ << sep << prefix << "has_error";
  646. }
  647. }
  648. auto FormatInstruction(InstId inst_id) -> void {
  649. if (!inst_id.is_valid()) {
  650. Indent();
  651. out_ << "invalid\n";
  652. return;
  653. }
  654. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  655. }
  656. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  657. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  658. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  659. switch (inst.kind()) {
  660. #define CARBON_SEM_IR_INST_KIND(InstT) \
  661. case InstT::Kind: \
  662. FormatInstruction(inst_id, inst.As<InstT>()); \
  663. break;
  664. #include "toolchain/sem_ir/inst_kind.def"
  665. }
  666. }
  667. auto Indent() -> void { out_.indent(indent_); }
  668. template <typename InstT>
  669. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  670. Indent();
  671. FormatInstructionLHS(inst_id, inst);
  672. out_ << InstT::Kind.ir_name();
  673. FormatInstructionRHS(inst);
  674. out_ << "\n";
  675. }
  676. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  677. switch (inst.kind().value_kind()) {
  678. case InstValueKind::Typed:
  679. FormatInstName(inst_id);
  680. out_ << ": ";
  681. switch (GetExprCategory(sem_ir_, inst_id)) {
  682. case ExprCategory::NotExpr:
  683. case ExprCategory::Error:
  684. case ExprCategory::Value:
  685. case ExprCategory::Mixed:
  686. break;
  687. case ExprCategory::DurableRef:
  688. case ExprCategory::EphemeralRef:
  689. out_ << "ref ";
  690. break;
  691. case ExprCategory::Initializing:
  692. out_ << "init ";
  693. break;
  694. }
  695. FormatType(inst.type_id());
  696. out_ << " = ";
  697. break;
  698. case InstValueKind::None:
  699. break;
  700. }
  701. }
  702. // Print ClassDecl with type-like semantics even though it lacks a type_id.
  703. auto FormatInstructionLHS(InstId inst_id, ClassDecl /*inst*/) -> void {
  704. FormatInstName(inst_id);
  705. out_ << " = ";
  706. }
  707. // Print InterfaceDecl with type-like semantics even though it lacks a
  708. // type_id.
  709. auto FormatInstructionLHS(InstId inst_id, InterfaceDecl /*inst*/) -> void {
  710. FormatInstName(inst_id);
  711. out_ << " = ";
  712. }
  713. // Print LazyImportRef with type-like semantics even though it lacks a
  714. // type_id.
  715. auto FormatInstructionLHS(InstId inst_id, LazyImportRef /*inst*/) -> void {
  716. FormatInstName(inst_id);
  717. out_ << " = ";
  718. }
  719. template <typename InstT>
  720. auto FormatInstructionRHS(InstT inst) -> void {
  721. // By default, an instruction has a comma-separated argument list.
  722. using Info = TypedInstArgsInfo<InstT>;
  723. if constexpr (Info::NumArgs == 2) {
  724. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  725. } else if constexpr (Info::NumArgs == 1) {
  726. FormatArgs(Info::template Get<0>(inst));
  727. } else {
  728. FormatArgs();
  729. }
  730. }
  731. auto FormatInstructionRHS(BlockArg inst) -> void {
  732. out_ << " ";
  733. FormatLabel(inst.block_id);
  734. }
  735. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  736. if (!in_terminator_sequence_) {
  737. Indent();
  738. }
  739. out_ << "if ";
  740. FormatInstName(inst.cond_id);
  741. out_ << " " << Branch::Kind.ir_name() << " ";
  742. FormatLabel(inst.target_id);
  743. out_ << " else ";
  744. in_terminator_sequence_ = true;
  745. }
  746. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  747. if (!in_terminator_sequence_) {
  748. Indent();
  749. }
  750. out_ << BranchWithArg::Kind.ir_name() << " ";
  751. FormatLabel(inst.target_id);
  752. out_ << "(";
  753. FormatInstName(inst.arg_id);
  754. out_ << ")\n";
  755. in_terminator_sequence_ = false;
  756. }
  757. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  758. if (!in_terminator_sequence_) {
  759. Indent();
  760. }
  761. out_ << Branch::Kind.ir_name() << " ";
  762. FormatLabel(inst.target_id);
  763. out_ << "\n";
  764. in_terminator_sequence_ = false;
  765. }
  766. auto FormatInstructionRHS(Call inst) -> void {
  767. out_ << " ";
  768. FormatArg(inst.callee_id);
  769. if (!inst.args_id.is_valid()) {
  770. out_ << "(<invalid>)";
  771. return;
  772. }
  773. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  774. bool has_return_slot = GetInitRepr(sem_ir_, inst.type_id).has_return_slot();
  775. InstId return_slot_id = InstId::Invalid;
  776. if (has_return_slot) {
  777. return_slot_id = args.back();
  778. args = args.drop_back();
  779. }
  780. llvm::ListSeparator sep;
  781. out_ << '(';
  782. for (auto inst_id : args) {
  783. out_ << sep;
  784. FormatArg(inst_id);
  785. }
  786. out_ << ')';
  787. if (has_return_slot) {
  788. FormatReturnSlot(return_slot_id);
  789. }
  790. }
  791. auto FormatInstructionRHS(ArrayInit inst) -> void {
  792. FormatArgs(inst.inits_id);
  793. FormatReturnSlot(inst.dest_id);
  794. }
  795. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  796. FormatArgs(inst.src_id);
  797. FormatReturnSlot(inst.dest_id);
  798. }
  799. auto FormatInstructionRHS(StructInit init) -> void {
  800. FormatArgs(init.elements_id);
  801. FormatReturnSlot(init.dest_id);
  802. }
  803. auto FormatInstructionRHS(TupleInit init) -> void {
  804. FormatArgs(init.elements_id);
  805. FormatReturnSlot(init.dest_id);
  806. }
  807. auto FormatInstructionRHS(CrossRef inst) -> void {
  808. // TODO: Figure out a way to make this meaningful. We'll need some way to
  809. // name cross-reference IRs, perhaps by the instruction ID of the import?
  810. out_ << " " << inst.ir_id << ", " << inst.inst_id;
  811. }
  812. auto FormatInstructionRHS(LazyImportRef inst) -> void {
  813. // Don't format the inst_id because it refers to a different IR.
  814. // TODO: Consider a better way to format the InstID from other IRs.
  815. out_ << " " << inst.ir_id << ", " << inst.inst_id;
  816. }
  817. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  818. FormatArgs(inst.result_id);
  819. out_ << " {";
  820. if (!sem_ir_.inst_blocks().Get(inst.block_id).empty()) {
  821. out_ << "\n";
  822. indent_ += 2;
  823. FormatCodeBlock(inst.block_id);
  824. indent_ -= 2;
  825. Indent();
  826. }
  827. out_ << "}";
  828. }
  829. // StructTypeFields are formatted as part of their StructType.
  830. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  831. }
  832. auto FormatInstructionRHS(StructType inst) -> void {
  833. out_ << " {";
  834. llvm::ListSeparator sep;
  835. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  836. out_ << sep << ".";
  837. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  838. FormatName(field.name_id);
  839. out_ << ": ";
  840. FormatType(field.field_type_id);
  841. }
  842. out_ << "}";
  843. }
  844. auto FormatArgs() -> void {}
  845. template <typename... Args>
  846. auto FormatArgs(Args... args) -> void {
  847. out_ << ' ';
  848. llvm::ListSeparator sep;
  849. ((out_ << sep, FormatArg(args)), ...);
  850. }
  851. auto FormatArg(BoolValue v) -> void { out_ << v; }
  852. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  853. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  854. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  855. auto FormatArg(InterfaceId id) -> void { FormatInterfaceName(id); }
  856. auto FormatArg(CrossRefIRId id) -> void { out_ << id; }
  857. auto FormatArg(IntId id) -> void {
  858. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  859. }
  860. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  861. auto FormatArg(NameScopeId id) -> void {
  862. out_ << '{';
  863. FormatNameScope(id, ", ", "");
  864. out_ << '}';
  865. }
  866. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  867. auto FormatArg(InstBlockId id) -> void {
  868. out_ << '(';
  869. llvm::ListSeparator sep;
  870. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  871. out_ << sep;
  872. FormatArg(inst_id);
  873. }
  874. out_ << ')';
  875. }
  876. auto FormatArg(RealId id) -> void {
  877. // TODO: Format with a `.` when the exponent is near zero.
  878. const auto& real = sem_ir_.reals().Get(id);
  879. real.mantissa.print(out_, /*isSigned=*/false);
  880. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  881. }
  882. auto FormatArg(StringLiteralId id) -> void {
  883. out_ << '"';
  884. out_.write_escaped(sem_ir_.string_literals().Get(id),
  885. /*UseHexEscapes=*/true);
  886. out_ << '"';
  887. }
  888. auto FormatArg(NameId id) -> void { FormatName(id); }
  889. auto FormatArg(TypeId id) -> void { FormatType(id); }
  890. auto FormatArg(TypeBlockId id) -> void {
  891. out_ << '(';
  892. llvm::ListSeparator sep;
  893. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  894. out_ << sep;
  895. FormatArg(type_id);
  896. }
  897. out_ << ')';
  898. }
  899. auto FormatReturnSlot(InstId dest_id) -> void {
  900. out_ << " to ";
  901. FormatArg(dest_id);
  902. }
  903. auto FormatName(NameId id) -> void {
  904. out_ << sem_ir_.names().GetFormatted(id);
  905. }
  906. auto FormatInstName(InstId id) -> void {
  907. out_ << inst_namer_.GetNameFor(scope_, id);
  908. }
  909. auto FormatLabel(InstBlockId id) -> void {
  910. out_ << inst_namer_.GetLabelFor(scope_, id);
  911. }
  912. auto FormatFunctionName(FunctionId id) -> void {
  913. out_ << inst_namer_.GetNameFor(id);
  914. }
  915. auto FormatClassName(ClassId id) -> void {
  916. out_ << inst_namer_.GetNameFor(id);
  917. }
  918. auto FormatInterfaceName(InterfaceId id) -> void {
  919. out_ << inst_namer_.GetNameFor(id);
  920. }
  921. auto FormatType(TypeId id) -> void {
  922. if (!id.is_valid()) {
  923. out_ << "invalid";
  924. } else {
  925. out_ << sem_ir_.StringifyType(id);
  926. }
  927. }
  928. private:
  929. const File& sem_ir_;
  930. llvm::raw_ostream& out_;
  931. InstNamer inst_namer_;
  932. InstNamer::ScopeIndex scope_ = InstNamer::ScopeIndex::None;
  933. bool in_terminator_sequence_ = false;
  934. int indent_ = 2;
  935. };
  936. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  937. const Parse::Tree& parse_tree, const File& sem_ir,
  938. llvm::raw_ostream& out) -> void {
  939. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  940. }
  941. } // namespace Carbon::SemIR