2 use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
3 use back::lto::ThinBuffer;
4 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler};
5 use rustc_codegen_ssa::traits::*;
8 use rustc::hir::def_id::LOCAL_CRATE;
9 use rustc::session::config::{self, OutputType, Passes, Lto};
10 use rustc::session::Session;
11 use rustc::ty::TyCtxt;
12 use time_graph::Timeline;
13 use llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
16 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule};
17 use rustc::util::common::time_ext;
18 use rustc_fs_util::{path_to_c_string, link_or_copy};
19 use rustc_data_structures::small_c_str::SmallCStr;
20 use errors::{self, Handler, FatalError};
22 use context::{is_pie_binary, get_reloc_model};
24 use LlvmCodegenBackend;
27 use std::ffi::{CString, CStr};
29 use std::io::{self, Write};
34 use libc::{c_uint, c_void, c_char, size_t};
36 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
37 ("pic", llvm::RelocMode::PIC),
38 ("static", llvm::RelocMode::Static),
39 ("default", llvm::RelocMode::Default),
40 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
41 ("ropi", llvm::RelocMode::ROPI),
42 ("rwpi", llvm::RelocMode::RWPI),
43 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
46 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
47 ("small", llvm::CodeModel::Small),
48 ("kernel", llvm::CodeModel::Kernel),
49 ("medium", llvm::CodeModel::Medium),
50 ("large", llvm::CodeModel::Large),
53 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
54 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
55 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
56 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
57 ("local-exec", llvm::ThreadLocalMode::LocalExec),
60 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
61 match llvm::last_error() {
62 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
63 None => handler.fatal(&msg),
67 pub fn write_output_file(
68 handler: &errors::Handler,
69 target: &'ll llvm::TargetMachine,
70 pm: &llvm::PassManager<'ll>,
73 file_type: llvm::FileType) -> Result<(), FatalError> {
75 let output_c = path_to_c_string(output);
76 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
77 if result.into_result().is_err() {
78 let msg = format!("could not write output to {}", output.display());
79 Err(llvm_err(handler, &msg))
86 pub fn create_target_machine(
89 ) -> &'static mut llvm::TargetMachine {
90 target_machine_factory(tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
91 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise() )
94 pub fn create_informational_target_machine(
97 ) -> &'static mut llvm::TargetMachine {
98 target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| {
99 llvm_err(sess.diagnostic(), &err).raise()
104 pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
106 use self::config::OptLevel::*;
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),
117 // If find_features is true this won't access `sess.crate_types` by assuming
118 // that `is_pie_binary` is false. When we discover LLVM target features
119 // `sess.crate_types` is uninitialized so we cannot access it.
120 pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool)
121 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
123 let reloc_model = get_reloc_model(sess);
125 let (opt_level, _) = to_llvm_opt_settings(optlvl);
126 let use_softfp = sess.opts.cg.soft_float;
128 let ffunction_sections = sess.target.target.options.function_sections;
129 let fdata_sections = ffunction_sections;
131 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
132 sess.target.target.options.code_model.as_ref(),
135 let code_model = match code_model_arg {
137 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
140 sess.err(&format!("{:?} is not a valid code model",
142 sess.abort_if_errors();
147 None => llvm::CodeModel::None,
150 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
151 let mut singlethread = sess.target.target.options.singlethread;
153 // On the wasm target once the `atomics` feature is enabled that means that
154 // we're no longer single-threaded, or otherwise we don't want LLVM to
155 // lower atomic operations to single-threaded operations.
157 sess.target.target.llvm_target.contains("wasm32") &&
158 features.iter().any(|s| *s == "+atomics")
160 singlethread = false;
163 let triple = SmallCStr::new(&sess.target.target.llvm_target);
164 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
165 let features = features.join(",");
166 let features = CString::new(features).unwrap();
167 let is_pie_binary = !find_features && is_pie_binary(sess);
168 let trap_unreachable = sess.target.target.options.trap_unreachable;
169 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
171 let asm_comments = sess.asm_comments();
175 llvm::LLVMRustCreateTargetMachine(
176 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
187 emit_stack_size_section,
192 format!("Could not create LLVM TargetMachine for triple: {}",
193 triple.to_str().unwrap())
198 pub(crate) fn save_temp_bitcode(
199 cgcx: &CodegenContext<LlvmCodegenBackend>,
200 module: &ModuleCodegen<ModuleLlvm>,
203 if !cgcx.save_temps {
207 let ext = format!("{}.bc", name);
208 let cgu = Some(&module.name[..]);
209 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
210 let cstr = path_to_c_string(&path);
211 let llmod = module.module_llvm.llmod();
212 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
216 pub struct DiagnosticHandlers<'a> {
217 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
218 llcx: &'a llvm::Context,
221 impl<'a> DiagnosticHandlers<'a> {
222 pub fn new(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
223 handler: &'a Handler,
224 llcx: &'a llvm::Context) -> Self {
225 let data = Box::into_raw(Box::new((cgcx, handler)));
227 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
228 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
230 DiagnosticHandlers { data, llcx }
234 impl<'a> Drop for DiagnosticHandlers<'a> {
236 use std::ptr::null_mut;
238 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
239 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
240 drop(Box::from_raw(self.data));
245 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
248 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
251 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
257 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
259 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
260 .expect("non-UTF8 SMDiagnostic");
262 report_inline_asm(cgcx, &msg, cookie);
265 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
269 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
271 match llvm::diagnostic::Diagnostic::unpack(info) {
272 llvm::diagnostic::InlineAsm(inline) => {
273 report_inline_asm(cgcx,
274 &llvm::twine_to_string(inline.message),
278 llvm::diagnostic::Optimization(opt) => {
279 let enabled = match cgcx.remark {
281 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
285 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
294 llvm::diagnostic::PGO(diagnostic_ref) |
295 llvm::diagnostic::Linker(diagnostic_ref) => {
296 let msg = llvm::build_string(|s| {
297 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
298 }).expect("non-UTF8 diagnostic");
299 diag_handler.warn(&msg);
301 llvm::diagnostic::UnknownDiagnostic(..) => {},
305 // Unsafe due to LLVM calls.
306 pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
307 diag_handler: &Handler,
308 module: &ModuleCodegen<ModuleLlvm>,
309 config: &ModuleConfig,
310 timeline: &mut Timeline)
311 -> Result<(), FatalError>
313 let llmod = module.module_llvm.llmod();
314 let llcx = &*module.module_llvm.llcx;
315 let tm = &*module.module_llvm.tm;
316 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
318 let module_name = module.name.clone();
319 let module_name = Some(&module_name[..]);
321 if config.emit_no_opt_bc {
322 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
323 let out = path_to_c_string(&out);
324 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
327 if config.opt_level.is_some() {
328 // Create the two optimizing pass managers. These mirror what clang
329 // does, and are by populated by LLVM's default PassManagerBuilder.
330 // Each manager has a different set of passes, but they also share
331 // some common passes.
332 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
333 let mpm = llvm::LLVMCreatePassManager();
336 // If we're verifying or linting, add them to the function pass
338 let addpass = |pass_name: &str| {
339 let pass_name = SmallCStr::new(pass_name);
340 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
342 None => return false,
344 let pass_manager = match llvm::LLVMRustPassKind(pass) {
345 llvm::PassKind::Function => &*fpm,
346 llvm::PassKind::Module => &*mpm,
347 llvm::PassKind::Other => {
348 diag_handler.err("Encountered LLVM pass kind we can't handle");
352 llvm::LLVMRustAddPass(pass_manager, pass);
356 if config.verify_llvm_ir { assert!(addpass("verify")); }
358 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
359 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
360 // we'll get errors in LLVM.
361 let using_thin_buffers = config.bitcode_needed();
362 let mut have_name_anon_globals_pass = false;
363 if !config.no_prepopulate_passes {
364 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
365 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
366 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
367 .unwrap_or(llvm::CodeGenOptLevel::None);
368 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
369 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
370 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
371 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
372 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
375 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
376 if using_thin_buffers && !prepare_for_thin_lto {
377 assert!(addpass("name-anon-globals"));
378 have_name_anon_globals_pass = true;
382 for pass in &config.passes {
384 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
386 if pass == "name-anon-globals" {
387 have_name_anon_globals_pass = true;
391 for pass in &cgcx.plugin_passes {
393 diag_handler.err(&format!("a plugin asked for LLVM pass \
394 `{}` but LLVM does not \
395 recognize it", pass));
397 if pass == "name-anon-globals" {
398 have_name_anon_globals_pass = true;
402 if using_thin_buffers && !have_name_anon_globals_pass {
403 // As described above, this will probably cause an error in LLVM
404 if config.no_prepopulate_passes {
405 diag_handler.err("The current compilation is going to use thin LTO buffers \
406 without running LLVM's NameAnonGlobals pass. \
407 This will likely cause errors in LLVM. Consider adding \
408 -C passes=name-anon-globals to the compiler command line.");
410 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
411 This will likely cause errors in LLVM and should never happen.");
416 diag_handler.abort_if_errors();
418 // Finally, run the actual optimization passes
419 time_ext(config.time_passes,
421 &format!("llvm function passes [{}]", module_name.unwrap()),
423 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
425 timeline.record("fpm");
426 time_ext(config.time_passes,
428 &format!("llvm module passes [{}]", module_name.unwrap()),
430 llvm::LLVMRunPassManager(mpm, llmod)
433 // Deallocate managers that we're now done with
434 llvm::LLVMDisposePassManager(fpm);
435 llvm::LLVMDisposePassManager(mpm);
440 pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
441 diag_handler: &Handler,
442 module: ModuleCodegen<ModuleLlvm>,
443 config: &ModuleConfig,
444 timeline: &mut Timeline)
445 -> Result<CompiledModule, FatalError>
447 timeline.record("codegen");
449 let llmod = module.module_llvm.llmod();
450 let llcx = &*module.module_llvm.llcx;
451 let tm = &*module.module_llvm.tm;
452 let module_name = module.name.clone();
453 let module_name = Some(&module_name[..]);
454 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
456 if cgcx.msvc_imps_needed {
457 create_msvc_imps(cgcx, llcx, llmod);
460 // A codegen-specific pass manager is used to generate object
461 // files for an LLVM module.
463 // Apparently each of these pass managers is a one-shot kind of
464 // thing, so we create a new one for each type of output. The
465 // pass manager passed to the closure should be ensured to not
466 // escape the closure itself, and the manager should only be
468 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
469 llmod: &'ll llvm::Module,
472 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
474 let cpm = llvm::LLVMCreatePassManager();
475 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
476 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
480 // If we don't have the integrated assembler, then we need to emit asm
481 // from LLVM and use `gcc` to create the object file.
482 let asm_to_obj = config.emit_obj && config.no_integrated_as;
484 // Change what we write and cleanup based on whether obj files are
485 // just llvm bitcode. In that case write bitcode, and possibly
486 // delete the bitcode if it wasn't requested. Don't generate the
487 // machine code, instead copy the .o file from the .bc
488 let write_bc = config.emit_bc || config.obj_is_bitcode;
489 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
490 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
491 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
493 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
494 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
497 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
498 let thin = ThinBuffer::new(llmod);
499 let data = thin.data();
500 timeline.record("make-bc");
503 if let Err(e) = fs::write(&bc_out, data) {
504 diag_handler.err(&format!("failed to write bytecode: {}", e));
506 timeline.record("write-bc");
509 if config.embed_bitcode {
510 embed_bitcode(cgcx, llcx, llmod, Some(data));
511 timeline.record("embed-bc");
514 if config.emit_bc_compressed {
515 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
516 let data = bytecode::encode(&module.name, data);
517 if let Err(e) = fs::write(&dst, data) {
518 diag_handler.err(&format!("failed to write bytecode: {}", e));
520 timeline.record("compress-bc");
522 } else if config.embed_bitcode_marker {
523 embed_bitcode(cgcx, llcx, llmod, None);
526 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
527 || -> Result<(), FatalError> {
529 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
530 let out = path_to_c_string(&out);
532 extern "C" fn demangle_callback(input_ptr: *const c_char,
534 output_ptr: *mut c_char,
535 output_len: size_t) -> size_t {
537 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
540 let input = match str::from_utf8(input) {
545 let output = unsafe {
546 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
548 let mut cursor = io::Cursor::new(output);
550 let demangled = match rustc_demangle::try_demangle(input) {
555 if let Err(_) = write!(cursor, "{:#}", demangled) {
556 // Possible only if provided buffer is not big enough
560 cursor.position() as size_t
563 with_codegen(tm, llmod, config.no_builtins, |cpm| {
564 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
565 llvm::LLVMDisposePassManager(cpm);
567 timeline.record("ir");
570 if config.emit_asm || asm_to_obj {
571 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
573 // We can't use the same module for asm and binary output, because that triggers
574 // various errors like invalid IR or broken binaries, so we might have to clone the
575 // module to produce the asm output
576 let llmod = if config.emit_obj {
577 llvm::LLVMCloneModule(llmod)
581 with_codegen(tm, llmod, config.no_builtins, |cpm| {
582 write_output_file(diag_handler, tm, cpm, llmod, &path,
583 llvm::FileType::AssemblyFile)
585 timeline.record("asm");
589 with_codegen(tm, llmod, config.no_builtins, |cpm| {
590 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
591 llvm::FileType::ObjectFile)
593 timeline.record("obj");
594 } else if asm_to_obj {
595 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
596 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
597 timeline.record("asm_to_obj");
599 if !config.emit_asm && !cgcx.save_temps {
600 drop(fs::remove_file(&assembly));
608 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
609 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
610 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
615 debug!("removing_bitcode {:?}", bc_out);
616 if let Err(e) = fs::remove_file(&bc_out) {
617 diag_handler.err(&format!("failed to remove bitcode: {}", e));
623 Ok(module.into_compiled_module(config.emit_obj,
625 config.emit_bc_compressed,
626 &cgcx.output_filenames))
629 /// Embed the bitcode of an LLVM module in the LLVM module itself.
631 /// This is done primarily for iOS where it appears to be standard to compile C
632 /// code at least with `-fembed-bitcode` which creates two sections in the
635 /// * __LLVM,__bitcode
636 /// * __LLVM,__cmdline
638 /// It appears *both* of these sections are necessary to get the linker to
639 /// recognize what's going on. For us though we just always throw in an empty
642 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
643 /// embed an empty section.
645 /// Basically all of this is us attempting to follow in the footsteps of clang
646 /// on iOS. See #35968 for lots more info.
647 unsafe fn embed_bitcode(cgcx: &CodegenContext<LlvmCodegenBackend>,
648 llcx: &llvm::Context,
649 llmod: &llvm::Module,
650 bitcode: Option<&[u8]>) {
651 let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
652 let llglobal = llvm::LLVMAddGlobal(
654 common::val_ty(llconst),
655 "rustc.embedded.module\0".as_ptr() as *const _,
657 llvm::LLVMSetInitializer(llglobal, llconst);
659 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
660 cgcx.opts.target_triple.triple().contains("-darwin");
662 let section = if is_apple {
667 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
668 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
669 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
671 let llconst = common::bytes_in_context(llcx, &[]);
672 let llglobal = llvm::LLVMAddGlobal(
674 common::val_ty(llconst),
675 "rustc.embedded.cmdline\0".as_ptr() as *const _,
677 llvm::LLVMSetInitializer(llglobal, llconst);
678 let section = if is_apple {
683 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
684 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
687 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
688 config: &ModuleConfig,
689 opt_level: llvm::CodeGenOptLevel,
690 prepare_for_thin_lto: bool,
691 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
694 // Create the PassManagerBuilder for LLVM. We configure it with
695 // reasonable defaults and prepare it to actually populate the pass
697 let builder = llvm::LLVMPassManagerBuilderCreate();
698 let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1)
699 .unwrap_or(llvm::CodeGenOptSizeNone);
700 let inline_threshold = config.inline_threshold;
702 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
703 let s = if s.is_empty() { "default_%m.profraw" } else { s };
704 CString::new(s.as_bytes()).unwrap()
707 let pgo_use_path = if config.pgo_use.is_empty() {
710 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
713 llvm::LLVMRustConfigurePassManagerBuilder(
716 config.merge_functions,
717 config.vectorize_slp,
718 config.vectorize_loop,
719 prepare_for_thin_lto,
720 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
721 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
724 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
726 if opt_size != llvm::CodeGenOptSizeNone {
727 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
730 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
732 // Here we match what clang does (kinda). For O0 we only inline
733 // always-inline functions (but don't add lifetime intrinsics), at O1 we
734 // inline with lifetime intrinsics, and O2+ we add an inliner with a
735 // thresholds copied from clang.
736 match (opt_level, opt_size, inline_threshold) {
738 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
740 (llvm::CodeGenOptLevel::Aggressive, ..) => {
741 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
743 (_, llvm::CodeGenOptSizeDefault, _) => {
744 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
746 (_, llvm::CodeGenOptSizeAggressive, _) => {
747 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
749 (llvm::CodeGenOptLevel::None, ..) => {
750 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
752 (llvm::CodeGenOptLevel::Less, ..) => {
753 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
755 (llvm::CodeGenOptLevel::Default, ..) => {
756 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
758 (llvm::CodeGenOptLevel::Other, ..) => {
759 bug!("CodeGenOptLevel::Other selected")
764 llvm::LLVMPassManagerBuilderDispose(builder);
767 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
768 // This is required to satisfy `dllimport` references to static data in .rlibs
769 // when using MSVC linker. We do this only for data, as linker can fix up
770 // code references on its own.
771 // See #26591, #27438
773 cgcx: &CodegenContext<LlvmCodegenBackend>,
774 llcx: &llvm::Context,
777 if !cgcx.msvc_imps_needed {
780 // The x86 ABI seems to require that leading underscores are added to symbol
781 // names, so we need an extra underscore on 32-bit. There's also a leading
782 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
783 // underscores added in front).
784 let prefix = if cgcx.target_pointer_width == "32" {
790 let i8p_ty = Type::i8p_llcx(llcx);
791 let globals = base::iter_globals(llmod)
793 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
794 llvm::LLVMIsDeclaration(val) == 0
797 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
798 let mut imp_name = prefix.as_bytes().to_vec();
799 imp_name.extend(name.to_bytes());
800 let imp_name = CString::new(imp_name).unwrap();
803 .collect::<Vec<_>>();
804 for (imp_name, val) in globals {
805 let imp = llvm::LLVMAddGlobal(llmod,
807 imp_name.as_ptr() as *const _);
808 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
809 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);