compile_subcommand.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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/driver/compile_subcommand.h"
  5. #include <functional>
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <system_error>
  10. #include <utility>
  11. #include "common/pretty_stack_trace_function.h"
  12. #include "common/vlog.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "toolchain/base/timings.h"
  16. #include "toolchain/check/check.h"
  17. #include "toolchain/codegen/codegen.h"
  18. #include "toolchain/diagnostics/diagnostic_emitter.h"
  19. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  20. #include "toolchain/lex/lex.h"
  21. #include "toolchain/lower/lower.h"
  22. #include "toolchain/parse/parse.h"
  23. #include "toolchain/parse/tree_and_subtrees.h"
  24. #include "toolchain/sem_ir/formatter.h"
  25. #include "toolchain/sem_ir/import_ir.h"
  26. #include "toolchain/sem_ir/inst_namer.h"
  27. #include "toolchain/source/source_buffer.h"
  28. namespace Carbon {
  29. auto CompileOptions::Build(CommandLine::CommandBuilder& b) -> void {
  30. b.AddStringPositionalArg(
  31. {
  32. .name = "FILE",
  33. .help = R"""(
  34. The input Carbon source file to compile.
  35. )""",
  36. },
  37. [&](auto& arg_b) {
  38. arg_b.Required(true);
  39. arg_b.Append(&input_filenames);
  40. });
  41. b.AddOneOfOption(
  42. {
  43. .name = "phase",
  44. .help = R"""(
  45. Selects the compilation phase to run. These phases are always run in sequence,
  46. so every phase before the one selected will also be run. The default is to
  47. compile to machine code.
  48. )""",
  49. },
  50. [&](auto& arg_b) {
  51. arg_b.SetOneOf(
  52. {
  53. arg_b.OneOfValue("lex", Phase::Lex),
  54. arg_b.OneOfValue("parse", Phase::Parse),
  55. arg_b.OneOfValue("check", Phase::Check),
  56. arg_b.OneOfValue("lower", Phase::Lower),
  57. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  58. },
  59. &phase);
  60. });
  61. // TODO: Rearrange the code setting this option and two related ones to
  62. // allow them to reference each other instead of hard-coding their names.
  63. b.AddStringOption(
  64. {
  65. .name = "output",
  66. .value_name = "FILE",
  67. .help = R"""(
  68. The output filename for codegen.
  69. When this is a file name, either textual assembly or a binary object will be
  70. written to it based on the flag `--asm-output`. The default is to write a binary
  71. object file.
  72. Passing `--output=-` will write the output to stdout. In that case, the flag
  73. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  74. object output can be forced by enabling `--force-obj-output`.
  75. )""",
  76. },
  77. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  78. // Include the common code generation options at this point to render it
  79. // after the more common options above, but before the more unusual options
  80. // below.
  81. codegen_options.Build(b);
  82. b.AddFlag(
  83. {
  84. .name = "asm-output",
  85. .help = R"""(
  86. Write textual assembly rather than a binary object file to the code generation
  87. output.
  88. This flag only applies when writing to a file. When writing to stdout, the
  89. default is textual assembly and this flag is ignored.
  90. )""",
  91. },
  92. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  93. b.AddFlag(
  94. {
  95. .name = "force-obj-output",
  96. .help = R"""(
  97. Force binary object output, even with `--output=-`.
  98. When `--output=-` is set, the default is textual assembly; this forces printing
  99. of a binary object file instead. Ignored for other `--output` values.
  100. )""",
  101. },
  102. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  103. b.AddFlag(
  104. {
  105. .name = "stream-errors",
  106. .help = R"""(
  107. Stream error messages to stderr as they are generated rather than sorting them
  108. and displaying them in source order.
  109. )""",
  110. },
  111. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  112. b.AddFlag(
  113. {
  114. .name = "dump-shared-values",
  115. .help = R"""(
  116. Dumps shared values. These aren't owned by any particular file or phase.
  117. )""",
  118. },
  119. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  120. b.AddFlag(
  121. {
  122. .name = "dump-tokens",
  123. .help = R"""(
  124. Dump the tokens to stdout when lexed.
  125. )""",
  126. },
  127. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  128. b.AddFlag(
  129. {
  130. .name = "omit-file-boundary-tokens",
  131. .help = R"""(
  132. For `--dump-tokens`, omit file start and end boundary tokens.
  133. )""",
  134. },
  135. [&](auto& arg_b) { arg_b.Set(&omit_file_boundary_tokens); });
  136. b.AddFlag(
  137. {
  138. .name = "dump-parse-tree",
  139. .help = R"""(
  140. Dump the parse tree to stdout when parsed.
  141. )""",
  142. },
  143. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  144. b.AddFlag(
  145. {
  146. .name = "preorder-parse-tree",
  147. .help = R"""(
  148. When dumping the parse tree, reorder it so that it is in preorder rather than
  149. postorder.
  150. )""",
  151. },
  152. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  153. b.AddFlag(
  154. {
  155. .name = "dump-raw-sem-ir",
  156. .help = R"""(
  157. Dump the raw JSON structure of SemIR to stdout when built.
  158. )""",
  159. },
  160. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  161. b.AddFlag(
  162. {
  163. .name = "dump-sem-ir",
  164. .help = R"""(
  165. Dump the full SemIR to stdout when built.
  166. )""",
  167. },
  168. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  169. b.AddOneOfOption(
  170. {
  171. .name = "dump-sem-ir-ranges",
  172. .help = R"""(
  173. Selects handling of `//@dump-sem-ir-[begin|end]` markers when dumping SemIR.
  174. By default, `if-present` prints ranges for files that have them, and full SemIR
  175. for files that don't. `only` skips files with no ranges, and `ignore` always
  176. prints full SemIR.
  177. )""",
  178. },
  179. [&](auto& arg_b) {
  180. arg_b.SetOneOf(
  181. {
  182. arg_b.OneOfValue("if-present", DumpSemIRRanges::IfPresent)
  183. .Default(true),
  184. arg_b.OneOfValue("only", DumpSemIRRanges::Only),
  185. arg_b.OneOfValue("ignore", DumpSemIRRanges::Ignore),
  186. },
  187. &dump_sem_ir_ranges);
  188. });
  189. b.AddFlag(
  190. {
  191. .name = "builtin-sem-ir",
  192. .help = R"""(
  193. Include the SemIR for builtins when dumping it.
  194. )""",
  195. },
  196. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  197. b.AddFlag(
  198. {
  199. .name = "dump-llvm-ir",
  200. .help = R"""(
  201. Dump the LLVM IR to stdout after lowering.
  202. )""",
  203. },
  204. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  205. b.AddFlag(
  206. {
  207. .name = "dump-asm",
  208. .help = R"""(
  209. Dump the generated assembly to stdout after codegen.
  210. )""",
  211. },
  212. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  213. b.AddFlag(
  214. {
  215. .name = "dump-mem-usage",
  216. .help = R"""(
  217. Dumps the amount of memory used.
  218. )""",
  219. },
  220. [&](auto& arg_b) { arg_b.Set(&dump_mem_usage); });
  221. b.AddFlag(
  222. {
  223. .name = "dump-timings",
  224. .help = R"""(
  225. Dumps the duration of each phase for each compilation unit.
  226. )""",
  227. },
  228. [&](auto& arg_b) { arg_b.Set(&dump_timings); });
  229. b.AddFlag(
  230. {
  231. .name = "prelude-import",
  232. .help = R"""(
  233. Whether to use the implicit prelude import. Enabled by default.
  234. )""",
  235. },
  236. [&](auto& arg_b) {
  237. arg_b.Default(true);
  238. arg_b.Set(&prelude_import);
  239. });
  240. b.AddFlag(
  241. {
  242. .name = "custom-core",
  243. .value_name = "CUSTOM_CORE",
  244. .help = R"""(
  245. Whether to use a custom Core package, the files for which must all be included
  246. in the compile command line.
  247. The prelude library in the Core package is imported automatically. By default,
  248. the Core package shipped with the toolchain is used, and its files do not need
  249. to be specified in the compile command line.
  250. )""",
  251. },
  252. [&](auto& arg_b) {
  253. arg_b.Default(false);
  254. arg_b.Set(&custom_core);
  255. });
  256. b.AddStringOption(
  257. {
  258. .name = "exclude-dump-file-prefix",
  259. .value_name = "PREFIX",
  260. .help = R"""(
  261. Excludes files with the given prefix from dumps.
  262. )""",
  263. },
  264. [&](auto& arg_b) { arg_b.Append(&exclude_dump_file_prefixes); });
  265. b.AddFlag(
  266. {
  267. .name = "debug-info",
  268. .help = R"""(
  269. Whether to emit DWARF debug information.
  270. )""",
  271. },
  272. [&](auto& arg_b) {
  273. arg_b.Default(true);
  274. arg_b.Set(&include_debug_info);
  275. });
  276. b.AddFlag(
  277. {
  278. .name = "verify-llvm-ir",
  279. .help = R"""(
  280. Whether to run the LLVM verifier on modules.
  281. )""",
  282. },
  283. [&](auto& arg_b) {
  284. arg_b.Default(true);
  285. arg_b.Set(&run_llvm_verifier);
  286. });
  287. }
  288. static constexpr CommandLine::CommandInfo SubcommandInfo = {
  289. .name = "compile",
  290. .help = R"""(
  291. Compile Carbon source code.
  292. This subcommand runs the Carbon compiler over input source code, checking it for
  293. errors and producing the requested output.
  294. Error messages are written to the standard error stream.
  295. Different phases of the compiler can be selected to run, and intermediate state
  296. can be written to standard output as these phases progress.
  297. )""",
  298. };
  299. CompileSubcommand::CompileSubcommand() : DriverSubcommand(SubcommandInfo) {}
  300. // Returns a string for printing the phase in a diagnostic.
  301. static auto PhaseToString(CompileOptions::Phase phase) -> std::string {
  302. switch (phase) {
  303. case CompileOptions::Phase::Lex:
  304. return "lex";
  305. case CompileOptions::Phase::Parse:
  306. return "parse";
  307. case CompileOptions::Phase::Check:
  308. return "check";
  309. case CompileOptions::Phase::Lower:
  310. return "lower";
  311. case CompileOptions::Phase::CodeGen:
  312. return "codegen";
  313. }
  314. }
  315. auto CompileSubcommand::ValidateOptions(
  316. Diagnostics::NoLocEmitter& emitter) const -> bool {
  317. CARBON_DIAGNOSTIC(
  318. CompilePhaseFlagConflict, Error,
  319. "requested dumping {0} but compile phase is limited to `{1}`",
  320. std::string, std::string);
  321. using Phase = CompileOptions::Phase;
  322. switch (options_.phase) {
  323. case Phase::Lex:
  324. if (options_.dump_parse_tree) {
  325. emitter.Emit(CompilePhaseFlagConflict, "parse tree",
  326. PhaseToString(options_.phase));
  327. return false;
  328. }
  329. [[fallthrough]];
  330. case Phase::Parse:
  331. if (options_.dump_sem_ir) {
  332. emitter.Emit(CompilePhaseFlagConflict, "SemIR",
  333. PhaseToString(options_.phase));
  334. return false;
  335. }
  336. [[fallthrough]];
  337. case Phase::Check:
  338. if (options_.dump_llvm_ir) {
  339. emitter.Emit(CompilePhaseFlagConflict, "LLVM IR",
  340. PhaseToString(options_.phase));
  341. return false;
  342. }
  343. [[fallthrough]];
  344. case Phase::Lower:
  345. case Phase::CodeGen:
  346. // Everything can be dumped in these phases.
  347. break;
  348. }
  349. return true;
  350. }
  351. namespace {
  352. class MultiUnitCache;
  353. // Ties together information for a file being compiled.
  354. class CompilationUnit {
  355. public:
  356. explicit CompilationUnit(int unit_index, DriverEnv* driver_env,
  357. const CompileOptions* options,
  358. Diagnostics::Consumer* consumer,
  359. llvm::StringRef input_filename);
  360. // Sets the multi-unit cache and initializes dependent member state.
  361. auto SetMultiUnitCache(MultiUnitCache* cache) -> void;
  362. // Loads source and lexes it. Returns true on success.
  363. auto RunLex() -> void;
  364. // Parses tokens. Returns true on success.
  365. auto RunParse() -> void;
  366. // Returns information needed to check this unit.
  367. auto GetCheckUnit() -> Check::Unit;
  368. // Runs post-check logic. Returns true if checking succeeded for the IR.
  369. auto PostCheck() -> void;
  370. // Lower SemIR to LLVM IR.
  371. auto RunLower() -> void;
  372. auto RunCodeGen() -> void;
  373. // Runs post-compile logic. This is always called, and called after all other
  374. // actions on the CompilationUnit.
  375. auto PostCompile() -> void;
  376. // Flushes diagnostics, specifically as part of generating stack trace
  377. // information.
  378. auto FlushForStackTrace() -> void { consumer_->Flush(); }
  379. auto input_filename() -> llvm::StringRef { return input_filename_; }
  380. auto success() -> bool { return success_; }
  381. auto has_source() -> bool { return source_.has_value(); }
  382. auto get_trees_and_subtrees() -> Parse::GetTreeAndSubtreesFn {
  383. return *tree_and_subtrees_getter_;
  384. }
  385. private:
  386. // Do codegen. Returns true on success.
  387. auto RunCodeGenHelper() -> bool;
  388. // The TreeAndSubtrees is mainly used for debugging and diagnostics, and has
  389. // significant overhead. Avoid constructing it when unused.
  390. auto GetParseTreeAndSubtrees() -> const Parse::TreeAndSubtrees&;
  391. // Handles printing of formatted SemIR.
  392. auto MaybePrintFormattedSemIR() -> void;
  393. // Wraps a call with log statements to indicate start and end. Typically logs
  394. // with the actual function name, but marks timings with the appropriate
  395. // phase.
  396. auto LogCall(llvm::StringLiteral logging_label,
  397. llvm::StringLiteral timing_label,
  398. llvm::function_ref<auto()->void> fn) -> void;
  399. // Returns true if the current file should be included in debug dumps.
  400. auto IncludeInDumps() -> bool;
  401. // The index of the unit amongst all units. Equivalent to a `CheckIRId`.
  402. int unit_index_;
  403. DriverEnv* driver_env_;
  404. const CompileOptions* options_;
  405. SharedValueStores value_stores_;
  406. // The input filename from the command line. For most diagnostics, we
  407. // typically use `source_->filename()`, which includes a `-` -> `<stdin>`
  408. // translation. However, logging and some diagnostics use the command line
  409. // argument.
  410. std::string input_filename_;
  411. // Copied from driver_ for CARBON_VLOG.
  412. llvm::raw_pwrite_stream* vlog_stream_;
  413. // Diagnostics are sent to consumer_, with optional sorting.
  414. std::optional<Diagnostics::SortingConsumer> sorting_consumer_;
  415. Diagnostics::Consumer* consumer_;
  416. bool success_ = true;
  417. // Initialized by `SetMultiUnitCache`.
  418. MultiUnitCache* cache_ = nullptr;
  419. // Tracks memory usage of the compile.
  420. std::optional<MemUsage> mem_usage_;
  421. // Tracks timings of the compile.
  422. std::optional<Timings> timings_;
  423. // These are initialized as steps are run.
  424. std::optional<SourceBuffer> source_;
  425. std::optional<Lex::TokenizedBuffer> tokens_;
  426. std::optional<Parse::Tree> parse_tree_;
  427. std::optional<Parse::TreeAndSubtrees> parse_tree_and_subtrees_;
  428. std::optional<std::function<auto()->const Parse::TreeAndSubtrees&>>
  429. tree_and_subtrees_getter_;
  430. std::optional<SemIR::File> sem_ir_;
  431. std::unique_ptr<clang::ASTUnit> cpp_ast_;
  432. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  433. std::unique_ptr<llvm::Module> module_;
  434. };
  435. // Caches lists that are shared cross-unit. Accessors do lazy caching because
  436. // they may not be used.
  437. class MultiUnitCache {
  438. public:
  439. // This relies on construction after `units` are all initialized, which is
  440. // reflected by the `ArrayRef` here.
  441. explicit MultiUnitCache(
  442. const CompileOptions* options,
  443. const llvm::ArrayRef<std::unique_ptr<CompilationUnit>> units)
  444. : options_(options), units_(units) {}
  445. auto include_in_dumps() -> llvm::ArrayRef<bool> {
  446. CARBON_CHECK(!units_.empty());
  447. if (include_in_dumps_.empty()) {
  448. BuildIncludeInDumps();
  449. }
  450. return include_in_dumps_;
  451. }
  452. auto tree_and_subtrees_getters()
  453. -> llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> {
  454. CARBON_CHECK(!units_.empty());
  455. if (tree_and_subtrees_getters_.empty()) {
  456. BuildTreeAndSubtreesGetters();
  457. }
  458. return tree_and_subtrees_getters_;
  459. }
  460. private:
  461. auto BuildIncludeInDumps() -> void {
  462. CARBON_CHECK(include_in_dumps_.empty());
  463. llvm::append_range(
  464. include_in_dumps_, llvm::map_range(units_, [&](const auto& unit) {
  465. return llvm::none_of(
  466. options_->exclude_dump_file_prefixes, [&](auto prefix) {
  467. return unit->input_filename().starts_with(prefix);
  468. });
  469. }));
  470. }
  471. auto BuildTreeAndSubtreesGetters() -> void {
  472. CARBON_CHECK(tree_and_subtrees_getters_.empty());
  473. llvm::append_range(
  474. tree_and_subtrees_getters_,
  475. llvm::map_range(units_, [&](const auto& unit) {
  476. return unit->has_source() ? unit->get_trees_and_subtrees() : nullptr;
  477. }));
  478. }
  479. const CompileOptions* options_;
  480. // The units being compiled.
  481. const llvm::ArrayRef<std::unique_ptr<CompilationUnit>> units_;
  482. // For each unit, whether it's included in dumps. Used cross-phase.
  483. llvm::SmallVector<bool> include_in_dumps_;
  484. // For each unit, the `TreeAndSubtrees` getter. Used by lowering.
  485. llvm::SmallVector<Parse::GetTreeAndSubtreesFn> tree_and_subtrees_getters_;
  486. };
  487. } // namespace
  488. CompilationUnit::CompilationUnit(int unit_index, DriverEnv* driver_env,
  489. const CompileOptions* options,
  490. Diagnostics::Consumer* consumer,
  491. llvm::StringRef input_filename)
  492. : unit_index_(unit_index),
  493. driver_env_(driver_env),
  494. options_(options),
  495. input_filename_(input_filename),
  496. vlog_stream_(driver_env_->vlog_stream) {
  497. if (vlog_stream_ != nullptr || options_->stream_errors) {
  498. consumer_ = consumer;
  499. } else {
  500. sorting_consumer_ = Diagnostics::SortingConsumer(*consumer);
  501. consumer_ = &*sorting_consumer_;
  502. }
  503. }
  504. auto CompilationUnit::IncludeInDumps() -> bool {
  505. return cache_->include_in_dumps()[unit_index_];
  506. }
  507. auto CompilationUnit::SetMultiUnitCache(MultiUnitCache* cache) -> void {
  508. CARBON_CHECK(!cache_, "Called SetMultiUnitCache twice");
  509. cache_ = cache;
  510. if (options_->dump_mem_usage && IncludeInDumps()) {
  511. CARBON_CHECK(!mem_usage_);
  512. mem_usage_ = MemUsage();
  513. }
  514. if (options_->dump_timings && IncludeInDumps()) {
  515. CARBON_CHECK(!timings_);
  516. timings_ = Timings();
  517. }
  518. }
  519. auto CompilationUnit::RunLex() -> void {
  520. CARBON_CHECK(cache_, "Must call SetMultiUnitCache first");
  521. CARBON_CHECK(!tokens_, "Called RunLex twice");
  522. LogCall("SourceBuffer::MakeFromFileOrStdin", "source", [&] {
  523. source_ = SourceBuffer::MakeFromFileOrStdin(*driver_env_->fs,
  524. input_filename_, *consumer_);
  525. });
  526. if (!source_) {
  527. success_ = false;
  528. return;
  529. }
  530. if (mem_usage_) {
  531. mem_usage_->Add("source_", source_->text().size(), source_->text().size());
  532. }
  533. CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());
  534. LogCall("Lex::Lex", "lex",
  535. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  536. if (options_->dump_tokens && IncludeInDumps()) {
  537. consumer_->Flush();
  538. tokens_->Print(*driver_env_->output_stream,
  539. options_->omit_file_boundary_tokens);
  540. }
  541. if (mem_usage_) {
  542. mem_usage_->Collect("tokens_", *tokens_);
  543. }
  544. CARBON_VLOG("*** Lex::TokenizedBuffer ***\n{0}", tokens_);
  545. if (tokens_->has_errors()) {
  546. success_ = false;
  547. }
  548. }
  549. auto CompilationUnit::RunParse() -> void {
  550. LogCall("Parse::Parse", "parse", [&] {
  551. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  552. });
  553. if (options_->dump_parse_tree && IncludeInDumps()) {
  554. consumer_->Flush();
  555. const auto& tree_and_subtrees = GetParseTreeAndSubtrees();
  556. if (options_->preorder_parse_tree) {
  557. tree_and_subtrees.PrintPreorder(*driver_env_->output_stream);
  558. } else {
  559. tree_and_subtrees.Print(*driver_env_->output_stream);
  560. }
  561. }
  562. if (mem_usage_) {
  563. mem_usage_->Collect("parse_tree_", *parse_tree_);
  564. }
  565. CARBON_VLOG("*** Parse::Tree ***\n{0}", parse_tree_);
  566. if (parse_tree_->has_errors()) {
  567. success_ = false;
  568. }
  569. }
  570. auto CompilationUnit::GetCheckUnit() -> Check::Unit {
  571. CARBON_CHECK(parse_tree_, "Must call RunParse first");
  572. CARBON_CHECK(!sem_ir_, "Called GetCheckUnit twice");
  573. tree_and_subtrees_getter_ = [this]() -> const Parse::TreeAndSubtrees& {
  574. return this->GetParseTreeAndSubtrees();
  575. };
  576. sem_ir_.emplace(&*parse_tree_, SemIR::CheckIRId(unit_index_),
  577. parse_tree_->packaging_decl(), value_stores_,
  578. input_filename_);
  579. return {.consumer = consumer_,
  580. .value_stores = &value_stores_,
  581. .timings = timings_ ? &*timings_ : nullptr,
  582. .sem_ir = &*sem_ir_,
  583. .cpp_ast = &cpp_ast_};
  584. }
  585. auto CompilationUnit::MaybePrintFormattedSemIR() -> void {
  586. bool print = options_->dump_sem_ir && IncludeInDumps();
  587. if (!vlog_stream_ && !print) {
  588. return;
  589. }
  590. if (options_->dump_sem_ir_ranges == CompileOptions::DumpSemIRRanges::Only &&
  591. !tokens_->has_dump_sem_ir_ranges()) {
  592. return;
  593. }
  594. bool use_dump_sem_ir_ranges =
  595. options_->dump_sem_ir_ranges != CompileOptions::DumpSemIRRanges::Ignore &&
  596. tokens_->has_dump_sem_ir_ranges();
  597. SemIR::Formatter formatter(&*sem_ir_, *tree_and_subtrees_getter_,
  598. cache_->include_in_dumps(),
  599. use_dump_sem_ir_ranges);
  600. formatter.Format();
  601. if (vlog_stream_) {
  602. CARBON_VLOG("*** SemIR::File ***\n");
  603. formatter.Write(*vlog_stream_);
  604. }
  605. if (print) {
  606. formatter.Write(*driver_env_->output_stream);
  607. }
  608. }
  609. auto CompilationUnit::PostCheck() -> void {
  610. CARBON_CHECK(sem_ir_, "Must call GetCheckUnit first");
  611. // We've finished all steps that can produce diagnostics. Emit the
  612. // diagnostics now, so that the developer sees them sooner and doesn't need
  613. // to wait for code generation.
  614. consumer_->Flush();
  615. if (mem_usage_) {
  616. mem_usage_->Collect("sem_ir_", *sem_ir_);
  617. }
  618. if (options_->dump_raw_sem_ir && IncludeInDumps()) {
  619. CARBON_VLOG("*** Raw SemIR::File ***\n{0}\n", *sem_ir_);
  620. sem_ir_->Print(*driver_env_->output_stream, options_->builtin_sem_ir);
  621. if (options_->dump_sem_ir) {
  622. *driver_env_->output_stream << "\n";
  623. }
  624. }
  625. MaybePrintFormattedSemIR();
  626. if (sem_ir_->has_errors()) {
  627. success_ = false;
  628. }
  629. }
  630. auto CompilationUnit::RunLower() -> void {
  631. LogCall("Lower::LowerToLLVM", "lower", [&] {
  632. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  633. // TODO: Consider disabling instruction naming by default if we're not
  634. // producing textual LLVM IR.
  635. SemIR::InstNamer inst_namer(&*sem_ir_);
  636. llvm::ArrayRef<Parse::GetTreeAndSubtreesFn> subtrees =
  637. cache_->tree_and_subtrees_getters();
  638. module_ = Lower::LowerToLLVM(
  639. *llvm_context_, driver_env_->fs,
  640. options_->run_llvm_verifier ? driver_env_->error_stream : nullptr,
  641. options_->include_debug_info, subtrees, input_filename_, *sem_ir_,
  642. &inst_namer, vlog_stream_);
  643. });
  644. if (vlog_stream_) {
  645. CARBON_VLOG("*** llvm::Module ***\n");
  646. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  647. /*ShouldPreserveUseListOrder=*/false,
  648. /*IsForDebug=*/true);
  649. }
  650. if (options_->dump_llvm_ir && IncludeInDumps()) {
  651. module_->print(*driver_env_->output_stream, /*AAW=*/nullptr,
  652. /*ShouldPreserveUseListOrder=*/true);
  653. }
  654. }
  655. auto CompilationUnit::RunCodeGen() -> void {
  656. CARBON_CHECK(module_, "Must call RunLower first");
  657. LogCall("CodeGen", "codegen", [&] { success_ = RunCodeGenHelper(); });
  658. }
  659. auto CompilationUnit::PostCompile() -> void {
  660. if (options_->dump_shared_values && IncludeInDumps()) {
  661. Yaml::Print(*driver_env_->output_stream,
  662. value_stores_.OutputYaml(input_filename_));
  663. }
  664. if (mem_usage_) {
  665. mem_usage_->Collect("value_stores_", value_stores_);
  666. Yaml::Print(*driver_env_->output_stream,
  667. mem_usage_->OutputYaml(input_filename_));
  668. }
  669. if (timings_) {
  670. Yaml::Print(*driver_env_->output_stream,
  671. timings_->OutputYaml(input_filename_));
  672. }
  673. // The diagnostics consumer must be flushed before compilation artifacts are
  674. // destructed, because diagnostics can refer to their state.
  675. consumer_->Flush();
  676. }
  677. auto CompilationUnit::RunCodeGenHelper() -> bool {
  678. std::optional<CodeGen> codegen =
  679. CodeGen::Make(module_.get(), options_->codegen_options.target,
  680. driver_env_->error_stream);
  681. if (!codegen) {
  682. return false;
  683. }
  684. if (vlog_stream_) {
  685. CARBON_VLOG("*** Assembly ***\n");
  686. codegen->EmitAssembly(*vlog_stream_);
  687. }
  688. if (options_->output_filename == "-") {
  689. // TODO: The output file name, forcing object output, and requesting
  690. // textual assembly output are all somewhat linked flags. We should add
  691. // some validation that they are used correctly.
  692. if (options_->force_obj_output) {
  693. if (!codegen->EmitObject(*driver_env_->output_stream)) {
  694. return false;
  695. }
  696. } else {
  697. if (!codegen->EmitAssembly(*driver_env_->output_stream)) {
  698. return false;
  699. }
  700. }
  701. } else {
  702. llvm::SmallString<256> output_filename = options_->output_filename;
  703. if (output_filename.empty()) {
  704. if (!source_->is_regular_file()) {
  705. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  706. // TODO: Consider rephrasing the diagnostic to use the file as the
  707. // `Emit` location.
  708. CARBON_DIAGNOSTIC(CompileInputNotRegularFile, Error,
  709. "output file name must be specified for input `{0}` "
  710. "that is not a regular file",
  711. std::string);
  712. driver_env_->emitter.Emit(CompileInputNotRegularFile, input_filename_);
  713. return false;
  714. }
  715. output_filename = input_filename_;
  716. llvm::sys::path::replace_extension(output_filename,
  717. options_->asm_output ? ".s" : ".o");
  718. } else {
  719. // TODO: Handle the case where multiple input files were specified
  720. // along with an output file name. That should either be an error or
  721. // should produce a single LLVM IR module containing all inputs.
  722. // Currently each unit overwrites the output from the previous one in
  723. // this case.
  724. }
  725. CARBON_VLOG("Writing output to: {0}\n", output_filename);
  726. std::error_code ec;
  727. llvm::raw_fd_ostream output_file(output_filename, ec,
  728. llvm::sys::fs::OF_None);
  729. if (ec) {
  730. // TODO: Consider rephrasing the diagnostic to use the file as the `Emit`
  731. // location.
  732. CARBON_DIAGNOSTIC(CompileOutputFileOpenError, Error,
  733. "could not open output file `{0}`: {1}", std::string,
  734. std::string);
  735. driver_env_->emitter.Emit(CompileOutputFileOpenError,
  736. output_filename.str().str(), ec.message());
  737. return false;
  738. }
  739. if (options_->asm_output) {
  740. if (!codegen->EmitAssembly(output_file)) {
  741. return false;
  742. }
  743. } else {
  744. if (!codegen->EmitObject(output_file)) {
  745. return false;
  746. }
  747. }
  748. }
  749. return true;
  750. }
  751. auto CompilationUnit::GetParseTreeAndSubtrees()
  752. -> const Parse::TreeAndSubtrees& {
  753. if (!parse_tree_and_subtrees_) {
  754. parse_tree_and_subtrees_ = Parse::TreeAndSubtrees(*tokens_, *parse_tree_);
  755. if (mem_usage_) {
  756. mem_usage_->Collect("parse_tree_and_subtrees_",
  757. *parse_tree_and_subtrees_);
  758. }
  759. }
  760. return *parse_tree_and_subtrees_;
  761. }
  762. auto CompilationUnit::LogCall(llvm::StringLiteral logging_label,
  763. llvm::StringLiteral timing_label,
  764. llvm::function_ref<auto()->void> fn) -> void {
  765. PrettyStackTraceFunction trace_file([&](llvm::raw_ostream& out) {
  766. out << "Filename: " << input_filename_ << "\n";
  767. });
  768. CARBON_VLOG("*** {0}: {1} ***\n", logging_label, input_filename_);
  769. Timings::ScopedTiming timing(timings_ ? &*timings_ : nullptr, timing_label);
  770. fn();
  771. CARBON_VLOG("*** {0} done ***\n", logging_label);
  772. }
  773. auto CompileSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  774. if (!ValidateOptions(driver_env.emitter)) {
  775. return {.success = false};
  776. }
  777. // Find the files comprising the prelude if we are importing it.
  778. // TODO: Replace this with a search for library api files in a
  779. // package-specific search path based on the library name.
  780. llvm::SmallVector<std::string> prelude;
  781. if (options_.prelude_import && !options_.custom_core &&
  782. options_.phase >= CompileOptions::Phase::Check) {
  783. if (auto find = driver_env.installation->ReadPreludeManifest(); find.ok()) {
  784. prelude = std::move(*find);
  785. } else {
  786. // TODO: Change ReadPreludeManifest to produce diagnostics.
  787. CARBON_DIAGNOSTIC(CompilePreludeManifestError, Error, "{0}", std::string);
  788. driver_env.emitter.Emit(CompilePreludeManifestError,
  789. PrintToString(find.error()));
  790. return {.success = false};
  791. }
  792. }
  793. // Prepare CompilationUnits before building scope exit handlers.
  794. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  795. int unit_index = -1;
  796. auto unit_builder = [&](llvm::StringRef filename) {
  797. return std::make_unique<CompilationUnit>(
  798. ++unit_index, &driver_env, &options_, &driver_env.consumer, filename);
  799. };
  800. llvm::append_range(units, llvm::map_range(prelude, unit_builder));
  801. llvm::append_range(units,
  802. llvm::map_range(options_.input_filenames, unit_builder));
  803. // Add the cache to all units. This must be done after all units are created.
  804. MultiUnitCache cache(&options_, units);
  805. for (auto& unit : units) {
  806. unit->SetMultiUnitCache(&cache);
  807. }
  808. auto on_exit = llvm::make_scope_exit([&]() {
  809. // Finish compilation units. This flushes their diagnostics in the order in
  810. // which they were specified on the command line.
  811. for (auto& unit : units) {
  812. unit->PostCompile();
  813. }
  814. driver_env.consumer.Flush();
  815. });
  816. PrettyStackTraceFunction flush_on_crash([&](llvm::raw_ostream& out) {
  817. // When crashing, flush diagnostics. If sorting diagnostics, they can be
  818. // redirected to the crash stream; if streaming, the original stream is
  819. // flushed.
  820. // TODO: Eventually we'll want to limit the count.
  821. if (options_.stream_errors) {
  822. out << "Flushing diagnostics\n";
  823. } else {
  824. out << "Pending diagnostics:\n";
  825. driver_env.consumer.set_stream(&out);
  826. }
  827. for (auto& unit : units) {
  828. unit->FlushForStackTrace();
  829. }
  830. driver_env.consumer.Flush();
  831. driver_env.consumer.set_stream(driver_env.error_stream);
  832. });
  833. // Returns a DriverResult object. Called whenever Compile returns.
  834. auto make_result = [&]() {
  835. DriverResult result = {.success = true};
  836. for (const auto& unit : units) {
  837. result.success &= unit->success();
  838. result.per_file_success.push_back(
  839. {unit->input_filename().str(), unit->success()});
  840. }
  841. return result;
  842. };
  843. // Lex.
  844. for (auto& unit : units) {
  845. unit->RunLex();
  846. }
  847. if (options_.phase == CompileOptions::Phase::Lex) {
  848. return make_result();
  849. }
  850. // Parse and check phases examine `has_source` because they want to proceed if
  851. // lex failed, but not if source doesn't exist. Later steps are skipped if
  852. // anything failed, so don't need this.
  853. // Parse.
  854. for (auto& unit : units) {
  855. if (unit->has_source()) {
  856. unit->RunParse();
  857. }
  858. }
  859. if (options_.phase == CompileOptions::Phase::Parse) {
  860. return make_result();
  861. }
  862. // Gather Check::Units.
  863. llvm::SmallVector<Check::Unit> check_units;
  864. check_units.reserve(units.size());
  865. for (auto& unit : units) {
  866. if (unit->has_source()) {
  867. check_units.push_back(unit->GetCheckUnit());
  868. }
  869. }
  870. // Execute the actual checking.
  871. CARBON_VLOG_TO(driver_env.vlog_stream, "*** Check::CheckParseTrees ***\n");
  872. Check::CheckParseTrees(check_units, cache.tree_and_subtrees_getters(),
  873. options_.prelude_import, driver_env.fs,
  874. options_.codegen_options.target,
  875. driver_env.vlog_stream, driver_env.fuzzing);
  876. CARBON_VLOG_TO(driver_env.vlog_stream,
  877. "*** Check::CheckParseTrees done ***\n");
  878. for (auto& unit : units) {
  879. if (unit->has_source()) {
  880. unit->PostCheck();
  881. }
  882. }
  883. if (options_.phase == CompileOptions::Phase::Check) {
  884. return make_result();
  885. }
  886. // Unlike previous steps, errors block further progress.
  887. if (llvm::any_of(units, [&](const auto& unit) { return !unit->success(); })) {
  888. CARBON_VLOG_TO(driver_env.vlog_stream,
  889. "*** Stopping before lowering due to errors ***\n");
  890. return make_result();
  891. }
  892. // Lower.
  893. for (const auto& unit : units) {
  894. unit->RunLower();
  895. }
  896. if (options_.phase == CompileOptions::Phase::Lower) {
  897. return make_result();
  898. }
  899. CARBON_CHECK(options_.phase == CompileOptions::Phase::CodeGen,
  900. "CodeGen should be the last stage");
  901. // Codegen.
  902. for (auto& unit : units) {
  903. unit->RunCodeGen();
  904. }
  905. return make_result();
  906. }
  907. } // namespace Carbon