Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 13 additions & 0 deletions compiler/rustc_codegen_llvm/src/declare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,19 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
instance: Option<Instance<'tcx>>,
) -> Value<'ll> {
debug!("declare_rust_fn(name={:?}, fn_abi={:?})", name, fn_abi);
// Some calling conventions (such as fastcall and vectorcall) decorate
// symbols with the argument byte count. Use rustc's original argument
// layouts and prefix the decorated name with `\x01` so LLVM does not
// decorate it a second time.
let decorated_name = rustc_codegen_ssa::common::windows_calling_convention_name(
&self.tcx.sess.target,
fn_abi.conv,
name,
&fn_abi.args,
)
.map(|name| format!("\x01{name}"));

let name = decorated_name.as_deref().unwrap_or(name);

// Function addresses in Rust are never significant, allowing functions to
// be merged.
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_codegen_ssa/src/back/lto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_session::config::Lto;
use rustc_structures::CrateType;
use tracing::info;

use crate::back::symbol_export::{self, allocator_shim_symbols, symbol_name_for_instance_in_crate};
use crate::back::symbol_export::{self, allocator_shim_symbols};
use crate::back::write::CodegenContext;
use crate::base::allocator_kind_for_codegen;
use crate::diagnostics::{DynamicLinkingWithLTO, LtoDisallowed, LtoDylib, LtoProcMacro};
Expand Down Expand Up @@ -104,11 +104,11 @@ pub(crate) fn exported_symbols_for_lto(
tcx.exported_non_generic_symbols(cnum)
.iter()
.chain(tcx.exported_generic_symbols(cnum))
.filter_map(|&(s, info): &(ExportedSymbol<'_>, SymbolExportInfo)| {
.flat_map(|&(s, info): &(ExportedSymbol<'_>, SymbolExportInfo)| {
if info.level.is_below_threshold(export_threshold) || info.used {
Some(symbol_name_for_instance_in_crate(tcx, s, cnum))
symbol_export::symbol_names_for_lto(tcx, s, cnum)
} else {
None
vec![]
}
})
.collect::<Vec<_>>()
Expand Down
117 changes: 96 additions & 21 deletions compiler/rustc_codegen_ssa/src/back/symbol_export.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::hash_map::Entry::*;

use object::pe;
use rustc_abi::{CanonAbi, X86Call};
use rustc_abi::{CanonAbi, ExternAbi};
use rustc_ast::expand::allocator::{AllocatorKind, NO_ALLOC_SHIM_IS_UNSTABLE, global_fn_name};
use rustc_crate_store::CrateDepKind;
use rustc_data_structures::fx::FxHashSet;
Expand Down Expand Up @@ -758,9 +758,74 @@ fn calling_convention_for_symbol<'tcx>(
.unwrap_or((CanonAbi::Rust, &[]))
}

/// Whether symbol decoration might require computing the full FnAbi.
fn needs_calling_convention_decoration<'tcx>(
tcx: TyCtxt<'tcx>,
symbol: ExportedSymbol<'tcx>,
) -> bool {
let target = &tcx.sess.target;

if !matches!(target.arch, Arch::X86 | Arch::X86_64) {
return false;
}

let def_id = match symbol {
ExportedSymbol::NonGeneric(def_id) | ExportedSymbol::Generic(def_id, _) => def_id,
_ => return false,
};

if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
return false;
}

let sig = tcx.fn_sig(def_id).skip_binder();

match target.arch {
Arch::X86 => match sig.abi() {
ExternAbi::Vectorcall { .. } => true,
ExternAbi::Fastcall { .. } | ExternAbi::Stdcall { .. } => target.is_like_windows,
ExternAbi::System { .. } => target.is_like_windows && !sig.c_variadic(),
_ => false,
},
Arch::X86_64 => matches!(sig.abi(), ExternAbi::Vectorcall { .. }),
_ => false,
}
}

/// Names used to preserve an exported symbol during LTO.
///
/// The restriction pass matches LLVM IR names, which retain the `\x01`
/// marker for explicitly decorated symbols. ThinLTO GUIDs instead use
/// the identifier without that marker, so preserve both spellings.
pub(crate) fn symbol_names_for_lto<'tcx>(
tcx: TyCtxt<'tcx>,
symbol: ExportedSymbol<'tcx>,
instantiating_crate: CrateNum,
) -> Vec<String> {
let name = symbol_name_for_instance_in_crate(tcx, symbol, instantiating_crate);
// ThinLTO GUIDs omit the LLVM marker for explicitly named symbols.
if let Some(stripped) = name.strip_prefix('\x01') {
return vec![name.clone(), stripped.to_owned()];
}

if !needs_calling_convention_decoration(tcx, symbol) {
return vec![name];
}

let (callconv, args) = calling_convention_for_symbol(tcx, symbol);

if let Some(decorated) =
crate::common::windows_calling_convention_name(&tcx.sess.target, callconv, &name, args)
{
vec![format!("\x01{decorated}"), decorated]
} else {
vec![name]
}
}
/// This is the symbol name of the given instance as seen by the linker.
///
/// On 32-bit Windows symbols are decorated according to their calling conventions.
/// On Windows, symbols are decorated according to their calling conventions.
/// Vectorcall symbols are also decorated on non-Windows targets.
pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
tcx: TyCtxt<'tcx>,
symbol: ExportedSymbol<'tcx>,
Expand All @@ -777,8 +842,19 @@ pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(

let target = &tcx.sess.target;
if !target.is_like_windows {
if !needs_calling_convention_decoration(tcx, symbol) {
return undecorated;
}

let (callconv, args) = calling_convention_for_symbol(tcx, symbol);
if let Some(name) =
crate::common::windows_calling_convention_name(target, callconv, &undecorated, args)
{
return name;
}

// Mach-O has a global "_" suffix and `object` crate will handle it.
// ELF does not have any symbol decorations.
// Other calling conventions do not need decoration here.
return undecorated;
}

Expand All @@ -791,27 +867,26 @@ pub(crate) fn linking_symbol_name_for_instance_in_crate<'tcx>(
_ => return undecorated,
};

// LLVM treats names beginning with '\x01' as already mangled and strips that prefix.
// Names beginning with '?' are left undecorated by LLVM; the prefix is kept.
if let Some(name) = undecorated.strip_prefix('\x01') {
return name.to_string();
}
if undecorated.starts_with('?') {
return undecorated;
}
let (callconv, args) = calling_convention_for_symbol(tcx, symbol);

// Decorate symbols with prefixes, suffixes and total number of bytes of arguments.
// Reference: https://docs.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170
let (prefix, suffix) = match callconv {
CanonAbi::X86(X86Call::Fastcall) => ("@", "@"),
CanonAbi::X86(X86Call::Stdcall) => ("_", "@"),
CanonAbi::X86(X86Call::Vectorcall) => ("", "@@"),
_ => {
if let Some(prefix) = prefix {
undecorated.insert(0, prefix);
}
return undecorated;
}
};
if let Some(name) =
crate::common::windows_calling_convention_name(target, callconv, &undecorated, args)
{
return name;
}

let args_in_bytes: u64 = args
.iter()
.map(|abi| abi.layout.size.bytes().next_multiple_of(target.pointer_width as u64 / 8))
.sum();
format!("{prefix}{undecorated}{suffix}{args_in_bytes}")
if let Some(prefix) = prefix {
undecorated.insert(0, prefix);
}
undecorated
}

pub(crate) fn exporting_symbol_name_for_instance_in_crate<'tcx>(
Expand Down
55 changes: 53 additions & 2 deletions compiler/rustc_codegen_ssa/src/common.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#![allow(non_camel_case_types)]

use rustc_abi::{CanonAbi, X86Call};
use rustc_attr_ir::PeImportNameType;
use rustc_attr_ir::lang_items::LangItem;
use rustc_crate_store::{DllCallingConvention, DllImport, DllImportSymbolType};
use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar};
use rustc_middle::ty::layout::TyAndLayout;
use rustc_middle::ty::{self, Instance, ScalarInt, TyCtxt};
use rustc_middle::ty::{self, Instance, ScalarInt, Ty, TyCtxt};
use rustc_span::{Span, bug, span_bug};
use rustc_target::spec::{CfgAbi, Env, Os, Target};
use rustc_target::callconv::ArgAbi;
use rustc_target::spec::{Arch, CfgAbi, Env, Os, Target};

use crate::traits::*;

Expand Down Expand Up @@ -174,6 +176,55 @@ pub fn is_using_dlltool(target: &Target) -> bool {
target.os == Os::Windows && target.env == Env::Gnu && target.cfg_abi == CfgAbi::Unspecified
}

/// Computes the total argument size used for Windows calling-convention
/// symbol decoration. Each argument is rounded up to the pointer width.
fn windows_abi_argument_byte_sum<'tcx>(args: &[ArgAbi<'tcx, Ty<'tcx>>], target: &Target) -> u64 {
let pointer_bytes = target.pointer_width as u64 / 8;

args.iter().map(|arg| arg.layout.size.bytes().next_multiple_of(pointer_bytes)).sum()
}

/// Computes the linker-visible decorated symbol name for supported Windows
/// calling conventions using the original `FnAbi` argument layouts.
/// Vectorcall is also decorated on non-Windows targets.
///
/// The byte count is computed before backend-specific argument lowering,
/// which may replace indirectly passed arguments with pointers.
///
/// For example, on 32-bit Windows, `extern "fastcall" fn foo(i32, i32)`
/// is decorated as `@foo@8`. On 64-bit targets,
/// `extern "vectorcall" fn foo(i32)` is decorated as `foo@@8`.
///
/// Returns `None` if no decoration is required or if the name begins with
/// `\x01` or `?`, indicating that it must not be decorated further.
///
/// This function does not add LLVM's `\x01` escape prefix. Backend-specific
/// handling of that marker is the responsibility of the caller.
pub fn windows_calling_convention_name<'tcx>(
target: &Target,
conv: CanonAbi,
name: &str,
args: &[ArgAbi<'tcx, Ty<'tcx>>],
) -> Option<String> {
if !target.is_like_windows && conv != CanonAbi::X86(X86Call::Vectorcall) {
return None;
}

if name.starts_with('\x01') || name.starts_with('?') {
return None;
}

let (prefix, suffix) = match (&target.arch, conv) {
(Arch::X86, CanonAbi::X86(X86Call::Fastcall)) => ("@", "@"),
(Arch::X86, CanonAbi::X86(X86Call::Stdcall)) => ("_", "@"),
(Arch::X86 | Arch::X86_64, CanonAbi::X86(X86Call::Vectorcall)) => ("", "@@"),
_ => return None,
};

let args_in_bytes = windows_abi_argument_byte_sum(args, target);
Some(format!("{prefix}{name}{suffix}{args_in_bytes}"))
}

pub fn i686_decorated_name(
dll_import: &DllImport,
mingw: bool,
Expand Down
11 changes: 5 additions & 6 deletions tests/assembly-llvm/win32-byte-count-suffix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,9 +249,8 @@ extern "vectorcall" fn eight_vectors_vectorcall(
) {
}

/// FIXME: the mangled name for this type is incorrect on msvc, where the argument is passed
/// indirectly and a pointer takes up 4 bytes, but clang counts the size of the type and uses
/// @8 there. With GNU the value is passed directly, so the suffix is correct.
// MSVC passes this argument indirectly, but the decoration uses the
// original 8-byte type size rather than the 4-byte pointer size.
#[repr(C, align(8))]
struct OverAligned(u32, u32);

Expand All @@ -260,16 +259,16 @@ struct OverAligned(u32, u32);
extern "C" fn overaligned(_: OverAligned) {}

// windows-gnu-LABEL: _overaligned_stdcall@8:
// windows-msvc-LABEL: _overaligned_stdcall@4:
// windows-msvc-LABEL: _overaligned_stdcall@8:
#[unsafe(no_mangle)]
extern "stdcall" fn overaligned_stdcall(_: OverAligned) {}

// windows-gnu-LABEL: @overaligned_fastcall@8:
// windows-msvc-LABEL: @overaligned_fastcall@4:
// windows-msvc-LABEL: @overaligned_fastcall@8:
#[unsafe(no_mangle)]
extern "fastcall" fn overaligned_fastcall(_: OverAligned) {}

// windows-gnu-LABEL: overaligned_vectorcall@@8:
// windows-msvc-LABEL: overaligned_vectorcall@@4:
// windows-msvc-LABEL: overaligned_vectorcall@@8:
#[unsafe(no_mangle)]
extern "vectorcall" fn overaligned_vectorcall(_: OverAligned) {}
23 changes: 19 additions & 4 deletions tests/codegen-llvm/abi-x86_64-win-zst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,15 @@ extern "win64" fn pass_c_maybezst_win64(_: CMaybeZst) {}
#[no_mangle]
extern "win64" fn pass_c_maybezst_2_win64(_: CMaybeZst2) {}

// CHECK: define x86_vectorcallcc void @pass_rust_zst_vectorcall()
// CHECK: define x86_vectorcallcc void @"\01pass_rust_zst_vectorcall@@0"(
#[no_mangle]
extern "vectorcall" fn pass_rust_zst_vectorcall(_: ()) {}

// CHECK: define x86_vectorcallcc void @pass_c_maybezst_vectorcall(ptr {{[^,]*}})
// CHECK: define x86_vectorcallcc void @"\01pass_c_maybezst_vectorcall@@0"(ptr {{[^,]*}})
#[no_mangle]
extern "vectorcall" fn pass_c_maybezst_vectorcall(_: CMaybeZst) {}

// CHECK: define x86_vectorcallcc void @pass_c_maybezst_2_vectorcall(ptr {{[^,]*}})
// CHECK: define x86_vectorcallcc void @"\01pass_c_maybezst_2_vectorcall@@0"(ptr {{[^,]*}})
#[no_mangle]
extern "vectorcall" fn pass_c_maybezst_2_vectorcall(_: CMaybeZst2) {}

Expand All @@ -73,6 +73,21 @@ extern "fastcall" fn pass_c_maybezst_fastcall(_: CMaybeZst) {}
#[cfg(windows)] // "fastcall" is not valid on 64bit Linux
extern "fastcall" fn pass_c_maybezst_2_fastcall(_: CMaybeZst2) {}

// Keep the original argument size when a vectorcall argument is passed
// indirectly. This also exercises vectorcall decoration on Linux.
#[repr(C)]
pub struct Big {
pub data: [u64; 4],
}

// CHECK: define x86_vectorcallcc void @"\01vc_big@@32"(
#[unsafe(export_name = "vc_big")]
pub extern "vectorcall" fn vc_big(_: Big) {}

// CHECK: define x86_vectorcallcc void @"\01vc_u64@@8"(
#[unsafe(export_name = "vc_u64")]
pub extern "vectorcall" fn vc_u64(_: u64) {}

// The sysv64 ABI ignores ZST.

// CHECK: define x86_64_sysvcc void @pass_rust_zst_sysv64()
Expand Down Expand Up @@ -116,7 +131,7 @@ extern "win64" fn ret_c_maybezst_win64() -> CMaybeZst {
CMaybeZst
}

// CHECK: define x86_vectorcallcc void @ret_c_maybezst_vectorcall(ptr {{[^,]*}})
// CHECK: define x86_vectorcallcc void @"\01ret_c_maybezst_vectorcall@@0"(ptr {{[^,]*}})
#[no_mangle]
extern "vectorcall" fn ret_c_maybezst_vectorcall() -> CMaybeZst {
CMaybeZst
Expand Down
46 changes: 46 additions & 0 deletions tests/codegen-llvm/msvc-x86-callconv-byte-count.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Regression test for rust-lang/rust#165299.
// Verify decoration using source argument layouts on 32-bit Windows.
//
//@ add-minicore
//@ revisions: msvc gnu
//@[msvc] compile-flags: --target i686-pc-windows-msvc
//@[gnu] compile-flags: --target i686-pc-windows-gnu
//@ needs-llvm-components: x86

#![feature(abi_vectorcall, no_core)]
#![no_core]
#![crate_type = "lib"]

extern crate minicore;
use minicore::*;

#[repr(C)]
pub struct Big {
pub data: [u64; 4],
}

// CHECK-DAG: @"\01@fast_big@32"
#[unsafe(export_name = "fast_big")]
pub extern "fastcall" fn fast_big(_: Big) {}

// CHECK-DAG: @"\01_std_big@32"
#[unsafe(export_name = "std_big")]
pub extern "stdcall" fn std_big(_: Big) {}

// CHECK-DAG: @"\01vec_big@@32"
#[unsafe(export_name = "vec_big")]
pub extern "vectorcall" fn vec_big(_: Big) {}

// CHECK-DAG: @"\01vec_u64@@8"
#[unsafe(export_name = "vec_u64")]
pub extern "vectorcall" fn vec_u64(_: u64) {}

// Names beginning with '?' are already decorated.
// CHECK-DAG: @"?special"
#[unsafe(export_name = "?special")]
pub extern "stdcall" fn question(_: u32) {}

// The LLVM escape prefix must not acquire another decoration.
// CHECK-DAG: @"\01special"
#[unsafe(export_name = "\x01special")]
pub extern "stdcall" fn escaped(_: u32) {}
Loading
Loading