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