compile_subcommand.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  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 "common/vlog.h"
  6. #include "llvm/ADT/ScopeExit.h"
  7. #include "toolchain/base/pretty_stack_trace_function.h"
  8. #include "toolchain/check/check.h"
  9. #include "toolchain/codegen/codegen.h"
  10. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  11. #include "toolchain/lex/lex.h"
  12. #include "toolchain/lower/lower.h"
  13. #include "toolchain/parse/parse.h"
  14. #include "toolchain/parse/tree_and_subtrees.h"
  15. #include "toolchain/sem_ir/formatter.h"
  16. #include "toolchain/sem_ir/inst_namer.h"
  17. #include "toolchain/source/source_buffer.h"
  18. namespace Carbon {
  19. auto operator<<(llvm::raw_ostream& out, CompileOptions::Phase phase)
  20. -> llvm::raw_ostream& {
  21. switch (phase) {
  22. case CompileOptions::Phase::Lex:
  23. out << "lex";
  24. break;
  25. case CompileOptions::Phase::Parse:
  26. out << "parse";
  27. break;
  28. case CompileOptions::Phase::Check:
  29. out << "check";
  30. break;
  31. case CompileOptions::Phase::Lower:
  32. out << "lower";
  33. break;
  34. case CompileOptions::Phase::CodeGen:
  35. out << "codegen";
  36. break;
  37. }
  38. return out;
  39. }
  40. constexpr CommandLine::CommandInfo CompileOptions::Info = {
  41. .name = "compile",
  42. .help = R"""(
  43. Compile Carbon source code.
  44. This subcommand runs the Carbon compiler over input source code, checking it for
  45. errors and producing the requested output.
  46. Error messages are written to the standard error stream.
  47. Different phases of the compiler can be selected to run, and intermediate state
  48. can be written to standard output as these phases progress.
  49. )""",
  50. };
  51. auto CompileOptions::Build(CommandLine::CommandBuilder& b) -> void {
  52. b.AddStringPositionalArg(
  53. {
  54. .name = "FILE",
  55. .help = R"""(
  56. The input Carbon source file to compile.
  57. )""",
  58. },
  59. [&](auto& arg_b) {
  60. arg_b.Required(true);
  61. arg_b.Append(&input_filenames);
  62. });
  63. b.AddOneOfOption(
  64. {
  65. .name = "phase",
  66. .help = R"""(
  67. Selects the compilation phase to run. These phases are always run in sequence,
  68. so every phase before the one selected will also be run. The default is to
  69. compile to machine code.
  70. )""",
  71. },
  72. [&](auto& arg_b) {
  73. arg_b.SetOneOf(
  74. {
  75. arg_b.OneOfValue("lex", Phase::Lex),
  76. arg_b.OneOfValue("parse", Phase::Parse),
  77. arg_b.OneOfValue("check", Phase::Check),
  78. arg_b.OneOfValue("lower", Phase::Lower),
  79. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  80. },
  81. &phase);
  82. });
  83. // TODO: Rearrange the code setting this option and two related ones to
  84. // allow them to reference each other instead of hard-coding their names.
  85. b.AddStringOption(
  86. {
  87. .name = "output",
  88. .value_name = "FILE",
  89. .help = R"""(
  90. The output filename for codegen.
  91. When this is a file name, either textual assembly or a binary object will be
  92. written to it based on the flag `--asm-output`. The default is to write a binary
  93. object file.
  94. Passing `--output=-` will write the output to stdout. In that case, the flag
  95. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  96. object output can be forced by enabling `--force-obj-output`.
  97. )""",
  98. },
  99. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  100. // Include the common code generation options at this point to render it
  101. // after the more common options above, but before the more unusual options
  102. // below.
  103. codegen_options.Build(b);
  104. b.AddFlag(
  105. {
  106. .name = "asm-output",
  107. .help = R"""(
  108. Write textual assembly rather than a binary object file to the code generation
  109. output.
  110. This flag only applies when writing to a file. When writing to stdout, the
  111. default is textual assembly and this flag is ignored.
  112. )""",
  113. },
  114. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  115. b.AddFlag(
  116. {
  117. .name = "force-obj-output",
  118. .help = R"""(
  119. Force binary object output, even with `--output=-`.
  120. When `--output=-` is set, the default is textual assembly; this forces printing
  121. of a binary object file instead. Ignored for other `--output` values.
  122. )""",
  123. },
  124. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  125. b.AddFlag(
  126. {
  127. .name = "stream-errors",
  128. .help = R"""(
  129. Stream error messages to stderr as they are generated rather than sorting them
  130. and displaying them in source order.
  131. )""",
  132. },
  133. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  134. b.AddFlag(
  135. {
  136. .name = "dump-shared-values",
  137. .help = R"""(
  138. Dumps shared values. These aren't owned by any particular file or phase.
  139. )""",
  140. },
  141. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  142. b.AddFlag(
  143. {
  144. .name = "dump-tokens",
  145. .help = R"""(
  146. Dump the tokens to stdout when lexed.
  147. )""",
  148. },
  149. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  150. b.AddFlag(
  151. {
  152. .name = "dump-parse-tree",
  153. .help = R"""(
  154. Dump the parse tree to stdout when parsed.
  155. )""",
  156. },
  157. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  158. b.AddFlag(
  159. {
  160. .name = "preorder-parse-tree",
  161. .help = R"""(
  162. When dumping the parse tree, reorder it so that it is in preorder rather than
  163. postorder.
  164. )""",
  165. },
  166. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  167. b.AddFlag(
  168. {
  169. .name = "dump-raw-sem-ir",
  170. .help = R"""(
  171. Dump the raw JSON structure of SemIR to stdout when built.
  172. )""",
  173. },
  174. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  175. b.AddFlag(
  176. {
  177. .name = "dump-sem-ir",
  178. .help = R"""(
  179. Dump the SemIR to stdout when built.
  180. )""",
  181. },
  182. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  183. b.AddFlag(
  184. {
  185. .name = "builtin-sem-ir",
  186. .help = R"""(
  187. Include the SemIR for builtins when dumping it.
  188. )""",
  189. },
  190. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  191. b.AddFlag(
  192. {
  193. .name = "dump-llvm-ir",
  194. .help = R"""(
  195. Dump the LLVM IR to stdout after lowering.
  196. )""",
  197. },
  198. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  199. b.AddFlag(
  200. {
  201. .name = "dump-asm",
  202. .help = R"""(
  203. Dump the generated assembly to stdout after codegen.
  204. )""",
  205. },
  206. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  207. b.AddFlag(
  208. {
  209. .name = "dump-mem-usage",
  210. .help = R"""(
  211. Dumps the amount of memory used.
  212. )""",
  213. },
  214. [&](auto& arg_b) { arg_b.Set(&dump_mem_usage); });
  215. b.AddFlag(
  216. {
  217. .name = "prelude-import",
  218. .help = R"""(
  219. Whether to use the implicit prelude import. Enabled by default.
  220. )""",
  221. },
  222. [&](auto& arg_b) {
  223. arg_b.Default(true);
  224. arg_b.Set(&prelude_import);
  225. });
  226. b.AddStringOption(
  227. {
  228. .name = "exclude-dump-file-prefix",
  229. .value_name = "PREFIX",
  230. .help = R"""(
  231. Excludes files with the given prefix from dumps.
  232. )""",
  233. },
  234. [&](auto& arg_b) { arg_b.Set(&exclude_dump_file_prefix); });
  235. b.AddFlag(
  236. {
  237. .name = "debug-info",
  238. .help = R"""(
  239. Emit DWARF debug information.
  240. )""",
  241. },
  242. [&](auto& arg_b) {
  243. arg_b.Default(true);
  244. arg_b.Set(&include_debug_info);
  245. });
  246. }
  247. auto CompileSubcommand::ValidateOptions(DriverEnv& driver_env) const -> bool {
  248. using Phase = CompileOptions::Phase;
  249. switch (options_.phase) {
  250. case Phase::Lex:
  251. if (options_.dump_parse_tree) {
  252. driver_env.error_stream
  253. << "error: requested dumping the parse tree but compile "
  254. "phase is limited to '"
  255. << options_.phase << "'\n";
  256. return false;
  257. }
  258. [[fallthrough]];
  259. case Phase::Parse:
  260. if (options_.dump_sem_ir) {
  261. driver_env.error_stream
  262. << "error: requested dumping the SemIR but compile phase "
  263. "is limited to '"
  264. << options_.phase << "'\n";
  265. return false;
  266. }
  267. [[fallthrough]];
  268. case Phase::Check:
  269. if (options_.dump_llvm_ir) {
  270. driver_env.error_stream
  271. << "error: requested dumping the LLVM IR but compile "
  272. "phase is limited to '"
  273. << options_.phase << "'\n";
  274. return false;
  275. }
  276. [[fallthrough]];
  277. case Phase::Lower:
  278. case Phase::CodeGen:
  279. // Everything can be dumped in these phases.
  280. break;
  281. }
  282. return true;
  283. }
  284. namespace {
  285. // Ties together information for a file being compiled.
  286. // TODO: Refactor this because it's a long class to have function definitions
  287. // inline.
  288. class CompilationUnit {
  289. public:
  290. explicit CompilationUnit(DriverEnv& driver_env, const CompileOptions& options,
  291. DiagnosticConsumer* consumer,
  292. llvm::StringRef input_filename)
  293. : driver_env_(&driver_env),
  294. options_(options),
  295. input_filename_(input_filename),
  296. vlog_stream_(driver_env_->vlog_stream) {
  297. if (vlog_stream_ != nullptr || options_.stream_errors) {
  298. consumer_ = consumer;
  299. } else {
  300. sorting_consumer_ = SortingDiagnosticConsumer(*consumer);
  301. consumer_ = &*sorting_consumer_;
  302. }
  303. if (options_.dump_mem_usage && IncludeInDumps()) {
  304. mem_usage_ = MemUsage();
  305. }
  306. }
  307. // Loads source and lexes it. Returns true on success.
  308. auto RunLex() -> void {
  309. LogCall("SourceBuffer::MakeFromFile", [&] {
  310. if (input_filename_ == "-") {
  311. source_ = SourceBuffer::MakeFromStdin(*consumer_);
  312. } else {
  313. source_ = SourceBuffer::MakeFromFile(driver_env_->fs, input_filename_,
  314. *consumer_);
  315. }
  316. });
  317. if (mem_usage_) {
  318. mem_usage_->Add("source_", source_->text().size(),
  319. source_->text().size());
  320. }
  321. if (!source_) {
  322. success_ = false;
  323. return;
  324. }
  325. CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());
  326. LogCall("Lex::Lex",
  327. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  328. if (options_.dump_tokens && IncludeInDumps()) {
  329. consumer_->Flush();
  330. driver_env_->output_stream << tokens_;
  331. }
  332. if (mem_usage_) {
  333. mem_usage_->Collect("tokens_", *tokens_);
  334. }
  335. CARBON_VLOG("*** Lex::TokenizedBuffer ***\n{0}", tokens_);
  336. if (tokens_->has_errors()) {
  337. success_ = false;
  338. }
  339. }
  340. // Parses tokens. Returns true on success.
  341. auto RunParse() -> void {
  342. CARBON_CHECK(tokens_);
  343. LogCall("Parse::Parse", [&] {
  344. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  345. });
  346. if (options_.dump_parse_tree && IncludeInDumps()) {
  347. consumer_->Flush();
  348. const auto& tree_and_subtrees = GetParseTreeAndSubtrees();
  349. if (options_.preorder_parse_tree) {
  350. tree_and_subtrees.PrintPreorder(driver_env_->output_stream);
  351. } else {
  352. tree_and_subtrees.Print(driver_env_->output_stream);
  353. }
  354. }
  355. if (mem_usage_) {
  356. mem_usage_->Collect("parse_tree_", *parse_tree_);
  357. }
  358. CARBON_VLOG("*** Parse::Tree ***\n{0}", parse_tree_);
  359. if (parse_tree_->has_errors()) {
  360. success_ = false;
  361. }
  362. }
  363. // Returns information needed to check this unit.
  364. auto GetCheckUnit() -> Check::Unit {
  365. CARBON_CHECK(parse_tree_);
  366. return {
  367. .value_stores = &value_stores_,
  368. .tokens = &*tokens_,
  369. .parse_tree = &*parse_tree_,
  370. .consumer = consumer_,
  371. .get_parse_tree_and_subtrees = [&]() -> const Parse::TreeAndSubtrees& {
  372. return GetParseTreeAndSubtrees();
  373. },
  374. .sem_ir = &sem_ir_};
  375. }
  376. // Runs post-check logic. Returns true if checking succeeded for the IR.
  377. auto PostCheck() -> void {
  378. CARBON_CHECK(sem_ir_);
  379. // We've finished all steps that can produce diagnostics. Emit the
  380. // diagnostics now, so that the developer sees them sooner and doesn't need
  381. // to wait for code generation.
  382. consumer_->Flush();
  383. if (mem_usage_) {
  384. mem_usage_->Collect("sem_ir_", *sem_ir_);
  385. }
  386. if (options_.dump_raw_sem_ir && IncludeInDumps()) {
  387. CARBON_VLOG("*** Raw SemIR::File ***\n{0}\n", *sem_ir_);
  388. sem_ir_->Print(driver_env_->output_stream, options_.builtin_sem_ir);
  389. if (options_.dump_sem_ir) {
  390. driver_env_->output_stream << "\n";
  391. }
  392. }
  393. bool print = options_.dump_sem_ir && IncludeInDumps();
  394. if (vlog_stream_ || print) {
  395. SemIR::Formatter formatter(*tokens_, *parse_tree_, *sem_ir_);
  396. if (vlog_stream_) {
  397. CARBON_VLOG("*** SemIR::File ***\n");
  398. formatter.Print(*vlog_stream_);
  399. }
  400. if (print) {
  401. formatter.Print(driver_env_->output_stream);
  402. }
  403. }
  404. if (sem_ir_->has_errors()) {
  405. success_ = false;
  406. }
  407. }
  408. // Lower SemIR to LLVM IR.
  409. auto RunLower(const Check::SemIRDiagnosticConverter& converter) -> void {
  410. CARBON_CHECK(sem_ir_);
  411. LogCall("Lower::LowerToLLVM", [&] {
  412. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  413. // TODO: Consider disabling instruction naming by default if we're not
  414. // producing textual LLVM IR.
  415. SemIR::InstNamer inst_namer(*tokens_, *parse_tree_, *sem_ir_);
  416. module_ = Lower::LowerToLLVM(*llvm_context_, options_.include_debug_info,
  417. converter, input_filename_, *sem_ir_,
  418. &inst_namer, vlog_stream_);
  419. });
  420. if (vlog_stream_) {
  421. CARBON_VLOG("*** llvm::Module ***\n");
  422. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  423. /*ShouldPreserveUseListOrder=*/false,
  424. /*IsForDebug=*/true);
  425. }
  426. if (options_.dump_llvm_ir && IncludeInDumps()) {
  427. module_->print(driver_env_->output_stream, /*AAW=*/nullptr,
  428. /*ShouldPreserveUseListOrder=*/true);
  429. }
  430. }
  431. auto RunCodeGen() -> void {
  432. CARBON_CHECK(module_);
  433. LogCall("CodeGen", [&] { success_ = RunCodeGenHelper(); });
  434. }
  435. // Runs post-compile logic. This is always called, and called after all other
  436. // actions on the CompilationUnit.
  437. auto PostCompile() -> void {
  438. if (options_.dump_shared_values && IncludeInDumps()) {
  439. Yaml::Print(driver_env_->output_stream,
  440. value_stores_.OutputYaml(input_filename_));
  441. }
  442. if (mem_usage_) {
  443. mem_usage_->Collect("value_stores_", value_stores_);
  444. Yaml::Print(driver_env_->output_stream,
  445. mem_usage_->OutputYaml(input_filename_));
  446. }
  447. // The diagnostics consumer must be flushed before compilation artifacts are
  448. // destructed, because diagnostics can refer to their state.
  449. consumer_->Flush();
  450. }
  451. // Flushes diagnostics, specifically as part of generating stack trace
  452. // information.
  453. auto FlushForStackTrace() -> void { consumer_->Flush(); }
  454. auto input_filename() -> llvm::StringRef { return input_filename_; }
  455. auto success() -> bool { return success_; }
  456. auto has_source() -> bool { return source_.has_value(); }
  457. private:
  458. // Do codegen. Returns true on success.
  459. auto RunCodeGenHelper() -> bool {
  460. std::optional<CodeGen> codegen = CodeGen::Make(
  461. *module_, options_.codegen_options.target, driver_env_->error_stream);
  462. if (!codegen) {
  463. return false;
  464. }
  465. if (vlog_stream_) {
  466. CARBON_VLOG("*** Assembly ***\n");
  467. codegen->EmitAssembly(*vlog_stream_);
  468. }
  469. if (options_.output_filename == "-") {
  470. // TODO: the output file name, forcing object output, and requesting
  471. // textual assembly output are all somewhat linked flags. We should add
  472. // some validation that they are used correctly.
  473. if (options_.force_obj_output) {
  474. if (!codegen->EmitObject(driver_env_->output_stream)) {
  475. return false;
  476. }
  477. } else {
  478. if (!codegen->EmitAssembly(driver_env_->output_stream)) {
  479. return false;
  480. }
  481. }
  482. } else {
  483. llvm::SmallString<256> output_filename = options_.output_filename;
  484. if (output_filename.empty()) {
  485. if (!source_->is_regular_file()) {
  486. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  487. driver_env_->error_stream
  488. << "error: output file name must be specified for input '"
  489. << input_filename_ << "' that is not a regular file\n";
  490. return false;
  491. }
  492. output_filename = input_filename_;
  493. llvm::sys::path::replace_extension(output_filename,
  494. options_.asm_output ? ".s" : ".o");
  495. } else {
  496. // TODO: Handle the case where multiple input files were specified
  497. // along with an output file name. That should either be an error or
  498. // should produce a single LLVM IR module containing all inputs.
  499. // Currently each unit overwrites the output from the previous one in
  500. // this case.
  501. }
  502. CARBON_VLOG("Writing output to: {0}\n", output_filename);
  503. std::error_code ec;
  504. llvm::raw_fd_ostream output_file(output_filename, ec,
  505. llvm::sys::fs::OF_None);
  506. if (ec) {
  507. driver_env_->error_stream << "error: could not open output file '"
  508. << output_filename << "': " << ec.message()
  509. << "\n";
  510. return false;
  511. }
  512. if (options_.asm_output) {
  513. if (!codegen->EmitAssembly(output_file)) {
  514. return false;
  515. }
  516. } else {
  517. if (!codegen->EmitObject(output_file)) {
  518. return false;
  519. }
  520. }
  521. }
  522. return true;
  523. }
  524. // The TreeAndSubtrees is mainly used for debugging and diagnostics, and has
  525. // significant overhead. Avoid constructing it when unused.
  526. auto GetParseTreeAndSubtrees() -> const Parse::TreeAndSubtrees& {
  527. if (!parse_tree_and_subtrees_) {
  528. parse_tree_and_subtrees_ = Parse::TreeAndSubtrees(*tokens_, *parse_tree_);
  529. if (mem_usage_) {
  530. mem_usage_->Collect("parse_tree_and_subtrees_",
  531. *parse_tree_and_subtrees_);
  532. }
  533. }
  534. return *parse_tree_and_subtrees_;
  535. }
  536. // Wraps a call with log statements to indicate start and end.
  537. auto LogCall(llvm::StringLiteral label, llvm::function_ref<void()> fn)
  538. -> void {
  539. CARBON_VLOG("*** {0}: {1} ***\n", label, input_filename_);
  540. fn();
  541. CARBON_VLOG("*** {0} done ***\n", label);
  542. }
  543. // Returns true if the file can be dumped.
  544. auto IncludeInDumps() const -> bool {
  545. return options_.exclude_dump_file_prefix.empty() ||
  546. !input_filename_.starts_with(options_.exclude_dump_file_prefix);
  547. }
  548. DriverEnv* driver_env_;
  549. SharedValueStores value_stores_;
  550. const CompileOptions& options_;
  551. std::string input_filename_;
  552. // Copied from driver_ for CARBON_VLOG.
  553. llvm::raw_pwrite_stream* vlog_stream_;
  554. // Diagnostics are sent to consumer_, with optional sorting.
  555. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  556. DiagnosticConsumer* consumer_;
  557. bool success_ = true;
  558. // Tracks memory usage of the compile.
  559. std::optional<MemUsage> mem_usage_;
  560. // These are initialized as steps are run.
  561. std::optional<SourceBuffer> source_;
  562. std::optional<Lex::TokenizedBuffer> tokens_;
  563. std::optional<Parse::Tree> parse_tree_;
  564. std::optional<Parse::TreeAndSubtrees> parse_tree_and_subtrees_;
  565. std::optional<SemIR::File> sem_ir_;
  566. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  567. std::unique_ptr<llvm::Module> module_;
  568. };
  569. } // namespace
  570. auto CompileSubcommand::Run(DriverEnv& driver_env) -> DriverResult {
  571. if (!ValidateOptions(driver_env)) {
  572. return {.success = false};
  573. }
  574. // Find the files comprising the prelude if we are importing it.
  575. // TODO: Replace this with a search for library api files in a
  576. // package-specific search path based on the library name.
  577. llvm::SmallVector<std::string> prelude;
  578. if (options_.prelude_import &&
  579. options_.phase >= CompileOptions::Phase::Check) {
  580. if (auto find = driver_env.installation->ReadPreludeManifest(); find.ok()) {
  581. prelude = std::move(*find);
  582. } else {
  583. driver_env.error_stream << "error: " << find.error() << "\n";
  584. return {.success = false};
  585. }
  586. }
  587. // Prepare CompilationUnits before building scope exit handlers.
  588. StreamDiagnosticConsumer stream_consumer(driver_env.error_stream);
  589. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  590. units.reserve(prelude.size() + options_.input_filenames.size());
  591. // Add the prelude files.
  592. for (const auto& input_filename : prelude) {
  593. units.push_back(std::make_unique<CompilationUnit>(
  594. driver_env, options_, &stream_consumer, input_filename));
  595. }
  596. // Add the input source files.
  597. for (const auto& input_filename : options_.input_filenames) {
  598. units.push_back(std::make_unique<CompilationUnit>(
  599. driver_env, options_, &stream_consumer, input_filename));
  600. }
  601. auto on_exit = llvm::make_scope_exit([&]() {
  602. // Finish compilation units. This flushes their diagnostics in the order in
  603. // which they were specified on the command line.
  604. for (auto& unit : units) {
  605. unit->PostCompile();
  606. }
  607. stream_consumer.Flush();
  608. });
  609. PrettyStackTraceFunction flush_on_crash([&](llvm::raw_ostream& out) {
  610. // When crashing, flush diagnostics. If sorting diagnostics, they can be
  611. // redirected to the crash stream; if streaming, the original stream is
  612. // flushed.
  613. // TODO: Eventually we'll want to limit the count.
  614. if (options_.stream_errors) {
  615. out << "Flushing diagnostics\n";
  616. } else {
  617. out << "Pending diagnostics:\n";
  618. stream_consumer.set_stream(&out);
  619. }
  620. for (auto& unit : units) {
  621. unit->FlushForStackTrace();
  622. }
  623. stream_consumer.Flush();
  624. stream_consumer.set_stream(&driver_env.error_stream);
  625. });
  626. // Returns a DriverResult object. Called whenever Compile returns.
  627. auto make_result = [&]() {
  628. DriverResult result = {.success = true};
  629. for (const auto& unit : units) {
  630. result.success &= unit->success();
  631. result.per_file_success.push_back(
  632. {unit->input_filename().str(), unit->success()});
  633. }
  634. return result;
  635. };
  636. // Lex.
  637. for (auto& unit : units) {
  638. unit->RunLex();
  639. }
  640. if (options_.phase == CompileOptions::Phase::Lex) {
  641. return make_result();
  642. }
  643. // Parse and check phases examine `has_source` because they want to proceed if
  644. // lex failed, but not if source doesn't exist. Later steps are skipped if
  645. // anything failed, so don't need this.
  646. // Parse.
  647. for (auto& unit : units) {
  648. if (unit->has_source()) {
  649. unit->RunParse();
  650. }
  651. }
  652. if (options_.phase == CompileOptions::Phase::Parse) {
  653. return make_result();
  654. }
  655. // Check.
  656. SharedValueStores builtin_value_stores;
  657. llvm::SmallVector<Check::Unit> check_units;
  658. for (auto& unit : units) {
  659. if (unit->has_source()) {
  660. check_units.push_back(unit->GetCheckUnit());
  661. }
  662. }
  663. llvm::SmallVector<Parse::NodeLocConverter> node_converters;
  664. node_converters.reserve(check_units.size());
  665. for (auto& unit : check_units) {
  666. node_converters.emplace_back(unit.tokens, unit.tokens->source().filename(),
  667. unit.get_parse_tree_and_subtrees);
  668. }
  669. CARBON_VLOG_TO(driver_env.vlog_stream, "*** Check::CheckParseTrees ***\n");
  670. Check::CheckParseTrees(check_units, node_converters, options_.prelude_import,
  671. driver_env.vlog_stream);
  672. CARBON_VLOG_TO(driver_env.vlog_stream,
  673. "*** Check::CheckParseTrees done ***\n");
  674. for (auto& unit : units) {
  675. if (unit->has_source()) {
  676. unit->PostCheck();
  677. }
  678. }
  679. if (options_.phase == CompileOptions::Phase::Check) {
  680. return make_result();
  681. }
  682. // Unlike previous steps, errors block further progress.
  683. if (std::any_of(units.begin(), units.end(),
  684. [&](const auto& unit) { return !unit->success(); })) {
  685. CARBON_VLOG_TO(driver_env.vlog_stream,
  686. "*** Stopping before lowering due to errors ***");
  687. return make_result();
  688. }
  689. // Lower.
  690. for (const auto& unit : units) {
  691. Check::SemIRDiagnosticConverter converter(node_converters,
  692. &**unit->GetCheckUnit().sem_ir);
  693. unit->RunLower(converter);
  694. }
  695. if (options_.phase == CompileOptions::Phase::Lower) {
  696. return make_result();
  697. }
  698. CARBON_CHECK(options_.phase == CompileOptions::Phase::CodeGen,
  699. "CodeGen should be the last stage");
  700. // Codegen.
  701. for (auto& unit : units) {
  702. unit->RunCodeGen();
  703. }
  704. return make_result();
  705. }
  706. } // namespace Carbon