formatter.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494
  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 <string>
  6. #include <utility>
  7. #include "common/ostream.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/Support/SaveAndRestore.h"
  11. #include "toolchain/base/fixed_size_value_store.h"
  12. #include "toolchain/base/kind_switch.h"
  13. #include "toolchain/base/shared_value_stores.h"
  14. #include "toolchain/lex/tokenized_buffer.h"
  15. #include "toolchain/parse/tree.h"
  16. #include "toolchain/parse/tree_and_subtrees.h"
  17. #include "toolchain/sem_ir/builtin_function_kind.h"
  18. #include "toolchain/sem_ir/constant.h"
  19. #include "toolchain/sem_ir/entity_with_params_base.h"
  20. #include "toolchain/sem_ir/expr_info.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/ids.h"
  23. #include "toolchain/sem_ir/name_scope.h"
  24. #include "toolchain/sem_ir/typed_insts.h"
  25. #include "toolchain/sem_ir/vtable.h"
  26. // TODO: Consider addressing recursion here, although it's not critical because
  27. // the formatter isn't required to work on arbitrary code. Still, it may help
  28. // in the future to debug complex code.
  29. // NOLINTBEGIN(misc-no-recursion)
  30. namespace Carbon::SemIR {
  31. Formatter::Formatter(
  32. const File* sem_ir, int total_ir_count,
  33. Parse::GetTreeAndSubtreesFn get_tree_and_subtrees,
  34. const FixedSizeValueStore<SemIR::CheckIRId, bool>* include_ir_in_dumps,
  35. bool use_dump_sem_ir_ranges)
  36. : sem_ir_(sem_ir),
  37. inst_namer_(sem_ir_, total_ir_count),
  38. get_tree_and_subtrees_(get_tree_and_subtrees),
  39. include_ir_in_dumps_(include_ir_in_dumps),
  40. use_dump_sem_ir_ranges_(use_dump_sem_ir_ranges),
  41. // Create a placeholder visible chunk and assign it to all instructions
  42. // that don't have a chunk of their own.
  43. tentative_inst_chunks_(sem_ir_->insts(), AddChunkNoFlush(true)) {
  44. if (use_dump_sem_ir_ranges_) {
  45. ComputeNodeParents();
  46. }
  47. // Create empty placeholder chunks for instructions that we output lazily.
  48. for (auto inst_id : llvm::concat<const InstId>(
  49. sem_ir_->constants().array_ref(),
  50. sem_ir_->inst_blocks().Get(InstBlockId::Imports))) {
  51. tentative_inst_chunks_.Set(inst_id, AddChunkNoFlush(false));
  52. }
  53. // Create a real chunk for the start of the output.
  54. AddChunkNoFlush(true);
  55. }
  56. auto Formatter::Format() -> void {
  57. out_ << "--- " << sem_ir_->filename() << "\n";
  58. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Constants,
  59. sem_ir_->constants().array_ref(),
  60. /*use_tentative_output_scopes=*/true);
  61. FormatTopLevelScopeIfUsed(InstNamer::ScopeId::Imports,
  62. sem_ir_->inst_blocks().Get(InstBlockId::Imports),
  63. /*use_tentative_output_scopes=*/true);
  64. FormatTopLevelScopeIfUsed(
  65. InstNamer::ScopeId::File,
  66. sem_ir_->inst_blocks().GetOrEmpty(sem_ir_->top_inst_block_id()),
  67. /*use_tentative_output_scopes=*/false);
  68. for (auto [id, _] : sem_ir_->interfaces().enumerate()) {
  69. FormatInterface(id);
  70. }
  71. for (auto [id, _] : sem_ir_->associated_constants().enumerate()) {
  72. FormatAssociatedConstant(id);
  73. }
  74. for (auto [id, _] : sem_ir_->impls().enumerate()) {
  75. FormatImpl(id);
  76. }
  77. for (auto [id, _] : sem_ir_->classes().enumerate()) {
  78. FormatClass(id);
  79. }
  80. for (auto [id, _] : sem_ir_->vtables().enumerate()) {
  81. FormatVtable(id);
  82. }
  83. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  84. FormatFunction(id);
  85. }
  86. for (auto [id, _] : sem_ir_->specifics().enumerate()) {
  87. FormatSpecific(id);
  88. }
  89. out_ << "\n";
  90. }
  91. auto Formatter::ComputeNodeParents() -> void {
  92. CARBON_CHECK(!node_parents_);
  93. node_parents_ = NodeParentStore::MakeWithExplicitSize(
  94. sem_ir_->parse_tree().size(), Parse::NodeId::None);
  95. for (auto n : sem_ir_->parse_tree().postorder()) {
  96. for (auto child : get_tree_and_subtrees_().children(n)) {
  97. node_parents_->Set(child, n);
  98. }
  99. }
  100. }
  101. auto Formatter::Write(llvm::raw_ostream& out) -> void {
  102. FlushChunk();
  103. for (const auto& chunk : output_chunks_) {
  104. if (chunk.include_in_output) {
  105. out << chunk.chunk;
  106. }
  107. }
  108. }
  109. auto Formatter::FlushChunk() -> void {
  110. CARBON_CHECK(output_chunks_.back().chunk.empty());
  111. output_chunks_.back().chunk = std::move(buffer_);
  112. buffer_.clear();
  113. }
  114. auto Formatter::AddChunkNoFlush(bool include_in_output) -> size_t {
  115. CARBON_CHECK(buffer_.empty());
  116. output_chunks_.push_back({.include_in_output = include_in_output});
  117. return output_chunks_.size() - 1;
  118. }
  119. auto Formatter::AddChunk(bool include_in_output) -> size_t {
  120. FlushChunk();
  121. return AddChunkNoFlush(include_in_output);
  122. }
  123. auto Formatter::IncludeChunkInOutput(size_t chunk) -> void {
  124. if (chunk == output_chunks_.size() - 1) {
  125. return;
  126. }
  127. if (auto& current_chunk = output_chunks_.back();
  128. !current_chunk.include_in_output) {
  129. current_chunk.dependencies.push_back(chunk);
  130. return;
  131. }
  132. llvm::SmallVector<size_t> to_add = {chunk};
  133. while (!to_add.empty()) {
  134. auto& chunk = output_chunks_[to_add.pop_back_val()];
  135. if (chunk.include_in_output) {
  136. continue;
  137. }
  138. chunk.include_in_output = true;
  139. to_add.append(chunk.dependencies);
  140. chunk.dependencies.clear();
  141. }
  142. }
  143. auto Formatter::ShouldIncludeInstByIR(InstId inst_id) -> bool {
  144. const auto* import_ir = GetCanonicalFileAndInstId(sem_ir_, inst_id).first;
  145. return include_ir_in_dumps_->Get(import_ir->check_ir_id());
  146. }
  147. // Returns true for a `DefinitionStart` node.
  148. static auto IsDefinitionStart(Parse::NodeKind node_kind) -> bool {
  149. switch (node_kind) {
  150. case Parse::NodeKind::BuiltinFunctionDefinitionStart:
  151. case Parse::NodeKind::ChoiceDefinitionStart:
  152. case Parse::NodeKind::ClassDefinitionStart:
  153. case Parse::NodeKind::FunctionDefinitionStart:
  154. case Parse::NodeKind::ImplDefinitionStart:
  155. case Parse::NodeKind::InterfaceDefinitionStart:
  156. case Parse::NodeKind::NamedConstraintDefinitionStart:
  157. return true;
  158. default:
  159. return false;
  160. }
  161. }
  162. auto Formatter::ShouldFormatEntity(InstId decl_id) -> bool {
  163. if (!decl_id.has_value()) {
  164. return true;
  165. }
  166. if (!ShouldIncludeInstByIR(decl_id)) {
  167. return false;
  168. }
  169. if (!use_dump_sem_ir_ranges_) {
  170. return true;
  171. }
  172. // When there are dump ranges, ignore imported instructions.
  173. auto loc_id = sem_ir_->insts().GetCanonicalLocId(decl_id);
  174. if (loc_id.kind() != LocId::Kind::NodeId) {
  175. return false;
  176. }
  177. const auto& tree_and_subtrees = get_tree_and_subtrees_();
  178. // This takes the earliest token from either the node or its first postorder
  179. // child. The first postorder child isn't necessarily the earliest token in
  180. // the subtree (for example, it can miss modifiers), but finding the earliest
  181. // token requires walking *all* children, whereas this approach is
  182. // constant-time.
  183. auto begin_node_id = *tree_and_subtrees.postorder(loc_id.node_id()).begin();
  184. // Non-defining declarations will be associated with a `Decl` node.
  185. // Definitions will have a `DefinitionStart` for which we can use the parent
  186. // to find the `Definition`, giving a range that includes the definition's
  187. // body.
  188. auto end_node_id = loc_id.node_id();
  189. if (IsDefinitionStart(sem_ir_->parse_tree().node_kind(end_node_id))) {
  190. end_node_id = node_parents_->Get(end_node_id);
  191. }
  192. Lex::InclusiveTokenRange range = {
  193. .begin = sem_ir_->parse_tree().node_token(begin_node_id),
  194. .end = sem_ir_->parse_tree().node_token(end_node_id)};
  195. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(range);
  196. }
  197. auto Formatter::ShouldFormatEntity(const EntityWithParamsBase& entity) -> bool {
  198. return ShouldFormatEntity(entity.latest_decl_id());
  199. }
  200. auto Formatter::ShouldFormatInst(InstId inst_id) -> bool {
  201. if (!use_dump_sem_ir_ranges_) {
  202. return true;
  203. }
  204. // When there are dump ranges, ignore imported instructions.
  205. auto loc_id = sem_ir_->insts().GetCanonicalLocId(inst_id);
  206. if (loc_id.kind() != LocId::Kind::NodeId) {
  207. return false;
  208. }
  209. auto token = sem_ir_->parse_tree().node_token(loc_id.node_id());
  210. return sem_ir_->parse_tree().tokens().OverlapsWithDumpSemIRRange(
  211. Lex::InclusiveTokenRange{.begin = token, .end = token});
  212. }
  213. auto Formatter::OpenBrace() -> void {
  214. // Put the constant value of an instruction before any braced block, rather
  215. // than at the end.
  216. FormatPendingConstantValue(AddSpace::After);
  217. // Put the imported-from library name before the definition of the entity.
  218. FormatPendingImportedFrom(AddSpace::After);
  219. out_ << '{';
  220. indent_ += 2;
  221. after_open_brace_ = true;
  222. }
  223. auto Formatter::CloseBrace() -> void {
  224. indent_ -= 2;
  225. if (!after_open_brace_) {
  226. Indent();
  227. }
  228. out_ << '}';
  229. after_open_brace_ = false;
  230. }
  231. auto Formatter::Semicolon() -> void {
  232. FormatPendingImportedFrom(AddSpace::Before);
  233. out_ << ';';
  234. }
  235. auto Formatter::Indent(int offset) -> void {
  236. if (after_open_brace_) {
  237. out_ << '\n';
  238. after_open_brace_ = false;
  239. }
  240. out_.indent(indent_ + offset);
  241. }
  242. auto Formatter::IndentLabel() -> void {
  243. CARBON_CHECK(indent_ >= 2);
  244. if (!after_open_brace_) {
  245. out_ << '\n';
  246. }
  247. Indent(-2);
  248. }
  249. auto Formatter::FormatTopLevelScopeIfUsed(InstNamer::ScopeId scope_id,
  250. llvm::ArrayRef<InstId> block,
  251. bool use_tentative_output_scopes)
  252. -> void {
  253. if (!use_tentative_output_scopes && use_dump_sem_ir_ranges_) {
  254. // Don't format the scope if no instructions are in a dump range.
  255. block = block.drop_while(
  256. [&](InstId inst_id) { return !ShouldFormatInst(inst_id); });
  257. }
  258. if (block.empty()) {
  259. return;
  260. }
  261. llvm::SaveAndRestore scope(scope_, scope_id);
  262. // Note, we don't use OpenBrace() / CloseBrace() here because we always want
  263. // a newline to avoid misformatting if the first instruction is omitted.
  264. out_ << "\n" << inst_namer_.GetScopeName(scope_id) << " {\n";
  265. indent_ += 2;
  266. for (const InstId inst_id : block) {
  267. // Format instructions when needed, but do nothing for elided entries;
  268. // unlike normal code blocks, scopes are non-sequential so skipped
  269. // instructions are assumed to be uninteresting.
  270. if (use_tentative_output_scopes) {
  271. // This is for constants and imports. These use tentative logic to
  272. // determine whether an instruction is printed.
  273. TentativeOutputScope scope(*this, tentative_inst_chunks_.Get(inst_id));
  274. FormatInst(inst_id);
  275. } else if (ShouldFormatInst(inst_id)) {
  276. // This is for the file scope. It uses only the range-based filtering.
  277. FormatInst(inst_id);
  278. }
  279. }
  280. out_ << "}\n";
  281. indent_ -= 2;
  282. }
  283. auto Formatter::FormatClass(ClassId id) -> void {
  284. const Class& class_info = sem_ir_->classes().Get(id);
  285. if (!ShouldFormatEntity(class_info)) {
  286. return;
  287. }
  288. FormatEntityStart("class", class_info, id);
  289. llvm::SaveAndRestore class_scope(scope_, inst_namer_.GetScopeFor(id));
  290. if (class_info.scope_id.has_value()) {
  291. out_ << ' ';
  292. OpenBrace();
  293. FormatCodeBlock(class_info.body_block_id);
  294. Indent();
  295. out_ << "complete_type_witness = ";
  296. FormatName(class_info.complete_type_witness_id);
  297. out_ << "\n";
  298. if (class_info.vtable_decl_id.has_value()) {
  299. Indent();
  300. out_ << "vtable_decl = ";
  301. FormatName(class_info.vtable_decl_id);
  302. out_ << "\n";
  303. }
  304. FormatNameScope(class_info.scope_id, "!members:\n");
  305. CloseBrace();
  306. } else {
  307. Semicolon();
  308. }
  309. out_ << '\n';
  310. FormatEntityEnd(class_info.generic_id);
  311. }
  312. auto Formatter::FormatVtable(VtableId id) -> void {
  313. const Vtable& vtable_info = sem_ir_->vtables().Get(id);
  314. out_ << '\n';
  315. Indent();
  316. out_ << "vtable ";
  317. FormatName(id);
  318. out_ << ' ';
  319. OpenBrace();
  320. for (auto function_id :
  321. sem_ir_->inst_blocks().Get(vtable_info.virtual_functions_id)) {
  322. Indent();
  323. FormatArg(function_id);
  324. out_ << '\n';
  325. }
  326. CloseBrace();
  327. out_ << '\n';
  328. }
  329. auto Formatter::FormatInterface(InterfaceId id) -> void {
  330. const Interface& interface_info = sem_ir_->interfaces().Get(id);
  331. if (!ShouldFormatEntity(interface_info)) {
  332. return;
  333. }
  334. FormatEntityStart("interface", interface_info, id);
  335. llvm::SaveAndRestore interface_scope(scope_, inst_namer_.GetScopeFor(id));
  336. if (interface_info.scope_id.has_value()) {
  337. out_ << ' ';
  338. OpenBrace();
  339. FormatCodeBlock(interface_info.body_block_id);
  340. // Always include the !members label because we always list the witness in
  341. // this section.
  342. IndentLabel();
  343. out_ << "!members:\n";
  344. FormatNameScope(interface_info.scope_id);
  345. Indent();
  346. out_ << "witness = ";
  347. FormatArg(interface_info.associated_entities_id);
  348. out_ << "\n";
  349. CloseBrace();
  350. } else {
  351. Semicolon();
  352. }
  353. out_ << '\n';
  354. FormatEntityEnd(interface_info.generic_id);
  355. }
  356. auto Formatter::FormatAssociatedConstant(AssociatedConstantId id) -> void {
  357. const AssociatedConstant& assoc_const =
  358. sem_ir_->associated_constants().Get(id);
  359. if (!ShouldFormatEntity(assoc_const.decl_id)) {
  360. return;
  361. }
  362. FormatEntityStart("assoc_const", assoc_const.decl_id, assoc_const.generic_id,
  363. id);
  364. llvm::SaveAndRestore assoc_const_scope(scope_, inst_namer_.GetScopeFor(id));
  365. out_ << " ";
  366. FormatName(assoc_const.name_id);
  367. out_ << ":! ";
  368. FormatTypeOfInst(assoc_const.decl_id);
  369. if (assoc_const.default_value_id.has_value()) {
  370. out_ << " = ";
  371. FormatArg(assoc_const.default_value_id);
  372. }
  373. out_ << ";\n";
  374. FormatEntityEnd(assoc_const.generic_id);
  375. }
  376. auto Formatter::FormatImpl(ImplId id) -> void {
  377. const Impl& impl_info = sem_ir_->impls().Get(id);
  378. if (!ShouldFormatEntity(impl_info)) {
  379. return;
  380. }
  381. FormatEntityStart("impl", impl_info, id);
  382. llvm::SaveAndRestore impl_scope(scope_, inst_namer_.GetScopeFor(id));
  383. out_ << ": ";
  384. FormatName(impl_info.self_id);
  385. out_ << " as ";
  386. FormatName(impl_info.constraint_id);
  387. if (impl_info.is_complete()) {
  388. out_ << ' ';
  389. OpenBrace();
  390. FormatCodeBlock(impl_info.body_block_id);
  391. // Print the !members label even if the name scope is empty because we
  392. // always list the witness in this section.
  393. IndentLabel();
  394. out_ << "!members:\n";
  395. if (impl_info.scope_id.has_value()) {
  396. FormatNameScope(impl_info.scope_id);
  397. }
  398. Indent();
  399. out_ << "witness = ";
  400. FormatArg(impl_info.witness_id);
  401. out_ << "\n";
  402. CloseBrace();
  403. } else {
  404. Semicolon();
  405. }
  406. out_ << '\n';
  407. FormatEntityEnd(impl_info.generic_id);
  408. }
  409. auto Formatter::FormatFunction(FunctionId id) -> void {
  410. const Function& fn = sem_ir_->functions().Get(id);
  411. if (!ShouldFormatEntity(fn)) {
  412. return;
  413. }
  414. std::string function_start;
  415. switch (fn.virtual_modifier) {
  416. case FunctionFields::VirtualModifier::Virtual:
  417. function_start += "virtual ";
  418. break;
  419. case FunctionFields::VirtualModifier::Abstract:
  420. function_start += "abstract ";
  421. break;
  422. case FunctionFields::VirtualModifier::Impl:
  423. function_start += "impl ";
  424. break;
  425. case FunctionFields::VirtualModifier::None:
  426. break;
  427. }
  428. if (fn.is_extern) {
  429. function_start += "extern ";
  430. }
  431. function_start += "fn";
  432. FormatEntityStart(function_start, fn, id);
  433. llvm::SaveAndRestore function_scope(scope_, inst_namer_.GetScopeFor(id));
  434. auto return_type_info = ReturnTypeInfo::ForFunction(*sem_ir_, fn);
  435. FormatParamList(fn.call_params_id, return_type_info.is_valid() &&
  436. return_type_info.has_return_slot());
  437. if (fn.builtin_function_kind() != BuiltinFunctionKind::None) {
  438. out_ << " = \""
  439. << FormatEscaped(fn.builtin_function_kind().name(),
  440. /*use_hex_escapes=*/true)
  441. << "\"";
  442. }
  443. if (fn.thunk_decl_id().has_value()) {
  444. out_ << " [thunk ";
  445. FormatArg(fn.thunk_decl_id());
  446. out_ << "]";
  447. }
  448. if (!fn.body_block_ids.empty()) {
  449. out_ << ' ';
  450. OpenBrace();
  451. for (auto block_id : fn.body_block_ids) {
  452. IndentLabel();
  453. FormatLabel(block_id);
  454. out_ << ":\n";
  455. FormatCodeBlock(block_id);
  456. }
  457. CloseBrace();
  458. } else {
  459. Semicolon();
  460. }
  461. out_ << '\n';
  462. FormatEntityEnd(fn.generic_id);
  463. }
  464. auto Formatter::FormatSpecificRegion(const Generic& generic,
  465. const Specific& specific,
  466. GenericInstIndex::Region region,
  467. llvm::StringRef region_name) -> void {
  468. if (!specific.GetValueBlock(region).has_value()) {
  469. return;
  470. }
  471. if (!region_name.empty()) {
  472. IndentLabel();
  473. out_ << "!" << region_name << ":\n";
  474. }
  475. for (auto [generic_inst_id, specific_inst_id] : llvm::zip_longest(
  476. sem_ir_->inst_blocks().GetOrEmpty(generic.GetEvalBlock(region)),
  477. sem_ir_->inst_blocks().GetOrEmpty(specific.GetValueBlock(region)))) {
  478. Indent();
  479. if (generic_inst_id) {
  480. FormatName(*generic_inst_id);
  481. } else {
  482. out_ << "<missing>";
  483. }
  484. out_ << " => ";
  485. if (specific_inst_id) {
  486. FormatName(*specific_inst_id);
  487. } else {
  488. out_ << "<missing>";
  489. }
  490. out_ << "\n";
  491. }
  492. }
  493. auto Formatter::FormatSpecific(SpecificId id) -> void {
  494. const auto& specific = sem_ir_->specifics().Get(id);
  495. const auto& generic = sem_ir_->generics().Get(specific.generic_id);
  496. if (!ShouldFormatEntity(generic.decl_id)) {
  497. // Omit specifics if we also omitted the generic.
  498. return;
  499. }
  500. if (specific.IsUnresolved()) {
  501. // Omit specifics that were never resolved. Such specifics exist only to
  502. // track the way the arguments were spelled, and that information is
  503. // conveyed entirely by the name of the specific. These specifics may also
  504. // not be referenced by any SemIR that we format, so including them adds
  505. // clutter and possibly emits references to instructions we didn't name.
  506. return;
  507. }
  508. llvm::SaveAndRestore generic_scope(
  509. scope_, inst_namer_.GetScopeFor(specific.generic_id));
  510. out_ << "\n";
  511. out_ << "specific ";
  512. FormatName(id);
  513. out_ << " ";
  514. OpenBrace();
  515. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Declaration,
  516. "");
  517. FormatSpecificRegion(generic, specific, GenericInstIndex::Region::Definition,
  518. "definition");
  519. CloseBrace();
  520. out_ << "\n";
  521. }
  522. auto Formatter::FormatGenericStart(llvm::StringRef entity_kind,
  523. GenericId generic_id) -> void {
  524. const auto& generic = sem_ir_->generics().Get(generic_id);
  525. out_ << "\n";
  526. Indent();
  527. out_ << "generic " << entity_kind << " ";
  528. FormatName(generic_id);
  529. llvm::SaveAndRestore generic_scope(scope_,
  530. inst_namer_.GetScopeFor(generic_id));
  531. FormatParamList(generic.bindings_id);
  532. out_ << " ";
  533. OpenBrace();
  534. FormatCodeBlock(generic.decl_block_id);
  535. if (generic.definition_block_id.has_value()) {
  536. IndentLabel();
  537. out_ << "!definition:\n";
  538. FormatCodeBlock(generic.definition_block_id);
  539. }
  540. }
  541. auto Formatter::FormatEntityEnd(GenericId generic_id) -> void {
  542. if (generic_id.has_value()) {
  543. CloseBrace();
  544. out_ << '\n';
  545. }
  546. }
  547. auto Formatter::FormatParamList(InstBlockId params_id, bool has_return_slot)
  548. -> void {
  549. if (!params_id.has_value()) {
  550. // TODO: This happens for imported functions, for which we don't currently
  551. // import the call parameters list.
  552. return;
  553. }
  554. llvm::StringLiteral close = ")";
  555. out_ << "(";
  556. llvm::ListSeparator sep;
  557. for (InstId param_id : sem_ir_->inst_blocks().Get(params_id)) {
  558. auto is_out_param = sem_ir_->insts().Is<OutParam>(param_id);
  559. if (is_out_param) {
  560. // TODO: An input parameter following an output parameter is formatted a
  561. // bit strangely. For example, alternating input and output parameters
  562. // produces:
  563. //
  564. // fn @F(%in1: %t) -> %out1: %t, %in2: %t -> %out2: %t
  565. //
  566. // This doesn't actually happen right now, though.
  567. out_ << std::exchange(close, llvm::StringLiteral(""));
  568. out_ << " -> ";
  569. } else {
  570. out_ << sep;
  571. }
  572. if (!param_id.has_value()) {
  573. out_ << "invalid";
  574. continue;
  575. }
  576. // Don't include the name of the return slot parameter if the function
  577. // doesn't have a return slot; the name won't be used for anything in that
  578. // case.
  579. // TODO: Should the call parameter even exist in that case? There isn't a
  580. // corresponding argument in a `call` instruction.
  581. if (!is_out_param || has_return_slot) {
  582. FormatName(param_id);
  583. out_ << ": ";
  584. }
  585. FormatTypeOfInst(param_id);
  586. }
  587. out_ << close;
  588. }
  589. auto Formatter::FormatCodeBlock(InstBlockId block_id) -> void {
  590. bool elided = false;
  591. for (const InstId inst_id : sem_ir_->inst_blocks().GetOrEmpty(block_id)) {
  592. if (ShouldFormatInst(inst_id)) {
  593. FormatInst(inst_id);
  594. elided = false;
  595. } else if (!elided) {
  596. // When formatting a block, leave a hint that instructions were elided.
  597. Indent();
  598. out_ << "<elided>\n";
  599. elided = true;
  600. }
  601. }
  602. }
  603. auto Formatter::FormatTrailingBlock(InstBlockId block_id) -> void {
  604. out_ << ' ';
  605. OpenBrace();
  606. FormatCodeBlock(block_id);
  607. CloseBrace();
  608. }
  609. auto Formatter::FormatNameScope(NameScopeId id, llvm::StringRef label) -> void {
  610. const auto& scope = sem_ir_->name_scopes().Get(id);
  611. if (scope.entries().empty() && scope.extended_scopes().empty() &&
  612. scope.import_ir_scopes().empty() && !scope.is_cpp_scope() &&
  613. !scope.has_error()) {
  614. // Name scope is empty.
  615. return;
  616. }
  617. if (!label.empty()) {
  618. IndentLabel();
  619. out_ << label;
  620. }
  621. for (auto [name_id, result] : scope.entries()) {
  622. Indent();
  623. out_ << ".";
  624. FormatName(name_id);
  625. switch (result.access_kind()) {
  626. case AccessKind::Public:
  627. break;
  628. case AccessKind::Protected:
  629. out_ << " [protected]";
  630. break;
  631. case AccessKind::Private:
  632. out_ << " [private]";
  633. break;
  634. }
  635. out_ << " = ";
  636. if (result.is_poisoned()) {
  637. out_ << "<poisoned>";
  638. } else {
  639. FormatName(result.is_found() ? result.target_inst_id() : InstId::None);
  640. }
  641. out_ << "\n";
  642. }
  643. for (auto extended_scope_id : scope.extended_scopes()) {
  644. Indent();
  645. out_ << "extend ";
  646. FormatName(extended_scope_id);
  647. out_ << "\n";
  648. }
  649. // This is used to cluster all "Core//prelude/..." imports, but not
  650. // "Core//prelude" itself. This avoids unrelated churn in test files when we
  651. // add or remove an unused prelude file, but is intended to still show the
  652. // existence of indirect imports.
  653. bool has_prelude_components = false;
  654. for (auto [import_ir_id, unused] : scope.import_ir_scopes()) {
  655. auto label = GetImportIRLabel(import_ir_id);
  656. if (label.starts_with("Core//prelude/")) {
  657. if (has_prelude_components) {
  658. // Only print the existence once.
  659. continue;
  660. } else {
  661. has_prelude_components = true;
  662. label = "Core//prelude/...";
  663. }
  664. }
  665. Indent();
  666. out_ << "import " << label << "\n";
  667. }
  668. if (scope.is_cpp_scope()) {
  669. Indent();
  670. out_ << "import Cpp//...\n";
  671. }
  672. if (scope.has_error()) {
  673. Indent();
  674. out_ << "has_error\n";
  675. }
  676. }
  677. auto Formatter::FormatInst(InstId inst_id) -> void {
  678. if (!inst_id.has_value()) {
  679. Indent();
  680. out_ << "none\n";
  681. return;
  682. }
  683. if (!in_terminator_sequence_) {
  684. Indent();
  685. }
  686. auto inst = sem_ir_->insts().GetWithAttachedType(inst_id);
  687. CARBON_KIND_SWITCH(inst) {
  688. case CARBON_KIND(Branch branch): {
  689. out_ << Branch::Kind.ir_name() << " ";
  690. FormatLabel(branch.target_id);
  691. out_ << "\n";
  692. in_terminator_sequence_ = false;
  693. return;
  694. }
  695. case CARBON_KIND(BranchIf branch_if): {
  696. out_ << "if ";
  697. FormatName(branch_if.cond_id);
  698. out_ << " " << Branch::Kind.ir_name() << " ";
  699. FormatLabel(branch_if.target_id);
  700. out_ << " else ";
  701. in_terminator_sequence_ = true;
  702. return;
  703. }
  704. case CARBON_KIND(BranchWithArg branch_with_arg): {
  705. out_ << BranchWithArg::Kind.ir_name() << " ";
  706. FormatLabel(branch_with_arg.target_id);
  707. out_ << "(";
  708. FormatName(branch_with_arg.arg_id);
  709. out_ << ")\n";
  710. in_terminator_sequence_ = false;
  711. return;
  712. }
  713. default: {
  714. FormatInstLhs(inst_id, inst);
  715. out_ << inst.kind().ir_name();
  716. // Add constants for everything except `ImportRefUnloaded`.
  717. if (!inst.Is<ImportRefUnloaded>()) {
  718. pending_constant_value_ =
  719. sem_ir_->constant_values().GetAttached(inst_id);
  720. pending_constant_value_is_self_ =
  721. sem_ir_->constant_values().GetInstIdIfValid(
  722. pending_constant_value_) == inst_id;
  723. }
  724. FormatInstRhs(inst);
  725. // This usually prints the constant, but when `FormatInstRhs` prints it
  726. // first (or for `ImportRefUnloaded`), this does nothing.
  727. FormatPendingConstantValue(AddSpace::Before);
  728. out_ << "\n";
  729. return;
  730. }
  731. }
  732. }
  733. auto Formatter::FormatPendingImportedFrom(AddSpace space_where) -> void {
  734. if (pending_imported_from_.empty()) {
  735. return;
  736. }
  737. if (space_where == AddSpace::Before) {
  738. out_ << ' ';
  739. }
  740. out_ << "[from \"" << FormatEscaped(pending_imported_from_) << "\"]";
  741. if (space_where == AddSpace::After) {
  742. out_ << ' ';
  743. }
  744. pending_imported_from_ = llvm::StringRef();
  745. }
  746. auto Formatter::FormatPendingConstantValue(AddSpace space_where) -> void {
  747. if (pending_constant_value_ == ConstantId::NotConstant) {
  748. return;
  749. }
  750. if (space_where == AddSpace::Before) {
  751. out_ << ' ';
  752. }
  753. out_ << '[';
  754. if (pending_constant_value_.has_value()) {
  755. switch (sem_ir_->constant_values().GetDependence(pending_constant_value_)) {
  756. case ConstantDependence::None:
  757. out_ << "concrete";
  758. break;
  759. case ConstantDependence::PeriodSelf:
  760. out_ << "symbolic_self";
  761. break;
  762. // TODO: Consider renaming this. This will cause a lot of SemIR churn.
  763. case ConstantDependence::Checked:
  764. out_ << "symbolic";
  765. break;
  766. case ConstantDependence::Template:
  767. out_ << "template";
  768. break;
  769. }
  770. if (!pending_constant_value_is_self_) {
  771. out_ << " = ";
  772. FormatConstant(pending_constant_value_);
  773. }
  774. } else {
  775. out_ << pending_constant_value_;
  776. }
  777. out_ << ']';
  778. if (space_where == AddSpace::After) {
  779. out_ << ' ';
  780. }
  781. pending_constant_value_ = ConstantId::NotConstant;
  782. }
  783. auto Formatter::FormatInstLhs(InstId inst_id, Inst inst) -> void {
  784. // Every typed instruction is named, and there are some untyped instructions
  785. // that have names (such as `ImportRefUnloaded`). When there's a typed
  786. // instruction with no name, it means an instruction is incorrectly not named
  787. // -- but should be printed as such.
  788. bool has_name = inst_namer_.has_name(inst_id);
  789. if (!has_name && !inst.kind().has_type()) {
  790. return;
  791. }
  792. FormatName(inst_id);
  793. if (inst.kind().has_type()) {
  794. out_ << ": ";
  795. switch (GetExprCategory(*sem_ir_, inst_id)) {
  796. case ExprCategory::NotExpr:
  797. case ExprCategory::Error:
  798. case ExprCategory::Value:
  799. case ExprCategory::Mixed:
  800. break;
  801. case ExprCategory::DurableRef:
  802. case ExprCategory::EphemeralRef:
  803. out_ << "ref ";
  804. break;
  805. case ExprCategory::Initializing:
  806. out_ << "init ";
  807. break;
  808. }
  809. FormatTypeOfInst(inst_id);
  810. }
  811. out_ << " = ";
  812. }
  813. auto Formatter::FormatInstArgAndKind(Inst::ArgAndKind arg_and_kind) -> void {
  814. GetFormatArgFn(arg_and_kind.kind())(*this, arg_and_kind.value());
  815. }
  816. auto Formatter::FormatInstRhs(Inst inst) -> void {
  817. CARBON_KIND_SWITCH(inst) {
  818. case SemIR::InstKind::ArrayInit:
  819. case SemIR::InstKind::StructInit:
  820. case SemIR::InstKind::TupleInit: {
  821. auto init = inst.As<AnyAggregateInit>();
  822. FormatArgs(init.elements_id);
  823. FormatReturnSlotArg(init.dest_id);
  824. return;
  825. }
  826. case SemIR::InstKind::ImportRefLoaded:
  827. case SemIR::InstKind::ImportRefUnloaded:
  828. FormatImportRefRhs(inst.As<AnyImportRef>());
  829. return;
  830. case SemIR::InstKind::OutParam:
  831. case SemIR::InstKind::RefParam:
  832. case SemIR::InstKind::ValueParam: {
  833. auto param = inst.As<AnyParam>();
  834. FormatArgs(param.index);
  835. // Omit pretty_name because it's an implementation detail of
  836. // pretty-printing.
  837. return;
  838. }
  839. case CARBON_KIND(AssociatedConstantDecl decl): {
  840. FormatArgs(decl.assoc_const_id);
  841. llvm::SaveAndRestore scope(scope_,
  842. inst_namer_.GetScopeFor(decl.assoc_const_id));
  843. FormatTrailingBlock(decl.decl_block_id);
  844. return;
  845. }
  846. case CARBON_KIND(BindSymbolicName bind): {
  847. // A BindSymbolicName with no value is a purely symbolic binding, such as
  848. // the `Self` in an interface. Don't print out `none` for the value.
  849. if (bind.value_id.has_value()) {
  850. FormatArgs(bind.entity_name_id, bind.value_id);
  851. } else {
  852. FormatArgs(bind.entity_name_id);
  853. }
  854. return;
  855. }
  856. case CARBON_KIND(BlockArg block): {
  857. out_ << " ";
  858. FormatLabel(block.block_id);
  859. return;
  860. }
  861. case CARBON_KIND(Call call): {
  862. FormatCallRhs(call);
  863. return;
  864. }
  865. case CARBON_KIND(ClassDecl decl): {
  866. FormatDeclRhs(decl.class_id,
  867. sem_ir_->classes().Get(decl.class_id).pattern_block_id,
  868. decl.decl_block_id);
  869. return;
  870. }
  871. case CARBON_KIND(CustomLayoutType type): {
  872. out_ << " {";
  873. auto layout = sem_ir_->custom_layouts().Get(type.layout_id);
  874. out_ << "size=" << layout[CustomLayoutId::SizeIndex]
  875. << ", align=" << layout[CustomLayoutId::AlignIndex];
  876. for (auto [field, offset] :
  877. llvm::zip(sem_ir_->struct_type_fields().Get(type.fields_id),
  878. layout.drop_front(CustomLayoutId::FirstFieldIndex))) {
  879. out_ << ", .";
  880. FormatName(field.name_id);
  881. out_ << "@" << offset << ": ";
  882. FormatInstAsType(field.type_inst_id);
  883. }
  884. out_ << "}";
  885. return;
  886. }
  887. case CARBON_KIND(FloatValue value): {
  888. llvm::SmallVector<char, 16> buffer;
  889. sem_ir_->floats().Get(value.float_id).toString(buffer);
  890. out_ << " " << buffer;
  891. return;
  892. }
  893. case CARBON_KIND(FunctionDecl decl): {
  894. FormatDeclRhs(decl.function_id,
  895. sem_ir_->functions().Get(decl.function_id).pattern_block_id,
  896. decl.decl_block_id);
  897. return;
  898. }
  899. case InstKind::ImportCppDecl: {
  900. FormatImportCppDeclRhs();
  901. return;
  902. }
  903. case CARBON_KIND(ImplDecl decl): {
  904. FormatDeclRhs(decl.impl_id,
  905. sem_ir_->impls().Get(decl.impl_id).pattern_block_id,
  906. decl.decl_block_id);
  907. return;
  908. }
  909. case CARBON_KIND(InitializeFrom init): {
  910. FormatArgs(init.src_id);
  911. FormatReturnSlotArg(init.dest_id);
  912. return;
  913. }
  914. case CARBON_KIND(InstValue inst): {
  915. out_ << ' ';
  916. OpenBrace();
  917. // TODO: Should we use a more compact representation in the case where the
  918. // inst is a SpliceBlock?
  919. FormatInst(inst.inst_id);
  920. CloseBrace();
  921. return;
  922. }
  923. case CARBON_KIND(InterfaceDecl decl): {
  924. FormatDeclRhs(
  925. decl.interface_id,
  926. sem_ir_->interfaces().Get(decl.interface_id).pattern_block_id,
  927. decl.decl_block_id);
  928. return;
  929. }
  930. case CARBON_KIND(IntValue value): {
  931. out_ << " ";
  932. sem_ir_->ints()
  933. .Get(value.int_id)
  934. .print(out_, sem_ir_->types().IsSignedInt(value.type_id));
  935. return;
  936. }
  937. case CARBON_KIND(NameBindingDecl name): {
  938. FormatTrailingBlock(name.pattern_block_id);
  939. return;
  940. }
  941. case CARBON_KIND(Namespace ns): {
  942. if (ns.import_id.has_value()) {
  943. FormatArgs(ns.import_id, ns.name_scope_id);
  944. } else {
  945. FormatArgs(ns.name_scope_id);
  946. }
  947. return;
  948. }
  949. case CARBON_KIND(ReturnExpr ret): {
  950. FormatArgs(ret.expr_id);
  951. if (ret.dest_id.has_value()) {
  952. FormatReturnSlotArg(ret.dest_id);
  953. }
  954. return;
  955. }
  956. case CARBON_KIND(ReturnSlot ret): {
  957. // Omit inst.type_inst_id because it's not semantically significant.
  958. FormatArgs(ret.storage_id);
  959. return;
  960. }
  961. case InstKind::ReturnSlotPattern:
  962. // No-op because type_id is the only semantically significant field,
  963. // and it's handled separately.
  964. return;
  965. case CARBON_KIND(SpliceBlock splice): {
  966. FormatArgs(splice.result_id);
  967. FormatTrailingBlock(splice.block_id);
  968. return;
  969. }
  970. case CARBON_KIND(StructType struct_type): {
  971. out_ << " {";
  972. llvm::ListSeparator sep;
  973. for (auto field :
  974. sem_ir_->struct_type_fields().Get(struct_type.fields_id)) {
  975. out_ << sep << ".";
  976. FormatName(field.name_id);
  977. out_ << ": ";
  978. FormatInstAsType(field.type_inst_id);
  979. }
  980. out_ << "}";
  981. return;
  982. }
  983. case CARBON_KIND(WhereExpr where): {
  984. FormatArgs(where.period_self_id);
  985. FormatTrailingBlock(where.requirements_id);
  986. return;
  987. }
  988. default:
  989. FormatInstRhsDefault(inst);
  990. return;
  991. }
  992. }
  993. auto Formatter::FormatInstRhsDefault(Inst inst) -> void {
  994. auto arg0 = inst.arg0_and_kind();
  995. if (arg0.kind() == IdKind::None) {
  996. return;
  997. }
  998. out_ << " ";
  999. FormatInstArgAndKind(arg0);
  1000. auto arg1 = inst.arg1_and_kind();
  1001. if (arg1.kind() == IdKind::None) {
  1002. return;
  1003. }
  1004. // Several instructions have a second operand that's a specific ID. We
  1005. // don't include it in the argument list if there is no corresponding
  1006. // specific, that is, when we're not in a generic context.
  1007. if (auto arg1_specific_id = arg1.TryAs<SpecificId>();
  1008. arg1_specific_id && !arg1_specific_id->has_value()) {
  1009. return;
  1010. }
  1011. out_ << ", ";
  1012. FormatInstArgAndKind(arg1);
  1013. }
  1014. auto Formatter::FormatCallRhs(Call inst) -> void {
  1015. out_ << " ";
  1016. FormatArg(inst.callee_id);
  1017. if (!inst.args_id.has_value()) {
  1018. out_ << "(<none>)";
  1019. return;
  1020. }
  1021. llvm::ArrayRef<InstId> args = sem_ir_->inst_blocks().Get(inst.args_id);
  1022. auto return_info = ReturnTypeInfo::ForType(*sem_ir_, inst.type_id);
  1023. if (!return_info.is_valid()) {
  1024. out_ << "(<invalid return info>)";
  1025. return;
  1026. }
  1027. bool has_return_slot = return_info.has_return_slot();
  1028. InstId return_slot_arg_id = InstId::None;
  1029. if (has_return_slot) {
  1030. return_slot_arg_id = args.consume_back();
  1031. }
  1032. llvm::ListSeparator sep;
  1033. out_ << '(';
  1034. for (auto inst_id : args) {
  1035. out_ << sep;
  1036. FormatArg(inst_id);
  1037. }
  1038. out_ << ')';
  1039. if (has_return_slot) {
  1040. FormatReturnSlotArg(return_slot_arg_id);
  1041. }
  1042. }
  1043. auto Formatter::FormatImportCppDeclRhs() -> void {
  1044. out_ << " ";
  1045. OpenBrace();
  1046. for (ImportCpp import_cpp : sem_ir_->import_cpps().values()) {
  1047. Indent();
  1048. out_ << "import Cpp ";
  1049. if (import_cpp.library_id.has_value()) {
  1050. out_ << "\""
  1051. << FormatEscaped(
  1052. sem_ir_->string_literal_values().Get(import_cpp.library_id))
  1053. << "\"";
  1054. } else {
  1055. out_ << "inline";
  1056. }
  1057. out_ << "\n";
  1058. }
  1059. CloseBrace();
  1060. }
  1061. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1062. out_ << " ";
  1063. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1064. FormatArg(import_ir_inst.ir_id());
  1065. out_ << ", ";
  1066. if (inst.entity_name_id.has_value()) {
  1067. // Prefer to show the entity name when possible.
  1068. FormatArg(inst.entity_name_id);
  1069. } else {
  1070. // Show a name based on the location when possible, or the numeric
  1071. // instruction as a last resort.
  1072. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1073. auto loc_id =
  1074. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1075. switch (loc_id.kind()) {
  1076. case LocId::Kind::None: {
  1077. out_ << import_ir_inst.inst_id() << " [no loc]";
  1078. break;
  1079. }
  1080. case LocId::Kind::ImportIRInstId: {
  1081. // TODO: Probably don't want to format each indirection, but maybe
  1082. // reuse GetCanonicalImportIRInst?
  1083. out_ << import_ir_inst.inst_id() << " [indirect]";
  1084. break;
  1085. }
  1086. case LocId::Kind::NodeId: {
  1087. // Formats a NodeId from the import.
  1088. const auto& tree = import_ir.sem_ir->parse_tree();
  1089. auto token = tree.node_token(loc_id.node_id());
  1090. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1091. << tree.tokens().GetColumnNumber(token);
  1092. break;
  1093. }
  1094. case LocId::Kind::InstId:
  1095. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1096. }
  1097. }
  1098. out_ << ", "
  1099. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1100. }
  1101. auto Formatter::FormatArg(EntityNameId id) -> void {
  1102. if (!id.has_value()) {
  1103. out_ << "_";
  1104. return;
  1105. }
  1106. const auto& info = sem_ir_->entity_names().Get(id);
  1107. FormatName(info.name_id);
  1108. if (info.bind_index().has_value()) {
  1109. out_ << ", " << info.bind_index().index;
  1110. }
  1111. if (info.is_template) {
  1112. out_ << ", template";
  1113. }
  1114. }
  1115. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1116. const auto& info = sem_ir_->facet_types().Get(id);
  1117. // Nothing output to indicate that this is a facet type since this is only
  1118. // used as the argument to a `facet_type` instruction.
  1119. out_ << "<";
  1120. llvm::ListSeparator sep(" & ");
  1121. if (info.extend_constraints.empty()) {
  1122. out_ << "type";
  1123. } else {
  1124. for (auto interface : info.extend_constraints) {
  1125. out_ << sep;
  1126. FormatName(interface.interface_id);
  1127. if (interface.specific_id.has_value()) {
  1128. out_ << ", ";
  1129. FormatName(interface.specific_id);
  1130. }
  1131. }
  1132. }
  1133. if (info.other_requirements || !info.self_impls_constraints.empty() ||
  1134. !info.rewrite_constraints.empty()) {
  1135. out_ << " where ";
  1136. llvm::ListSeparator and_sep(" and ");
  1137. if (!info.self_impls_constraints.empty()) {
  1138. out_ << and_sep << ".Self impls ";
  1139. llvm::ListSeparator amp_sep(" & ");
  1140. for (auto interface : info.self_impls_constraints) {
  1141. out_ << amp_sep;
  1142. FormatName(interface.interface_id);
  1143. if (interface.specific_id.has_value()) {
  1144. out_ << ", ";
  1145. FormatName(interface.specific_id);
  1146. }
  1147. }
  1148. }
  1149. for (auto rewrite : info.rewrite_constraints) {
  1150. out_ << and_sep;
  1151. FormatArg(rewrite.lhs_id);
  1152. out_ << " = ";
  1153. FormatArg(rewrite.rhs_id);
  1154. }
  1155. if (info.other_requirements) {
  1156. out_ << and_sep << "TODO";
  1157. }
  1158. }
  1159. out_ << ">";
  1160. }
  1161. auto Formatter::FormatArg(ImportIRId id) -> void {
  1162. if (id.has_value()) {
  1163. out_ << GetImportIRLabel(id);
  1164. } else {
  1165. out_ << id;
  1166. }
  1167. }
  1168. auto Formatter::FormatArg(IntId id) -> void {
  1169. // We don't know the signedness to use here. Default to unsigned.
  1170. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1171. }
  1172. auto Formatter::FormatArg(NameScopeId id) -> void {
  1173. OpenBrace();
  1174. FormatNameScope(id);
  1175. CloseBrace();
  1176. }
  1177. auto Formatter::FormatArg(InstBlockId id) -> void {
  1178. if (!id.has_value()) {
  1179. out_ << "invalid";
  1180. return;
  1181. }
  1182. out_ << '(';
  1183. llvm::ListSeparator sep;
  1184. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1185. out_ << sep;
  1186. FormatArg(inst_id);
  1187. }
  1188. out_ << ')';
  1189. }
  1190. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1191. FormatArg(static_cast<InstBlockId>(id));
  1192. }
  1193. auto Formatter::FormatArg(RealId id) -> void {
  1194. // TODO: Format with a `.` when the exponent is near zero.
  1195. const auto& real = sem_ir_->reals().Get(id);
  1196. real.mantissa.print(out_, /*isSigned=*/false);
  1197. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1198. }
  1199. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1200. out_ << '"'
  1201. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1202. /*use_hex_escapes=*/true)
  1203. << '"';
  1204. }
  1205. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1206. out_ << " to ";
  1207. FormatArg(dest_id);
  1208. }
  1209. auto Formatter::FormatName(NameId id) -> void {
  1210. out_ << sem_ir_->names().GetFormatted(id);
  1211. }
  1212. auto Formatter::FormatName(InstId id) -> void {
  1213. if (id.has_value()) {
  1214. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1215. }
  1216. out_ << inst_namer_.GetNameFor(scope_, id);
  1217. }
  1218. auto Formatter::FormatName(SpecificId id) -> void {
  1219. const auto& specific = sem_ir_->specifics().Get(id);
  1220. FormatName(specific.generic_id);
  1221. FormatArg(specific.args_id);
  1222. }
  1223. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1224. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1225. FormatName(interface.interface_id);
  1226. if (interface.specific_id.has_value()) {
  1227. out_ << ", ";
  1228. FormatArg(interface.specific_id);
  1229. }
  1230. }
  1231. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1232. out_ << inst_namer_.GetLabelFor(scope_, id);
  1233. }
  1234. auto Formatter::FormatConstant(ConstantId id) -> void {
  1235. if (!id.has_value()) {
  1236. out_ << "<not constant>";
  1237. return;
  1238. }
  1239. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1240. FormatName(inst_id);
  1241. // For an attached constant, also list the unattached constant.
  1242. if (id.is_symbolic() && sem_ir_->constant_values()
  1243. .GetSymbolicConstant(id)
  1244. .generic_id.has_value()) {
  1245. // TODO: Skip printing this if it's the same as `inst_id`.
  1246. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1247. out_ << " (";
  1248. FormatName(unattached_inst_id);
  1249. out_ << ")";
  1250. }
  1251. }
  1252. auto Formatter::FormatInstAsType(InstId id) -> void {
  1253. if (!id.has_value()) {
  1254. out_ << "invalid";
  1255. return;
  1256. }
  1257. // Types are formatted in the `constants` scope because they typically refer
  1258. // to constants.
  1259. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1260. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1261. const_id.has_value()) {
  1262. FormatConstant(const_id);
  1263. } else {
  1264. // Type instruction didn't have a constant value. Fall back to printing
  1265. // the instruction name.
  1266. FormatArg(id);
  1267. }
  1268. }
  1269. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1270. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1271. if (!type_id.has_value()) {
  1272. out_ << "invalid";
  1273. return;
  1274. }
  1275. // Types are formatted in the `constants` scope because they typically refer
  1276. // to constants.
  1277. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1278. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1279. }
  1280. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1281. CARBON_CHECK(id.has_value(),
  1282. "Callers are responsible for checking `id.has_value`");
  1283. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1284. CARBON_CHECK(import_ir.library_id().has_value());
  1285. auto package_id = import_ir.package_id();
  1286. llvm::StringRef package_name =
  1287. package_id.AsIdentifierId().has_value()
  1288. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1289. : package_id.AsSpecialName();
  1290. llvm::StringRef library_name =
  1291. (import_ir.library_id() != LibraryNameId::Default)
  1292. ? import_ir.string_literal_values().Get(
  1293. import_ir.library_id().AsStringLiteralValueId())
  1294. : "default";
  1295. return llvm::formatv("{0}//{1}", package_name, library_name);
  1296. }
  1297. } // namespace Carbon::SemIR
  1298. // NOLINTEND(misc-no-recursion)