]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/back/write.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / back / write.rs
CommitLineData
9fa01778 1use crate::back::lto::ThinBuffer;
74b04a01
XL
2use crate::back::profiling::{
3 selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
4};
9fa01778 5use crate::base;
dfeec247 6use crate::common;
9fa01778 7use crate::consts;
f2b60f7d 8use crate::llvm::{self, DiagnosticInfo, PassManager};
9fa01778 9use crate::llvm_util;
9fa01778 10use crate::type_::Type;
9fa01778 11use crate::LlvmCodegenBackend;
dfeec247 12use crate::ModuleLlvm;
6a06907d 13use rustc_codegen_ssa::back::link::ensure_removed;
fc512014
XL
14use rustc_codegen_ssa::back::write::{
15 BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
16 TargetMachineFactoryFn,
17};
dfeec247 18use rustc_codegen_ssa::traits::*;
f9f354fc 19use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
3c0e092e 20use rustc_data_structures::profiling::SelfProfilerRef;
b7449926 21use rustc_data_structures::small_c_str::SmallCStr;
f035d41b 22use rustc_errors::{FatalError, Handler, Level};
dfeec247 23use rustc_fs_util::{link_or_copy, path_to_c_string};
ba9703b0 24use rustc_middle::ty::TyCtxt;
a2a8927a 25use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
ba9703b0 26use rustc_session::Session;
f035d41b 27use rustc_span::symbol::sym;
f9f354fc 28use rustc_span::InnerSpan;
cdc7bbd5 29use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
1a4d82fc 30
dfeec247 31use libc::{c_char, c_int, c_uint, c_void, size_t};
60c5eb7d 32use std::ffi::CString;
2c00a5a8
XL
33use std::fs;
34use std::io::{self, Write};
48663c56 35use std::path::{Path, PathBuf};
dfeec247 36use std::slice;
1a4d82fc 37use std::str;
3b2f2976 38use std::sync::Arc;
1a4d82fc 39
60c5eb7d 40pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
7453a54e 41 match llvm::last_error() {
041b39d2 42 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
c295e0f8 43 None => handler.fatal(msg),
1a4d82fc
JJ
44 }
45}
46
a2a8927a 47pub fn write_output_file<'ll>(
dfeec247
XL
48 handler: &rustc_errors::Handler,
49 target: &'ll llvm::TargetMachine,
50 pm: &llvm::PassManager<'ll>,
51 m: &'ll llvm::Module,
52 output: &Path,
fc512014 53 dwo_output: Option<&Path>,
dfeec247 54 file_type: llvm::FileType,
3c0e092e 55 self_profiler_ref: &SelfProfilerRef,
dfeec247 56) -> Result<(), FatalError> {
923072b8 57 debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
1a4d82fc 58 unsafe {
a1dfa0c6 59 let output_c = path_to_c_string(output);
923072b8
FG
60 let dwo_output_c;
61 let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
62 dwo_output_c = path_to_c_string(dwo_output);
63 dwo_output_c.as_ptr()
fc512014 64 } else {
923072b8 65 std::ptr::null()
fc512014 66 };
923072b8
FG
67 let result = llvm::LLVMRustWriteOutputFile(
68 target,
69 pm,
70 m,
71 output_c.as_ptr(),
72 dwo_output_ptr,
73 file_type,
74 );
3c0e092e
XL
75
76 // Record artifact sizes for self-profiling
77 if result == llvm::LLVMRustResult::Success {
78 let artifact_kind = match file_type {
79 llvm::FileType::ObjectFile => "object_file",
80 llvm::FileType::AssemblyFile => "assembly_file",
81 };
82 record_artifact_size(self_profiler_ref, artifact_kind, output);
83 if let Some(dwo_file) = dwo_output {
84 record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
85 }
86 }
87
532ac7d7 88 result.into_result().map_err(|()| {
041b39d2 89 let msg = format!("could not write output to {}", output.display());
532ac7d7
XL
90 llvm_err(handler, &msg)
91 })
1a4d82fc 92 }
1a4d82fc
JJ
93}
94
f9f354fc 95pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
fc512014 96 let config = TargetMachineFactoryConfig { split_dwarf_file: None };
5e7ed085
FG
97 // Can't use query system here quite yet because this function is invoked before the query
98 // system/tcx is set up.
99 let features = llvm_util::global_llvm_features(sess, false);
100 target_machine_factory(sess, config::OptLevel::No, &features)(config)
dfeec247 101 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
ea8adc8c
XL
102}
103
fc512014 104pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
5869c6ff 105 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
a2a8927a
XL
106 tcx.output_filenames(()).split_dwarf_path(
107 tcx.sess.split_debuginfo(),
064997fb 108 tcx.sess.opts.unstable_opts.split_dwarf_kind,
a2a8927a
XL
109 Some(mod_name),
110 )
5869c6ff
XL
111 } else {
112 None
113 };
fc512014 114 let config = TargetMachineFactoryConfig { split_dwarf_file };
5e7ed085
FG
115 target_machine_factory(
116 &tcx.sess,
117 tcx.backend_optimization_level(()),
118 tcx.global_backend_features(()),
119 )(config)
120 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
532ac7d7 121}
9fa01778 122
dfeec247
XL
123pub fn to_llvm_opt_settings(
124 cfg: config::OptLevel,
125) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
9fa01778
XL
126 use self::config::OptLevel::*;
127 match cfg {
128 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
129 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
130 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
131 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
132 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
133 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
134 }
135}
136
74b04a01
XL
137fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
138 use config::OptLevel::*;
139 match cfg {
140 No => llvm::PassBuilderOptLevel::O0,
141 Less => llvm::PassBuilderOptLevel::O1,
142 Default => llvm::PassBuilderOptLevel::O2,
143 Aggressive => llvm::PassBuilderOptLevel::O3,
144 Size => llvm::PassBuilderOptLevel::Os,
145 SizeMin => llvm::PassBuilderOptLevel::Oz,
146 }
147}
148
f9f354fc
XL
149fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
150 match relocation_model {
151 RelocModel::Static => llvm::RelocModel::Static,
c295e0f8
XL
152 // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
153 RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
f9f354fc
XL
154 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
155 RelocModel::Ropi => llvm::RelocModel::ROPI,
156 RelocModel::Rwpi => llvm::RelocModel::RWPI,
157 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
158 }
159}
160
6a06907d 161pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
f9f354fc
XL
162 match code_model {
163 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
164 Some(CodeModel::Small) => llvm::CodeModel::Small,
165 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
166 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
167 Some(CodeModel::Large) => llvm::CodeModel::Large,
168 None => llvm::CodeModel::None,
169 }
170}
171
dfeec247
XL
172pub fn target_machine_factory(
173 sess: &Session,
174 optlvl: config::OptLevel,
5e7ed085 175 target_features: &[String],
fc512014 176) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
f9f354fc 177 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
1a4d82fc 178
9fa01778 179 let (opt_level, _) = to_llvm_opt_settings(optlvl);
1a4d82fc
JJ
180 let use_softfp = sess.opts.cg.soft_float;
181
29967ef6 182 let ffunction_sections =
064997fb 183 sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
1a4d82fc 184 let fdata_sections = ffunction_sections;
064997fb 185 let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
1a4d82fc 186
f9f354fc 187 let code_model = to_llvm_code_model(sess.code_model());
1a4d82fc 188
29967ef6 189 let mut singlethread = sess.target.singlethread;
abe05a73 190
b7449926
XL
191 // On the wasm target once the `atomics` feature is enabled that means that
192 // we're no longer single-threaded, or otherwise we don't want LLVM to
193 // lower atomic operations to single-threaded operations.
cdc7bbd5 194 if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
b7449926
XL
195 singlethread = false;
196 }
1a4d82fc 197
29967ef6 198 let triple = SmallCStr::new(&sess.target.llvm_target);
b7449926 199 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
5e7ed085 200 let features = CString::new(target_features.join(",")).unwrap();
29967ef6 201 let abi = SmallCStr::new(&sess.target.llvm_abiname);
fc512014 202 let trap_unreachable =
064997fb
FG
203 sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
204 let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
ea8adc8c 205
9c376795 206 let asm_comments = sess.opts.unstable_opts.asm_comments;
29967ef6 207 let relax_elf_relocations =
064997fb 208 sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
f9f354fc 209
29967ef6 210 let use_init_array =
064997fb 211 !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
f9f354fc 212
a2a8927a
XL
213 let path_mapping = sess.source_map().path_mapping().clone();
214
fc512014 215 Arc::new(move |config: TargetMachineFactoryConfig| {
a2a8927a
XL
216 let split_dwarf_file =
217 path_mapping.map_prefix(config.split_dwarf_file.unwrap_or_default()).0;
fc512014
XL
218 let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
219
ea8adc8c
XL
220 let tm = unsafe {
221 llvm::LLVMRustCreateTargetMachine(
dfeec247
XL
222 triple.as_ptr(),
223 cpu.as_ptr(),
224 features.as_ptr(),
225 abi.as_ptr(),
ea8adc8c
XL
226 code_model,
227 reloc_model,
228 opt_level,
229 use_softfp,
ea8adc8c
XL
230 ffunction_sections,
231 fdata_sections,
3c0e092e 232 funique_section_names,
abe05a73
XL
233 trap_unreachable,
234 singlethread,
b7449926 235 asm_comments,
0bf4aa26 236 emit_stack_size_section,
60c5eb7d 237 relax_elf_relocations,
f9f354fc 238 use_init_array,
fc512014 239 split_dwarf_file.as_ptr(),
ea8adc8c
XL
240 )
241 };
1a4d82fc 242
b7449926 243 tm.ok_or_else(|| {
dfeec247 244 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
b7449926 245 })
ea8adc8c 246 })
1a4d82fc
JJ
247}
248
a1dfa0c6
XL
249pub(crate) fn save_temp_bitcode(
250 cgcx: &CodegenContext<LlvmCodegenBackend>,
251 module: &ModuleCodegen<ModuleLlvm>,
dfeec247 252 name: &str,
a1dfa0c6
XL
253) {
254 if !cgcx.save_temps {
dfeec247 255 return;
ea8adc8c 256 }
a1dfa0c6
XL
257 unsafe {
258 let ext = format!("{}.bc", name);
259 let cgu = Some(&module.name[..]);
260 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
261 let cstr = path_to_c_string(&path);
262 let llmod = module.module_llvm.llmod();
263 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
ea8adc8c
XL
264 }
265}
266
b7449926 267pub struct DiagnosticHandlers<'a> {
a1dfa0c6 268 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
b7449926 269 llcx: &'a llvm::Context,
a2a8927a 270 old_handler: Option<&'a llvm::DiagnosticHandler>,
ea8adc8c
XL
271}
272
273impl<'a> DiagnosticHandlers<'a> {
dfeec247
XL
274 pub fn new(
275 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
276 handler: &'a Handler,
277 llcx: &'a llvm::Context,
278 ) -> Self {
a2a8927a
XL
279 let remark_passes_all: bool;
280 let remark_passes: Vec<CString>;
281 match &cgcx.remark {
282 Passes::All => {
283 remark_passes_all = true;
284 remark_passes = Vec::new();
285 }
286 Passes::Some(passes) => {
287 remark_passes_all = false;
288 remark_passes =
289 passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
290 }
291 };
292 let remark_passes: Vec<*const c_char> =
293 remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
8faf50e0 294 let data = Box::into_raw(Box::new((cgcx, handler)));
ea8adc8c 295 unsafe {
a2a8927a
XL
296 let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
297 llvm::LLVMRustContextConfigureDiagnosticHandler(
298 llcx,
299 diagnostic_handler,
300 data.cast(),
301 remark_passes_all,
302 remark_passes.as_ptr(),
303 remark_passes.len(),
304 );
a2a8927a 305 DiagnosticHandlers { data, llcx, old_handler }
ea8adc8c
XL
306 }
307 }
1a4d82fc
JJ
308}
309
ea8adc8c
XL
310impl<'a> Drop for DiagnosticHandlers<'a> {
311 fn drop(&mut self) {
312 unsafe {
a2a8927a 313 llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
8faf50e0 314 drop(Box::from_raw(self.data));
ea8adc8c
XL
315 }
316 }
1a4d82fc
JJ
317}
318
f9f354fc 319fn report_inline_asm(
dfeec247 320 cgcx: &CodegenContext<LlvmCodegenBackend>,
f9f354fc 321 msg: String,
f035d41b 322 level: llvm::DiagnosticLevel,
f9f354fc
XL
323 mut cookie: c_uint,
324 source: Option<(String, Vec<InnerSpan>)>,
dfeec247 325) {
f9f354fc
XL
326 // In LTO build we may get srcloc values from other crates which are invalid
327 // since they use a different source map. To be safe we just suppress these
328 // in LTO builds.
329 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
330 cookie = 0;
331 }
f035d41b 332 let level = match level {
3c0e092e 333 llvm::DiagnosticLevel::Error => Level::Error { lint: false },
923072b8 334 llvm::DiagnosticLevel::Warning => Level::Warning(None),
f035d41b
XL
335 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
336 };
337 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
1a4d82fc
JJ
338}
339
b7449926 340unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
ea8adc8c 341 if user.is_null() {
dfeec247 342 return;
ea8adc8c 343 }
a1dfa0c6 344 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
1a4d82fc
JJ
345
346 match llvm::diagnostic::Diagnostic::unpack(info) {
85aaf69f 347 llvm::diagnostic::InlineAsm(inline) => {
94222f64 348 report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
85aaf69f
SL
349 }
350
1a4d82fc 351 llvm::diagnostic::Optimization(opt) => {
1a4d82fc 352 let enabled = match cgcx.remark {
b7449926
XL
353 Passes::All => true,
354 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
1a4d82fc
JJ
355 };
356
357 if enabled {
dfeec247 358 diag_handler.note_without_error(&format!(
a2a8927a
XL
359 "{}:{}:{}: {}: {}",
360 opt.filename, opt.line, opt.column, opt.pass_name, opt.message,
dfeec247 361 ));
1a4d82fc
JJ
362 }
363 }
dfeec247 364 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
0531ce1d
XL
365 let msg = llvm::build_string(|s| {
366 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
dfeec247
XL
367 })
368 .expect("non-UTF8 diagnostic");
0531ce1d
XL
369 diag_handler.warn(&msg);
370 }
1b1a35ee
XL
371 llvm::diagnostic::Unsupported(diagnostic_ref) => {
372 let msg = llvm::build_string(|s| {
373 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
374 })
375 .expect("non-UTF8 diagnostic");
376 diag_handler.err(&msg);
377 }
dfeec247 378 llvm::diagnostic::UnknownDiagnostic(..) => {}
1a4d82fc
JJ
379 }
380}
381
74b04a01
XL
382fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
383 match config.pgo_gen {
384 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
385 let path = if let Some(dir_path) = opt_dir_path {
386 dir_path.join("default_%m.profraw")
387 } else {
388 PathBuf::from("default_%m.profraw")
389 };
390
391 Some(CString::new(format!("{}", path.display())).unwrap())
392 }
393 SwitchWithOptPath::Disabled => None,
394 }
395}
396
397fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
398 config
399 .pgo_use
400 .as_ref()
401 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
402}
403
c295e0f8
XL
404fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
405 config
406 .pgo_sample_use
407 .as_ref()
408 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
409}
410
f2b60f7d
FG
411fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
412 if config.instrument_coverage {
413 Some(CString::new("default_%m_%p.profraw").unwrap())
414 } else {
415 None
416 }
417}
418
2b03887a 419pub(crate) unsafe fn llvm_optimize(
74b04a01 420 cgcx: &CodegenContext<LlvmCodegenBackend>,
17df50a5 421 diag_handler: &Handler,
74b04a01
XL
422 module: &ModuleCodegen<ModuleLlvm>,
423 config: &ModuleConfig,
424 opt_level: config::OptLevel,
425 opt_stage: llvm::OptStage,
17df50a5 426) -> Result<(), FatalError> {
74b04a01
XL
427 let unroll_loops =
428 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
429 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
430 let pgo_gen_path = get_pgo_gen_path(config);
431 let pgo_use_path = get_pgo_use_path(config);
c295e0f8 432 let pgo_sample_use_path = get_pgo_sample_use_path(config);
74b04a01 433 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
f2b60f7d 434 let instr_profile_output_path = get_instr_profile_output_path(config);
74b04a01
XL
435 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
436 let sanitizer_options = if !is_lto {
f035d41b
XL
437 Some(llvm::SanitizerOptions {
438 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
439 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
440 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
441 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
74b04a01 442 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
f035d41b 443 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
6a06907d
XL
444 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
445 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
74b04a01
XL
446 })
447 } else {
448 None
449 };
450
c295e0f8
XL
451 let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
452 Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
74b04a01 453 } else {
c295e0f8 454 None
74b04a01
XL
455 };
456
c295e0f8
XL
457 let llvm_selfprofiler =
458 llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
459
923072b8 460 let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
17df50a5 461
a2a8927a
XL
462 let llvm_plugins = config.llvm_plugins.join(",");
463
74b04a01
XL
464 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
465 // We would have to add upstream support for this first, before we can support
466 // config.inline_threshold and our more aggressive default thresholds.
2b03887a 467 let result = llvm::LLVMRustOptimize(
74b04a01
XL
468 module.module_llvm.llmod(),
469 &*module.module_llvm.tm,
470 to_pass_builder_opt_level(opt_level),
471 opt_stage,
472 config.no_prepopulate_passes,
473 config.verify_llvm_ir,
474 using_thin_buffers,
475 config.merge_functions,
476 unroll_loops,
477 config.vectorize_slp,
478 config.vectorize_loop,
479 config.no_builtins,
f9f354fc 480 config.emit_lifetime_markers,
74b04a01
XL
481 sanitizer_options.as_ref(),
482 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
483 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
17df50a5 484 config.instrument_coverage,
f2b60f7d 485 instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
17df50a5 486 config.instrument_gcov,
c295e0f8
XL
487 pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
488 config.debug_info_for_profiling,
74b04a01
XL
489 llvm_selfprofiler,
490 selfprofile_before_pass_callback,
491 selfprofile_after_pass_callback,
17df50a5
XL
492 extra_passes.as_ptr().cast(),
493 extra_passes.len(),
a2a8927a
XL
494 llvm_plugins.as_ptr().cast(),
495 llvm_plugins.len(),
74b04a01 496 );
17df50a5 497 result.into_result().map_err(|()| llvm_err(diag_handler, "failed to run LLVM passes"))
74b04a01
XL
498}
499
1a4d82fc 500// Unsafe due to LLVM calls.
dfeec247
XL
501pub(crate) unsafe fn optimize(
502 cgcx: &CodegenContext<LlvmCodegenBackend>,
503 diag_handler: &Handler,
504 module: &ModuleCodegen<ModuleLlvm>,
505 config: &ModuleConfig,
17df50a5 506) -> Result<(), FatalError> {
a2a8927a 507 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
e74abb32 508
b7449926
XL
509 let llmod = module.module_llvm.llmod();
510 let llcx = &*module.module_llvm.llcx;
ea8adc8c 511 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
1a4d82fc 512
94b46f34 513 let module_name = module.name.clone();
3b2f2976 514 let module_name = Some(&module_name[..]);
5bcae85e 515
1a4d82fc 516 if config.emit_no_opt_bc {
ea8adc8c 517 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
a1dfa0c6 518 let out = path_to_c_string(&out);
1a4d82fc
JJ
519 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
520 }
521
60c5eb7d 522 if let Some(opt_level) = config.opt_level {
2b03887a
FG
523 let opt_stage = match cgcx.lto {
524 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
525 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
526 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
527 _ => llvm::OptStage::PreLinkNoLTO,
528 };
529 return llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage);
ea8adc8c 530 }
17df50a5 531 Ok(())
ea8adc8c 532}
1a4d82fc 533
1b1a35ee
XL
534pub(crate) fn link(
535 cgcx: &CodegenContext<LlvmCodegenBackend>,
536 diag_handler: &Handler,
537 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
538) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
539 use super::lto::{Linker, ModuleBuffer};
2b03887a 540 // Sort the modules by name to ensure deterministic behavior.
1b1a35ee
XL
541 modules.sort_by(|a, b| a.name.cmp(&b.name));
542 let (first, elements) =
543 modules.split_first().expect("Bug! modules must contain at least one module.");
544
545 let mut linker = Linker::new(first.module_llvm.llmod());
546 for module in elements {
04454e1e 547 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
1b1a35ee 548 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
c295e0f8 549 linker.add(buffer.data()).map_err(|()| {
1b1a35ee 550 let msg = format!("failed to serialize module {:?}", module.name);
c295e0f8 551 llvm_err(diag_handler, &msg)
1b1a35ee
XL
552 })?;
553 }
554 drop(linker);
555 Ok(modules.remove(0))
556}
557
dfeec247
XL
558pub(crate) unsafe fn codegen(
559 cgcx: &CodegenContext<LlvmCodegenBackend>,
560 diag_handler: &Handler,
561 module: ModuleCodegen<ModuleLlvm>,
562 config: &ModuleConfig,
563) -> Result<CompiledModule, FatalError> {
a2a8927a 564 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
1a4d82fc 565 {
b7449926
XL
566 let llmod = module.module_llvm.llmod();
567 let llcx = &*module.module_llvm.llcx;
568 let tm = &*module.module_llvm.tm;
569 let module_name = module.name.clone();
570 let module_name = Some(&module_name[..]);
571 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
1a4d82fc 572
b7449926
XL
573 if cgcx.msvc_imps_needed {
574 create_msvc_imps(cgcx, llcx, llmod);
575 }
576
577 // A codegen-specific pass manager is used to generate object
578 // files for an LLVM module.
579 //
580 // Apparently each of these pass managers is a one-shot kind of
581 // thing, so we create a new one for each type of output. The
582 // pass manager passed to the closure should be ensured to not
583 // escape the closure itself, and the manager should only be
584 // used once.
dfeec247
XL
585 unsafe fn with_codegen<'ll, F, R>(
586 tm: &'ll llvm::TargetMachine,
587 llmod: &'ll llvm::Module,
588 no_builtins: bool,
589 f: F,
590 ) -> R
591 where
592 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
b7449926
XL
593 {
594 let cpm = llvm::LLVMCreatePassManager();
60c5eb7d 595 llvm::LLVMAddAnalysisPasses(tm, cpm);
b7449926
XL
596 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
597 f(cpm)
598 }
599
ba9703b0
XL
600 // Two things to note:
601 // - If object files are just LLVM bitcode we write bitcode, copy it to
602 // the .o file, and delete the bitcode if it wasn't otherwise
603 // requested.
604 // - If we don't have the integrated assembler then we need to emit
605 // asm from LLVM and use `gcc` to create the object file.
b7449926
XL
606
607 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
608 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
609
ba9703b0 610 if config.bitcode_needed() {
74b04a01
XL
611 let _timer = cgcx
612 .prof
a2a8927a 613 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
064997fb 614 let thin = ThinBuffer::new(llmod, config.emit_thin_lto);
a1dfa0c6 615 let data = thin.data();
abe05a73 616
3c0e092e
XL
617 if let Some(bitcode_filename) = bc_out.file_name() {
618 cgcx.prof.artifact_size(
619 "llvm_bitcode",
620 bitcode_filename.to_string_lossy(),
621 data.len() as u64,
622 );
623 }
624
ba9703b0 625 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
a2a8927a
XL
626 let _timer = cgcx
627 .prof
628 .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
b7449926 629 if let Err(e) = fs::write(&bc_out, data) {
532ac7d7
XL
630 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
631 diag_handler.err(&msg);
b7449926 632 }
abe05a73 633 }
abe05a73 634
ba9703b0 635 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
a2a8927a
XL
636 let _timer = cgcx
637 .prof
638 .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
f9f354fc 639 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
abe05a73 640 }
b7449926
XL
641 }
642
ba9703b0 643 if config.emit_ir {
a2a8927a
XL
644 let _timer =
645 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
ba9703b0
XL
646 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
647 let out_c = path_to_c_string(&out);
648
649 extern "C" fn demangle_callback(
650 input_ptr: *const c_char,
651 input_len: size_t,
652 output_ptr: *mut c_char,
653 output_len: size_t,
654 ) -> size_t {
655 let input =
656 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
657
5e7ed085 658 let Ok(input) = str::from_utf8(input) else { return 0 };
ba9703b0
XL
659
660 let output = unsafe {
661 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
662 };
663 let mut cursor = io::Cursor::new(output);
664
5e7ed085 665 let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
ba9703b0
XL
666
667 if write!(cursor, "{:#}", demangled).is_err() {
668 // Possible only if provided buffer is not big enough
669 return 0;
041b39d2
XL
670 }
671
ba9703b0 672 cursor.position() as size_t
041b39d2
XL
673 }
674
ba9703b0 675 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
3c0e092e
XL
676
677 if result == llvm::LLVMRustResult::Success {
678 record_artifact_size(&cgcx.prof, "llvm_ir", &out);
679 }
680
ba9703b0
XL
681 result.into_result().map_err(|()| {
682 let msg = format!("failed to write LLVM IR to {}", out.display());
683 llvm_err(diag_handler, &msg)
684 })?;
685 }
9cc50fc6 686
ba9703b0 687 if config.emit_asm {
a2a8927a
XL
688 let _timer =
689 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
ba9703b0
XL
690 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
691
692 // We can't use the same module for asm and object code output,
693 // because that triggers various errors like invalid IR or broken
694 // binaries. So we must clone the module to produce the asm output
695 // if we are also producing object code.
696 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
697 llvm::LLVMCloneModule(llmod)
698 } else {
699 llmod
700 };
701 with_codegen(tm, llmod, config.no_builtins, |cpm| {
fc512014
XL
702 write_output_file(
703 diag_handler,
704 tm,
705 cpm,
706 llmod,
707 &path,
708 None,
709 llvm::FileType::AssemblyFile,
3c0e092e 710 &cgcx.prof,
fc512014 711 )
ba9703b0
XL
712 })?;
713 }
1a4d82fc 714
ba9703b0
XL
715 match config.emit_obj {
716 EmitObj::ObjectCode(_) => {
74b04a01
XL
717 let _timer = cgcx
718 .prof
a2a8927a 719 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
fc512014
XL
720
721 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
a2a8927a
XL
722 let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
723 // Don't change how DWARF is emitted when disabled.
724 (SplitDebuginfo::Off, _) => None,
725 // Don't provide a DWARF object path if split debuginfo is enabled but this is
726 // a platform that doesn't support Split DWARF.
727 _ if !cgcx.target_can_use_split_dwarf => None,
728 // Don't provide a DWARF object path in single mode, sections will be written
729 // into the object as normal but ignored by linker.
730 (_, SplitDwarfKind::Single) => None,
731 // Emit (a subset of the) DWARF into a separate dwarf object file in split
732 // mode.
733 (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
fc512014
XL
734 };
735
b7449926 736 with_codegen(tm, llmod, config.no_builtins, |cpm| {
dfeec247
XL
737 write_output_file(
738 diag_handler,
739 tm,
740 cpm,
741 llmod,
742 &obj_out,
fc512014 743 dwo_out,
dfeec247 744 llvm::FileType::ObjectFile,
3c0e092e 745 &cgcx.prof,
dfeec247 746 )
b7449926 747 })?;
ba9703b0 748 }
b7449926 749
ba9703b0
XL
750 EmitObj::Bitcode => {
751 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
752 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
753 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
b7449926 754 }
1a4d82fc 755
ba9703b0
XL
756 if !config.emit_bc {
757 debug!("removing_bitcode {:?}", bc_out);
6a06907d 758 ensure_removed(diag_handler, &bc_out);
ba9703b0 759 }
b7449926 760 }
7453a54e 761
ba9703b0 762 EmitObj::None => {}
7453a54e 763 }
7453a54e 764
b7449926
XL
765 drop(handlers);
766 }
ba9703b0 767
487cf647
FG
768 // `.dwo` files are only emitted if:
769 //
770 // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
771 // produce dwarf objects, even if otherwise enabled)
772 // - Target supports Split DWARF
773 // - Split debuginfo is enabled
774 // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
775 // sections in the `.o` files).
776 let dwarf_object_emitted = matches!(config.emit_obj, EmitObj::ObjectCode(_))
777 && cgcx.target_can_use_split_dwarf
778 && cgcx.split_debuginfo != SplitDebuginfo::Off
779 && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
dfeec247 780 Ok(module.into_compiled_module(
ba9703b0 781 config.emit_obj != EmitObj::None,
487cf647 782 dwarf_object_emitted,
dfeec247 783 config.emit_bc,
dfeec247
XL
784 &cgcx.output_filenames,
785 ))
1a4d82fc
JJ
786}
787
a2a8927a
XL
788fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
789 let mut asm = format!(".section {},\"{}\"\n", section_name, section_flags).into_bytes();
790 asm.extend_from_slice(b".ascii \"");
791 asm.reserve(data.len());
792 for &byte in data {
793 if byte == b'\\' || byte == b'"' {
794 asm.push(b'\\');
795 asm.push(byte);
796 } else if byte < 0x20 || byte >= 0x80 {
797 // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
798 // width, while hex escapes will consume following characters.
799 asm.push(b'\\');
800 asm.push(b'0' + ((byte >> 6) & 0x7));
801 asm.push(b'0' + ((byte >> 3) & 0x7));
802 asm.push(b'0' + ((byte >> 0) & 0x7));
803 } else {
804 asm.push(byte);
805 }
806 }
807 asm.extend_from_slice(b"\"\n");
808 asm
809}
810
0531ce1d 811/// Embed the bitcode of an LLVM module in the LLVM module itself.
abe05a73 812///
0531ce1d
XL
813/// This is done primarily for iOS where it appears to be standard to compile C
814/// code at least with `-fembed-bitcode` which creates two sections in the
815/// executable:
816///
817/// * __LLVM,__bitcode
818/// * __LLVM,__cmdline
819///
820/// It appears *both* of these sections are necessary to get the linker to
f9f354fc
XL
821/// recognize what's going on. A suitable cmdline value is taken from the
822/// target spec.
0531ce1d
XL
823///
824/// Furthermore debug/O1 builds don't actually embed bitcode but rather just
825/// embed an empty section.
826///
827/// Basically all of this is us attempting to follow in the footsteps of clang
828/// on iOS. See #35968 for lots more info.
dfeec247
XL
829unsafe fn embed_bitcode(
830 cgcx: &CodegenContext<LlvmCodegenBackend>,
831 llcx: &llvm::Context,
832 llmod: &llvm::Module,
f9f354fc
XL
833 cmdline: &str,
834 bitcode: &[u8],
dfeec247 835) {
f9f354fc
XL
836 // We're adding custom sections to the output object file, but we definitely
837 // do not want these custom sections to make their way into the final linked
838 // executable. The purpose of these custom sections is for tooling
839 // surrounding object files to work with the LLVM IR, if necessary. For
840 // example rustc's own LTO will look for LLVM IR inside of the object file
841 // in these sections by default.
842 //
843 // To handle this is a bit different depending on the object file format
844 // used by the backend, broken down into a few different categories:
845 //
846 // * Mach-O - this is for macOS. Inspecting the source code for the native
847 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
848 // automatically skipped by the linker. In that case there's nothing extra
849 // that we need to do here.
850 //
851 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
852 // `.llvmcmd` sections, so there's nothing extra we need to do.
853 //
854 // * COFF - if we don't do anything the linker will by default copy all
855 // these sections to the output artifact, not what we want! To subvert
856 // this we want to flag the sections we inserted here as
a2a8927a 857 // `IMAGE_SCN_LNK_REMOVE`.
f9f354fc
XL
858 //
859 // * ELF - this is very similar to COFF above. One difference is that these
860 // sections are removed from the output linked artifact when
861 // `--gc-sections` is passed, which we pass by default. If that flag isn't
862 // passed though then these sections will show up in the final output.
863 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
a2a8927a
XL
864 //
865 // Unfortunately, LLVM provides no way to set custom section flags. For ELF
866 // and COFF we emit the sections using module level inline assembly for that
867 // reason (see issue #90326 for historical background).
868 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
869 || cgcx.opts.target_triple.triple().contains("-darwin")
923072b8
FG
870 || cgcx.opts.target_triple.triple().contains("-tvos")
871 || cgcx.opts.target_triple.triple().contains("-watchos");
f9f354fc
XL
872 if is_apple
873 || cgcx.opts.target_triple.triple().starts_with("wasm")
874 || cgcx.opts.target_triple.triple().starts_with("asmjs")
875 {
a2a8927a
XL
876 // We don't need custom section flags, create LLVM globals.
877 let llconst = common::bytes_in_context(llcx, bitcode);
878 let llglobal = llvm::LLVMAddGlobal(
879 llmod,
880 common::val_ty(llconst),
881 "rustc.embedded.module\0".as_ptr().cast(),
882 );
883 llvm::LLVMSetInitializer(llglobal, llconst);
884
885 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
886 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
887 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
888 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
889
890 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
891 let llglobal = llvm::LLVMAddGlobal(
892 llmod,
893 common::val_ty(llconst),
894 "rustc.embedded.cmdline\0".as_ptr().cast(),
895 );
896 llvm::LLVMSetInitializer(llglobal, llconst);
897 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
898 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
899 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
f9f354fc 900 } else {
a2a8927a
XL
901 // We need custom section flags, so emit module-level inline assembly.
902 let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
903 let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
904 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
905 let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
f9f354fc
XL
906 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
907 }
abe05a73
XL
908}
909
abe05a73
XL
910// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
911// This is required to satisfy `dllimport` references to static data in .rlibs
9c376795 912// when using MSVC linker. We do this only for data, as linker can fix up
abe05a73
XL
913// code references on its own.
914// See #26591, #27438
a1dfa0c6
XL
915fn create_msvc_imps(
916 cgcx: &CodegenContext<LlvmCodegenBackend>,
917 llcx: &llvm::Context,
dfeec247 918 llmod: &llvm::Module,
a1dfa0c6 919) {
abe05a73 920 if !cgcx.msvc_imps_needed {
dfeec247 921 return;
abe05a73
XL
922 }
923 // The x86 ABI seems to require that leading underscores are added to symbol
48663c56 924 // names, so we need an extra underscore on x86. There's also a leading
0731742a 925 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
abe05a73 926 // underscores added in front).
dfeec247 927 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
48663c56 928
abe05a73
XL
929 unsafe {
930 let i8p_ty = Type::i8p_llcx(llcx);
931 let globals = base::iter_globals(llmod)
932 .filter(|&val| {
dfeec247
XL
933 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
934 && llvm::LLVMIsDeclaration(val) == 0
abe05a73 935 })
48663c56
XL
936 .filter_map(|val| {
937 // Exclude some symbols that we know are not Rust symbols.
60c5eb7d 938 let name = llvm::get_value_name(val);
dfeec247 939 if ignored(name) { None } else { Some((val, name)) }
48663c56
XL
940 })
941 .map(move |(val, name)| {
abe05a73 942 let mut imp_name = prefix.as_bytes().to_vec();
60c5eb7d 943 imp_name.extend(name);
abe05a73
XL
944 let imp_name = CString::new(imp_name).unwrap();
945 (imp_name, val)
946 })
947 .collect::<Vec<_>>();
48663c56 948
abe05a73 949 for (imp_name, val) in globals {
dfeec247 950 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
abe05a73
XL
951 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
952 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
953 }
954 }
48663c56
XL
955
956 // Use this function to exclude certain symbols from `__imp` generation.
957 fn ignored(symbol_name: &[u8]) -> bool {
958 // These are symbols generated by LLVM's profiling instrumentation
959 symbol_name.starts_with(b"__llvm_profile_")
960 }
abe05a73 961}
3c0e092e
XL
962
963fn record_artifact_size(
964 self_profiler_ref: &SelfProfilerRef,
965 artifact_kind: &'static str,
966 path: &Path,
967) {
968 // Don't stat the file if we are not going to record its size.
969 if !self_profiler_ref.enabled() {
970 return;
971 }
972
973 if let Some(artifact_name) = path.file_name() {
974 let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
975 self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
976 }
977}