Skip to content

Commit

Permalink
Rollup merge of #95202 - Urgau:check-cfg-perf-well-known-values, r=pe…
Browse files Browse the repository at this point in the history
…trochenkov

Reduce the cost of loading all built-ins targets

This PR started by measuring the exact slowdown of checking of well known conditional values.
Than this PR implemented some technics to reduce the cost of loading all built-ins targets.

cf. #82450 (comment)
  • Loading branch information
Dylan-DPC authored Apr 3, 2022
2 parents 2ad4eb2 + 1a1f5b8 commit 796bc7e
Show file tree
Hide file tree
Showing 226 changed files with 1,337 additions and 1,296 deletions.
8 changes: 6 additions & 2 deletions compiler/rustc_codegen_cranelift/src/driver/aot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,12 @@ pub(crate) fn run_aot(
};

// FIXME handle `-Ctarget-cpu=native`
let target_cpu =
tcx.sess.opts.cg.target_cpu.as_ref().unwrap_or(&tcx.sess.target.cpu).to_owned();
let target_cpu = match tcx.sess.opts.cg.target_cpu {
Some(ref name) => name,
None => tcx.sess.target.cpu.as_ref(),
}
.to_owned();

Box::new((
CodegenResults {
modules,
Expand Down
6 changes: 4 additions & 2 deletions compiler/rustc_codegen_gcc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,10 @@ fn handle_native(name: &str) -> &str {
}

pub fn target_cpu(sess: &Session) -> &str {
let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
handle_native(name)
match sess.opts.cg.target_cpu {
Some(ref name) => handle_native(name),
None => handle_native(sess.target.cpu.as_ref()),
}
}

pub fn target_features(sess: &Session) -> Vec<Symbol> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribu

// The function name varies on platforms.
// See test/CodeGen/mcount.c in clang.
let mcount_name = cx.sess().target.mcount.as_str();
let mcount_name = cx.sess().target.mcount.as_ref();

Some(llvm::CreateAttrStringValue(
cx.llcx,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1452,7 +1452,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> {
}

fn fptoint_sat_broken_in_llvm(&self) -> bool {
match self.tcx.sess.target.arch.as_str() {
match self.tcx.sess.target.arch.as_ref() {
// FIXME - https://bugs.llvm.org/show_bug.cgi?id=50083
"riscv64" => llvm_util::get_version() < (13, 0, 0),
_ => false,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_llvm/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ pub unsafe fn create_module<'ll>(
let mod_name = SmallCStr::new(mod_name);
let llmod = llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx);

let mut target_data_layout = sess.target.data_layout.clone();
let mut target_data_layout = sess.target.data_layout.to_string();
let llvm_version = llvm_util::get_version();
if llvm_version < (13, 0, 0) {
if sess.target.arch == "powerpc64" {
Expand Down Expand Up @@ -859,7 +859,7 @@ impl<'ll> CodegenCx<'ll, '_> {

// This isn't an "LLVM intrinsic", but LLVM's optimization passes
// recognize it like one and we assume it exists in `core::slice::cmp`
match self.sess().target.arch.as_str() {
match self.sess().target.arch.as_ref() {
"avr" | "msp430" => ifn!("memcmp", fn(i8p, i8p, t_isize) -> t_i16),
_ => ifn!("memcmp", fn(i8p, i8p, t_isize) -> t_i32),
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_codegen_llvm/src/intrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,7 +329,7 @@ impl<'ll, 'tcx> IntrinsicCallMethods<'tcx> for Builder<'_, 'll, 'tcx> {
let b_ptr = self.bitcast(b, i8p_ty);
let n = self.const_usize(layout.size().bytes());
let cmp = self.call_intrinsic("memcmp", &[a_ptr, b_ptr, n]);
match self.cx.sess().target.arch.as_str() {
match self.cx.sess().target.arch.as_ref() {
"avr" | "msp430" => self.icmp(IntPredicate::IntEQ, cmp, self.const_i16(0)),
_ => self.icmp(IntPredicate::IntEQ, cmp, self.const_i32(0)),
}
Expand Down
10 changes: 6 additions & 4 deletions compiler/rustc_codegen_llvm/src/llvm_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ unsafe fn configure_llvm(sess: &Session) {
full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
}

let cg_opts = sess.opts.cg.llvm_args.iter();
let tg_opts = sess.target.llvm_args.iter();
let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
let sess_args = cg_opts.chain(tg_opts);

let user_specified_args: FxHashSet<_> =
Expand Down Expand Up @@ -375,8 +375,10 @@ fn handle_native(name: &str) -> &str {
}

pub fn target_cpu(sess: &Session) -> &str {
let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
handle_native(name)
match sess.opts.cg.target_cpu {
Some(ref name) => handle_native(name),
None => handle_native(sess.target.cpu.as_ref()),
}
}

/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
Expand Down
31 changes: 16 additions & 15 deletions compiler/rustc_codegen_ssa/src/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ use std::ffi::OsString;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::lazy::OnceCell;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Output, Stdio};
use std::{ascii, char, env, fmt, fs, io, mem, str};
Expand Down Expand Up @@ -674,11 +675,11 @@ fn link_natively<'a, B: ArchiveBuilder<'a>>(

linker::disable_localization(&mut cmd);

for &(ref k, ref v) in &sess.target.link_env {
cmd.env(k, v);
for &(ref k, ref v) in sess.target.link_env.as_ref() {
cmd.env(k.as_ref(), v.as_ref());
}
for k in &sess.target.link_env_remove {
cmd.env_remove(k);
for k in sess.target.link_env_remove.as_ref() {
cmd.env_remove(k.as_ref());
}

if sess.opts.prints.contains(&PrintRequest::LinkArgs) {
Expand Down Expand Up @@ -1216,7 +1217,7 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {

if let Some(ret) = infer_from(
sess,
sess.target.linker.clone().map(PathBuf::from),
sess.target.linker.as_deref().map(PathBuf::from),
Some(sess.target.linker_flavor),
) {
return ret;
Expand Down Expand Up @@ -1586,7 +1587,7 @@ fn add_post_link_objects(
/// FIXME: Determine where exactly these args need to be inserted.
fn add_pre_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
if let Some(args) = sess.target.pre_link_args.get(&flavor) {
cmd.args(args);
cmd.args(args.iter().map(Deref::deref));
}
cmd.args(&sess.opts.debugging_opts.pre_link_args);
}
Expand All @@ -1602,7 +1603,7 @@ fn add_link_script(cmd: &mut dyn Linker, sess: &Session, tmpdir: &Path, crate_ty
let file_name = ["rustc", &sess.target.llvm_target, "linkfile.ld"].join("-");

let path = tmpdir.join(file_name);
if let Err(e) = fs::write(&path, script) {
if let Err(e) = fs::write(&path, script.as_ref()) {
sess.fatal(&format!("failed to write link script to {}: {}", path.display(), e));
}

Expand Down Expand Up @@ -1634,23 +1635,23 @@ fn add_late_link_args(
});
if any_dynamic_crate {
if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
cmd.args(args);
cmd.args(args.iter().map(Deref::deref));
}
} else {
if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
cmd.args(args);
cmd.args(args.iter().map(Deref::deref));
}
}
if let Some(args) = sess.target.late_link_args.get(&flavor) {
cmd.args(args);
cmd.args(args.iter().map(Deref::deref));
}
}

/// Add arbitrary "post-link" args defined by the target spec.
/// FIXME: Determine where exactly these args need to be inserted.
fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
if let Some(args) = sess.target.post_link_args.get(&flavor) {
cmd.args(args);
cmd.args(args.iter().map(Deref::deref));
}
}

Expand Down Expand Up @@ -1960,8 +1961,8 @@ fn add_order_independent_options(
cmd.arg(&codegen_results.crate_info.target_cpu);
cmd.arg("--cpu-features");
cmd.arg(match &sess.opts.cg.target_feature {
feat if !feat.is_empty() => feat,
_ => &sess.target.options.features,
feat if !feat.is_empty() => feat.as_ref(),
_ => sess.target.options.features.as_ref(),
});
}

Expand Down Expand Up @@ -2478,12 +2479,12 @@ fn add_apple_sdk(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor) {
let os = &sess.target.os;
let llvm_target = &sess.target.llvm_target;
if sess.target.vendor != "apple"
|| !matches!(os.as_str(), "ios" | "tvos")
|| !matches!(os.as_ref(), "ios" | "tvos")
|| flavor != LinkerFlavor::Gcc
{
return;
}
let sdk_name = match (arch.as_str(), os.as_str()) {
let sdk_name = match (arch.as_ref(), os.as_ref()) {
("aarch64", "tvos") => "appletvos",
("x86_64", "tvos") => "appletvsimulator",
("arm", "ios") => "iphoneos",
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_ssa/src/back/linker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ pub fn get_linker<'a>(
if let Some(ref tool) = msvc_tool {
let original_path = tool.path();
if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
let arch = match t.arch.as_str() {
let arch = match t.arch.as_ref() {
"x86_64" => Some("x64"),
"x86" => Some("x86"),
"aarch64" => Some("arm64"),
Expand Down Expand Up @@ -1520,7 +1520,7 @@ impl<'a> L4Bender<'a> {

pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
if let Some(ref exports) = tcx.sess.target.override_export_symbols {
return exports.clone();
return exports.iter().map(ToString::to_string).collect();
}

let mut symbols = Vec::new();
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_codegen_ssa/src/back/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ impl ModuleConfig {
false
),
emit_obj,
bc_cmdline: sess.target.bitcode_llvm_cmdline.clone(),
bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),

verify_llvm_ir: sess.verify_llvm_ir(),
no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
Expand Down Expand Up @@ -1061,7 +1061,7 @@ fn start_executing_work<B: ExtraBackendMethods>(
is_pe_coff: tcx.sess.target.is_like_windows,
target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
target_pointer_width: tcx.sess.target.pointer_width,
target_arch: tcx.sess.target.arch.clone(),
target_arch: tcx.sess.target.arch.to_string(),
debuginfo: tcx.sess.opts.debuginfo,
split_debuginfo: tcx.sess.split_debuginfo(),
split_dwarf_kind: tcx.sess.opts.debugging_opts.split_dwarf_kind,
Expand Down
12 changes: 6 additions & 6 deletions compiler/rustc_metadata/src/locator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,10 +416,10 @@ impl<'a> CrateLocator<'a> {
(&f[rlib_prefix.len()..(f.len() - rlib_suffix.len())], CrateFlavor::Rlib)
} else if f.starts_with(rmeta_prefix) && f.ends_with(rmeta_suffix) {
(&f[rmeta_prefix.len()..(f.len() - rmeta_suffix.len())], CrateFlavor::Rmeta)
} else if f.starts_with(dylib_prefix) && f.ends_with(dylib_suffix) {
} else if f.starts_with(dylib_prefix) && f.ends_with(dylib_suffix.as_ref()) {
(&f[dylib_prefix.len()..(f.len() - dylib_suffix.len())], CrateFlavor::Dylib)
} else {
if f.starts_with(staticlib_prefix) && f.ends_with(staticlib_suffix) {
if f.starts_with(staticlib_prefix) && f.ends_with(staticlib_suffix.as_ref()) {
self.crate_rejections.via_kind.push(CrateMismatch {
path: spf.path.clone(),
got: "static".to_string(),
Expand Down Expand Up @@ -698,8 +698,8 @@ impl<'a> CrateLocator<'a> {
};

if file.starts_with("lib") && (file.ends_with(".rlib") || file.ends_with(".rmeta"))
|| file.starts_with(&self.target.dll_prefix)
&& file.ends_with(&self.target.dll_suffix)
|| file.starts_with(self.target.dll_prefix.as_ref())
&& file.ends_with(self.target.dll_suffix.as_ref())
{
// Make sure there's at most one rlib and at most one dylib.
// Note to take care and match against the non-canonicalized name:
Expand Down Expand Up @@ -733,8 +733,8 @@ impl<'a> CrateLocator<'a> {
crate_name: self.crate_name,
root,
triple: self.triple,
dll_prefix: self.target.dll_prefix.clone(),
dll_suffix: self.target.dll_suffix.clone(),
dll_prefix: self.target.dll_prefix.to_string(),
dll_suffix: self.target.dll_suffix.to_string(),
crate_rejections: self.crate_rejections,
})
}
Expand Down
16 changes: 16 additions & 0 deletions compiler/rustc_serialize/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ use self::JsonEvent::*;
use self::ParserError::*;
use self::ParserState::*;

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::mem::swap;
use std::num::FpCategory as Fp;
Expand Down Expand Up @@ -2196,6 +2197,12 @@ impl ToJson for string::String {
}
}

impl<'a> ToJson for Cow<'a, str> {
fn to_json(&self) -> Json {
Json::String(self.to_string())
}
}

macro_rules! tuple_impl {
// use variables to indicate the arity of the tuple
($($tyvar:ident),* ) => {
Expand Down Expand Up @@ -2240,6 +2247,15 @@ impl<A: ToJson> ToJson for Vec<A> {
}
}

impl<'a, A: ToJson> ToJson for Cow<'a, [A]>
where
[A]: ToOwned,
{
fn to_json(&self) -> Json {
Json::Array(self.iter().map(|elt| elt.to_json()).collect())
}
}

impl<T: ToString, A: ToJson> ToJson for BTreeMap<T, A> {
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -956,7 +956,7 @@ fn default_configuration(sess: &Session) -> CrateConfig {
ret.reserve(7); // the minimum number of insertions
// Target bindings.
ret.insert((sym::target_os, Some(Symbol::intern(os))));
for fam in &sess.target.families {
for fam in sess.target.families.as_ref() {
ret.insert((sym::target_family, Some(Symbol::intern(fam))));
if fam == "windows" {
ret.insert((sym::windows, None));
Expand Down
14 changes: 7 additions & 7 deletions compiler/rustc_target/src/spec/aarch64_apple_darwin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ use crate::spec::{FramePointer, LinkerFlavor, SanitizerSet, Target, TargetOption

pub fn target() -> Target {
let mut base = super::apple_base::opts("macos");
base.cpu = "apple-a14".to_string();
base.cpu = "apple-a14".into();
base.max_atomic_width = Some(128);

// FIXME: The leak sanitizer currently fails the tests, see #88132.
base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::THREAD;

base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-arch".to_string(), "arm64".to_string()]);
base.link_env_remove.extend(super::apple_base::macos_link_env_remove());
base.pre_link_args.insert(LinkerFlavor::Gcc, vec!["-arch".into(), "arm64".into()]);
base.link_env_remove.to_mut().extend(super::apple_base::macos_link_env_remove());

// Clang automatically chooses a more specific target based on
// MACOSX_DEPLOYMENT_TARGET. To enable cross-language LTO to work
// correctly, we do too.
let llvm_target = super::apple_base::macos_llvm_target("arm64");

Target {
llvm_target,
llvm_target: llvm_target.into(),
pointer_width: 64,
data_layout: "e-m:o-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
data_layout: "e-m:o-i64:64-i128:128-n32:64-S128".into(),
arch: "aarch64".into(),
options: TargetOptions {
mcount: "\u{1}mcount".to_string(),
mcount: "\u{1}mcount".into(),
frame_pointer: FramePointer::NonLeaf,
..base
},
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_target/src/spec/aarch64_apple_ios.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@ pub fn target() -> Target {
let llvm_target = super::apple_base::ios_llvm_target(arch);

Target {
llvm_target,
llvm_target: llvm_target.into(),
pointer_width: 64,
data_layout: "e-m:o-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
data_layout: "e-m:o-i64:64-i128:128-n32:64-S128".into(),
arch: "aarch64".into(),
options: TargetOptions {
features: "+neon,+fp-armv8,+apple-a7".to_string(),
features: "+neon,+fp-armv8,+apple-a7".into(),
max_atomic_width: Some(128),
forces_embed_bitcode: true,
frame_pointer: FramePointer::NonLeaf,
Expand All @@ -29,7 +29,7 @@ pub fn target() -> Target {
-target-abi\0\
darwinpcs\0\
-Os\0"
.to_string(),
.into(),
..opts("ios", Arch::Arm64)
},
}
Expand Down
Loading

0 comments on commit 796bc7e

Please sign in to comment.