formatter.cpp 44 KB

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