driver.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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/driver.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <optional>
  8. #include "common/command_line.h"
  9. #include "common/version.h"
  10. #include "common/vlog.h"
  11. #include "llvm/ADT/ArrayRef.h"
  12. #include "llvm/ADT/ScopeExit.h"
  13. #include "llvm/ADT/StringExtras.h"
  14. #include "llvm/ADT/StringRef.h"
  15. #include "llvm/IR/LLVMContext.h"
  16. #include "llvm/Support/Path.h"
  17. #include "llvm/TargetParser/Host.h"
  18. #include "llvm/TargetParser/Triple.h"
  19. #include "toolchain/base/value_store.h"
  20. #include "toolchain/check/check.h"
  21. #include "toolchain/codegen/codegen.h"
  22. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  23. #include "toolchain/driver/clang_runner.h"
  24. #include "toolchain/lex/lex.h"
  25. #include "toolchain/lower/lower.h"
  26. #include "toolchain/parse/parse.h"
  27. #include "toolchain/sem_ir/formatter.h"
  28. #include "toolchain/sem_ir/inst_namer.h"
  29. #include "toolchain/source/source_buffer.h"
  30. namespace Carbon {
  31. auto Driver::FindPreludeFiles(llvm::StringRef core_package_dir,
  32. llvm::raw_ostream& error_stream)
  33. -> llvm::SmallVector<std::string> {
  34. llvm::SmallVector<std::string> result;
  35. // Include <data>/core/prelude.carbon, which is the entry point into the
  36. // prelude.
  37. {
  38. llvm::SmallString<256> prelude_file(core_package_dir);
  39. llvm::sys::path::append(prelude_file, llvm::sys::path::Style::posix,
  40. "prelude.carbon");
  41. result.push_back(prelude_file.str().str());
  42. }
  43. // Glob for <data>/core/prelude/**/*.carbon and add all the files we find.
  44. llvm::SmallString<256> prelude_dir(core_package_dir);
  45. llvm::sys::path::append(prelude_dir, llvm::sys::path::Style::posix,
  46. "prelude");
  47. std::error_code ec;
  48. for (llvm::sys::fs::recursive_directory_iterator prelude_files_it(
  49. prelude_dir, ec, /*follow_symlinks=*/false);
  50. prelude_files_it != llvm::sys::fs::recursive_directory_iterator();
  51. prelude_files_it.increment(ec)) {
  52. if (ec) {
  53. error_stream << "ERROR: Could not find prelude: " << ec.message() << "\n";
  54. result.clear();
  55. return result;
  56. }
  57. auto prelude_file = prelude_files_it->path();
  58. if (llvm::sys::path::extension(prelude_file) == ".carbon") {
  59. result.push_back(prelude_file);
  60. }
  61. }
  62. return result;
  63. }
  64. struct Driver::CodegenOptions {
  65. void Build(CommandLine::CommandBuilder& b) {
  66. b.AddStringOption(
  67. {
  68. .name = "target",
  69. .help = R"""(
  70. Select a target platform. Uses the LLVM target syntax. Also known as a "triple"
  71. for historical reasons.
  72. This corresponds to the `target` flag to Clang and accepts the same strings
  73. documented there:
  74. https://clang.llvm.org/docs/CrossCompilation.html#target-triple
  75. )""",
  76. },
  77. [&](auto& arg_b) {
  78. arg_b.Default(host);
  79. arg_b.Set(&target);
  80. });
  81. }
  82. std::string host = llvm::sys::getDefaultTargetTriple();
  83. llvm::StringRef target;
  84. };
  85. struct Driver::CompileOptions {
  86. static constexpr CommandLine::CommandInfo Info = {
  87. .name = "compile",
  88. .help = R"""(
  89. Compile Carbon source code.
  90. This subcommand runs the Carbon compiler over input source code, checking it for
  91. errors and producing the requested output.
  92. Error messages are written to the standard error stream.
  93. Different phases of the compiler can be selected to run, and intermediate state
  94. can be written to standard output as these phases progress.
  95. )""",
  96. };
  97. enum class Phase : int8_t {
  98. Lex,
  99. Parse,
  100. Check,
  101. Lower,
  102. CodeGen,
  103. };
  104. friend auto operator<<(llvm::raw_ostream& out, Phase phase)
  105. -> llvm::raw_ostream& {
  106. switch (phase) {
  107. case Phase::Lex:
  108. out << "lex";
  109. break;
  110. case Phase::Parse:
  111. out << "parse";
  112. break;
  113. case Phase::Check:
  114. out << "check";
  115. break;
  116. case Phase::Lower:
  117. out << "lower";
  118. break;
  119. case Phase::CodeGen:
  120. out << "codegen";
  121. break;
  122. }
  123. return out;
  124. }
  125. void Build(CommandLine::CommandBuilder& b, CodegenOptions& codegen_options) {
  126. b.AddStringPositionalArg(
  127. {
  128. .name = "FILE",
  129. .help = R"""(
  130. The input Carbon source file to compile.
  131. )""",
  132. },
  133. [&](auto& arg_b) {
  134. arg_b.Required(true);
  135. arg_b.Append(&input_filenames);
  136. });
  137. b.AddOneOfOption(
  138. {
  139. .name = "phase",
  140. .help = R"""(
  141. Selects the compilation phase to run. These phases are always run in sequence,
  142. so every phase before the one selected will also be run. The default is to
  143. compile to machine code.
  144. )""",
  145. },
  146. [&](auto& arg_b) {
  147. arg_b.SetOneOf(
  148. {
  149. arg_b.OneOfValue("lex", Phase::Lex),
  150. arg_b.OneOfValue("parse", Phase::Parse),
  151. arg_b.OneOfValue("check", Phase::Check),
  152. arg_b.OneOfValue("lower", Phase::Lower),
  153. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  154. },
  155. &phase);
  156. });
  157. // TODO: Rearrange the code setting this option and two related ones to
  158. // allow them to reference each other instead of hard-coding their names.
  159. b.AddStringOption(
  160. {
  161. .name = "output",
  162. .value_name = "FILE",
  163. .help = R"""(
  164. The output filename for codegen.
  165. When this is a file name, either textual assembly or a binary object will be
  166. written to it based on the flag `--asm-output`. The default is to write a binary
  167. object file.
  168. Passing `--output=-` will write the output to stdout. In that case, the flag
  169. `--asm-output` is ignored and the output defaults to textual assembly. Binary
  170. object output can be forced by enabling `--force-obj-output`.
  171. )""",
  172. },
  173. [&](auto& arg_b) { arg_b.Set(&output_filename); });
  174. // Include the common code generation options at this point to render it
  175. // after the more common options above, but before the more unusual options
  176. // below.
  177. codegen_options.Build(b);
  178. b.AddFlag(
  179. {
  180. .name = "asm-output",
  181. .help = R"""(
  182. Write textual assembly rather than a binary object file to the code generation
  183. output.
  184. This flag only applies when writing to a file. When writing to stdout, the
  185. default is textual assembly and this flag is ignored.
  186. )""",
  187. },
  188. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  189. b.AddFlag(
  190. {
  191. .name = "force-obj-output",
  192. .help = R"""(
  193. Force binary object output, even with `--output=-`.
  194. When `--output=-` is set, the default is textual assembly; this forces printing
  195. of a binary object file instead. Ignored for other `--output` values.
  196. )""",
  197. },
  198. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  199. b.AddFlag(
  200. {
  201. .name = "stream-errors",
  202. .help = R"""(
  203. Stream error messages to stderr as they are generated rather than sorting them
  204. and displaying them in source order.
  205. )""",
  206. },
  207. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  208. b.AddFlag(
  209. {
  210. .name = "dump-shared-values",
  211. .help = R"""(
  212. Dumps shared values. These aren't owned by any particular file or phase.
  213. )""",
  214. },
  215. [&](auto& arg_b) { arg_b.Set(&dump_shared_values); });
  216. b.AddFlag(
  217. {
  218. .name = "dump-tokens",
  219. .help = R"""(
  220. Dump the tokens to stdout when lexed.
  221. )""",
  222. },
  223. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  224. b.AddFlag(
  225. {
  226. .name = "dump-parse-tree",
  227. .help = R"""(
  228. Dump the parse tree to stdout when parsed.
  229. )""",
  230. },
  231. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  232. b.AddFlag(
  233. {
  234. .name = "preorder-parse-tree",
  235. .help = R"""(
  236. When dumping the parse tree, reorder it so that it is in preorder rather than
  237. postorder.
  238. )""",
  239. },
  240. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  241. b.AddFlag(
  242. {
  243. .name = "dump-raw-sem-ir",
  244. .help = R"""(
  245. Dump the raw JSON structure of SemIR to stdout when built.
  246. )""",
  247. },
  248. [&](auto& arg_b) { arg_b.Set(&dump_raw_sem_ir); });
  249. b.AddFlag(
  250. {
  251. .name = "dump-sem-ir",
  252. .help = R"""(
  253. Dump the SemIR to stdout when built.
  254. )""",
  255. },
  256. [&](auto& arg_b) { arg_b.Set(&dump_sem_ir); });
  257. b.AddFlag(
  258. {
  259. .name = "builtin-sem-ir",
  260. .help = R"""(
  261. Include the SemIR for builtins when dumping it.
  262. )""",
  263. },
  264. [&](auto& arg_b) { arg_b.Set(&builtin_sem_ir); });
  265. b.AddFlag(
  266. {
  267. .name = "dump-llvm-ir",
  268. .help = R"""(
  269. Dump the LLVM IR to stdout after lowering.
  270. )""",
  271. },
  272. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  273. b.AddFlag(
  274. {
  275. .name = "dump-asm",
  276. .help = R"""(
  277. Dump the generated assembly to stdout after codegen.
  278. )""",
  279. },
  280. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  281. b.AddFlag(
  282. {
  283. .name = "prelude-import",
  284. .help = R"""(
  285. Whether to use the implicit prelude import. Enabled by default.
  286. )""",
  287. },
  288. [&](auto& arg_b) {
  289. arg_b.Default(true);
  290. arg_b.Set(&prelude_import);
  291. });
  292. b.AddStringOption(
  293. {
  294. .name = "exclude-dump-file-prefix",
  295. .value_name = "PREFIX",
  296. .help = R"""(
  297. Excludes files with the given prefix from dumps.
  298. )""",
  299. },
  300. [&](auto& arg_b) { arg_b.Set(&exclude_dump_file_prefix); });
  301. }
  302. Phase phase;
  303. llvm::StringRef output_filename;
  304. llvm::SmallVector<llvm::StringRef> input_filenames;
  305. bool asm_output = false;
  306. bool force_obj_output = false;
  307. bool dump_shared_values = false;
  308. bool dump_tokens = false;
  309. bool dump_parse_tree = false;
  310. bool dump_raw_sem_ir = false;
  311. bool dump_sem_ir = false;
  312. bool dump_llvm_ir = false;
  313. bool dump_asm = false;
  314. bool stream_errors = false;
  315. bool preorder_parse_tree = false;
  316. bool builtin_sem_ir = false;
  317. bool prelude_import = false;
  318. llvm::StringRef exclude_dump_file_prefix;
  319. };
  320. struct Driver::LinkOptions {
  321. static constexpr CommandLine::CommandInfo Info = {
  322. .name = "link",
  323. .help = R"""(
  324. Link Carbon executables.
  325. This subcommand links Carbon executables by combining object files.
  326. TODO: Support linking binary libraries, both archives and shared libraries.
  327. TODO: Support linking against binary libraries.
  328. )""",
  329. };
  330. void Build(CommandLine::CommandBuilder& b, CodegenOptions& codegen_options) {
  331. b.AddStringPositionalArg(
  332. {
  333. .name = "OBJECT_FILE",
  334. .help = R"""(
  335. The input object files.
  336. )""",
  337. },
  338. [&](auto& arg_b) {
  339. arg_b.Required(true);
  340. arg_b.Append(&object_filenames);
  341. });
  342. b.AddStringOption(
  343. {
  344. .name = "output",
  345. .value_name = "FILE",
  346. .help = R"""(
  347. The linked file name. The output is always a linked binary.
  348. )""",
  349. },
  350. [&](auto& arg_b) {
  351. arg_b.Required(true);
  352. arg_b.Set(&output_filename);
  353. });
  354. codegen_options.Build(b);
  355. }
  356. llvm::StringRef output_filename;
  357. llvm::SmallVector<llvm::StringRef> object_filenames;
  358. };
  359. struct Driver::Options {
  360. static const CommandLine::CommandInfo Info;
  361. enum class Subcommand : int8_t {
  362. Compile,
  363. Link,
  364. };
  365. void Build(CommandLine::CommandBuilder& b) {
  366. b.AddFlag(
  367. {
  368. .name = "verbose",
  369. .short_name = "v",
  370. .help = "Enable verbose logging to the stderr stream.",
  371. },
  372. [&](CommandLine::FlagBuilder& arg_b) { arg_b.Set(&verbose); });
  373. b.AddSubcommand(CompileOptions::Info,
  374. [&](CommandLine::CommandBuilder& sub_b) {
  375. compile_options.Build(sub_b, codegen_options);
  376. sub_b.Do([&] { subcommand = Subcommand::Compile; });
  377. });
  378. b.AddSubcommand(LinkOptions::Info, [&](CommandLine::CommandBuilder& sub_b) {
  379. link_options.Build(sub_b, codegen_options);
  380. sub_b.Do([&] { subcommand = Subcommand::Link; });
  381. });
  382. b.RequiresSubcommand();
  383. }
  384. bool verbose;
  385. Subcommand subcommand;
  386. CodegenOptions codegen_options;
  387. CompileOptions compile_options;
  388. LinkOptions link_options;
  389. };
  390. // Note that this is not constexpr so that it can include information generated
  391. // in separate translation units and potentially overridden at link time in the
  392. // version string.
  393. const CommandLine::CommandInfo Driver::Options::Info = {
  394. .name = "carbon",
  395. .version = Version::ToolchainInfo,
  396. .help = R"""(
  397. This is the unified Carbon Language toolchain driver. Its subcommands provide
  398. all of the core behavior of the toolchain, including compilation, linking, and
  399. developer tools. Each of these has its own subcommand, and you can pass a
  400. specific subcommand to the `help` subcommand to get details about its usage.
  401. )""",
  402. .help_epilogue = R"""(
  403. For questions, issues, or bug reports, please use our GitHub project:
  404. https://github.com/carbon-language/carbon-lang
  405. )""",
  406. };
  407. auto Driver::ParseArgs(llvm::ArrayRef<llvm::StringRef> args, Options& options)
  408. -> CommandLine::ParseResult {
  409. return CommandLine::Parse(
  410. args, output_stream_, error_stream_, Options::Info,
  411. [&](CommandLine::CommandBuilder& b) { options.Build(b); });
  412. }
  413. auto Driver::RunCommand(llvm::ArrayRef<llvm::StringRef> args) -> RunResult {
  414. Options options;
  415. CommandLine::ParseResult result = ParseArgs(args, options);
  416. if (result == CommandLine::ParseResult::Error) {
  417. return {.success = false};
  418. } else if (result == CommandLine::ParseResult::MetaSuccess) {
  419. return {.success = true};
  420. }
  421. if (options.verbose) {
  422. // Note this implies streamed output in order to interleave.
  423. vlog_stream_ = &error_stream_;
  424. }
  425. switch (options.subcommand) {
  426. case Options::Subcommand::Compile:
  427. return Compile(options.compile_options, options.codegen_options);
  428. case Options::Subcommand::Link:
  429. return Link(options.link_options, options.codegen_options);
  430. }
  431. llvm_unreachable("All subcommands handled!");
  432. }
  433. auto Driver::ValidateCompileOptions(const CompileOptions& options) const
  434. -> bool {
  435. using Phase = CompileOptions::Phase;
  436. switch (options.phase) {
  437. case Phase::Lex:
  438. if (options.dump_parse_tree) {
  439. error_stream_ << "ERROR: Requested dumping the parse tree but compile "
  440. "phase is limited to '"
  441. << options.phase << "'.\n";
  442. return false;
  443. }
  444. [[fallthrough]];
  445. case Phase::Parse:
  446. if (options.dump_sem_ir) {
  447. error_stream_ << "ERROR: Requested dumping the SemIR but compile phase "
  448. "is limited to '"
  449. << options.phase << "'.\n";
  450. return false;
  451. }
  452. [[fallthrough]];
  453. case Phase::Check:
  454. if (options.dump_llvm_ir) {
  455. error_stream_ << "ERROR: Requested dumping the LLVM IR but compile "
  456. "phase is limited to '"
  457. << options.phase << "'.\n";
  458. return false;
  459. }
  460. [[fallthrough]];
  461. case Phase::Lower:
  462. case Phase::CodeGen:
  463. // Everything can be dumped in these phases.
  464. break;
  465. }
  466. return true;
  467. }
  468. // Ties together information for a file being compiled.
  469. class Driver::CompilationUnit {
  470. public:
  471. explicit CompilationUnit(Driver* driver, const CompileOptions& options,
  472. const CodegenOptions& codegen_options,
  473. DiagnosticConsumer* consumer,
  474. llvm::StringRef input_filename)
  475. : driver_(driver),
  476. options_(options),
  477. codegen_options_(codegen_options),
  478. input_filename_(input_filename),
  479. vlog_stream_(driver_->vlog_stream_) {
  480. if (vlog_stream_ != nullptr || options_.stream_errors) {
  481. consumer_ = consumer;
  482. } else {
  483. sorting_consumer_ = SortingDiagnosticConsumer(*consumer);
  484. consumer_ = &*sorting_consumer_;
  485. }
  486. }
  487. // Loads source and lexes it. Returns true on success.
  488. auto RunLex() -> void {
  489. LogCall("SourceBuffer::MakeFromFile", [&] {
  490. if (input_filename_ == "-") {
  491. source_ = SourceBuffer::MakeFromStdin(*consumer_);
  492. } else {
  493. source_ = SourceBuffer::MakeFromFile(driver_->fs_, input_filename_,
  494. *consumer_);
  495. }
  496. });
  497. if (!source_) {
  498. success_ = false;
  499. return;
  500. }
  501. CARBON_VLOG() << "*** SourceBuffer ***\n```\n"
  502. << source_->text() << "\n```\n";
  503. LogCall("Lex::Lex",
  504. [&] { tokens_ = Lex::Lex(value_stores_, *source_, *consumer_); });
  505. if (options_.dump_tokens && IncludeInDumps()) {
  506. consumer_->Flush();
  507. driver_->output_stream_ << tokens_;
  508. }
  509. CARBON_VLOG() << "*** Lex::TokenizedBuffer ***\n" << tokens_;
  510. if (tokens_->has_errors()) {
  511. success_ = false;
  512. }
  513. }
  514. // Parses tokens. Returns true on success.
  515. auto RunParse() -> void {
  516. CARBON_CHECK(tokens_);
  517. LogCall("Parse::Parse", [&] {
  518. parse_tree_ = Parse::Parse(*tokens_, *consumer_, vlog_stream_);
  519. });
  520. if (options_.dump_parse_tree && IncludeInDumps()) {
  521. consumer_->Flush();
  522. parse_tree_->Print(driver_->output_stream_, options_.preorder_parse_tree);
  523. }
  524. CARBON_VLOG() << "*** Parse::Tree ***\n" << parse_tree_;
  525. if (parse_tree_->has_errors()) {
  526. success_ = false;
  527. }
  528. }
  529. // Returns information needed to check this unit.
  530. auto GetCheckUnit() -> Check::Unit {
  531. CARBON_CHECK(parse_tree_);
  532. return {.value_stores = &value_stores_,
  533. .tokens = &*tokens_,
  534. .parse_tree = &*parse_tree_,
  535. .consumer = consumer_,
  536. .sem_ir = &sem_ir_};
  537. }
  538. // Runs post-check logic. Returns true if checking succeeded for the IR.
  539. auto PostCheck() -> void {
  540. CARBON_CHECK(sem_ir_);
  541. // We've finished all steps that can produce diagnostics. Emit the
  542. // diagnostics now, so that the developer sees them sooner and doesn't need
  543. // to wait for code generation.
  544. consumer_->Flush();
  545. CARBON_VLOG() << "*** Raw SemIR::File ***\n" << *sem_ir_ << "\n";
  546. if (options_.dump_raw_sem_ir && IncludeInDumps()) {
  547. sem_ir_->Print(driver_->output_stream_, options_.builtin_sem_ir);
  548. if (options_.dump_sem_ir) {
  549. driver_->output_stream_ << "\n";
  550. }
  551. }
  552. if (vlog_stream_) {
  553. CARBON_VLOG() << "*** SemIR::File ***\n";
  554. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_, *vlog_stream_);
  555. }
  556. if (options_.dump_sem_ir && IncludeInDumps()) {
  557. SemIR::FormatFile(*tokens_, *parse_tree_, *sem_ir_,
  558. driver_->output_stream_);
  559. }
  560. if (sem_ir_->has_errors()) {
  561. success_ = false;
  562. }
  563. }
  564. // Lower SemIR to LLVM IR.
  565. auto RunLower() -> void {
  566. CARBON_CHECK(sem_ir_);
  567. LogCall("Lower::LowerToLLVM", [&] {
  568. llvm_context_ = std::make_unique<llvm::LLVMContext>();
  569. // TODO: Consider disabling instruction naming by default if we're not
  570. // producing textual LLVM IR.
  571. SemIR::InstNamer inst_namer(*tokens_, *parse_tree_, *sem_ir_);
  572. module_ = Lower::LowerToLLVM(*llvm_context_, input_filename_, *sem_ir_,
  573. &inst_namer, vlog_stream_);
  574. });
  575. if (vlog_stream_) {
  576. CARBON_VLOG() << "*** llvm::Module ***\n";
  577. module_->print(*vlog_stream_, /*AAW=*/nullptr,
  578. /*ShouldPreserveUseListOrder=*/false,
  579. /*IsForDebug=*/true);
  580. }
  581. if (options_.dump_llvm_ir && IncludeInDumps()) {
  582. module_->print(driver_->output_stream_, /*AAW=*/nullptr,
  583. /*ShouldPreserveUseListOrder=*/true);
  584. }
  585. }
  586. auto RunCodeGen() -> void {
  587. CARBON_CHECK(module_);
  588. LogCall("CodeGen", [&] { success_ = RunCodeGenHelper(); });
  589. }
  590. // Runs post-compile logic. This is always called, and called after all other
  591. // actions on the CompilationUnit.
  592. auto PostCompile() const -> void {
  593. if (options_.dump_shared_values && IncludeInDumps()) {
  594. Yaml::Print(driver_->output_stream_,
  595. value_stores_.OutputYaml(input_filename_));
  596. }
  597. // The diagnostics consumer must be flushed before compilation artifacts are
  598. // destructed, because diagnostics can refer to their state.
  599. consumer_->Flush();
  600. }
  601. auto input_filename() -> llvm::StringRef { return input_filename_; }
  602. auto success() -> bool { return success_; }
  603. auto has_source() -> bool { return source_.has_value(); }
  604. private:
  605. // Do codegen. Returns true on success.
  606. auto RunCodeGenHelper() -> bool {
  607. std::optional<CodeGen> codegen = CodeGen::Make(
  608. *module_, codegen_options_.target, driver_->error_stream_);
  609. if (!codegen) {
  610. return false;
  611. }
  612. if (vlog_stream_) {
  613. CARBON_VLOG() << "*** Assembly ***\n";
  614. codegen->EmitAssembly(*vlog_stream_);
  615. }
  616. if (options_.output_filename == "-") {
  617. // TODO: the output file name, forcing object output, and requesting
  618. // textual assembly output are all somewhat linked flags. We should add
  619. // some validation that they are used correctly.
  620. if (options_.force_obj_output) {
  621. if (!codegen->EmitObject(driver_->output_stream_)) {
  622. return false;
  623. }
  624. } else {
  625. if (!codegen->EmitAssembly(driver_->output_stream_)) {
  626. return false;
  627. }
  628. }
  629. } else {
  630. llvm::SmallString<256> output_filename = options_.output_filename;
  631. if (output_filename.empty()) {
  632. if (!source_->is_regular_file()) {
  633. // Don't invent file names like `-.o` or `/dev/stdin.o`.
  634. driver_->error_stream_
  635. << "ERROR: Output file name must be specified for input '"
  636. << input_filename_ << "' that is not a regular file.\n";
  637. return false;
  638. }
  639. output_filename = input_filename_;
  640. llvm::sys::path::replace_extension(output_filename,
  641. options_.asm_output ? ".s" : ".o");
  642. } else {
  643. // TODO: Handle the case where multiple input files were specified
  644. // along with an output file name. That should either be an error or
  645. // should produce a single LLVM IR module containing all inputs.
  646. // Currently each unit overwrites the output from the previous one in
  647. // this case.
  648. }
  649. CARBON_VLOG() << "Writing output to: " << output_filename << "\n";
  650. std::error_code ec;
  651. llvm::raw_fd_ostream output_file(output_filename, ec,
  652. llvm::sys::fs::OF_None);
  653. if (ec) {
  654. driver_->error_stream_ << "ERROR: Could not open output file '"
  655. << output_filename << "': " << ec.message()
  656. << "\n";
  657. return false;
  658. }
  659. if (options_.asm_output) {
  660. if (!codegen->EmitAssembly(output_file)) {
  661. return false;
  662. }
  663. } else {
  664. if (!codegen->EmitObject(output_file)) {
  665. return false;
  666. }
  667. }
  668. }
  669. return true;
  670. }
  671. // Wraps a call with log statements to indicate start and end.
  672. auto LogCall(llvm::StringLiteral label, llvm::function_ref<void()> fn)
  673. -> void {
  674. CARBON_VLOG() << "*** " << label << ": " << input_filename_ << " ***\n";
  675. fn();
  676. CARBON_VLOG() << "*** " << label << " done ***\n";
  677. }
  678. // Returns true if the file can be dumped.
  679. auto IncludeInDumps() const -> bool {
  680. return options_.exclude_dump_file_prefix.empty() ||
  681. !input_filename_.starts_with(options_.exclude_dump_file_prefix);
  682. }
  683. Driver* driver_;
  684. SharedValueStores value_stores_;
  685. const CompileOptions& options_;
  686. const CodegenOptions& codegen_options_;
  687. std::string input_filename_;
  688. // Copied from driver_ for CARBON_VLOG.
  689. llvm::raw_pwrite_stream* vlog_stream_;
  690. // Diagnostics are sent to consumer_, with optional sorting.
  691. std::optional<SortingDiagnosticConsumer> sorting_consumer_;
  692. DiagnosticConsumer* consumer_;
  693. bool success_ = true;
  694. // These are initialized as steps are run.
  695. std::optional<SourceBuffer> source_;
  696. std::optional<Lex::TokenizedBuffer> tokens_;
  697. std::optional<Parse::Tree> parse_tree_;
  698. std::optional<SemIR::File> sem_ir_;
  699. std::unique_ptr<llvm::LLVMContext> llvm_context_;
  700. std::unique_ptr<llvm::Module> module_;
  701. };
  702. auto Driver::Compile(const CompileOptions& options,
  703. const CodegenOptions& codegen_options) -> RunResult {
  704. if (!ValidateCompileOptions(options)) {
  705. return {.success = false};
  706. }
  707. // Find the files comprising the prelude if we are importing it.
  708. // TODO: Replace this with a search for library api files in a
  709. // package-specific search path based on the library name.
  710. bool want_prelude =
  711. options.prelude_import && options.phase >= CompileOptions::Phase::Check;
  712. auto prelude = want_prelude ? FindPreludeFiles(installation_->core_package(),
  713. error_stream_)
  714. : llvm::SmallVector<std::string>{};
  715. if (want_prelude && prelude.empty()) {
  716. return {.success = false};
  717. }
  718. // Prepare CompilationUnits before building scope exit handlers.
  719. StreamDiagnosticConsumer stream_consumer(error_stream_);
  720. llvm::SmallVector<std::unique_ptr<CompilationUnit>> units;
  721. units.reserve(prelude.size() + options.input_filenames.size());
  722. // Add the prelude files.
  723. for (const auto& input_filename : prelude) {
  724. units.push_back(std::make_unique<CompilationUnit>(
  725. this, options, codegen_options, &stream_consumer, input_filename));
  726. }
  727. // Add the input source files.
  728. for (const auto& input_filename : options.input_filenames) {
  729. units.push_back(std::make_unique<CompilationUnit>(
  730. this, options, codegen_options, &stream_consumer, input_filename));
  731. }
  732. auto on_exit = llvm::make_scope_exit([&]() {
  733. // Finish compilation units. This flushes their diagnostics in the order in
  734. // which they were specified on the command line.
  735. for (auto& unit : units) {
  736. unit->PostCompile();
  737. }
  738. stream_consumer.Flush();
  739. });
  740. // Returns a RunResult object. Called whenever Compile returns.
  741. auto make_result = [&]() {
  742. RunResult result = {.success = true};
  743. for (const auto& unit : units) {
  744. result.success &= unit->success();
  745. result.per_file_success.push_back(
  746. {unit->input_filename().str(), unit->success()});
  747. }
  748. return result;
  749. };
  750. // Lex.
  751. for (auto& unit : units) {
  752. unit->RunLex();
  753. }
  754. if (options.phase == CompileOptions::Phase::Lex) {
  755. return make_result();
  756. }
  757. // Parse and check phases examine `has_source` because they want to proceed if
  758. // lex failed, but not if source doesn't exist. Later steps are skipped if
  759. // anything failed, so don't need this.
  760. // Parse.
  761. for (auto& unit : units) {
  762. if (unit->has_source()) {
  763. unit->RunParse();
  764. }
  765. }
  766. if (options.phase == CompileOptions::Phase::Parse) {
  767. return make_result();
  768. }
  769. // Check.
  770. SharedValueStores builtin_value_stores;
  771. llvm::SmallVector<Check::Unit> check_units;
  772. for (auto& unit : units) {
  773. if (unit->has_source()) {
  774. check_units.push_back(unit->GetCheckUnit());
  775. }
  776. }
  777. CARBON_VLOG() << "*** Check::CheckParseTrees ***\n";
  778. Check::CheckParseTrees(llvm::MutableArrayRef(check_units),
  779. options.prelude_import, vlog_stream_);
  780. CARBON_VLOG() << "*** Check::CheckParseTrees done ***\n";
  781. for (auto& unit : units) {
  782. if (unit->has_source()) {
  783. unit->PostCheck();
  784. }
  785. }
  786. if (options.phase == CompileOptions::Phase::Check) {
  787. return make_result();
  788. }
  789. // Unlike previous steps, errors block further progress.
  790. if (std::any_of(units.begin(), units.end(),
  791. [&](const auto& unit) { return !unit->success(); })) {
  792. CARBON_VLOG() << "*** Stopping before lowering due to errors ***";
  793. return make_result();
  794. }
  795. // Lower.
  796. for (auto& unit : units) {
  797. unit->RunLower();
  798. }
  799. if (options.phase == CompileOptions::Phase::Lower) {
  800. return make_result();
  801. }
  802. CARBON_CHECK(options.phase == CompileOptions::Phase::CodeGen)
  803. << "CodeGen should be the last stage";
  804. // Codegen.
  805. for (auto& unit : units) {
  806. unit->RunCodeGen();
  807. }
  808. return make_result();
  809. }
  810. static void AddOSFlags(llvm::StringRef target,
  811. llvm::SmallVectorImpl<llvm::StringRef>& args) {
  812. llvm::Triple triple(target);
  813. switch (triple.getOS()) {
  814. case llvm::Triple::Darwin:
  815. case llvm::Triple::MacOSX:
  816. // On macOS we need to set the sysroot to a viable SDK. Currently, this
  817. // hard codes the path to be the unversioned symlink. The prefix is also
  818. // hard coded in Homebrew and so this seems likely to work reasonably
  819. // well. Homebrew and I suspect the Xcode Clang both have this hard coded
  820. // at build time, so this seems reasonably safe but we can revisit if/when
  821. // needed.
  822. args.push_back(
  823. "--sysroot=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk");
  824. // We also need to insist on a modern linker, otherwise the driver tries
  825. // too old and deprecated flags. The specific number here comes from an
  826. // inspection of the Clang driver source code to understand where features
  827. // were enabled, and this appears to be the latest version to control
  828. // driver behavior.
  829. //
  830. // TODO: We should replace this with use of `lld` eventually.
  831. args.push_back("-mlinker-version=705");
  832. break;
  833. default:
  834. // By default, just let the Clang driver handle everything.
  835. break;
  836. }
  837. }
  838. auto Driver::Link(const LinkOptions& options,
  839. const CodegenOptions& codegen_options) -> RunResult {
  840. // TODO: Currently we use the Clang driver to link. This works well on Unix
  841. // OSes but we likely need to directly build logic to invoke `link.exe` on
  842. // Windows where `cl.exe` doesn't typically cover that logic.
  843. // Use a reasonably large small vector here to minimize allocations. We expect
  844. // to link reasonably large numbers of object files.
  845. llvm::SmallVector<llvm::StringRef, 128> clang_args;
  846. // We link using a C++ mode of the driver.
  847. clang_args.push_back("--driver-mode=g++");
  848. // Use LLD, which we provide in our install directory, for linking.
  849. clang_args.push_back("-fuse-ld=lld");
  850. // Add OS-specific flags based on the target.
  851. AddOSFlags(codegen_options.target, clang_args);
  852. clang_args.push_back("-o");
  853. clang_args.push_back(options.output_filename);
  854. clang_args.append(options.object_filenames.begin(),
  855. options.object_filenames.end());
  856. ClangRunner runner(installation_, codegen_options.target, vlog_stream_);
  857. return {.success = runner.Run(clang_args)};
  858. }
  859. } // namespace Carbon