codegen.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/codegen/codegen.h"
  5. #include <cstdio>
  6. #include <memory>
  7. #include "llvm/IR/LegacyPassManager.h"
  8. #include "llvm/MC/TargetRegistry.h"
  9. #include "llvm/Support/TargetSelect.h"
  10. #include "llvm/Target/TargetOptions.h"
  11. #include "llvm/TargetParser/Host.h"
  12. namespace Carbon {
  13. auto CodeGen::Create(llvm::Module& module, llvm::StringRef target_triple,
  14. llvm::raw_pwrite_stream& errors)
  15. -> std::optional<CodeGen> {
  16. // Initialize the target registry etc.
  17. llvm::InitializeAllTargetInfos();
  18. llvm::InitializeAllTargets();
  19. llvm::InitializeAllTargetMCs();
  20. llvm::InitializeAllAsmParsers();
  21. llvm::InitializeAllAsmPrinters();
  22. std::string error;
  23. const llvm::Target* target =
  24. llvm::TargetRegistry::lookupTarget(target_triple, error);
  25. if (!target) {
  26. errors << "ERROR: Invalid target: " << error << "\n";
  27. return {};
  28. }
  29. module.setTargetTriple(target_triple);
  30. constexpr llvm::StringLiteral CPU = "generic";
  31. constexpr llvm::StringLiteral Features = "";
  32. llvm::TargetOptions target_opts;
  33. std::optional<llvm::Reloc::Model> reloc_model;
  34. CodeGen codegen(module, errors);
  35. codegen.target_machine_.reset(target->createTargetMachine(
  36. target_triple, CPU, Features, target_opts, reloc_model));
  37. return codegen;
  38. }
  39. auto CodeGen::EmitAssembly(llvm::raw_pwrite_stream& out) -> bool {
  40. return EmitCode(out, llvm::CodeGenFileType::CGFT_AssemblyFile);
  41. }
  42. auto CodeGen::EmitObject(llvm::raw_pwrite_stream& out) -> bool {
  43. return EmitCode(out, llvm::CodeGenFileType::CGFT_ObjectFile);
  44. }
  45. auto CodeGen::EmitCode(llvm::raw_pwrite_stream& out,
  46. llvm::CodeGenFileType file_type) -> bool {
  47. module_.setDataLayout(target_machine_->createDataLayout());
  48. // Using the legacy PM to generate the assembly since the new PM
  49. // does not work with this yet.
  50. // TODO: make the new PM work with the codegen pipeline.
  51. llvm::legacy::PassManager pass;
  52. // Note that this returns true on an error.
  53. if (target_machine_->addPassesToEmitFile(pass, out, nullptr, file_type)) {
  54. errors_ << "ERROR: Unable to emit to this file.\n";
  55. return false;
  56. }
  57. pass.run(module_);
  58. return true;
  59. }
  60. } // namespace Carbon