codegen.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 <optional>
  7. #include <string>
  8. #include "common/check.h"
  9. #include "llvm/IR/LegacyPassManager.h"
  10. #include "llvm/MC/TargetRegistry.h"
  11. #include "llvm/Target/TargetOptions.h"
  12. #include "llvm/TargetParser/Host.h"
  13. #include "toolchain/diagnostics/diagnostic_consumer.h"
  14. namespace Carbon {
  15. auto CodeGen::EmitAssembly(llvm::raw_pwrite_stream& out) -> bool {
  16. return EmitCode(out, llvm::CodeGenFileType::AssemblyFile);
  17. }
  18. auto CodeGen::EmitObject(llvm::raw_pwrite_stream& out) -> bool {
  19. return EmitCode(out, llvm::CodeGenFileType::ObjectFile);
  20. }
  21. auto CodeGen::EmitCode(llvm::raw_pwrite_stream& out,
  22. llvm::CodeGenFileType file_type) -> bool {
  23. module_->setDataLayout(target_machine_->createDataLayout());
  24. // Using the legacy PM to generate the assembly since the new PM
  25. // does not work with this yet.
  26. // TODO: Make the new PM work with the codegen pipeline.
  27. llvm::legacy::PassManager pass;
  28. // Note that this returns true on an error.
  29. if (target_machine_->addPassesToEmitFile(pass, out, nullptr, file_type)) {
  30. CARBON_DIAGNOSTIC(CodeGenUnableToEmit, Error,
  31. "unable to emit to this file");
  32. emitter_.Emit(module_->getName(), CodeGenUnableToEmit);
  33. return false;
  34. }
  35. pass.run(*module_);
  36. return true;
  37. }
  38. } // namespace Carbon