codegen.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. #ifndef CARBON_TOOLCHAIN_CODEGEN_CODEGEN_H_
  5. #define CARBON_TOOLCHAIN_CODEGEN_CODEGEN_H_
  6. #include "llvm/IR/Module.h"
  7. #include "llvm/Target/TargetMachine.h"
  8. #include "toolchain/diagnostics/diagnostic_consumer.h"
  9. #include "toolchain/diagnostics/file_diagnostics.h"
  10. namespace Carbon {
  11. class CodeGen {
  12. public:
  13. // `module` and `errors` must not be null. `consumer` may be null, in which
  14. // case diagnostics go to stderr.
  15. static auto Make(llvm::Module* module, llvm::StringRef target_triple_str,
  16. Diagnostics::Consumer* consumer = nullptr)
  17. -> std::optional<CodeGen>;
  18. // Generates the object code file.
  19. // Returns false in case of failure, and any information about the failure is
  20. // printed to the error stream.
  21. //
  22. // Note this requires a `pwrite` stream to allow patching the output.
  23. auto EmitObject(llvm::raw_pwrite_stream& out) -> bool;
  24. // Prints the assembly to stdout.
  25. // Returns false in case of failure, and any information about the failure is
  26. // printed to the error stream.
  27. //
  28. // Note this requires a `pwrite` stream to allow patching the output.
  29. auto EmitAssembly(llvm::raw_pwrite_stream& out) -> bool;
  30. private:
  31. // `module` and `consumer` must not be null.
  32. explicit CodeGen(llvm::Module* module, Diagnostics::Consumer* consumer)
  33. : module_(module), emitter_(consumer) {}
  34. // Using the llvm pass emits either assembly or object code to dest.
  35. // Returns false in case of failure, and any information about the failure is
  36. // printed to the error stream.
  37. auto EmitCode(llvm::raw_pwrite_stream& out, llvm::CodeGenFileType file_type)
  38. -> bool;
  39. llvm::Module* module_;
  40. // The emitter for diagnostics.
  41. Diagnostics::FileEmitter emitter_;
  42. std::unique_ptr<llvm::TargetMachine> target_machine_;
  43. };
  44. } // namespace Carbon
  45. #endif // CARBON_TOOLCHAIN_CODEGEN_CODEGEN_H_