]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/common.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / common.rs
CommitLineData
94b46f34 1//! Code that is useful in various codegen modules.
1a4d82fc 2
ba9703b0
XL
3use crate::consts::{self, const_alloc_to_llvm};
4pub use crate::context::CodegenCx;
dfeec247 5use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True};
9fa01778
XL
6use crate::type_::Type;
7use crate::type_of::LayoutLlvmExt;
8use crate::value::Value;
54a0048b 9
3dfed10e 10use rustc_ast::Mutability;
ba9703b0
XL
11use rustc_codegen_ssa::mir::place::PlaceRef;
12use rustc_codegen_ssa::traits::*;
f2b60f7d 13use rustc_hir::def_id::DefId;
ba9703b0 14use rustc_middle::bug;
5e7ed085 15use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar};
c295e0f8 16use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
f2b60f7d
FG
17use rustc_middle::ty::TyCtxt;
18use rustc_session::cstore::{DllCallingConvention, DllImport, PeImportNameType};
c295e0f8 19use rustc_target::abi::{self, AddressSpace, HasDataLayout, Pointer, Size};
f2b60f7d 20use rustc_target::spec::Target;
1a4d82fc 21
ba9703b0 22use libc::{c_char, c_uint};
f2b60f7d 23use std::fmt::Write;
1a4d82fc 24
1a4d82fc
JJ
25/*
26* A note on nomenclature of linking: "extern", "foreign", and "upcall".
27*
28* An "extern" is an LLVM symbol we wind up emitting an undefined external
29* reference to. This means "we don't have the thing in this compilation unit,
30* please make sure you link it in at runtime". This could be a reference to
31* C code found in a C library, or rust code found in a rust crate.
32*
33* Most "externs" are implicitly declared (automatically) as a result of a
34* user declaring an extern _module_ dependency; this causes the rust driver
35* to locate an extern crate, scan its compilation metadata, and emit extern
36* declarations for any symbols used by the declaring crate.
37*
38* A "foreign" is an extern that references C (or other non-rust ABI) code.
39* There is no metadata to scan for extern references so in these cases either
40* a header-digester like bindgen, or manual function prototypes, have to
41* serve as declarators. So these are usually given explicitly as prototype
42* declarations, in rust code, with ABI attributes on them noting which ABI to
43* link via.
44*
45* An "upcall" is a foreign call generated by the compiler (not corresponding
46* to any user-written call in the code) into the runtime library, to perform
47* some helper task such as bringing a task to life, allocating memory, etc.
48*
49*/
50
7453a54e
SL
51/// A structure representing an active landing pad for the duration of a basic
52/// block.
53///
54/// Each `Block` may contain an instance of this, indicating whether the block
55/// is part of a landing pad or not. This is used to make decision about whether
0731742a 56/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
7453a54e
SL
57/// use `invoke`) and also about various function call metadata.
58///
59/// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
60/// just a bunch of `None` instances (not too interesting), but for MSVC
61/// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
62/// When inside of a landing pad, each function call in LLVM IR needs to be
63/// annotated with which landing pad it's a part of. This is accomplished via
64/// the `OperandBundleDef` value created for MSVC landing pads.
b7449926
XL
65pub struct Funclet<'ll> {
66 cleanuppad: &'ll Value,
67 operand: OperandBundleDef<'ll>,
7453a54e
SL
68}
69
a2a8927a 70impl<'ll> Funclet<'ll> {
b7449926 71 pub fn new(cleanuppad: &'ll Value) -> Self {
dfeec247 72 Funclet { cleanuppad, operand: OperandBundleDef::new("funclet", &[cleanuppad]) }
7453a54e
SL
73 }
74
b7449926 75 pub fn cleanuppad(&self) -> &'ll Value {
3157f602
XL
76 self.cleanuppad
77 }
7453a54e 78
b7449926 79 pub fn bundle(&self) -> &OperandBundleDef<'ll> {
32a655c1 80 &self.operand
7453a54e 81 }
1a4d82fc
JJ
82}
83
a2a8927a 84impl<'ll> BackendTypes for CodegenCx<'ll, '_> {
a1dfa0c6 85 type Value = &'ll Value;
29967ef6 86 // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`.
e74abb32
XL
87 type Function = &'ll Value;
88
a1dfa0c6
XL
89 type BasicBlock = &'ll BasicBlock;
90 type Type = &'ll Type;
91 type Funclet = Funclet<'ll>;
1a4d82fc 92
a1dfa0c6 93 type DIScope = &'ll llvm::debuginfo::DIScope;
29967ef6 94 type DILocation = &'ll llvm::debuginfo::DILocation;
74b04a01 95 type DIVariable = &'ll llvm::debuginfo::DIVariable;
1a4d82fc
JJ
96}
97
a2a8927a 98impl<'ll> CodegenCx<'ll, '_> {
532ac7d7 99 pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
ba9703b0 100 unsafe { llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint) }
532ac7d7
XL
101 }
102
103 pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
ba9703b0 104 unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
532ac7d7
XL
105 }
106
107 pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
108 bytes_in_context(self.llcx, bytes)
109 }
110
532ac7d7
XL
111 pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
112 unsafe {
113 assert_eq!(idx as c_uint as u64, idx);
064997fb 114 let r = llvm::LLVMGetAggregateElement(v, idx as c_uint).unwrap();
532ac7d7 115
dfeec247 116 debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
532ac7d7
XL
117
118 r
119 }
120 }
532ac7d7
XL
121}
122
a2a8927a 123impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
a1dfa0c6 124 fn const_null(&self, t: &'ll Type) -> &'ll Value {
dfeec247 125 unsafe { llvm::LLVMConstNull(t) }
1a4d82fc 126 }
1a4d82fc 127
a1dfa0c6 128 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
dfeec247 129 unsafe { llvm::LLVMGetUndef(t) }
ea8adc8c 130 }
ea8adc8c 131
a1dfa0c6 132 fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
dfeec247 133 unsafe { llvm::LLVMConstInt(t, i as u64, True) }
1a4d82fc 134 }
1a4d82fc 135
a1dfa0c6 136 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
dfeec247 137 unsafe { llvm::LLVMConstInt(t, i, False) }
32a655c1 138 }
c34b1796 139
a1dfa0c6
XL
140 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
141 unsafe {
142 let words = [u as u64, (u >> 64) as u64];
143 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
144 }
145 }
1a4d82fc 146
a1dfa0c6
XL
147 fn const_bool(&self, val: bool) -> &'ll Value {
148 self.const_uint(self.type_i1(), val as u64)
1a4d82fc
JJ
149 }
150
5e7ed085
FG
151 fn const_i16(&self, i: i16) -> &'ll Value {
152 self.const_int(self.type_i16(), i as i64)
153 }
154
a1dfa0c6
XL
155 fn const_i32(&self, i: i32) -> &'ll Value {
156 self.const_int(self.type_i32(), i as i64)
157 }
1a4d82fc 158
a1dfa0c6
XL
159 fn const_u32(&self, i: u32) -> &'ll Value {
160 self.const_uint(self.type_i32(), i as u64)
161 }
1a4d82fc 162
a1dfa0c6
XL
163 fn const_u64(&self, i: u64) -> &'ll Value {
164 self.const_uint(self.type_i64(), i)
165 }
1a4d82fc 166
a1dfa0c6
XL
167 fn const_usize(&self, i: u64) -> &'ll Value {
168 let bit_size = self.data_layout().pointer_size.bits();
169 if bit_size < 64 {
170 // make sure it doesn't overflow
dfeec247 171 assert!(i < (1 << bit_size));
1a4d82fc
JJ
172 }
173
a1dfa0c6 174 self.const_uint(self.isize_ty, i)
1a4d82fc 175 }
1a4d82fc 176
a1dfa0c6
XL
177 fn const_u8(&self, i: u8) -> &'ll Value {
178 self.const_uint(self.type_i8(), i as u64)
179 }
ff7c6d11 180
416331ca
XL
181 fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
182 unsafe { llvm::LLVMConstReal(t, val) }
183 }
184
064997fb
FG
185 fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
186 let str_global = *self
187 .const_str_cache
188 .borrow_mut()
189 .raw_entry_mut()
190 .from_key(s)
191 .or_insert_with(|| {
192 let sc = self.const_bytes(s.as_bytes());
193 let sym = self.generate_local_symbol_name("str");
194 let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
195 bug!("symbol `{}` is already defined", sym);
196 });
197 unsafe {
198 llvm::LLVMSetInitializer(g, sc);
199 llvm::LLVMSetGlobalConstant(g, True);
200 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
201 }
202 (s.to_owned(), g)
203 })
204 .1;
205 let len = s.len();
dfeec247 206 let cs = consts::ptrcast(
5e7ed085 207 str_global,
f035d41b 208 self.type_ptr_to(self.layout_of(self.tcx.types.str_).llvm_type(self)),
dfeec247 209 );
e74abb32
XL
210 (cs, self.const_usize(len as u64))
211 }
212
dfeec247 213 fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
a1dfa0c6 214 struct_in_context(self.llcx, elts, packed)
85aaf69f 215 }
85aaf69f 216
e74abb32 217 fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
f2b60f7d
FG
218 try_as_const_integral(v).and_then(|v| unsafe {
219 let mut i = 0u64;
220 let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
221 success.then_some(i)
222 })
0531ce1d 223 }
0531ce1d 224
a1dfa0c6 225 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
e74abb32
XL
226 try_as_const_integral(v).and_then(|v| unsafe {
227 let (mut lo, mut hi) = (0u64, 0u64);
dfeec247 228 let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
60c5eb7d 229 success.then_some(hi_lo_to_u128(lo, hi))
e74abb32 230 })
c34b1796 231 }
c34b1796 232
c295e0f8 233 fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
04454e1e 234 let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
a1dfa0c6 235 match cv {
29967ef6 236 Scalar::Int(int) => {
04454e1e 237 let data = int.assert_bits(layout.size(self));
dc9dc135 238 let llval = self.const_uint_big(self.type_ix(bitsize), data);
04454e1e 239 if layout.primitive() == Pointer {
a1dfa0c6
XL
240 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
241 } else {
242 self.const_bitcast(llval, llty)
243 }
dfeec247 244 }
136023e0
XL
245 Scalar::Ptr(ptr, _size) => {
246 let (alloc_id, offset) = ptr.into_parts();
247 let (base_addr, base_addr_space) = match self.tcx.global_alloc(alloc_id) {
f9f354fc 248 GlobalAlloc::Memory(alloc) => {
a1dfa0c6 249 let init = const_alloc_to_llvm(self, alloc);
5e7ed085 250 let alloc = alloc.inner();
ba9703b0
XL
251 let value = match alloc.mutability {
252 Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
253 _ => self.static_addr_of(init, alloc.align, None),
254 };
255 if !self.sess().fewer_names() {
136023e0 256 llvm::set_value_name(value, format!("{:?}", alloc_id).as_bytes());
a1dfa0c6 257 }
3dfed10e 258 (value, AddressSpace::DATA)
a1dfa0c6 259 }
3dfed10e
XL
260 GlobalAlloc::Function(fn_instance) => (
261 self.get_fn_addr(fn_instance.polymorphize(self.tcx)),
262 self.data_layout().instruction_address_space,
263 ),
064997fb
FG
264 GlobalAlloc::VTable(ty, trait_ref) => {
265 let alloc = self
266 .tcx
267 .global_alloc(self.tcx.vtable_allocation((ty, trait_ref)))
268 .unwrap_memory();
269 let init = const_alloc_to_llvm(self, alloc);
270 let value = self.static_addr_of(init, alloc.inner().align, None);
271 (value, AddressSpace::DATA)
272 }
f9f354fc 273 GlobalAlloc::Static(def_id) => {
48663c56 274 assert!(self.tcx.is_static(def_id));
f9f354fc 275 assert!(!self.tcx.is_thread_local_static(def_id));
3dfed10e 276 (self.get_static(def_id), AddressSpace::DATA)
a1dfa0c6 277 }
a1dfa0c6 278 };
dfeec247 279 let llval = unsafe {
94222f64
XL
280 llvm::LLVMRustConstInBoundsGEP2(
281 self.type_i8(),
3dfed10e 282 self.const_bitcast(base_addr, self.type_i8p_ext(base_addr_space)),
136023e0 283 &self.const_usize(offset.bytes()),
dfeec247
XL
284 1,
285 )
286 };
04454e1e 287 if layout.primitive() != Pointer {
a1dfa0c6
XL
288 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
289 } else {
290 self.const_bitcast(llval, llty)
291 }
292 }
1a4d82fc 293 }
a1dfa0c6 294 }
e9174d1e 295
5e7ed085 296 fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value {
136023e0
XL
297 const_alloc_to_llvm(self, alloc)
298 }
299
a1dfa0c6
XL
300 fn from_const_alloc(
301 &self,
ba9703b0 302 layout: TyAndLayout<'tcx>,
5e7ed085 303 alloc: ConstAllocation<'tcx>,
a1dfa0c6
XL
304 offset: Size,
305 ) -> PlaceRef<'tcx, &'ll Value> {
5e7ed085
FG
306 let alloc_align = alloc.inner().align;
307 assert_eq!(alloc_align, layout.align.abi);
e1599b0c
XL
308 let llty = self.type_ptr_to(layout.llvm_type(self));
309 let llval = if layout.size == Size::ZERO {
5e7ed085 310 let llval = self.const_usize(alloc_align.bytes());
e1599b0c
XL
311 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
312 } else {
313 let init = const_alloc_to_llvm(self, alloc);
5e7ed085 314 let base_addr = self.static_addr_of(init, alloc_align, None);
e1599b0c 315
dfeec247 316 let llval = unsafe {
94222f64
XL
317 llvm::LLVMRustConstInBoundsGEP2(
318 self.type_i8(),
dfeec247
XL
319 self.const_bitcast(base_addr, self.type_i8p()),
320 &self.const_usize(offset.bytes()),
321 1,
322 )
323 };
e1599b0c
XL
324 self.const_bitcast(llval, llty)
325 };
326 PlaceRef::new_sized(llval, layout)
a1dfa0c6 327 }
92a42be0 328
a1dfa0c6
XL
329 fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
330 consts::ptrcast(val, ty)
92a42be0
SL
331 }
332}
333
5869c6ff 334/// Get the [LLVM type][Type] of a [`Value`].
ba9703b0 335pub fn val_ty(v: &Value) -> &Type {
dfeec247 336 unsafe { llvm::LLVMTypeOf(v) }
92a42be0
SL
337}
338
a2a8927a 339pub fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
a1dfa0c6
XL
340 unsafe {
341 let ptr = bytes.as_ptr() as *const c_char;
ba9703b0 342 llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True)
92a42be0
SL
343 }
344}
476ff2be 345
a2a8927a
XL
346pub fn struct_in_context<'ll>(
347 llcx: &'ll llvm::Context,
348 elts: &[&'ll Value],
349 packed: bool,
350) -> &'ll Value {
a1dfa0c6 351 unsafe {
dfeec247 352 llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), elts.len() as c_uint, packed as Bool)
476ff2be
SL
353 }
354}
a1dfa0c6
XL
355
356#[inline]
357fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
358 ((hi as u128) << 64) | (lo as u128)
359}
e74abb32 360
ba9703b0 361fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
dfeec247 362 unsafe { llvm::LLVMIsAConstantInt(v) }
e74abb32 363}
f2b60f7d
FG
364
365pub(crate) fn get_dllimport<'tcx>(
366 tcx: TyCtxt<'tcx>,
367 id: DefId,
368 name: &str,
369) -> Option<&'tcx DllImport> {
370 tcx.native_library(id)
371 .map(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
372 .flatten()
373}
374
375pub(crate) fn is_mingw_gnu_toolchain(target: &Target) -> bool {
376 target.vendor == "pc" && target.os == "windows" && target.env == "gnu" && target.abi.is_empty()
377}
378
379pub(crate) fn i686_decorated_name(
380 dll_import: &DllImport,
381 mingw: bool,
382 disable_name_mangling: bool,
383) -> String {
384 let name = dll_import.name.as_str();
385
386 let (add_prefix, add_suffix) = match dll_import.import_name_type {
387 Some(PeImportNameType::NoPrefix) => (false, true),
388 Some(PeImportNameType::Undecorated) => (false, false),
389 _ => (true, true),
390 };
391
392 // Worst case: +1 for disable name mangling, +1 for prefix, +4 for suffix (@@__).
393 let mut decorated_name = String::with_capacity(name.len() + 6);
394
395 if disable_name_mangling {
396 // LLVM uses a binary 1 ('\x01') prefix to a name to indicate that mangling needs to be disabled.
397 decorated_name.push('\x01');
398 }
399
400 let prefix = if add_prefix && dll_import.is_fn {
401 match dll_import.calling_convention {
402 DllCallingConvention::C | DllCallingConvention::Vectorcall(_) => None,
403 DllCallingConvention::Stdcall(_) => (!mingw
404 || dll_import.import_name_type == Some(PeImportNameType::Decorated))
405 .then_some('_'),
406 DllCallingConvention::Fastcall(_) => Some('@'),
407 }
408 } else if !dll_import.is_fn && !mingw {
409 // For static variables, prefix with '_' on MSVC.
410 Some('_')
411 } else {
412 None
413 };
414 if let Some(prefix) = prefix {
415 decorated_name.push(prefix);
416 }
417
418 decorated_name.push_str(name);
419
420 if add_suffix && dll_import.is_fn {
421 match dll_import.calling_convention {
422 DllCallingConvention::C => {}
423 DllCallingConvention::Stdcall(arg_list_size)
424 | DllCallingConvention::Fastcall(arg_list_size) => {
425 write!(&mut decorated_name, "@{}", arg_list_size).unwrap();
426 }
427 DllCallingConvention::Vectorcall(arg_list_size) => {
428 write!(&mut decorated_name, "@@{}", arg_list_size).unwrap();
429 }
430 }
431 }
432
433 decorated_name
434}