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 pub use self::Repr::*;
48 use llvm::{ValueRef, True, IntEQ, IntNE};
49 use back::abi::FAT_PTR_ADDR;
51 use middle::ty::{self, Ty};
55 use syntax::attr::IntType;
59 use trans::cleanup::CleanupMethods;
62 use trans::debuginfo::DebugLoc;
64 use trans::monomorphize;
65 use trans::type_::Type;
68 type Hint = attr::ReprAttr;
70 // Representation of the context surrounding an unsized type. I want
71 // to be able to track the drop flags that are injected by trans.
72 #[derive(Clone, Copy, PartialEq, Debug)]
73 pub struct TypeContext {
75 needs_drop_flag: bool,
79 pub fn prefix(&self) -> Type { self.prefix }
80 pub fn needs_drop_flag(&self) -> bool { self.needs_drop_flag }
82 fn direct(t: Type) -> TypeContext {
83 TypeContext { prefix: t, needs_drop_flag: false }
85 fn may_need_drop_flag(t: Type, needs_drop_flag: bool) -> TypeContext {
86 TypeContext { prefix: t, needs_drop_flag: needs_drop_flag }
88 pub fn to_string(self) -> String {
89 let TypeContext { prefix, needs_drop_flag } = self;
90 format!("TypeContext {{ prefix: {}, needs_drop_flag: {} }}",
91 prefix.to_string(), needs_drop_flag)
96 #[derive(Eq, PartialEq, Debug)]
98 /// C-like enums; basically an int.
99 CEnum(IntType, Disr, Disr), // discriminant range (signedness based on the IntType)
100 /// Single-case variants, and structs/tuples/records.
102 /// Structs with destructors need a dynamic destroyedness flag to
103 /// avoid running the destructor too many times; this is included
104 /// in the `Struct` if present.
105 /// (The flag if nonzero, represents the initialization value to use;
106 /// if zero, then use no flag at all.)
107 Univariant(Struct<'tcx>, u8),
108 /// General-case enums: for each case there is a struct, and they
109 /// all start with a field for the discriminant.
111 /// Types with destructors need a dynamic destroyedness flag to
112 /// avoid running the destructor too many times; the last argument
113 /// indicates whether such a flag is present.
114 /// (The flag, if nonzero, represents the initialization value to use;
115 /// if zero, then use no flag at all.)
116 General(IntType, Vec<Struct<'tcx>>, u8),
117 /// Two cases distinguished by a nullable pointer: the case with discriminant
118 /// `nndiscr` must have single field which is known to be nonnull due to its type.
119 /// The other case is known to be zero sized. Hence we represent the enum
120 /// as simply a nullable pointer: if not null it indicates the `nndiscr` variant,
121 /// otherwise it indicates the other case.
125 nullfields: Vec<Ty<'tcx>>
127 /// Two cases distinguished by a nullable pointer: the case with discriminant
128 /// `nndiscr` is represented by the struct `nonnull`, where the `discrfield`th
129 /// field is known to be nonnull due to its type; if that field is null, then
130 /// it represents the other case, which is inhabited by at most one value
131 /// (and all other fields are undefined/unused).
133 /// For example, `std::option::Option` instantiated at a safe pointer type
134 /// is represented such that `None` is a null pointer and `Some` is the
135 /// identity function.
136 StructWrappedNullablePointer {
137 nonnull: Struct<'tcx>,
139 discrfield: DiscrField,
140 nullfields: Vec<Ty<'tcx>>,
144 /// For structs, and struct-like parts of anything fancier.
145 #[derive(Eq, PartialEq, Debug)]
146 pub struct Struct<'tcx> {
147 // If the struct is DST, then the size and alignment do not take into
148 // account the unsized fields of the struct.
153 pub fields: Vec<Ty<'tcx>>,
156 /// Convenience for `represent_type`. There should probably be more or
157 /// these, for places in trans where the `Ty` isn't directly
159 pub fn represent_node<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
160 node: ast::NodeId) -> Rc<Repr<'tcx>> {
161 represent_type(bcx.ccx(), node_id_type(bcx, node))
164 /// Decides how to represent a given type.
165 pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
168 debug!("Representing: {}", t);
169 match cx.adt_reprs().borrow().get(&t) {
170 Some(repr) => return repr.clone(),
174 let repr = Rc::new(represent_type_uncached(cx, t));
175 debug!("Represented as: {:?}", repr);
176 cx.adt_reprs().borrow_mut().insert(t, repr.clone());
180 macro_rules! repeat_u8_as_u32 {
181 ($name:expr) => { (($name as u32) << 24 |
182 ($name as u32) << 16 |
183 ($name as u32) << 8 |
186 macro_rules! repeat_u8_as_u64 {
187 ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
188 (repeat_u8_as_u32!($name) as u64)) }
191 /// `DTOR_NEEDED_HINT` is a stack-local hint that just means
192 /// "we do not know whether the destructor has run or not; check the
193 /// drop-flag embedded in the value itself."
194 pub const DTOR_NEEDED_HINT: u8 = 0x3d;
196 /// `DTOR_MOVED_HINT` is a stack-local hint that means "this value has
197 /// definitely been moved; you do not need to run its destructor."
199 /// (However, for now, such values may still end up being explicitly
200 /// zeroed by the generated code; this is the distinction between
201 /// `datum::DropFlagInfo::ZeroAndMaintain` versus
202 /// `datum::DropFlagInfo::DontZeroJustUse`.)
203 pub const DTOR_MOVED_HINT: u8 = 0x2d;
205 pub const DTOR_NEEDED: u8 = 0xd4;
206 pub const DTOR_NEEDED_U32: u32 = repeat_u8_as_u32!(DTOR_NEEDED);
207 pub const DTOR_NEEDED_U64: u64 = repeat_u8_as_u64!(DTOR_NEEDED);
209 pub fn dtor_needed_usize(ccx: &CrateContext) -> usize {
210 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
211 "32" => DTOR_NEEDED_U32 as usize,
212 "64" => DTOR_NEEDED_U64 as usize,
213 tws => panic!("Unsupported target word size for int: {}", tws),
217 pub const DTOR_DONE: u8 = 0x1d;
218 pub const DTOR_DONE_U32: u32 = repeat_u8_as_u32!(DTOR_DONE);
219 pub const DTOR_DONE_U64: u64 = repeat_u8_as_u64!(DTOR_DONE);
221 pub fn dtor_done_usize(ccx: &CrateContext) -> usize {
222 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
223 "32" => DTOR_DONE_U32 as usize,
224 "64" => DTOR_DONE_U64 as usize,
225 tws => panic!("Unsupported target word size for int: {}", tws),
229 fn dtor_to_init_u8(dtor: bool) -> u8 {
230 if dtor { DTOR_NEEDED } else { 0 }
233 pub trait GetDtorType<'tcx> { fn dtor_type(&self) -> Ty<'tcx>; }
234 impl<'tcx> GetDtorType<'tcx> for ty::ctxt<'tcx> {
235 fn dtor_type(&self) -> Ty<'tcx> { self.types.u8 }
238 fn dtor_active(flag: u8) -> bool {
242 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
243 t: Ty<'tcx>) -> Repr<'tcx> {
245 ty::TyTuple(ref elems) => {
246 Univariant(mk_struct(cx, &elems[..], false, t), 0)
248 ty::TyStruct(def, substs) => {
249 let mut ftys = def.struct_variant().fields.iter().map(|field| {
250 monomorphize::field_ty(cx.tcx(), substs, field)
251 }).collect::<Vec<_>>();
252 let packed = cx.tcx().lookup_packed(def.did);
253 let dtor = cx.tcx().ty_dtor(def.did).has_drop_flag();
255 ftys.push(cx.tcx().dtor_type());
258 Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
260 ty::TyClosure(_, ref substs) => {
261 Univariant(mk_struct(cx, &substs.upvar_tys, false, t), 0)
263 ty::TyEnum(def, substs) => {
264 let cases = get_cases(cx.tcx(), def, substs);
265 let hint = *cx.tcx().lookup_repr_hints(def.did).get(0)
266 .unwrap_or(&attr::ReprAny);
268 let dtor = cx.tcx().ty_dtor(def.did).has_drop_flag();
270 if cases.is_empty() {
271 // Uninhabitable; represent as unit
272 // (Typechecking will reject discriminant-sizing attrs.)
273 assert_eq!(hint, attr::ReprAny);
274 let ftys = if dtor { vec!(cx.tcx().dtor_type()) } else { vec!() };
275 return Univariant(mk_struct(cx, &ftys[..], false, t),
276 dtor_to_init_u8(dtor));
279 if !dtor && cases.iter().all(|c| c.tys.is_empty()) {
280 // All bodies empty -> intlike
281 let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
282 let bounds = IntBounds {
283 ulo: *discrs.iter().min().unwrap(),
284 uhi: *discrs.iter().max().unwrap(),
285 slo: discrs.iter().map(|n| *n as i64).min().unwrap(),
286 shi: discrs.iter().map(|n| *n as i64).max().unwrap()
288 return mk_cenum(cx, hint, &bounds);
291 // Since there's at least one
292 // non-empty body, explicit discriminants should have
293 // been rejected by a checker before this point.
294 if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
295 cx.sess().bug(&format!("non-C-like enum {} with specified \
297 cx.tcx().item_path_str(def.did)));
300 if cases.len() == 1 {
301 // Equivalent to a struct/tuple/newtype.
302 // (Typechecking will reject discriminant-sizing attrs.)
303 assert_eq!(hint, attr::ReprAny);
304 let mut ftys = cases[0].tys.clone();
305 if dtor { ftys.push(cx.tcx().dtor_type()); }
306 return Univariant(mk_struct(cx, &ftys[..], false, t),
307 dtor_to_init_u8(dtor));
310 if !dtor && cases.len() == 2 && hint == attr::ReprAny {
311 // Nullable pointer optimization
314 if cases[1 - discr].is_zerolen(cx, t) {
315 let st = mk_struct(cx, &cases[discr].tys,
317 match cases[discr].find_ptr(cx) {
318 Some(ref df) if df.len() == 1 && st.fields.len() == 1 => {
319 return RawNullablePointer {
320 nndiscr: discr as Disr,
322 nullfields: cases[1 - discr].tys.clone()
325 Some(mut discrfield) => {
327 discrfield.reverse();
328 return StructWrappedNullablePointer {
329 nndiscr: discr as Disr,
331 discrfield: discrfield,
332 nullfields: cases[1 - discr].tys.clone()
343 assert!((cases.len() - 1) as i64 >= 0);
344 let bounds = IntBounds { ulo: 0, uhi: (cases.len() - 1) as u64,
345 slo: 0, shi: (cases.len() - 1) as i64 };
346 let min_ity = range_to_inttype(cx, hint, &bounds);
348 // Create the set of structs that represent each variant
349 // Use the minimum integer type we figured out above
350 let fields : Vec<_> = cases.iter().map(|c| {
351 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
352 ftys.push_all(&c.tys);
353 if dtor { ftys.push(cx.tcx().dtor_type()); }
354 mk_struct(cx, &ftys, false, t)
358 // Check to see if we should use a different type for the
359 // discriminant. If the overall alignment of the type is
360 // the same as the first field in each variant, we can safely use
361 // an alignment-sized type.
362 // We increase the size of the discriminant to avoid LLVM copying
363 // padding when it doesn't need to. This normally causes unaligned
364 // load/stores and excessive memcpy/memset operations. By using a
365 // bigger integer size, LLVM can be sure about it's contents and
366 // won't be so conservative.
367 // This check is needed to avoid increasing the size of types when
368 // the alignment of the first field is smaller than the overall
369 // alignment of the type.
370 let (_, align) = union_size_and_align(&fields);
371 let mut use_align = true;
373 // Get the first non-zero-sized field
374 let field = st.fields.iter().skip(1).filter(|ty| {
375 let t = type_of::sizing_type_of(cx, **ty);
376 machine::llsize_of_real(cx, t) != 0 ||
377 // This case is only relevant for zero-sized types with large alignment
378 machine::llalign_of_min(cx, t) != 1
381 if let Some(field) = field {
382 let field_align = type_of::align_of(cx, *field);
383 if field_align != align {
389 let ity = if use_align {
390 // Use the overall alignment
392 1 => attr::UnsignedInt(ast::TyU8),
393 2 => attr::UnsignedInt(ast::TyU16),
394 4 => attr::UnsignedInt(ast::TyU32),
395 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
396 attr::UnsignedInt(ast::TyU64),
397 _ => min_ity // use min_ity as a fallback
403 let fields : Vec<_> = cases.iter().map(|c| {
404 let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity));
405 ftys.push_all(&c.tys);
406 if dtor { ftys.push(cx.tcx().dtor_type()); }
407 mk_struct(cx, &ftys[..], false, t)
410 ensure_enum_fits_in_address_space(cx, &fields[..], t);
412 General(ity, fields, dtor_to_init_u8(dtor))
414 _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}", t))
418 // this should probably all be in ty
424 /// This represents the (GEP) indices to follow to get to the discriminant field
425 pub type DiscrField = Vec<usize>;
427 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
429 mut path: DiscrField) -> Option<DiscrField> {
431 // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
432 ty::TyRef(_, ty::TypeAndMut { ty, .. }) | ty::TyBox(ty) if !type_is_sized(tcx, ty) => {
433 path.push(FAT_PTR_ADDR);
437 // Regular thin pointer: &T/&mut T/Box<T>
438 ty::TyRef(..) | ty::TyBox(..) => Some(path),
440 // Functions are just pointers
441 ty::TyBareFn(..) => Some(path),
443 // Is this the NonZero lang item wrapping a pointer or integer type?
444 ty::TyStruct(def, substs) if Some(def.did) == tcx.lang_items.non_zero() => {
445 let nonzero_fields = &def.struct_variant().fields;
446 assert_eq!(nonzero_fields.len(), 1);
447 let field_ty = monomorphize::field_ty(tcx, substs, &nonzero_fields[0]);
449 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) if !type_is_sized(tcx, ty) => {
450 path.push_all(&[0, FAT_PTR_ADDR]);
453 ty::TyRawPtr(..) | ty::TyInt(..) | ty::TyUint(..) => {
461 // Perhaps one of the fields of this struct is non-zero
462 // let's recurse and find out
463 ty::TyStruct(def, substs) => {
464 for (j, field) in def.struct_variant().fields.iter().enumerate() {
465 let field_ty = monomorphize::field_ty(tcx, substs, field);
466 if let Some(mut fpath) = find_discr_field_candidate(tcx, field_ty, path.clone()) {
474 // Perhaps one of the upvars of this struct is non-zero
475 // Let's recurse and find out!
476 ty::TyClosure(_, ref substs) => {
477 for (j, &ty) in substs.upvar_tys.iter().enumerate() {
478 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
486 // Can we use one of the fields in this tuple?
487 ty::TyTuple(ref tys) => {
488 for (j, &ty) in tys.iter().enumerate() {
489 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
497 // Is this a fixed-size array of something non-zero
498 // with at least one element?
499 ty::TyArray(ety, d) if d > 0 => {
500 if let Some(mut vpath) = find_discr_field_candidate(tcx, ety, path) {
508 // Anything else is not a pointer
513 impl<'tcx> Case<'tcx> {
514 fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool {
515 mk_struct(cx, &self.tys, false, scapegoat).size == 0
518 fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> {
519 for (i, &ty) in self.tys.iter().enumerate() {
520 if let Some(mut path) = find_discr_field_candidate(cx.tcx(), ty, vec![]) {
529 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
530 adt: ty::AdtDef<'tcx>,
531 substs: &subst::Substs<'tcx>)
533 adt.variants.iter().map(|vi| {
534 let field_tys = vi.fields.iter().map(|field| {
535 monomorphize::field_ty(tcx, substs, field)
537 Case { discr: vi.disr_val, tys: field_tys }
541 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
542 tys: &[Ty<'tcx>], packed: bool,
545 let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
546 let lltys : Vec<Type> = if sized {
547 tys.iter().map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
549 tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
550 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
553 ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
555 let llty_rec = Type::struct_(cx, &lltys[..], packed);
557 size: machine::llsize_of_alloc(cx, llty_rec),
558 align: machine::llalign_of_min(cx, llty_rec),
561 fields: tys.to_vec(),
573 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
574 hint: Hint, bounds: &IntBounds)
576 let it = range_to_inttype(cx, hint, bounds);
578 attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
579 attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
583 fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType {
584 debug!("range_to_inttype: {:?} {:?}", hint, bounds);
585 // Lists of sizes to try. u64 is always allowed as a fallback.
586 #[allow(non_upper_case_globals)]
587 const choose_shortest: &'static [IntType] = &[
588 attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
589 attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
590 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
591 #[allow(non_upper_case_globals)]
592 const at_least_32: &'static [IntType] = &[
593 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
597 attr::ReprInt(span, ity) => {
598 if !bounds_usable(cx, ity, bounds) {
599 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
603 attr::ReprExtern => {
604 attempts = match &cx.sess().target.target.arch[..] {
605 // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
606 // appears to be used on Linux and NetBSD, but some systems may use the variant
607 // corresponding to `choose_shortest`. However, we don't run on those yet...?
608 "arm" => at_least_32,
613 attempts = choose_shortest;
615 attr::ReprPacked => {
616 cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
619 cx.tcx().sess.bug("range_to_inttype: found ReprSimd on an enum");
622 for &ity in attempts {
623 if bounds_usable(cx, ity, bounds) {
627 return attr::UnsignedInt(ast::TyU64);
630 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
632 attr::SignedInt(t) => Type::int_from_ty(cx, t),
633 attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
637 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
638 debug!("bounds_usable: {:?} {:?}", ity, bounds);
640 attr::SignedInt(_) => {
641 let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true);
642 let llhi = C_integral(ll_inttype(cx, ity), bounds.shi as u64, true);
643 bounds.slo == const_to_int(lllo) as i64 && bounds.shi == const_to_int(llhi) as i64
645 attr::UnsignedInt(_) => {
646 let lllo = C_integral(ll_inttype(cx, ity), bounds.ulo, false);
647 let llhi = C_integral(ll_inttype(cx, ity), bounds.uhi, false);
648 bounds.ulo == const_to_uint(lllo) as u64 && bounds.uhi == const_to_uint(llhi) as u64
653 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
655 attr::SignedInt(t) => tcx.mk_mach_int(t),
656 attr::UnsignedInt(t) => tcx.mk_mach_uint(t)
660 // LLVM doesn't like types that don't fit in the address space
661 fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
664 scapegoat: Ty<'tcx>) {
666 for &llty in fields {
667 // Invariant: offset < ccx.obj_size_bound() <= 1<<61
669 let type_align = machine::llalign_of_min(ccx, llty);
670 offset = roundup(offset, type_align);
672 // type_align is a power-of-2, so still offset < ccx.obj_size_bound()
673 // llsize_of_alloc(ccx, llty) is also less than ccx.obj_size_bound()
674 // so the sum is less than 1<<62 (and therefore can't overflow).
675 offset += machine::llsize_of_alloc(ccx, llty);
677 if offset >= ccx.obj_size_bound() {
678 ccx.report_overbig_object(scapegoat);
683 fn union_size_and_align(sts: &[Struct]) -> (machine::llsize, machine::llalign) {
684 let size = sts.iter().map(|st| st.size).max().unwrap();
685 let align = sts.iter().map(|st| st.align).max().unwrap();
686 (roundup(size, align), align)
689 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
691 scapegoat: Ty<'tcx>) {
692 let (total_size, _) = union_size_and_align(fields);
694 if total_size >= ccx.obj_size_bound() {
695 ccx.report_overbig_object(scapegoat);
700 /// LLVM-level types are a little complicated.
702 /// C-like enums need to be actual ints, not wrapped in a struct,
703 /// because that changes the ABI on some platforms (see issue #10308).
705 /// For nominal types, in some cases, we need to use LLVM named structs
706 /// and fill in the actual contents in a second pass to prevent
707 /// unbounded recursion; see also the comments in `trans::type_of`.
708 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>) -> Type {
709 let c = generic_type_of(cx, r, None, false, false, false);
710 assert!(!c.needs_drop_flag);
715 // Pass dst=true if the type you are passing is a DST. Yes, we could figure
716 // this out, but if you call this on an unsized type without realising it, you
717 // are going to get the wrong type (it will not include the unsized parts of it).
718 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
719 r: &Repr<'tcx>, dst: bool) -> Type {
720 let c = generic_type_of(cx, r, None, true, dst, false);
721 assert!(!c.needs_drop_flag);
724 pub fn sizing_type_context_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
725 r: &Repr<'tcx>, dst: bool) -> TypeContext {
726 generic_type_of(cx, r, None, true, dst, true)
728 pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
729 r: &Repr<'tcx>, name: &str) -> Type {
730 let c = generic_type_of(cx, r, Some(name), false, false, false);
731 assert!(!c.needs_drop_flag);
734 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
735 r: &Repr<'tcx>, llty: &mut Type) {
737 CEnum(..) | General(..) | RawNullablePointer { .. } => { }
738 Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
739 llty.set_struct_body(&struct_llfields(cx, st, false, false),
744 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
749 delay_drop_flag: bool) -> TypeContext {
750 debug!("adt::generic_type_of r: {:?} name: {:?} sizing: {} dst: {} delay_drop_flag: {}",
751 r, name, sizing, dst, delay_drop_flag);
753 CEnum(ity, _, _) => TypeContext::direct(ll_inttype(cx, ity)),
754 RawNullablePointer { nnty, .. } =>
755 TypeContext::direct(type_of::sizing_type_of(cx, nnty)),
756 StructWrappedNullablePointer { nonnull: ref st, .. } => {
760 Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
764 assert_eq!(sizing, false);
765 TypeContext::direct(Type::named_struct(cx, name))
769 Univariant(ref st, dtor_needed) => {
770 let dtor_needed = dtor_needed != 0;
773 let mut fields = struct_llfields(cx, st, sizing, dst);
774 if delay_drop_flag && dtor_needed {
777 TypeContext::may_need_drop_flag(
778 Type::struct_(cx, &fields,
780 delay_drop_flag && dtor_needed)
783 // Hypothesis: named_struct's can never need a
784 // drop flag. (... needs validation.)
785 assert_eq!(sizing, false);
786 TypeContext::direct(Type::named_struct(cx, name))
790 General(ity, ref sts, dtor_needed) => {
791 let dtor_needed = dtor_needed != 0;
792 // We need a representation that has:
793 // * The alignment of the most-aligned field
794 // * The size of the largest variant (rounded up to that alignment)
795 // * No alignment padding anywhere any variant has actual data
796 // (currently matters only for enums small enough to be immediate)
797 // * The discriminant in an obvious place.
799 // So we start with the discriminant, pad it up to the alignment with
800 // more of its own type, then use alignment-sized ints to get the rest
803 // FIXME #10604: this breaks when vector types are present.
804 let (size, align) = union_size_and_align(&sts[..]);
805 let align_s = align as u64;
806 assert_eq!(size % align_s, 0);
807 let align_units = size / align_s - 1;
809 let discr_ty = ll_inttype(cx, ity);
810 let discr_size = machine::llsize_of_alloc(cx, discr_ty);
811 let fill_ty = match align_s {
812 1 => Type::array(&Type::i8(cx), align_units),
813 2 => Type::array(&Type::i16(cx), align_units),
814 4 => Type::array(&Type::i32(cx), align_units),
815 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
816 Type::array(&Type::i64(cx), align_units),
817 a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
819 _ => panic!("unsupported enum alignment: {}", align)
821 assert_eq!(machine::llalign_of_min(cx, fill_ty), align);
822 assert_eq!(align_s % discr_size, 0);
823 let mut fields: Vec<Type> =
825 Type::array(&discr_ty, align_s / discr_size - 1),
826 fill_ty].iter().cloned().collect();
827 if delay_drop_flag && dtor_needed {
832 TypeContext::may_need_drop_flag(
833 Type::struct_(cx, &fields[..], false),
834 delay_drop_flag && dtor_needed)
837 let mut llty = Type::named_struct(cx, name);
838 llty.set_struct_body(&fields[..], false);
839 TypeContext::may_need_drop_flag(
841 delay_drop_flag && dtor_needed)
848 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
849 sizing: bool, dst: bool) -> Vec<Type> {
851 st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
852 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
854 st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
858 /// Obtain a representation of the discriminant sufficient to translate
859 /// destructuring; this may or may not involve the actual discriminant.
861 /// This should ideally be less tightly tied to `_match`.
862 pub fn trans_switch<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
863 r: &Repr<'tcx>, scrutinee: ValueRef)
864 -> (_match::BranchKind, Option<ValueRef>) {
866 CEnum(..) | General(..) |
867 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
868 (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
871 // N.B.: Univariant means <= 1 enum variants (*not* == 1 variants).
872 (_match::Single, None)
877 pub fn is_discr_signed<'tcx>(r: &Repr<'tcx>) -> bool {
879 CEnum(ity, _, _) => ity.is_signed(),
880 General(ity, _, _) => ity.is_signed(),
881 Univariant(..) => false,
882 RawNullablePointer { .. } => false,
883 StructWrappedNullablePointer { .. } => false,
887 /// Obtain the actual discriminant of a value.
888 pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
889 scrutinee: ValueRef, cast_to: Option<Type>)
891 debug!("trans_get_discr r: {:?}", r);
893 CEnum(ity, min, max) => load_discr(bcx, ity, scrutinee, min, max),
894 General(ity, ref cases, _) => {
895 let ptr = GEPi(bcx, scrutinee, &[0, 0]);
896 load_discr(bcx, ity, ptr, 0, (cases.len() - 1) as Disr)
898 Univariant(..) => C_u8(bcx.ccx(), 0),
899 RawNullablePointer { nndiscr, nnty, .. } => {
900 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
901 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
902 ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None)
904 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
905 struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee)
910 Some(llty) => if is_discr_signed(r) { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
914 fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField,
915 scrutinee: ValueRef) -> ValueRef {
916 let llptrptr = GEPi(bcx, scrutinee, &discrfield[..]);
917 let llptr = Load(bcx, llptrptr);
918 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
919 ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
922 /// Helper for cases where the discriminant is simply loaded.
923 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
925 let llty = ll_inttype(bcx.ccx(), ity);
926 assert_eq!(val_ty(ptr), llty.ptr_to());
927 let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
929 let bits = bits as usize;
930 let mask = (!0u64 >> (64 - bits)) as Disr;
931 // For a (max) discr of -1, max will be `-1 as usize`, which overflows.
932 // However, that is fine here (it would still represent the full range),
933 if (max.wrapping_add(1)) & mask == min & mask {
934 // i.e., if the range is everything. The lo==hi case would be
935 // rejected by the LLVM verifier (it would mean either an
936 // empty set, which is impossible, or the entire range of the
937 // type, which is pointless).
940 // llvm::ConstantRange can deal with ranges that wrap around,
941 // so an overflow on (max + 1) is fine.
942 LoadRangeAssert(bcx, ptr, min, (max.wrapping_add(1)), /* signed: */ True)
946 /// Yield information about how to dispatch a case of the
947 /// discriminant-like value returned by `trans_switch`.
949 /// This should ideally be less tightly tied to `_match`.
950 pub fn trans_case<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr, discr: Disr)
951 -> _match::OptResult<'blk, 'tcx> {
953 CEnum(ity, _, _) => {
954 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
955 discr as u64, true)))
957 General(ity, _, _) => {
958 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
959 discr as u64, true)))
962 bcx.ccx().sess().bug("no cases for univariants or structs")
964 RawNullablePointer { .. } |
965 StructWrappedNullablePointer { .. } => {
966 assert!(discr == 0 || discr == 1);
967 _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
972 /// Set the discriminant for a new value of the given case of the given
974 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
975 val: ValueRef, discr: Disr) {
977 CEnum(ity, min, max) => {
978 assert_discr_in_range(ity, min, max, discr);
979 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
982 General(ity, ref cases, dtor) => {
983 if dtor_active(dtor) {
984 let ptr = trans_field_ptr(bcx, r, val, discr,
985 cases[discr as usize].fields.len() - 2);
986 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED), ptr);
988 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
989 GEPi(bcx, val, &[0, 0]));
991 Univariant(ref st, dtor) => {
992 assert_eq!(discr, 0);
993 if dtor_active(dtor) {
994 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED),
995 GEPi(bcx, val, &[0, st.fields.len() - 1]));
998 RawNullablePointer { nndiscr, nnty, ..} => {
999 if discr != nndiscr {
1000 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
1001 Store(bcx, C_null(llptrty), val);
1004 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
1005 if discr != nndiscr {
1006 let llptrptr = GEPi(bcx, val, &discrfield[..]);
1007 let llptrty = val_ty(llptrptr).element_type();
1008 Store(bcx, C_null(llptrty), llptrptr);
1014 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
1016 attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
1017 attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
1021 /// The number of fields in a given case; for use when obtaining this
1022 /// information from the type or definition is less convenient.
1023 pub fn num_args(r: &Repr, discr: Disr) -> usize {
1026 Univariant(ref st, dtor) => {
1027 assert_eq!(discr, 0);
1028 st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
1030 General(_, ref cases, dtor) => {
1031 cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
1033 RawNullablePointer { nndiscr, ref nullfields, .. } => {
1034 if discr == nndiscr { 1 } else { nullfields.len() }
1036 StructWrappedNullablePointer { ref nonnull, nndiscr,
1037 ref nullfields, .. } => {
1038 if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
1043 /// Access a field, at a point when the value's case is known.
1044 pub fn trans_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
1045 val: ValueRef, discr: Disr, ix: usize) -> ValueRef {
1046 // Note: if this ever needs to generate conditionals (e.g., if we
1047 // decide to do some kind of cdr-coding-like non-unique repr
1048 // someday), it will need to return a possibly-new bcx as well.
1051 bcx.ccx().sess().bug("element access in C-like enum")
1053 Univariant(ref st, _dtor) => {
1054 assert_eq!(discr, 0);
1055 struct_field_ptr(bcx, st, val, ix, false)
1057 General(_, ref cases, _) => {
1058 struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
1060 RawNullablePointer { nndiscr, ref nullfields, .. } |
1061 StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
1062 // The unit-like case might have a nonzero number of unit-like fields.
1063 // (e.d., Result of Either with (), as one side.)
1064 let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
1065 assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
1066 // The contents of memory at this pointer can't matter, but use
1067 // the value that's "reasonable" in case of pointer comparison.
1068 PointerCast(bcx, val, ty.ptr_to())
1070 RawNullablePointer { nndiscr, nnty, .. } => {
1072 assert_eq!(discr, nndiscr);
1073 let ty = type_of::type_of(bcx.ccx(), nnty);
1074 PointerCast(bcx, val, ty.ptr_to())
1076 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1077 assert_eq!(discr, nndiscr);
1078 struct_field_ptr(bcx, nonnull, val, ix, false)
1083 pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, val: ValueRef,
1084 ix: usize, needs_cast: bool) -> ValueRef {
1085 let val = if needs_cast {
1086 let ccx = bcx.ccx();
1087 let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>();
1088 let real_ty = Type::struct_(ccx, &fields[..], st.packed);
1089 PointerCast(bcx, val, real_ty.ptr_to())
1094 GEPi(bcx, val, &[0, ix])
1097 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1101 -> Block<'blk, 'tcx> where
1102 F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1106 Univariant(ref st, _) => {
1109 General(ity, ref cases, _) => {
1110 let ccx = bcx.ccx();
1112 // See the comments in trans/base.rs for more information (inside
1113 // iter_structural_ty), but the gist here is that if the enum's
1114 // discriminant is *not* in the range that we're expecting (in which
1115 // case we'll take the fall-through branch on the switch
1116 // instruction) then we can't just optimize this to an Unreachable
1119 // Currently we still have filling drop, so this means that the drop
1120 // glue for enums may be called when the enum has been paved over
1121 // with the "I've been dropped" value. In this case the default
1122 // branch of the switch instruction will actually be taken at
1123 // runtime, so the basic block isn't actually unreachable, so we
1124 // need to make it do something with defined behavior. In this case
1125 // we just return early from the function.
1126 let ret_void_cx = fcx.new_temp_block("enum-variant-iter-ret-void");
1127 RetVoid(ret_void_cx, DebugLoc::None);
1129 let discr_val = trans_get_discr(bcx, r, value, None);
1130 let llswitch = Switch(bcx, discr_val, ret_void_cx.llbb, cases.len());
1131 let bcx_next = fcx.new_temp_block("enum-variant-iter-next");
1133 for (discr, case) in cases.iter().enumerate() {
1134 let mut variant_cx = fcx.new_temp_block(
1135 &format!("enum-variant-iter-{}", &discr.to_string())
1137 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1138 AddCase(llswitch, rhs_val, variant_cx.llbb);
1140 let fields = case.fields.iter().map(|&ty|
1141 type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>();
1142 let real_ty = Type::struct_(ccx, &fields[..], case.packed);
1143 let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to());
1145 variant_cx = f(variant_cx, case, variant_value);
1146 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1155 /// Access the struct drop flag, if present.
1156 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1159 -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1161 let tcx = bcx.tcx();
1162 let ptr_ty = bcx.tcx().mk_imm_ptr(tcx.dtor_type());
1164 Univariant(ref st, dtor) if dtor_active(dtor) => {
1165 let flag_ptr = GEPi(bcx, val, &[0, st.fields.len() - 1]);
1166 datum::immediate_rvalue_bcx(bcx, flag_ptr, ptr_ty).to_expr_datumblock()
1168 General(_, _, dtor) if dtor_active(dtor) => {
1170 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1171 let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
1172 bcx, tcx.dtor_type(), "drop_flag",
1173 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
1175 bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
1176 let ptr = struct_field_ptr(variant_cx, st, value, (st.fields.len() - 1), false);
1177 datum::Datum::new(ptr, ptr_ty, datum::Lvalue::new("adt::trans_drop_flag_ptr"))
1178 .store_to(variant_cx, scratch.val)
1180 let expr_datum = scratch.to_expr_datum();
1181 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1182 datum::DatumBlock::new(bcx, expr_datum)
1184 _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1188 /// Construct a constant value, suitable for initializing a
1189 /// GlobalVariable, given a case and constant values for its fields.
1190 /// Note that this may have a different LLVM type (and different
1191 /// alignment!) from the representation's `type_of`, so it needs a
1192 /// pointer cast before use.
1194 /// The LLVM type system does not directly support unions, and only
1195 /// pointers can be bitcast, so a constant (and, by extension, the
1196 /// GlobalVariable initialized by it) will have a type that can vary
1197 /// depending on which case of an enum it is.
1199 /// To understand the alignment situation, consider `enum E { V64(u64),
1200 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1201 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1202 /// i32, i32}`, which is 4-byte aligned.
1204 /// Currently the returned value has the same size as the type, but
1205 /// this could be changed in the future to avoid allocating unnecessary
1206 /// space after values of shorter-than-maximum cases.
1207 pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr: Disr,
1208 vals: &[ValueRef]) -> ValueRef {
1210 CEnum(ity, min, max) => {
1211 assert_eq!(vals.len(), 0);
1212 assert_discr_in_range(ity, min, max, discr);
1213 C_integral(ll_inttype(ccx, ity), discr as u64, true)
1215 General(ity, ref cases, _) => {
1216 let case = &cases[discr as usize];
1217 let (max_sz, _) = union_size_and_align(&cases[..]);
1218 let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1219 let mut f = vec![lldiscr];
1221 let mut contents = build_const_struct(ccx, case, &f[..]);
1222 contents.push_all(&[padding(ccx, max_sz - case.size)]);
1223 C_struct(ccx, &contents[..], false)
1225 Univariant(ref st, _dro) => {
1226 assert!(discr == 0);
1227 let contents = build_const_struct(ccx, st, vals);
1228 C_struct(ccx, &contents[..], st.packed)
1230 RawNullablePointer { nndiscr, nnty, .. } => {
1231 if discr == nndiscr {
1232 assert_eq!(vals.len(), 1);
1235 C_null(type_of::sizing_type_of(ccx, nnty))
1238 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1239 if discr == nndiscr {
1240 C_struct(ccx, &build_const_struct(ccx,
1245 let vals = nonnull.fields.iter().map(|&ty| {
1246 // Always use null even if it's not the `discrfield`th
1247 // field; see #8506.
1248 C_null(type_of::sizing_type_of(ccx, ty))
1249 }).collect::<Vec<ValueRef>>();
1250 C_struct(ccx, &build_const_struct(ccx,
1259 /// Compute struct field offsets relative to struct begin.
1260 fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1261 st: &Struct<'tcx>) -> Vec<u64> {
1262 let mut offsets = vec!();
1265 for &ty in &st.fields {
1266 let llty = type_of::sizing_type_of(ccx, ty);
1268 let type_align = type_of::align_of(ccx, ty);
1269 offset = roundup(offset, type_align);
1271 offsets.push(offset);
1272 offset += machine::llsize_of_alloc(ccx, llty);
1274 assert_eq!(st.fields.len(), offsets.len());
1278 /// Building structs is a little complicated, because we might need to
1279 /// insert padding if a field's value is less aligned than its type.
1281 /// Continuing the example from `trans_const`, a value of type `(u32,
1282 /// E)` should have the `E` at offset 8, but if that field's
1283 /// initializer is 4-byte aligned then simply translating the tuple as
1284 /// a two-element struct will locate it at offset 4, and accesses to it
1285 /// will read the wrong memory.
1286 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1287 st: &Struct<'tcx>, vals: &[ValueRef])
1289 assert_eq!(vals.len(), st.fields.len());
1291 let target_offsets = compute_struct_field_offsets(ccx, st);
1293 // offset of current value
1295 let mut cfields = Vec::new();
1296 for (&val, target_offset) in vals.iter().zip(target_offsets) {
1298 let val_align = machine::llalign_of_min(ccx, val_ty(val));
1299 offset = roundup(offset, val_align);
1301 if offset != target_offset {
1302 cfields.push(padding(ccx, target_offset - offset));
1303 offset = target_offset;
1305 assert!(!is_undef(val));
1307 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1310 assert!(st.sized && offset <= st.size);
1311 if offset != st.size {
1312 cfields.push(padding(ccx, st.size - offset));
1318 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1319 C_undef(Type::array(&Type::i8(ccx), size))
1322 // FIXME this utility routine should be somewhere more general
1324 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1326 /// Get the discriminant of a constant value.
1327 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1329 CEnum(ity, _, _) => {
1331 attr::SignedInt(..) => const_to_int(val) as Disr,
1332 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1335 General(ity, _, _) => {
1337 attr::SignedInt(..) => const_to_int(const_get_elt(ccx, val, &[0])) as Disr,
1338 attr::UnsignedInt(..) => const_to_uint(const_get_elt(ccx, val, &[0])) as Disr
1341 Univariant(..) => 0,
1342 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1343 ccx.sess().bug("const discrim access of non c-like enum")
1348 /// Extract a field of a constant value, as appropriate for its
1351 /// (Not to be confused with `common::const_get_elt`, which operates on
1352 /// raw LLVM-level structs and arrays.)
1353 pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
1354 _discr: Disr, ix: usize) -> ValueRef {
1356 CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
1357 Univariant(..) => const_struct_field(ccx, val, ix),
1358 General(..) => const_struct_field(ccx, val, ix + 1),
1359 RawNullablePointer { .. } => {
1363 StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1367 /// Extract field of struct-like const, skipping our alignment padding.
1368 fn const_struct_field(ccx: &CrateContext, val: ValueRef, ix: usize) -> ValueRef {
1369 // Get the ix-th non-undef element of the struct.
1370 let mut real_ix = 0; // actual position in the struct
1371 let mut ix = ix; // logical index relative to real_ix
1375 field = const_get_elt(ccx, val, &[real_ix]);
1376 if !is_undef(field) {
1379 real_ix = real_ix + 1;
1385 real_ix = real_ix + 1;