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.
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.
11 //! # Representation of Algebraic Data Types
13 //! This module determines how to represent enums, structs, and tuples
14 //! based on their monomorphized types; it is responsible both for
15 //! choosing a representation and translating basic operations on
16 //! values of those types. (Note: exporting the representations for
17 //! debuggers is handled in debuginfo.rs, not here.)
19 //! Note that the interface treats everything as a general case of an
20 //! enum, so structs/tuples/etc. have one pseudo-variant with
21 //! discriminant 0; i.e., as if they were a univariant enum.
23 //! Having everything in one place will enable improvements to data
24 //! structure representation; possibilities include:
26 //! - User-specified alignment (e.g., cacheline-aligning parts of
27 //! concurrently accessed data structures); LLVM can't represent this
28 //! directly, so we'd have to insert padding fields in any structure
29 //! that might contain one and adjust GEP indices accordingly. See
32 //! - Store nested enums' discriminants in the same word. Rather, if
33 //! some variants start with enums, and those enums representations
34 //! have unused alignment padding between discriminant and body, the
35 //! outer enum's discriminant can be stored there and those variants
36 //! can start at offset 0. Kind of fancy, and might need work to
37 //! make copies of the inner enum type cooperate, but it could help
38 //! with `Option` or `Result` wrapped around another enum.
40 //! - Tagged pointers would be neat, but given that any type can be
41 //! used unboxed and any field can have pointers (including mutable)
42 //! taken to it, implementing them for Rust seems difficult.
44 #![allow(unsigned_negation)]
46 pub use self::Repr::*;
50 use llvm::{ValueRef, True, IntEQ, IntNE};
51 use back::abi::FAT_PTR_ADDR;
53 use middle::ty::{self, Ty, ClosureTyper};
57 use syntax::attr::IntType;
61 use trans::cleanup::CleanupMethods;
64 use trans::debuginfo::DebugLoc;
66 use trans::monomorphize;
67 use trans::type_::Type;
69 use util::ppaux::ty_to_string;
71 type Hint = attr::ReprAttr;
74 #[derive(Eq, PartialEq, Debug)]
76 /// C-like enums; basically an int.
77 CEnum(IntType, Disr, Disr), // discriminant range (signedness based on the IntType)
78 /// Single-case variants, and structs/tuples/records.
80 /// Structs with destructors need a dynamic destroyedness flag to
81 /// avoid running the destructor too many times; this is included
82 /// in the `Struct` if present.
83 /// (The flag if nonzero, represents the initialization value to use;
84 /// if zero, then use no flag at all.)
85 Univariant(Struct<'tcx>, u8),
86 /// General-case enums: for each case there is a struct, and they
87 /// all start with a field for the discriminant.
89 /// Types with destructors need a dynamic destroyedness flag to
90 /// avoid running the destructor too many times; the last argument
91 /// indicates whether such a flag is present.
92 /// (The flag, if nonzero, represents the initialization value to use;
93 /// if zero, then use no flag at all.)
94 General(IntType, Vec<Struct<'tcx>>, u8),
95 /// Two cases distinguished by a nullable pointer: the case with discriminant
96 /// `nndiscr` must have single field which is known to be nonnull due to its type.
97 /// The other case is known to be zero sized. Hence we represent the enum
98 /// as simply a nullable pointer: if not null it indicates the `nndiscr` variant,
99 /// otherwise it indicates the other case.
103 nullfields: Vec<Ty<'tcx>>
105 /// Two cases distinguished by a nullable pointer: the case with discriminant
106 /// `nndiscr` is represented by the struct `nonnull`, where the `discrfield`th
107 /// field is known to be nonnull due to its type; if that field is null, then
108 /// it represents the other case, which is inhabited by at most one value
109 /// (and all other fields are undefined/unused).
111 /// For example, `std::option::Option` instantiated at a safe pointer type
112 /// is represented such that `None` is a null pointer and `Some` is the
113 /// identity function.
114 StructWrappedNullablePointer {
115 nonnull: Struct<'tcx>,
117 discrfield: DiscrField,
118 nullfields: Vec<Ty<'tcx>>,
122 /// For structs, and struct-like parts of anything fancier.
123 #[derive(Eq, PartialEq, Debug)]
124 pub struct Struct<'tcx> {
125 // If the struct is DST, then the size and alignment do not take into
126 // account the unsized fields of the struct.
131 pub fields: Vec<Ty<'tcx>>
134 /// Convenience for `represent_type`. There should probably be more or
135 /// these, for places in trans where the `Ty` isn't directly
137 pub fn represent_node<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
138 node: ast::NodeId) -> Rc<Repr<'tcx>> {
139 represent_type(bcx.ccx(), node_id_type(bcx, node))
142 /// Decides how to represent a given type.
143 pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
144 t: Ty<'tcx>) -> Rc<Repr<'tcx>> {
145 debug!("Representing: {}", ty_to_string(cx.tcx(), t));
146 match cx.adt_reprs().borrow().get(&t) {
147 Some(repr) => return repr.clone(),
151 let repr = Rc::new(represent_type_uncached(cx, t));
152 debug!("Represented as: {:?}", repr);
153 cx.adt_reprs().borrow_mut().insert(t, repr.clone());
157 macro_rules! repeat_u8_as_u32 {
158 ($name:expr) => { (($name as u32) << 24 |
159 ($name as u32) << 16 |
160 ($name as u32) << 8 |
163 macro_rules! repeat_u8_as_u64 {
164 ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
165 (repeat_u8_as_u32!($name) as u64)) }
168 pub const DTOR_NEEDED: u8 = 0xd4;
169 pub const DTOR_NEEDED_U32: u32 = repeat_u8_as_u32!(DTOR_NEEDED);
170 pub const DTOR_NEEDED_U64: u64 = repeat_u8_as_u64!(DTOR_NEEDED);
172 pub fn dtor_needed_usize(ccx: &CrateContext) -> usize {
173 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
174 "32" => DTOR_NEEDED_U32 as usize,
175 "64" => DTOR_NEEDED_U64 as usize,
176 tws => panic!("Unsupported target word size for int: {}", tws),
180 pub const DTOR_DONE: u8 = 0x1d;
181 pub const DTOR_DONE_U32: u32 = repeat_u8_as_u32!(DTOR_DONE);
182 pub const DTOR_DONE_U64: u64 = repeat_u8_as_u64!(DTOR_DONE);
184 pub fn dtor_done_usize(ccx: &CrateContext) -> usize {
185 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
186 "32" => DTOR_DONE_U32 as usize,
187 "64" => DTOR_DONE_U64 as usize,
188 tws => panic!("Unsupported target word size for int: {}", tws),
192 fn dtor_to_init_u8(dtor: bool) -> u8 {
193 if dtor { DTOR_NEEDED } else { 0 }
196 pub trait GetDtorType<'tcx> { fn dtor_type(&self) -> Ty<'tcx>; }
197 impl<'tcx> GetDtorType<'tcx> for ty::ctxt<'tcx> {
198 fn dtor_type(&self) -> Ty<'tcx> { self.types.u8 }
201 fn dtor_active(flag: u8) -> bool {
205 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
206 t: Ty<'tcx>) -> Repr<'tcx> {
208 ty::ty_tup(ref elems) => {
209 Univariant(mk_struct(cx, &elems[..], false, t), 0)
211 ty::ty_struct(def_id, substs) => {
212 let fields = ty::lookup_struct_fields(cx.tcx(), def_id);
213 let mut ftys = fields.iter().map(|field| {
214 let fty = ty::lookup_field_type(cx.tcx(), def_id, field.id, substs);
215 monomorphize::normalize_associated_type(cx.tcx(), &fty)
216 }).collect::<Vec<_>>();
217 let packed = ty::lookup_packed(cx.tcx(), def_id);
218 let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag();
219 if dtor { ftys.push(cx.tcx().dtor_type()); }
221 Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
223 ty::ty_closure(def_id, substs) => {
224 let typer = NormalizingClosureTyper::new(cx.tcx());
225 let upvars = typer.closure_upvars(def_id, substs).unwrap();
226 let upvar_types = upvars.iter().map(|u| u.ty).collect::<Vec<_>>();
227 Univariant(mk_struct(cx, &upvar_types[..], false, t), 0)
229 ty::ty_enum(def_id, substs) => {
230 let cases = get_cases(cx.tcx(), def_id, substs);
231 let hint = *ty::lookup_repr_hints(cx.tcx(), def_id).get(0)
232 .unwrap_or(&attr::ReprAny);
234 let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag();
236 if cases.is_empty() {
237 // Uninhabitable; represent as unit
238 // (Typechecking will reject discriminant-sizing attrs.)
239 assert_eq!(hint, attr::ReprAny);
240 let ftys = if dtor { vec!(cx.tcx().dtor_type()) } else { vec!() };
241 return Univariant(mk_struct(cx, &ftys[..], false, t),
242 dtor_to_init_u8(dtor));
245 if !dtor && cases.iter().all(|c| c.tys.is_empty()) {
246 // All bodies empty -> intlike
247 let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
248 let bounds = IntBounds {
249 ulo: *discrs.iter().min().unwrap(),
250 uhi: *discrs.iter().max().unwrap(),
251 slo: discrs.iter().map(|n| *n as i64).min().unwrap(),
252 shi: discrs.iter().map(|n| *n as i64).max().unwrap()
254 return mk_cenum(cx, hint, &bounds);
257 // Since there's at least one
258 // non-empty body, explicit discriminants should have
259 // been rejected by a checker before this point.
260 if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
261 cx.sess().bug(&format!("non-C-like enum {} with specified \
263 ty::item_path_str(cx.tcx(),
267 if cases.len() == 1 {
268 // Equivalent to a struct/tuple/newtype.
269 // (Typechecking will reject discriminant-sizing attrs.)
270 assert_eq!(hint, attr::ReprAny);
271 let mut ftys = cases[0].tys.clone();
272 if dtor { ftys.push(cx.tcx().dtor_type()); }
273 return Univariant(mk_struct(cx, &ftys[..], false, t),
274 dtor_to_init_u8(dtor));
277 if !dtor && cases.len() == 2 && hint == attr::ReprAny {
278 // Nullable pointer optimization
281 if cases[1 - discr].is_zerolen(cx, t) {
282 let st = mk_struct(cx, &cases[discr].tys,
284 match cases[discr].find_ptr(cx) {
285 Some(ref df) if df.len() == 1 && st.fields.len() == 1 => {
286 return RawNullablePointer {
287 nndiscr: discr as Disr,
289 nullfields: cases[1 - discr].tys.clone()
292 Some(mut discrfield) => {
294 discrfield.reverse();
295 return StructWrappedNullablePointer {
296 nndiscr: discr as Disr,
298 discrfield: discrfield,
299 nullfields: cases[1 - discr].tys.clone()
310 assert!((cases.len() - 1) as i64 >= 0);
311 let bounds = IntBounds { ulo: 0, uhi: (cases.len() - 1) as u64,
312 slo: 0, shi: (cases.len() - 1) as i64 };
313 let min_ity = range_to_inttype(cx, hint, &bounds);
315 // Create the set of structs that represent each variant
316 // Use the minimum integer type we figured out above
317 let fields : Vec<_> = cases.iter().map(|c| {
318 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
319 ftys.push_all(&c.tys);
320 if dtor { ftys.push(cx.tcx().dtor_type()); }
321 mk_struct(cx, &ftys, false, t)
325 // Check to see if we should use a different type for the
326 // discriminant. If the overall alignment of the type is
327 // the same as the first field in each variant, we can safely use
328 // an alignment-sized type.
329 // We increase the size of the discriminant to avoid LLVM copying
330 // padding when it doesn't need to. This normally causes unaligned
331 // load/stores and excessive memcpy/memset operations. By using a
332 // bigger integer size, LLVM can be sure about it's contents and
333 // won't be so conservative.
334 // This check is needed to avoid increasing the size of types when
335 // the alignment of the first field is smaller than the overall
336 // alignment of the type.
337 let (_, align) = union_size_and_align(&fields);
338 let mut use_align = true;
340 // Get the first non-zero-sized field
341 let field = st.fields.iter().skip(1).filter(|ty| {
342 let t = type_of::sizing_type_of(cx, **ty);
343 machine::llsize_of_real(cx, t) != 0 ||
344 // This case is only relevant for zero-sized types with large alignment
345 machine::llalign_of_min(cx, t) != 1
348 if let Some(field) = field {
349 let field_align = type_of::align_of(cx, *field);
350 if field_align != align {
356 let ity = if use_align {
357 // Use the overall alignment
359 1 => attr::UnsignedInt(ast::TyU8),
360 2 => attr::UnsignedInt(ast::TyU16),
361 4 => attr::UnsignedInt(ast::TyU32),
362 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
363 attr::UnsignedInt(ast::TyU64),
364 _ => min_ity // use min_ity as a fallback
370 let fields : Vec<_> = cases.iter().map(|c| {
371 let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity));
372 ftys.push_all(&c.tys);
373 if dtor { ftys.push(cx.tcx().dtor_type()); }
374 mk_struct(cx, &ftys[..], false, t)
377 ensure_enum_fits_in_address_space(cx, &fields[..], t);
379 General(ity, fields, dtor_to_init_u8(dtor))
381 _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}",
382 ty_to_string(cx.tcx(), t)))
386 // this should probably all be in ty
392 /// This represents the (GEP) indices to follow to get to the discriminant field
393 pub type DiscrField = Vec<usize>;
395 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
397 mut path: DiscrField) -> Option<DiscrField> {
399 // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
400 ty::ty_rptr(_, ty::mt { ty, .. }) | ty::ty_uniq(ty) if !type_is_sized(tcx, ty) => {
401 path.push(FAT_PTR_ADDR);
405 // Regular thin pointer: &T/&mut T/Box<T>
406 ty::ty_rptr(..) | ty::ty_uniq(..) => Some(path),
408 // Functions are just pointers
409 ty::ty_bare_fn(..) => Some(path),
411 // Is this the NonZero lang item wrapping a pointer or integer type?
412 ty::ty_struct(did, substs) if Some(did) == tcx.lang_items.non_zero() => {
413 let nonzero_fields = ty::lookup_struct_fields(tcx, did);
414 assert_eq!(nonzero_fields.len(), 1);
415 let nonzero_field = ty::lookup_field_type(tcx, did, nonzero_fields[0].id, substs);
416 match nonzero_field.sty {
417 ty::ty_ptr(ty::mt { ty, .. }) if !type_is_sized(tcx, ty) => {
418 path.push_all(&[0, FAT_PTR_ADDR]);
421 ty::ty_ptr(..) | ty::ty_int(..) | ty::ty_uint(..) => {
429 // Perhaps one of the fields of this struct is non-zero
430 // let's recurse and find out
431 ty::ty_struct(def_id, substs) => {
432 let fields = ty::lookup_struct_fields(tcx, def_id);
433 for (j, field) in fields.iter().enumerate() {
434 let field_ty = ty::lookup_field_type(tcx, def_id, field.id, substs);
435 if let Some(mut fpath) = find_discr_field_candidate(tcx, field_ty, path.clone()) {
443 // Can we use one of the fields in this tuple?
444 ty::ty_tup(ref tys) => {
445 for (j, &ty) in tys.iter().enumerate() {
446 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
454 // Is this a fixed-size array of something non-zero
455 // with at least one element?
456 ty::ty_vec(ety, Some(d)) if d > 0 => {
457 if let Some(mut vpath) = find_discr_field_candidate(tcx, ety, path) {
465 // Anything else is not a pointer
470 impl<'tcx> Case<'tcx> {
471 fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool {
472 mk_struct(cx, &self.tys, false, scapegoat).size == 0
475 fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> {
476 for (i, &ty) in self.tys.iter().enumerate() {
477 if let Some(mut path) = find_discr_field_candidate(cx.tcx(), ty, vec![]) {
486 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
488 substs: &subst::Substs<'tcx>)
490 ty::enum_variants(tcx, def_id).iter().map(|vi| {
491 let arg_tys = vi.args.iter().map(|&raw_ty| {
492 monomorphize::apply_param_substs(tcx, substs, &raw_ty)
494 Case { discr: vi.disr_val, tys: arg_tys }
498 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
499 tys: &[Ty<'tcx>], packed: bool,
502 let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
503 let lltys : Vec<Type> = if sized {
505 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
507 tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
508 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
511 ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
513 let llty_rec = Type::struct_(cx, &lltys[..], packed);
515 size: machine::llsize_of_alloc(cx, llty_rec),
516 align: machine::llalign_of_min(cx, llty_rec),
519 fields: tys.to_vec(),
531 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
532 hint: Hint, bounds: &IntBounds)
534 let it = range_to_inttype(cx, hint, bounds);
536 attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
537 attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
541 fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType {
542 debug!("range_to_inttype: {:?} {:?}", hint, bounds);
543 // Lists of sizes to try. u64 is always allowed as a fallback.
544 #[allow(non_upper_case_globals)]
545 const choose_shortest: &'static [IntType] = &[
546 attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
547 attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
548 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
549 #[allow(non_upper_case_globals)]
550 const at_least_32: &'static [IntType] = &[
551 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
555 attr::ReprInt(span, ity) => {
556 if !bounds_usable(cx, ity, bounds) {
557 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
561 attr::ReprExtern => {
562 attempts = match &cx.sess().target.target.arch[..] {
563 // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
564 // appears to be used on Linux and NetBSD, but some systems may use the variant
565 // corresponding to `choose_shortest`. However, we don't run on those yet...?
566 "arm" => at_least_32,
571 attempts = choose_shortest;
573 attr::ReprPacked => {
574 cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
577 for &ity in attempts {
578 if bounds_usable(cx, ity, bounds) {
582 return attr::UnsignedInt(ast::TyU64);
585 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
587 attr::SignedInt(t) => Type::int_from_ty(cx, t),
588 attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
592 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
593 debug!("bounds_usable: {:?} {:?}", ity, bounds);
595 attr::SignedInt(_) => {
596 let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true);
597 let llhi = C_integral(ll_inttype(cx, ity), bounds.shi as u64, true);
598 bounds.slo == const_to_int(lllo) as i64 && bounds.shi == const_to_int(llhi) as i64
600 attr::UnsignedInt(_) => {
601 let lllo = C_integral(ll_inttype(cx, ity), bounds.ulo, false);
602 let llhi = C_integral(ll_inttype(cx, ity), bounds.uhi, false);
603 bounds.ulo == const_to_uint(lllo) as u64 && bounds.uhi == const_to_uint(llhi) as u64
608 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
610 attr::SignedInt(t) => ty::mk_mach_int(tcx, t),
611 attr::UnsignedInt(t) => ty::mk_mach_uint(tcx, t)
615 // LLVM doesn't like types that don't fit in the address space
616 fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
619 scapegoat: Ty<'tcx>) {
621 for &llty in fields {
622 // Invariant: offset < ccx.obj_size_bound() <= 1<<61
624 let type_align = machine::llalign_of_min(ccx, llty);
625 offset = roundup(offset, type_align);
627 // type_align is a power-of-2, so still offset < ccx.obj_size_bound()
628 // llsize_of_alloc(ccx, llty) is also less than ccx.obj_size_bound()
629 // so the sum is less than 1<<62 (and therefore can't overflow).
630 offset += machine::llsize_of_alloc(ccx, llty);
632 if offset >= ccx.obj_size_bound() {
633 ccx.report_overbig_object(scapegoat);
638 fn union_size_and_align(sts: &[Struct]) -> (machine::llsize, machine::llalign) {
639 let size = sts.iter().map(|st| st.size).max().unwrap();
640 let align = sts.iter().map(|st| st.align).max().unwrap();
641 (roundup(size, align), align)
644 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
646 scapegoat: Ty<'tcx>) {
647 let (total_size, _) = union_size_and_align(fields);
649 if total_size >= ccx.obj_size_bound() {
650 ccx.report_overbig_object(scapegoat);
655 /// LLVM-level types are a little complicated.
657 /// C-like enums need to be actual ints, not wrapped in a struct,
658 /// because that changes the ABI on some platforms (see issue #10308).
660 /// For nominal types, in some cases, we need to use LLVM named structs
661 /// and fill in the actual contents in a second pass to prevent
662 /// unbounded recursion; see also the comments in `trans::type_of`.
663 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>) -> Type {
664 generic_type_of(cx, r, None, false, false)
666 // Pass dst=true if the type you are passing is a DST. Yes, we could figure
667 // this out, but if you call this on an unsized type without realising it, you
668 // are going to get the wrong type (it will not include the unsized parts of it).
669 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
670 r: &Repr<'tcx>, dst: bool) -> Type {
671 generic_type_of(cx, r, None, true, dst)
673 pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
674 r: &Repr<'tcx>, name: &str) -> Type {
675 generic_type_of(cx, r, Some(name), false, false)
677 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
678 r: &Repr<'tcx>, llty: &mut Type) {
680 CEnum(..) | General(..) | RawNullablePointer { .. } => { }
681 Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
682 llty.set_struct_body(&struct_llfields(cx, st, false, false),
687 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
693 CEnum(ity, _, _) => ll_inttype(cx, ity),
694 RawNullablePointer { nnty, .. } => type_of::sizing_type_of(cx, nnty),
695 Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } => {
698 Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
701 Some(name) => { assert_eq!(sizing, false); Type::named_struct(cx, name) }
704 General(ity, ref sts, _) => {
705 // We need a representation that has:
706 // * The alignment of the most-aligned field
707 // * The size of the largest variant (rounded up to that alignment)
708 // * No alignment padding anywhere any variant has actual data
709 // (currently matters only for enums small enough to be immediate)
710 // * The discriminant in an obvious place.
712 // So we start with the discriminant, pad it up to the alignment with
713 // more of its own type, then use alignment-sized ints to get the rest
716 // FIXME #10604: this breaks when vector types are present.
717 let (size, align) = union_size_and_align(&sts[..]);
718 let align_s = align as u64;
719 assert_eq!(size % align_s, 0);
720 let align_units = size / align_s - 1;
722 let discr_ty = ll_inttype(cx, ity);
723 let discr_size = machine::llsize_of_alloc(cx, discr_ty);
724 let fill_ty = match align_s {
725 1 => Type::array(&Type::i8(cx), align_units),
726 2 => Type::array(&Type::i16(cx), align_units),
727 4 => Type::array(&Type::i32(cx), align_units),
728 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
729 Type::array(&Type::i64(cx), align_units),
730 a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
732 _ => panic!("unsupported enum alignment: {}", align)
734 assert_eq!(machine::llalign_of_min(cx, fill_ty), align);
735 assert_eq!(align_s % discr_size, 0);
736 let fields = [discr_ty,
737 Type::array(&discr_ty, align_s / discr_size - 1),
740 None => Type::struct_(cx, &fields[..], false),
742 let mut llty = Type::named_struct(cx, name);
743 llty.set_struct_body(&fields[..], false);
751 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
752 sizing: bool, dst: bool) -> Vec<Type> {
754 st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
755 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
757 st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
761 /// Obtain a representation of the discriminant sufficient to translate
762 /// destructuring; this may or may not involve the actual discriminant.
764 /// This should ideally be less tightly tied to `_match`.
765 pub fn trans_switch<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
766 r: &Repr<'tcx>, scrutinee: ValueRef)
767 -> (_match::BranchKind, Option<ValueRef>) {
769 CEnum(..) | General(..) |
770 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
771 (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
774 // N.B.: Univariant means <= 1 enum variants (*not* == 1 variants).
775 (_match::Single, None)
782 /// Obtain the actual discriminant of a value.
783 pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
784 scrutinee: ValueRef, cast_to: Option<Type>)
788 debug!("trans_get_discr r: {:?}", r);
790 CEnum(ity, min, max) => {
791 val = load_discr(bcx, ity, scrutinee, min, max);
792 signed = ity.is_signed();
794 General(ity, ref cases, _) => {
795 let ptr = GEPi(bcx, scrutinee, &[0, 0]);
796 val = load_discr(bcx, ity, ptr, 0, (cases.len() - 1) as Disr);
797 signed = ity.is_signed();
800 val = C_u8(bcx.ccx(), 0);
803 RawNullablePointer { nndiscr, nnty, .. } => {
804 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
805 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
806 val = ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None);
809 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
810 val = struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee);
816 Some(llty) => if signed { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
820 fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField,
821 scrutinee: ValueRef) -> ValueRef {
822 let llptrptr = GEPi(bcx, scrutinee, &discrfield[..]);
823 let llptr = Load(bcx, llptrptr);
824 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
825 ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
828 /// Helper for cases where the discriminant is simply loaded.
829 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
831 let llty = ll_inttype(bcx.ccx(), ity);
832 assert_eq!(val_ty(ptr), llty.ptr_to());
833 let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
835 let bits = bits as usize;
836 let mask = (!0u64 >> (64 - bits)) as Disr;
837 // For a (max) discr of -1, max will be `-1 as usize`, which overflows.
838 // However, that is fine here (it would still represent the full range),
839 if (max.wrapping_add(1)) & mask == min & mask {
840 // i.e., if the range is everything. The lo==hi case would be
841 // rejected by the LLVM verifier (it would mean either an
842 // empty set, which is impossible, or the entire range of the
843 // type, which is pointless).
846 // llvm::ConstantRange can deal with ranges that wrap around,
847 // so an overflow on (max + 1) is fine.
848 LoadRangeAssert(bcx, ptr, min, (max.wrapping_add(1)), /* signed: */ True)
852 /// Yield information about how to dispatch a case of the
853 /// discriminant-like value returned by `trans_switch`.
855 /// This should ideally be less tightly tied to `_match`.
856 pub fn trans_case<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr, discr: Disr)
857 -> _match::OptResult<'blk, 'tcx> {
859 CEnum(ity, _, _) => {
860 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
861 discr as u64, true)))
863 General(ity, _, _) => {
864 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
865 discr as u64, true)))
868 bcx.ccx().sess().bug("no cases for univariants or structs")
870 RawNullablePointer { .. } |
871 StructWrappedNullablePointer { .. } => {
872 assert!(discr == 0 || discr == 1);
873 _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
878 /// Set the discriminant for a new value of the given case of the given
880 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
881 val: ValueRef, discr: Disr) {
883 CEnum(ity, min, max) => {
884 assert_discr_in_range(ity, min, max, discr);
885 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
888 General(ity, ref cases, dtor) => {
889 if dtor_active(dtor) {
890 let ptr = trans_field_ptr(bcx, r, val, discr,
891 cases[discr as usize].fields.len() - 2);
892 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED as usize), ptr);
894 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
895 GEPi(bcx, val, &[0, 0]));
897 Univariant(ref st, dtor) => {
898 assert_eq!(discr, 0);
899 if dtor_active(dtor) {
900 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED as usize),
901 GEPi(bcx, val, &[0, st.fields.len() - 1]));
904 RawNullablePointer { nndiscr, nnty, ..} => {
905 if discr != nndiscr {
906 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
907 Store(bcx, C_null(llptrty), val);
910 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
911 if discr != nndiscr {
912 let llptrptr = GEPi(bcx, val, &discrfield[..]);
913 let llptrty = val_ty(llptrptr).element_type();
914 Store(bcx, C_null(llptrty), llptrptr);
920 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
922 attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
923 attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
927 /// The number of fields in a given case; for use when obtaining this
928 /// information from the type or definition is less convenient.
929 pub fn num_args(r: &Repr, discr: Disr) -> usize {
932 Univariant(ref st, dtor) => {
933 assert_eq!(discr, 0);
934 st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
936 General(_, ref cases, dtor) => {
937 cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
939 RawNullablePointer { nndiscr, ref nullfields, .. } => {
940 if discr == nndiscr { 1 } else { nullfields.len() }
942 StructWrappedNullablePointer { ref nonnull, nndiscr,
943 ref nullfields, .. } => {
944 if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
949 /// Access a field, at a point when the value's case is known.
950 pub fn trans_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
951 val: ValueRef, discr: Disr, ix: usize) -> ValueRef {
952 // Note: if this ever needs to generate conditionals (e.g., if we
953 // decide to do some kind of cdr-coding-like non-unique repr
954 // someday), it will need to return a possibly-new bcx as well.
957 bcx.ccx().sess().bug("element access in C-like enum")
959 Univariant(ref st, _dtor) => {
960 assert_eq!(discr, 0);
961 struct_field_ptr(bcx, st, val, ix, false)
963 General(_, ref cases, _) => {
964 struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
966 RawNullablePointer { nndiscr, ref nullfields, .. } |
967 StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
968 // The unit-like case might have a nonzero number of unit-like fields.
969 // (e.d., Result of Either with (), as one side.)
970 let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
971 assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
972 // The contents of memory at this pointer can't matter, but use
973 // the value that's "reasonable" in case of pointer comparison.
974 PointerCast(bcx, val, ty.ptr_to())
976 RawNullablePointer { nndiscr, nnty, .. } => {
978 assert_eq!(discr, nndiscr);
979 let ty = type_of::type_of(bcx.ccx(), nnty);
980 PointerCast(bcx, val, ty.ptr_to())
982 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
983 assert_eq!(discr, nndiscr);
984 struct_field_ptr(bcx, nonnull, val, ix, false)
989 pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, val: ValueRef,
990 ix: usize, needs_cast: bool) -> ValueRef {
991 let val = if needs_cast {
993 let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>();
994 let real_ty = Type::struct_(ccx, &fields[..], st.packed);
995 PointerCast(bcx, val, real_ty.ptr_to())
1000 GEPi(bcx, val, &[0, ix])
1003 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1007 -> Block<'blk, 'tcx> where
1008 F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1012 Univariant(ref st, _) => {
1015 General(ity, ref cases, _) => {
1016 let ccx = bcx.ccx();
1017 let unr_cx = fcx.new_temp_block("enum-variant-iter-unr");
1018 Unreachable(unr_cx);
1020 let discr_val = trans_get_discr(bcx, r, value, None);
1021 let llswitch = Switch(bcx, discr_val, unr_cx.llbb, cases.len());
1022 let bcx_next = fcx.new_temp_block("enum-variant-iter-next");
1024 for (discr, case) in cases.iter().enumerate() {
1025 let mut variant_cx = fcx.new_temp_block(
1026 &format!("enum-variant-iter-{}", &discr.to_string())
1028 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1029 AddCase(llswitch, rhs_val, variant_cx.llbb);
1031 let fields = case.fields.iter().map(|&ty|
1032 type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>();
1033 let real_ty = Type::struct_(ccx, &fields[..], case.packed);
1034 let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to());
1036 variant_cx = f(variant_cx, case, variant_value);
1037 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1046 /// Access the struct drop flag, if present.
1047 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, val: ValueRef)
1048 -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1050 let tcx = bcx.tcx();
1051 let ptr_ty = ty::mk_imm_ptr(bcx.tcx(), tcx.dtor_type());
1053 Univariant(ref st, dtor) if dtor_active(dtor) => {
1054 let flag_ptr = GEPi(bcx, val, &[0, st.fields.len() - 1]);
1055 datum::immediate_rvalue_bcx(bcx, flag_ptr, ptr_ty).to_expr_datumblock()
1057 General(_, _, dtor) if dtor_active(dtor) => {
1059 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1060 let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
1061 bcx, tcx.dtor_type(), "drop_flag",
1062 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
1064 bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
1065 let ptr = struct_field_ptr(variant_cx, st, value, (st.fields.len() - 1), false);
1066 datum::Datum::new(ptr, ptr_ty, datum::Lvalue)
1067 .store_to(variant_cx, scratch.val)
1069 let expr_datum = scratch.to_expr_datum();
1070 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1071 datum::DatumBlock::new(bcx, expr_datum)
1073 _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1077 /// Construct a constant value, suitable for initializing a
1078 /// GlobalVariable, given a case and constant values for its fields.
1079 /// Note that this may have a different LLVM type (and different
1080 /// alignment!) from the representation's `type_of`, so it needs a
1081 /// pointer cast before use.
1083 /// The LLVM type system does not directly support unions, and only
1084 /// pointers can be bitcast, so a constant (and, by extension, the
1085 /// GlobalVariable initialized by it) will have a type that can vary
1086 /// depending on which case of an enum it is.
1088 /// To understand the alignment situation, consider `enum E { V64(u64),
1089 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1090 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1091 /// i32, i32}`, which is 4-byte aligned.
1093 /// Currently the returned value has the same size as the type, but
1094 /// this could be changed in the future to avoid allocating unnecessary
1095 /// space after values of shorter-than-maximum cases.
1096 pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr: Disr,
1097 vals: &[ValueRef]) -> ValueRef {
1099 CEnum(ity, min, max) => {
1100 assert_eq!(vals.len(), 0);
1101 assert_discr_in_range(ity, min, max, discr);
1102 C_integral(ll_inttype(ccx, ity), discr as u64, true)
1104 General(ity, ref cases, _) => {
1105 let case = &cases[discr as usize];
1106 let (max_sz, _) = union_size_and_align(&cases[..]);
1107 let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1108 let mut f = vec![lldiscr];
1110 let mut contents = build_const_struct(ccx, case, &f[..]);
1111 contents.push_all(&[padding(ccx, max_sz - case.size)]);
1112 C_struct(ccx, &contents[..], false)
1114 Univariant(ref st, _dro) => {
1115 assert!(discr == 0);
1116 let contents = build_const_struct(ccx, st, vals);
1117 C_struct(ccx, &contents[..], st.packed)
1119 RawNullablePointer { nndiscr, nnty, .. } => {
1120 if discr == nndiscr {
1121 assert_eq!(vals.len(), 1);
1124 C_null(type_of::sizing_type_of(ccx, nnty))
1127 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1128 if discr == nndiscr {
1129 C_struct(ccx, &build_const_struct(ccx,
1134 let vals = nonnull.fields.iter().map(|&ty| {
1135 // Always use null even if it's not the `discrfield`th
1136 // field; see #8506.
1137 C_null(type_of::sizing_type_of(ccx, ty))
1138 }).collect::<Vec<ValueRef>>();
1139 C_struct(ccx, &build_const_struct(ccx,
1148 /// Compute struct field offsets relative to struct begin.
1149 fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1150 st: &Struct<'tcx>) -> Vec<u64> {
1151 let mut offsets = vec!();
1154 for &ty in &st.fields {
1155 let llty = type_of::sizing_type_of(ccx, ty);
1157 let type_align = type_of::align_of(ccx, ty);
1158 offset = roundup(offset, type_align);
1160 offsets.push(offset);
1161 offset += machine::llsize_of_alloc(ccx, llty);
1163 assert_eq!(st.fields.len(), offsets.len());
1167 /// Building structs is a little complicated, because we might need to
1168 /// insert padding if a field's value is less aligned than its type.
1170 /// Continuing the example from `trans_const`, a value of type `(u32,
1171 /// E)` should have the `E` at offset 8, but if that field's
1172 /// initializer is 4-byte aligned then simply translating the tuple as
1173 /// a two-element struct will locate it at offset 4, and accesses to it
1174 /// will read the wrong memory.
1175 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1176 st: &Struct<'tcx>, vals: &[ValueRef])
1178 assert_eq!(vals.len(), st.fields.len());
1180 let target_offsets = compute_struct_field_offsets(ccx, st);
1182 // offset of current value
1184 let mut cfields = Vec::new();
1185 for (&val, &target_offset) in vals.iter().zip(target_offsets.iter()) {
1187 let val_align = machine::llalign_of_min(ccx, val_ty(val));
1188 offset = roundup(offset, val_align);
1190 if offset != target_offset {
1191 cfields.push(padding(ccx, target_offset - offset));
1192 offset = target_offset;
1194 assert!(!is_undef(val));
1196 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1199 assert!(st.sized && offset <= st.size);
1200 if offset != st.size {
1201 cfields.push(padding(ccx, st.size - offset));
1207 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1208 C_undef(Type::array(&Type::i8(ccx), size))
1211 // FIXME this utility routine should be somewhere more general
1213 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1215 /// Get the discriminant of a constant value.
1216 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1218 CEnum(ity, _, _) => {
1220 attr::SignedInt(..) => const_to_int(val) as Disr,
1221 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1224 General(ity, _, _) => {
1226 attr::SignedInt(..) => const_to_int(const_get_elt(ccx, val, &[0])) as Disr,
1227 attr::UnsignedInt(..) => const_to_uint(const_get_elt(ccx, val, &[0])) as Disr
1230 Univariant(..) => 0,
1231 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1232 ccx.sess().bug("const discrim access of non c-like enum")
1237 /// Extract a field of a constant value, as appropriate for its
1240 /// (Not to be confused with `common::const_get_elt`, which operates on
1241 /// raw LLVM-level structs and arrays.)
1242 pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
1243 _discr: Disr, ix: usize) -> ValueRef {
1245 CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
1246 Univariant(..) => const_struct_field(ccx, val, ix),
1247 General(..) => const_struct_field(ccx, val, ix + 1),
1248 RawNullablePointer { .. } => {
1252 StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1256 /// Extract field of struct-like const, skipping our alignment padding.
1257 fn const_struct_field(ccx: &CrateContext, val: ValueRef, ix: usize) -> ValueRef {
1258 // Get the ix-th non-undef element of the struct.
1259 let mut real_ix = 0; // actual position in the struct
1260 let mut ix = ix; // logical index relative to real_ix
1264 field = const_get_elt(ccx, val, &[real_ix]);
1265 if !is_undef(field) {
1268 real_ix = real_ix + 1;
1274 real_ix = real_ix + 1;