codegen.cpp 2.0 KB

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