formatter.cpp 42 KB

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