]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/type_.rs
Kill RacyCell in favor of marking SyncSender explicitly Send.
[rust.git] / src / librustc_trans / trans / type_.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 #![allow(non_upper_case_globals)]
12
13 use llvm;
14 use llvm::{TypeRef, Bool, False, True, TypeKind, ValueRef};
15 use llvm::{Float, Double, X86_FP80, PPC_FP128, FP128};
16
17 use trans::context::CrateContext;
18 use util::nodemap::FnvHashMap;
19
20 use syntax::ast;
21
22 use std::ffi::CString;
23 use std::mem;
24 use std::cell::RefCell;
25 use std::iter::repeat;
26
27 use libc::c_uint;
28
29 #[derive(Clone, Copy, PartialEq, Show)]
30 #[repr(C)]
31 pub struct Type {
32     rf: TypeRef
33 }
34
35 macro_rules! ty {
36     ($e:expr) => ( Type::from_ref(unsafe { $e }))
37 }
38
39 /// Wrapper for LLVM TypeRef
40 impl Type {
41     #[inline(always)]
42     pub fn from_ref(r: TypeRef) -> Type {
43         Type {
44             rf: r
45         }
46     }
47
48     #[inline(always)] // So it doesn't kill --opt-level=0 builds of the compiler
49     pub fn to_ref(&self) -> TypeRef {
50         self.rf
51     }
52
53     pub fn void(ccx: &CrateContext) -> Type {
54         ty!(llvm::LLVMVoidTypeInContext(ccx.llcx()))
55     }
56
57     pub fn nil(ccx: &CrateContext) -> Type {
58         Type::empty_struct(ccx)
59     }
60
61     pub fn metadata(ccx: &CrateContext) -> Type {
62         ty!(llvm::LLVMMetadataTypeInContext(ccx.llcx()))
63     }
64
65     pub fn i1(ccx: &CrateContext) -> Type {
66         ty!(llvm::LLVMInt1TypeInContext(ccx.llcx()))
67     }
68
69     pub fn i8(ccx: &CrateContext) -> Type {
70         ty!(llvm::LLVMInt8TypeInContext(ccx.llcx()))
71     }
72
73     pub fn i16(ccx: &CrateContext) -> Type {
74         ty!(llvm::LLVMInt16TypeInContext(ccx.llcx()))
75     }
76
77     pub fn i32(ccx: &CrateContext) -> Type {
78         ty!(llvm::LLVMInt32TypeInContext(ccx.llcx()))
79     }
80
81     pub fn i64(ccx: &CrateContext) -> Type {
82         ty!(llvm::LLVMInt64TypeInContext(ccx.llcx()))
83     }
84
85     // Creates an integer type with the given number of bits, e.g. i24
86     pub fn ix(ccx: &CrateContext, num_bits: u64) -> Type {
87         ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), num_bits as c_uint))
88     }
89
90     pub fn f32(ccx: &CrateContext) -> Type {
91         ty!(llvm::LLVMFloatTypeInContext(ccx.llcx()))
92     }
93
94     pub fn f64(ccx: &CrateContext) -> Type {
95         ty!(llvm::LLVMDoubleTypeInContext(ccx.llcx()))
96     }
97
98     pub fn bool(ccx: &CrateContext) -> Type {
99         Type::i8(ccx)
100     }
101
102     pub fn char(ccx: &CrateContext) -> Type {
103         Type::i32(ccx)
104     }
105
106     pub fn i8p(ccx: &CrateContext) -> Type {
107         Type::i8(ccx).ptr_to()
108     }
109
110     pub fn int(ccx: &CrateContext) -> Type {
111         match &ccx.tcx().sess.target.target.target_pointer_width[] {
112             "32" => Type::i32(ccx),
113             "64" => Type::i64(ccx),
114             tws => panic!("Unsupported target word size for int: {}", tws),
115         }
116     }
117
118     pub fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type {
119         match t {
120             ast::TyIs(_) => ccx.int_type(),
121             ast::TyI8 => Type::i8(ccx),
122             ast::TyI16 => Type::i16(ccx),
123             ast::TyI32 => Type::i32(ccx),
124             ast::TyI64 => Type::i64(ccx)
125         }
126     }
127
128     pub fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type {
129         match t {
130             ast::TyUs(_) => ccx.int_type(),
131             ast::TyU8 => Type::i8(ccx),
132             ast::TyU16 => Type::i16(ccx),
133             ast::TyU32 => Type::i32(ccx),
134             ast::TyU64 => Type::i64(ccx)
135         }
136     }
137
138     pub fn float_from_ty(ccx: &CrateContext, t: ast::FloatTy) -> Type {
139         match t {
140             ast::TyF32 => Type::f32(ccx),
141             ast::TyF64 => Type::f64(ccx),
142         }
143     }
144
145     pub fn func(args: &[Type], ret: &Type) -> Type {
146         let vec : &[TypeRef] = unsafe { mem::transmute(args) };
147         ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(),
148                                    args.len() as c_uint, False))
149     }
150
151     pub fn variadic_func(args: &[Type], ret: &Type) -> Type {
152         let vec : &[TypeRef] = unsafe { mem::transmute(args) };
153         ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(),
154                                    args.len() as c_uint, True))
155     }
156
157     pub fn struct_(ccx: &CrateContext, els: &[Type], packed: bool) -> Type {
158         let els : &[TypeRef] = unsafe { mem::transmute(els) };
159         ty!(llvm::LLVMStructTypeInContext(ccx.llcx(), els.as_ptr(),
160                                           els.len() as c_uint,
161                                           packed as Bool))
162     }
163
164     pub fn named_struct(ccx: &CrateContext, name: &str) -> Type {
165         let name = CString::from_slice(name.as_bytes());
166         ty!(llvm::LLVMStructCreateNamed(ccx.llcx(), name.as_ptr()))
167     }
168
169     pub fn empty_struct(ccx: &CrateContext) -> Type {
170         Type::struct_(ccx, &[], false)
171     }
172
173     pub fn vtable(ccx: &CrateContext) -> Type {
174         Type::array(&Type::i8p(ccx).ptr_to(), 1)
175     }
176
177     pub fn generic_glue_fn(cx: &CrateContext) -> Type {
178         match cx.tn().find_type("glue_fn") {
179             Some(ty) => return ty,
180             None => ()
181         }
182
183         let ty = Type::glue_fn(cx, Type::i8p(cx));
184         cx.tn().associate_type("glue_fn", &ty);
185
186         ty
187     }
188
189     pub fn glue_fn(ccx: &CrateContext, t: Type) -> Type {
190         Type::func(&[t], &Type::void(ccx))
191     }
192
193     pub fn tydesc(ccx: &CrateContext, str_slice_ty: Type) -> Type {
194         let mut tydesc = Type::named_struct(ccx, "tydesc");
195         let glue_fn_ty = Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to();
196
197         let int_ty = Type::int(ccx);
198
199         // Must mirror:
200         //
201         // std::unstable::intrinsics::TyDesc
202
203         let elems = [int_ty,     // size
204                      int_ty,     // align
205                      glue_fn_ty, // drop
206                      str_slice_ty]; // name
207         tydesc.set_struct_body(&elems, false);
208
209         tydesc
210     }
211
212     pub fn array(ty: &Type, len: u64) -> Type {
213         ty!(llvm::LLVMRustArrayType(ty.to_ref(), len))
214     }
215
216     pub fn vector(ty: &Type, len: u64) -> Type {
217         ty!(llvm::LLVMVectorType(ty.to_ref(), len as c_uint))
218     }
219
220     pub fn vec(ccx: &CrateContext, ty: &Type) -> Type {
221         Type::struct_(ccx,
222             &[Type::array(ty, 0), Type::int(ccx)],
223         false)
224     }
225
226     pub fn opaque_vec(ccx: &CrateContext) -> Type {
227         Type::vec(ccx, &Type::i8(ccx))
228     }
229
230     // The box pointed to by @T.
231     pub fn at_box(ccx: &CrateContext, ty: Type) -> Type {
232         Type::struct_(ccx, &[
233             ccx.int_type(), Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to(),
234             Type::i8p(ccx), Type::i8p(ccx), ty
235         ], false)
236     }
237
238     pub fn vtable_ptr(ccx: &CrateContext) -> Type {
239         Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to().ptr_to()
240     }
241
242     pub fn opaque_trait(ccx: &CrateContext) -> Type {
243         Type::struct_(ccx, &[Type::opaque_trait_data(ccx).ptr_to(), Type::vtable_ptr(ccx)], false)
244     }
245
246     pub fn opaque_trait_data(ccx: &CrateContext) -> Type {
247         Type::i8(ccx)
248     }
249
250     pub fn kind(&self) -> TypeKind {
251         unsafe {
252             llvm::LLVMGetTypeKind(self.to_ref())
253         }
254     }
255
256     pub fn set_struct_body(&mut self, els: &[Type], packed: bool) {
257         unsafe {
258             let vec : &[TypeRef] = mem::transmute(els);
259             llvm::LLVMStructSetBody(self.to_ref(), vec.as_ptr(),
260                                     els.len() as c_uint, packed as Bool)
261         }
262     }
263
264     pub fn ptr_to(&self) -> Type {
265         ty!(llvm::LLVMPointerType(self.to_ref(), 0))
266     }
267
268     pub fn is_aggregate(&self) -> bool {
269         match self.kind() {
270             TypeKind::Struct | TypeKind::Array => true,
271             _ =>  false
272         }
273     }
274
275     pub fn is_packed(&self) -> bool {
276         unsafe {
277             llvm::LLVMIsPackedStruct(self.to_ref()) == True
278         }
279     }
280
281     pub fn element_type(&self) -> Type {
282         unsafe {
283             Type::from_ref(llvm::LLVMGetElementType(self.to_ref()))
284         }
285     }
286
287     /// Return the number of elements in `self` if it is a LLVM vector type.
288     pub fn vector_length(&self) -> uint {
289         unsafe {
290             llvm::LLVMGetVectorSize(self.to_ref()) as uint
291         }
292     }
293
294     pub fn array_length(&self) -> uint {
295         unsafe {
296             llvm::LLVMGetArrayLength(self.to_ref()) as uint
297         }
298     }
299
300     pub fn field_types(&self) -> Vec<Type> {
301         unsafe {
302             let n_elts = llvm::LLVMCountStructElementTypes(self.to_ref()) as uint;
303             if n_elts == 0 {
304                 return Vec::new();
305             }
306             let mut elts: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_elts).collect();
307             llvm::LLVMGetStructElementTypes(self.to_ref(),
308                                             elts.as_mut_ptr() as *mut TypeRef);
309             elts
310         }
311     }
312
313     pub fn return_type(&self) -> Type {
314         ty!(llvm::LLVMGetReturnType(self.to_ref()))
315     }
316
317     pub fn func_params(&self) -> Vec<Type> {
318         unsafe {
319             let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as uint;
320             let mut args: Vec<_> = repeat(Type { rf: 0 as TypeRef }).take(n_args).collect();
321             llvm::LLVMGetParamTypes(self.to_ref(),
322                                     args.as_mut_ptr() as *mut TypeRef);
323             args
324         }
325     }
326
327     pub fn float_width(&self) -> uint {
328         match self.kind() {
329             Float => 32,
330             Double => 64,
331             X86_FP80 => 80,
332             FP128 | PPC_FP128 => 128,
333             _ => panic!("llvm_float_width called on a non-float type")
334         }
335     }
336
337     /// Retrieve the bit width of the integer type `self`.
338     pub fn int_width(&self) -> u64 {
339         unsafe {
340             llvm::LLVMGetIntTypeWidth(self.to_ref()) as u64
341         }
342     }
343 }
344
345
346 /* Memory-managed object interface to type handles. */
347
348 pub struct TypeNames {
349     named_types: RefCell<FnvHashMap<String, TypeRef>>,
350 }
351
352 impl TypeNames {
353     pub fn new() -> TypeNames {
354         TypeNames {
355             named_types: RefCell::new(FnvHashMap())
356         }
357     }
358
359     pub fn associate_type(&self, s: &str, t: &Type) {
360         assert!(self.named_types.borrow_mut().insert(s.to_string(),
361                                                      t.to_ref()).is_none());
362     }
363
364     pub fn find_type(&self, s: &str) -> Option<Type> {
365         self.named_types.borrow().get(s).map(|x| Type::from_ref(*x))
366     }
367
368     pub fn type_to_string(&self, ty: Type) -> String {
369         llvm::build_string(|s| unsafe {
370                 llvm::LLVMWriteTypeToString(ty.to_ref(), s);
371             }).expect("non-UTF8 type description from LLVM")
372     }
373
374     pub fn types_to_str(&self, tys: &[Type]) -> String {
375         let strs: Vec<String> = tys.iter().map(|t| self.type_to_string(*t)).collect();
376         format!("[{}]", strs.connect(","))
377     }
378
379     pub fn val_to_string(&self, val: ValueRef) -> String {
380         llvm::build_string(|s| unsafe {
381                 llvm::LLVMWriteValueToString(val, s);
382             }).expect("nun-UTF8 value description from LLVM")
383     }
384 }