driver.cpp 33 KB

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