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