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