2019-02-17 18:58:58 +00:00
|
|
|
use crate::back::lto::ThinBuffer;
|
2020-02-11 21:37:16 +00:00
|
|
|
use crate::back::profiling::{
|
|
|
|
selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
|
|
|
|
};
|
2019-02-17 18:58:58 +00:00
|
|
|
use crate::base;
|
2019-12-24 22:38:22 +00:00
|
|
|
use crate::common;
|
2019-02-17 18:58:58 +00:00
|
|
|
use crate::consts;
|
|
|
|
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
|
|
|
|
use crate::llvm_util;
|
|
|
|
use crate::type_::Type;
|
|
|
|
use crate::LlvmCodegenBackend;
|
2019-12-24 22:38:22 +00:00
|
|
|
use crate::ModuleLlvm;
|
2021-02-14 16:27:08 +00:00
|
|
|
use rustc_codegen_ssa::back::link::ensure_removed;
|
2020-09-23 15:57:50 +00:00
|
|
|
use rustc_codegen_ssa::back::write::{
|
2020-09-23 16:33:54 +00:00
|
|
|
BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
|
|
|
|
TargetMachineFactoryFn,
|
2020-09-23 15:57:50 +00:00
|
|
|
};
|
2019-12-24 22:38:22 +00:00
|
|
|
use rustc_codegen_ssa::traits::*;
|
2020-04-23 18:45:55 +00:00
|
|
|
use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
|
2021-11-08 15:59:36 +00:00
|
|
|
use rustc_data_structures::profiling::SelfProfilerRef;
|
2018-08-07 14:04:34 +00:00
|
|
|
use rustc_data_structures::small_c_str::SmallCStr;
|
2020-06-09 13:37:59 +00:00
|
|
|
use rustc_errors::{FatalError, Handler, Level};
|
2019-12-24 22:38:22 +00:00
|
|
|
use rustc_fs_util::{link_or_copy, path_to_c_string};
|
2020-03-29 15:19:48 +00:00
|
|
|
use rustc_middle::bug;
|
|
|
|
use rustc_middle::ty::TyCtxt;
|
2021-02-07 21:47:03 +00:00
|
|
|
use rustc_session::config::{self, Lto, OutputType, Passes, SwitchWithOptPath};
|
2020-03-11 11:49:08 +00:00
|
|
|
use rustc_session::Session;
|
2020-06-23 16:41:56 +00:00
|
|
|
use rustc_span::symbol::sym;
|
2020-05-26 19:07:59 +00:00
|
|
|
use rustc_span::InnerSpan;
|
2021-02-07 21:47:03 +00:00
|
|
|
use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
|
2020-08-05 11:35:53 +00:00
|
|
|
use tracing::debug;
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
use libc::{c_char, c_int, c_uint, c_void, size_t};
|
2019-12-04 20:00:28 +00:00
|
|
|
use std::ffi::CString;
|
2018-01-10 16:58:39 +00:00
|
|
|
use std::fs;
|
|
|
|
use std::io::{self, Write};
|
2019-04-10 11:46:37 +00:00
|
|
|
use std::path::{Path, PathBuf};
|
2019-12-24 22:38:22 +00:00
|
|
|
use std::slice;
|
2014-08-11 17:33:58 +00:00
|
|
|
use std::str;
|
2017-07-24 12:21:28 +00:00
|
|
|
use std::sync::Arc;
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2019-10-22 15:51:35 +00:00
|
|
|
pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
|
2015-10-23 05:07:19 +00:00
|
|
|
match llvm::last_error() {
|
2017-06-15 14:08:18 +00:00
|
|
|
Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
|
2021-09-30 17:38:50 +00:00
|
|
|
None => handler.fatal(msg),
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn write_output_file(
|
2019-12-24 22:38:22 +00:00
|
|
|
handler: &rustc_errors::Handler,
|
|
|
|
target: &'ll llvm::TargetMachine,
|
|
|
|
pm: &llvm::PassManager<'ll>,
|
|
|
|
m: &'ll llvm::Module,
|
|
|
|
output: &Path,
|
2020-09-23 16:33:54 +00:00
|
|
|
dwo_output: Option<&Path>,
|
2019-12-24 22:38:22 +00:00
|
|
|
file_type: llvm::FileType,
|
2021-11-08 15:59:36 +00:00
|
|
|
self_profiler_ref: &SelfProfilerRef,
|
2019-12-24 22:38:22 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2014-08-11 17:33:58 +00:00
|
|
|
unsafe {
|
2018-11-29 13:09:28 +00:00
|
|
|
let output_c = path_to_c_string(output);
|
2020-09-23 16:33:54 +00:00
|
|
|
let result = if let Some(dwo_output) = dwo_output {
|
|
|
|
let dwo_output_c = path_to_c_string(dwo_output);
|
|
|
|
llvm::LLVMRustWriteOutputFile(
|
|
|
|
target,
|
|
|
|
pm,
|
|
|
|
m,
|
|
|
|
output_c.as_ptr(),
|
|
|
|
dwo_output_c.as_ptr(),
|
|
|
|
file_type,
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
llvm::LLVMRustWriteOutputFile(
|
|
|
|
target,
|
|
|
|
pm,
|
|
|
|
m,
|
|
|
|
output_c.as_ptr(),
|
|
|
|
std::ptr::null(),
|
|
|
|
file_type,
|
|
|
|
)
|
|
|
|
};
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
// Record artifact sizes for self-profiling
|
|
|
|
if result == llvm::LLVMRustResult::Success {
|
|
|
|
let artifact_kind = match file_type {
|
|
|
|
llvm::FileType::ObjectFile => "object_file",
|
|
|
|
llvm::FileType::AssemblyFile => "assembly_file",
|
|
|
|
};
|
|
|
|
record_artifact_size(self_profiler_ref, artifact_kind, output);
|
|
|
|
if let Some(dwo_file) = dwo_output {
|
|
|
|
record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-04-06 00:48:23 +00:00
|
|
|
result.into_result().map_err(|()| {
|
2017-06-15 14:08:18 +00:00
|
|
|
let msg = format!("could not write output to {}", output.display());
|
2019-04-06 00:48:23 +00:00
|
|
|
llvm_err(handler, &msg)
|
|
|
|
})
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-23 18:10:01 +00:00
|
|
|
pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
|
2020-09-23 16:33:54 +00:00
|
|
|
let config = TargetMachineFactoryConfig { split_dwarf_file: None };
|
|
|
|
target_machine_factory(sess, config::OptLevel::No)(config)
|
2019-12-24 22:38:22 +00:00
|
|
|
.unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
|
2020-09-23 16:33:54 +00:00
|
|
|
pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
|
2020-11-30 16:39:08 +00:00
|
|
|
let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
|
2021-05-11 12:39:04 +00:00
|
|
|
tcx.output_filenames(()).split_dwarf_path(tcx.sess.split_debuginfo(), Some(mod_name))
|
2020-11-30 16:39:08 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2020-09-23 16:33:54 +00:00
|
|
|
let config = TargetMachineFactoryConfig { split_dwarf_file };
|
2021-09-30 17:38:50 +00:00
|
|
|
target_machine_factory(tcx.sess, tcx.backend_optimization_level(()))(config)
|
2019-12-24 22:38:22 +00:00
|
|
|
.unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
|
2019-02-20 20:27:00 +00:00
|
|
|
}
|
2018-10-27 12:29:06 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
pub fn to_llvm_opt_settings(
|
|
|
|
cfg: config::OptLevel,
|
|
|
|
) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
|
2018-10-27 12:29:06 +00:00
|
|
|
use self::config::OptLevel::*;
|
|
|
|
match cfg {
|
|
|
|
No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
|
|
|
|
Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
|
|
|
|
Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
|
|
|
|
Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
|
|
|
|
Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
|
|
|
|
SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-05 18:16:58 +00:00
|
|
|
fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
|
|
|
|
use config::OptLevel::*;
|
|
|
|
match cfg {
|
|
|
|
No => llvm::PassBuilderOptLevel::O0,
|
|
|
|
Less => llvm::PassBuilderOptLevel::O1,
|
|
|
|
Default => llvm::PassBuilderOptLevel::O2,
|
|
|
|
Aggressive => llvm::PassBuilderOptLevel::O3,
|
|
|
|
Size => llvm::PassBuilderOptLevel::Os,
|
|
|
|
SizeMin => llvm::PassBuilderOptLevel::Oz,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-23 17:49:00 +00:00
|
|
|
fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
|
2020-04-22 21:46:45 +00:00
|
|
|
match relocation_model {
|
2020-04-23 17:49:00 +00:00
|
|
|
RelocModel::Static => llvm::RelocModel::Static,
|
2021-09-10 13:11:56 +00:00
|
|
|
// LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
|
|
|
|
RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
|
2020-04-23 17:49:00 +00:00
|
|
|
RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
|
|
|
|
RelocModel::Ropi => llvm::RelocModel::ROPI,
|
|
|
|
RelocModel::Rwpi => llvm::RelocModel::RWPI,
|
|
|
|
RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
|
2020-04-22 21:46:45 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 23:35:13 +00:00
|
|
|
pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
|
2020-05-07 00:34:27 +00:00
|
|
|
match code_model {
|
|
|
|
Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
|
|
|
|
Some(CodeModel::Small) => llvm::CodeModel::Small,
|
|
|
|
Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
|
|
|
|
Some(CodeModel::Medium) => llvm::CodeModel::Medium,
|
|
|
|
Some(CodeModel::Large) => llvm::CodeModel::Large,
|
|
|
|
None => llvm::CodeModel::None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
pub fn target_machine_factory(
|
|
|
|
sess: &Session,
|
|
|
|
optlvl: config::OptLevel,
|
2020-09-23 15:57:50 +00:00
|
|
|
) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
|
2020-04-22 21:46:45 +00:00
|
|
|
let reloc_model = to_llvm_relocation_model(sess.relocation_model());
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2018-10-27 12:29:06 +00:00
|
|
|
let (opt_level, _) = to_llvm_opt_settings(optlvl);
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
let use_softfp = sess.opts.cg.soft_float;
|
|
|
|
|
2020-10-26 19:55:07 +00:00
|
|
|
let ffunction_sections =
|
2020-11-08 11:27:51 +00:00
|
|
|
sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.function_sections);
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
let fdata_sections = ffunction_sections;
|
2021-10-11 19:09:32 +00:00
|
|
|
let funique_section_names = !sess.opts.debugging_opts.no_unique_section_names;
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-05-07 00:34:27 +00:00
|
|
|
let code_model = to_llvm_code_model(sess.code_model());
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-11-08 11:27:51 +00:00
|
|
|
let mut singlethread = sess.target.singlethread;
|
2018-09-01 05:41:17 +00:00
|
|
|
|
|
|
|
// On the wasm target once the `atomics` feature is enabled that means that
|
|
|
|
// we're no longer single-threaded, or otherwise we don't want LLVM to
|
|
|
|
// lower atomic operations to single-threaded operations.
|
2020-12-30 18:52:21 +00:00
|
|
|
if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
|
2018-09-01 05:41:17 +00:00
|
|
|
singlethread = false;
|
|
|
|
}
|
2017-10-23 03:01:00 +00:00
|
|
|
|
2020-10-15 09:44:00 +00:00
|
|
|
let triple = SmallCStr::new(&sess.target.llvm_target);
|
2018-08-23 18:03:22 +00:00
|
|
|
let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
|
2021-03-13 13:29:39 +00:00
|
|
|
let features = llvm_util::llvm_global_features(sess).join(",");
|
2018-04-23 22:17:07 +00:00
|
|
|
let features = CString::new(features).unwrap();
|
2020-11-08 11:27:51 +00:00
|
|
|
let abi = SmallCStr::new(&sess.target.llvm_abiname);
|
2020-11-23 23:55:10 +00:00
|
|
|
let trap_unreachable =
|
|
|
|
sess.opts.debugging_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
|
2018-09-13 17:43:15 +00:00
|
|
|
let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
|
2017-07-23 15:14:38 +00:00
|
|
|
|
2018-08-12 17:59:18 +00:00
|
|
|
let asm_comments = sess.asm_comments();
|
2020-11-08 11:27:51 +00:00
|
|
|
let relax_elf_relocations =
|
|
|
|
sess.opts.debugging_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
|
|
|
|
|
|
|
|
let use_init_array =
|
|
|
|
!sess.opts.debugging_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
|
2020-04-17 02:40:11 +00:00
|
|
|
|
2020-09-23 16:33:54 +00:00
|
|
|
Arc::new(move |config: TargetMachineFactoryConfig| {
|
|
|
|
let split_dwarf_file = config.split_dwarf_file.unwrap_or_default();
|
|
|
|
let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
|
|
|
|
|
2017-07-23 15:14:38 +00:00
|
|
|
let tm = unsafe {
|
|
|
|
llvm::LLVMRustCreateTargetMachine(
|
2019-12-24 22:38:22 +00:00
|
|
|
triple.as_ptr(),
|
|
|
|
cpu.as_ptr(),
|
|
|
|
features.as_ptr(),
|
|
|
|
abi.as_ptr(),
|
2017-07-23 15:14:38 +00:00
|
|
|
code_model,
|
|
|
|
reloc_model,
|
|
|
|
opt_level,
|
|
|
|
use_softfp,
|
|
|
|
ffunction_sections,
|
|
|
|
fdata_sections,
|
2021-10-11 19:09:32 +00:00
|
|
|
funique_section_names,
|
2017-11-11 15:08:00 +00:00
|
|
|
trap_unreachable,
|
2017-10-23 03:01:00 +00:00
|
|
|
singlethread,
|
2018-08-12 17:59:18 +00:00
|
|
|
asm_comments,
|
2018-09-13 17:43:15 +00:00
|
|
|
emit_stack_size_section,
|
2019-12-02 12:22:45 +00:00
|
|
|
relax_elf_relocations,
|
2020-04-17 02:40:11 +00:00
|
|
|
use_init_array,
|
2020-09-23 16:33:54 +00:00
|
|
|
split_dwarf_file.as_ptr(),
|
2017-07-23 15:14:38 +00:00
|
|
|
)
|
|
|
|
};
|
2014-10-29 01:58:46 +00:00
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
tm.ok_or_else(|| {
|
2019-12-24 22:38:22 +00:00
|
|
|
format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
|
2018-06-27 14:57:25 +00:00
|
|
|
})
|
2017-07-23 15:14:38 +00:00
|
|
|
})
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
2018-10-23 15:01:35 +00:00
|
|
|
pub(crate) fn save_temp_bitcode(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
2019-12-24 22:38:22 +00:00
|
|
|
name: &str,
|
2018-10-23 15:01:35 +00:00
|
|
|
) {
|
|
|
|
if !cgcx.save_temps {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-09-14 03:26:39 +00:00
|
|
|
}
|
2018-10-23 15:01:35 +00:00
|
|
|
unsafe {
|
|
|
|
let ext = format!("{}.bc", name);
|
|
|
|
let cgu = Some(&module.name[..]);
|
|
|
|
let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
|
2018-11-29 13:09:28 +00:00
|
|
|
let cstr = path_to_c_string(&path);
|
2018-10-23 15:01:35 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-17 23:20:51 +00:00
|
|
|
pub struct DiagnosticHandlers<'a> {
|
2018-10-23 15:01:35 +00:00
|
|
|
data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
|
2018-06-27 14:57:25 +00:00
|
|
|
llcx: &'a llvm::Context,
|
2021-11-12 00:00:00 +00:00
|
|
|
old_handler: Option<&'a llvm::DiagnosticHandler>,
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> DiagnosticHandlers<'a> {
|
2019-12-24 22:38:22 +00:00
|
|
|
pub fn new(
|
|
|
|
cgcx: &'a CodegenContext<LlvmCodegenBackend>,
|
|
|
|
handler: &'a Handler,
|
|
|
|
llcx: &'a llvm::Context,
|
|
|
|
) -> Self {
|
2021-11-12 00:00:00 +00:00
|
|
|
let remark_passes_all: bool;
|
|
|
|
let remark_passes: Vec<CString>;
|
|
|
|
match &cgcx.remark {
|
|
|
|
Passes::All => {
|
|
|
|
remark_passes_all = true;
|
|
|
|
remark_passes = Vec::new();
|
|
|
|
}
|
|
|
|
Passes::Some(passes) => {
|
|
|
|
remark_passes_all = false;
|
|
|
|
remark_passes =
|
|
|
|
passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let remark_passes: Vec<*const c_char> =
|
|
|
|
remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
|
2018-07-14 23:52:45 +00:00
|
|
|
let data = Box::into_raw(Box::new((cgcx, handler)));
|
2017-07-23 15:14:38 +00:00
|
|
|
unsafe {
|
2021-11-12 00:00:00 +00:00
|
|
|
let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
|
|
|
|
llvm::LLVMRustContextConfigureDiagnosticHandler(
|
|
|
|
llcx,
|
|
|
|
diagnostic_handler,
|
|
|
|
data.cast(),
|
|
|
|
remark_passes_all,
|
|
|
|
remark_passes.as_ptr(),
|
|
|
|
remark_passes.len(),
|
|
|
|
);
|
2019-10-05 07:48:14 +00:00
|
|
|
llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
|
2021-11-12 00:00:00 +00:00
|
|
|
DiagnosticHandlers { data, llcx, old_handler }
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-12 15:17:58 +00:00
|
|
|
}
|
|
|
|
|
2017-07-23 15:14:38 +00:00
|
|
|
impl<'a> Drop for DiagnosticHandlers<'a> {
|
|
|
|
fn drop(&mut self) {
|
2018-07-14 23:52:45 +00:00
|
|
|
use std::ptr::null_mut;
|
2017-07-23 15:14:38 +00:00
|
|
|
unsafe {
|
2018-07-14 23:52:45 +00:00
|
|
|
llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
|
2021-11-12 00:00:00 +00:00
|
|
|
llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
|
2018-07-14 23:52:45 +00:00
|
|
|
drop(Box::from_raw(self.data));
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
|
|
|
}
|
2014-09-12 15:17:58 +00:00
|
|
|
}
|
|
|
|
|
2020-05-26 19:07:59 +00:00
|
|
|
fn report_inline_asm(
|
2019-12-24 22:38:22 +00:00
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2020-05-26 19:07:59 +00:00
|
|
|
msg: String,
|
2020-06-09 13:37:59 +00:00
|
|
|
level: llvm::DiagnosticLevel,
|
2020-05-26 19:07:59 +00:00
|
|
|
mut cookie: c_uint,
|
|
|
|
source: Option<(String, Vec<InnerSpan>)>,
|
2019-12-24 22:38:22 +00:00
|
|
|
) {
|
2020-05-26 19:07:59 +00:00
|
|
|
// In LTO build we may get srcloc values from other crates which are invalid
|
|
|
|
// since they use a different source map. To be safe we just suppress these
|
|
|
|
// in LTO builds.
|
|
|
|
if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
|
|
|
|
cookie = 0;
|
|
|
|
}
|
2020-06-09 13:37:59 +00:00
|
|
|
let level = match level {
|
2021-07-21 03:23:22 +00:00
|
|
|
llvm::DiagnosticLevel::Error => Level::Error { lint: false },
|
2020-06-09 13:37:59 +00:00
|
|
|
llvm::DiagnosticLevel::Warning => Level::Warning,
|
|
|
|
llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
|
|
|
|
};
|
|
|
|
cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
|
2014-09-27 08:33:36 +00:00
|
|
|
}
|
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
|
2017-07-23 15:14:38 +00:00
|
|
|
if user.is_null() {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
2018-10-23 15:01:35 +00:00
|
|
|
let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
|
2015-01-22 18:43:39 +00:00
|
|
|
|
2021-07-28 19:31:47 +00:00
|
|
|
let smdiag = llvm::diagnostic::SrcMgrDiagnostic::unpack(diag);
|
|
|
|
report_inline_asm(cgcx, smdiag.message, smdiag.level, cookie, smdiag.source);
|
2015-01-22 18:43:39 +00:00
|
|
|
}
|
|
|
|
|
2018-07-13 10:59:41 +00:00
|
|
|
unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
|
2017-07-23 15:14:38 +00:00
|
|
|
if user.is_null() {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
2018-10-23 15:01:35 +00:00
|
|
|
let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
|
2014-09-12 15:17:58 +00:00
|
|
|
|
|
|
|
match llvm::diagnostic::Diagnostic::unpack(info) {
|
2015-01-22 18:43:39 +00:00
|
|
|
llvm::diagnostic::InlineAsm(inline) => {
|
2021-07-28 19:31:47 +00:00
|
|
|
report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
|
2015-01-22 18:43:39 +00:00
|
|
|
}
|
|
|
|
|
2014-09-12 15:17:58 +00:00
|
|
|
llvm::diagnostic::Optimization(opt) => {
|
|
|
|
let enabled = match cgcx.remark {
|
2018-07-26 17:22:14 +00:00
|
|
|
Passes::All => true,
|
|
|
|
Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
|
2014-09-12 15:17:58 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
if enabled {
|
2019-12-24 22:38:22 +00:00
|
|
|
diag_handler.note_without_error(&format!(
|
2021-11-12 00:00:00 +00:00
|
|
|
"{}:{}:{}: {}: {}",
|
|
|
|
opt.filename, opt.line, opt.column, opt.pass_name, opt.message,
|
2019-12-24 22:38:22 +00:00
|
|
|
));
|
2014-09-12 15:17:58 +00:00
|
|
|
}
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
|
2018-03-12 17:11:59 +00:00
|
|
|
let msg = llvm::build_string(|s| {
|
|
|
|
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
|
2019-12-24 22:38:22 +00:00
|
|
|
})
|
|
|
|
.expect("non-UTF8 diagnostic");
|
2018-03-12 20:18:01 +00:00
|
|
|
diag_handler.warn(&msg);
|
2018-03-12 17:11:59 +00:00
|
|
|
}
|
2020-09-29 11:20:56 +00:00
|
|
|
llvm::diagnostic::Unsupported(diagnostic_ref) => {
|
|
|
|
let msg = llvm::build_string(|s| {
|
|
|
|
llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
|
|
|
|
})
|
|
|
|
.expect("non-UTF8 diagnostic");
|
|
|
|
diag_handler.err(&msg);
|
|
|
|
}
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::diagnostic::UnknownDiagnostic(..) => {}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-01-05 18:16:58 +00:00
|
|
|
fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
match config.pgo_gen {
|
|
|
|
SwitchWithOptPath::Enabled(ref opt_dir_path) => {
|
|
|
|
let path = if let Some(dir_path) = opt_dir_path {
|
|
|
|
dir_path.join("default_%m.profraw")
|
|
|
|
} else {
|
|
|
|
PathBuf::from("default_%m.profraw")
|
|
|
|
};
|
|
|
|
|
|
|
|
Some(CString::new(format!("{}", path.display())).unwrap())
|
|
|
|
}
|
|
|
|
SwitchWithOptPath::Disabled => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
config
|
|
|
|
.pgo_use
|
|
|
|
.as_ref()
|
|
|
|
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
|
|
|
|
}
|
|
|
|
|
2021-05-07 07:41:37 +00:00
|
|
|
fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
|
|
|
|
config
|
|
|
|
.pgo_sample_use
|
|
|
|
.as_ref()
|
|
|
|
.map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
|
|
|
|
}
|
|
|
|
|
2021-10-08 10:10:52 +00:00
|
|
|
pub(crate) fn should_use_new_llvm_pass_manager(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
) -> bool {
|
2021-08-21 20:20:32 +00:00
|
|
|
// The new pass manager is enabled by default for LLVM >= 13.
|
|
|
|
// This matches Clang, which also enables it since Clang 13.
|
2021-10-08 10:10:52 +00:00
|
|
|
|
|
|
|
// FIXME: There are some perf issues with the new pass manager
|
|
|
|
// when targeting s390x, so it is temporarily disabled for that
|
|
|
|
// arch, see https://github.com/rust-lang/rust/issues/89609
|
|
|
|
config
|
|
|
|
.new_llvm_pass_manager
|
|
|
|
.unwrap_or_else(|| cgcx.target_arch != "s390x" && llvm_util::get_version() >= (13, 0, 0))
|
2020-01-05 18:16:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
|
2020-02-11 21:37:16 +00:00
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
2021-04-05 13:37:11 +00:00
|
|
|
diag_handler: &Handler,
|
2020-01-05 18:16:58 +00:00
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
opt_level: config::OptLevel,
|
|
|
|
opt_stage: llvm::OptStage,
|
2021-04-05 13:37:11 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2020-01-05 18:16:58 +00:00
|
|
|
let unroll_loops =
|
|
|
|
opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
|
|
|
|
let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
|
|
|
|
let pgo_gen_path = get_pgo_gen_path(config);
|
|
|
|
let pgo_use_path = get_pgo_use_path(config);
|
2021-05-07 07:41:37 +00:00
|
|
|
let pgo_sample_use_path = get_pgo_sample_use_path(config);
|
2020-01-05 18:16:58 +00:00
|
|
|
let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
|
|
|
|
// Sanitizer instrumentation is only inserted during the pre-link optimization stage.
|
|
|
|
let sanitizer_options = if !is_lto {
|
2020-06-14 00:00:00 +00:00
|
|
|
Some(llvm::SanitizerOptions {
|
|
|
|
sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
|
|
|
|
sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
|
|
|
|
sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
|
|
|
|
sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
|
2020-01-05 18:16:58 +00:00
|
|
|
sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
|
2020-06-14 00:00:00 +00:00
|
|
|
sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
|
2021-01-23 02:32:38 +00:00
|
|
|
sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
|
|
|
|
sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
|
2020-01-05 18:16:58 +00:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
|
2021-09-29 20:58:33 +00:00
|
|
|
let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
|
|
|
|
Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
|
2020-02-11 21:37:16 +00:00
|
|
|
} else {
|
2021-09-29 20:58:33 +00:00
|
|
|
None
|
2020-02-11 21:37:16 +00:00
|
|
|
};
|
|
|
|
|
2021-09-29 20:58:33 +00:00
|
|
|
let llvm_selfprofiler =
|
|
|
|
llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
|
|
|
|
|
2021-04-05 13:37:11 +00:00
|
|
|
let extra_passes = config.passes.join(",");
|
|
|
|
|
2020-01-05 18:16:58 +00:00
|
|
|
// FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
|
|
|
|
// We would have to add upstream support for this first, before we can support
|
|
|
|
// config.inline_threshold and our more aggressive default thresholds.
|
2021-04-05 13:37:11 +00:00
|
|
|
let result = llvm::LLVMRustOptimizeWithNewPassManager(
|
2020-01-05 18:16:58 +00:00
|
|
|
module.module_llvm.llmod(),
|
|
|
|
&*module.module_llvm.tm,
|
|
|
|
to_pass_builder_opt_level(opt_level),
|
|
|
|
opt_stage,
|
|
|
|
config.no_prepopulate_passes,
|
|
|
|
config.verify_llvm_ir,
|
|
|
|
using_thin_buffers,
|
|
|
|
config.merge_functions,
|
|
|
|
unroll_loops,
|
|
|
|
config.vectorize_slp,
|
|
|
|
config.vectorize_loop,
|
|
|
|
config.no_builtins,
|
2020-05-13 00:00:00 +00:00
|
|
|
config.emit_lifetime_markers,
|
2020-01-05 18:16:58 +00:00
|
|
|
sanitizer_options.as_ref(),
|
|
|
|
pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
2021-04-05 08:45:04 +00:00
|
|
|
config.instrument_coverage,
|
2021-04-05 09:26:48 +00:00
|
|
|
config.instrument_gcov,
|
2021-05-07 07:41:37 +00:00
|
|
|
pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
|
|
|
|
config.debug_info_for_profiling,
|
2020-02-11 21:37:16 +00:00
|
|
|
llvm_selfprofiler,
|
|
|
|
selfprofile_before_pass_callback,
|
|
|
|
selfprofile_after_pass_callback,
|
2021-04-05 13:37:11 +00:00
|
|
|
extra_passes.as_ptr().cast(),
|
|
|
|
extra_passes.len(),
|
2020-01-05 18:16:58 +00:00
|
|
|
);
|
2021-04-05 13:37:11 +00:00
|
|
|
result.into_result().map_err(|()| llvm_err(diag_handler, "failed to run LLVM passes"))
|
2020-01-05 18:16:58 +00:00
|
|
|
}
|
|
|
|
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
// Unsafe due to LLVM calls.
|
2019-12-24 22:38:22 +00:00
|
|
|
pub(crate) unsafe fn optimize(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
diag_handler: &Handler,
|
|
|
|
module: &ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
2021-04-05 13:37:11 +00:00
|
|
|
) -> Result<(), FatalError> {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
|
2019-09-27 12:04:36 +00:00
|
|
|
|
2018-08-20 15:13:01 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
let llcx = &*module.module_llvm.llcx;
|
|
|
|
let tm = &*module.module_llvm.tm;
|
2017-07-23 15:14:38 +00:00
|
|
|
let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
|
2014-09-12 15:17:58 +00:00
|
|
|
|
2018-05-08 13:10:16 +00:00
|
|
|
let module_name = module.name.clone();
|
2017-07-25 15:26:24 +00:00
|
|
|
let module_name = Some(&module_name[..]);
|
2016-05-14 00:48:32 +00:00
|
|
|
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
if config.emit_no_opt_bc {
|
2017-09-14 03:26:39 +00:00
|
|
|
let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
|
2018-11-29 13:09:28 +00:00
|
|
|
let out = path_to_c_string(&out);
|
2014-11-25 21:28:35 +00:00
|
|
|
llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
}
|
|
|
|
|
2019-11-18 00:00:00 +00:00
|
|
|
if let Some(opt_level) = config.opt_level {
|
2021-10-08 10:10:52 +00:00
|
|
|
if should_use_new_llvm_pass_manager(cgcx, config) {
|
2020-01-05 18:16:58 +00:00
|
|
|
let opt_stage = match cgcx.lto {
|
|
|
|
Lto::Fat => llvm::OptStage::PreLinkFatLTO,
|
|
|
|
Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
|
|
|
|
_ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
|
|
|
|
_ => llvm::OptStage::PreLinkNoLTO,
|
|
|
|
};
|
2021-04-05 13:37:11 +00:00
|
|
|
return optimize_with_new_llvm_pass_manager(
|
|
|
|
cgcx,
|
|
|
|
diag_handler,
|
|
|
|
module,
|
|
|
|
config,
|
|
|
|
opt_level,
|
|
|
|
opt_stage,
|
|
|
|
);
|
2020-01-05 18:16:58 +00:00
|
|
|
}
|
|
|
|
|
2020-02-11 21:37:16 +00:00
|
|
|
if cgcx.prof.llvm_recording_enabled() {
|
|
|
|
diag_handler
|
|
|
|
.warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
|
|
|
|
}
|
|
|
|
|
2015-07-22 23:22:51 +00:00
|
|
|
// Create the two optimizing pass managers. These mirror what clang
|
|
|
|
// does, and are by populated by LLVM's default PassManagerBuilder.
|
|
|
|
// Each manager has a different set of passes, but they also share
|
|
|
|
// some common passes.
|
|
|
|
let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
|
|
|
|
let mpm = llvm::LLVMCreatePassManager();
|
|
|
|
|
2018-07-17 11:17:47 +00:00
|
|
|
{
|
2019-07-13 18:17:16 +00:00
|
|
|
let find_pass = |pass_name: &str| {
|
2018-08-07 14:04:34 +00:00
|
|
|
let pass_name = SmallCStr::new(pass_name);
|
2019-07-13 18:17:16 +00:00
|
|
|
llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
|
2016-01-25 01:22:24 +00:00
|
|
|
};
|
2014-08-11 17:33:58 +00:00
|
|
|
|
2019-07-13 18:17:16 +00:00
|
|
|
if config.verify_llvm_ir {
|
|
|
|
// Verification should run as the very first pass.
|
|
|
|
llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut extra_passes = Vec::new();
|
|
|
|
let mut have_name_anon_globals_pass = false;
|
|
|
|
|
|
|
|
for pass_name in &config.passes {
|
|
|
|
if pass_name == "lint" {
|
|
|
|
// Linting should also be performed early, directly on the generated IR.
|
|
|
|
llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(pass) = find_pass(pass_name) {
|
|
|
|
extra_passes.push(pass);
|
|
|
|
} else {
|
|
|
|
diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
|
|
|
|
}
|
|
|
|
|
|
|
|
if pass_name == "name-anon-globals" {
|
|
|
|
have_name_anon_globals_pass = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-05 09:26:48 +00:00
|
|
|
// Instrumentation must be inserted before optimization,
|
|
|
|
// otherwise LLVM may optimize some functions away which
|
|
|
|
// breaks llvm-cov.
|
|
|
|
//
|
|
|
|
// This mirrors what Clang does in lib/CodeGen/BackendUtil.cpp.
|
|
|
|
if config.instrument_gcov {
|
|
|
|
llvm::LLVMRustAddPass(mpm, find_pass("insert-gcov-profiling").unwrap());
|
|
|
|
}
|
2021-04-05 08:45:04 +00:00
|
|
|
if config.instrument_coverage {
|
|
|
|
llvm::LLVMRustAddPass(mpm, find_pass("instrprof").unwrap());
|
|
|
|
}
|
2021-05-07 07:41:37 +00:00
|
|
|
if config.debug_info_for_profiling {
|
|
|
|
llvm::LLVMRustAddPass(mpm, find_pass("add-discriminators").unwrap());
|
|
|
|
}
|
2021-04-05 08:45:04 +00:00
|
|
|
|
2019-11-19 00:00:00 +00:00
|
|
|
add_sanitizer_passes(config, &mut extra_passes);
|
2019-11-18 00:00:00 +00:00
|
|
|
|
2018-05-30 20:46:56 +00:00
|
|
|
// Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
|
|
|
|
// to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
|
|
|
|
// we'll get errors in LLVM.
|
2018-11-02 12:22:48 +00:00
|
|
|
let using_thin_buffers = config.bitcode_needed();
|
2018-07-17 11:17:47 +00:00
|
|
|
if !config.no_prepopulate_passes {
|
2019-11-29 03:31:09 +00:00
|
|
|
llvm::LLVMAddAnalysisPasses(tm, fpm);
|
|
|
|
llvm::LLVMAddAnalysisPasses(tm, mpm);
|
2019-11-18 00:00:00 +00:00
|
|
|
let opt_level = to_llvm_opt_settings(opt_level).0;
|
2019-12-24 22:38:22 +00:00
|
|
|
let prepare_for_thin_lto = cgcx.lto == Lto::Thin
|
|
|
|
|| cgcx.lto == Lto::ThinLocal
|
|
|
|
|| (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
|
2021-09-30 17:38:50 +00:00
|
|
|
with_llvm_pmb(llmod, config, opt_level, prepare_for_thin_lto, &mut |b| {
|
2019-07-13 18:17:16 +00:00
|
|
|
llvm::LLVMRustAddLastExtensionPasses(
|
2019-12-24 22:38:22 +00:00
|
|
|
b,
|
|
|
|
extra_passes.as_ptr(),
|
|
|
|
extra_passes.len() as size_t,
|
|
|
|
);
|
2018-12-02 13:41:39 +00:00
|
|
|
llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
|
|
|
|
llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
|
|
|
|
});
|
|
|
|
|
2018-05-30 20:46:56 +00:00
|
|
|
have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
|
|
|
|
if using_thin_buffers && !prepare_for_thin_lto {
|
2019-07-13 18:17:16 +00:00
|
|
|
llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
|
2018-05-30 20:46:56 +00:00
|
|
|
have_name_anon_globals_pass = true;
|
|
|
|
}
|
2019-07-13 18:17:16 +00:00
|
|
|
} else {
|
|
|
|
// If we don't use the standard pipeline, directly populate the MPM
|
|
|
|
// with the extra passes.
|
|
|
|
for pass in extra_passes {
|
|
|
|
llvm::LLVMRustAddPass(mpm, pass);
|
2018-05-30 20:46:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if using_thin_buffers && !have_name_anon_globals_pass {
|
|
|
|
// As described above, this will probably cause an error in LLVM
|
|
|
|
if config.no_prepopulate_passes {
|
2019-12-24 22:38:22 +00:00
|
|
|
diag_handler.err(
|
|
|
|
"The current compilation is going to use thin LTO buffers \
|
2018-10-06 09:37:28 +00:00
|
|
|
without running LLVM's NameAnonGlobals pass. \
|
|
|
|
This will likely cause errors in LLVM. Consider adding \
|
2019-12-24 22:38:22 +00:00
|
|
|
-C passes=name-anon-globals to the compiler command line.",
|
|
|
|
);
|
2018-05-30 20:46:56 +00:00
|
|
|
} else {
|
2019-12-24 22:38:22 +00:00
|
|
|
bug!(
|
|
|
|
"We are using thin LTO buffers without running the NameAnonGlobals pass. \
|
|
|
|
This will likely cause errors in LLVM and should never happen."
|
|
|
|
);
|
2018-05-30 20:46:56 +00:00
|
|
|
}
|
2015-04-08 19:52:58 +00:00
|
|
|
}
|
2015-07-22 23:22:51 +00:00
|
|
|
}
|
2015-04-08 19:52:58 +00:00
|
|
|
|
2017-07-24 11:54:18 +00:00
|
|
|
diag_handler.abort_if_errors();
|
2015-04-08 19:52:58 +00:00
|
|
|
|
2015-07-22 23:22:51 +00:00
|
|
|
// Finally, run the actual optimization passes
|
2019-02-13 13:13:30 +00:00
|
|
|
{
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.extra_verbose_generic_activity(
|
|
|
|
"LLVM_module_optimize_function_passes",
|
|
|
|
&module.name[..],
|
|
|
|
);
|
2020-01-01 01:24:05 +00:00
|
|
|
llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
|
2019-02-13 13:13:30 +00:00
|
|
|
}
|
|
|
|
{
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.extra_verbose_generic_activity(
|
|
|
|
"LLVM_module_optimize_module_passes",
|
|
|
|
&module.name[..],
|
|
|
|
);
|
2020-01-01 01:24:05 +00:00
|
|
|
llvm::LLVMRunPassManager(mpm, llmod);
|
2019-02-13 13:13:30 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2015-07-22 23:22:51 +00:00
|
|
|
// Deallocate managers that we're now done with
|
|
|
|
llvm::LLVMDisposePassManager(fpm);
|
|
|
|
llvm::LLVMDisposePassManager(mpm);
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
2021-04-05 13:37:11 +00:00
|
|
|
Ok(())
|
2017-07-23 15:14:38 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
|
2020-06-14 00:00:00 +00:00
|
|
|
if config.sanitizer.contains(SanitizerSet::ADDRESS) {
|
|
|
|
let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
|
|
|
|
passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
|
|
|
|
passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
|
|
|
|
}
|
|
|
|
if config.sanitizer.contains(SanitizerSet::MEMORY) {
|
|
|
|
let track_origins = config.sanitizer_memory_track_origins as c_int;
|
|
|
|
let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
|
|
|
|
passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
|
|
|
|
}
|
|
|
|
if config.sanitizer.contains(SanitizerSet::THREAD) {
|
|
|
|
passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
|
2019-11-19 00:00:00 +00:00
|
|
|
}
|
2021-01-23 02:32:38 +00:00
|
|
|
if config.sanitizer.contains(SanitizerSet::HWADDRESS) {
|
|
|
|
let recover = config.sanitizer_recover.contains(SanitizerSet::HWADDRESS);
|
|
|
|
passes.push(llvm::LLVMRustCreateHWAddressSanitizerPass(recover));
|
|
|
|
}
|
2019-11-19 00:00:00 +00:00
|
|
|
}
|
|
|
|
|
2020-09-09 04:51:16 +00:00
|
|
|
pub(crate) fn link(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
diag_handler: &Handler,
|
|
|
|
mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
|
|
|
|
) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
|
|
|
|
use super::lto::{Linker, ModuleBuffer};
|
|
|
|
// Sort the modules by name to ensure to ensure deterministic behavior.
|
|
|
|
modules.sort_by(|a, b| a.name.cmp(&b.name));
|
|
|
|
let (first, elements) =
|
|
|
|
modules.split_first().expect("Bug! modules must contain at least one module.");
|
|
|
|
|
|
|
|
let mut linker = Linker::new(first.module_llvm.llmod());
|
|
|
|
for module in elements {
|
|
|
|
let _timer =
|
|
|
|
cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
|
|
|
|
let buffer = ModuleBuffer::new(module.module_llvm.llmod());
|
2021-09-30 17:38:50 +00:00
|
|
|
linker.add(buffer.data()).map_err(|()| {
|
2020-09-09 04:51:16 +00:00
|
|
|
let msg = format!("failed to serialize module {:?}", module.name);
|
2021-09-30 17:38:50 +00:00
|
|
|
llvm_err(diag_handler, &msg)
|
2020-09-09 04:51:16 +00:00
|
|
|
})?;
|
|
|
|
}
|
|
|
|
drop(linker);
|
|
|
|
Ok(modules.remove(0))
|
|
|
|
}
|
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
pub(crate) unsafe fn codegen(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
diag_handler: &Handler,
|
|
|
|
module: ModuleCodegen<ModuleLlvm>,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
) -> Result<CompiledModule, FatalError> {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
|
2014-12-09 18:44:51 +00:00
|
|
|
{
|
2018-08-20 15:13:01 +00:00
|
|
|
let llmod = module.module_llvm.llmod();
|
|
|
|
let llcx = &*module.module_llvm.llcx;
|
|
|
|
let tm = &*module.module_llvm.tm;
|
2018-06-27 14:57:25 +00:00
|
|
|
let module_name = module.name.clone();
|
|
|
|
let module_name = Some(&module_name[..]);
|
|
|
|
let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
|
2017-10-20 01:44:33 +00:00
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
if cgcx.msvc_imps_needed {
|
|
|
|
create_msvc_imps(cgcx, llcx, llmod);
|
2017-10-20 01:44:33 +00:00
|
|
|
}
|
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
// A codegen-specific pass manager is used to generate object
|
|
|
|
// files for an LLVM module.
|
|
|
|
//
|
|
|
|
// Apparently each of these pass managers is a one-shot kind of
|
|
|
|
// thing, so we create a new one for each type of output. The
|
|
|
|
// pass manager passed to the closure should be ensured to not
|
|
|
|
// escape the closure itself, and the manager should only be
|
|
|
|
// used once.
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe fn with_codegen<'ll, F, R>(
|
|
|
|
tm: &'ll llvm::TargetMachine,
|
|
|
|
llmod: &'ll llvm::Module,
|
|
|
|
no_builtins: bool,
|
|
|
|
f: F,
|
|
|
|
) -> R
|
|
|
|
where
|
|
|
|
F: FnOnce(&'ll mut PassManager<'ll>) -> R,
|
2018-06-27 14:57:25 +00:00
|
|
|
{
|
|
|
|
let cpm = llvm::LLVMCreatePassManager();
|
2019-11-29 03:31:09 +00:00
|
|
|
llvm::LLVMAddAnalysisPasses(tm, cpm);
|
2018-06-27 14:57:25 +00:00
|
|
|
llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
|
|
|
|
f(cpm)
|
|
|
|
}
|
|
|
|
|
2020-03-20 01:09:24 +00:00
|
|
|
// Two things to note:
|
|
|
|
// - If object files are just LLVM bitcode we write bitcode, copy it to
|
|
|
|
// the .o file, and delete the bitcode if it wasn't otherwise
|
|
|
|
// requested.
|
|
|
|
// - If we don't have the integrated assembler then we need to emit
|
|
|
|
// asm from LLVM and use `gcc` to create the object file.
|
2018-06-27 14:57:25 +00:00
|
|
|
|
|
|
|
let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
|
|
|
|
let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
|
|
|
|
|
2020-03-20 01:09:24 +00:00
|
|
|
if config.bitcode_needed() {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
|
2018-11-01 20:06:50 +00:00
|
|
|
let thin = ThinBuffer::new(llmod);
|
|
|
|
let data = thin.data();
|
2018-03-09 15:25:54 +00:00
|
|
|
|
2021-11-08 15:59:36 +00:00
|
|
|
if let Some(bitcode_filename) = bc_out.file_name() {
|
|
|
|
cgcx.prof.artifact_size(
|
|
|
|
"llvm_bitcode",
|
|
|
|
bitcode_filename.to_string_lossy(),
|
|
|
|
data.len() as u64,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg(
|
|
|
|
"LLVM_module_codegen_emit_bitcode",
|
|
|
|
&module.name[..],
|
|
|
|
);
|
2018-06-27 14:57:25 +00:00
|
|
|
if let Err(e) = fs::write(&bc_out, data) {
|
2019-04-06 00:48:23 +00:00
|
|
|
let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
|
|
|
|
diag_handler.err(&msg);
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
2017-10-20 01:44:33 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
|
2020-02-07 14:01:23 +00:00
|
|
|
let _timer = cgcx.prof.generic_activity_with_arg(
|
|
|
|
"LLVM_module_codegen_embed_bitcode",
|
|
|
|
&module.name[..],
|
|
|
|
);
|
2020-05-07 23:48:30 +00:00
|
|
|
embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
if config.emit_ir {
|
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
|
|
|
|
let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
|
|
|
|
let out_c = path_to_c_string(&out);
|
|
|
|
|
|
|
|
extern "C" fn demangle_callback(
|
|
|
|
input_ptr: *const c_char,
|
|
|
|
input_len: size_t,
|
|
|
|
output_ptr: *mut c_char,
|
|
|
|
output_len: size_t,
|
|
|
|
) -> size_t {
|
|
|
|
let input =
|
|
|
|
unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
|
|
|
|
|
|
|
|
let input = match str::from_utf8(input) {
|
|
|
|
Ok(s) => s,
|
|
|
|
Err(_) => return 0,
|
|
|
|
};
|
|
|
|
|
|
|
|
let output = unsafe {
|
|
|
|
slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
|
|
|
|
};
|
|
|
|
let mut cursor = io::Cursor::new(output);
|
|
|
|
|
|
|
|
let demangled = match rustc_demangle::try_demangle(input) {
|
|
|
|
Ok(d) => d,
|
|
|
|
Err(_) => return 0,
|
|
|
|
};
|
|
|
|
|
|
|
|
if write!(cursor, "{:#}", demangled).is_err() {
|
|
|
|
// Possible only if provided buffer is not big enough
|
|
|
|
return 0;
|
2017-06-29 14:52:43 +00:00
|
|
|
}
|
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
cursor.position() as size_t
|
2020-01-01 01:24:05 +00:00
|
|
|
}
|
run optimization and codegen on worker threads
Refactor the code in `llvm::back` that invokes LLVM optimization and codegen
passes so that it can be called from worker threads. (Previously, it used
`&Session` extensively, and `Session` is not `Share`.) The new code can handle
multiple compilation units, by compiling each unit to `crate.0.o`, `crate.1.o`,
etc., and linking together all the `crate.N.o` files into a single `crate.o`
using `ld -r`. The later linking steps can then be run unchanged.
The new code preserves the behavior of `--emit`/`-o` when building a single
compilation unit. With multiple compilation units, the `--emit=asm/ir/bc`
options produce multiple files, so combinations like `--emit=ir -o foo.ll` will
not actually produce `foo.ll` (they instead produce several `foo.N.ll` files).
The new code supports `-Z lto` only when using a single compilation unit.
Compiling with multiple compilation units and `-Z lto` will produce an error.
(I can't think of any good reason to do such a thing.) Linking with `-Z lto`
against a library that was built as multiple compilation units will also fail,
because the rlib does not contain a `crate.bytecode.deflate` file. This could
be supported in the future by linking together the `crate.N.bc` files produced
when compiling the library into a single `crate.bc`, or by making the LTO code
support multiple `crate.N.bytecode.deflate` files.
2014-07-17 17:52:52 +00:00
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
if result == llvm::LLVMRustResult::Success {
|
|
|
|
record_artifact_size(&cgcx.prof, "llvm_ir", &out);
|
|
|
|
}
|
|
|
|
|
2020-03-20 01:46:27 +00:00
|
|
|
result.into_result().map_err(|()| {
|
|
|
|
let msg = format!("failed to write LLVM IR to {}", out.display());
|
|
|
|
llvm_err(diag_handler, &msg)
|
|
|
|
})?;
|
|
|
|
}
|
2020-01-01 01:24:05 +00:00
|
|
|
|
2020-03-24 03:06:47 +00:00
|
|
|
if config.emit_asm {
|
2020-03-20 01:46:27 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
|
|
|
|
let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
|
|
|
|
|
2020-03-24 03:06:47 +00:00
|
|
|
// We can't use the same module for asm and object code output,
|
|
|
|
// because that triggers various errors like invalid IR or broken
|
|
|
|
// binaries. So we must clone the module to produce the asm output
|
|
|
|
// if we are also producing object code.
|
|
|
|
let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
|
|
|
|
llvm::LLVMCloneModule(llmod)
|
|
|
|
} else {
|
|
|
|
llmod
|
|
|
|
};
|
2020-03-20 01:46:27 +00:00
|
|
|
with_codegen(tm, llmod, config.no_builtins, |cpm| {
|
2020-09-23 16:33:54 +00:00
|
|
|
write_output_file(
|
|
|
|
diag_handler,
|
|
|
|
tm,
|
|
|
|
cpm,
|
|
|
|
llmod,
|
|
|
|
&path,
|
|
|
|
None,
|
|
|
|
llvm::FileType::AssemblyFile,
|
2021-11-08 15:59:36 +00:00
|
|
|
&cgcx.prof,
|
2020-09-23 16:33:54 +00:00
|
|
|
)
|
2020-03-20 01:46:27 +00:00
|
|
|
})?;
|
|
|
|
}
|
|
|
|
|
2020-03-26 02:53:03 +00:00
|
|
|
match config.emit_obj {
|
|
|
|
EmitObj::ObjectCode(_) => {
|
2020-03-24 03:06:47 +00:00
|
|
|
let _timer = cgcx
|
|
|
|
.prof
|
|
|
|
.generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
|
2020-09-23 16:33:54 +00:00
|
|
|
|
|
|
|
let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
|
2020-11-30 16:39:08 +00:00
|
|
|
let dwo_out = match cgcx.split_debuginfo {
|
2020-09-23 16:33:54 +00:00
|
|
|
// Don't change how DWARF is emitted in single mode (or when disabled).
|
2020-11-30 16:39:08 +00:00
|
|
|
SplitDebuginfo::Off | SplitDebuginfo::Packed => None,
|
2020-09-23 16:33:54 +00:00
|
|
|
// Emit (a subset of the) DWARF into a separate file in split mode.
|
2020-11-30 16:39:08 +00:00
|
|
|
SplitDebuginfo::Unpacked => {
|
|
|
|
if cgcx.target_can_use_split_dwarf {
|
|
|
|
Some(dwo_out.as_path())
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
2020-09-23 16:33:54 +00:00
|
|
|
};
|
|
|
|
|
2020-03-24 03:06:47 +00:00
|
|
|
with_codegen(tm, llmod, config.no_builtins, |cpm| {
|
|
|
|
write_output_file(
|
|
|
|
diag_handler,
|
|
|
|
tm,
|
|
|
|
cpm,
|
|
|
|
llmod,
|
|
|
|
&obj_out,
|
2020-09-23 16:33:54 +00:00
|
|
|
dwo_out,
|
2020-03-24 03:06:47 +00:00
|
|
|
llvm::FileType::ObjectFile,
|
2021-11-08 15:59:36 +00:00
|
|
|
&cgcx.prof,
|
2020-03-24 03:06:47 +00:00
|
|
|
)
|
|
|
|
})?;
|
2020-01-01 01:24:05 +00:00
|
|
|
}
|
2015-11-27 19:44:33 +00:00
|
|
|
|
2020-03-26 02:53:03 +00:00
|
|
|
EmitObj::Bitcode => {
|
|
|
|
debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
|
|
|
|
if let Err(e) = link_or_copy(&bc_out, &obj_out) {
|
|
|
|
diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
|
|
|
|
}
|
|
|
|
|
|
|
|
if !config.emit_bc {
|
|
|
|
debug!("removing_bitcode {:?}", bc_out);
|
2021-02-14 16:27:08 +00:00
|
|
|
ensure_removed(diag_handler, &bc_out);
|
2020-03-20 22:15:07 +00:00
|
|
|
}
|
2018-06-27 14:57:25 +00:00
|
|
|
}
|
2020-03-26 02:53:03 +00:00
|
|
|
|
|
|
|
EmitObj::None => {}
|
2015-11-27 19:44:33 +00:00
|
|
|
}
|
|
|
|
|
2018-06-27 14:57:25 +00:00
|
|
|
drop(handlers);
|
|
|
|
}
|
2020-03-24 03:06:47 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
Ok(module.into_compiled_module(
|
Introduce `EmitObj`.
Currently, there are three fields in `ModuleConfig` that dictate
how object files are emitted: `emit_obj`, `obj_is_bitcode`, and
`embed_bitcode`.
Some of the combinations of these fields are nonsensical, in particular
having both `obj_is_bitcode` and `embed_bitcode` true at the same time.
Also, currently:
- we needlessly emit and then delete a bytecode file if `obj_is_bitcode`
is true but `emit_obj` is false;
- we needlessly embed bitcode in the LLVM module if `embed_bitcode` is
true and `emit_obj` is false.
This commit combines the three fields into one, with a new type
`EmitObj` (and the auxiliary `BitcodeSection`) which can encode five
different possibilities.
In the old code, `set_flags` would set `obj_is_bitcode` and
`embed_bitcode` on all three of the configs (`modules`, `allocator`,
`metadata`) if the relevant other conditions were met, even if no object
code needed to be emitted for one or more of them. Whereas
`start_async_codegen` would set `emit_obj`, but only for those configs
that need it.
In the new code, `start_async_codegen` does all the work of setting
`emit_obj`, and it only does that for the configs that need it.
`set_flags` no longer sets anything related to object file emission.
2020-03-24 01:24:52 +00:00
|
|
|
config.emit_obj != EmitObj::None,
|
2020-11-30 16:39:08 +00:00
|
|
|
cgcx.target_can_use_split_dwarf && cgcx.split_debuginfo == SplitDebuginfo::Unpacked,
|
2019-12-24 22:38:22 +00:00
|
|
|
config.emit_bc,
|
|
|
|
&cgcx.output_filenames,
|
|
|
|
))
|
2016-06-30 20:32:13 +00:00
|
|
|
}
|
|
|
|
|
2018-03-09 15:25:54 +00:00
|
|
|
/// Embed the bitcode of an LLVM module in the LLVM module itself.
|
|
|
|
///
|
|
|
|
/// This is done primarily for iOS where it appears to be standard to compile C
|
|
|
|
/// code at least with `-fembed-bitcode` which creates two sections in the
|
|
|
|
/// executable:
|
|
|
|
///
|
|
|
|
/// * __LLVM,__bitcode
|
|
|
|
/// * __LLVM,__cmdline
|
|
|
|
///
|
|
|
|
/// It appears *both* of these sections are necessary to get the linker to
|
2020-05-07 05:34:31 +00:00
|
|
|
/// recognize what's going on. A suitable cmdline value is taken from the
|
|
|
|
/// target spec.
|
2018-03-09 15:25:54 +00:00
|
|
|
///
|
|
|
|
/// Furthermore debug/O1 builds don't actually embed bitcode but rather just
|
|
|
|
/// embed an empty section.
|
|
|
|
///
|
|
|
|
/// Basically all of this is us attempting to follow in the footsteps of clang
|
|
|
|
/// on iOS. See #35968 for lots more info.
|
2019-12-24 22:38:22 +00:00
|
|
|
unsafe fn embed_bitcode(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
llcx: &llvm::Context,
|
|
|
|
llmod: &llvm::Module,
|
2020-05-07 05:34:31 +00:00
|
|
|
cmdline: &str,
|
2020-05-07 23:48:30 +00:00
|
|
|
bitcode: &[u8],
|
2019-12-24 22:38:22 +00:00
|
|
|
) {
|
2020-05-07 23:48:30 +00:00
|
|
|
let llconst = common::bytes_in_context(llcx, bitcode);
|
2018-03-09 15:25:54 +00:00
|
|
|
let llglobal = llvm::LLVMAddGlobal(
|
|
|
|
llmod,
|
2018-09-06 21:44:51 +00:00
|
|
|
common::val_ty(llconst),
|
2019-10-05 07:48:14 +00:00
|
|
|
"rustc.embedded.module\0".as_ptr().cast(),
|
2018-03-09 15:25:54 +00:00
|
|
|
);
|
|
|
|
llvm::LLVMSetInitializer(llglobal, llconst);
|
2018-04-17 11:15:27 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
|
2020-05-07 05:34:31 +00:00
|
|
|
|| cgcx.opts.target_triple.triple().contains("-darwin")
|
|
|
|
|| cgcx.opts.target_triple.triple().contains("-tvos");
|
2018-04-17 11:15:27 +00:00
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
|
2019-10-05 07:48:14 +00:00
|
|
|
llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
|
2018-03-09 15:25:54 +00:00
|
|
|
llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
|
2018-04-16 12:27:37 +00:00
|
|
|
llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
|
2018-03-09 15:25:54 +00:00
|
|
|
|
2020-05-07 05:34:31 +00:00
|
|
|
let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
|
2018-03-09 15:25:54 +00:00
|
|
|
let llglobal = llvm::LLVMAddGlobal(
|
|
|
|
llmod,
|
2018-09-06 21:44:51 +00:00
|
|
|
common::val_ty(llconst),
|
2019-10-05 07:48:14 +00:00
|
|
|
"rustc.embedded.cmdline\0".as_ptr().cast(),
|
2018-03-09 15:25:54 +00:00
|
|
|
);
|
|
|
|
llvm::LLVMSetInitializer(llglobal, llconst);
|
2019-12-24 22:38:22 +00:00
|
|
|
let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
|
2019-10-05 07:48:14 +00:00
|
|
|
llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
|
2018-03-09 15:25:54 +00:00
|
|
|
llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
|
2020-04-23 18:45:55 +00:00
|
|
|
|
|
|
|
// We're adding custom sections to the output object file, but we definitely
|
|
|
|
// do not want these custom sections to make their way into the final linked
|
|
|
|
// executable. The purpose of these custom sections is for tooling
|
|
|
|
// surrounding object files to work with the LLVM IR, if necessary. For
|
|
|
|
// example rustc's own LTO will look for LLVM IR inside of the object file
|
|
|
|
// in these sections by default.
|
|
|
|
//
|
|
|
|
// To handle this is a bit different depending on the object file format
|
|
|
|
// used by the backend, broken down into a few different categories:
|
|
|
|
//
|
|
|
|
// * Mach-O - this is for macOS. Inspecting the source code for the native
|
|
|
|
// linker here shows that the `.llvmbc` and `.llvmcmd` sections are
|
|
|
|
// automatically skipped by the linker. In that case there's nothing extra
|
|
|
|
// that we need to do here.
|
|
|
|
//
|
|
|
|
// * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
|
|
|
|
// `.llvmcmd` sections, so there's nothing extra we need to do.
|
|
|
|
//
|
|
|
|
// * COFF - if we don't do anything the linker will by default copy all
|
|
|
|
// these sections to the output artifact, not what we want! To subvert
|
|
|
|
// this we want to flag the sections we inserted here as
|
|
|
|
// `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
|
|
|
|
// do this. Thankfully though we can do this with some inline assembly,
|
|
|
|
// which is easy enough to add via module-level global inline asm.
|
|
|
|
//
|
|
|
|
// * ELF - this is very similar to COFF above. One difference is that these
|
|
|
|
// sections are removed from the output linked artifact when
|
|
|
|
// `--gc-sections` is passed, which we pass by default. If that flag isn't
|
|
|
|
// passed though then these sections will show up in the final output.
|
|
|
|
// Additionally the flag that we need to set here is `SHF_EXCLUDE`.
|
|
|
|
if is_apple
|
|
|
|
|| cgcx.opts.target_triple.triple().starts_with("wasm")
|
|
|
|
|| cgcx.opts.target_triple.triple().starts_with("asmjs")
|
|
|
|
{
|
|
|
|
// nothing to do here
|
2020-11-11 21:54:23 +00:00
|
|
|
} else if cgcx.is_pe_coff {
|
2020-04-23 18:45:55 +00:00
|
|
|
let asm = "
|
|
|
|
.section .llvmbc,\"n\"
|
|
|
|
.section .llvmcmd,\"n\"
|
|
|
|
";
|
|
|
|
llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
|
|
|
|
} else {
|
|
|
|
let asm = "
|
2020-10-23 19:54:00 +00:00
|
|
|
.section .llvmbc,\"e\"
|
|
|
|
.section .llvmcmd,\"e\"
|
2020-04-23 18:45:55 +00:00
|
|
|
";
|
|
|
|
llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
|
|
|
|
}
|
2018-03-09 15:25:54 +00:00
|
|
|
}
|
|
|
|
|
2019-12-24 22:38:22 +00:00
|
|
|
pub unsafe fn with_llvm_pmb(
|
|
|
|
llmod: &llvm::Module,
|
|
|
|
config: &ModuleConfig,
|
|
|
|
opt_level: llvm::CodeGenOptLevel,
|
|
|
|
prepare_for_thin_lto: bool,
|
|
|
|
f: &mut dyn FnMut(&llvm::PassManagerBuilder),
|
|
|
|
) {
|
2018-02-19 00:57:12 +00:00
|
|
|
use std::ptr;
|
|
|
|
|
2014-08-11 17:33:58 +00:00
|
|
|
// Create the PassManagerBuilder for LLVM. We configure it with
|
|
|
|
// reasonable defaults and prepare it to actually populate the pass
|
|
|
|
// manager.
|
|
|
|
let builder = llvm::LLVMPassManagerBuilderCreate();
|
2021-01-11 19:45:33 +00:00
|
|
|
let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
|
2015-11-20 00:07:09 +00:00
|
|
|
let inline_threshold = config.inline_threshold;
|
2020-01-05 18:16:58 +00:00
|
|
|
let pgo_gen_path = get_pgo_gen_path(config);
|
|
|
|
let pgo_use_path = get_pgo_use_path(config);
|
2021-05-07 07:41:37 +00:00
|
|
|
let pgo_sample_use_path = get_pgo_sample_use_path(config);
|
2018-02-19 00:57:12 +00:00
|
|
|
|
|
|
|
llvm::LLVMRustConfigurePassManagerBuilder(
|
|
|
|
builder,
|
|
|
|
opt_level,
|
|
|
|
config.merge_functions,
|
|
|
|
config.vectorize_slp,
|
|
|
|
config.vectorize_loop,
|
2018-05-12 12:07:20 +00:00
|
|
|
prepare_for_thin_lto,
|
2018-02-19 00:57:12 +00:00
|
|
|
pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
|
|
|
|
pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
|
2021-05-07 07:41:37 +00:00
|
|
|
pgo_sample_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
|
2018-02-19 00:57:12 +00:00
|
|
|
);
|
|
|
|
|
2016-03-27 19:42:47 +00:00
|
|
|
llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
|
|
|
|
|
|
|
|
if opt_size != llvm::CodeGenOptSizeNone {
|
|
|
|
llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
|
|
|
|
}
|
rustc: Update LLVM
This commit updates the LLVM submodule in use to the current HEAD of the LLVM
repository. This is primarily being done to start picking up unwinding support
for MSVC, which is currently unimplemented in the revision of LLVM we are using.
Along the way a few changes had to be made:
* As usual, lots of C++ debuginfo bindings in LLVM changed, so there were some
significant changes to our RustWrapper.cpp
* As usual, some pass management changed in LLVM, so clang was re-scrutinized to
ensure that we're doing the same thing as clang.
* Some optimization options are now passed directly into the
`PassManagerBuilder` instead of through CLI switches to LLVM.
* The `NoFramePointerElim` option was removed from LLVM, favoring instead the
`no-frame-pointer-elim` function attribute instead.
Additionally, LLVM has picked up some new optimizations which required fixing an
existing soundness hole in the IR we generate. It appears that the current LLVM
we use does not expose this hole. When an enum is moved, the previous slot in
memory is overwritten with a bit pattern corresponding to "dropped". When the
drop glue for this slot is run, however, the switch on the discriminant can
often start executing the `unreachable` block of the switch due to the
discriminant now being outside the normal range. This was patched over locally
for now by having the `unreachable` block just change to a `ret void`.
2015-05-14 19:10:43 +00:00
|
|
|
|
|
|
|
llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
|
|
|
|
|
|
|
|
// Here we match what clang does (kinda). For O0 we only inline
|
|
|
|
// always-inline functions (but don't add lifetime intrinsics), at O1 we
|
|
|
|
// inline with lifetime intrinsics, and O2+ we add an inliner with a
|
|
|
|
// thresholds copied from clang.
|
2016-03-27 19:42:47 +00:00
|
|
|
match (opt_level, opt_size, inline_threshold) {
|
2016-08-26 16:23:42 +00:00
|
|
|
(.., Some(t)) => {
|
2021-02-24 00:00:00 +00:00
|
|
|
llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t);
|
2015-11-20 00:07:09 +00:00
|
|
|
}
|
2016-08-26 16:23:42 +00:00
|
|
|
(llvm::CodeGenOptLevel::Aggressive, ..) => {
|
2016-03-27 19:42:47 +00:00
|
|
|
llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
|
|
|
|
}
|
|
|
|
(_, llvm::CodeGenOptSizeDefault, _) => {
|
|
|
|
llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
|
|
|
|
}
|
|
|
|
(_, llvm::CodeGenOptSizeAggressive, _) => {
|
|
|
|
llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
|
|
|
|
}
|
2016-08-26 16:23:42 +00:00
|
|
|
(llvm::CodeGenOptLevel::None, ..) => {
|
2020-05-13 00:00:00 +00:00
|
|
|
llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
2016-08-26 16:23:42 +00:00
|
|
|
(llvm::CodeGenOptLevel::Less, ..) => {
|
2020-05-13 00:00:00 +00:00
|
|
|
llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
2016-08-26 16:23:42 +00:00
|
|
|
(llvm::CodeGenOptLevel::Default, ..) => {
|
rustc: Update LLVM
This commit updates the LLVM submodule in use to the current HEAD of the LLVM
repository. This is primarily being done to start picking up unwinding support
for MSVC, which is currently unimplemented in the revision of LLVM we are using.
Along the way a few changes had to be made:
* As usual, lots of C++ debuginfo bindings in LLVM changed, so there were some
significant changes to our RustWrapper.cpp
* As usual, some pass management changed in LLVM, so clang was re-scrutinized to
ensure that we're doing the same thing as clang.
* Some optimization options are now passed directly into the
`PassManagerBuilder` instead of through CLI switches to LLVM.
* The `NoFramePointerElim` option was removed from LLVM, favoring instead the
`no-frame-pointer-elim` function attribute instead.
Additionally, LLVM has picked up some new optimizations which required fixing an
existing soundness hole in the IR we generate. It appears that the current LLVM
we use does not expose this hole. When an enum is moved, the previous slot in
memory is overwritten with a bit pattern corresponding to "dropped". When the
drop glue for this slot is run, however, the switch on the discriminant can
often start executing the `unreachable` block of the switch due to the
discriminant now being outside the normal range. This was patched over locally
for now by having the `unreachable` block just change to a `ret void`.
2015-05-14 19:10:43 +00:00
|
|
|
llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
|
2014-08-11 17:33:58 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-07-22 23:22:51 +00:00
|
|
|
f(builder);
|
2014-08-11 17:33:58 +00:00
|
|
|
llvm::LLVMPassManagerBuilderDispose(builder);
|
|
|
|
}
|
2017-07-21 15:15:18 +00:00
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
|
|
|
|
// This is required to satisfy `dllimport` references to static data in .rlibs
|
|
|
|
// when using MSVC linker. We do this only for data, as linker can fix up
|
|
|
|
// code references on its own.
|
|
|
|
// See #26591, #27438
|
2018-10-23 15:01:35 +00:00
|
|
|
fn create_msvc_imps(
|
|
|
|
cgcx: &CodegenContext<LlvmCodegenBackend>,
|
|
|
|
llcx: &llvm::Context,
|
2019-12-24 22:38:22 +00:00
|
|
|
llmod: &llvm::Module,
|
2018-10-23 15:01:35 +00:00
|
|
|
) {
|
2017-10-17 20:08:13 +00:00
|
|
|
if !cgcx.msvc_imps_needed {
|
2019-12-24 22:38:22 +00:00
|
|
|
return;
|
2017-10-17 20:08:13 +00:00
|
|
|
}
|
|
|
|
// The x86 ABI seems to require that leading underscores are added to symbol
|
2019-05-16 22:05:56 +00:00
|
|
|
// names, so we need an extra underscore on x86. There's also a leading
|
2018-11-27 02:59:49 +00:00
|
|
|
// '\x01' here which disables LLVM's symbol mangling (e.g., no extra
|
2017-10-17 20:08:13 +00:00
|
|
|
// underscores added in front).
|
2019-12-24 22:38:22 +00:00
|
|
|
let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
|
2019-04-09 12:47:00 +00:00
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
unsafe {
|
2018-09-06 21:44:51 +00:00
|
|
|
let i8p_ty = Type::i8p_llcx(llcx);
|
2017-10-17 20:08:13 +00:00
|
|
|
let globals = base::iter_globals(llmod)
|
|
|
|
.filter(|&val| {
|
2019-12-24 22:38:22 +00:00
|
|
|
llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
|
|
|
|
&& llvm::LLVMIsDeclaration(val) == 0
|
2017-10-17 20:08:13 +00:00
|
|
|
})
|
2019-04-09 12:47:00 +00:00
|
|
|
.filter_map(|val| {
|
|
|
|
// Exclude some symbols that we know are not Rust symbols.
|
2019-12-04 20:00:28 +00:00
|
|
|
let name = llvm::get_value_name(val);
|
2019-12-24 22:38:22 +00:00
|
|
|
if ignored(name) { None } else { Some((val, name)) }
|
2019-04-09 12:47:00 +00:00
|
|
|
})
|
|
|
|
.map(move |(val, name)| {
|
2017-10-17 20:08:13 +00:00
|
|
|
let mut imp_name = prefix.as_bytes().to_vec();
|
2019-12-04 20:00:28 +00:00
|
|
|
imp_name.extend(name);
|
2017-10-17 20:08:13 +00:00
|
|
|
let imp_name = CString::new(imp_name).unwrap();
|
|
|
|
(imp_name, val)
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
2019-04-09 12:47:00 +00:00
|
|
|
|
2017-10-17 20:08:13 +00:00
|
|
|
for (imp_name, val) in globals {
|
2019-12-24 22:38:22 +00:00
|
|
|
let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
|
2017-10-17 20:08:13 +00:00
|
|
|
llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
|
|
|
|
llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
|
|
|
|
}
|
|
|
|
}
|
2019-04-09 12:47:00 +00:00
|
|
|
|
|
|
|
// Use this function to exclude certain symbols from `__imp` generation.
|
|
|
|
fn ignored(symbol_name: &[u8]) -> bool {
|
|
|
|
// These are symbols generated by LLVM's profiling instrumentation
|
|
|
|
symbol_name.starts_with(b"__llvm_profile_")
|
|
|
|
}
|
2017-10-17 20:08:13 +00:00
|
|
|
}
|
2021-11-08 15:59:36 +00:00
|
|
|
|
|
|
|
fn record_artifact_size(
|
|
|
|
self_profiler_ref: &SelfProfilerRef,
|
|
|
|
artifact_kind: &'static str,
|
|
|
|
path: &Path,
|
|
|
|
) {
|
|
|
|
// Don't stat the file if we are not going to record its size.
|
|
|
|
if !self_profiler_ref.enabled() {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(artifact_name) = path.file_name() {
|
|
|
|
let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
|
|
|
|
self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
|
|
|
|
}
|
|
|
|
}
|