2022-07-12 13:52:35 -07:00
|
|
|
use std::ops::Range;
|
2024-07-29 08:13:50 +10:00
|
|
|
|
2024-11-02 19:32:52 -07:00
|
|
|
use rustc_abi::{
|
|
|
|
Align, AlignFromBytesError, HasDataLayout, Primitive, Scalar, Size, WrappingRange,
|
|
|
|
};
|
2024-07-25 20:02:56 +00:00
|
|
|
use rustc_codegen_ssa::common;
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_codegen_ssa::traits::*;
|
2024-02-26 18:03:06 +00:00
|
|
|
use rustc_hir::def::DefKind;
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_hir::def_id::DefId;
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_middle::mir::interpret::{
|
2023-01-25 01:46:19 -05:00
|
|
|
Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar,
|
|
|
|
read_target_uint,
|
2020-03-29 17:19:48 +02:00
|
|
|
};
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::mir::mono::MonoItem;
|
2024-11-15 13:53:31 +01:00
|
|
|
use rustc_middle::ty::Instance;
|
|
|
|
use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::{bug, span_bug};
|
2024-05-22 14:50:24 +10:00
|
|
|
use tracing::{debug, instrument, trace};
|
2018-07-10 13:28:39 +03:00
|
|
|
|
2024-10-28 18:52:39 +11:00
|
|
|
use crate::common::{AsCCharPtr, CodegenCx};
|
2023-05-17 10:30:14 +00:00
|
|
|
use crate::errors::{
|
|
|
|
InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined,
|
2024-07-29 08:13:50 +10:00
|
|
|
};
|
2020-03-11 00:00:00 +00:00
|
|
|
use crate::llvm::{self, True};
|
2019-02-18 03:58:58 +09:00
|
|
|
use crate::type_::Type;
|
|
|
|
use crate::type_of::LayoutLlvmExt;
|
|
|
|
use crate::value::Value;
|
2019-12-24 17:38:22 -05:00
|
|
|
use crate::{base, debuginfo};
|
2024-07-29 08:13:50 +10:00
|
|
|
|
2024-07-06 22:26:42 +10:00
|
|
|
pub(crate) fn const_alloc_to_llvm<'ll>(
|
2024-04-14 13:52:56 -04:00
|
|
|
cx: &CodegenCx<'ll, '_>,
|
|
|
|
alloc: ConstAllocation<'_>,
|
|
|
|
is_static: bool,
|
|
|
|
) -> &'ll Value {
|
Introduce `ConstAllocation`.
Currently some `Allocation`s are interned, some are not, and it's very
hard to tell at a use point which is which.
This commit introduces `ConstAllocation` for the known-interned ones,
which makes the division much clearer. `ConstAllocation::inner()` is
used to get the underlying `Allocation`.
In some places it's natural to use an `Allocation`, in some it's natural
to use a `ConstAllocation`, and in some places there's no clear choice.
I've tried to make things look as nice as possible, while generally
favouring `ConstAllocation`, which is the type that embodies more
information. This does require quite a few calls to `inner()`.
The commit also tweaks how `PartialOrd` works for `Interned`. The
previous code was too clever by half, building on `T: Ord` to make the
code shorter. That caused problems with deriving `PartialOrd` and `Ord`
for `ConstAllocation`, so I changed it to build on `T: PartialOrd`,
which is slightly more verbose but much more standard and avoided the
problems.
2022-03-02 07:15:04 +11:00
|
|
|
let alloc = alloc.inner();
|
2024-04-14 13:52:56 -04:00
|
|
|
// We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
|
|
|
|
// integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
|
|
|
|
// producing empty LLVM allocations as they're just adding noise to binaries and forcing less
|
|
|
|
// optimal codegen.
|
|
|
|
//
|
|
|
|
// Statics have a guaranteed meaningful address so it's less clear that we want to do
|
|
|
|
// something like this; it's also harder.
|
|
|
|
if !is_static {
|
|
|
|
assert!(alloc.len() != 0);
|
|
|
|
}
|
2022-11-06 13:00:09 +01:00
|
|
|
let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
|
2018-10-03 13:49:57 +02:00
|
|
|
let dl = cx.data_layout();
|
|
|
|
let pointer_size = dl.pointer_size.bytes() as usize;
|
|
|
|
|
2022-08-27 14:11:19 -04:00
|
|
|
// Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
|
|
|
|
// must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
|
2021-03-31 00:06:01 -04:00
|
|
|
fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
|
|
|
|
llvals: &mut Vec<&'ll Value>,
|
|
|
|
cx: &'a CodegenCx<'ll, 'b>,
|
|
|
|
alloc: &'a Allocation,
|
|
|
|
range: Range<usize>,
|
|
|
|
) {
|
2022-11-06 13:44:50 +01:00
|
|
|
let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
|
2021-03-31 00:06:01 -04:00
|
|
|
|
|
|
|
let chunk_to_llval = move |chunk| match chunk {
|
|
|
|
InitChunk::Init(range) => {
|
|
|
|
let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
|
|
|
|
let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
|
|
|
|
cx.const_bytes(bytes)
|
|
|
|
}
|
|
|
|
InitChunk::Uninit(range) => {
|
|
|
|
let len = range.end.bytes() - range.start.bytes();
|
|
|
|
cx.const_undef(cx.type_array(cx.type_i8(), len))
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-02-19 01:17:31 -05:00
|
|
|
// Generating partially-uninit consts is limited to small numbers of chunks,
|
2022-02-18 15:57:10 -05:00
|
|
|
// to avoid the cost of generating large complex const expressions.
|
2024-09-18 13:34:49 +10:00
|
|
|
// For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
|
|
|
|
// would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
|
2023-02-01 12:52:06 -08:00
|
|
|
let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
|
2022-02-19 01:17:31 -05:00
|
|
|
let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
|
2021-04-27 00:15:41 -04:00
|
|
|
|
2022-02-19 01:17:31 -05:00
|
|
|
if allow_uninit_chunks {
|
2021-04-27 00:15:41 -04:00
|
|
|
llvals.extend(chunks.map(chunk_to_llval));
|
|
|
|
} else {
|
2022-02-19 01:17:31 -05:00
|
|
|
// If this allocation contains any uninit bytes, codegen as if it was initialized
|
|
|
|
// (using some arbitrary value for uninit bytes).
|
|
|
|
let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
|
|
|
|
llvals.push(cx.const_bytes(bytes));
|
2021-03-31 00:06:01 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-03 13:49:57 +02:00
|
|
|
let mut next_offset = 0;
|
2023-11-25 18:41:53 +01:00
|
|
|
for &(offset, prov) in alloc.provenance().ptrs().iter() {
|
2018-10-03 13:49:57 +02:00
|
|
|
let offset = offset.bytes();
|
|
|
|
assert_eq!(offset as usize as u64, offset);
|
|
|
|
let offset = offset as usize;
|
|
|
|
if offset > next_offset {
|
2022-08-27 14:11:19 -04:00
|
|
|
// This `inspect` is okay since we have checked that there is no provenance, it
|
2019-08-28 03:58:42 +02:00
|
|
|
// is within the bounds of the allocation, and it doesn't affect interpreter execution
|
2021-03-31 00:06:01 -04:00
|
|
|
// (we inspect the result after interpreter execution).
|
|
|
|
append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
|
2018-10-03 13:49:57 +02:00
|
|
|
}
|
|
|
|
let ptr_offset = read_target_uint(
|
|
|
|
dl.endian,
|
2019-08-14 04:40:03 +02:00
|
|
|
// This `inspect` is okay since it is within the bounds of the allocation, it doesn't
|
|
|
|
// affect interpreter execution (we inspect the result after interpreter execution),
|
2022-08-27 14:11:19 -04:00
|
|
|
// and we properly interpret the provenance as a relocation pointer offset.
|
2020-08-08 07:53:47 -06:00
|
|
|
alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
|
2019-12-24 17:38:22 -05:00
|
|
|
)
|
|
|
|
.expect("const_alloc_to_llvm: could not read relocation pointer")
|
|
|
|
as u64;
|
2020-06-11 17:52:09 +12:00
|
|
|
|
2023-11-25 18:41:53 +01:00
|
|
|
let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
|
2020-06-11 17:52:09 +12:00
|
|
|
|
2018-10-03 13:49:57 +02:00
|
|
|
llvals.push(cx.scalar_to_backend(
|
2023-11-25 18:41:53 +01:00
|
|
|
InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
|
2022-03-03 12:02:12 +00:00
|
|
|
Scalar::Initialized {
|
2023-01-22 23:03:58 -05:00
|
|
|
value: Primitive::Pointer(address_space),
|
2022-04-05 13:13:21 +00:00
|
|
|
valid_range: WrappingRange::full(dl.pointer_size),
|
2022-03-03 12:02:12 +00:00
|
|
|
},
|
2022-12-06 00:07:28 -05:00
|
|
|
cx.type_ptr_ext(address_space),
|
2018-10-03 13:49:57 +02:00
|
|
|
));
|
|
|
|
next_offset = offset + pointer_size;
|
|
|
|
}
|
2019-08-14 04:40:03 +02:00
|
|
|
if alloc.len() >= next_offset {
|
|
|
|
let range = next_offset..alloc.len();
|
2022-08-27 14:11:19 -04:00
|
|
|
// This `inspect` is okay since we have check that it is after all provenance, it is
|
2019-08-14 04:40:03 +02:00
|
|
|
// within the bounds of the allocation, and it doesn't affect interpreter execution (we
|
2021-03-31 00:06:01 -04:00
|
|
|
// inspect the result after interpreter execution).
|
|
|
|
append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
|
2018-10-03 13:49:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
cx.const_struct(&llvals, true)
|
|
|
|
}
|
|
|
|
|
2024-02-26 17:43:18 +00:00
|
|
|
fn codegen_static_initializer<'ll, 'tcx>(
|
2018-10-03 13:49:57 +02:00
|
|
|
cx: &CodegenCx<'ll, 'tcx>,
|
|
|
|
def_id: DefId,
|
Introduce `ConstAllocation`.
Currently some `Allocation`s are interned, some are not, and it's very
hard to tell at a use point which is which.
This commit introduces `ConstAllocation` for the known-interned ones,
which makes the division much clearer. `ConstAllocation::inner()` is
used to get the underlying `Allocation`.
In some places it's natural to use an `Allocation`, in some it's natural
to use a `ConstAllocation`, and in some places there's no clear choice.
I've tried to make things look as nice as possible, while generally
favouring `ConstAllocation`, which is the type that embodies more
information. This does require quite a few calls to `inner()`.
The commit also tweaks how `PartialOrd` works for `Interned`. The
previous code was too clever by half, building on `T: Ord` to make the
code shorter. That caused problems with deriving `PartialOrd` and `Ord`
for `ConstAllocation`, so I changed it to build on `T: PartialOrd`,
which is slightly more verbose but much more standard and avoided the
problems.
2022-03-02 07:15:04 +11:00
|
|
|
) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
|
2020-07-31 13:27:54 +02:00
|
|
|
let alloc = cx.tcx.eval_static_initializer(def_id)?;
|
2024-04-14 13:52:56 -04:00
|
|
|
Ok((const_alloc_to_llvm(cx, alloc, /*static*/ true), alloc))
|
2018-10-03 13:49:57 +02:00
|
|
|
}
|
2017-07-30 20:43:53 +03:00
|
|
|
|
2021-12-14 13:49:49 -05:00
|
|
|
fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
|
2017-09-08 14:49:51 -07:00
|
|
|
// The target may require greater alignment for globals than the type does.
|
|
|
|
// Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
|
2022-11-16 20:34:16 +00:00
|
|
|
// which can force it to be smaller. Rust doesn't support this yet.
|
2020-11-08 14:27:51 +03:00
|
|
|
if let Some(min) = cx.sess().target.min_global_align {
|
2018-09-09 00:22:22 +03:00
|
|
|
match Align::from_bits(min) {
|
2018-09-09 01:16:45 +03:00
|
|
|
Ok(min) => align = align.max(min),
|
2023-05-17 10:30:14 +00:00
|
|
|
Err(err) => match err {
|
|
|
|
AlignFromBytesError::NotPowerOfTwo(align) => {
|
2023-12-18 22:21:37 +11:00
|
|
|
cx.sess().dcx().emit_err(InvalidMinimumAlignmentNotPowerOfTwo { align });
|
2023-05-17 10:30:14 +00:00
|
|
|
}
|
|
|
|
AlignFromBytesError::TooLarge(align) => {
|
2023-12-18 22:21:37 +11:00
|
|
|
cx.sess().dcx().emit_err(InvalidMinimumAlignmentTooLarge { align });
|
2023-05-17 10:30:14 +00:00
|
|
|
}
|
|
|
|
},
|
2017-09-08 14:49:51 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
unsafe {
|
2018-09-09 01:16:45 +03:00
|
|
|
llvm::LLVMSetAlignment(gv, align.bytes() as u32);
|
2017-09-08 14:49:51 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-14 13:49:49 -05:00
|
|
|
fn check_and_apply_linkage<'ll, 'tcx>(
|
2018-07-10 13:28:39 +03:00
|
|
|
cx: &CodegenCx<'ll, 'tcx>,
|
2018-07-23 08:43:22 -04:00
|
|
|
attrs: &CodegenFnAttrs,
|
2023-10-06 12:16:56 +00:00
|
|
|
llty: &'ll Type,
|
2020-07-10 15:45:05 +10:00
|
|
|
sym: &str,
|
2022-07-12 13:52:35 -07:00
|
|
|
def_id: DefId,
|
2018-07-10 13:28:39 +03:00
|
|
|
) -> &'ll Value {
|
Move linkage type check to HIR analysis and fix semantics issues.
This ensures that the error is printed even for unused variables,
as well as unifying the handling between the LLVM and GCC backends.
This also fixes unusual behavior around exported Rust-defined variables
with linkage attributes. With the previous behavior, it appears to be
impossible to define such a variable such that it can actually be imported
and used by another crate. This is because on the importing side, the
variable is required to be a pointer, but on the exporting side, the
type checker rejects static variables of pointer type because they do
not implement `Sync`. Even if it were possible to import such a type, it
appears that code generation on the importing side would add an unexpected
additional level of pointer indirection, which would break type safety.
This highlighted that the semantics of linkage on Rust-defined variables
is different to linkage on foreign items. As such, we now model the
difference with two different codegen attributes: linkage for Rust-defined
variables, and import_linkage for foreign items.
This change gives semantics to the test
src/test/ui/linkage-attr/auxiliary/def_illtyped_external.rs which was
previously expected to fail to compile. Therefore, convert it into a
test that is expected to successfully compile.
The update to the GCC backend is speculative and untested.
2022-11-23 18:13:30 -08:00
|
|
|
if let Some(linkage) = attrs.import_linkage {
|
2018-07-23 08:43:22 -04:00
|
|
|
debug!("get_static: sym={} linkage={:?}", sym, linkage);
|
|
|
|
|
2024-10-25 21:40:38 +11:00
|
|
|
// Declare a symbol `foo` with the desired linkage.
|
|
|
|
let g1 = cx.declare_global(sym, cx.type_i8());
|
|
|
|
llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
|
|
|
|
|
|
|
|
// Declare an internal global `extern_with_linkage_foo` which
|
|
|
|
// is initialized with the address of `foo`. If `foo` is
|
|
|
|
// discarded during linking (for example, if `foo` has weak
|
|
|
|
// linkage and there are no definitions), then
|
|
|
|
// `extern_with_linkage_foo` will instead be initialized to
|
|
|
|
// zero.
|
|
|
|
let mut real_name = "_rust_extern_with_linkage_".to_string();
|
|
|
|
real_name.push_str(sym);
|
|
|
|
let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
|
|
|
|
cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
|
|
|
|
span: cx.tcx.def_span(def_id),
|
|
|
|
symbol_name: sym,
|
|
|
|
})
|
|
|
|
});
|
|
|
|
llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
|
2025-01-14 12:25:16 +00:00
|
|
|
llvm::set_initializer(g2, g1);
|
2024-10-25 21:40:38 +11:00
|
|
|
g2
|
2022-07-12 13:52:35 -07:00
|
|
|
} else if cx.tcx.sess.target.arch == "x86"
|
2024-09-19 15:00:30 -07:00
|
|
|
&& common::is_mingw_gnu_toolchain(&cx.tcx.sess.target)
|
2024-07-25 20:02:56 +00:00
|
|
|
&& let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
|
2022-07-12 13:52:35 -07:00
|
|
|
{
|
2024-09-19 15:00:30 -07:00
|
|
|
cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
|
2018-07-23 08:43:22 -04:00
|
|
|
} else {
|
|
|
|
// Generate an external declaration.
|
|
|
|
// FIXME(nagisa): investigate whether it can be changed into define_global
|
2021-09-30 19:38:50 +02:00
|
|
|
cx.declare_global(sym, llty)
|
2018-07-23 08:43:22 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-12-14 13:49:49 -05:00
|
|
|
impl<'ll> CodegenCx<'ll, '_> {
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
|
2019-12-24 17:38:22 -05:00
|
|
|
unsafe { llvm::LLVMConstBitCast(val, ty) }
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
2018-11-24 17:11:59 +01:00
|
|
|
|
Cast global variables to default address space
Pointers for variables all need to be in the same address space for
correct compilation. Therefore ensure that even if a global variable is
created in a different address space, it is casted to the default
address space before its value is used.
This is necessary for the amdgpu target and others where the default
address space for global variables is not 0.
For example `core` does not compile in debug mode when not casting the
address space to the default one because it tries to emit the following
(simplified) LLVM IR, containing a type mismatch:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspace(1) @alloc_0 }>, align 8
; ^ here a struct containing a `ptr` is needed, but it is created using a `ptr addrspace(1)`
```
For this to compile, we need to insert a constant `addrspacecast` before
we use a global variable:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspacecast (ptr addrspace(1) @alloc_0 to ptr) }>, align 8
```
As vtables are global variables as well, they are also created with an
`addrspacecast`. In the SSA backend, after a vtable global is created,
metadata is added to it. To add metadata, we need the non-casted global
variable. Therefore we strip away an addrspacecast if there is one, to
get the underlying global.
2025-01-02 13:10:11 +01:00
|
|
|
pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
|
|
|
|
unsafe { llvm::LLVMConstPointerCast(val, ty) }
|
|
|
|
}
|
|
|
|
|
2025-01-24 00:37:05 +01:00
|
|
|
/// Create a global variable.
|
|
|
|
///
|
|
|
|
/// The returned global variable is a pointer in the default address space for globals.
|
|
|
|
/// Fails if a symbol with the given name already exists.
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn static_addr_of_mut(
|
2018-09-10 16:28:47 +02:00
|
|
|
&self,
|
|
|
|
cv: &'ll Value,
|
2018-09-09 01:16:45 +03:00
|
|
|
align: Align,
|
2018-09-10 16:28:47 +02:00
|
|
|
kind: Option<&str>,
|
|
|
|
) -> &'ll Value {
|
2024-10-25 21:40:38 +11:00
|
|
|
let gv = match kind {
|
|
|
|
Some(kind) if !self.tcx.sess.fewer_names() => {
|
|
|
|
let name = self.generate_local_symbol_name(kind);
|
|
|
|
let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
|
|
|
|
bug!("symbol `{}` is already defined", name);
|
|
|
|
});
|
|
|
|
llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
|
|
|
|
gv
|
|
|
|
}
|
|
|
|
_ => self.define_private_global(self.val_ty(cv)),
|
|
|
|
};
|
2025-01-14 12:25:16 +00:00
|
|
|
llvm::set_initializer(gv, cv);
|
2024-10-25 21:40:38 +11:00
|
|
|
set_global_alignment(self, gv, align);
|
|
|
|
llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global);
|
|
|
|
gv
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
|
|
|
|
2025-01-24 00:37:05 +01:00
|
|
|
/// Create a global constant.
|
|
|
|
///
|
|
|
|
/// The returned global variable is a pointer in the default address space for globals.
|
Cast global variables to default address space
Pointers for variables all need to be in the same address space for
correct compilation. Therefore ensure that even if a global variable is
created in a different address space, it is casted to the default
address space before its value is used.
This is necessary for the amdgpu target and others where the default
address space for global variables is not 0.
For example `core` does not compile in debug mode when not casting the
address space to the default one because it tries to emit the following
(simplified) LLVM IR, containing a type mismatch:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspace(1) @alloc_0 }>, align 8
; ^ here a struct containing a `ptr` is needed, but it is created using a `ptr addrspace(1)`
```
For this to compile, we need to insert a constant `addrspacecast` before
we use a global variable:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspacecast (ptr addrspace(1) @alloc_0 to ptr) }>, align 8
```
As vtables are global variables as well, they are also created with an
`addrspacecast`. In the SSA backend, after a vtable global is created,
metadata is added to it. To add metadata, we need the non-casted global
variable. Therefore we strip away an addrspacecast if there is one, to
get the underlying global.
2025-01-02 13:10:11 +01:00
|
|
|
pub(crate) fn static_addr_of_impl(
|
|
|
|
&self,
|
|
|
|
cv: &'ll Value,
|
|
|
|
align: Align,
|
|
|
|
kind: Option<&str>,
|
|
|
|
) -> &'ll Value {
|
|
|
|
if let Some(&gv) = self.const_globals.borrow().get(&cv) {
|
|
|
|
unsafe {
|
|
|
|
// Upgrade the alignment in cases where the same constant is used with different
|
|
|
|
// alignment requirements
|
|
|
|
let llalign = align.bytes() as u32;
|
|
|
|
if llalign > llvm::LLVMGetAlignment(gv) {
|
|
|
|
llvm::LLVMSetAlignment(gv, llalign);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return gv;
|
|
|
|
}
|
|
|
|
let gv = self.static_addr_of_mut(cv, align, kind);
|
|
|
|
unsafe {
|
|
|
|
llvm::LLVMSetGlobalConstant(gv, True);
|
|
|
|
}
|
|
|
|
self.const_globals.borrow_mut().insert(cv, gv);
|
|
|
|
gv
|
|
|
|
}
|
|
|
|
|
2023-10-06 13:32:57 +00:00
|
|
|
#[instrument(level = "debug", skip(self))]
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
|
2018-09-10 16:28:47 +02:00
|
|
|
let instance = Instance::mono(self.tcx, def_id);
|
2023-10-06 13:32:57 +00:00
|
|
|
trace!(?instance);
|
2024-02-26 18:03:06 +00:00
|
|
|
|
|
|
|
let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
|
2024-09-18 13:34:49 +10:00
|
|
|
// Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
|
|
|
|
// out the llvm type from the actual evaluated initializer.
|
2024-02-26 18:03:06 +00:00
|
|
|
let llty = if nested {
|
|
|
|
self.type_i8()
|
|
|
|
} else {
|
2024-11-15 13:53:31 +01:00
|
|
|
let ty = instance.ty(self.tcx, self.typing_env());
|
2024-02-26 18:03:06 +00:00
|
|
|
trace!(?ty);
|
|
|
|
self.layout_of(ty).llvm_type(self)
|
|
|
|
};
|
2023-10-06 13:32:57 +00:00
|
|
|
self.get_static_inner(def_id, llty)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[instrument(level = "debug", skip(self, llty))]
|
2024-09-18 10:21:02 +10:00
|
|
|
fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
|
2024-04-19 23:09:57 +02:00
|
|
|
let instance = Instance::mono(self.tcx, def_id);
|
|
|
|
if let Some(&g) = self.instances.borrow().get(&instance) {
|
2023-10-06 13:32:57 +00:00
|
|
|
trace!("used cached value");
|
2018-09-10 16:28:47 +02:00
|
|
|
return g;
|
|
|
|
}
|
|
|
|
|
2019-12-24 17:38:22 -05:00
|
|
|
let defined_in_current_codegen_unit =
|
|
|
|
self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
|
|
|
|
assert!(
|
|
|
|
!defined_in_current_codegen_unit,
|
|
|
|
"consts::get_static() should always hit the cache for \
|
2023-07-25 23:04:01 +02:00
|
|
|
statics defined in the same CGU, but did not for `{def_id:?}`"
|
2019-12-24 17:38:22 -05:00
|
|
|
);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2024-04-19 23:09:57 +02:00
|
|
|
let sym = self.tcx.symbol_name(instance).name;
|
2021-02-02 15:38:51 +01:00
|
|
|
let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2023-10-06 13:32:57 +00:00
|
|
|
debug!(?sym, ?fn_attrs);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2021-02-04 11:17:01 +01:00
|
|
|
let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
|
2021-02-02 15:38:51 +01:00
|
|
|
if let Some(g) = self.get_declared_value(sym) {
|
2022-12-06 00:07:28 -05:00
|
|
|
if self.val_ty(g) != self.type_ptr() {
|
2021-02-02 15:38:51 +01:00
|
|
|
span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
2021-02-02 15:38:51 +01:00
|
|
|
}
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2021-02-02 15:38:51 +01:00
|
|
|
let g = self.declare_global(sym, llty);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2021-02-02 15:38:51 +01:00
|
|
|
if !self.tcx.is_reachable_non_generic(def_id) {
|
2024-10-19 12:17:33 +11:00
|
|
|
llvm::set_visibility(g, llvm::Visibility::Hidden);
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
2015-06-28 10:36:46 -07:00
|
|
|
|
2016-08-16 17:41:38 +03:00
|
|
|
g
|
2015-06-28 10:36:46 -07:00
|
|
|
} else {
|
2023-10-06 12:16:56 +00:00
|
|
|
check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
|
2021-02-02 15:38:51 +01:00
|
|
|
};
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2021-02-02 15:38:51 +01:00
|
|
|
// Thread-local statics in some other crate need to *always* be linked
|
|
|
|
// against in a thread-local fashion, so we need to be sure to apply the
|
|
|
|
// thread-local attribute locally if it was present remotely. If we
|
|
|
|
// don't do this then linker errors can be generated where the linker
|
|
|
|
// complains that one object files has a thread local version of the
|
|
|
|
// symbol and another one doesn't.
|
|
|
|
if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
|
|
|
|
llvm::set_thread_local_mode(g, self.tls_model);
|
|
|
|
}
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2025-02-14 17:27:49 +00:00
|
|
|
let dso_local = self.assume_dso_local(g, true);
|
2022-11-21 16:47:02 +01:00
|
|
|
|
2021-02-04 11:17:01 +01:00
|
|
|
if !def_id.is_local() {
|
2024-09-18 13:34:49 +10:00
|
|
|
let needs_dll_storage_attr = self.use_dll_storage_attrs
|
|
|
|
&& !self.tcx.is_foreign_item(def_id)
|
2022-11-21 16:47:02 +01:00
|
|
|
// Local definitions can never be imported, so we must not apply
|
|
|
|
// the DLLImport annotation.
|
2024-09-18 13:34:49 +10:00
|
|
|
&& !dso_local
|
2024-03-20 18:54:01 +01:00
|
|
|
// Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
|
|
|
|
// as the code generation happens out of process. Instead we assume static linkage
|
|
|
|
// and disallow dynamic linking when linker plugin based LTO is enabled.
|
|
|
|
// Regular in-process ThinLTO doesn't need this workaround.
|
|
|
|
&& !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
|
2018-09-10 16:28:47 +02:00
|
|
|
|
|
|
|
// If this assertion triggers, there's something wrong with commandline
|
|
|
|
// argument validation.
|
2024-07-19 16:52:33 -07:00
|
|
|
assert!(
|
2019-12-24 17:38:22 -05:00
|
|
|
!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
|
2020-11-08 14:27:51 +03:00
|
|
|
&& self.tcx.sess.target.is_like_windows
|
2019-12-24 17:38:22 -05:00
|
|
|
&& self.tcx.sess.opts.cg.prefer_dynamic)
|
|
|
|
);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
|
|
|
if needs_dll_storage_attr {
|
2018-11-27 02:59:49 +00:00
|
|
|
// This item is external but not foreign, i.e., it originates from an external Rust
|
2018-09-10 16:28:47 +02:00
|
|
|
// crate. Since we don't know whether this crate will be linked dynamically or
|
|
|
|
// statically in the final application, we always mark such symbols as 'dllimport'.
|
|
|
|
// If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
|
|
|
|
// to make things work.
|
|
|
|
//
|
|
|
|
// However, in some scenarios we defer emission of statics to downstream
|
|
|
|
// crates, so there are cases where a static with an upstream DefId
|
|
|
|
// is actually present in the current crate. We can find out via the
|
|
|
|
// is_codegened_item query.
|
2018-11-07 12:08:41 +02:00
|
|
|
if !self.tcx.is_codegened_item(def_id) {
|
2025-02-14 17:27:49 +00:00
|
|
|
llvm::set_dllimport_storage_class(g);
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
|
|
|
}
|
2021-02-02 15:38:51 +01:00
|
|
|
}
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2022-10-18 16:55:32 +02:00
|
|
|
if self.use_dll_storage_attrs
|
|
|
|
&& let Some(library) = self.tcx.native_library(def_id)
|
|
|
|
&& library.kind.is_dllimport()
|
|
|
|
{
|
2018-09-10 16:28:47 +02:00
|
|
|
// For foreign (native) libs we know the exact storage type to use.
|
2025-02-14 17:27:49 +00:00
|
|
|
llvm::set_dllimport_storage_class(g);
|
2013-06-21 18:46:34 -07:00
|
|
|
}
|
2015-06-28 10:36:46 -07:00
|
|
|
|
2024-04-19 23:09:57 +02:00
|
|
|
self.instances.borrow_mut().insert(instance, g);
|
2018-09-10 16:28:47 +02:00
|
|
|
g
|
|
|
|
}
|
|
|
|
|
2023-10-06 15:00:44 +00:00
|
|
|
fn codegen_static_item(&self, def_id: DefId) {
|
2018-09-10 16:28:47 +02:00
|
|
|
unsafe {
|
2024-02-26 18:03:06 +00:00
|
|
|
assert!(
|
|
|
|
llvm::LLVMGetInitializer(
|
|
|
|
self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
|
|
|
|
)
|
|
|
|
.is_none()
|
|
|
|
);
|
2018-11-07 12:08:41 +02:00
|
|
|
let attrs = self.tcx.codegen_fn_attrs(def_id);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2022-02-19 00:48:49 +01:00
|
|
|
let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
|
2018-09-10 16:28:47 +02:00
|
|
|
// Error has already been reported
|
2022-02-19 00:48:49 +01:00
|
|
|
return;
|
2018-09-10 16:28:47 +02:00
|
|
|
};
|
Introduce `ConstAllocation`.
Currently some `Allocation`s are interned, some are not, and it's very
hard to tell at a use point which is which.
This commit introduces `ConstAllocation` for the known-interned ones,
which makes the division much clearer. `ConstAllocation::inner()` is
used to get the underlying `Allocation`.
In some places it's natural to use an `Allocation`, in some it's natural
to use a `ConstAllocation`, and in some places there's no clear choice.
I've tried to make things look as nice as possible, while generally
favouring `ConstAllocation`, which is the type that embodies more
information. This does require quite a few calls to `inner()`.
The commit also tweaks how `PartialOrd` works for `Interned`. The
previous code was too clever by half, building on `T: Ord` to make the
code shorter. That caused problems with deriving `PartialOrd` and `Ord`
for `ConstAllocation`, so I changed it to build on `T: PartialOrd`,
which is slightly more verbose but much more standard and avoided the
problems.
2022-03-02 07:15:04 +11:00
|
|
|
let alloc = alloc.inner();
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2023-10-06 14:43:37 +00:00
|
|
|
let val_llty = self.val_ty(v);
|
|
|
|
|
2024-02-23 16:06:04 +00:00
|
|
|
let g = self.get_static_inner(def_id, val_llty);
|
2024-08-08 19:29:47 +08:00
|
|
|
let llty = llvm::LLVMGlobalGetValueType(g);
|
2024-02-23 16:06:04 +00:00
|
|
|
|
2018-09-10 16:28:47 +02:00
|
|
|
let g = if val_llty == llty {
|
|
|
|
g
|
|
|
|
} else {
|
2025-01-31 10:45:42 +00:00
|
|
|
// codegen_static_initializer creates the global value just from the
|
|
|
|
// `Allocation` data by generating one big struct value that is just
|
|
|
|
// all the bytes and pointers after each other. This will almost never
|
|
|
|
// match the type that the static was declared with. Unfortunately
|
|
|
|
// we can't just LLVMConstBitCast our way out of it because that has very
|
|
|
|
// specific rules on what can be cast. So instead of adding a new way to
|
|
|
|
// generate static initializers that match the static's type, we picked
|
|
|
|
// the easier option and retroactively change the type of the static item itself.
|
2019-12-04 12:00:28 -08:00
|
|
|
let name = llvm::get_value_name(g).to_vec();
|
|
|
|
llvm::set_value_name(g, b"");
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2024-10-25 21:40:38 +11:00
|
|
|
let linkage = llvm::get_linkage(g);
|
2024-10-19 12:17:33 +11:00
|
|
|
let visibility = llvm::get_visibility(g);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
|
|
|
let new_g = llvm::LLVMRustGetOrInsertGlobal(
|
2019-12-24 17:38:22 -05:00
|
|
|
self.llmod,
|
2024-10-28 18:52:39 +11:00
|
|
|
name.as_c_char_ptr(),
|
2019-12-24 17:38:22 -05:00
|
|
|
name.len(),
|
|
|
|
val_llty,
|
|
|
|
);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2024-10-25 21:40:38 +11:00
|
|
|
llvm::set_linkage(new_g, linkage);
|
2024-10-19 12:17:33 +11:00
|
|
|
llvm::set_visibility(new_g, visibility);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2022-03-01 00:53:25 +00:00
|
|
|
// The old global has had its name removed but is returned by
|
|
|
|
// get_static since it is in the instance cache. Provide an
|
|
|
|
// alternative lookup that points to the new global so that
|
|
|
|
// global_asm! can compute the correct mangled symbol name
|
|
|
|
// for the global.
|
|
|
|
self.renamed_statics.borrow_mut().insert(def_id, new_g);
|
|
|
|
|
2018-09-10 16:28:47 +02:00
|
|
|
// To avoid breaking any invariants, we leave around the old
|
|
|
|
// global for the moment; we'll replace all references to it
|
|
|
|
// with the new global later. (See base::codegen_backend.)
|
2018-11-07 12:08:41 +02:00
|
|
|
self.statics_to_rauw.borrow_mut().push((g, new_g));
|
2018-09-10 16:28:47 +02:00
|
|
|
new_g
|
|
|
|
};
|
2023-10-06 14:39:23 +00:00
|
|
|
set_global_alignment(self, g, alloc.align);
|
2025-01-14 12:25:16 +00:00
|
|
|
llvm::set_initializer(g, v);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
2025-02-14 17:27:49 +00:00
|
|
|
self.assume_dso_local(g, true);
|
2021-05-14 03:47:41 +02:00
|
|
|
|
2024-03-11 18:39:23 +00:00
|
|
|
// Forward the allocation's mutability (picked by the const interner) to LLVM.
|
2023-10-06 15:00:44 +00:00
|
|
|
if alloc.mutability.is_not() {
|
2020-10-26 21:02:48 -04:00
|
|
|
llvm::LLVMSetGlobalConstant(g, llvm::True);
|
2018-06-28 06:24:09 +08:00
|
|
|
}
|
2016-05-06 20:02:09 -04:00
|
|
|
|
2022-03-03 11:15:25 +01:00
|
|
|
debuginfo::build_global_var_di_node(self, def_id, g);
|
2018-09-10 16:28:47 +02:00
|
|
|
|
|
|
|
if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
|
|
|
|
llvm::set_thread_local_mode(g, self.tls_model);
|
|
|
|
}
|
2016-05-06 20:02:09 -04:00
|
|
|
|
2018-09-10 16:28:47 +02:00
|
|
|
// Wasm statics with custom link sections get special treatment as they
|
2024-02-23 16:05:28 -08:00
|
|
|
// go into custom sections of the wasm executable. The exception to this
|
|
|
|
// is the `.init_array` section which are treated specially by the wasm linker.
|
|
|
|
if self.tcx.sess.target.is_like_wasm
|
|
|
|
&& attrs
|
|
|
|
.link_section
|
|
|
|
.map(|link_section| !link_section.as_str().starts_with(".init_array"))
|
|
|
|
.unwrap_or(true)
|
|
|
|
{
|
2018-09-10 16:28:47 +02:00
|
|
|
if let Some(section) = attrs.link_section {
|
2023-04-05 15:08:17 +03:00
|
|
|
let section = llvm::LLVMMDStringInContext2(
|
2018-11-07 12:08:41 +02:00
|
|
|
self.llcx,
|
2024-10-28 18:52:39 +11:00
|
|
|
section.as_str().as_c_char_ptr(),
|
2023-04-05 15:08:17 +03:00
|
|
|
section.as_str().len(),
|
2018-09-10 16:28:47 +02:00
|
|
|
);
|
2022-11-06 13:00:09 +01:00
|
|
|
assert!(alloc.provenance().ptrs().is_empty());
|
2019-08-14 04:40:03 +02:00
|
|
|
|
2022-08-27 14:11:19 -04:00
|
|
|
// The `inspect` method is okay here because we checked for provenance, and
|
2019-08-14 04:40:03 +02:00
|
|
|
// because we are doing this access to inspect the final interpreter state (not
|
|
|
|
// as part of the interpreter execution).
|
2019-12-24 17:38:22 -05:00
|
|
|
let bytes =
|
2020-08-08 07:53:47 -06:00
|
|
|
alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
|
2023-04-05 15:08:17 +03:00
|
|
|
let alloc =
|
2024-10-28 18:52:39 +11:00
|
|
|
llvm::LLVMMDStringInContext2(self.llcx, bytes.as_c_char_ptr(), bytes.len());
|
2018-09-10 16:28:47 +02:00
|
|
|
let data = [section, alloc];
|
2023-04-05 15:08:17 +03:00
|
|
|
let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len());
|
2025-02-24 14:45:16 +00:00
|
|
|
let val = self.get_metadata_value(meta);
|
2018-09-10 16:28:47 +02:00
|
|
|
llvm::LLVMAddNamedMetadataOperand(
|
2018-11-07 12:08:41 +02:00
|
|
|
self.llmod,
|
2024-08-20 14:04:48 -07:00
|
|
|
c"wasm.custom_sections".as_ptr(),
|
2023-04-05 15:08:17 +03:00
|
|
|
val,
|
2018-09-10 16:28:47 +02:00
|
|
|
);
|
|
|
|
}
|
|
|
|
} else {
|
2021-09-30 19:38:50 +02:00
|
|
|
base::set_link_section(g, attrs);
|
2018-07-13 11:30:47 -07:00
|
|
|
}
|
|
|
|
|
2024-07-08 15:49:50 +02:00
|
|
|
base::set_variable_sanitizer_attrs(g, attrs);
|
|
|
|
|
2018-09-10 16:28:47 +02:00
|
|
|
if attrs.flags.contains(CodegenFnAttrFlags::USED) {
|
2021-11-22 13:14:54 +01:00
|
|
|
// `USED` and `USED_LINKER` can't be used together.
|
|
|
|
assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
|
|
|
|
|
2021-08-20 21:13:18 +02:00
|
|
|
// The semantics of #[used] in Rust only require the symbol to make it into the
|
|
|
|
// object file. It is explicitly allowed for the linker to strip the symbol if it
|
2023-02-16 18:58:08 +02:00
|
|
|
// is dead, which means we are allowed to use `llvm.compiler.used` instead of
|
2022-02-06 13:51:11 -08:00
|
|
|
// `llvm.used` here.
|
|
|
|
//
|
2021-08-20 21:13:18 +02:00
|
|
|
// Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
|
|
|
|
// sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
|
2022-02-06 13:51:11 -08:00
|
|
|
// in the handling of `.init_array` (the static constructor list) in versions of
|
|
|
|
// the gold linker (prior to the one released with binutils 2.36).
|
|
|
|
//
|
2022-05-11 01:55:00 -07:00
|
|
|
// That said, we only ever emit these when compiling for ELF targets, unless
|
|
|
|
// `#[used(compiler)]` is explicitly requested. This is to avoid similar breakage
|
|
|
|
// on other targets, in particular MachO targets have *their* static constructor
|
2023-02-16 18:58:08 +02:00
|
|
|
// lists broken if `llvm.compiler.used` is emitted rather than `llvm.used`. However,
|
2024-09-18 13:34:49 +10:00
|
|
|
// that check happens when assigning the `CodegenFnAttrFlags` in
|
|
|
|
// `rustc_hir_analysis`, so we don't need to take care of it here.
|
2021-08-20 21:13:18 +02:00
|
|
|
self.add_compiler_used_global(g);
|
2018-09-10 16:28:47 +02:00
|
|
|
}
|
2021-11-22 13:14:54 +01:00
|
|
|
if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
|
|
|
|
// `USED` and `USED_LINKER` can't be used together.
|
|
|
|
assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED));
|
|
|
|
|
|
|
|
self.add_used_global(g);
|
|
|
|
}
|
2017-02-20 14:42:47 -05:00
|
|
|
}
|
2013-01-10 21:23:07 -08:00
|
|
|
}
|
2023-10-06 14:12:51 +00:00
|
|
|
}
|
|
|
|
|
2024-09-17 10:15:26 +10:00
|
|
|
impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
|
2025-01-24 00:37:05 +01:00
|
|
|
/// Get a pointer to a global variable.
|
|
|
|
///
|
|
|
|
/// The pointer will always be in the default address space. If global variables default to a
|
|
|
|
/// different address space, an addrspacecast is inserted.
|
2023-10-06 14:12:51 +00:00
|
|
|
fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
|
Cast global variables to default address space
Pointers for variables all need to be in the same address space for
correct compilation. Therefore ensure that even if a global variable is
created in a different address space, it is casted to the default
address space before its value is used.
This is necessary for the amdgpu target and others where the default
address space for global variables is not 0.
For example `core` does not compile in debug mode when not casting the
address space to the default one because it tries to emit the following
(simplified) LLVM IR, containing a type mismatch:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspace(1) @alloc_0 }>, align 8
; ^ here a struct containing a `ptr` is needed, but it is created using a `ptr addrspace(1)`
```
For this to compile, we need to insert a constant `addrspacecast` before
we use a global variable:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspacecast (ptr addrspace(1) @alloc_0 to ptr) }>, align 8
```
As vtables are global variables as well, they are also created with an
`addrspacecast`. In the SSA backend, after a vtable global is created,
metadata is added to it. To add metadata, we need the non-casted global
variable. Therefore we strip away an addrspacecast if there is one, to
get the underlying global.
2025-01-02 13:10:11 +01:00
|
|
|
let gv = self.static_addr_of_impl(cv, align, kind);
|
2025-01-24 00:37:05 +01:00
|
|
|
// static_addr_of_impl returns the bare global variable, which might not be in the default
|
|
|
|
// address space. Cast to the default address space if necessary.
|
Cast global variables to default address space
Pointers for variables all need to be in the same address space for
correct compilation. Therefore ensure that even if a global variable is
created in a different address space, it is casted to the default
address space before its value is used.
This is necessary for the amdgpu target and others where the default
address space for global variables is not 0.
For example `core` does not compile in debug mode when not casting the
address space to the default one because it tries to emit the following
(simplified) LLVM IR, containing a type mismatch:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspace(1) @alloc_0 }>, align 8
; ^ here a struct containing a `ptr` is needed, but it is created using a `ptr addrspace(1)`
```
For this to compile, we need to insert a constant `addrspacecast` before
we use a global variable:
```llvm
@alloc_0 = addrspace(1) constant <{ [6 x i8] }> <{ [6 x i8] c"bit.rs" }>, align 1
@alloc_1 = addrspace(1) constant <{ ptr }> <{ ptr addrspacecast (ptr addrspace(1) @alloc_0 to ptr) }>, align 8
```
As vtables are global variables as well, they are also created with an
`addrspacecast`. In the SSA backend, after a vtable global is created,
metadata is added to it. To add metadata, we need the non-casted global
variable. Therefore we strip away an addrspacecast if there is one, to
get the underlying global.
2025-01-02 13:10:11 +01:00
|
|
|
self.const_pointercast(gv, self.type_ptr())
|
2023-10-06 14:12:51 +00:00
|
|
|
}
|
|
|
|
|
2023-10-06 15:00:44 +00:00
|
|
|
fn codegen_static(&self, def_id: DefId) {
|
|
|
|
self.codegen_static_item(def_id)
|
2023-10-06 14:12:51 +00:00
|
|
|
}
|
2020-07-02 11:27:15 -07:00
|
|
|
|
2022-12-06 00:07:28 -05:00
|
|
|
/// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
|
2020-07-02 11:27:15 -07:00
|
|
|
fn add_used_global(&self, global: &'ll Value) {
|
2022-12-06 00:07:28 -05:00
|
|
|
self.used_statics.borrow_mut().push(global);
|
2020-07-02 11:27:15 -07:00
|
|
|
}
|
2021-08-20 21:13:18 +02:00
|
|
|
|
|
|
|
/// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
|
2022-12-06 00:07:28 -05:00
|
|
|
/// an array of ptr.
|
2021-08-20 21:13:18 +02:00
|
|
|
fn add_compiler_used_global(&self, global: &'ll Value) {
|
2022-12-06 00:07:28 -05:00
|
|
|
self.compiler_used_statics.borrow_mut().push(global);
|
2021-08-20 21:13:18 +02:00
|
|
|
}
|
2012-07-31 18:34:36 -07:00
|
|
|
}
|