2 use crate::back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
3 use crate::back::lto::ThinBuffer;
6 use crate::time_graph::Timeline;
7 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
10 use crate::type_::Type;
11 use crate::context::{is_pie_binary, get_reloc_model};
13 use crate::LlvmCodegenBackend;
14 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler};
15 use rustc_codegen_ssa::traits::*;
16 use rustc::hir::def_id::LOCAL_CRATE;
17 use rustc::session::config::{self, OutputType, Passes, Lto};
18 use rustc::session::Session;
19 use rustc::ty::TyCtxt;
20 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule};
21 use rustc::util::common::time_ext;
22 use rustc_fs_util::{path_to_c_string, link_or_copy};
23 use rustc_data_structures::small_c_str::SmallCStr;
24 use errors::{Handler, FatalError};
26 use std::ffi::{CString, CStr};
28 use std::io::{self, Write};
33 use libc::{c_uint, c_void, c_char, size_t};
35 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
36 ("pic", llvm::RelocMode::PIC),
37 ("static", llvm::RelocMode::Static),
38 ("default", llvm::RelocMode::Default),
39 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
40 ("ropi", llvm::RelocMode::ROPI),
41 ("rwpi", llvm::RelocMode::RWPI),
42 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
45 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
46 ("small", llvm::CodeModel::Small),
47 ("kernel", llvm::CodeModel::Kernel),
48 ("medium", llvm::CodeModel::Medium),
49 ("large", llvm::CodeModel::Large),
52 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
53 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
54 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
55 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
56 ("local-exec", llvm::ThreadLocalMode::LocalExec),
59 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
60 match llvm::last_error() {
61 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
62 None => handler.fatal(&msg),
66 pub fn write_output_file(
67 handler: &errors::Handler,
68 target: &'ll llvm::TargetMachine,
69 pm: &llvm::PassManager<'ll>,
72 file_type: llvm::FileType) -> Result<(), FatalError> {
74 let output_c = path_to_c_string(output);
75 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
76 if result.into_result().is_err() {
77 let msg = format!("could not write output to {}", output.display());
78 Err(llvm_err(handler, &msg))
85 pub fn create_target_machine(
86 tcx: TyCtxt<'_, '_, '_>,
88 ) -> &'static mut llvm::TargetMachine {
89 target_machine_factory(tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
90 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise() )
93 pub fn create_informational_target_machine(
96 ) -> &'static mut llvm::TargetMachine {
97 target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| {
98 llvm_err(sess.diagnostic(), &err).raise()
103 pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
105 use self::config::OptLevel::*;
107 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
108 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
109 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
110 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
111 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
112 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
116 // If find_features is true this won't access `sess.crate_types` by assuming
117 // that `is_pie_binary` is false. When we discover LLVM target features
118 // `sess.crate_types` is uninitialized so we cannot access it.
119 pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool)
120 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
122 let reloc_model = get_reloc_model(sess);
124 let (opt_level, _) = to_llvm_opt_settings(optlvl);
125 let use_softfp = sess.opts.cg.soft_float;
127 let ffunction_sections = sess.target.target.options.function_sections;
128 let fdata_sections = ffunction_sections;
130 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
131 sess.target.target.options.code_model.as_ref(),
134 let code_model = match code_model_arg {
136 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
139 sess.err(&format!("{:?} is not a valid code model",
141 sess.abort_if_errors();
146 None => llvm::CodeModel::None,
149 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
150 let mut singlethread = sess.target.target.options.singlethread;
152 // On the wasm target once the `atomics` feature is enabled that means that
153 // we're no longer single-threaded, or otherwise we don't want LLVM to
154 // lower atomic operations to single-threaded operations.
156 sess.target.target.llvm_target.contains("wasm32") &&
157 features.iter().any(|s| *s == "+atomics")
159 singlethread = false;
162 let triple = SmallCStr::new(&sess.target.target.llvm_target);
163 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
164 let features = features.join(",");
165 let features = CString::new(features).unwrap();
166 let is_pie_binary = !find_features && is_pie_binary(sess);
167 let trap_unreachable = sess.target.target.options.trap_unreachable;
168 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
170 let asm_comments = sess.asm_comments();
174 llvm::LLVMRustCreateTargetMachine(
175 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
186 emit_stack_size_section,
191 format!("Could not create LLVM TargetMachine for triple: {}",
192 triple.to_str().unwrap())
197 pub(crate) fn save_temp_bitcode(
198 cgcx: &CodegenContext<LlvmCodegenBackend>,
199 module: &ModuleCodegen<ModuleLlvm>,
202 if !cgcx.save_temps {
206 let ext = format!("{}.bc", name);
207 let cgu = Some(&module.name[..]);
208 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
209 let cstr = path_to_c_string(&path);
210 let llmod = module.module_llvm.llmod();
211 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
215 pub struct DiagnosticHandlers<'a> {
216 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
217 llcx: &'a llvm::Context,
220 impl<'a> DiagnosticHandlers<'a> {
221 pub fn new(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
222 handler: &'a Handler,
223 llcx: &'a llvm::Context) -> Self {
224 let data = Box::into_raw(Box::new((cgcx, handler)));
226 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
227 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
229 DiagnosticHandlers { data, llcx }
233 impl<'a> Drop for DiagnosticHandlers<'a> {
235 use std::ptr::null_mut;
237 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
238 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
239 drop(Box::from_raw(self.data));
244 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
247 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
250 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
256 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
258 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
259 .expect("non-UTF8 SMDiagnostic");
261 report_inline_asm(cgcx, &msg, cookie);
264 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
268 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
270 match llvm::diagnostic::Diagnostic::unpack(info) {
271 llvm::diagnostic::InlineAsm(inline) => {
272 report_inline_asm(cgcx,
273 &llvm::twine_to_string(inline.message),
277 llvm::diagnostic::Optimization(opt) => {
278 let enabled = match cgcx.remark {
280 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
284 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
293 llvm::diagnostic::PGO(diagnostic_ref) |
294 llvm::diagnostic::Linker(diagnostic_ref) => {
295 let msg = llvm::build_string(|s| {
296 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
297 }).expect("non-UTF8 diagnostic");
298 diag_handler.warn(&msg);
300 llvm::diagnostic::UnknownDiagnostic(..) => {},
304 // Unsafe due to LLVM calls.
305 pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
306 diag_handler: &Handler,
307 module: &ModuleCodegen<ModuleLlvm>,
308 config: &ModuleConfig,
309 timeline: &mut Timeline)
310 -> Result<(), FatalError>
312 let llmod = module.module_llvm.llmod();
313 let llcx = &*module.module_llvm.llcx;
314 let tm = &*module.module_llvm.tm;
315 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
317 let module_name = module.name.clone();
318 let module_name = Some(&module_name[..]);
320 if config.emit_no_opt_bc {
321 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
322 let out = path_to_c_string(&out);
323 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
326 if config.opt_level.is_some() {
327 // Create the two optimizing pass managers. These mirror what clang
328 // does, and are by populated by LLVM's default PassManagerBuilder.
329 // Each manager has a different set of passes, but they also share
330 // some common passes.
331 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
332 let mpm = llvm::LLVMCreatePassManager();
335 // If we're verifying or linting, add them to the function pass
337 let addpass = |pass_name: &str| {
338 let pass_name = SmallCStr::new(pass_name);
339 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
341 None => return false,
343 let pass_manager = match llvm::LLVMRustPassKind(pass) {
344 llvm::PassKind::Function => &*fpm,
345 llvm::PassKind::Module => &*mpm,
346 llvm::PassKind::Other => {
347 diag_handler.err("Encountered LLVM pass kind we can't handle");
351 llvm::LLVMRustAddPass(pass_manager, pass);
355 if config.verify_llvm_ir { assert!(addpass("verify")); }
357 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
358 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
359 // we'll get errors in LLVM.
360 let using_thin_buffers = config.bitcode_needed();
361 let mut have_name_anon_globals_pass = false;
362 if !config.no_prepopulate_passes {
363 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
364 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
365 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
366 .unwrap_or(llvm::CodeGenOptLevel::None);
367 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
368 (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
369 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
370 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
371 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
374 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
375 if using_thin_buffers && !prepare_for_thin_lto {
376 assert!(addpass("name-anon-globals"));
377 have_name_anon_globals_pass = true;
381 for pass in &config.passes {
383 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
385 if pass == "name-anon-globals" {
386 have_name_anon_globals_pass = true;
390 for pass in &cgcx.plugin_passes {
392 diag_handler.err(&format!("a plugin asked for LLVM pass \
393 `{}` but LLVM does not \
394 recognize it", pass));
396 if pass == "name-anon-globals" {
397 have_name_anon_globals_pass = true;
401 if using_thin_buffers && !have_name_anon_globals_pass {
402 // As described above, this will probably cause an error in LLVM
403 if config.no_prepopulate_passes {
404 diag_handler.err("The current compilation is going to use thin LTO buffers \
405 without running LLVM's NameAnonGlobals pass. \
406 This will likely cause errors in LLVM. Consider adding \
407 -C passes=name-anon-globals to the compiler command line.");
409 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
410 This will likely cause errors in LLVM and should never happen.");
415 diag_handler.abort_if_errors();
417 // Finally, run the actual optimization passes
418 time_ext(config.time_passes,
420 &format!("llvm function passes [{}]", module_name.unwrap()),
422 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
424 timeline.record("fpm");
425 time_ext(config.time_passes,
427 &format!("llvm module passes [{}]", module_name.unwrap()),
429 llvm::LLVMRunPassManager(mpm, llmod)
432 // Deallocate managers that we're now done with
433 llvm::LLVMDisposePassManager(fpm);
434 llvm::LLVMDisposePassManager(mpm);
439 pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
440 diag_handler: &Handler,
441 module: ModuleCodegen<ModuleLlvm>,
442 config: &ModuleConfig,
443 timeline: &mut Timeline)
444 -> Result<CompiledModule, FatalError>
446 timeline.record("codegen");
448 let llmod = module.module_llvm.llmod();
449 let llcx = &*module.module_llvm.llcx;
450 let tm = &*module.module_llvm.tm;
451 let module_name = module.name.clone();
452 let module_name = Some(&module_name[..]);
453 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
455 if cgcx.msvc_imps_needed {
456 create_msvc_imps(cgcx, llcx, llmod);
459 // A codegen-specific pass manager is used to generate object
460 // files for an LLVM module.
462 // Apparently each of these pass managers is a one-shot kind of
463 // thing, so we create a new one for each type of output. The
464 // pass manager passed to the closure should be ensured to not
465 // escape the closure itself, and the manager should only be
467 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
468 llmod: &'ll llvm::Module,
471 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
473 let cpm = llvm::LLVMCreatePassManager();
474 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
475 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
479 // If we don't have the integrated assembler, then we need to emit asm
480 // from LLVM and use `gcc` to create the object file.
481 let asm_to_obj = config.emit_obj && config.no_integrated_as;
483 // Change what we write and cleanup based on whether obj files are
484 // just llvm bitcode. In that case write bitcode, and possibly
485 // delete the bitcode if it wasn't requested. Don't generate the
486 // machine code, instead copy the .o file from the .bc
487 let write_bc = config.emit_bc || config.obj_is_bitcode;
488 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
489 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
490 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
492 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
493 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
496 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
497 let thin = ThinBuffer::new(llmod);
498 let data = thin.data();
499 timeline.record("make-bc");
502 if let Err(e) = fs::write(&bc_out, data) {
503 diag_handler.err(&format!("failed to write bytecode: {}", e));
505 timeline.record("write-bc");
508 if config.embed_bitcode {
509 embed_bitcode(cgcx, llcx, llmod, Some(data));
510 timeline.record("embed-bc");
513 if config.emit_bc_compressed {
514 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
515 let data = bytecode::encode(&module.name, data);
516 if let Err(e) = fs::write(&dst, data) {
517 diag_handler.err(&format!("failed to write bytecode: {}", e));
519 timeline.record("compress-bc");
521 } else if config.embed_bitcode_marker {
522 embed_bitcode(cgcx, llcx, llmod, None);
525 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
526 || -> Result<(), FatalError> {
528 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
529 let out = path_to_c_string(&out);
531 extern "C" fn demangle_callback(input_ptr: *const c_char,
533 output_ptr: *mut c_char,
534 output_len: size_t) -> size_t {
536 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
539 let input = match str::from_utf8(input) {
544 let output = unsafe {
545 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
547 let mut cursor = io::Cursor::new(output);
549 let demangled = match rustc_demangle::try_demangle(input) {
554 if let Err(_) = write!(cursor, "{:#}", demangled) {
555 // Possible only if provided buffer is not big enough
559 cursor.position() as size_t
562 with_codegen(tm, llmod, config.no_builtins, |cpm| {
563 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
564 llvm::LLVMDisposePassManager(cpm);
566 timeline.record("ir");
569 if config.emit_asm || asm_to_obj {
570 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
572 // We can't use the same module for asm and binary output, because that triggers
573 // various errors like invalid IR or broken binaries, so we might have to clone the
574 // module to produce the asm output
575 let llmod = if config.emit_obj {
576 llvm::LLVMCloneModule(llmod)
580 with_codegen(tm, llmod, config.no_builtins, |cpm| {
581 write_output_file(diag_handler, tm, cpm, llmod, &path,
582 llvm::FileType::AssemblyFile)
584 timeline.record("asm");
588 with_codegen(tm, llmod, config.no_builtins, |cpm| {
589 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
590 llvm::FileType::ObjectFile)
592 timeline.record("obj");
593 } else if asm_to_obj {
594 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
595 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
596 timeline.record("asm_to_obj");
598 if !config.emit_asm && !cgcx.save_temps {
599 drop(fs::remove_file(&assembly));
607 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
608 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
609 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
614 debug!("removing_bitcode {:?}", bc_out);
615 if let Err(e) = fs::remove_file(&bc_out) {
616 diag_handler.err(&format!("failed to remove bitcode: {}", e));
622 Ok(module.into_compiled_module(config.emit_obj,
624 config.emit_bc_compressed,
625 &cgcx.output_filenames))
628 /// Embed the bitcode of an LLVM module in the LLVM module itself.
630 /// This is done primarily for iOS where it appears to be standard to compile C
631 /// code at least with `-fembed-bitcode` which creates two sections in the
634 /// * __LLVM,__bitcode
635 /// * __LLVM,__cmdline
637 /// It appears *both* of these sections are necessary to get the linker to
638 /// recognize what's going on. For us though we just always throw in an empty
641 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
642 /// embed an empty section.
644 /// Basically all of this is us attempting to follow in the footsteps of clang
645 /// on iOS. See #35968 for lots more info.
646 unsafe fn embed_bitcode(cgcx: &CodegenContext<LlvmCodegenBackend>,
647 llcx: &llvm::Context,
648 llmod: &llvm::Module,
649 bitcode: Option<&[u8]>) {
650 let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
651 let llglobal = llvm::LLVMAddGlobal(
653 common::val_ty(llconst),
654 "rustc.embedded.module\0".as_ptr() as *const _,
656 llvm::LLVMSetInitializer(llglobal, llconst);
658 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
659 cgcx.opts.target_triple.triple().contains("-darwin");
661 let section = if is_apple {
666 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
667 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
668 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
670 let llconst = common::bytes_in_context(llcx, &[]);
671 let llglobal = llvm::LLVMAddGlobal(
673 common::val_ty(llconst),
674 "rustc.embedded.cmdline\0".as_ptr() as *const _,
676 llvm::LLVMSetInitializer(llglobal, llconst);
677 let section = if is_apple {
682 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
683 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
686 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
687 config: &ModuleConfig,
688 opt_level: llvm::CodeGenOptLevel,
689 prepare_for_thin_lto: bool,
690 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
693 // Create the PassManagerBuilder for LLVM. We configure it with
694 // reasonable defaults and prepare it to actually populate the pass
696 let builder = llvm::LLVMPassManagerBuilderCreate();
697 let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1)
698 .unwrap_or(llvm::CodeGenOptSizeNone);
699 let inline_threshold = config.inline_threshold;
701 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
702 let s = if s.is_empty() { "default_%m.profraw" } else { s };
703 CString::new(s.as_bytes()).unwrap()
706 let pgo_use_path = if config.pgo_use.is_empty() {
709 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
712 llvm::LLVMRustConfigurePassManagerBuilder(
715 config.merge_functions,
716 config.vectorize_slp,
717 config.vectorize_loop,
718 prepare_for_thin_lto,
719 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
720 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
723 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
725 if opt_size != llvm::CodeGenOptSizeNone {
726 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
729 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
731 // Here we match what clang does (kinda). For O0 we only inline
732 // always-inline functions (but don't add lifetime intrinsics), at O1 we
733 // inline with lifetime intrinsics, and O2+ we add an inliner with a
734 // thresholds copied from clang.
735 match (opt_level, opt_size, inline_threshold) {
737 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
739 (llvm::CodeGenOptLevel::Aggressive, ..) => {
740 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
742 (_, llvm::CodeGenOptSizeDefault, _) => {
743 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
745 (_, llvm::CodeGenOptSizeAggressive, _) => {
746 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
748 (llvm::CodeGenOptLevel::None, ..) => {
749 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
751 (llvm::CodeGenOptLevel::Less, ..) => {
752 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
754 (llvm::CodeGenOptLevel::Default, ..) => {
755 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
757 (llvm::CodeGenOptLevel::Other, ..) => {
758 bug!("CodeGenOptLevel::Other selected")
763 llvm::LLVMPassManagerBuilderDispose(builder);
766 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
767 // This is required to satisfy `dllimport` references to static data in .rlibs
768 // when using MSVC linker. We do this only for data, as linker can fix up
769 // code references on its own.
770 // See #26591, #27438
772 cgcx: &CodegenContext<LlvmCodegenBackend>,
773 llcx: &llvm::Context,
776 if !cgcx.msvc_imps_needed {
779 // The x86 ABI seems to require that leading underscores are added to symbol
780 // names, so we need an extra underscore on 32-bit. There's also a leading
781 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
782 // underscores added in front).
783 let prefix = if cgcx.target_pointer_width == "32" {
789 let i8p_ty = Type::i8p_llcx(llcx);
790 let globals = base::iter_globals(llmod)
792 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
793 llvm::LLVMIsDeclaration(val) == 0
796 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
797 let mut imp_name = prefix.as_bytes().to_vec();
798 imp_name.extend(name.to_bytes());
799 let imp_name = CString::new(imp_name).unwrap();
802 .collect::<Vec<_>>();
803 for (imp_name, val) in globals {
804 let imp = llvm::LLVMAddGlobal(llmod,
806 imp_name.as_ptr() as *const _);
807 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
808 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);