driver.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 "common/command_line.h"
  6. #include "common/vlog.h"
  7. #include "llvm/ADT/ArrayRef.h"
  8. #include "llvm/ADT/ScopeExit.h"
  9. #include "llvm/ADT/StringExtras.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/ADT/StringSwitch.h"
  12. #include "llvm/IR/LLVMContext.h"
  13. #include "llvm/Support/Format.h"
  14. #include "llvm/Support/Path.h"
  15. #include "llvm/TargetParser/Host.h"
  16. #include "toolchain/codegen/codegen.h"
  17. #include "toolchain/diagnostics/diagnostic_emitter.h"
  18. #include "toolchain/diagnostics/sorting_diagnostic_consumer.h"
  19. #include "toolchain/lexer/tokenized_buffer.h"
  20. #include "toolchain/lowering/lower_to_llvm.h"
  21. #include "toolchain/parser/parse_tree.h"
  22. #include "toolchain/semantics/semantics_ir.h"
  23. #include "toolchain/semantics/semantics_ir_formatter.h"
  24. #include "toolchain/source/source_buffer.h"
  25. namespace Carbon {
  26. struct Driver::CompileOptions {
  27. static constexpr CommandLine::CommandInfo Info = {
  28. .name = "compile",
  29. .help = R"""(
  30. Compile Carbon source code.
  31. This subcommand runs the Carbon compiler over input source code, checking it for
  32. errors and producing the requested output.
  33. Error messages are written to the standard error stream.
  34. Different phases of the compiler can be selected to run, and intermediate state
  35. can be written to standard output as these phases progress.
  36. )""",
  37. };
  38. enum class Phase {
  39. Lex,
  40. Parse,
  41. Check,
  42. Lower,
  43. CodeGen,
  44. };
  45. friend auto operator<<(llvm::raw_ostream& out, Phase phase)
  46. -> llvm::raw_ostream& {
  47. switch (phase) {
  48. case Phase::Lex:
  49. out << "lex";
  50. break;
  51. case Phase::Parse:
  52. out << "parse";
  53. break;
  54. case Phase::Check:
  55. out << "check";
  56. break;
  57. case Phase::Lower:
  58. out << "lower";
  59. break;
  60. case Phase::CodeGen:
  61. out << "codegen";
  62. break;
  63. }
  64. return out;
  65. }
  66. void Build(CommandLine::CommandBuilder& b) {
  67. b.AddStringPositionalArg(
  68. {
  69. .name = "FILE",
  70. .help = R"""(
  71. The input Carbon source file to compile.
  72. )""",
  73. },
  74. [&](auto& arg_b) {
  75. arg_b.Required(true);
  76. arg_b.Set(&input_file_name);
  77. });
  78. b.AddOneOfOption(
  79. {
  80. .name = "phase",
  81. .help = R"""(
  82. Selects the compilation phase to run. These phases are always run in sequence,
  83. so every phase before the one selected will also be run. The default is to
  84. compile to machine code.
  85. )""",
  86. },
  87. [&](auto& arg_b) {
  88. arg_b.SetOneOf(
  89. {
  90. arg_b.OneOfValue("lex", Phase::Lex),
  91. arg_b.OneOfValue("parse", Phase::Parse),
  92. arg_b.OneOfValue("check", Phase::Check),
  93. arg_b.OneOfValue("lower", Phase::Lower),
  94. arg_b.OneOfValue("codegen", Phase::CodeGen).Default(true),
  95. },
  96. &phase);
  97. });
  98. // TODO: Rearrange the code setting this option and two related ones to
  99. // allow them to reference each other instead of hard-coding their names.
  100. b.AddStringOption(
  101. {
  102. .name = "output",
  103. .value_name = "FILE",
  104. .help = R"""(
  105. The output filename for codegen.
  106. When this is a file name, either textual assembly or a binary object will be
  107. written to it based on the flag `--asm-output`. The default is to write a binary
  108. object file.
  109. Passing `--output=-` will write the output to stdout. In that
  110. case, the flag `--asm-output` is ignored and the output defaults to textual
  111. assembly. Binary object output can be forced by enabling `--force-obj-output`.
  112. )""",
  113. },
  114. [&](auto& arg_b) { arg_b.Set(&output_file_name); });
  115. b.AddStringOption(
  116. {
  117. .name = "target",
  118. .help = R"""(
  119. Select a target platform. Uses the LLVM target syntax. Also known as a "triple"
  120. for historical reasons.
  121. This corresponds to the `target` flag to Clang and accepts the same strings
  122. documented there:
  123. https://clang.llvm.org/docs/CrossCompilation.html#target-triple
  124. )""",
  125. },
  126. [&](auto& arg_b) {
  127. arg_b.Default(host);
  128. arg_b.Set(&target);
  129. });
  130. b.AddFlag(
  131. {
  132. .name = "asm-output",
  133. .help = R"""(
  134. Write textual assembly rather than a binary object file to the code generation
  135. output.
  136. This flag only applies when writing to a file. When writing to stdout, the
  137. default is textual assembly and this flag is ignored.
  138. )""",
  139. },
  140. [&](auto& arg_b) { arg_b.Set(&asm_output); });
  141. b.AddFlag(
  142. {
  143. .name = "force-obj-output",
  144. .help = R"""(
  145. Force binary object output, even with `--output=-`.
  146. When `--output=-` is set, the default is textual assembly; this forces printing
  147. of a binary object file instead. Ignored for other `--output` values.
  148. )""",
  149. },
  150. [&](auto& arg_b) { arg_b.Set(&force_obj_output); });
  151. b.AddFlag(
  152. {
  153. .name = "stream-errors",
  154. .help = R"""(
  155. Stream error messages to stderr as they are generated rather than sorting them
  156. and displaying them in source order.
  157. )""",
  158. },
  159. [&](auto& arg_b) { arg_b.Set(&stream_errors); });
  160. b.AddFlag(
  161. {
  162. .name = "dump-tokens",
  163. .help = R"""(
  164. Dump the tokens to stdout when lexed.
  165. )""",
  166. },
  167. [&](auto& arg_b) { arg_b.Set(&dump_tokens); });
  168. b.AddFlag(
  169. {
  170. .name = "dump-parse-tree",
  171. .help = R"""(
  172. Dump the parse tree to stdout when parsed.
  173. )""",
  174. },
  175. [&](auto& arg_b) { arg_b.Set(&dump_parse_tree); });
  176. b.AddFlag(
  177. {
  178. .name = "preorder-parse-tree",
  179. .help = R"""(
  180. When dumping the parse tree, reorder it so that it is in preorder rather than
  181. postorder.
  182. )""",
  183. },
  184. [&](auto& arg_b) { arg_b.Set(&preorder_parse_tree); });
  185. b.AddFlag(
  186. {
  187. .name = "dump-raw-semantics-ir",
  188. .help = R"""(
  189. Dump the raw JSON structure of semantics IR to stdout when built.
  190. )""",
  191. },
  192. [&](auto& arg_b) { arg_b.Set(&dump_raw_semantics_ir); });
  193. b.AddFlag(
  194. {
  195. .name = "dump-semantics-ir",
  196. .help = R"""(
  197. Dump the semantics IR to stdout when built.
  198. )""",
  199. },
  200. [&](auto& arg_b) { arg_b.Set(&dump_semantics_ir); });
  201. b.AddFlag(
  202. {
  203. .name = "builtin-semantics-ir",
  204. .help = R"""(
  205. Include the semantics IR for builtins when dumping it.
  206. )""",
  207. },
  208. [&](auto& arg_b) { arg_b.Set(&builtin_semantics_ir); });
  209. b.AddFlag(
  210. {
  211. .name = "dump-llvm-ir",
  212. .help = R"""(
  213. Dump the LLVM IR to stdout after lowering.
  214. )""",
  215. },
  216. [&](auto& arg_b) { arg_b.Set(&dump_llvm_ir); });
  217. b.AddFlag(
  218. {
  219. .name = "dump-asm",
  220. .help = R"""(
  221. Dump the generated assembly to stdout after codegen.
  222. )""",
  223. },
  224. [&](auto& arg_b) { arg_b.Set(&dump_asm); });
  225. }
  226. Phase phase;
  227. std::string host = llvm::sys::getDefaultTargetTriple();
  228. llvm::StringRef target;
  229. llvm::StringRef output_file_name;
  230. llvm::StringRef input_file_name;
  231. bool asm_output = false;
  232. bool force_obj_output = false;
  233. bool dump_tokens = false;
  234. bool dump_parse_tree = false;
  235. bool dump_raw_semantics_ir = false;
  236. bool dump_semantics_ir = false;
  237. bool dump_llvm_ir = false;
  238. bool dump_asm = false;
  239. bool stream_errors = false;
  240. bool preorder_parse_tree = false;
  241. bool builtin_semantics_ir = false;
  242. };
  243. struct Driver::Options {
  244. static constexpr CommandLine::CommandInfo Info = {
  245. .name = "carbon",
  246. // TODO: Setup more detailed version information and use that here.
  247. .version = R"""(
  248. Carbon Language toolchain -- version 0.0.0
  249. )""",
  250. .help = R"""(
  251. This is the unified Carbon Language toolchain driver. It's subcommands provide
  252. all of the core behavior of the toolchain, including compilation, linking, and
  253. developer tools. Each of these has its own subcommand, and you can pass a
  254. specific subcommand to the `help` subcommand to get details about is usage.
  255. )""",
  256. .help_epilogue = R"""(
  257. For questions, issues, or bug reports, please use our GitHub project:
  258. https://github.com/carbon-language/carbon-lang
  259. )""",
  260. };
  261. enum class Subcommand {
  262. Compile,
  263. };
  264. void Build(CommandLine::CommandBuilder& b) {
  265. b.AddFlag(
  266. {
  267. .name = "verbose",
  268. .short_name = "v",
  269. .help = "Enable verbose logging to the stderr stream.",
  270. },
  271. [&](CommandLine::FlagBuilder& arg_b) { arg_b.Set(&verbose); });
  272. b.AddSubcommand(CompileOptions::Info,
  273. [&](CommandLine::CommandBuilder& sub_b) {
  274. compile_options.Build(sub_b);
  275. sub_b.Do([&] { subcommand = Subcommand::Compile; });
  276. });
  277. b.RequiresSubcommand();
  278. }
  279. bool verbose;
  280. Subcommand subcommand;
  281. CompileOptions compile_options;
  282. };
  283. auto Driver::ParseArgs(llvm::ArrayRef<llvm::StringRef> args, Options& options)
  284. -> CommandLine::ParseResult {
  285. return CommandLine::Parse(
  286. args, output_stream_, error_stream_, Options::Info,
  287. [&](CommandLine::CommandBuilder& b) { options.Build(b); });
  288. }
  289. auto Driver::RunCommand(llvm::ArrayRef<llvm::StringRef> args) -> bool {
  290. Options options;
  291. CommandLine::ParseResult result = ParseArgs(args, options);
  292. if (result == CommandLine::ParseResult::Error) {
  293. return false;
  294. } else if (result == CommandLine::ParseResult::MetaSuccess) {
  295. return true;
  296. }
  297. if (options.verbose) {
  298. // Note this implies streamed output in order to interleave.
  299. vlog_stream_ = &error_stream_;
  300. }
  301. switch (options.subcommand) {
  302. case Options::Subcommand::Compile:
  303. return Compile(options.compile_options);
  304. }
  305. llvm_unreachable("All subcommands handled!");
  306. }
  307. auto Driver::ValidateCompileOptions(const CompileOptions& options) const
  308. -> bool {
  309. using Phase = CompileOptions::Phase;
  310. switch (options.phase) {
  311. case Phase::Lex:
  312. if (options.dump_parse_tree) {
  313. error_stream_ << "ERROR: Requested dumping the parse tree but compile "
  314. "phase is limited to '"
  315. << options.phase << "'\n";
  316. return false;
  317. }
  318. [[clang::fallthrough]];
  319. case Phase::Parse:
  320. if (options.dump_semantics_ir) {
  321. error_stream_ << "ERROR: Requested dumping the semantics IR but "
  322. "compile phase is limited to '"
  323. << options.phase << "'\n";
  324. return false;
  325. }
  326. [[clang::fallthrough]];
  327. case Phase::Check:
  328. if (options.dump_llvm_ir) {
  329. error_stream_ << "ERROR: Requested dumping the LLVM IR but compile "
  330. "phase is limited to '"
  331. << options.phase << "'\n";
  332. return false;
  333. }
  334. [[clang::fallthrough]];
  335. case Phase::Lower:
  336. case Phase::CodeGen:
  337. // Everything can be dumped in these phases.
  338. break;
  339. }
  340. return true;
  341. }
  342. auto Driver::Compile(const CompileOptions& options) -> bool {
  343. using Phase = CompileOptions::Phase;
  344. if (!ValidateCompileOptions(options)) {
  345. return false;
  346. }
  347. StreamDiagnosticConsumer stream_consumer(error_stream_);
  348. DiagnosticConsumer* consumer = &stream_consumer;
  349. std::unique_ptr<SortingDiagnosticConsumer> sorting_consumer;
  350. if (vlog_stream_ == nullptr && !options.stream_errors) {
  351. sorting_consumer = std::make_unique<SortingDiagnosticConsumer>(*consumer);
  352. consumer = sorting_consumer.get();
  353. }
  354. CARBON_VLOG() << "*** SourceBuffer::CreateFromFile on '"
  355. << options.input_file_name << "' ***\n";
  356. auto source = SourceBuffer::CreateFromFile(fs_, options.input_file_name);
  357. CARBON_VLOG() << "*** SourceBuffer::CreateFromFile done ***\n";
  358. // Require flushing the consumer before the source buffer is destroyed,
  359. // because diagnostics may reference the buffer.
  360. auto flush = llvm::make_scope_exit([&]() { consumer->Flush(); });
  361. if (!source.ok()) {
  362. error_stream_ << "ERROR: Unable to open input source file: "
  363. << source.error();
  364. return false;
  365. }
  366. CARBON_VLOG() << "*** file:\n```\n" << source->text() << "\n```\n";
  367. CARBON_VLOG() << "*** TokenizedBuffer::Lex ***\n";
  368. auto tokenized_source = TokenizedBuffer::Lex(*source, *consumer);
  369. bool has_errors = tokenized_source.has_errors();
  370. CARBON_VLOG() << "*** TokenizedBuffer::Lex done ***\n";
  371. if (options.dump_tokens) {
  372. CARBON_VLOG() << "Finishing output.";
  373. consumer->Flush();
  374. output_stream_ << tokenized_source;
  375. }
  376. CARBON_VLOG() << "tokenized_buffer: " << tokenized_source;
  377. if (options.phase == Phase::Lex) {
  378. return !has_errors;
  379. }
  380. CARBON_VLOG() << "*** ParseTree::Parse ***\n";
  381. auto parse_tree = ParseTree::Parse(tokenized_source, *consumer, vlog_stream_);
  382. has_errors |= parse_tree.has_errors();
  383. CARBON_VLOG() << "*** ParseTree::Parse done ***\n";
  384. if (options.dump_parse_tree) {
  385. consumer->Flush();
  386. parse_tree.Print(output_stream_, options.preorder_parse_tree);
  387. }
  388. CARBON_VLOG() << "parse_tree: " << parse_tree;
  389. if (options.phase == Phase::Parse) {
  390. return !has_errors;
  391. }
  392. const SemanticsIR builtin_ir = SemanticsIR::MakeBuiltinIR();
  393. CARBON_VLOG() << "*** SemanticsIR::MakeFromParseTree ***\n";
  394. const SemanticsIR semantics_ir = SemanticsIR::MakeFromParseTree(
  395. builtin_ir, tokenized_source, parse_tree, *consumer, vlog_stream_);
  396. has_errors |= semantics_ir.has_errors();
  397. CARBON_VLOG() << "*** SemanticsIR::MakeFromParseTree done ***\n";
  398. if (options.dump_raw_semantics_ir) {
  399. consumer->Flush();
  400. semantics_ir.Print(output_stream_, options.builtin_semantics_ir);
  401. if (options.dump_semantics_ir) {
  402. output_stream_ << "\n";
  403. }
  404. }
  405. if (options.dump_semantics_ir) {
  406. FormatSemanticsIR(tokenized_source, parse_tree, semantics_ir,
  407. output_stream_);
  408. }
  409. CARBON_VLOG() << "semantics_ir: " << semantics_ir;
  410. if (options.phase == Phase::Check) {
  411. return !has_errors;
  412. }
  413. // Unlike previous steps, errors block further progress.
  414. if (has_errors) {
  415. CARBON_VLOG() << "*** Stopping before lowering due to syntax errors ***";
  416. return false;
  417. }
  418. consumer->Flush();
  419. CARBON_VLOG() << "*** LowerToLLVM ***\n";
  420. llvm::LLVMContext llvm_context;
  421. const std::unique_ptr<llvm::Module> module = LowerToLLVM(
  422. llvm_context, options.input_file_name, semantics_ir, vlog_stream_);
  423. CARBON_VLOG() << "*** LowerToLLVM done ***\n";
  424. if (options.dump_llvm_ir) {
  425. module->print(output_stream_, /*AAW=*/nullptr,
  426. /*ShouldPreserveUseListOrder=*/true);
  427. }
  428. if (vlog_stream_) {
  429. CARBON_VLOG() << "module: ";
  430. module->print(*vlog_stream_, /*AAW=*/nullptr,
  431. /*ShouldPreserveUseListOrder=*/false,
  432. /*IsForDebug=*/true);
  433. }
  434. if (options.phase == Phase::Lower) {
  435. return true;
  436. }
  437. CARBON_VLOG() << "*** CodeGen ***\n";
  438. std::optional<CodeGen> codegen =
  439. CodeGen::Create(*module, options.target, error_stream_);
  440. if (!codegen) {
  441. return false;
  442. }
  443. if (vlog_stream_) {
  444. CARBON_VLOG() << "assembly:\n";
  445. codegen->EmitAssembly(*vlog_stream_);
  446. }
  447. if (options.output_file_name == "-") {
  448. // TODO: the output file name, forcing object output, and requesting textual
  449. // assembly output are all somewhat linked flags. We should add some
  450. // validation that they are used correctly.
  451. if (options.force_obj_output) {
  452. if (!codegen->EmitObject(output_stream_)) {
  453. return false;
  454. }
  455. } else {
  456. if (!codegen->EmitAssembly(output_stream_)) {
  457. return false;
  458. }
  459. }
  460. } else {
  461. llvm::SmallString<256> output_file_name = options.output_file_name;
  462. if (output_file_name.empty()) {
  463. output_file_name = options.input_file_name;
  464. llvm::sys::path::replace_extension(output_file_name,
  465. options.asm_output ? ".s" : ".o");
  466. }
  467. CARBON_VLOG() << "Writing output to: " << output_file_name << "\n";
  468. std::error_code ec;
  469. llvm::raw_fd_ostream output_file(output_file_name, ec,
  470. llvm::sys::fs::OF_None);
  471. if (ec) {
  472. error_stream_ << "ERROR: Could not open output file '" << output_file_name
  473. << "': " << ec.message() << "\n";
  474. return false;
  475. }
  476. if (options.asm_output) {
  477. if (!codegen->EmitAssembly(output_file)) {
  478. return false;
  479. }
  480. } else {
  481. if (!codegen->EmitObject(output_file)) {
  482. return false;
  483. }
  484. }
  485. }
  486. CARBON_VLOG() << "*** CodeGen done ***\n";
  487. return true;
  488. }
  489. } // namespace Carbon