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