codegen.cpp 2.0 KB

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