formatter.cpp 28 KB

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