formatter.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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(BindSymbolicName bind): {
  873. // A BindSymbolicName 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 (ImportCpp import_cpp : sem_ir_->import_cpps().values()) {
  1081. Indent();
  1082. out_ << "import Cpp ";
  1083. if (import_cpp.library_id.has_value()) {
  1084. out_ << "\""
  1085. << FormatEscaped(
  1086. sem_ir_->string_literal_values().Get(import_cpp.library_id))
  1087. << "\"";
  1088. } else {
  1089. out_ << "inline";
  1090. }
  1091. out_ << "\n";
  1092. }
  1093. CloseBrace();
  1094. }
  1095. auto Formatter::FormatImportRefRhs(AnyImportRef inst) -> void {
  1096. out_ << " ";
  1097. auto import_ir_inst = sem_ir_->import_ir_insts().Get(inst.import_ir_inst_id);
  1098. FormatArg(import_ir_inst.ir_id());
  1099. out_ << ", ";
  1100. if (inst.entity_name_id.has_value()) {
  1101. // Prefer to show the entity name when possible.
  1102. FormatArg(inst.entity_name_id);
  1103. } else {
  1104. // Show a name based on the location when possible, or the numeric
  1105. // instruction as a last resort.
  1106. const auto& import_ir = sem_ir_->import_irs().Get(import_ir_inst.ir_id());
  1107. auto loc_id =
  1108. import_ir.sem_ir->insts().GetCanonicalLocId(import_ir_inst.inst_id());
  1109. switch (loc_id.kind()) {
  1110. case LocId::Kind::None: {
  1111. out_ << import_ir_inst.inst_id() << " [no loc]";
  1112. break;
  1113. }
  1114. case LocId::Kind::ImportIRInstId: {
  1115. // TODO: Probably don't want to format each indirection, but maybe
  1116. // reuse GetCanonicalImportIRInst?
  1117. out_ << import_ir_inst.inst_id() << " [indirect]";
  1118. break;
  1119. }
  1120. case LocId::Kind::NodeId: {
  1121. // Formats a NodeId from the import.
  1122. const auto& tree = import_ir.sem_ir->parse_tree();
  1123. auto token = tree.node_token(loc_id.node_id());
  1124. out_ << "loc" << tree.tokens().GetLineNumber(token) << "_"
  1125. << tree.tokens().GetColumnNumber(token);
  1126. break;
  1127. }
  1128. case LocId::Kind::InstId:
  1129. CARBON_FATAL("Unexpected LocId: {0}", loc_id);
  1130. }
  1131. }
  1132. out_ << ", "
  1133. << (inst.kind == InstKind::ImportRefLoaded ? "loaded" : "unloaded");
  1134. }
  1135. auto Formatter::FormatArg(EntityNameId id) -> void {
  1136. if (!id.has_value()) {
  1137. out_ << "_";
  1138. return;
  1139. }
  1140. const auto& info = sem_ir_->entity_names().Get(id);
  1141. FormatName(info.name_id);
  1142. if (info.bind_index().has_value()) {
  1143. out_ << ", " << info.bind_index().index;
  1144. }
  1145. if (info.is_template) {
  1146. out_ << ", template";
  1147. }
  1148. }
  1149. auto Formatter::FormatArg(FacetTypeId id) -> void {
  1150. const auto& info = sem_ir_->facet_types().Get(id);
  1151. // Nothing output to indicate that this is a facet type since this is only
  1152. // used as the argument to a `facet_type` instruction.
  1153. out_ << "<";
  1154. llvm::ListSeparator sep(" & ");
  1155. if (info.extend_constraints.empty()) {
  1156. out_ << "type";
  1157. } else {
  1158. for (auto interface : info.extend_constraints) {
  1159. out_ << sep;
  1160. FormatName(interface.interface_id);
  1161. if (interface.specific_id.has_value()) {
  1162. out_ << ", ";
  1163. FormatName(interface.specific_id);
  1164. }
  1165. }
  1166. }
  1167. if (info.other_requirements || !info.builtin_constraint_mask.empty() ||
  1168. !info.self_impls_constraints.empty() ||
  1169. !info.rewrite_constraints.empty()) {
  1170. out_ << " where ";
  1171. llvm::ListSeparator and_sep(" and ");
  1172. if (!info.self_impls_constraints.empty()) {
  1173. out_ << and_sep << ".Self impls ";
  1174. llvm::ListSeparator amp_sep(" & ");
  1175. for (auto interface : info.self_impls_constraints) {
  1176. out_ << amp_sep;
  1177. FormatName(interface.interface_id);
  1178. if (interface.specific_id.has_value()) {
  1179. out_ << ", ";
  1180. FormatName(interface.specific_id);
  1181. }
  1182. }
  1183. }
  1184. for (auto rewrite : info.rewrite_constraints) {
  1185. out_ << and_sep;
  1186. FormatArg(rewrite.lhs_id);
  1187. out_ << " = ";
  1188. FormatArg(rewrite.rhs_id);
  1189. }
  1190. if (info.builtin_constraint_mask.HasAnyOf(
  1191. BuiltinConstraintMask::TypeCanDestroy)) {
  1192. out_ << and_sep << ".Self impls <CanDestroy>";
  1193. }
  1194. if (info.other_requirements) {
  1195. out_ << and_sep << "TODO";
  1196. }
  1197. }
  1198. out_ << ">";
  1199. }
  1200. auto Formatter::FormatArg(ImportIRId id) -> void {
  1201. if (id.has_value()) {
  1202. out_ << GetImportIRLabel(id);
  1203. } else {
  1204. out_ << id;
  1205. }
  1206. }
  1207. auto Formatter::FormatArg(IntId id) -> void {
  1208. // We don't know the signedness to use here. Default to unsigned.
  1209. sem_ir_->ints().Get(id).print(out_, /*isSigned=*/false);
  1210. }
  1211. auto Formatter::FormatArg(NameScopeId id) -> void {
  1212. OpenBrace();
  1213. FormatNameScope(id);
  1214. CloseBrace();
  1215. }
  1216. auto Formatter::FormatArg(InstBlockId id) -> void {
  1217. if (!id.has_value()) {
  1218. out_ << "invalid";
  1219. return;
  1220. }
  1221. out_ << '(';
  1222. llvm::ListSeparator sep;
  1223. for (auto inst_id : sem_ir_->inst_blocks().Get(id)) {
  1224. out_ << sep;
  1225. FormatArg(inst_id);
  1226. }
  1227. out_ << ')';
  1228. }
  1229. auto Formatter::FormatArg(AbsoluteInstBlockId id) -> void {
  1230. FormatArg(static_cast<InstBlockId>(id));
  1231. }
  1232. auto Formatter::FormatArg(RealId id) -> void {
  1233. // TODO: Format with a `.` when the exponent is near zero.
  1234. const auto& real = sem_ir_->reals().Get(id);
  1235. real.mantissa.print(out_, /*isSigned=*/false);
  1236. out_ << (real.is_decimal ? 'e' : 'p') << real.exponent;
  1237. }
  1238. auto Formatter::FormatArg(StringLiteralValueId id) -> void {
  1239. out_ << '"'
  1240. << FormatEscaped(sem_ir_->string_literal_values().Get(id),
  1241. /*use_hex_escapes=*/true)
  1242. << '"';
  1243. }
  1244. auto Formatter::FormatReturnSlotArg(InstId dest_id) -> void {
  1245. out_ << " to ";
  1246. FormatArg(dest_id);
  1247. }
  1248. auto Formatter::FormatName(NameId id) -> void {
  1249. out_ << sem_ir_->names().GetFormatted(id);
  1250. }
  1251. auto Formatter::FormatName(InstId id) -> void {
  1252. if (id.has_value()) {
  1253. IncludeChunkInOutput(tentative_inst_chunks_.Get(id));
  1254. }
  1255. out_ << inst_namer_.GetNameFor(scope_, id);
  1256. }
  1257. auto Formatter::FormatName(SpecificId id) -> void {
  1258. const auto& specific = sem_ir_->specifics().Get(id);
  1259. FormatName(specific.generic_id);
  1260. FormatArg(specific.args_id);
  1261. }
  1262. auto Formatter::FormatName(SpecificInterfaceId id) -> void {
  1263. const auto& interface = sem_ir_->specific_interfaces().Get(id);
  1264. FormatName(interface.interface_id);
  1265. if (interface.specific_id.has_value()) {
  1266. out_ << ", ";
  1267. FormatArg(interface.specific_id);
  1268. }
  1269. }
  1270. auto Formatter::FormatLabel(InstBlockId id) -> void {
  1271. out_ << inst_namer_.GetLabelFor(scope_, id);
  1272. }
  1273. auto Formatter::FormatConstant(ConstantId id) -> void {
  1274. if (!id.has_value()) {
  1275. out_ << "<not constant>";
  1276. return;
  1277. }
  1278. auto inst_id = GetInstWithConstantValue(*sem_ir_, id);
  1279. FormatName(inst_id);
  1280. // For an attached constant, also list the unattached constant.
  1281. if (id.is_symbolic() && sem_ir_->constant_values()
  1282. .GetSymbolicConstant(id)
  1283. .generic_id.has_value()) {
  1284. // TODO: Skip printing this if it's the same as `inst_id`.
  1285. auto unattached_inst_id = sem_ir_->constant_values().GetInstId(id);
  1286. out_ << " (";
  1287. FormatName(unattached_inst_id);
  1288. out_ << ")";
  1289. }
  1290. }
  1291. auto Formatter::FormatInstAsType(InstId id) -> void {
  1292. if (!id.has_value()) {
  1293. out_ << "invalid";
  1294. return;
  1295. }
  1296. // Types are formatted in the `constants` scope because they typically refer
  1297. // to constants.
  1298. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1299. if (auto const_id = sem_ir_->constant_values().GetAttached(id);
  1300. const_id.has_value()) {
  1301. FormatConstant(const_id);
  1302. } else {
  1303. // Type instruction didn't have a constant value. Fall back to printing
  1304. // the instruction name.
  1305. FormatArg(id);
  1306. }
  1307. }
  1308. auto Formatter::FormatTypeOfInst(InstId id) -> void {
  1309. auto type_id = sem_ir_->insts().GetAttachedType(id);
  1310. if (!type_id.has_value()) {
  1311. out_ << "invalid";
  1312. return;
  1313. }
  1314. // Types are formatted in the `constants` scope because they typically refer
  1315. // to constants.
  1316. llvm::SaveAndRestore file_scope(scope_, InstNamer::ScopeId::Constants);
  1317. FormatConstant(sem_ir_->types().GetConstantId(type_id));
  1318. }
  1319. auto Formatter::GetImportIRLabel(ImportIRId id) -> std::string {
  1320. CARBON_CHECK(id.has_value(),
  1321. "Callers are responsible for checking `id.has_value`");
  1322. const auto& import_ir = *sem_ir_->import_irs().Get(id).sem_ir;
  1323. CARBON_CHECK(import_ir.library_id().has_value());
  1324. auto package_id = import_ir.package_id();
  1325. llvm::StringRef package_name =
  1326. package_id.AsIdentifierId().has_value()
  1327. ? import_ir.identifiers().Get(package_id.AsIdentifierId())
  1328. : package_id.AsSpecialName();
  1329. llvm::StringRef library_name =
  1330. (import_ir.library_id() != LibraryNameId::Default)
  1331. ? import_ir.string_literal_values().Get(
  1332. import_ir.library_id().AsStringLiteralValueId())
  1333. : "default";
  1334. return llvm::formatv("{0}//{1}", package_name, library_name);
  1335. }
  1336. } // namespace Carbon::SemIR
  1337. // NOLINTEND(misc-no-recursion)