driver.cpp 32 KB

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