8000 Cleanup and document `-C relocation-model` by petrochenkov · Pull Request #71490 · rust-lang/rust · GitHub
[go: up one dir, main page]

Skip to content

Cleanup and document -C relocation-model #71490

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 26, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
rustc_target: Stop using "string typing" for relocation models
Introduce `enum RelocModel` instead.
  • Loading branch information
petrochenkov committed Apr 26, 2020
commit fb91e5ed2fe72c6ce38abe0ec2ca47cbeac78d8d
26 changes: 14 additions & 12 deletions src/librustc_codegen_llvm/back/write.rs
8000
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::back::profiling::{
use crate::base;
use crate::common;
use crate::consts;
use crate::context::{get_reloc_model, is_pie_binary};
use crate::context::is_pie_binary;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util;
use crate::type_::Type;
Expand All @@ -25,6 +25,7 @@ use rustc_middle::bug;
use rustc_middle::ty::TyCtxt;
use rustc_session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
use rustc_session::Session;
use rustc_target::spec::RelocModel;

use libc::{c_char, c_int, c_uint, c_void, size_t};
use std::ffi::CString;
Expand All @@ -35,16 +36,6 @@ use std::slice;
use std::str;
use std::sync::Arc;

pub const RELOC_MODEL_ARGS: [(&str, llvm::RelocMode); 7] = [
("pic", llvm::RelocMode::PIC),
("static", llvm::RelocMode::Static),
("default", llvm::RelocMode::Default),
("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
("ropi", llvm::RelocMode::ROPI),
("rwpi", llvm::RelocMode::RWPI),
("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
];

pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
("small", llvm::CodeModel::Small),
("kernel", llvm::CodeModel::Kernel),
Expand Down Expand Up @@ -126,6 +117,17 @@ fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel
}
}

fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocMode {
match relocation_model {
RelocModel::Static => llvm::RelocMode::Static,
RelocModel::Pic => llvm::RelocMode::PIC,
RelocModel::DynamicNoPic => llvm::RelocMode::DynamicNoPic,
RelocModel::Ropi => llvm::RelocMode::ROPI,
RelocModel::Rwpi => llvm::RelocMode::RWPI,
RelocModel::RopiRwpi => llvm::RelocMode::ROPI_RWPI,
}
}

// If find_features is true this won't access `sess.crate_types` by assuming
// that `is_pie_binary` is false. When we discover LLVM target features
// `sess.crate_types` is uninitialized so we cannot access it.
Expand All @@ -134,7 +136,7 @@ pub fn target_machine_factory(
optlvl: config::OptLevel,
find_features: bool,
) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
let reloc_model = get_reloc_model(sess);
let reloc_model = to_llvm_relocation_model(sess.relocation_model());

let (opt_level, _) = to_llvm_opt_settings(optlvl);
let use_softfp = sess.opts.cg.soft_float;
Expand Down
27 changes: 4 additions & 23 deletions src/librustc_codegen_llvm/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use rustc_session::Session;
use rustc_span::source_map::{Span, DUMMY_SP};
use rustc_span::symbol::Symbol;
use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx};
use rustc_target::spec::{HasTargetSpec, Target};
use rustc_target::spec::{HasTargetSpec, RelocModel, Target};

use std::cell::{Cell, RefCell};
use std::ffi::CStr;
Expand Down Expand Up @@ -87,22 +87,6 @@ pub struct CodegenCx<'ll, 'tcx> {
local_gen_sym_counter: Cell<usize>,
}

pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
let reloc_model_arg = match sess.opts.cg.relocation_model {
Some(ref s) => &s[..],
None => &sess.target.target.options.relocation_model[..],
};

match crate::back::write::RELOC_MODEL_ARGS.iter().find(|&&arg| arg.0 == reloc_model_arg) {
Some(x) => x.1,
_ => {
sess.err(&format!("{:?} is not a valid relocation mode", reloc_model_arg));
sess.abort_if_errors();
bug!();
}
}
}

fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
let tls_model_arg = match sess.opts.debugging_opts.tls_model {
Some(ref s) => &s[..],
Expand All @@ -119,12 +103,9 @@ fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
}
}

fn is_any_library(sess: &Session) -> bool {
sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
}

pub fn is_pie_binary(sess: &Session) -> bool {
!is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
sess.relocation_model() == RelocModel::Pic
&& !sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
}

fn strip_function_ptr_alignment(data_layout: String) -> String {
Expand Down 6D40 Expand Up @@ -200,7 +181,7 @@ pub unsafe fn create_module(
let llvm_target = SmallCStr::new(&sess.target.target.llvm_target);
llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());

if get_reloc_model(sess) == llvm::RelocMode::PIC {
if sess.relocation_model() == RelocModel::Pic {
llvm::LLVMRustSetModulePICLevel(llmod);
}

Expand Down
4 changes: 3 additions & 1 deletion src/librustc_codegen_llvm/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,9 @@ impl CodegenBackend for LlvmCodegenBackend {
match req {
PrintRequest::RelocationModels => {
println!("Available relocation models:");
for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
for name in
9E88 &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
{
println!(" {}", name);
}
println!();
Expand Down
1 change: 0 additions & 1 deletion src/librustc_codegen_llvm/llvm/ffi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,6 @@ pub struct SanitizerOptions {
#[derive(Copy, Clone, PartialEq)]
#[repr(C)]
pub enum RelocMode {
Default,
Static,
PIC,
DynamicNoPic,
Expand Down
13 changes: 2 additions & 11 deletions src/librustc_codegen_ssa/back/link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_session::search_paths::PathKind;
/// need out of the shared crate context before we get rid of it.
use rustc_session::{filesearch, Session};
use rustc_span::symbol::Symbol;
use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelroLevel};
use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, RelroLevel};

use super::archive::ArchiveBuilder;
use super::command::Command;
Expand Down Expand Up @@ -1352,7 +1352,7 @@ fn add_position_independent_executable_args(
if sess.target.target.options.position_independent_executables {
let attr_link_args = &*codegen_results.crate_info.link_args;
let mut user_defined_link_args = sess.opts.cg.link_args.iter().chain(attr_link_args);
if is_pic(sess)
if sess.relocation_model() == RelocModel::Pic
&& !sess.crt_static(Some(crate_type))
&& !user_defined_link_args.any(|x| x == "-static")
{
Expand Down Expand Up @@ -1992,12 +1992,3 @@ fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
config::Lto::No | config::Lto::ThinLocal => false,
}
}

fn is_pic(sess: &Session) -> bool {
let reloc_model_arg = match sess.opts.cg.relocation_model {
Some(ref s) => &s[..],
None => &sess.target.target.options.relocation_model[..],
};

reloc_model_arg == "pic"
}
4 changes: 2 additions & 2 deletions src/librustc_interface/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use rustc_session::{build_session, Session};
use rustc_span::edition::{Edition, DEFAULT_EDITION};
use rustc_span::symbol::sym;
use rustc_span::SourceFileHashAlgorithm;
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};
use std::collections::{BTreeMap, BTreeSet};
use std::iter::FromIterator;
use std::path::PathBuf;
Expand Down Expand Up @@ -430,7 +430,7 @@ fn test_codegen_options_tracking_hash() {
tracked!(prefer_dynamic, true);
tracked!(profile_generate, SwitchWithOptPath::Enabled(None));
tracked!(profile_use, Some(PathBuf::from("abc")));
tracked!(relocation_model, Some(String::from("relocation model")));
tracked!(relocation_model, Some(RelocModel::Pic));
tracked!(soft_float, true);
tracked!(target_cpu, Some(String::from("abc")));
tracked!(target_feature, String::from("all the features, all of them"));
Expand Down
7 changes: 2 additions & 10000 ; 5 deletions src/librustc_session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1311,10 +1311,6 @@ fn collect_print_requests(
prints.push(PrintRequest::TargetFeatures);
cg.target_feature = String::new();
}
if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
prints.push(PrintRequest::RelocationModels);
cg.relocation_model = None;
}
if cg.code_model.as_ref().map_or(false, |s| s == "help") {
prints.push(PrintRequest::CodeModels);
cg.code_model = None;
Expand Down Expand Up @@ -2005,7 +2001,7 @@ crate mod dep_tracking {
use crate::utils::NativeLibraryKind;
use rustc_feature::UnstableFeatures;
use rustc_span::edition::Edition;
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelocModel, RelroLevel, TargetTriple};
use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::hash::Hash;
Expand Down Expand Up @@ -2053,6 +2049,7 @@ crate mod dep_tracking {
impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
impl_dep_tracking_hash_via_hash!(Option<RelocModel>);
impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
impl_dep_tracking_hash_via_hash!(Option<lint::Level>);
Expand Down
20 changes: 14 additions & 6 deletions src/librustc_session/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::search_paths::SearchPath;
use crate::utils::NativeLibraryKind;

use rustc_target::spec::TargetTriple;
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};

use rustc_feature::UnstableFeatures;
use rustc_span::edition::Edition;
Expand Down Expand Up @@ -265,14 +265,13 @@ macro_rules! options {
pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
pub const parse_relocation_model: &str =
"one of supported relocation models (`rustc --print relocation-models`)";
}

#[allow(dead_code)]
mod $mod_set {
use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
SymbolManglingVersion, CFGuard, SourceFileHashAlgorithm};
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
use std::path::PathBuf;
use super::*;
use std::str::FromStr;

// Sometimes different options need to build a common structure.
Expand Down Expand Up @@ -598,6 +597,15 @@ macro_rules! options {
true
}

fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
match v.and_then(|s| RelocModel::from_str(s).ok()) {
Some(relocation_model) => *slot = Some(relocation_model),
None if v == Some("default") => *slot = None,
_ => return false,
}
true
}

fn parse_symbol_mangling_version(
slot: &mut SymbolManglingVersion,
v: Option<&str>,
Expand Down Expand Up @@ -697,7 +705,7 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
"compile the program with profiling instrumentation"),
profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
"use the given `.profdata` file for profile-guided optimization"),
relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
"choose the relocation model to use (`rustc --print relocation-models` for details)"),
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
"print remarks for these optimization passes (space separated, or \"all\")"),
Expand Down
6 changes: 5 additions & 1 deletion src/librustc_session/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported
use rustc_span::edition::Edition;
use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
use rustc_span::SourceFileHashAlgorithm;
use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target, TargetTriple};

use std::cell::{self, RefCell};
use std::env;
Expand Down Expand Up @@ -584,6 +584,10 @@ impl Session {
}
}

pub fn relocation_model(&self) -> RelocModel {
self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
}

pub fn must_not_eliminate_frame_pointers(&self) -> bool {
// "mcount" function relies on stack pointer.
// See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_target/spec/aarch64_unknown_none.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
//
// For example, `-C target-cpu=cortex-a53`.

use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions};
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
let opts = TargetOptions {
linker: Some("rust-lld".to_owned()),
features: "+strict-align,+neon,+fp-armv8".to_string(),
executables: true,
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
disable_redzone: true,
linker_is_gnu: true,
max_atomic_width: Some(128),
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_target/spec/aarch64_unknown_none_softfloat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
//
// For example, `-C target-cpu=cortex-a53`.

use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions};
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
let opts = TargetOptions {
linker: Some("rust-lld".to_owned()),
features: "+strict-align,-neon,-fp-armv8".to_string(),
executables: true,
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
disable_redzone: true,
linker_is_gnu: true,
max_atomic_width: Some(128),
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_target/spec/armebv7r_none_eabi.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Targets the Big endian Cortex-R4/R5 processor (ARMv7-R)

use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};

pub fn target() -> TargetResult {
Ok(Target {
Expand All @@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions {
executables: true,
linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort,
max_atomic_width: Some(32),
abi_blacklist: super::arm_base::abi_blacklist(),
Expand Down
5 changes: 3 additions & 2 deletions src/librustc_target/spec/armebv7r_none_eabihf.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Targets the Cortex-R4F/R5F processor (ARMv7-R)

use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
use crate::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel};
use crate::spec::{Target, TargetOptions, TargetResult};

pub fn target() -> TargetResult {
Ok(Target {
Expand All @@ -18,7 +19,7 @@ pub fn target() -> TargetResult {
options: TargetOptions {
executables: true,
linker: Some("rust-lld".to_owned()),
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
panic_strategy: PanicStrategy::Abort,
features: "+vfp3,-d32,-fp16".to_string(),
max_atomic_width: Some(32),
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_target/spec/armv7a_none_eabi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
// - `relocation-model` set to `static`; also no PIE, no relro and no dynamic
// linking. rationale: matches `thumb` targets

use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions};
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
let opts = TargetOptions {
linker: Some("rust-lld".to_owned()),
features: "+v7,+thumb2,+soft-float,-neon,+strict-align".to_string(),
executables: true,
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
disable_redzone: true,
max_atomic_width: Some(64),
panic_strategy: PanicStrategy::Abort,
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_target/spec/armv7a_none_eabihf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
// changes (list in `armv7a_none_eabi.rs`) to bring it closer to the bare-metal
// `thumb` & `aarch64` targets.

use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions};
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};

pub fn target() -> Result<Target, String> {
let opts = TargetOptions {
linker: Some("rust-lld".to_owned()),
features: "+v7,+vfp3,-d32,+thumb2,-neon,+strict-align".to_string(),
executables: true,
relocation_model: "static".to_string(),
relocation_model: RelocModel::Static,
disable_redzone: true,
max_atomic_width: Some(64),
panic_strategy: PanicStrategy::Abort,
Expand Down
Loading
0