]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/type_of.rs
doc: remove incomplete sentence
[rust.git] / src / librustc_trans / trans / type_of.rs
1 // Copyright 2012-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_camel_case_types)]
12
13 pub use self::named_ty::*;
14
15 use middle::subst;
16 use trans::adt;
17 use trans::common::*;
18 use trans::foreign;
19 use trans::machine;
20 use middle::ty::{mod, Ty};
21 use util::ppaux;
22 use util::ppaux::Repr;
23
24 use trans::type_::Type;
25
26 use std::num::Int;
27 use syntax::abi;
28 use syntax::ast;
29
30 // LLVM doesn't like objects that are too big. Issue #17913
31 fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
32                                                 llet: Type,
33                                                 size: machine::llsize,
34                                                 scapegoat: Ty<'tcx>) {
35     let esz = machine::llsize_of_alloc(ccx, llet);
36     match esz.checked_mul(size) {
37         Some(n) if n < ccx.obj_size_bound() => {}
38         _ => { ccx.report_overbig_object(scapegoat) }
39     }
40 }
41
42 pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
43                                  arg_ty: Ty<'tcx>) -> bool {
44     !type_is_immediate(ccx, arg_ty)
45 }
46
47 pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
48                                     ty: Ty<'tcx>) -> bool {
49     !type_is_immediate(ccx, ty)
50 }
51
52 pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
53                                       arg_ty: Ty<'tcx>) -> Type {
54     let llty = arg_type_of(ccx, arg_ty);
55     if arg_is_indirect(ccx, arg_ty) {
56         llty.ptr_to()
57     } else {
58         llty
59     }
60 }
61
62 /// Yields the types of the "real" arguments for this function. For most
63 /// functions, these are simply the types of the arguments. For functions with
64 /// the `RustCall` ABI, however, this untuples the arguments of the function.
65 pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
66                                                 inputs: &[Ty<'tcx>],
67                                                 abi: abi::Abi)
68                                                 -> Vec<Ty<'tcx>> {
69     if abi != abi::RustCall {
70         return inputs.iter().map(|x| (*x).clone()).collect()
71     }
72
73     if inputs.len() == 0 {
74         return Vec::new()
75     }
76
77     let mut result = Vec::new();
78     for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() {
79         if i < inputs.len() - 1 {
80             result.push(arg_prior_to_tuple);
81         }
82     }
83
84     match inputs[inputs.len() - 1].sty {
85         ty::ty_tup(ref tupled_arguments) => {
86             debug!("untuple_arguments_if_necessary(): untupling arguments");
87             for &tupled_argument in tupled_arguments.iter() {
88                 result.push(tupled_argument);
89             }
90         }
91         _ => {
92             ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \
93                                 is neither a tuple nor unit")
94         }
95     }
96
97     result
98 }
99
100 pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
101                                  llenvironment_type: Option<Type>,
102                                  inputs: &[Ty<'tcx>],
103                                  output: ty::FnOutput<'tcx>,
104                                  abi: abi::Abi)
105                                  -> Type {
106     let mut atys: Vec<Type> = Vec::new();
107
108     // First, munge the inputs, if this has the `rust-call` ABI.
109     let inputs = untuple_arguments_if_necessary(cx, inputs, abi);
110
111     // Arg 0: Output pointer.
112     // (if the output type is non-immediate)
113     let lloutputtype = match output {
114         ty::FnConverging(output) => {
115             let use_out_pointer = return_uses_outptr(cx, output);
116             let lloutputtype = arg_type_of(cx, output);
117             // Use the output as the actual return value if it's immediate.
118             if use_out_pointer {
119                 atys.push(lloutputtype.ptr_to());
120                 Type::void(cx)
121             } else if return_type_is_void(cx, output) {
122                 Type::void(cx)
123             } else {
124                 lloutputtype
125             }
126         }
127         ty::FnDiverging => Type::void(cx)
128     };
129
130     // Arg 1: Environment
131     match llenvironment_type {
132         None => {}
133         Some(llenvironment_type) => atys.push(llenvironment_type),
134     }
135
136     // ... then explicit args.
137     let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty));
138     atys.extend(input_tys);
139
140     Type::func(atys[], &lloutputtype)
141 }
142
143 // Given a function type and a count of ty params, construct an llvm type
144 pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type {
145     match fty.sty {
146         ty::ty_closure(ref f) => {
147             type_of_rust_fn(cx,
148                             Some(Type::i8p(cx)),
149                             f.sig.0.inputs.as_slice(),
150                             f.sig.0.output,
151                             f.abi)
152         }
153         ty::ty_bare_fn(_, ref f) => {
154             // FIXME(#19925) once fn item types are
155             // zero-sized, we'll need to do something here
156             if f.abi == abi::Rust || f.abi == abi::RustCall {
157                 type_of_rust_fn(cx,
158                                 None,
159                                 f.sig.0.inputs.as_slice(),
160                                 f.sig.0.output,
161                                 f.abi)
162             } else {
163                 foreign::lltype_for_foreign_fn(cx, fty)
164             }
165         }
166         _ => {
167             cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
168         }
169     }
170 }
171
172 // A "sizing type" is an LLVM type, the size and alignment of which are
173 // guaranteed to be equivalent to what you would get out of `type_of()`. It's
174 // useful because:
175 //
176 // (1) It may be cheaper to compute the sizing type than the full type if all
177 //     you're interested in is the size and/or alignment;
178 //
179 // (2) It won't make any recursive calls to determine the structure of the
180 //     type behind pointers. This can help prevent infinite loops for
181 //     recursive types. For example, enum types rely on this behavior.
182
183 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
184     match cx.llsizingtypes().borrow().get(&t).cloned() {
185         Some(t) => return t,
186         None => ()
187     }
188
189     let llsizingty = match t.sty {
190         _ if !lltype_is_sized(cx.tcx(), t) => {
191             cx.sess().bug(format!("trying to take the sizing type of {}, an unsized type",
192                                   ppaux::ty_to_string(cx.tcx(), t))[])
193         }
194
195         ty::ty_bool => Type::bool(cx),
196         ty::ty_char => Type::char(cx),
197         ty::ty_int(t) => Type::int_from_ty(cx, t),
198         ty::ty_uint(t) => Type::uint_from_ty(cx, t),
199         ty::ty_float(t) => Type::float_from_ty(cx, t),
200
201         ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
202             if type_is_sized(cx.tcx(), ty) {
203                 Type::i8p(cx)
204             } else {
205                 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
206             }
207         }
208
209         ty::ty_bare_fn(..) => Type::i8p(cx),
210         ty::ty_closure(..) => Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false),
211
212         ty::ty_vec(ty, Some(size)) => {
213             let llty = sizing_type_of(cx, ty);
214             let size = size as u64;
215             ensure_array_fits_in_address_space(cx, llty, size, t);
216             Type::array(&llty, size)
217         }
218
219         ty::ty_tup(ref tys) if tys.is_empty() => {
220             Type::nil(cx)
221         }
222
223         ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => {
224             let repr = adt::represent_type(cx, t);
225             adt::sizing_type_of(cx, &*repr, false)
226         }
227
228         ty::ty_struct(..) => {
229             if ty::type_is_simd(cx.tcx(), t) {
230                 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
231                 let n = ty::simd_size(cx.tcx(), t) as u64;
232                 ensure_array_fits_in_address_space(cx, llet, n, t);
233                 Type::vector(&llet, n)
234             } else {
235                 let repr = adt::represent_type(cx, t);
236                 adt::sizing_type_of(cx, &*repr, false)
237             }
238         }
239
240         ty::ty_open(_) => {
241             Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
242         }
243
244         ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
245             cx.sess().bug(format!("fictitious type {} in sizing_type_of()",
246                                   ppaux::ty_to_string(cx.tcx(), t))[])
247         }
248         ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
249     };
250
251     cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
252     llsizingty
253 }
254
255 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
256     if ty::type_is_bool(t) {
257         Type::i1(cx)
258     } else {
259         type_of(cx, t)
260     }
261 }
262
263 // NB: If you update this, be sure to update `sizing_type_of()` as well.
264 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
265     fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
266         // It is possible to end up here with a sized type. This happens with a
267         // struct which might be unsized, but is monomorphised to a sized type.
268         // In this case we'll fake a fat pointer with no unsize info (we use 0).
269         // However, its still a fat pointer, so we need some type use.
270         if type_is_sized(cx.tcx(), t) {
271             return Type::i8p(cx);
272         }
273
274         match unsized_part_of_type(cx.tcx(), t).sty {
275             ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyU),
276             ty::ty_trait(_) => Type::vtable_ptr(cx),
277             _ => panic!("Unexpected type returned from unsized_part_of_type : {}",
278                        t.repr(cx.tcx()))
279         }
280     }
281
282     // Check the cache.
283     match cx.lltypes().borrow().get(&t) {
284         Some(&llty) => return llty,
285         None => ()
286     }
287
288     debug!("type_of {} {}", t.repr(cx.tcx()), t.sty);
289
290     // Replace any typedef'd types with their equivalent non-typedef
291     // type. This ensures that all LLVM nominal types that contain
292     // Rust types are defined as the same LLVM types.  If we don't do
293     // this then, e.g. `Option<{myfield: bool}>` would be a different
294     // type than `Option<myrec>`.
295     let t_norm = ty::normalize_ty(cx.tcx(), t);
296
297     if t != t_norm {
298         let llty = type_of(cx, t_norm);
299         debug!("--> normalized {} {} to {} {} llty={}",
300                 t.repr(cx.tcx()),
301                 t,
302                 t_norm.repr(cx.tcx()),
303                 t_norm,
304                 cx.tn().type_to_string(llty));
305         cx.lltypes().borrow_mut().insert(t, llty);
306         return llty;
307     }
308
309     let mut llty = match t.sty {
310       ty::ty_bool => Type::bool(cx),
311       ty::ty_char => Type::char(cx),
312       ty::ty_int(t) => Type::int_from_ty(cx, t),
313       ty::ty_uint(t) => Type::uint_from_ty(cx, t),
314       ty::ty_float(t) => Type::float_from_ty(cx, t),
315       ty::ty_enum(did, ref substs) => {
316           // Only create the named struct, but don't fill it in. We
317           // fill it in *after* placing it into the type cache. This
318           // avoids creating more than one copy of the enum when one
319           // of the enum's variants refers to the enum itself.
320           let repr = adt::represent_type(cx, t);
321           let tps = substs.types.get_slice(subst::TypeSpace);
322           let name = llvm_type_name(cx, an_enum, did, tps);
323           adt::incomplete_type_of(cx, &*repr, name[])
324       }
325       ty::ty_unboxed_closure(did, _, ref substs) => {
326           // Only create the named struct, but don't fill it in. We
327           // fill it in *after* placing it into the type cache.
328           let repr = adt::represent_type(cx, t);
329           // Unboxed closures can have substitutions in all spaces
330           // inherited from their environment, so we use entire
331           // contents of the VecPerParamSpace to to construct the llvm
332           // name
333           let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
334           adt::incomplete_type_of(cx, &*repr, name[])
335       }
336
337       ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
338           match ty.sty {
339               ty::ty_str => {
340                   // This means we get a nicer name in the output (str is always
341                   // unsized).
342                   cx.tn().find_type("str_slice").unwrap()
343               }
344               ty::ty_trait(..) => Type::opaque_trait(cx),
345               _ if !type_is_sized(cx.tcx(), ty) => {
346                   let p_ty = type_of(cx, ty).ptr_to();
347                   Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false)
348               }
349               _ => type_of(cx, ty).ptr_to(),
350           }
351       }
352
353       ty::ty_vec(ty, Some(size)) => {
354           let size = size as u64;
355           let llty = type_of(cx, ty);
356           ensure_array_fits_in_address_space(cx, llty, size, t);
357           Type::array(&llty, size)
358       }
359       ty::ty_vec(ty, None) => {
360           type_of(cx, ty)
361       }
362
363       ty::ty_trait(..) => {
364           Type::opaque_trait_data(cx)
365       }
366
367       ty::ty_str => Type::i8(cx),
368
369       ty::ty_bare_fn(..) => {
370           type_of_fn_from_ty(cx, t).ptr_to()
371       }
372       ty::ty_closure(_) => {
373           let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
374           Type::struct_(cx, &[fn_ty, Type::i8p(cx)], false)
375       }
376       ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
377       ty::ty_tup(..) => {
378           let repr = adt::represent_type(cx, t);
379           adt::type_of(cx, &*repr)
380       }
381       ty::ty_struct(did, ref substs) => {
382           if ty::type_is_simd(cx.tcx(), t) {
383               let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
384               let n = ty::simd_size(cx.tcx(), t) as u64;
385               ensure_array_fits_in_address_space(cx, llet, n, t);
386               Type::vector(&llet, n)
387           } else {
388               // Only create the named struct, but don't fill it in. We fill it
389               // in *after* placing it into the type cache. This prevents
390               // infinite recursion with recursive struct types.
391               let repr = adt::represent_type(cx, t);
392               let tps = substs.types.get_slice(subst::TypeSpace);
393               let name = llvm_type_name(cx, a_struct, did, tps);
394               adt::incomplete_type_of(cx, &*repr, name[])
395           }
396       }
397
398       ty::ty_open(t) => match t.sty {
399           ty::ty_struct(..) => {
400               let p_ty = type_of(cx, t).ptr_to();
401               Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
402           }
403           ty::ty_vec(ty, None) => {
404               let p_ty = type_of(cx, ty).ptr_to();
405               Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
406           }
407           ty::ty_str => {
408               let p_ty = Type::i8p(cx);
409               Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
410           }
411           ty::ty_trait(..) => Type::opaque_trait(cx),
412           _ => cx.sess().bug(format!("ty_open with sized type: {}",
413                                      ppaux::ty_to_string(cx.tcx(), t))[])
414       },
415
416       ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
417       ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"),
418       ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
419       ty::ty_err(..) => cx.sess().bug("type_of with ty_err"),
420     };
421
422     debug!("--> mapped t={} {} to llty={}",
423             t.repr(cx.tcx()),
424             t,
425             cx.tn().type_to_string(llty));
426
427     cx.lltypes().borrow_mut().insert(t, llty);
428
429     // If this was an enum or struct, fill in the type now.
430     match t.sty {
431         ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..)
432                 if !ty::type_is_simd(cx.tcx(), t) => {
433             let repr = adt::represent_type(cx, t);
434             adt::finish_type_of(cx, &*repr, &mut llty);
435         }
436         _ => ()
437     }
438
439     return llty;
440 }
441
442 pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
443                           -> machine::llalign {
444     let llty = sizing_type_of(cx, t);
445     machine::llalign_of_min(cx, llty)
446 }
447
448 // Want refinements! (Or case classes, I guess
449 #[deriving(Copy)]
450 pub enum named_ty {
451     a_struct,
452     an_enum,
453     an_unboxed_closure,
454 }
455
456 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
457                                 what: named_ty,
458                                 did: ast::DefId,
459                                 tps: &[Ty<'tcx>])
460                                 -> String {
461     let name = match what {
462         a_struct => "struct",
463         an_enum => "enum",
464         an_unboxed_closure => return "closure".to_string(),
465     };
466
467     let base = ty::item_path_str(cx.tcx(), did);
468     let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
469     let tstr = if strings.is_empty() {
470         base
471     } else {
472         format!("{}<{}>", base, strings)
473     };
474
475     if did.krate == 0 {
476         format!("{}.{}", name, tstr)
477     } else {
478         format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
479     }
480 }
481
482 pub fn type_of_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, self_ty: Ty<'tcx>) -> Type {
483     let self_ty = type_of(ccx, self_ty).ptr_to();
484     Type::func(&[self_ty], &Type::void(ccx))
485 }