Skip to content

Commit 7bdd2ba

Browse files
committed
Fix LTO
1 parent 12257cc commit 7bdd2ba

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

src/back/write.rs

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::{env, fs};
22

3-
use gccjit::OutputKind;
3+
use gccjit::{Context, OutputKind};
44
use rustc_codegen_ssa::back::link::ensure_removed;
55
use rustc_codegen_ssa::back::write::{BitcodeSection, CodegenContext, EmitObj, ModuleConfig};
66
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
@@ -176,10 +176,45 @@ pub(crate) unsafe fn codegen(
176176
context.add_driver_option("-nostdlib");
177177

178178
// NOTE: this doesn't actually generate an executable. With the above flags, it combines the .o files together in another .o.
179-
context.compile_to_file(
179+
// FIXME FIXME: this produces an object file with GIMPLE IR, but it should
180+
// produce an object file with machine code.
181+
//println!("LTO-ed object file: {:?}", obj_out);
182+
/*context.compile_to_file(
180183
OutputKind::Executable,
181184
obj_out.to_str().expect("path to str"),
182-
);
185+
);*/
186+
187+
let path = obj_out.to_str().expect("path to str");
188+
189+
let lto_path = format!("{}.lto", path);
190+
context.compile_to_file(OutputKind::Executable, &lto_path);
191+
//println!("****************************************************************************************************");
192+
193+
let context = Context::default(); // TODO: might need to set some other flags from new_context.
194+
//context.add_driver_option("-v");
195+
//println!("*** Arch: {}", cgcx.target_arch);
196+
if cgcx.target_arch == "x86" || cgcx.target_arch == "x86_64" {
197+
//println!("**** Added -masm=intel");
198+
//context.add_command_line_option("-masm=intel");
199+
// NOTE: it seems we need to use add_driver_option instead of
200+
// add_command_line_option here because we use the LTO frontend via gcc.
201+
context.add_driver_option("-masm=intel");
202+
}
203+
204+
// NOTE: these two options are needed to invoke LTO to produce an object file.
205+
// We need to initiate a second compilation because the arguments "-x lto"
206+
// needs to be at the very beginning.
207+
// TODO TODO: check that LTO still does the optimizations across different
208+
// object files with this change.
209+
// TODO: this should probably be in a condition `if fat_lto`.
210+
context.add_driver_option("-x");
211+
context.add_driver_option("lto");
212+
context.add_driver_option("-fPIC"); // TODO TODO: only add this flag when necessary.
213+
context.add_driver_option(lto_path);
214+
215+
// FIXME FIXME: it seems this object file doesn't contain the main function and
216+
// some other code.
217+
context.compile_to_file(OutputKind::ObjectFile, path);
183218
} else {
184219
context.compile_to_file(
185220
OutputKind::ObjectFile,

0 commit comments

Comments
 (0)