Skip to content

Commit 7106800

Browse files
committed
Auto merge of rust-lang#123656 - lqd:linker-features, r=petrochenkov
Linker flavors next steps: linker features This is my understanding of the first step towards `@petrochenkov's` vision for the future of linker flavors, described in rust-lang#119906 (comment) and the discussion that followed. To summarize: having `Cc` and `Lld` embedded in linker flavors creates tension about naming, and a combinatorial explosion of flavors for each new linker feature we'd want to use. Linker features are an extension mechanism that is complementary to principal flavors, with benefits described in rust-lang#119906. The most immediate use of this flag would be to turn self-contained linking on and off via features instead of flavors. For example, `-Clinker-features=+/-lld` would toggle using lld instead of selecting a precise flavor, and would be "generic" and work cross-platform (whereas linker flavors are currently more tied to targets). Under this scheme, MCP510 is expected to be `-Clink-self-contained=+linker -Zlinker-features=+lld -Zunstable-options` (though for the time being, the original flags using lld-cc flavors still work). I purposefully didn't add or document CLI support for `+/-cc`, as it would be a noop right now. I only expect that we'd initially want to stabilize `+/-lld` to begin with. r? `@petrochenkov` You had requested that minimal churn would be done to the 230 target specs and this does none yet: the linker features are inferred from the flavor since they're currently isomorphic. We of course expect this to change sooner rather than later. In the future, we can allow targets to define linker features independently from their flavor, and remove the cc and lld components from the flavors to use the features instead, this actually doesn't need to block stabilization, as we discussed. (Best reviewed per commit)
2 parents 6eaa7fb + dee834b commit 7106800

File tree

6 files changed

+223
-27
lines changed

6 files changed

+223
-27
lines changed

compiler/rustc_codegen_ssa/src/back/link.rs

+46-25
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc_metadata::fs::{copy_to_stdout, emit_wrapper_file, METADATA_FILENAME};
1111
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
1212
use rustc_middle::middle::dependency_format::Linkage;
1313
use rustc_middle::middle::exported_symbols::SymbolExportKind;
14+
use rustc_session::config::LinkerFeaturesCli;
1415
use rustc_session::config::{self, CFGuard, CrateType, DebugInfo, OutFileName, Strip};
1516
use rustc_session::config::{OutputFilenames, OutputType, PrintKind, SplitDwarfKind};
1617
use rustc_session::cstore::DllImport;
@@ -22,10 +23,10 @@ use rustc_session::utils::NativeLibKind;
2223
use rustc_session::{filesearch, Session};
2324
use rustc_span::symbol::Symbol;
2425
use rustc_target::spec::crt_objects::CrtObjects;
25-
use rustc_target::spec::LinkSelfContainedComponents;
2626
use rustc_target::spec::LinkSelfContainedDefault;
2727
use rustc_target::spec::LinkerFlavorCli;
2828
use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld, PanicStrategy};
29+
use rustc_target::spec::{LinkSelfContainedComponents, LinkerFeatures};
2930
use rustc_target::spec::{RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo};
3031

3132
use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
@@ -76,8 +77,8 @@ pub fn ensure_removed(dcx: &DiagCtxt, path: &Path) {
7677

7778
/// Performs the linkage portion of the compilation phase. This will generate all
7879
/// of the requested outputs for this compilation session.
79-
pub fn link_binary<'a>(
80-
sess: &'a Session,
80+
pub fn link_binary(
81+
sess: &Session,
8182
archive_builder_builder: &dyn ArchiveBuilderBuilder,
8283
codegen_results: &CodegenResults,
8384
outputs: &OutputFilenames,
@@ -465,9 +466,9 @@ fn link_rlib<'a>(
465466
/// then the CodegenResults value contains one NativeLib instance for each block. However, the
466467
/// linker appears to expect only a single import library for each library used, so we need to
467468
/// collate the symbols together by library name before generating the import libraries.
468-
fn collate_raw_dylibs<'a, 'b>(
469-
sess: &'a Session,
470-
used_libraries: impl IntoIterator<Item = &'b NativeLib>,
469+
fn collate_raw_dylibs<'a>(
470+
sess: &Session,
471+
used_libraries: impl IntoIterator<Item = &'a NativeLib>,
471472
) -> Result<Vec<(String, Vec<DllImport>)>, ErrorGuaranteed> {
472473
// Use index maps to preserve original order of imports and libraries.
473474
let mut dylib_table = FxIndexMap::<String, FxIndexMap<Symbol, &DllImport>>::default();
@@ -514,8 +515,8 @@ fn collate_raw_dylibs<'a, 'b>(
514515
///
515516
/// There's no need to include metadata in a static archive, so ensure to not link in the metadata
516517
/// object file (and also don't prepare the archive with a metadata file).
517-
fn link_staticlib<'a>(
518-
sess: &'a Session,
518+
fn link_staticlib(
519+
sess: &Session,
519520
archive_builder_builder: &dyn ArchiveBuilderBuilder,
520521
codegen_results: &CodegenResults,
521522
out_filename: &Path,
@@ -627,11 +628,7 @@ fn link_staticlib<'a>(
627628

628629
/// Use `thorin` (rust implementation of a dwarf packaging utility) to link DWARF objects into a
629630
/// DWARF package.
630-
fn link_dwarf_object<'a>(
631-
sess: &'a Session,
632-
cg_results: &CodegenResults,
633-
executable_out_filename: &Path,
634-
) {
631+
fn link_dwarf_object(sess: &Session, cg_results: &CodegenResults, executable_out_filename: &Path) {
635632
let mut dwp_out_filename = executable_out_filename.to_path_buf().into_os_string();
636633
dwp_out_filename.push(".dwp");
637634
debug!(?dwp_out_filename, ?executable_out_filename);
@@ -735,8 +732,8 @@ fn link_dwarf_object<'a>(
735732
///
736733
/// This will invoke the system linker/cc to create the resulting file. This links to all upstream
737734
/// files as well.
738-
fn link_natively<'a>(
739-
sess: &'a Session,
735+
fn link_natively(
736+
sess: &Session,
740737
archive_builder_builder: &dyn ArchiveBuilderBuilder,
741738
crate_type: CrateType,
742739
out_filename: &Path,
@@ -1100,8 +1097,8 @@ fn link_natively<'a>(
11001097
Ok(())
11011098
}
11021099

1103-
fn strip_symbols_with_external_utility<'a>(
1104-
sess: &'a Session,
1100+
fn strip_symbols_with_external_utility(
1101+
sess: &Session,
11051102
util: &str,
11061103
out_filename: &Path,
11071104
option: Option<&str>,
@@ -1338,7 +1335,9 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
13381335
sess: &Session,
13391336
linker: Option<PathBuf>,
13401337
flavor: Option<LinkerFlavor>,
1338+
features: LinkerFeaturesCli,
13411339
) -> Option<(PathBuf, LinkerFlavor)> {
1340+
let flavor = flavor.map(|flavor| adjust_flavor_to_features(flavor, features));
13421341
match (linker, flavor) {
13431342
(Some(linker), Some(flavor)) => Some((linker, flavor)),
13441343
// only the linker flavor is known; use the default linker for the selected flavor
@@ -1386,12 +1385,33 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
13861385
sess.dcx().emit_fatal(errors::LinkerFileStem);
13871386
});
13881387
let flavor = sess.target.linker_flavor.with_linker_hints(stem);
1388+
let flavor = adjust_flavor_to_features(flavor, features);
13891389
Some((linker, flavor))
13901390
}
13911391
(None, None) => None,
13921392
}
13931393
}
13941394

1395+
// While linker flavors and linker features are isomorphic (and thus targets don't need to
1396+
// define features separately), we use the flavor as the root piece of data and have the
1397+
// linker-features CLI flag influence *that*, so that downstream code does not have to check for
1398+
// both yet.
1399+
fn adjust_flavor_to_features(
1400+
flavor: LinkerFlavor,
1401+
features: LinkerFeaturesCli,
1402+
) -> LinkerFlavor {
1403+
// Note: a linker feature cannot be both enabled and disabled on the CLI.
1404+
if features.enabled.contains(LinkerFeatures::LLD) {
1405+
flavor.with_lld_enabled()
1406+
} else if features.disabled.contains(LinkerFeatures::LLD) {
1407+
flavor.with_lld_disabled()
1408+
} else {
1409+
flavor
1410+
}
1411+
}
1412+
1413+
let features = sess.opts.unstable_opts.linker_features;
1414+
13951415
// linker and linker flavor specified via command line have precedence over what the target
13961416
// specification specifies
13971417
let linker_flavor = match sess.opts.cg.linker_flavor {
@@ -1405,14 +1425,15 @@ pub fn linker_and_flavor(sess: &Session) -> (PathBuf, LinkerFlavor) {
14051425
.linker_flavor
14061426
.map(|flavor| sess.target.linker_flavor.with_cli_hints(flavor)),
14071427
};
1408-
if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor) {
1428+
if let Some(ret) = infer_from(sess, sess.opts.cg.linker.clone(), linker_flavor, features) {
14091429
return ret;
14101430
}
14111431

14121432
if let Some(ret) = infer_from(
14131433
sess,
14141434
sess.target.linker.as_deref().map(PathBuf::from),
14151435
Some(sess.target.linker_flavor),
1436+
features,
14161437
) {
14171438
return ret;
14181439
}
@@ -2105,10 +2126,10 @@ fn add_rpath_args(
21052126
/// to the linking process as a whole.
21062127
/// Order-independent options may still override each other in order-dependent fashion,
21072128
/// e.g `--foo=yes --foo=no` may be equivalent to `--foo=no`.
2108-
fn linker_with_args<'a>(
2129+
fn linker_with_args(
21092130
path: &Path,
21102131
flavor: LinkerFlavor,
2111-
sess: &'a Session,
2132+
sess: &Session,
21122133
archive_builder_builder: &dyn ArchiveBuilderBuilder,
21132134
crate_type: CrateType,
21142135
tmpdir: &Path,
@@ -2640,9 +2661,9 @@ fn add_local_native_libraries(
26402661
);
26412662
}
26422663

2643-
fn add_upstream_rust_crates<'a>(
2664+
fn add_upstream_rust_crates(
26442665
cmd: &mut dyn Linker,
2645-
sess: &'a Session,
2666+
sess: &Session,
26462667
archive_builder_builder: &dyn ArchiveBuilderBuilder,
26472668
codegen_results: &CodegenResults,
26482669
crate_type: CrateType,
@@ -2779,7 +2800,7 @@ fn add_upstream_native_libraries(
27792800
// file generated by the MSVC linker. See https://github.com/rust-lang/rust/issues/112586.
27802801
//
27812802
// The returned path will always have `fix_windows_verbatim_for_gcc()` applied to it.
2782-
fn rehome_sysroot_lib_dir<'a>(sess: &'a Session, lib_dir: &Path) -> PathBuf {
2803+
fn rehome_sysroot_lib_dir(sess: &Session, lib_dir: &Path) -> PathBuf {
27832804
let sysroot_lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
27842805
let canonical_sysroot_lib_path =
27852806
{ try_canonicalize(&sysroot_lib_path).unwrap_or_else(|_| sysroot_lib_path.clone()) };
@@ -2812,9 +2833,9 @@ fn rehome_sysroot_lib_dir<'a>(sess: &'a Session, lib_dir: &Path) -> PathBuf {
28122833
// Note, however, that if we're not doing LTO we can just pass the rlib
28132834
// blindly to the linker (fast) because it's fine if it's not actually
28142835
// included as we're at the end of the dependency chain.
2815-
fn add_static_crate<'a>(
2836+
fn add_static_crate(
28162837
cmd: &mut dyn Linker,
2817-
sess: &'a Session,
2838+
sess: &Session,
28182839
archive_builder_builder: &dyn ArchiveBuilderBuilder,
28192840
codegen_results: &CodegenResults,
28202841
tmpdir: &Path,

compiler/rustc_session/src/config.rs

+43-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use rustc_feature::UnstableFeatures;
1818
use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION};
1919
use rustc_span::source_map::FilePathMapping;
2020
use rustc_span::{FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm};
21-
use rustc_target::spec::LinkSelfContainedComponents;
21+
use rustc_target::spec::{LinkSelfContainedComponents, LinkerFeatures};
2222
use rustc_target::spec::{SplitDebuginfo, Target, TargetTriple};
2323
use std::collections::btree_map::{
2424
Iter as BTreeMapIter, Keys as BTreeMapKeysIter, Values as BTreeMapValuesIter,
@@ -292,6 +292,48 @@ impl LinkSelfContained {
292292
}
293293
}
294294

295+
/// The different values that `-Z linker-features` can take on the CLI: a list of individually
296+
/// enabled or disabled features used during linking.
297+
///
298+
/// There is no need to enable or disable them in bulk. Each feature is fine-grained, and can be
299+
/// used to turn `LinkerFeatures` on or off, without needing to change the linker flavor:
300+
/// - using the system lld, or the self-contained `rust-lld` linker
301+
/// - using a C/C++ compiler to drive the linker (not yet exposed on the CLI)
302+
/// - etc.
303+
#[derive(Default, Copy, Clone, PartialEq, Debug)]
304+
pub struct LinkerFeaturesCli {
305+
/// The linker features that are enabled on the CLI, using the `+feature` syntax.
306+
pub enabled: LinkerFeatures,
307+
308+
/// The linker features that are disabled on the CLI, using the `-feature` syntax.
309+
pub disabled: LinkerFeatures,
310+
}
311+
312+
impl LinkerFeaturesCli {
313+
/// Accumulates an enabled or disabled feature as specified on the CLI, if possible.
314+
/// For example: `+lld`, and `-lld`.
315+
pub(crate) fn handle_cli_feature(&mut self, feature: &str) -> Option<()> {
316+
// Duplicate flags are reduced as we go, the last occurrence wins:
317+
// `+feature,-feature,+feature` only enables the feature, and does not record it as both
318+
// enabled and disabled on the CLI.
319+
// We also only expose `+/-lld` at the moment, as it's currenty the only implemented linker
320+
// feature and toggling `LinkerFeatures::CC` would be a noop.
321+
match feature {
322+
"+lld" => {
323+
self.enabled.insert(LinkerFeatures::LLD);
324+
self.disabled.remove(LinkerFeatures::LLD);
325+
Some(())
326+
}
327+
"-lld" => {
328+
self.disabled.insert(LinkerFeatures::LLD);
329+
self.enabled.remove(LinkerFeatures::LLD);
330+
Some(())
331+
}
332+
_ => None,
333+
}
334+
}
335+
}
336+
295337
/// Used with `-Z assert-incr-state`.
296338
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
297339
pub enum IncrementalStateAssertion {

compiler/rustc_session/src/options.rs

+20
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,8 @@ mod desc {
426426
"one of supported split dwarf modes (`split` or `single`)";
427427
pub const parse_link_self_contained: &str = "one of: `y`, `yes`, `on`, `n`, `no`, `off`, or a list of enabled (`+` prefix) and disabled (`-` prefix) \
428428
components: `crto`, `libc`, `unwind`, `linker`, `sanitizers`, `mingw`";
429+
pub const parse_linker_features: &str =
430+
"a list of enabled (`+` prefix) and disabled (`-` prefix) features: `lld`";
429431
pub const parse_polonius: &str = "either no value or `legacy` (the default), or `next`";
430432
pub const parse_stack_protector: &str =
431433
"one of (`none` (default), `basic`, `strong`, or `all`)";
@@ -1269,6 +1271,22 @@ mod parse {
12691271
true
12701272
}
12711273

1274+
/// Parse a comma-separated list of enabled and disabled linker features.
1275+
pub(crate) fn parse_linker_features(slot: &mut LinkerFeaturesCli, v: Option<&str>) -> bool {
1276+
match v {
1277+
Some(s) => {
1278+
for feature in s.split(',') {
1279+
if slot.handle_cli_feature(feature).is_none() {
1280+
return false;
1281+
}
1282+
}
1283+
1284+
true
1285+
}
1286+
None => false,
1287+
}
1288+
}
1289+
12721290
pub(crate) fn parse_wasi_exec_model(slot: &mut Option<WasiExecModel>, v: Option<&str>) -> bool {
12731291
match v {
12741292
Some("command") => *slot = Some(WasiExecModel::Command),
@@ -1721,6 +1739,8 @@ options! {
17211739
"link native libraries in the linker invocation (default: yes)"),
17221740
link_only: bool = (false, parse_bool, [TRACKED],
17231741
"link the `.rlink` file generated by `-Z no-link` (default: no)"),
1742+
linker_features: LinkerFeaturesCli = (LinkerFeaturesCli::default(), parse_linker_features, [UNTRACKED],
1743+
"a comma-separated list of linker features to enable (+) or disable (-): `lld`"),
17241744
lint_mir: bool = (false, parse_bool, [UNTRACKED],
17251745
"lint MIR before and after each transformation"),
17261746
llvm_module_flag: Vec<(String, u32, String)> = (Vec::new(), parse_llvm_module_flag, [TRACKED],

compiler/rustc_target/src/spec/mod.rs

+74
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,28 @@ impl LinkerFlavor {
448448
| LinkerFlavor::Ptx => false,
449449
}
450450
}
451+
452+
/// For flavors with an `Lld` component, ensure it's enabled. Otherwise, returns the given
453+
/// flavor unmodified.
454+
pub fn with_lld_enabled(self) -> LinkerFlavor {
455+
match self {
456+
LinkerFlavor::Gnu(cc, Lld::No) => LinkerFlavor::Gnu(cc, Lld::Yes),
457+
LinkerFlavor::Darwin(cc, Lld::No) => LinkerFlavor::Darwin(cc, Lld::Yes),
458+
LinkerFlavor::Msvc(Lld::No) => LinkerFlavor::Msvc(Lld::Yes),
459+
_ => self,
460+
}
461+
}
462+
463+
/// For flavors with an `Lld` component, ensure it's disabled. Otherwise, returns the given
464+
/// flavor unmodified.
465+
pub fn with_lld_disabled(self) -> LinkerFlavor {
466+
match self {
467+
LinkerFlavor::Gnu(cc, Lld::Yes) => LinkerFlavor::Gnu(cc, Lld::No),
468+
LinkerFlavor::Darwin(cc, Lld::Yes) => LinkerFlavor::Darwin(cc, Lld::No),
469+
LinkerFlavor::Msvc(Lld::Yes) => LinkerFlavor::Msvc(Lld::No),
470+
_ => self,
471+
}
472+
}
451473
}
452474

453475
macro_rules! linker_flavor_cli_impls {
@@ -698,6 +720,58 @@ impl ToJson for LinkSelfContainedComponents {
698720
}
699721
}
700722

723+
bitflags::bitflags! {
724+
/// The `-Z linker-features` components that can individually be enabled or disabled.
725+
///
726+
/// They are feature flags intended to be a more flexible mechanism than linker flavors, and
727+
/// also to prevent a combinatorial explosion of flavors whenever a new linker feature is
728+
/// required. These flags are "generic", in the sense that they can work on multiple targets on
729+
/// the CLI. Otherwise, one would have to select different linkers flavors for each target.
730+
///
731+
/// Here are some examples of the advantages they offer:
732+
/// - default feature sets for principal flavors, or for specific targets.
733+
/// - flavor-specific features: for example, clang offers automatic cross-linking with
734+
/// `--target`, which gcc-style compilers don't support. The *flavor* is still a C/C++
735+
/// compiler, and we don't need to multiply the number of flavors for this use-case. Instead,
736+
/// we can have a single `+target` feature.
737+
/// - umbrella features: for example if clang accumulates more features in the future than just
738+
/// the `+target` above. That could be modeled as `+clang`.
739+
/// - niche features for resolving specific issues: for example, on Apple targets the linker
740+
/// flag implementing the `as-needed` native link modifier (#99424) is only possible on
741+
/// sufficiently recent linker versions.
742+
/// - still allows for discovery and automation, for example via feature detection. This can be
743+
/// useful in exotic environments/build systems.
744+
#[derive(Clone, Copy, PartialEq, Eq, Default)]
745+
pub struct LinkerFeatures: u8 {
746+
/// Invoke the linker via a C/C++ compiler (e.g. on most unix targets).
747+
const CC = 1 << 0;
748+
/// Use the lld linker, either the system lld or the self-contained linker `rust-lld`.
749+
const LLD = 1 << 1;
750+
}
751+
}
752+
rustc_data_structures::external_bitflags_debug! { LinkerFeatures }
753+
754+
impl LinkerFeatures {
755+
/// Parses a single `-Z linker-features` well-known feature, not a set of flags.
756+
pub fn from_str(s: &str) -> Option<LinkerFeatures> {
757+
Some(match s {
758+
"cc" => LinkerFeatures::CC,
759+
"lld" => LinkerFeatures::LLD,
760+
_ => return None,
761+
})
762+
}
763+
764+
/// Returns whether the `lld` linker feature is enabled.
765+
pub fn is_lld_enabled(self) -> bool {
766+
self.contains(LinkerFeatures::LLD)
767+
}
768+
769+
/// Returns whether the `cc` linker feature is enabled.
770+
pub fn is_cc_enabled(self) -> bool {
771+
self.contains(LinkerFeatures::CC)
772+
}
773+
}
774+
701775
#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)]
702776
pub enum PanicStrategy {
703777
Unwind,

0 commit comments

Comments
 (0)