formatter.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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 Branch::Kind: {
  393. AddBlockLabel(scope_idx, inst.As<Branch>().target_id, inst);
  394. break;
  395. }
  396. case BranchIf::Kind: {
  397. AddBlockLabel(scope_idx, inst.As<BranchIf>().target_id, inst);
  398. break;
  399. }
  400. case BranchWithArg::Kind: {
  401. AddBlockLabel(scope_idx, inst.As<BranchWithArg>().target_id, inst);
  402. break;
  403. }
  404. case SpliceBlock::Kind: {
  405. CollectNamesInBlock(scope_idx, inst.As<SpliceBlock>().block_id);
  406. break;
  407. }
  408. case BindName::Kind: {
  409. add_inst_name_id(inst.As<BindName>().name_id);
  410. continue;
  411. }
  412. case FunctionDecl::Kind: {
  413. add_inst_name_id(sem_ir_.functions()
  414. .Get(inst.As<FunctionDecl>().function_id)
  415. .name_id);
  416. continue;
  417. }
  418. case ClassDecl::Kind: {
  419. add_inst_name_id(
  420. sem_ir_.classes().Get(inst.As<ClassDecl>().class_id).name_id,
  421. ".decl");
  422. continue;
  423. }
  424. case ClassType::Kind: {
  425. add_inst_name_id(
  426. sem_ir_.classes().Get(inst.As<ClassType>().class_id).name_id);
  427. continue;
  428. }
  429. case Import::Kind: {
  430. add_inst_name("import");
  431. continue;
  432. }
  433. case InterfaceDecl::Kind: {
  434. add_inst_name_id(sem_ir_.interfaces()
  435. .Get(inst.As<InterfaceDecl>().interface_id)
  436. .name_id,
  437. ".decl");
  438. continue;
  439. }
  440. case LazyImportRef::Kind: {
  441. add_inst_name("lazy_import_ref");
  442. continue;
  443. }
  444. case NameRef::Kind: {
  445. add_inst_name_id(inst.As<NameRef>().name_id, ".ref");
  446. continue;
  447. }
  448. case Param::Kind: {
  449. add_inst_name_id(inst.As<Param>().name_id);
  450. continue;
  451. }
  452. case SelfParam::Kind: {
  453. add_inst_name(inst.As<SelfParam>().is_addr_self.index ? "self.addr"
  454. : "self");
  455. continue;
  456. }
  457. case VarStorage::Kind: {
  458. add_inst_name_id(inst.As<VarStorage>().name_id, ".var");
  459. continue;
  460. }
  461. default: {
  462. break;
  463. }
  464. }
  465. // Sequentially number all remaining values.
  466. if (inst.kind().value_kind() != InstValueKind::None) {
  467. add_inst_name("");
  468. }
  469. }
  470. }
  471. const Lex::TokenizedBuffer& tokenized_buffer_;
  472. const Parse::Tree& parse_tree_;
  473. const File& sem_ir_;
  474. Namespace globals = {.prefix = "@"};
  475. std::vector<std::pair<ScopeIndex, Namespace::Name>> insts;
  476. std::vector<std::pair<ScopeIndex, Namespace::Name>> labels;
  477. std::vector<Scope> scopes;
  478. };
  479. } // namespace
  480. // Formatter for printing textual Semantics IR.
  481. class Formatter {
  482. public:
  483. explicit Formatter(const Lex::TokenizedBuffer& tokenized_buffer,
  484. const Parse::Tree& parse_tree, const File& sem_ir,
  485. llvm::raw_ostream& out)
  486. : sem_ir_(sem_ir),
  487. out_(out),
  488. inst_namer_(tokenized_buffer, parse_tree, sem_ir) {}
  489. // Prints the SemIR.
  490. //
  491. // Constants are printed first and may be referenced by later sections,
  492. // including file-scoped instructions. The file scope may contain entity
  493. // declarations which are defined later, such as classes.
  494. auto Format() -> void {
  495. out_ << "--- " << sem_ir_.filename() << "\n\n";
  496. FormatConstants();
  497. out_ << "file {\n";
  498. // TODO: Handle the case where there are multiple top-level instruction
  499. // blocks. For example, there may be branching in the initializer of a
  500. // global or a type expression.
  501. if (auto block_id = sem_ir_.top_inst_block_id(); block_id.is_valid()) {
  502. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeIndex::File);
  503. FormatCodeBlock(block_id);
  504. }
  505. out_ << "}\n";
  506. for (int i : llvm::seq(sem_ir_.interfaces().size())) {
  507. FormatInterface(InterfaceId(i));
  508. }
  509. for (int i : llvm::seq(sem_ir_.classes().size())) {
  510. FormatClass(ClassId(i));
  511. }
  512. for (int i : llvm::seq(sem_ir_.functions().size())) {
  513. FormatFunction(FunctionId(i));
  514. }
  515. // End-of-file newline.
  516. out_ << "\n";
  517. }
  518. auto FormatConstants() -> void {
  519. if (!sem_ir_.constants().size()) {
  520. return;
  521. }
  522. llvm::SaveAndRestore constants_scope(scope_,
  523. InstNamer::ScopeIndex::Constants);
  524. out_ << "constants {\n";
  525. FormatCodeBlock(sem_ir_.constants().array_ref());
  526. out_ << "}\n\n";
  527. }
  528. auto FormatClass(ClassId id) -> void {
  529. const Class& class_info = sem_ir_.classes().Get(id);
  530. out_ << "\nclass ";
  531. FormatClassName(id);
  532. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  533. if (class_info.scope_id.is_valid()) {
  534. out_ << " {\n";
  535. FormatCodeBlock(class_info.body_block_id);
  536. out_ << "\n!members:";
  537. FormatNameScope(class_info.scope_id, "", "\n ");
  538. out_ << "\n}\n";
  539. } else {
  540. out_ << ";\n";
  541. }
  542. }
  543. auto FormatInterface(InterfaceId id) -> void {
  544. const Interface& interface_info = sem_ir_.interfaces().Get(id);
  545. out_ << "\ninterface ";
  546. FormatInterfaceName(id);
  547. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  548. if (interface_info.scope_id.is_valid()) {
  549. out_ << " {\n";
  550. FormatCodeBlock(interface_info.body_block_id);
  551. out_ << "\n!members:";
  552. FormatNameScope(interface_info.scope_id, "", "\n ");
  553. out_ << "\n}\n";
  554. } else {
  555. out_ << ";\n";
  556. }
  557. }
  558. auto FormatFunction(FunctionId id) -> void {
  559. const Function& fn = sem_ir_.functions().Get(id);
  560. out_ << "\nfn ";
  561. FormatFunctionName(id);
  562. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  563. if (fn.implicit_param_refs_id != InstBlockId::Empty) {
  564. out_ << "[";
  565. FormatParamList(fn.implicit_param_refs_id);
  566. out_ << "]";
  567. }
  568. out_ << "(";
  569. FormatParamList(fn.param_refs_id);
  570. out_ << ")";
  571. if (fn.return_type_id.is_valid()) {
  572. out_ << " -> ";
  573. if (fn.return_slot_id.is_valid()) {
  574. FormatInstName(fn.return_slot_id);
  575. out_ << ": ";
  576. }
  577. FormatType(fn.return_type_id);
  578. }
  579. if (!fn.body_block_ids.empty()) {
  580. out_ << " {";
  581. for (auto block_id : fn.body_block_ids) {
  582. out_ << "\n";
  583. FormatLabel(block_id);
  584. out_ << ":\n";
  585. FormatCodeBlock(block_id);
  586. }
  587. out_ << "}\n";
  588. } else {
  589. out_ << ";\n";
  590. }
  591. }
  592. auto FormatParamList(InstBlockId param_refs_id) -> void {
  593. llvm::ListSeparator sep;
  594. for (const InstId param_id : sem_ir_.inst_blocks().Get(param_refs_id)) {
  595. out_ << sep;
  596. if (!param_id.is_valid()) {
  597. out_ << "invalid";
  598. continue;
  599. }
  600. FormatInstName(param_id);
  601. out_ << ": ";
  602. FormatType(sem_ir_.insts().Get(param_id).type_id());
  603. }
  604. }
  605. auto FormatCodeBlock(InstBlockId block_id) -> void {
  606. if (block_id.is_valid()) {
  607. FormatCodeBlock(sem_ir_.inst_blocks().Get(block_id));
  608. }
  609. }
  610. auto FormatCodeBlock(llvm::ArrayRef<InstId> block) -> void {
  611. for (const InstId inst_id : block) {
  612. FormatInstruction(inst_id);
  613. }
  614. }
  615. auto FormatNameScope(NameScopeId id, llvm::StringRef separator,
  616. llvm::StringRef prefix) -> void {
  617. const auto& scope = sem_ir_.name_scopes().Get(id);
  618. // Name scopes aren't kept in any particular order. Sort the entries before
  619. // we print them for stability and consistency.
  620. llvm::SmallVector<std::pair<InstId, NameId>> entries;
  621. for (auto [name_id, inst_id] : scope.names) {
  622. entries.push_back({inst_id, name_id});
  623. }
  624. llvm::sort(entries,
  625. [](auto a, auto b) { return a.first.index < b.first.index; });
  626. llvm::ListSeparator sep(separator);
  627. for (auto [inst_id, name_id] : entries) {
  628. out_ << sep << prefix << ".";
  629. FormatName(name_id);
  630. out_ << " = ";
  631. FormatInstName(inst_id);
  632. }
  633. for (auto extended_scope_id : scope.extended_scopes) {
  634. // TODO: Print this scope in a better way.
  635. out_ << sep << prefix << "extend " << extended_scope_id;
  636. }
  637. if (scope.has_error) {
  638. out_ << sep << prefix << "has_error";
  639. }
  640. }
  641. auto FormatInstruction(InstId inst_id) -> void {
  642. if (!inst_id.is_valid()) {
  643. Indent();
  644. out_ << "invalid\n";
  645. return;
  646. }
  647. FormatInstruction(inst_id, sem_ir_.insts().Get(inst_id));
  648. }
  649. auto FormatInstruction(InstId inst_id, Inst inst) -> void {
  650. // clang warns on unhandled enum values; clang-tidy is incorrect here.
  651. // NOLINTNEXTLINE(bugprone-switch-missing-default-case)
  652. switch (inst.kind()) {
  653. #define CARBON_SEM_IR_INST_KIND(InstT) \
  654. case InstT::Kind: \
  655. FormatInstruction(inst_id, inst.As<InstT>()); \
  656. break;
  657. #include "toolchain/sem_ir/inst_kind.def"
  658. }
  659. }
  660. auto Indent() -> void { out_.indent(indent_); }
  661. template <typename InstT>
  662. auto FormatInstruction(InstId inst_id, InstT inst) -> void {
  663. Indent();
  664. FormatInstructionLHS(inst_id, inst);
  665. out_ << InstT::Kind.ir_name();
  666. FormatInstructionRHS(inst);
  667. out_ << "\n";
  668. }
  669. auto FormatInstructionLHS(InstId inst_id, Inst inst) -> void {
  670. switch (inst.kind().value_kind()) {
  671. case InstValueKind::Typed:
  672. FormatInstName(inst_id);
  673. out_ << ": ";
  674. switch (GetExprCategory(sem_ir_, inst_id)) {
  675. case ExprCategory::NotExpr:
  676. case ExprCategory::Error:
  677. case ExprCategory::Value:
  678. case ExprCategory::Mixed:
  679. break;
  680. case ExprCategory::DurableRef:
  681. case ExprCategory::EphemeralRef:
  682. out_ << "ref ";
  683. break;
  684. case ExprCategory::Initializing:
  685. out_ << "init ";
  686. break;
  687. }
  688. FormatType(inst.type_id());
  689. out_ << " = ";
  690. break;
  691. case InstValueKind::None:
  692. break;
  693. }
  694. }
  695. // Print ClassDecl with type-like semantics even though it lacks a type_id.
  696. auto FormatInstructionLHS(InstId inst_id, ClassDecl /*inst*/) -> void {
  697. FormatInstName(inst_id);
  698. out_ << " = ";
  699. }
  700. // Print InterfaceDecl with type-like semantics even though it lacks a
  701. // type_id.
  702. auto FormatInstructionLHS(InstId inst_id, InterfaceDecl /*inst*/) -> void {
  703. FormatInstName(inst_id);
  704. out_ << " = ";
  705. }
  706. // Print LazyImportRef with type-like semantics even though it lacks a
  707. // type_id.
  708. auto FormatInstructionLHS(InstId inst_id, LazyImportRef /*inst*/) -> void {
  709. FormatInstName(inst_id);
  710. out_ << " = ";
  711. }
  712. template <typename InstT>
  713. auto FormatInstructionRHS(InstT inst) -> void {
  714. // By default, an instruction has a comma-separated argument list.
  715. using Info = TypedInstArgsInfo<InstT>;
  716. if constexpr (Info::NumArgs == 2) {
  717. FormatArgs(Info::template Get<0>(inst), Info::template Get<1>(inst));
  718. } else if constexpr (Info::NumArgs == 1) {
  719. FormatArgs(Info::template Get<0>(inst));
  720. } else {
  721. FormatArgs();
  722. }
  723. }
  724. auto FormatInstructionRHS(BlockArg inst) -> void {
  725. out_ << " ";
  726. FormatLabel(inst.block_id);
  727. }
  728. auto FormatInstruction(InstId /*inst_id*/, BranchIf inst) -> void {
  729. if (!in_terminator_sequence_) {
  730. Indent();
  731. }
  732. out_ << "if ";
  733. FormatInstName(inst.cond_id);
  734. out_ << " " << Branch::Kind.ir_name() << " ";
  735. FormatLabel(inst.target_id);
  736. out_ << " else ";
  737. in_terminator_sequence_ = true;
  738. }
  739. auto FormatInstruction(InstId /*inst_id*/, BranchWithArg inst) -> void {
  740. if (!in_terminator_sequence_) {
  741. Indent();
  742. }
  743. out_ << BranchWithArg::Kind.ir_name() << " ";
  744. FormatLabel(inst.target_id);
  745. out_ << "(";
  746. FormatInstName(inst.arg_id);
  747. out_ << ")\n";
  748. in_terminator_sequence_ = false;
  749. }
  750. auto FormatInstruction(InstId /*inst_id*/, Branch inst) -> void {
  751. if (!in_terminator_sequence_) {
  752. Indent();
  753. }
  754. out_ << Branch::Kind.ir_name() << " ";
  755. FormatLabel(inst.target_id);
  756. out_ << "\n";
  757. in_terminator_sequence_ = false;
  758. }
  759. auto FormatInstructionRHS(Call inst) -> void {
  760. out_ << " ";
  761. FormatArg(inst.callee_id);
  762. if (!inst.args_id.is_valid()) {
  763. out_ << "(<invalid>)";
  764. return;
  765. }
  766. llvm::ArrayRef<InstId> args = sem_ir_.inst_blocks().Get(inst.args_id);
  767. bool has_return_slot = GetInitRepr(sem_ir_, inst.type_id).has_return_slot();
  768. InstId return_slot_id = InstId::Invalid;
  769. if (has_return_slot) {
  770. return_slot_id = args.back();
  771. args = args.drop_back();
  772. }
  773. llvm::ListSeparator sep;
  774. out_ << '(';
  775. for (auto inst_id : args) {
  776. out_ << sep;
  777. FormatArg(inst_id);
  778. }
  779. out_ << ')';
  780. if (has_return_slot) {
  781. FormatReturnSlot(return_slot_id);
  782. }
  783. }
  784. auto FormatInstructionRHS(ArrayInit inst) -> void {
  785. FormatArgs(inst.inits_id);
  786. FormatReturnSlot(inst.dest_id);
  787. }
  788. auto FormatInstructionRHS(InitializeFrom inst) -> void {
  789. FormatArgs(inst.src_id);
  790. FormatReturnSlot(inst.dest_id);
  791. }
  792. auto FormatInstructionRHS(StructInit init) -> void {
  793. FormatArgs(init.elements_id);
  794. FormatReturnSlot(init.dest_id);
  795. }
  796. auto FormatInstructionRHS(TupleInit init) -> void {
  797. FormatArgs(init.elements_id);
  798. FormatReturnSlot(init.dest_id);
  799. }
  800. auto FormatInstructionRHS(CrossRef inst) -> void {
  801. // TODO: Figure out a way to make this meaningful. We'll need some way to
  802. // name cross-reference IRs, perhaps by the instruction ID of the import?
  803. out_ << " " << inst.ir_id << ", " << inst.inst_id;
  804. }
  805. auto FormatInstructionRHS(LazyImportRef inst) -> void {
  806. // Don't format the inst_id because it refers to a different IR.
  807. // TODO: Consider a better way to format the InstID from other IRs.
  808. out_ << " " << inst.ir_id << ", " << inst.inst_id;
  809. }
  810. auto FormatInstructionRHS(SpliceBlock inst) -> void {
  811. FormatArgs(inst.result_id);
  812. out_ << " {";
  813. if (!sem_ir_.inst_blocks().Get(inst.block_id).empty()) {
  814. out_ << "\n";
  815. indent_ += 2;
  816. FormatCodeBlock(inst.block_id);
  817. indent_ -= 2;
  818. Indent();
  819. }
  820. out_ << "}";
  821. }
  822. // StructTypeFields are formatted as part of their StructType.
  823. auto FormatInstruction(InstId /*inst_id*/, StructTypeField /*inst*/) -> void {
  824. }
  825. auto FormatInstructionRHS(StructType inst) -> void {
  826. out_ << " {";
  827. llvm::ListSeparator sep;
  828. for (auto field_id : sem_ir_.inst_blocks().Get(inst.fields_id)) {
  829. out_ << sep << ".";
  830. auto field = sem_ir_.insts().GetAs<StructTypeField>(field_id);
  831. FormatName(field.name_id);
  832. out_ << ": ";
  833. FormatType(field.field_type_id);
  834. }
  835. out_ << "}";
  836. }
  837. auto FormatArgs() -> void {}
  838. template <typename... Args>
  839. auto FormatArgs(Args... args) -> void {
  840. out_ << ' ';
  841. llvm::ListSeparator sep;
  842. ((out_ << sep, FormatArg(args)), ...);
  843. }
  844. auto FormatArg(BoolValue v) -> void { out_ << v; }
  845. auto FormatArg(BuiltinKind kind) -> void { out_ << kind.label(); }
  846. auto FormatArg(FunctionId id) -> void { FormatFunctionName(id); }
  847. auto FormatArg(ClassId id) -> void { FormatClassName(id); }
  848. auto FormatArg(InterfaceId id) -> void { FormatInterfaceName(id); }
  849. auto FormatArg(CrossRefIRId id) -> void { out_ << id; }
  850. auto FormatArg(IntId id) -> void {
  851. sem_ir_.ints().Get(id).print(out_, /*isSigned=*/false);
  852. }
  853. auto FormatArg(ElementIndex index) -> void { out_ << index; }
  854. auto FormatArg(NameScopeId id) -> void {
  855. out_ << '{';
  856. FormatNameScope(id, ", ", "");
  857. out_ << '}';
  858. }
  859. auto FormatArg(InstId id) -> void { FormatInstName(id); }
  860. auto FormatArg(InstBlockId id) -> void {
  861. out_ << '(';
  862. llvm::ListSeparator sep;
  863. for (auto inst_id : sem_ir_.inst_blocks().Get(id)) {
  864. out_ << sep;
  865. FormatArg(inst_id);
  866. }
  867. out_ << ')';
  868. }
  869. auto FormatArg(RealId id) -> void {
  870. // TODO: Format with a `.` when the exponent is near zero.
  871. const auto& real = sem_ir_.reals().Get(id);
  872. real.mantissa.print(out_, /*isSigned=*/false);
  873. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  874. }
  875. auto FormatArg(StringLiteralId id) -> void {
  876. out_ << '"';
  877. out_.write_escaped(sem_ir_.string_literals().Get(id),
  878. /*UseHexEscapes=*/true);
  879. out_ << '"';
  880. }
  881. auto FormatArg(NameId id) -> void { FormatName(id); }
  882. auto FormatArg(TypeId id) -> void { FormatType(id); }
  883. auto FormatArg(TypeBlockId id) -> void {
  884. out_ << '(';
  885. llvm::ListSeparator sep;
  886. for (auto type_id : sem_ir_.type_blocks().Get(id)) {
  887. out_ << sep;
  888. FormatArg(type_id);
  889. }
  890. out_ << ')';
  891. }
  892. auto FormatReturnSlot(InstId dest_id) -> void {
  893. out_ << " to ";
  894. FormatArg(dest_id);
  895. }
  896. auto FormatName(NameId id) -> void {
  897. out_ << sem_ir_.names().GetFormatted(id);
  898. }
  899. auto FormatInstName(InstId id) -> void {
  900. out_ << inst_namer_.GetNameFor(scope_, id);
  901. }
  902. auto FormatLabel(InstBlockId id) -> void {
  903. out_ << inst_namer_.GetLabelFor(scope_, id);
  904. }
  905. auto FormatFunctionName(FunctionId id) -> void {
  906. out_ << inst_namer_.GetNameFor(id);
  907. }
  908. auto FormatClassName(ClassId id) -> void {
  909. out_ << inst_namer_.GetNameFor(id);
  910. }
  911. auto FormatInterfaceName(InterfaceId id) -> void {
  912. out_ << inst_namer_.GetNameFor(id);
  913. }
  914. auto FormatType(TypeId id) -> void {
  915. if (!id.is_valid()) {
  916. out_ << "invalid";
  917. } else {
  918. out_ << sem_ir_.StringifyType(id);
  919. }
  920. }
  921. private:
  922. const File& sem_ir_;
  923. llvm::raw_ostream& out_;
  924. InstNamer inst_namer_;
  925. InstNamer::ScopeIndex scope_ = InstNamer::ScopeIndex::None;
  926. bool in_terminator_sequence_ = false;
  927. int indent_ = 2;
  928. };
  929. auto FormatFile(const Lex::TokenizedBuffer& tokenized_buffer,
  930. const Parse::Tree& parse_tree, const File& sem_ir,
  931. llvm::raw_ostream& out) -> void {
  932. Formatter(tokenized_buffer, parse_tree, sem_ir, out).Format();
  933. }
  934. } // namespace Carbon::SemIR