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