5 //! This API is completely unstable and subject to change.
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
15 #![recursion_limit = "256"]
17 use back
::write
::{create_informational_target_machine, create_target_machine}
;
19 pub use llvm_util
::target_features
;
20 use rustc_ast
::expand
::allocator
::AllocatorKind
;
21 use rustc_codegen_ssa
::back
::lto
::{LtoModuleCodegen, SerializedModule, ThinModule}
;
22 use rustc_codegen_ssa
::back
::write
::{
23 CodegenContext
, FatLTOInput
, ModuleConfig
, TargetMachineFactoryConfig
, TargetMachineFactoryFn
,
25 use rustc_codegen_ssa
::traits
::*;
26 use rustc_codegen_ssa
::ModuleCodegen
;
27 use rustc_codegen_ssa
::{CodegenResults, CompiledModule}
;
28 use rustc_data_structures
::fx
::FxHashMap
;
29 use rustc_errors
::{ErrorReported, FatalError, Handler}
;
30 use rustc_middle
::dep_graph
::{WorkProduct, WorkProductId}
;
31 use rustc_middle
::middle
::cstore
::EncodedMetadata
;
32 use rustc_middle
::ty
::TyCtxt
;
33 use rustc_session
::config
::{OptLevel, OutputFilenames, PrintRequest}
;
34 use rustc_session
::Session
;
35 use rustc_span
::symbol
::Symbol
;
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
66 pub use super::llvm_
::*;
77 pub struct LlvmCodegenBackend(());
79 impl ExtraBackendMethods
for LlvmCodegenBackend
{
80 fn new_metadata(&self, tcx
: TyCtxt
<'_
>, mod_name
: &str) -> ModuleLlvm
{
81 ModuleLlvm
::new_metadata(tcx
, mod_name
)
84 fn write_compressed_metadata
<'tcx
>(
87 metadata
: &EncodedMetadata
,
88 llvm_module
: &mut ModuleLlvm
,
90 base
::write_compressed_metadata(tcx
, metadata
, llvm_module
)
92 fn codegen_allocator
<'tcx
>(
95 mods
: &mut ModuleLlvm
,
97 has_alloc_error_handler
: bool
,
99 unsafe { allocator::codegen(tcx, mods, kind, has_alloc_error_handler) }
101 fn compile_codegen_unit(
105 ) -> (ModuleCodegen
<ModuleLlvm
>, u64) {
106 base
::compile_codegen_unit(tcx
, cgu_name
)
108 fn target_machine_factory(
112 ) -> TargetMachineFactoryFn
<Self> {
113 back
::write
::target_machine_factory(sess
, optlvl
)
115 fn target_cpu
<'b
>(&self, sess
: &'b Session
) -> &'b
str {
116 llvm_util
::target_cpu(sess
)
118 fn tune_cpu
<'b
>(&self, sess
: &'b Session
) -> Option
<&'b
str> {
119 llvm_util
::tune_cpu(sess
)
123 impl WriteBackendMethods
for LlvmCodegenBackend
{
124 type Module
= ModuleLlvm
;
125 type ModuleBuffer
= back
::lto
::ModuleBuffer
;
126 type Context
= llvm
::Context
;
127 type TargetMachine
= &'
static mut llvm
::TargetMachine
;
128 type ThinData
= back
::lto
::ThinData
;
129 type ThinBuffer
= back
::lto
::ThinBuffer
;
130 fn print_pass_timings(&self) {
132 llvm
::LLVMRustPrintPassTimings();
136 cgcx
: &CodegenContext
<Self>,
137 diag_handler
: &Handler
,
138 modules
: Vec
<ModuleCodegen
<Self::Module
>>,
139 ) -> Result
<ModuleCodegen
<Self::Module
>, FatalError
> {
140 back
::write
::link(cgcx
, diag_handler
, modules
)
143 cgcx
: &CodegenContext
<Self>,
144 modules
: Vec
<FatLTOInput
<Self>>,
145 cached_modules
: Vec
<(SerializedModule
<Self::ModuleBuffer
>, WorkProduct
)>,
146 ) -> Result
<LtoModuleCodegen
<Self>, FatalError
> {
147 back
::lto
::run_fat(cgcx
, modules
, cached_modules
)
150 cgcx
: &CodegenContext
<Self>,
151 modules
: Vec
<(String
, Self::ThinBuffer
)>,
152 cached_modules
: Vec
<(SerializedModule
<Self::ModuleBuffer
>, WorkProduct
)>,
153 ) -> Result
<(Vec
<LtoModuleCodegen
<Self>>, Vec
<WorkProduct
>), FatalError
> {
154 back
::lto
::run_thin(cgcx
, modules
, cached_modules
)
157 cgcx
: &CodegenContext
<Self>,
158 diag_handler
: &Handler
,
159 module
: &ModuleCodegen
<Self::Module
>,
160 config
: &ModuleConfig
,
161 ) -> Result
<(), FatalError
> {
162 back
::write
::optimize(cgcx
, diag_handler
, module
, config
)
164 unsafe fn optimize_thin(
165 cgcx
: &CodegenContext
<Self>,
166 thin
: &mut ThinModule
<Self>,
167 ) -> Result
<ModuleCodegen
<Self::Module
>, FatalError
> {
168 back
::lto
::optimize_thin_module(thin
, cgcx
)
171 cgcx
: &CodegenContext
<Self>,
172 diag_handler
: &Handler
,
173 module
: ModuleCodegen
<Self::Module
>,
174 config
: &ModuleConfig
,
175 ) -> Result
<CompiledModule
, FatalError
> {
176 back
::write
::codegen(cgcx
, diag_handler
, module
, config
)
178 fn prepare_thin(module
: ModuleCodegen
<Self::Module
>) -> (String
, Self::ThinBuffer
) {
179 back
::lto
::prepare_thin(module
)
181 fn serialize_module(module
: ModuleCodegen
<Self::Module
>) -> (String
, Self::ModuleBuffer
) {
182 (module
.name
, back
::lto
::ModuleBuffer
::new(module
.module_llvm
.llmod()))
184 fn run_lto_pass_manager(
185 cgcx
: &CodegenContext
<Self>,
186 module
: &ModuleCodegen
<Self::Module
>,
187 config
: &ModuleConfig
,
189 ) -> Result
<(), FatalError
> {
190 let diag_handler
= cgcx
.create_diag_handler();
191 back
::lto
::run_pass_manager(cgcx
, &diag_handler
, module
, config
, thin
)
195 unsafe impl Send
for LlvmCodegenBackend {}
// Llvm is on a per-thread basis
196 unsafe impl Sync
for LlvmCodegenBackend {}
198 impl LlvmCodegenBackend
{
199 pub fn new() -> Box
<dyn CodegenBackend
> {
200 Box
::new(LlvmCodegenBackend(()))
204 impl CodegenBackend
for LlvmCodegenBackend
{
205 fn init(&self, sess
: &Session
) {
206 llvm_util
::init(sess
); // Make sure llvm is inited
209 fn print(&self, req
: PrintRequest
, sess
: &Session
) {
211 PrintRequest
::RelocationModels
=> {
212 println
!("Available relocation models:");
214 &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
216 println
!(" {}", name
);
220 PrintRequest
::CodeModels
=> {
221 println
!("Available code models:");
222 for name
in &["tiny", "small", "kernel", "medium", "large"] {
223 println
!(" {}", name
);
227 PrintRequest
::TlsModels
=> {
228 println
!("Available TLS models:");
229 for name
in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
230 println
!(" {}", name
);
234 req
=> llvm_util
::print(req
, sess
),
238 fn print_passes(&self) {
239 llvm_util
::print_passes();
242 fn print_version(&self) {
243 llvm_util
::print_version();
246 fn target_features(&self, sess
: &Session
) -> Vec
<Symbol
> {
247 target_features(sess
)
250 fn codegen_crate
<'tcx
>(
253 metadata
: EncodedMetadata
,
254 need_metadata_module
: bool
,
256 Box
::new(rustc_codegen_ssa
::base
::codegen_crate(
257 LlvmCodegenBackend(()),
259 crate::llvm_util
::target_cpu(tcx
.sess
).to_string(),
261 need_metadata_module
,
267 ongoing_codegen
: Box
<dyn Any
>,
269 ) -> Result
<(CodegenResults
, FxHashMap
<WorkProductId
, WorkProduct
>), ErrorReported
> {
270 let (codegen_results
, work_products
) = ongoing_codegen
271 .downcast
::<rustc_codegen_ssa
::back
::write
::OngoingCodegen
<LlvmCodegenBackend
>>()
272 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
275 sess
.time("llvm_dump_timing_file", || {
276 if sess
.opts
.debugging_opts
.llvm_time_trace
{
277 llvm_util
::time_trace_profiler_finish("llvm_timings.json");
281 Ok((codegen_results
, work_products
))
287 codegen_results
: CodegenResults
,
288 outputs
: &OutputFilenames
,
289 ) -> Result
<(), ErrorReported
> {
290 use crate::back
::archive
::LlvmArchiveBuilder
;
291 use rustc_codegen_ssa
::back
::link
::link_binary
;
293 // Run the linker on any artifacts that resulted from the LLVM run.
294 // This should produce either a finished executable or library.
295 link_binary
::<LlvmArchiveBuilder
<'_
>>(sess
, &codegen_results
, outputs
)
299 pub struct ModuleLlvm
{
300 llcx
: &'
static mut llvm
::Context
,
301 llmod_raw
: *const llvm
::Module
,
302 tm
: &'
static mut llvm
::TargetMachine
,
305 unsafe impl Send
for ModuleLlvm {}
306 unsafe impl Sync
for ModuleLlvm {}
309 fn new(tcx
: TyCtxt
<'_
>, mod_name
: &str) -> Self {
311 let llcx
= llvm
::LLVMRustContextCreate(tcx
.sess
.fewer_names());
312 let llmod_raw
= context
::create_module(tcx
, llcx
, mod_name
) as *const _
;
313 ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
317 fn new_metadata(tcx
: TyCtxt
<'_
>, mod_name
: &str) -> Self {
319 let llcx
= llvm
::LLVMRustContextCreate(tcx
.sess
.fewer_names());
320 let llmod_raw
= context
::create_module(tcx
, llcx
, mod_name
) as *const _
;
321 ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
326 cgcx
: &CodegenContext
<LlvmCodegenBackend
>,
330 ) -> Result
<Self, FatalError
> {
332 let llcx
= llvm
::LLVMRustContextCreate(cgcx
.fewer_names
);
333 let llmod_raw
= back
::lto
::parse_module(llcx
, name
, buffer
, handler
)?
;
334 let tm_factory_config
= TargetMachineFactoryConfig
::new(&cgcx
, name
.to_str().unwrap());
335 let tm
= match (cgcx
.tm_factory
)(tm_factory_config
) {
338 handler
.struct_err(&e
).emit();
339 return Err(FatalError
);
343 Ok(ModuleLlvm { llmod_raw, llcx, tm }
)
347 fn llmod(&self) -> &llvm
::Module
{
348 unsafe { &*self.llmod_raw }
352 impl Drop
for ModuleLlvm
{
355 llvm
::LLVMContextDispose(&mut *(self.llcx
as *mut _
));
356 llvm
::LLVMRustDisposeTargetMachine(&mut *(self.tm
as *mut _
));