From 1d1dc48407e9feb5443173aefb3fd0db252e82c7 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:37:28 +0200 Subject: [PATCH 01/10] codegen_llvm_back: whitespace & formatting fixes --- src/librustc_codegen_llvm/back/archive.rs | 1 + src/librustc_codegen_llvm/back/link.rs | 15 +++--- src/librustc_codegen_llvm/back/lto.rs | 17 +++--- src/librustc_codegen_llvm/back/rpath.rs | 3 +- src/librustc_codegen_llvm/back/write.rs | 57 ++++++++++----------- src/librustc_codegen_utils/linker.rs | 11 ++-- src/librustc_codegen_utils/symbol_export.rs | 11 ++-- 7 files changed, 53 insertions(+), 62 deletions(-) diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index ce4cb1ea3a042..077c8c31f4a2e 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -83,6 +83,7 @@ impl<'a> ArchiveBuilder<'a> { if self.src_archive().is_none() { return Vec::new() } + let archive = self.src_archive.as_ref().unwrap().as_ref().unwrap(); let ret = archive.iter() .filter_map(|child| child.ok()) diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index dd95c3d986299..b137102659aa3 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -47,8 +47,8 @@ use std::str; use syntax::attr; pub use rustc_codegen_utils::link::{find_crate_name, filename_for_input, default_output_for_target, - invalid_output_for_target, out_filename, check_file_is_writeable, - filename_for_metadata}; + invalid_output_for_target, filename_for_metadata, + out_filename, check_file_is_writeable}; // The third parameter is for env vars, used on windows to set up the // path for MSVC to find its DLLs, and gcc to find its bundled @@ -147,9 +147,7 @@ pub(crate) fn link_binary(sess: &Session, // Remove the temporary object file and metadata if we aren't saving temps if !sess.opts.cg.save_temps { - if sess.opts.output_types.should_codegen() && - !preserve_objects_for_their_debuginfo(sess) - { + if sess.opts.output_types.should_codegen() && !preserve_objects_for_their_debuginfo(sess) { for obj in codegen_results.modules.iter().filter_map(|m| m.object.as_ref()) { remove(sess, obj); } @@ -814,8 +812,8 @@ fn link_natively(sess: &Session, .unwrap_or_else(|_| { let mut x = "Non-UTF-8 output: ".to_string(); x.extend(s.iter() - .flat_map(|&b| ascii::escape_default(b)) - .map(|b| char::from_u32(b as u32).unwrap())); + .flat_map(|&b| ascii::escape_default(b)) + .map(|b| char::from_u32(b as u32).unwrap())); x }) } @@ -1012,8 +1010,7 @@ fn exec_linker(sess: &Session, cmd: &mut Command, out_filename: &Path, tmpdir: & // ensure the line is interpreted as one whole argument. for c in self.arg.chars() { match c { - '\\' | - ' ' => write!(f, "\\{}", c)?, + '\\' | ' ' => write!(f, "\\{}", c)?, c => write!(f, "{}", c)?, } } diff --git a/src/librustc_codegen_llvm/back/lto.rs b/src/librustc_codegen_llvm/back/lto.rs index 3d96fef7c0d6f..cb944e08c8324 100644 --- a/src/librustc_codegen_llvm/back/lto.rs +++ b/src/librustc_codegen_llvm/back/lto.rs @@ -205,11 +205,11 @@ pub(crate) fn run(cgcx: &CodegenContext, Lto::Fat => { assert!(cached_modules.is_empty()); let opt_jobs = fat_lto(cgcx, - &diag_handler, - modules, - upstream_modules, - &symbol_white_list, - timeline); + &diag_handler, + modules, + upstream_modules, + &symbol_white_list, + timeline); opt_jobs.map(|opt_jobs| (opt_jobs, vec![])) } Lto::Thin | @@ -310,8 +310,8 @@ fn fat_lto(cgcx: &CodegenContext, unsafe { let ptr = symbol_white_list.as_ptr(); llvm::LLVMRustRunRestrictionPass(llmod, - ptr as *const *const libc::c_char, - symbol_white_list.len() as libc::size_t); + ptr as *const *const libc::c_char, + symbol_white_list.len() as libc::size_t); cgcx.save_temp_bitcode(&module, "lto.after-restriction"); } @@ -617,8 +617,7 @@ fn run_pass_manager(cgcx: &CodegenContext, llvm::LLVMRustAddPass(pm, pass.unwrap()); } - time_ext(cgcx.time_passes, None, "LTO passes", || - llvm::LLVMRunPassManager(pm, llmod)); + time_ext(cgcx.time_passes, None, "LTO passes", || llvm::LLVMRunPassManager(pm, llmod)); llvm::LLVMDisposePassManager(pm); } diff --git a/src/librustc_codegen_llvm/back/rpath.rs b/src/librustc_codegen_llvm/back/rpath.rs index 9609cb0c1553b..a7772bf55180a 100644 --- a/src/librustc_codegen_llvm/back/rpath.rs +++ b/src/librustc_codegen_llvm/back/rpath.rs @@ -117,8 +117,7 @@ fn get_rpath_relative_to_output(config: &mut RPathConfig, lib: &Path) -> String let relative = path_relative_from(&lib, &output).unwrap_or_else(|| panic!("couldn't create relative path from {:?} to {:?}", output, lib)); // FIXME (#9639): This needs to handle non-utf8 paths - format!("{}/{}", prefix, - relative.to_str().expect("non-utf8 component in path")) + format!("{}/{}", prefix, relative.to_str().expect("non-utf8 component in path")) } // This routine is adapted from the *old* Path's `path_relative_from` diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 184be4b9eab39..b55121ca69048 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -106,8 +106,7 @@ pub fn write_output_file( file_type: llvm::FileType) -> Result<(), FatalError> { unsafe { let output_c = path2cstr(output); - let result = llvm::LLVMRustWriteOutputFile( - target, pm, m, output_c.as_ptr(), file_type); + let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type); if result.into_result().is_err() { let msg = format!("could not write output to {}", output.display()); Err(llvm_err(handler, msg)) @@ -590,8 +589,7 @@ unsafe fn optimize(cgcx: &CodegenContext, for pass in &config.passes { if !addpass(pass) { - diag_handler.warn(&format!("unknown pass `{}`, ignoring", - pass)); + diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass)); } if pass == "name-anon-globals" { have_name_anon_globals_pass = true; @@ -601,8 +599,8 @@ unsafe fn optimize(cgcx: &CodegenContext, for pass in &cgcx.plugin_passes { if !addpass(pass) { diag_handler.err(&format!("a plugin asked for LLVM pass \ - `{}` but LLVM does not \ - recognize it", pass)); + `{}` but LLVM does not \ + recognize it", pass)); } if pass == "name-anon-globals" { have_name_anon_globals_pass = true; @@ -613,12 +611,12 @@ unsafe fn optimize(cgcx: &CodegenContext, // As described above, this will probably cause an error in LLVM if config.no_prepopulate_passes { diag_handler.err("The current compilation is going to use thin LTO buffers \ - without running LLVM's NameAnonGlobals pass. \ - This will likely cause errors in LLVM. Consider adding \ - -C passes=name-anon-globals to the compiler command line."); + without running LLVM's NameAnonGlobals pass. \ + This will likely cause errors in LLVM. Consider adding \ + -C passes=name-anon-globals to the compiler command line."); } else { bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \ - This will likely cause errors in LLVM and should never happen."); + This will likely cause errors in LLVM and should never happen."); } } } @@ -704,9 +702,9 @@ unsafe fn codegen(cgcx: &CodegenContext, // escape the closure itself, and the manager should only be // used once. unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine, - llmod: &'ll llvm::Module, - no_builtins: bool, - f: F) -> R + llmod: &'ll llvm::Module, + no_builtins: bool, + f: F) -> R where F: FnOnce(&'ll mut PassManager<'ll>) -> R, { let cpm = llvm::LLVMCreatePassManager(); @@ -818,7 +816,7 @@ unsafe fn codegen(cgcx: &CodegenContext, }; with_codegen(tm, llmod, config.no_builtins, |cpm| { write_output_file(diag_handler, tm, cpm, llmod, &path, - llvm::FileType::AssemblyFile) + llvm::FileType::AssemblyFile) })?; timeline.record("asm"); } @@ -826,7 +824,7 @@ unsafe fn codegen(cgcx: &CodegenContext, if write_obj { with_codegen(tm, llmod, config.no_builtins, |cpm| { write_output_file(diag_handler, tm, cpm, llmod, &obj_out, - llvm::FileType::ObjectFile) + llvm::FileType::ObjectFile) })?; timeline.record("obj"); } else if asm_to_obj { @@ -947,11 +945,11 @@ fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool { } pub fn start_async_codegen(tcx: TyCtxt, - time_graph: Option, - metadata: EncodedMetadata, - coordinator_receive: Receiver>, - total_cgus: usize) - -> OngoingCodegen { + time_graph: Option, + metadata: EncodedMetadata, + coordinator_receive: Receiver>, + total_cgus: usize) + -> OngoingCodegen { let sess = tcx.sess; let crate_name = tcx.crate_name(LOCAL_CRATE); let crate_hash = tcx.crate_hash(LOCAL_CRATE); @@ -1116,7 +1114,8 @@ fn copy_all_cgu_workproducts_to_incr_comp_cache_dir( } if let Some((id, product)) = - copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) { + copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) + { work_products.insert(id, product); } } @@ -1584,10 +1583,8 @@ fn start_executing_work(tcx: TyCtxt, let (name, mut cmd) = get_linker(sess, &linker, flavor); cmd.args(&sess.target.target.options.asm_args); - Some(Arc::new(AssemblerCommand { - name, - cmd, - })) + + Some(Arc::new(AssemblerCommand { name, cmd })) } else { None }; @@ -2186,9 +2183,9 @@ pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, handler.struct_err(&format!("linking with `{}` failed: {}", pname.display(), prog.status)) - .note(&format!("{:?}", &cmd)) - .note(str::from_utf8(¬e[..]).unwrap()) - .emit(); + .note(&format!("{:?}", &cmd)) + .note(str::from_utf8(¬e[..]).unwrap()) + .emit(); handler.abort_if_errors(); } }, @@ -2450,8 +2447,8 @@ impl OngoingCodegen { } pub(crate) fn submit_pre_codegened_module_to_llvm(&self, - tcx: TyCtxt, - module: ModuleCodegen) { + tcx: TyCtxt, + module: ModuleCodegen) { self.wait_for_signal_to_codegen_item(); self.check_for_errors(tcx.sess); diff --git a/src/librustc_codegen_utils/linker.rs b/src/librustc_codegen_utils/linker.rs index c1f41fd509a14..501166af90686 100644 --- a/src/librustc_codegen_utils/linker.rs +++ b/src/librustc_codegen_utils/linker.rs @@ -224,9 +224,9 @@ impl<'a> GccLinker<'a> { } impl<'a> Linker for GccLinker<'a> { - fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}",lib)); } + fn link_dylib(&mut self, lib: &str) { self.hint_dynamic(); self.cmd.arg(format!("-l{}", lib)); } fn link_staticlib(&mut self, lib: &str) { - self.hint_static(); self.cmd.arg(format!("-l{}",lib)); + self.hint_static(); self.cmd.arg(format!("-l{}", lib)); } fn link_rlib(&mut self, lib: &Path) { self.hint_static(); self.cmd.arg(lib); } fn include_path(&mut self, path: &Path) { self.cmd.arg("-L").arg(path); } @@ -243,7 +243,7 @@ impl<'a> Linker for GccLinker<'a> { fn link_rust_dylib(&mut self, lib: &str, _path: &Path) { self.hint_dynamic(); - self.cmd.arg(format!("-l{}",lib)); + self.cmd.arg(format!("-l{}", lib)); } fn link_framework(&mut self, framework: &str) { @@ -261,7 +261,7 @@ impl<'a> Linker for GccLinker<'a> { self.hint_static(); let target = &self.sess.target.target; if !target.options.is_like_osx { - self.linker_arg("--whole-archive").cmd.arg(format!("-l{}",lib)); + self.linker_arg("--whole-archive").cmd.arg(format!("-l{}", lib)); self.linker_arg("--no-whole-archive"); } else { // -force_load is the macOS equivalent of --whole-archive, but it @@ -373,8 +373,7 @@ impl<'a> Linker for GccLinker<'a> { // purely to support rustbuild right now, we should get a more // principled solution at some point to force the compiler to pass // the right `-Wl,-install_name` with an `@rpath` in it. - if self.sess.opts.cg.rpath || - self.sess.opts.debugging_opts.osx_rpath_install_name { + if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name { self.linker_arg("-install_name"); let mut v = OsString::from("@rpath/"); v.push(out_filename.file_name().unwrap()); diff --git a/src/librustc_codegen_utils/symbol_export.rs b/src/librustc_codegen_utils/symbol_export.rs index 6c40296b2ef37..dff7e518630e4 100644 --- a/src/librustc_codegen_utils/symbol_export.rs +++ b/src/librustc_codegen_utils/symbol_export.rs @@ -47,11 +47,10 @@ fn crate_export_threshold(crate_type: config::CrateType) -> SymbolExportLevel { } } -pub fn crates_export_threshold(crate_types: &[config::CrateType]) - -> SymbolExportLevel { - if crate_types.iter().any(|&crate_type| { - crate_export_threshold(crate_type) == SymbolExportLevel::Rust - }) { +pub fn crates_export_threshold(crate_types: &[config::CrateType]) -> SymbolExportLevel { + if crate_types.iter().any(|&crate_type| + crate_export_threshold(crate_type) == SymbolExportLevel::Rust) + { SymbolExportLevel::Rust } else { SymbolExportLevel::C @@ -359,7 +358,7 @@ fn is_unreachable_local_definition_provider(tcx: TyCtxt, def_id: DefId) -> bool !tcx.reachable_set(LOCAL_CRATE).0.contains(&node_id) } else { bug!("is_unreachable_local_definition called with non-local DefId: {:?}", - def_id) + def_id) } } From c4c39e9395f10005aa6919d426e18fec43328392 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:42:14 +0200 Subject: [PATCH 02/10] codegen_llvm_back: use Cow<'static, str> where applicable --- src/librustc_codegen_llvm/back/archive.rs | 3 +-- src/librustc_codegen_llvm/back/bytecode.rs | 16 ++++++++-------- src/librustc_codegen_llvm/back/lto.rs | 18 +++++++++--------- src/librustc_codegen_llvm/back/write.rs | 6 +++--- 4 files changed, 21 insertions(+), 22 deletions(-) diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index 077c8c31f4a2e..a69d5b7fd9b99 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -282,10 +282,9 @@ impl<'a> ArchiveBuilder<'a> { let ret = if r.into_result().is_err() { let err = llvm::LLVMRustGetLastError(); let msg = if err.is_null() { - "failed to write archive".to_string() + "failed to write archive".into() } else { String::from_utf8_lossy(CStr::from_ptr(err).to_bytes()) - .into_owned() }; Err(io::Error::new(io::ErrorKind::Other, msg)) } else { diff --git a/src/librustc_codegen_llvm/back/bytecode.rs b/src/librustc_codegen_llvm/back/bytecode.rs index 9a3dd9d2f8814..c6cb94a7e3395 100644 --- a/src/librustc_codegen_llvm/back/bytecode.rs +++ b/src/librustc_codegen_llvm/back/bytecode.rs @@ -106,39 +106,39 @@ pub struct DecodedBytecode<'a> { } impl<'a> DecodedBytecode<'a> { - pub fn new(data: &'a [u8]) -> Result, String> { + pub fn new(data: &'a [u8]) -> Result, &'static str> { if !data.starts_with(RLIB_BYTECODE_OBJECT_MAGIC) { - return Err("magic bytecode prefix not found".to_string()) + return Err("magic bytecode prefix not found") } let data = &data[RLIB_BYTECODE_OBJECT_MAGIC.len()..]; if !data.starts_with(&[RLIB_BYTECODE_OBJECT_VERSION, 0, 0, 0]) { - return Err("wrong version prefix found in bytecode".to_string()) + return Err("wrong version prefix found in bytecode") } let data = &data[4..]; if data.len() < 4 { - return Err("bytecode corrupted".to_string()) + return Err("bytecode corrupted") } let identifier_len = unsafe { u32::from_le(ptr::read_unaligned(data.as_ptr() as *const u32)) as usize }; let data = &data[4..]; if data.len() < identifier_len { - return Err("bytecode corrupted".to_string()) + return Err("bytecode corrupted") } let identifier = match str::from_utf8(&data[..identifier_len]) { Ok(s) => s, - Err(_) => return Err("bytecode corrupted".to_string()) + Err(_) => return Err("bytecode corrupted") }; let data = &data[identifier_len..]; if data.len() < 8 { - return Err("bytecode corrupted".to_string()) + return Err("bytecode corrupted") } let bytecode_len = unsafe { u64::from_le(ptr::read_unaligned(data.as_ptr() as *const u64)) as usize }; let data = &data[8..]; if data.len() < bytecode_len { - return Err("bytecode corrupted".to_string()) + return Err("bytecode corrupted") } let encoded_bytecode = &data[..bytecode_len]; diff --git a/src/librustc_codegen_llvm/back/lto.rs b/src/librustc_codegen_llvm/back/lto.rs index cb944e08c8324..5521ddf0e6a38 100644 --- a/src/librustc_codegen_llvm/back/lto.rs +++ b/src/librustc_codegen_llvm/back/lto.rs @@ -296,7 +296,7 @@ fn fat_lto(cgcx: &CodegenContext, let data = bc_decoded.data(); linker.add(&data).map_err(|()| { let msg = format!("failed to load bc of {:?}", name); - write::llvm_err(&diag_handler, msg) + write::llvm_err(&diag_handler, &msg) }) })?; timeline.record(&format!("link {:?}", name)); @@ -490,7 +490,7 @@ fn thin_lto(cgcx: &CodegenContext, symbol_white_list.as_ptr(), symbol_white_list.len() as u32, ).ok_or_else(|| { - write::llvm_err(&diag_handler, "failed to prepare thin LTO context".to_string()) + write::llvm_err(&diag_handler, "failed to prepare thin LTO context") })?; info!("thin LTO data created"); @@ -746,7 +746,7 @@ impl ThinModule { { let diag_handler = cgcx.create_diag_handler(); let tm = (cgcx.tm_factory)().map_err(|e| { - write::llvm_err(&diag_handler, e) + write::llvm_err(&diag_handler, &e) })?; // Right now the implementation we've got only works over serialized @@ -761,7 +761,7 @@ impl ThinModule { self.data().len(), self.shared.module_names[self.idx].as_ptr(), ).ok_or_else(|| { - let msg = "failed to parse bitcode for thin LTO module".to_string(); + let msg = "failed to parse bitcode for thin LTO module"; write::llvm_err(&diag_handler, msg) })? as *const _; let module = ModuleCodegen { @@ -785,7 +785,7 @@ impl ThinModule { let mut cu2 = ptr::null_mut(); llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2); if !cu2.is_null() { - let msg = "multiple source DICompileUnits found".to_string(); + let msg = "multiple source DICompileUnits found"; return Err(write::llvm_err(&diag_handler, msg)) } @@ -806,25 +806,25 @@ impl ThinModule { // You can find some more comments about these functions in the LLVM // bindings we've got (currently `PassWrapper.cpp`) if !llvm::LLVMRustPrepareThinLTORename(self.shared.data.0, llmod) { - let msg = "failed to prepare thin LTO module".to_string(); + let msg = "failed to prepare thin LTO module"; return Err(write::llvm_err(&diag_handler, msg)) } cgcx.save_temp_bitcode(&module, "thin-lto-after-rename"); timeline.record("rename"); if !llvm::LLVMRustPrepareThinLTOResolveWeak(self.shared.data.0, llmod) { - let msg = "failed to prepare thin LTO module".to_string(); + let msg = "failed to prepare thin LTO module"; return Err(write::llvm_err(&diag_handler, msg)) } cgcx.save_temp_bitcode(&module, "thin-lto-after-resolve"); timeline.record("resolve"); if !llvm::LLVMRustPrepareThinLTOInternalize(self.shared.data.0, llmod) { - let msg = "failed to prepare thin LTO module".to_string(); + let msg = "failed to prepare thin LTO module"; return Err(write::llvm_err(&diag_handler, msg)) } cgcx.save_temp_bitcode(&module, "thin-lto-after-internalize"); timeline.record("internalize"); if !llvm::LLVMRustPrepareThinLTOImport(self.shared.data.0, llmod) { - let msg = "failed to prepare thin LTO module".to_string(); + let msg = "failed to prepare thin LTO module"; return Err(write::llvm_err(&diag_handler, msg)) } cgcx.save_temp_bitcode(&module, "thin-lto-after-import"); diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index b55121ca69048..f5c7da138c472 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -90,7 +90,7 @@ pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [ const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc"; -pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError { +pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError { match llvm::last_error() { Some(err) => handler.fatal(&format!("{}: {}", msg, err)), None => handler.fatal(&msg), @@ -109,7 +109,7 @@ pub fn write_output_file( let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type); if result.into_result().is_err() { let msg = format!("could not write output to {}", output.display()); - Err(llvm_err(handler, msg)) + Err(llvm_err(handler, &msg)) } else { Ok(()) } @@ -139,7 +139,7 @@ pub fn create_target_machine( find_features: bool, ) -> &'static mut llvm::TargetMachine { target_machine_factory(sess, find_features)().unwrap_or_else(|err| { - llvm_err(sess.diagnostic(), err).raise() + llvm_err(sess.diagnostic(), &err).raise() }) } From 4286c3c1b0a4eb508483c915120a875966ac27c9 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:46:46 +0200 Subject: [PATCH 03/10] codegen_llvm_back: remove explicit returns --- src/librustc_codegen_llvm/back/archive.rs | 18 +++++++++--------- src/librustc_codegen_llvm/back/link.rs | 3 ++- src/librustc_codegen_llvm/back/rpath.rs | 6 ++++-- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index a69d5b7fd9b99..9f884a0cbe502 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -85,14 +85,14 @@ impl<'a> ArchiveBuilder<'a> { } let archive = self.src_archive.as_ref().unwrap().as_ref().unwrap(); - let ret = archive.iter() - .filter_map(|child| child.ok()) - .filter(is_relevant_child) - .filter_map(|child| child.name()) - .filter(|name| !self.removals.iter().any(|x| x == name)) - .map(|name| name.to_string()) - .collect(); - return ret; + + archive.iter() + .filter_map(|child| child.ok()) + .filter(is_relevant_child) + .filter_map(|child| child.name()) + .filter(|name| !self.removals.iter().any(|x| x == name)) + .map(|name| name.to_owned()) + .collect() } fn src_archive(&mut self) -> Option<&ArchiveRO> { @@ -293,7 +293,7 @@ impl<'a> ArchiveBuilder<'a> { for member in members { llvm::LLVMRustArchiveMemberFree(member); } - return ret + ret } } } diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index b137102659aa3..b575a77a2b5b0 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -340,7 +340,8 @@ fn archive_search_paths(sess: &Session) -> Vec { sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| { search.push(path.to_path_buf()); }); - return search; + + search } fn archive_config<'a>(sess: &'a Session, diff --git a/src/librustc_codegen_llvm/back/rpath.rs b/src/librustc_codegen_llvm/back/rpath.rs index a7772bf55180a..6cee753b4bfb6 100644 --- a/src/librustc_codegen_llvm/back/rpath.rs +++ b/src/librustc_codegen_llvm/back/rpath.rs @@ -59,7 +59,8 @@ fn rpaths_to_flags(rpaths: &[String]) -> Vec { ret.push(format!("-Wl,-rpath,{}", &(*rpath))); } } - return ret; + + ret } fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec { @@ -92,7 +93,8 @@ fn get_rpaths(config: &mut RPathConfig, libs: &[PathBuf]) -> Vec { // Remove duplicates let rpaths = minimize_rpaths(&rpaths); - return rpaths; + + rpaths } fn get_rpaths_relative_to_output(config: &mut RPathConfig, From 3dbb2cc864db144154a5f4c349bcbc017533ee07 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:49:03 +0200 Subject: [PATCH 04/10] codegen_llvm_back: improve common patterns --- src/librustc_codegen_llvm/back/archive.rs | 9 ++----- src/librustc_codegen_llvm/back/link.rs | 31 ++++++++--------------- src/librustc_codegen_llvm/back/lto.rs | 10 ++------ src/librustc_codegen_llvm/back/wasm.rs | 4 +-- src/librustc_codegen_llvm/back/write.rs | 15 +++++------ src/librustc_codegen_utils/linker.rs | 18 +++++-------- 6 files changed, 30 insertions(+), 57 deletions(-) diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index 9f884a0cbe502..daddae42db2be 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -185,13 +185,8 @@ impl<'a> ArchiveBuilder<'a> { /// Combine the provided files, rlibs, and native libraries into a single /// `Archive`. pub fn build(&mut self) { - let kind = match self.llvm_archive_kind() { - Ok(kind) => kind, - Err(kind) => { - self.config.sess.fatal(&format!("Don't know how to build archive of type: {}", - kind)); - } - }; + let kind = self.llvm_archive_kind().unwrap_or_else(|kind| + self.config.sess.fatal(&format!("Don't know how to build archive of type: {}", kind))); if let Err(e) = self.build_with_llvm(kind) { self.config.sess.fatal(&format!("failed to build archive: {}", e)); diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index b575a77a2b5b0..acb0bbe8f6740 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -107,13 +107,10 @@ pub fn get_linker(sess: &Session, linker: &Path, flavor: LinkerFlavor) -> (PathB } pub fn remove(sess: &Session, path: &Path) { - match fs::remove_file(path) { - Ok(..) => {} - Err(e) => { - sess.err(&format!("failed to remove {}: {}", - path.display(), - e)); - } + if let Err(e) = fs::remove_file(path) { + sess.err(&format!("failed to remove {}: {}", + path.display(), + e)); } } @@ -184,7 +181,7 @@ fn preserve_objects_for_their_debuginfo(sess: &Session) -> bool { // the objects as they're losslessly contained inside the archives. let output_linked = sess.crate_types.borrow() .iter() - .any(|x| *x != config::CrateType::Rlib && *x != config::CrateType::Staticlib); + .any(|&x| x != config::CrateType::Rlib && x != config::CrateType::Staticlib); if !output_linked { return false } @@ -289,13 +286,10 @@ fn link_binary_output(sess: &Session, // final destination, with a `fs::rename` call. In order for the rename to // always succeed, the temporary file needs to be on the same filesystem, // which is why we create it inside the output directory specifically. - let metadata_tmpdir = match TempFileBuilder::new() + let metadata_tmpdir = TempFileBuilder::new() .prefix("rmeta") .tempdir_in(out_filename.parent().unwrap()) - { - Ok(tmpdir) => tmpdir, - Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)), - }; + .unwrap_or_else(|err| sess.fatal(&format!("couldn't create a temp dir: {}", err))); let metadata = emit_metadata(sess, codegen_results, &metadata_tmpdir); if let Err(e) = fs::rename(metadata, &out_filename) { sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e)); @@ -303,10 +297,8 @@ fn link_binary_output(sess: &Session, out_filenames.push(out_filename); } - let tmpdir = match TempFileBuilder::new().prefix("rustc").tempdir() { - Ok(tmpdir) => tmpdir, - Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)), - }; + let tmpdir = TempFileBuilder::new().prefix("rustc").tempdir().unwrap_or_else(|err| + sess.fatal(&format!("couldn't create a temp dir: {}", err))); if outputs.outputs.should_codegen() { let out_filename = out_filename(sess, crate_type, outputs, crate_name); @@ -869,9 +861,8 @@ fn link_natively(sess: &Session, sess.opts.debuginfo != DebugInfo::None && !preserve_objects_for_their_debuginfo(sess) { - match Command::new("dsymutil").arg(out_filename).output() { - Ok(..) => {} - Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)), + if let Err(e) = Command::new("dsymutil").arg(out_filename).output() { + sess.fatal(&format!("failed to run dsymutil: {}", e)) } } diff --git a/src/librustc_codegen_llvm/back/lto.rs b/src/librustc_codegen_llvm/back/lto.rs index 5521ddf0e6a38..76faffa25216a 100644 --- a/src/librustc_codegen_llvm/back/lto.rs +++ b/src/librustc_codegen_llvm/back/lto.rs @@ -919,12 +919,6 @@ impl ThinLTOImports { } fn module_name_to_str(c_str: &CStr) -> &str { - match c_str.to_str() { - Ok(s) => s, - Err(e) => { - bug!("Encountered non-utf8 LLVM module name `{}`: {}", - c_str.to_string_lossy(), - e) - } - } + c_str.to_str().unwrap_or_else(|e| + bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)) } diff --git a/src/librustc_codegen_llvm/back/wasm.rs b/src/librustc_codegen_llvm/back/wasm.rs index f37854b7bcae0..7101255173caf 100644 --- a/src/librustc_codegen_llvm/back/wasm.rs +++ b/src/librustc_codegen_llvm/back/wasm.rs @@ -42,7 +42,7 @@ const WASM_EXTERNAL_KIND_GLOBAL: u8 = 3; /// https://github.com/llvm-mirror/llvm/commit/0f32e1365, although support still /// needs to be added, tracked at https://bugs.llvm.org/show_bug.cgi?id=37168 pub fn rewrite_imports(path: &Path, import_map: &FxHashMap) { - if import_map.len() == 0 { + if import_map.is_empty() { return } @@ -127,7 +127,7 @@ impl<'a> Iterator for WasmSections<'a> { type Item = (u8, &'a [u8]); fn next(&mut self) -> Option<(u8, &'a [u8])> { - if self.0.data.len() == 0 { + if self.0.data.is_empty() { return None } diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index f5c7da138c472..9ce1130c77ecc 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -1440,15 +1440,12 @@ fn execute_copy_from_cache_work_item(cgcx: &CodegenContext, module.name, source_file, obj_out.display()); - match link_or_copy(&source_file, &obj_out) { - Ok(_) => { } - Err(err) => { - let diag_handler = cgcx.create_diag_handler(); - diag_handler.err(&format!("unable to copy {} to {}: {}", - source_file.display(), - obj_out.display(), - err)); - } + if let Err(err) = link_or_copy(&source_file, &obj_out) { + let diag_handler = cgcx.create_diag_handler(); + diag_handler.err(&format!("unable to copy {} to {}: {}", + source_file.display(), + obj_out.display(), + err)); } } diff --git a/src/librustc_codegen_utils/linker.rs b/src/librustc_codegen_utils/linker.rs index 501166af90686..8485ccd8f3d94 100644 --- a/src/librustc_codegen_utils/linker.rs +++ b/src/librustc_codegen_utils/linker.rs @@ -343,17 +343,13 @@ impl<'a> Linker for GccLinker<'a> { } fn debuginfo(&mut self) { - match self.sess.opts.debuginfo { - DebugInfo::None => { - // If we are building without debuginfo enabled and we were called with - // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo - // found when linking to get rid of symbols from libstd. - match self.sess.opts.debugging_opts.strip_debuginfo_if_disabled { - Some(true) => { self.linker_arg("-S"); }, - _ => {}, - } - }, - _ => {}, + if let DebugInfo::None = self.sess.opts.debuginfo { + // If we are building without debuginfo enabled and we were called with + // `-Zstrip-debuginfo-if-disabled=yes`, tell the linker to strip any debuginfo + // found when linking to get rid of symbols from libstd. + if let Some(true) = self.sess.opts.debugging_opts.strip_debuginfo_if_disabled { + self.linker_arg("-S"); + } }; } From 0195d9b95f0e96f391ea4ab271be6a9c1cf6b182 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:50:00 +0200 Subject: [PATCH 05/10] codegen_llvm_back: use to_owned instead of to_string with string literals --- src/librustc_codegen_llvm/back/archive.rs | 2 +- src/librustc_codegen_llvm/back/rpath.rs | 4 ++-- src/librustc_codegen_llvm/back/write.rs | 2 +- src/librustc_codegen_utils/linker.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index daddae42db2be..54245a36017ab 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -172,7 +172,7 @@ impl<'a> ArchiveBuilder<'a> { let name = file.file_name().unwrap().to_str().unwrap(); self.additions.push(Addition::File { path: file.to_path_buf(), - name_in_archive: name.to_string(), + name_in_archive: name.to_owned(), }); } diff --git a/src/librustc_codegen_llvm/back/rpath.rs b/src/librustc_codegen_llvm/back/rpath.rs index 6cee753b4bfb6..ee4a9b30a1a85 100644 --- a/src/librustc_codegen_llvm/back/rpath.rs +++ b/src/librustc_codegen_llvm/back/rpath.rs @@ -42,7 +42,7 @@ pub fn get_rpath_flags(config: &mut RPathConfig) -> Vec { // Use DT_RUNPATH instead of DT_RPATH if available if config.linker_is_gnu { - flags.push("-Wl,--enable-new-dtags".to_string()); + flags.push("-Wl,--enable-new-dtags".to_owned()); } flags @@ -169,7 +169,7 @@ fn get_install_prefix_rpath(config: &mut RPathConfig) -> String { let path = (config.get_install_prefix_lib_path)(); let path = env::current_dir().unwrap().join(&path); // FIXME (#9639): This needs to handle non-utf8 paths - path.to_str().expect("non-utf8 component in rpath").to_string() + path.to_str().expect("non-utf8 component in rpath").to_owned() } fn minimize_rpaths(rpaths: &[String]) -> Vec { diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 9ce1130c77ecc..724580c628e13 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -455,7 +455,7 @@ impl<'a> Drop for DiagnosticHandlers<'a> { unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext, msg: &'b str, cookie: c_uint) { - cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string()); + cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned()); } unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, diff --git a/src/librustc_codegen_utils/linker.rs b/src/librustc_codegen_utils/linker.rs index 8485ccd8f3d94..d9a769c4b5f24 100644 --- a/src/librustc_codegen_utils/linker.rs +++ b/src/librustc_codegen_utils/linker.rs @@ -860,7 +860,7 @@ impl<'a> Linker for EmLinker<'a> { let res = encoder.emit_seq(symbols.len(), |encoder| { for (i, sym) in symbols.iter().enumerate() { encoder.emit_seq_elt(i, |encoder| { - encoder.emit_str(&("_".to_string() + sym)) + encoder.emit_str(&("_".to_owned() + sym)) })?; } Ok(()) From ed5802c4d1fe396477ec149ef047223c86e9bb0b Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:50:34 +0200 Subject: [PATCH 06/10] codegen_llvm_back: remove 'static from consts --- src/librustc_codegen_llvm/back/bytecode.rs | 2 +- src/librustc_codegen_llvm/back/write.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc_codegen_llvm/back/bytecode.rs b/src/librustc_codegen_llvm/back/bytecode.rs index c6cb94a7e3395..0b264de18c124 100644 --- a/src/librustc_codegen_llvm/back/bytecode.rs +++ b/src/librustc_codegen_llvm/back/bytecode.rs @@ -42,7 +42,7 @@ use flate2::write::DeflateEncoder; // This is the "magic number" expected at the beginning of a LLVM bytecode // object in an rlib. -pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT"; +pub const RLIB_BYTECODE_OBJECT_MAGIC: &[u8] = b"RUST_OBJECT"; // The version number this compiler will write to bytecode objects in rlibs pub const RLIB_BYTECODE_OBJECT_VERSION: u8 = 2; diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 724580c628e13..8973852caa86b 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -64,7 +64,7 @@ use std::time::Instant; use std::thread; use libc::{c_uint, c_void, c_char, size_t}; -pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [ +pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [ ("pic", llvm::RelocMode::PIC), ("static", llvm::RelocMode::Static), ("default", llvm::RelocMode::Default), @@ -81,7 +81,7 @@ pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[ ("large", llvm::CodeModel::Large), ]; -pub const TLS_MODEL_ARGS : [(&'static str, llvm::ThreadLocalMode); 4] = [ +pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [ ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic), ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic), ("initial-exec", llvm::ThreadLocalMode::InitialExec), From 3968ada0064296f7d4077c9d1f317a3d71514f21 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:51:14 +0200 Subject: [PATCH 07/10] codegen_llvm_back: use mem::replace instead of swap where more concise --- src/librustc_codegen_utils/linker.rs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/librustc_codegen_utils/linker.rs b/src/librustc_codegen_utils/linker.rs index d9a769c4b5f24..ae1d77f152189 100644 --- a/src/librustc_codegen_utils/linker.rs +++ b/src/librustc_codegen_utils/linker.rs @@ -456,9 +456,8 @@ impl<'a> Linker for GccLinker<'a> { fn finalize(&mut self) -> Command { self.hint_dynamic(); // Reset to default before returning the composed command line. - let mut cmd = Command::new(""); - ::std::mem::swap(&mut cmd, &mut self.cmd); - cmd + + ::std::mem::replace(&mut self.cmd, Command::new("")) } fn group_start(&mut self) { @@ -710,9 +709,7 @@ impl<'a> Linker for MsvcLinker<'a> { } fn finalize(&mut self) -> Command { - let mut cmd = Command::new(""); - ::std::mem::swap(&mut cmd, &mut self.cmd); - cmd + ::std::mem::replace(&mut self.cmd, Command::new("")) } // MSVC doesn't need group indicators @@ -880,9 +877,7 @@ impl<'a> Linker for EmLinker<'a> { } fn finalize(&mut self) -> Command { - let mut cmd = Command::new(""); - ::std::mem::swap(&mut cmd, &mut self.cmd); - cmd + ::std::mem::replace(&mut self.cmd, Command::new("")) } // Appears not necessary on Emscripten @@ -1080,9 +1075,7 @@ impl<'a> Linker for WasmLd<'a> { // indicative of bugs, let's prevent them. self.cmd.arg("--fatal-warnings"); - let mut cmd = Command::new(""); - ::std::mem::swap(&mut cmd, &mut self.cmd); - cmd + ::std::mem::replace(&mut self.cmd, Command::new("")) } // Not needed for now with LLD From 4d88914a27317a480dce4de1bf3e8a0c1622472d Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:52:53 +0200 Subject: [PATCH 08/10] codegen_llvm_back: possible minor speedup in logic --- src/librustc_codegen_llvm/back/link.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index acb0bbe8f6740..2a68ab07c5e67 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -265,7 +265,7 @@ pub(crate) fn ignored_for_lto(sess: &Session, info: &CrateInfo, cnum: CrateNum) // crates providing these functions don't participate in LTO (e.g. // no_builtins or compiler builtins crates). !sess.target.target.options.no_builtins && - (info.is_no_builtins.contains(&cnum) || info.compiler_builtins == Some(cnum)) + (info.compiler_builtins == Some(cnum) || info.is_no_builtins.contains(&cnum)) } fn link_binary_output(sess: &Session, From 815a3b6b6926f07aba4eb03d16ca30053c0b55e0 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 6 Oct 2018 11:53:23 +0200 Subject: [PATCH 09/10] codegen_llvm_back: remove a redundant continue --- src/librustc_codegen_llvm/back/link.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index 2a68ab07c5e67..5e12c70753c3e 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -1415,7 +1415,6 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker, for f in archive.src_files() { if f.ends_with(RLIB_BYTECODE_EXTENSION) || f == METADATA_FILENAME { archive.remove_file(&f); - continue } } From 2f99d09ef7b622286d9eedef1366399cdcca4d6d Mon Sep 17 00:00:00 2001 From: ljedrz Date: Mon, 29 Oct 2018 10:19:09 +0100 Subject: [PATCH 10/10] codegen_llvm_back: simplify a conversion to char --- src/librustc_codegen_llvm/back/link.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index 5e12c70753c3e..111637b6aa967 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -806,7 +806,7 @@ fn link_natively(sess: &Session, let mut x = "Non-UTF-8 output: ".to_string(); x.extend(s.iter() .flat_map(|&b| ascii::escape_default(b)) - .map(|b| char::from_u32(b as u32).unwrap())); + .map(char::from)); x }) }