]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/write.rs
Auto merge of #60272 - Jakst:patch-1, r=Manishearth
[rust.git] / src / librustc_codegen_llvm / back / write.rs
1 use crate::attributes;
2 use crate::back::bytecode;
3 use crate::back::lto::ThinBuffer;
4 use crate::base;
5 use crate::consts;
6 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
7 use crate::llvm_util;
8 use crate::ModuleLlvm;
9 use crate::type_::Type;
10 use crate::context::{is_pie_binary, get_reloc_model};
11 use crate::common;
12 use crate::LlvmCodegenBackend;
13 use rustc::hir::def_id::LOCAL_CRATE;
14 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, run_assembler};
15 use rustc_codegen_ssa::traits::*;
16 use rustc::session::config::{self, OutputType, Passes, Lto, PgoGenerate};
17 use rustc::session::Session;
18 use rustc::ty::TyCtxt;
19 use rustc_codegen_ssa::{RLIB_BYTECODE_EXTENSION, ModuleCodegen, CompiledModule};
20 use rustc::util::common::time_ext;
21 use rustc_fs_util::{path_to_c_string, link_or_copy};
22 use rustc_data_structures::small_c_str::SmallCStr;
23 use errors::{Handler, FatalError};
24
25 use std::ffi::{CString, CStr};
26 use std::fs;
27 use std::io::{self, Write};
28 use std::path::{Path, PathBuf};
29 use std::str;
30 use std::sync::Arc;
31 use std::slice;
32 use libc::{c_uint, c_void, c_char, size_t};
33
34 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
35     ("pic", llvm::RelocMode::PIC),
36     ("static", llvm::RelocMode::Static),
37     ("default", llvm::RelocMode::Default),
38     ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
39     ("ropi", llvm::RelocMode::ROPI),
40     ("rwpi", llvm::RelocMode::RWPI),
41     ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
42 ];
43
44 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
45     ("small", llvm::CodeModel::Small),
46     ("kernel", llvm::CodeModel::Kernel),
47     ("medium", llvm::CodeModel::Medium),
48     ("large", llvm::CodeModel::Large),
49 ];
50
51 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
52     ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
53     ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
54     ("initial-exec", llvm::ThreadLocalMode::InitialExec),
55     ("local-exec", llvm::ThreadLocalMode::LocalExec),
56 ];
57
58 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
59     match llvm::last_error() {
60         Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
61         None => handler.fatal(&msg),
62     }
63 }
64
65 pub fn write_output_file(
66         handler: &errors::Handler,
67         target: &'ll llvm::TargetMachine,
68         pm: &llvm::PassManager<'ll>,
69         m: &'ll llvm::Module,
70         output: &Path,
71         file_type: llvm::FileType) -> Result<(), FatalError> {
72     unsafe {
73         let output_c = path_to_c_string(output);
74         let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
75         result.into_result().map_err(|()| {
76             let msg = format!("could not write output to {}", output.display());
77             llvm_err(handler, &msg)
78         })
79     }
80 }
81
82 pub fn create_informational_target_machine(
83     sess: &Session,
84     find_features: bool,
85 ) -> &'static mut llvm::TargetMachine {
86     target_machine_factory(sess, config::OptLevel::No, find_features)().unwrap_or_else(|err| {
87         llvm_err(sess.diagnostic(), &err).raise()
88     })
89 }
90
91 pub fn create_target_machine(
92     tcx: TyCtxt<'_, '_, '_>,
93     find_features: bool,
94 ) -> &'static mut llvm::TargetMachine {
95     target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
96     .unwrap_or_else(|err| {
97         llvm_err(tcx.sess.diagnostic(), &err).raise()
98     })
99 }
100
101 pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
102 {
103     use self::config::OptLevel::*;
104     match cfg {
105         No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
106         Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
107         Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
108         Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
109         Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
110         SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
111     }
112 }
113
114 // If find_features is true this won't access `sess.crate_types` by assuming
115 // that `is_pie_binary` is false. When we discover LLVM target features
116 // `sess.crate_types` is uninitialized so we cannot access it.
117 pub fn target_machine_factory(sess: &Session, optlvl: config::OptLevel, find_features: bool)
118     -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
119 {
120     let reloc_model = get_reloc_model(sess);
121
122     let (opt_level, _) = to_llvm_opt_settings(optlvl);
123     let use_softfp = sess.opts.cg.soft_float;
124
125     let ffunction_sections = sess.target.target.options.function_sections;
126     let fdata_sections = ffunction_sections;
127
128     let code_model_arg = sess.opts.cg.code_model.as_ref().or(
129         sess.target.target.options.code_model.as_ref(),
130     );
131
132     let code_model = match code_model_arg {
133         Some(s) => {
134             match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
135                 Some(x) => x.1,
136                 _ => {
137                     sess.err(&format!("{:?} is not a valid code model",
138                                       code_model_arg));
139                     sess.abort_if_errors();
140                     bug!();
141                 }
142             }
143         }
144         None => llvm::CodeModel::None,
145     };
146
147     let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
148     let mut singlethread = sess.target.target.options.singlethread;
149
150     // On the wasm target once the `atomics` feature is enabled that means that
151     // we're no longer single-threaded, or otherwise we don't want LLVM to
152     // lower atomic operations to single-threaded operations.
153     if singlethread &&
154         sess.target.target.llvm_target.contains("wasm32") &&
155         features.iter().any(|s| *s == "+atomics")
156     {
157         singlethread = false;
158     }
159
160     let triple = SmallCStr::new(&sess.target.target.llvm_target);
161     let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
162     let features = features.join(",");
163     let features = CString::new(features).unwrap();
164     let is_pie_binary = !find_features && is_pie_binary(sess);
165     let trap_unreachable = sess.target.target.options.trap_unreachable;
166     let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
167
168     let asm_comments = sess.asm_comments();
169
170     Arc::new(move || {
171         let tm = unsafe {
172             llvm::LLVMRustCreateTargetMachine(
173                 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
174                 code_model,
175                 reloc_model,
176                 opt_level,
177                 use_softfp,
178                 is_pie_binary,
179                 ffunction_sections,
180                 fdata_sections,
181                 trap_unreachable,
182                 singlethread,
183                 asm_comments,
184                 emit_stack_size_section,
185             )
186         };
187
188         tm.ok_or_else(|| {
189             format!("Could not create LLVM TargetMachine for triple: {}",
190                     triple.to_str().unwrap())
191         })
192     })
193 }
194
195 pub(crate) fn save_temp_bitcode(
196     cgcx: &CodegenContext<LlvmCodegenBackend>,
197     module: &ModuleCodegen<ModuleLlvm>,
198     name: &str
199 ) {
200     if !cgcx.save_temps {
201         return
202     }
203     unsafe {
204         let ext = format!("{}.bc", name);
205         let cgu = Some(&module.name[..]);
206         let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
207         let cstr = path_to_c_string(&path);
208         let llmod = module.module_llvm.llmod();
209         llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
210     }
211 }
212
213 pub struct DiagnosticHandlers<'a> {
214     data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
215     llcx: &'a llvm::Context,
216 }
217
218 impl<'a> DiagnosticHandlers<'a> {
219     pub fn new(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
220                handler: &'a Handler,
221                llcx: &'a llvm::Context) -> Self {
222         let data = Box::into_raw(Box::new((cgcx, handler)));
223         unsafe {
224             llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
225             llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
226         }
227         DiagnosticHandlers { data, llcx }
228     }
229 }
230
231 impl<'a> Drop for DiagnosticHandlers<'a> {
232     fn drop(&mut self) {
233         use std::ptr::null_mut;
234         unsafe {
235             llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
236             llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
237             drop(Box::from_raw(self.data));
238         }
239     }
240 }
241
242 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext<LlvmCodegenBackend>,
243                                                msg: &'b str,
244                                                cookie: c_uint) {
245     cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
246 }
247
248 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
249                                         user: *const c_void,
250                                         cookie: c_uint) {
251     if user.is_null() {
252         return
253     }
254     let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
255
256     let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
257         .expect("non-UTF8 SMDiagnostic");
258
259     report_inline_asm(cgcx, &msg, cookie);
260 }
261
262 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
263     if user.is_null() {
264         return
265     }
266     let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
267
268     match llvm::diagnostic::Diagnostic::unpack(info) {
269         llvm::diagnostic::InlineAsm(inline) => {
270             report_inline_asm(cgcx,
271                               &llvm::twine_to_string(inline.message),
272                               inline.cookie);
273         }
274
275         llvm::diagnostic::Optimization(opt) => {
276             let enabled = match cgcx.remark {
277                 Passes::All => true,
278                 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
279             };
280
281             if enabled {
282                 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
283                                                 opt.kind.describe(),
284                                                 opt.pass_name,
285                                                 opt.filename,
286                                                 opt.line,
287                                                 opt.column,
288                                                 opt.message));
289             }
290         }
291         llvm::diagnostic::PGO(diagnostic_ref) |
292         llvm::diagnostic::Linker(diagnostic_ref) => {
293             let msg = llvm::build_string(|s| {
294                 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
295             }).expect("non-UTF8 diagnostic");
296             diag_handler.warn(&msg);
297         }
298         llvm::diagnostic::UnknownDiagnostic(..) => {},
299     }
300 }
301
302 // Unsafe due to LLVM calls.
303 pub(crate) unsafe fn optimize(cgcx: &CodegenContext<LlvmCodegenBackend>,
304                    diag_handler: &Handler,
305                    module: &ModuleCodegen<ModuleLlvm>,
306                    config: &ModuleConfig)
307     -> Result<(), FatalError>
308 {
309     let llmod = module.module_llvm.llmod();
310     let llcx = &*module.module_llvm.llcx;
311     let tm = &*module.module_llvm.tm;
312     let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
313
314     let module_name = module.name.clone();
315     let module_name = Some(&module_name[..]);
316
317     if config.emit_no_opt_bc {
318         let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
319         let out = path_to_c_string(&out);
320         llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
321     }
322
323     if config.opt_level.is_some() {
324         // Create the two optimizing pass managers. These mirror what clang
325         // does, and are by populated by LLVM's default PassManagerBuilder.
326         // Each manager has a different set of passes, but they also share
327         // some common passes.
328         let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
329         let mpm = llvm::LLVMCreatePassManager();
330
331         {
332             // If we're verifying or linting, add them to the function pass
333             // manager.
334             let addpass = |pass_name: &str| {
335                 let pass_name = SmallCStr::new(pass_name);
336                 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
337                     Some(pass) => pass,
338                     None => return false,
339                 };
340                 let pass_manager = match llvm::LLVMRustPassKind(pass) {
341                     llvm::PassKind::Function => &*fpm,
342                     llvm::PassKind::Module => &*mpm,
343                     llvm::PassKind::Other => {
344                         diag_handler.err("Encountered LLVM pass kind we can't handle");
345                         return true
346                     },
347                 };
348                 llvm::LLVMRustAddPass(pass_manager, pass);
349                 true
350             };
351
352             if config.verify_llvm_ir { assert!(addpass("verify")); }
353
354             // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
355             // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
356             // we'll get errors in LLVM.
357             let using_thin_buffers = config.bitcode_needed();
358             let mut have_name_anon_globals_pass = false;
359             if !config.no_prepopulate_passes {
360                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
361                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
362                 let opt_level = config.opt_level.map(|x| to_llvm_opt_settings(x).0)
363                     .unwrap_or(llvm::CodeGenOptLevel::None);
364                 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
365                     (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
366                 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
367                     llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
368                     llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
369                 });
370
371                 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
372                 if using_thin_buffers && !prepare_for_thin_lto {
373                     assert!(addpass("name-anon-globals"));
374                     have_name_anon_globals_pass = true;
375                 }
376             }
377
378             for pass in &config.passes {
379                 if !addpass(pass) {
380                     diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
381                 }
382                 if pass == "name-anon-globals" {
383                     have_name_anon_globals_pass = true;
384                 }
385             }
386
387             for pass in &cgcx.plugin_passes {
388                 if !addpass(pass) {
389                     diag_handler.err(&format!("a plugin asked for LLVM pass \
390                                                `{}` but LLVM does not \
391                                                recognize it", pass));
392                 }
393                 if pass == "name-anon-globals" {
394                     have_name_anon_globals_pass = true;
395                 }
396             }
397
398             if using_thin_buffers && !have_name_anon_globals_pass {
399                 // As described above, this will probably cause an error in LLVM
400                 if config.no_prepopulate_passes {
401                     diag_handler.err("The current compilation is going to use thin LTO buffers \
402                                       without running LLVM's NameAnonGlobals pass. \
403                                       This will likely cause errors in LLVM. Consider adding \
404                                       -C passes=name-anon-globals to the compiler command line.");
405                 } else {
406                     bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
407                           This will likely cause errors in LLVM and should never happen.");
408                 }
409             }
410         }
411
412         diag_handler.abort_if_errors();
413
414         // Finally, run the actual optimization passes
415         {
416             let _timer = cgcx.profile_activity("LLVM_function_passes");
417             time_ext(config.time_passes,
418                         None,
419                         &format!("llvm function passes [{}]", module_name.unwrap()),
420                         || {
421                 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
422             });
423         }
424         {
425             let _timer = cgcx.profile_activity("LLVM_module_passes");
426             time_ext(config.time_passes,
427                     None,
428                     &format!("llvm module passes [{}]", module_name.unwrap()),
429                     || {
430                 llvm::LLVMRunPassManager(mpm, llmod)
431             });
432         }
433
434         // Deallocate managers that we're now done with
435         llvm::LLVMDisposePassManager(fpm);
436         llvm::LLVMDisposePassManager(mpm);
437     }
438     Ok(())
439 }
440
441 pub(crate) unsafe fn codegen(cgcx: &CodegenContext<LlvmCodegenBackend>,
442                   diag_handler: &Handler,
443                   module: ModuleCodegen<ModuleLlvm>,
444                   config: &ModuleConfig)
445     -> Result<CompiledModule, FatalError>
446 {
447     let _timer = cgcx.profile_activity("codegen");
448     {
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);
455
456         if cgcx.msvc_imps_needed {
457             create_msvc_imps(cgcx, llcx, llmod);
458         }
459
460         // A codegen-specific pass manager is used to generate object
461         // files for an LLVM module.
462         //
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
467         // used once.
468         unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
469                                           llmod: &'ll llvm::Module,
470                                           no_builtins: bool,
471                                           f: F) -> R
472             where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
473         {
474             let cpm = llvm::LLVMCreatePassManager();
475             llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
476             llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
477             f(cpm)
478         }
479
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;
483
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;
492
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);
495
496
497         if write_bc || config.emit_bc_compressed || config.embed_bitcode {
498             let _timer = cgcx.profile_activity("LLVM_make_bitcode");
499             let thin = ThinBuffer::new(llmod);
500             let data = thin.data();
501
502             if write_bc {
503                 let _timer = cgcx.profile_activity("LLVM_emit_bitcode");
504                 if let Err(e) = fs::write(&bc_out, data) {
505                     let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
506                     diag_handler.err(&msg);
507                 }
508             }
509
510             if config.embed_bitcode {
511                 let _timer = cgcx.profile_activity("LLVM_embed_bitcode");
512                 embed_bitcode(cgcx, llcx, llmod, Some(data));
513             }
514
515             if config.emit_bc_compressed {
516                 let _timer = cgcx.profile_activity("LLVM_compress_bitcode");
517                 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
518                 let data = bytecode::encode(&module.name, data);
519                 if let Err(e) = fs::write(&dst, data) {
520                     let msg = format!("failed to write bytecode to {}: {}", dst.display(), e);
521                     diag_handler.err(&msg);
522                 }
523             }
524         } else if config.embed_bitcode_marker {
525             embed_bitcode(cgcx, llcx, llmod, None);
526         }
527
528         time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
529             || -> Result<(), FatalError> {
530             if config.emit_ir {
531                 let _timer = cgcx.profile_activity("LLVM_emit_ir");
532                 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
533                 let out_c = path_to_c_string(&out);
534
535                 extern "C" fn demangle_callback(input_ptr: *const c_char,
536                                                 input_len: size_t,
537                                                 output_ptr: *mut c_char,
538                                                 output_len: size_t) -> size_t {
539                     let input = unsafe {
540                         slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
541                     };
542
543                     let input = match str::from_utf8(input) {
544                         Ok(s) => s,
545                         Err(_) => return 0,
546                     };
547
548                     let output = unsafe {
549                         slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
550                     };
551                     let mut cursor = io::Cursor::new(output);
552
553                     let demangled = match rustc_demangle::try_demangle(input) {
554                         Ok(d) => d,
555                         Err(_) => return 0,
556                     };
557
558                     if let Err(_) = write!(cursor, "{:#}", demangled) {
559                         // Possible only if provided buffer is not big enough
560                         return 0;
561                     }
562
563                     cursor.position() as size_t
564                 }
565
566                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
567                     let result =
568                         llvm::LLVMRustPrintModule(cpm, llmod, out_c.as_ptr(), demangle_callback);
569                     llvm::LLVMDisposePassManager(cpm);
570                     result.into_result().map_err(|()| {
571                         let msg = format!("failed to write LLVM IR to {}", out.display());
572                         llvm_err(diag_handler, &msg)
573                     })
574                 })?;
575             }
576
577             if config.emit_asm || asm_to_obj {
578                 let _timer = cgcx.profile_activity("LLVM_emit_asm");
579                 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
580
581                 // We can't use the same module for asm and binary output, because that triggers
582                 // various errors like invalid IR or broken binaries, so we might have to clone the
583                 // module to produce the asm output
584                 let llmod = if config.emit_obj {
585                     llvm::LLVMCloneModule(llmod)
586                 } else {
587                     llmod
588                 };
589                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
590                     write_output_file(diag_handler, tm, cpm, llmod, &path,
591                                       llvm::FileType::AssemblyFile)
592                 })?;
593             }
594
595             if write_obj {
596                 let _timer = cgcx.profile_activity("LLVM_emit_obj");
597                 with_codegen(tm, llmod, config.no_builtins, |cpm| {
598                     write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
599                                       llvm::FileType::ObjectFile)
600                 })?;
601             } else if asm_to_obj {
602                 let _timer = cgcx.profile_activity("LLVM_asm_to_obj");
603                 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
604                 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
605
606                 if !config.emit_asm && !cgcx.save_temps {
607                     drop(fs::remove_file(&assembly));
608                 }
609             }
610
611             Ok(())
612         })?;
613
614         if copy_bc_to_obj {
615             debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
616             if let Err(e) = link_or_copy(&bc_out, &obj_out) {
617                 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
618             }
619         }
620
621         if rm_bc {
622             debug!("removing_bitcode {:?}", bc_out);
623             if let Err(e) = fs::remove_file(&bc_out) {
624                 diag_handler.err(&format!("failed to remove bitcode: {}", e));
625             }
626         }
627
628         drop(handlers);
629     }
630     Ok(module.into_compiled_module(config.emit_obj,
631                                    config.emit_bc,
632                                    config.emit_bc_compressed,
633                                    &cgcx.output_filenames))
634 }
635
636 /// Embed the bitcode of an LLVM module in the LLVM module itself.
637 ///
638 /// This is done primarily for iOS where it appears to be standard to compile C
639 /// code at least with `-fembed-bitcode` which creates two sections in the
640 /// executable:
641 ///
642 /// * __LLVM,__bitcode
643 /// * __LLVM,__cmdline
644 ///
645 /// It appears *both* of these sections are necessary to get the linker to
646 /// recognize what's going on. For us though we just always throw in an empty
647 /// cmdline section.
648 ///
649 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
650 /// embed an empty section.
651 ///
652 /// Basically all of this is us attempting to follow in the footsteps of clang
653 /// on iOS. See #35968 for lots more info.
654 unsafe fn embed_bitcode(cgcx: &CodegenContext<LlvmCodegenBackend>,
655                         llcx: &llvm::Context,
656                         llmod: &llvm::Module,
657                         bitcode: Option<&[u8]>) {
658     let llconst = common::bytes_in_context(llcx, bitcode.unwrap_or(&[]));
659     let llglobal = llvm::LLVMAddGlobal(
660         llmod,
661         common::val_ty(llconst),
662         "rustc.embedded.module\0".as_ptr() as *const _,
663     );
664     llvm::LLVMSetInitializer(llglobal, llconst);
665
666     let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
667                    cgcx.opts.target_triple.triple().contains("-darwin");
668
669     let section = if is_apple {
670         "__LLVM,__bitcode\0"
671     } else {
672         ".llvmbc\0"
673     };
674     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
675     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
676     llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
677
678     let llconst = common::bytes_in_context(llcx, &[]);
679     let llglobal = llvm::LLVMAddGlobal(
680         llmod,
681         common::val_ty(llconst),
682         "rustc.embedded.cmdline\0".as_ptr() as *const _,
683     );
684     llvm::LLVMSetInitializer(llglobal, llconst);
685     let section = if  is_apple {
686         "__LLVM,__cmdline\0"
687     } else {
688         ".llvmcmd\0"
689     };
690     llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
691     llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
692 }
693
694 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
695                             config: &ModuleConfig,
696                             opt_level: llvm::CodeGenOptLevel,
697                             prepare_for_thin_lto: bool,
698                             f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
699     use std::ptr;
700
701     // Create the PassManagerBuilder for LLVM. We configure it with
702     // reasonable defaults and prepare it to actually populate the pass
703     // manager.
704     let builder = llvm::LLVMPassManagerBuilderCreate();
705     let opt_size = config.opt_size.map(|x| to_llvm_opt_settings(x).1)
706         .unwrap_or(llvm::CodeGenOptSizeNone);
707     let inline_threshold = config.inline_threshold;
708
709     let pgo_gen_path = match config.pgo_gen {
710         PgoGenerate::Enabled(ref opt_dir_path) => {
711             let path = if let Some(dir_path) = opt_dir_path {
712                 dir_path.join("default_%m.profraw")
713             } else {
714                 PathBuf::from("default_%m.profraw")
715             };
716
717             Some(CString::new(format!("{}", path.display())).unwrap())
718         }
719         PgoGenerate::Disabled => {
720             None
721         }
722     };
723
724     let pgo_use_path = if config.pgo_use.is_empty() {
725         None
726     } else {
727         Some(CString::new(config.pgo_use.as_bytes()).unwrap())
728     };
729
730     llvm::LLVMRustConfigurePassManagerBuilder(
731         builder,
732         opt_level,
733         config.merge_functions,
734         config.vectorize_slp,
735         config.vectorize_loop,
736         prepare_for_thin_lto,
737         pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
738         pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
739     );
740
741     llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
742
743     if opt_size != llvm::CodeGenOptSizeNone {
744         llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
745     }
746
747     llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
748
749     // Here we match what clang does (kinda). For O0 we only inline
750     // always-inline functions (but don't add lifetime intrinsics), at O1 we
751     // inline with lifetime intrinsics, and O2+ we add an inliner with a
752     // thresholds copied from clang.
753     match (opt_level, opt_size, inline_threshold) {
754         (.., Some(t)) => {
755             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
756         }
757         (llvm::CodeGenOptLevel::Aggressive, ..) => {
758             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
759         }
760         (_, llvm::CodeGenOptSizeDefault, _) => {
761             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
762         }
763         (_, llvm::CodeGenOptSizeAggressive, _) => {
764             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
765         }
766         (llvm::CodeGenOptLevel::None, ..) => {
767             llvm::LLVMRustAddAlwaysInlinePass(builder, false);
768         }
769         (llvm::CodeGenOptLevel::Less, ..) => {
770             llvm::LLVMRustAddAlwaysInlinePass(builder, true);
771         }
772         (llvm::CodeGenOptLevel::Default, ..) => {
773             llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
774         }
775         (llvm::CodeGenOptLevel::Other, ..) => {
776             bug!("CodeGenOptLevel::Other selected")
777         }
778     }
779
780     f(builder);
781     llvm::LLVMPassManagerBuilderDispose(builder);
782 }
783
784 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
785 // This is required to satisfy `dllimport` references to static data in .rlibs
786 // when using MSVC linker.  We do this only for data, as linker can fix up
787 // code references on its own.
788 // See #26591, #27438
789 fn create_msvc_imps(
790     cgcx: &CodegenContext<LlvmCodegenBackend>,
791     llcx: &llvm::Context,
792     llmod: &llvm::Module
793 ) {
794     if !cgcx.msvc_imps_needed {
795         return
796     }
797     // The x86 ABI seems to require that leading underscores are added to symbol
798     // names, so we need an extra underscore on 32-bit. There's also a leading
799     // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
800     // underscores added in front).
801     let prefix = if cgcx.target_pointer_width == "32" {
802         "\x01__imp__"
803     } else {
804         "\x01__imp_"
805     };
806
807     unsafe {
808         let i8p_ty = Type::i8p_llcx(llcx);
809         let globals = base::iter_globals(llmod)
810             .filter(|&val| {
811                 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
812                     llvm::LLVMIsDeclaration(val) == 0
813             })
814             .filter_map(|val| {
815                 // Exclude some symbols that we know are not Rust symbols.
816                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
817                 if ignored(name.to_bytes()) {
818                     None
819                 } else {
820                     Some((val, name))
821                 }
822             })
823             .map(move |(val, name)| {
824                 let mut imp_name = prefix.as_bytes().to_vec();
825                 imp_name.extend(name.to_bytes());
826                 let imp_name = CString::new(imp_name).unwrap();
827                 (imp_name, val)
828             })
829             .collect::<Vec<_>>();
830
831         for (imp_name, val) in globals {
832             let imp = llvm::LLVMAddGlobal(llmod,
833                                           i8p_ty,
834                                           imp_name.as_ptr() as *const _);
835             llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
836             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
837         }
838     }
839
840     // Use this function to exclude certain symbols from `__imp` generation.
841     fn ignored(symbol_name: &[u8]) -> bool {
842         // These are symbols generated by LLVM's profiling instrumentation
843         symbol_name.starts_with(b"__llvm_profile_")
844     }
845 }