formatter.cpp 48 KB

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