]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/adt.rs
Use ast attributes every where (remove HIR attributes).
[rust.git] / src / librustc_trans / trans / adt.rs
1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Representation of Algebraic Data Types
12 //!
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.)
18 //!
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.
22 //!
23 //! Having everything in one place will enable improvements to data
24 //! structure representation; possibilities include:
25 //!
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
30 //!   issue #4578.
31 //!
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.
39 //!
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.
43
44 pub use self::Repr::*;
45
46 use std::rc::Rc;
47
48 use llvm::{ValueRef, True, IntEQ, IntNE};
49 use back::abi::FAT_PTR_ADDR;
50 use middle::subst;
51 use middle::ty::{self, Ty};
52 use middle::ty::Disr;
53 use syntax::ast;
54 use syntax::attr;
55 use syntax::attr::IntType;
56 use trans::_match;
57 use trans::build::*;
58 use trans::cleanup;
59 use trans::cleanup::CleanupMethods;
60 use trans::common::*;
61 use trans::datum;
62 use trans::debuginfo::DebugLoc;
63 use trans::machine;
64 use trans::monomorphize;
65 use trans::type_::Type;
66 use trans::type_of;
67
68 type Hint = attr::ReprAttr;
69
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 {
74     prefix: Type,
75     needs_drop_flag: bool,
76 }
77
78 impl TypeContext {
79     pub fn prefix(&self) -> Type { self.prefix }
80     pub fn needs_drop_flag(&self) -> bool { self.needs_drop_flag }
81
82     fn direct(t: Type) -> TypeContext {
83         TypeContext { prefix: t, needs_drop_flag: false }
84     }
85     fn may_need_drop_flag(t: Type, needs_drop_flag: bool) -> TypeContext {
86         TypeContext { prefix: t, needs_drop_flag: needs_drop_flag }
87     }
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)
92     }
93 }
94
95 /// Representations.
96 #[derive(Eq, PartialEq, Debug)]
97 pub enum Repr<'tcx> {
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.
101     ///
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.
110     ///
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.
122     RawNullablePointer {
123         nndiscr: Disr,
124         nnty: Ty<'tcx>,
125         nullfields: Vec<Ty<'tcx>>
126     },
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).
132     ///
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>,
138         nndiscr: Disr,
139         discrfield: DiscrField,
140         nullfields: Vec<Ty<'tcx>>,
141     }
142 }
143
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.
149     pub size: u64,
150     pub align: u32,
151     pub sized: bool,
152     pub packed: bool,
153     pub fields: Vec<Ty<'tcx>>,
154 }
155
156 /// Convenience for `represent_type`.  There should probably be more or
157 /// these, for places in trans where the `Ty` isn't directly
158 /// available.
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))
162 }
163
164 /// Decides how to represent a given type.
165 pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
166                                 t: Ty<'tcx>)
167                                 -> Rc<Repr<'tcx>> {
168     debug!("Representing: {}", t);
169     match cx.adt_reprs().borrow().get(&t) {
170         Some(repr) => return repr.clone(),
171         None => {}
172     }
173
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());
177     repr
178 }
179
180 const fn repeat_u8_as_u32(val: u8) -> u32 {
181     (val as u32) << 24 | (val as u32) << 16 | (val as u32) << 8 | val as u32
182 }
183
184 const fn repeat_u8_as_u64(val: u8) -> u64 {
185     (repeat_u8_as_u32(val) as u64) << 32 | repeat_u8_as_u32(val) as u64
186 }
187
188 /// `DTOR_NEEDED_HINT` is a stack-local hint that just means
189 /// "we do not know whether the destructor has run or not; check the
190 /// drop-flag embedded in the value itself."
191 pub const DTOR_NEEDED_HINT: u8 = 0x3d;
192
193 /// `DTOR_MOVED_HINT` is a stack-local hint that means "this value has
194 /// definitely been moved; you do not need to run its destructor."
195 ///
196 /// (However, for now, such values may still end up being explicitly
197 /// zeroed by the generated code; this is the distinction between
198 /// `datum::DropFlagInfo::ZeroAndMaintain` versus
199 /// `datum::DropFlagInfo::DontZeroJustUse`.)
200 pub const DTOR_MOVED_HINT: u8 = 0x2d;
201
202 pub const DTOR_NEEDED: u8 = 0xd4;
203 pub const DTOR_NEEDED_U32: u32 = repeat_u8_as_u32(DTOR_NEEDED);
204 pub const DTOR_NEEDED_U64: u64 = repeat_u8_as_u64(DTOR_NEEDED);
205 #[allow(dead_code)]
206 pub fn dtor_needed_usize(ccx: &CrateContext) -> usize {
207     match &ccx.tcx().sess.target.target.target_pointer_width[..] {
208         "32" => DTOR_NEEDED_U32 as usize,
209         "64" => DTOR_NEEDED_U64 as usize,
210         tws => panic!("Unsupported target word size for int: {}", tws),
211     }
212 }
213
214 pub const DTOR_DONE: u8 = 0x1d;
215 pub const DTOR_DONE_U32: u32 = repeat_u8_as_u32(DTOR_DONE);
216 pub const DTOR_DONE_U64: u64 = repeat_u8_as_u64(DTOR_DONE);
217 #[allow(dead_code)]
218 pub fn dtor_done_usize(ccx: &CrateContext) -> usize {
219     match &ccx.tcx().sess.target.target.target_pointer_width[..] {
220         "32" => DTOR_DONE_U32 as usize,
221         "64" => DTOR_DONE_U64 as usize,
222         tws => panic!("Unsupported target word size for int: {}", tws),
223     }
224 }
225
226 fn dtor_to_init_u8(dtor: bool) -> u8 {
227     if dtor { DTOR_NEEDED } else { 0 }
228 }
229
230 pub trait GetDtorType<'tcx> { fn dtor_type(&self) -> Ty<'tcx>; }
231 impl<'tcx> GetDtorType<'tcx> for ty::ctxt<'tcx> {
232     fn dtor_type(&self) -> Ty<'tcx> { self.types.u8 }
233 }
234
235 fn dtor_active(flag: u8) -> bool {
236     flag != 0
237 }
238
239 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
240                                      t: Ty<'tcx>) -> Repr<'tcx> {
241     match t.sty {
242         ty::TyTuple(ref elems) => {
243             Univariant(mk_struct(cx, &elems[..], false, t), 0)
244         }
245         ty::TyStruct(def, substs) => {
246             let mut ftys = def.struct_variant().fields.iter().map(|field| {
247                 monomorphize::field_ty(cx.tcx(), substs, field)
248             }).collect::<Vec<_>>();
249             let packed = cx.tcx().lookup_packed(def.did);
250             let dtor = def.dtor_kind().has_drop_flag();
251             if dtor {
252                 ftys.push(cx.tcx().dtor_type());
253             }
254
255             Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
256         }
257         ty::TyClosure(_, ref substs) => {
258             Univariant(mk_struct(cx, &substs.upvar_tys, false, t), 0)
259         }
260         ty::TyEnum(def, substs) => {
261             let cases = get_cases(cx.tcx(), def, substs);
262             let hint = *cx.tcx().lookup_repr_hints(def.did).get(0)
263                 .unwrap_or(&attr::ReprAny);
264
265             let dtor = def.dtor_kind().has_drop_flag();
266
267             if cases.is_empty() {
268                 // Uninhabitable; represent as unit
269                 // (Typechecking will reject discriminant-sizing attrs.)
270                 assert_eq!(hint, attr::ReprAny);
271                 let ftys = if dtor { vec!(cx.tcx().dtor_type()) } else { vec!() };
272                 return Univariant(mk_struct(cx, &ftys[..], false, t),
273                                   dtor_to_init_u8(dtor));
274             }
275
276             if !dtor && cases.iter().all(|c| c.tys.is_empty()) {
277                 // All bodies empty -> intlike
278                 let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
279                 let bounds = IntBounds {
280                     ulo: *discrs.iter().min().unwrap(),
281                     uhi: *discrs.iter().max().unwrap(),
282                     slo: discrs.iter().map(|n| *n as i64).min().unwrap(),
283                     shi: discrs.iter().map(|n| *n as i64).max().unwrap()
284                 };
285                 return mk_cenum(cx, hint, &bounds);
286             }
287
288             // Since there's at least one
289             // non-empty body, explicit discriminants should have
290             // been rejected by a checker before this point.
291             if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
292                 cx.sess().bug(&format!("non-C-like enum {} with specified \
293                                         discriminants",
294                                        cx.tcx().item_path_str(def.did)));
295             }
296
297             if cases.len() == 1 {
298                 // Equivalent to a struct/tuple/newtype.
299                 // (Typechecking will reject discriminant-sizing attrs.)
300                 assert_eq!(hint, attr::ReprAny);
301                 let mut ftys = cases[0].tys.clone();
302                 if dtor { ftys.push(cx.tcx().dtor_type()); }
303                 return Univariant(mk_struct(cx, &ftys[..], false, t),
304                                   dtor_to_init_u8(dtor));
305             }
306
307             if !dtor && cases.len() == 2 && hint == attr::ReprAny {
308                 // Nullable pointer optimization
309                 let mut discr = 0;
310                 while discr < 2 {
311                     if cases[1 - discr].is_zerolen(cx, t) {
312                         let st = mk_struct(cx, &cases[discr].tys,
313                                            false, t);
314                         match cases[discr].find_ptr(cx) {
315                             Some(ref df) if df.len() == 1 && st.fields.len() == 1 => {
316                                 return RawNullablePointer {
317                                     nndiscr: discr as Disr,
318                                     nnty: st.fields[0],
319                                     nullfields: cases[1 - discr].tys.clone()
320                                 };
321                             }
322                             Some(mut discrfield) => {
323                                 discrfield.push(0);
324                                 discrfield.reverse();
325                                 return StructWrappedNullablePointer {
326                                     nndiscr: discr as Disr,
327                                     nonnull: st,
328                                     discrfield: discrfield,
329                                     nullfields: cases[1 - discr].tys.clone()
330                                 };
331                             }
332                             None => {}
333                         }
334                     }
335                     discr += 1;
336                 }
337             }
338
339             // The general case.
340             assert!((cases.len() - 1) as i64 >= 0);
341             let bounds = IntBounds { ulo: 0, uhi: (cases.len() - 1) as u64,
342                                      slo: 0, shi: (cases.len() - 1) as i64 };
343             let min_ity = range_to_inttype(cx, hint, &bounds);
344
345             // Create the set of structs that represent each variant
346             // Use the minimum integer type we figured out above
347             let fields : Vec<_> = cases.iter().map(|c| {
348                 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
349                 ftys.push_all(&c.tys);
350                 if dtor { ftys.push(cx.tcx().dtor_type()); }
351                 mk_struct(cx, &ftys, false, t)
352             }).collect();
353
354
355             // Check to see if we should use a different type for the
356             // discriminant. If the overall alignment of the type is
357             // the same as the first field in each variant, we can safely use
358             // an alignment-sized type.
359             // We increase the size of the discriminant to avoid LLVM copying
360             // padding when it doesn't need to. This normally causes unaligned
361             // load/stores and excessive memcpy/memset operations. By using a
362             // bigger integer size, LLVM can be sure about it's contents and
363             // won't be so conservative.
364             // This check is needed to avoid increasing the size of types when
365             // the alignment of the first field is smaller than the overall
366             // alignment of the type.
367             let (_, align) = union_size_and_align(&fields);
368             let mut use_align = true;
369             for st in &fields {
370                 // Get the first non-zero-sized field
371                 let field = st.fields.iter().skip(1).filter(|ty| {
372                     let t = type_of::sizing_type_of(cx, **ty);
373                     machine::llsize_of_real(cx, t) != 0 ||
374                     // This case is only relevant for zero-sized types with large alignment
375                     machine::llalign_of_min(cx, t) != 1
376                 }).next();
377
378                 if let Some(field) = field {
379                     let field_align = type_of::align_of(cx, *field);
380                     if field_align != align {
381                         use_align = false;
382                         break;
383                     }
384                 }
385             }
386             let ity = if use_align {
387                 // Use the overall alignment
388                 match align {
389                     1 => attr::UnsignedInt(ast::TyU8),
390                     2 => attr::UnsignedInt(ast::TyU16),
391                     4 => attr::UnsignedInt(ast::TyU32),
392                     8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
393                         attr::UnsignedInt(ast::TyU64),
394                     _ => min_ity // use min_ity as a fallback
395                 }
396             } else {
397                 min_ity
398             };
399
400             let fields : Vec<_> = cases.iter().map(|c| {
401                 let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity));
402                 ftys.push_all(&c.tys);
403                 if dtor { ftys.push(cx.tcx().dtor_type()); }
404                 mk_struct(cx, &ftys[..], false, t)
405             }).collect();
406
407             ensure_enum_fits_in_address_space(cx, &fields[..], t);
408
409             General(ity, fields, dtor_to_init_u8(dtor))
410         }
411         _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}", t))
412     }
413 }
414
415 // this should probably all be in ty
416 struct Case<'tcx> {
417     discr: Disr,
418     tys: Vec<Ty<'tcx>>
419 }
420
421 /// This represents the (GEP) indices to follow to get to the discriminant field
422 pub type DiscrField = Vec<usize>;
423
424 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
425                                     ty: Ty<'tcx>,
426                                     mut path: DiscrField) -> Option<DiscrField> {
427     match ty.sty {
428         // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
429         ty::TyRef(_, ty::TypeAndMut { ty, .. }) | ty::TyBox(ty) if !type_is_sized(tcx, ty) => {
430             path.push(FAT_PTR_ADDR);
431             Some(path)
432         },
433
434         // Regular thin pointer: &T/&mut T/Box<T>
435         ty::TyRef(..) | ty::TyBox(..) => Some(path),
436
437         // Functions are just pointers
438         ty::TyBareFn(..) => Some(path),
439
440         // Is this the NonZero lang item wrapping a pointer or integer type?
441         ty::TyStruct(def, substs) if Some(def.did) == tcx.lang_items.non_zero() => {
442             let nonzero_fields = &def.struct_variant().fields;
443             assert_eq!(nonzero_fields.len(), 1);
444             let field_ty = monomorphize::field_ty(tcx, substs, &nonzero_fields[0]);
445             match field_ty.sty {
446                 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) if !type_is_sized(tcx, ty) => {
447                     path.push_all(&[0, FAT_PTR_ADDR]);
448                     Some(path)
449                 },
450                 ty::TyRawPtr(..) | ty::TyInt(..) | ty::TyUint(..) => {
451                     path.push(0);
452                     Some(path)
453                 },
454                 _ => None
455             }
456         },
457
458         // Perhaps one of the fields of this struct is non-zero
459         // let's recurse and find out
460         ty::TyStruct(def, substs) => {
461             for (j, field) in def.struct_variant().fields.iter().enumerate() {
462                 let field_ty = monomorphize::field_ty(tcx, substs, field);
463                 if let Some(mut fpath) = find_discr_field_candidate(tcx, field_ty, path.clone()) {
464                     fpath.push(j);
465                     return Some(fpath);
466                 }
467             }
468             None
469         },
470
471         // Perhaps one of the upvars of this struct is non-zero
472         // Let's recurse and find out!
473         ty::TyClosure(_, ref substs) => {
474             for (j, &ty) in substs.upvar_tys.iter().enumerate() {
475                 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
476                     fpath.push(j);
477                     return Some(fpath);
478                 }
479             }
480             None
481         },
482
483         // Can we use one of the fields in this tuple?
484         ty::TyTuple(ref tys) => {
485             for (j, &ty) in tys.iter().enumerate() {
486                 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
487                     fpath.push(j);
488                     return Some(fpath);
489                 }
490             }
491             None
492         },
493
494         // Is this a fixed-size array of something non-zero
495         // with at least one element?
496         ty::TyArray(ety, d) if d > 0 => {
497             if let Some(mut vpath) = find_discr_field_candidate(tcx, ety, path) {
498                 vpath.push(0);
499                 Some(vpath)
500             } else {
501                 None
502             }
503         },
504
505         // Anything else is not a pointer
506         _ => None
507     }
508 }
509
510 impl<'tcx> Case<'tcx> {
511     fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool {
512         mk_struct(cx, &self.tys, false, scapegoat).size == 0
513     }
514
515     fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> {
516         for (i, &ty) in self.tys.iter().enumerate() {
517             if let Some(mut path) = find_discr_field_candidate(cx.tcx(), ty, vec![]) {
518                 path.push(i);
519                 return Some(path);
520             }
521         }
522         None
523     }
524 }
525
526 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
527                    adt: ty::AdtDef<'tcx>,
528                    substs: &subst::Substs<'tcx>)
529                    -> Vec<Case<'tcx>> {
530     adt.variants.iter().map(|vi| {
531         let field_tys = vi.fields.iter().map(|field| {
532             monomorphize::field_ty(tcx, substs, field)
533         }).collect();
534         Case { discr: vi.disr_val, tys: field_tys }
535     }).collect()
536 }
537
538 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
539                        tys: &[Ty<'tcx>], packed: bool,
540                        scapegoat: Ty<'tcx>)
541                        -> Struct<'tcx> {
542     let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
543     let lltys : Vec<Type> = if sized {
544         tys.iter().map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
545     } else {
546         tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
547            .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
548     };
549
550     ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
551
552     let llty_rec = Type::struct_(cx, &lltys[..], packed);
553     Struct {
554         size: machine::llsize_of_alloc(cx, llty_rec),
555         align: machine::llalign_of_min(cx, llty_rec),
556         sized: sized,
557         packed: packed,
558         fields: tys.to_vec(),
559     }
560 }
561
562 #[derive(Debug)]
563 struct IntBounds {
564     slo: i64,
565     shi: i64,
566     ulo: u64,
567     uhi: u64
568 }
569
570 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
571                       hint: Hint, bounds: &IntBounds)
572                       -> Repr<'tcx> {
573     let it = range_to_inttype(cx, hint, bounds);
574     match it {
575         attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
576         attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
577     }
578 }
579
580 fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType {
581     debug!("range_to_inttype: {:?} {:?}", hint, bounds);
582     // Lists of sizes to try.  u64 is always allowed as a fallback.
583     #[allow(non_upper_case_globals)]
584     const choose_shortest: &'static [IntType] = &[
585         attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
586         attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
587         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
588     #[allow(non_upper_case_globals)]
589     const at_least_32: &'static [IntType] = &[
590         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
591
592     let attempts;
593     match hint {
594         attr::ReprInt(span, ity) => {
595             if !bounds_usable(cx, ity, bounds) {
596                 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
597             }
598             return ity;
599         }
600         attr::ReprExtern => {
601             attempts = match &cx.sess().target.target.arch[..] {
602                 // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
603                 // appears to be used on Linux and NetBSD, but some systems may use the variant
604                 // corresponding to `choose_shortest`.  However, we don't run on those yet...?
605                 "arm" => at_least_32,
606                 _ => at_least_32,
607             }
608         }
609         attr::ReprAny => {
610             attempts = choose_shortest;
611         },
612         attr::ReprPacked => {
613             cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
614         }
615         attr::ReprSimd => {
616             cx.tcx().sess.bug("range_to_inttype: found ReprSimd on an enum");
617         }
618     }
619     for &ity in attempts {
620         if bounds_usable(cx, ity, bounds) {
621             return ity;
622         }
623     }
624     return attr::UnsignedInt(ast::TyU64);
625 }
626
627 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
628     match ity {
629         attr::SignedInt(t) => Type::int_from_ty(cx, t),
630         attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
631     }
632 }
633
634 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
635     debug!("bounds_usable: {:?} {:?}", ity, bounds);
636     match ity {
637         attr::SignedInt(_) => {
638             let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true);
639             let llhi = C_integral(ll_inttype(cx, ity), bounds.shi as u64, true);
640             bounds.slo == const_to_int(lllo) as i64 && bounds.shi == const_to_int(llhi) as i64
641         }
642         attr::UnsignedInt(_) => {
643             let lllo = C_integral(ll_inttype(cx, ity), bounds.ulo, false);
644             let llhi = C_integral(ll_inttype(cx, ity), bounds.uhi, false);
645             bounds.ulo == const_to_uint(lllo) as u64 && bounds.uhi == const_to_uint(llhi) as u64
646         }
647     }
648 }
649
650 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
651     match ity {
652         attr::SignedInt(t) => tcx.mk_mach_int(t),
653         attr::UnsignedInt(t) => tcx.mk_mach_uint(t)
654     }
655 }
656
657 // LLVM doesn't like types that don't fit in the address space
658 fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
659                                                  fields: &[Type],
660                                                  packed: bool,
661                                                  scapegoat: Ty<'tcx>) {
662     let mut offset = 0;
663     for &llty in fields {
664         // Invariant: offset < ccx.obj_size_bound() <= 1<<61
665         if !packed {
666             let type_align = machine::llalign_of_min(ccx, llty);
667             offset = roundup(offset, type_align);
668         }
669         // type_align is a power-of-2, so still offset < ccx.obj_size_bound()
670         // llsize_of_alloc(ccx, llty) is also less than ccx.obj_size_bound()
671         // so the sum is less than 1<<62 (and therefore can't overflow).
672         offset += machine::llsize_of_alloc(ccx, llty);
673
674         if offset >= ccx.obj_size_bound() {
675             ccx.report_overbig_object(scapegoat);
676         }
677     }
678 }
679
680 fn union_size_and_align(sts: &[Struct]) -> (machine::llsize, machine::llalign) {
681     let size = sts.iter().map(|st| st.size).max().unwrap();
682     let align = sts.iter().map(|st| st.align).max().unwrap();
683     (roundup(size, align), align)
684 }
685
686 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
687                                                fields: &[Struct],
688                                                scapegoat: Ty<'tcx>) {
689     let (total_size, _) = union_size_and_align(fields);
690
691     if total_size >= ccx.obj_size_bound() {
692         ccx.report_overbig_object(scapegoat);
693     }
694 }
695
696
697 /// LLVM-level types are a little complicated.
698 ///
699 /// C-like enums need to be actual ints, not wrapped in a struct,
700 /// because that changes the ABI on some platforms (see issue #10308).
701 ///
702 /// For nominal types, in some cases, we need to use LLVM named structs
703 /// and fill in the actual contents in a second pass to prevent
704 /// unbounded recursion; see also the comments in `trans::type_of`.
705 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>) -> Type {
706     let c = generic_type_of(cx, r, None, false, false, false);
707     assert!(!c.needs_drop_flag);
708     c.prefix
709 }
710
711
712 // Pass dst=true if the type you are passing is a DST. Yes, we could figure
713 // this out, but if you call this on an unsized type without realising it, you
714 // are going to get the wrong type (it will not include the unsized parts of it).
715 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
716                                 r: &Repr<'tcx>, dst: bool) -> Type {
717     let c = generic_type_of(cx, r, None, true, dst, false);
718     assert!(!c.needs_drop_flag);
719     c.prefix
720 }
721 pub fn sizing_type_context_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
722                                         r: &Repr<'tcx>, dst: bool) -> TypeContext {
723     generic_type_of(cx, r, None, true, dst, true)
724 }
725 pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
726                                     r: &Repr<'tcx>, name: &str) -> Type {
727     let c = generic_type_of(cx, r, Some(name), false, false, false);
728     assert!(!c.needs_drop_flag);
729     c.prefix
730 }
731 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
732                                 r: &Repr<'tcx>, llty: &mut Type) {
733     match *r {
734         CEnum(..) | General(..) | RawNullablePointer { .. } => { }
735         Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
736             llty.set_struct_body(&struct_llfields(cx, st, false, false),
737                                  st.packed)
738     }
739 }
740
741 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
742                              r: &Repr<'tcx>,
743                              name: Option<&str>,
744                              sizing: bool,
745                              dst: bool,
746                              delay_drop_flag: bool) -> TypeContext {
747     debug!("adt::generic_type_of r: {:?} name: {:?} sizing: {} dst: {} delay_drop_flag: {}",
748            r, name, sizing, dst, delay_drop_flag);
749     match *r {
750         CEnum(ity, _, _) => TypeContext::direct(ll_inttype(cx, ity)),
751         RawNullablePointer { nnty, .. } =>
752             TypeContext::direct(type_of::sizing_type_of(cx, nnty)),
753         StructWrappedNullablePointer { nonnull: ref st, .. } => {
754             match name {
755                 None => {
756                     TypeContext::direct(
757                         Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
758                                       st.packed))
759                 }
760                 Some(name) => {
761                     assert_eq!(sizing, false);
762                     TypeContext::direct(Type::named_struct(cx, name))
763                 }
764             }
765         }
766         Univariant(ref st, dtor_needed) => {
767             let dtor_needed = dtor_needed != 0;
768             match name {
769                 None => {
770                     let mut fields = struct_llfields(cx, st, sizing, dst);
771                     if delay_drop_flag && dtor_needed {
772                         fields.pop();
773                     }
774                     TypeContext::may_need_drop_flag(
775                         Type::struct_(cx, &fields,
776                                       st.packed),
777                         delay_drop_flag && dtor_needed)
778                 }
779                 Some(name) => {
780                     // Hypothesis: named_struct's can never need a
781                     // drop flag. (... needs validation.)
782                     assert_eq!(sizing, false);
783                     TypeContext::direct(Type::named_struct(cx, name))
784                 }
785             }
786         }
787         General(ity, ref sts, dtor_needed) => {
788             let dtor_needed = dtor_needed != 0;
789             // We need a representation that has:
790             // * The alignment of the most-aligned field
791             // * The size of the largest variant (rounded up to that alignment)
792             // * No alignment padding anywhere any variant has actual data
793             //   (currently matters only for enums small enough to be immediate)
794             // * The discriminant in an obvious place.
795             //
796             // So we start with the discriminant, pad it up to the alignment with
797             // more of its own type, then use alignment-sized ints to get the rest
798             // of the size.
799             //
800             // FIXME #10604: this breaks when vector types are present.
801             let (size, align) = union_size_and_align(&sts[..]);
802             let align_s = align as u64;
803             assert_eq!(size % align_s, 0);
804             let align_units = size / align_s - 1;
805
806             let discr_ty = ll_inttype(cx, ity);
807             let discr_size = machine::llsize_of_alloc(cx, discr_ty);
808             let fill_ty = match align_s {
809                 1 => Type::array(&Type::i8(cx), align_units),
810                 2 => Type::array(&Type::i16(cx), align_units),
811                 4 => Type::array(&Type::i32(cx), align_units),
812                 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
813                                  Type::array(&Type::i64(cx), align_units),
814                 a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
815                                                               align_units),
816                 _ => panic!("unsupported enum alignment: {}", align)
817             };
818             assert_eq!(machine::llalign_of_min(cx, fill_ty), align);
819             assert_eq!(align_s % discr_size, 0);
820             let mut fields: Vec<Type> =
821                 [discr_ty,
822                  Type::array(&discr_ty, align_s / discr_size - 1),
823                  fill_ty].iter().cloned().collect();
824             if delay_drop_flag && dtor_needed {
825                 fields.pop();
826             }
827             match name {
828                 None => {
829                     TypeContext::may_need_drop_flag(
830                         Type::struct_(cx, &fields[..], false),
831                         delay_drop_flag && dtor_needed)
832                 }
833                 Some(name) => {
834                     let mut llty = Type::named_struct(cx, name);
835                     llty.set_struct_body(&fields[..], false);
836                     TypeContext::may_need_drop_flag(
837                         llty,
838                         delay_drop_flag && dtor_needed)
839                 }
840             }
841         }
842     }
843 }
844
845 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
846                              sizing: bool, dst: bool) -> Vec<Type> {
847     if sizing {
848         st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
849             .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
850     } else {
851         st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
852     }
853 }
854
855 /// Obtain a representation of the discriminant sufficient to translate
856 /// destructuring; this may or may not involve the actual discriminant.
857 ///
858 /// This should ideally be less tightly tied to `_match`.
859 pub fn trans_switch<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
860                                 r: &Repr<'tcx>, scrutinee: ValueRef)
861                                 -> (_match::BranchKind, Option<ValueRef>) {
862     match *r {
863         CEnum(..) | General(..) |
864         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
865             (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
866         }
867         Univariant(..) => {
868             // N.B.: Univariant means <= 1 enum variants (*not* == 1 variants).
869             (_match::Single, None)
870         }
871     }
872 }
873
874 pub fn is_discr_signed<'tcx>(r: &Repr<'tcx>) -> bool {
875     match *r {
876         CEnum(ity, _, _) => ity.is_signed(),
877         General(ity, _, _) => ity.is_signed(),
878         Univariant(..) => false,
879         RawNullablePointer { .. } => false,
880         StructWrappedNullablePointer { .. } => false,
881     }
882 }
883
884 /// Obtain the actual discriminant of a value.
885 pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
886                                    scrutinee: ValueRef, cast_to: Option<Type>)
887     -> ValueRef {
888     debug!("trans_get_discr r: {:?}", r);
889     let val = match *r {
890         CEnum(ity, min, max) => load_discr(bcx, ity, scrutinee, min, max),
891         General(ity, ref cases, _) => {
892             let ptr = StructGEP(bcx, scrutinee, 0);
893             load_discr(bcx, ity, ptr, 0, (cases.len() - 1) as Disr)
894         }
895         Univariant(..) => C_u8(bcx.ccx(), 0),
896         RawNullablePointer { nndiscr, nnty, .. } =>  {
897             let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
898             let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
899             ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None)
900         }
901         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
902             struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee)
903         }
904     };
905     match cast_to {
906         None => val,
907         Some(llty) => if is_discr_signed(r) { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
908     }
909 }
910
911 fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField,
912                                     scrutinee: ValueRef) -> ValueRef {
913     let llptrptr = GEPi(bcx, scrutinee, &discrfield[..]);
914     let llptr = Load(bcx, llptrptr);
915     let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
916     ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
917 }
918
919 /// Helper for cases where the discriminant is simply loaded.
920 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
921     -> ValueRef {
922     let llty = ll_inttype(bcx.ccx(), ity);
923     assert_eq!(val_ty(ptr), llty.ptr_to());
924     let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
925     assert!(bits <= 64);
926     let  bits = bits as usize;
927     let mask = (!0u64 >> (64 - bits)) as Disr;
928     // For a (max) discr of -1, max will be `-1 as usize`, which overflows.
929     // However, that is fine here (it would still represent the full range),
930     if (max.wrapping_add(1)) & mask == min & mask {
931         // i.e., if the range is everything.  The lo==hi case would be
932         // rejected by the LLVM verifier (it would mean either an
933         // empty set, which is impossible, or the entire range of the
934         // type, which is pointless).
935         Load(bcx, ptr)
936     } else {
937         // llvm::ConstantRange can deal with ranges that wrap around,
938         // so an overflow on (max + 1) is fine.
939         LoadRangeAssert(bcx, ptr, min, (max.wrapping_add(1)), /* signed: */ True)
940     }
941 }
942
943 /// Yield information about how to dispatch a case of the
944 /// discriminant-like value returned by `trans_switch`.
945 ///
946 /// This should ideally be less tightly tied to `_match`.
947 pub fn trans_case<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr, discr: Disr)
948                               -> _match::OptResult<'blk, 'tcx> {
949     match *r {
950         CEnum(ity, _, _) => {
951             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
952                                                               discr as u64, true)))
953         }
954         General(ity, _, _) => {
955             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
956                                                               discr as u64, true)))
957         }
958         Univariant(..) => {
959             bcx.ccx().sess().bug("no cases for univariants or structs")
960         }
961         RawNullablePointer { .. } |
962         StructWrappedNullablePointer { .. } => {
963             assert!(discr == 0 || discr == 1);
964             _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
965         }
966     }
967 }
968
969 /// Set the discriminant for a new value of the given case of the given
970 /// representation.
971 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
972                                    val: ValueRef, discr: Disr) {
973     match *r {
974         CEnum(ity, min, max) => {
975             assert_discr_in_range(ity, min, max, discr);
976             Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
977                   val);
978         }
979         General(ity, ref cases, dtor) => {
980             if dtor_active(dtor) {
981                 let ptr = trans_field_ptr(bcx, r, val, discr,
982                                           cases[discr as usize].fields.len() - 2);
983                 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED), ptr);
984             }
985             Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
986                   StructGEP(bcx, val, 0));
987         }
988         Univariant(ref st, dtor) => {
989             assert_eq!(discr, 0);
990             if dtor_active(dtor) {
991                 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED),
992                       StructGEP(bcx, val, st.fields.len() - 1));
993             }
994         }
995         RawNullablePointer { nndiscr, nnty, ..} => {
996             if discr != nndiscr {
997                 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
998                 Store(bcx, C_null(llptrty), val);
999             }
1000         }
1001         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
1002             if discr != nndiscr {
1003                 let llptrptr = GEPi(bcx, val, &discrfield[..]);
1004                 let llptrty = val_ty(llptrptr).element_type();
1005                 Store(bcx, C_null(llptrty), llptrptr);
1006             }
1007         }
1008     }
1009 }
1010
1011 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
1012     match ity {
1013         attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
1014         attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
1015     }
1016 }
1017
1018 /// The number of fields in a given case; for use when obtaining this
1019 /// information from the type or definition is less convenient.
1020 pub fn num_args(r: &Repr, discr: Disr) -> usize {
1021     match *r {
1022         CEnum(..) => 0,
1023         Univariant(ref st, dtor) => {
1024             assert_eq!(discr, 0);
1025             st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
1026         }
1027         General(_, ref cases, dtor) => {
1028             cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
1029         }
1030         RawNullablePointer { nndiscr, ref nullfields, .. } => {
1031             if discr == nndiscr { 1 } else { nullfields.len() }
1032         }
1033         StructWrappedNullablePointer { ref nonnull, nndiscr,
1034                                        ref nullfields, .. } => {
1035             if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
1036         }
1037     }
1038 }
1039
1040 /// Access a field, at a point when the value's case is known.
1041 pub fn trans_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
1042                                    val: ValueRef, discr: Disr, ix: usize) -> ValueRef {
1043     // Note: if this ever needs to generate conditionals (e.g., if we
1044     // decide to do some kind of cdr-coding-like non-unique repr
1045     // someday), it will need to return a possibly-new bcx as well.
1046     match *r {
1047         CEnum(..) => {
1048             bcx.ccx().sess().bug("element access in C-like enum")
1049         }
1050         Univariant(ref st, _dtor) => {
1051             assert_eq!(discr, 0);
1052             struct_field_ptr(bcx, st, val, ix, false)
1053         }
1054         General(_, ref cases, _) => {
1055             struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
1056         }
1057         RawNullablePointer { nndiscr, ref nullfields, .. } |
1058         StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
1059             // The unit-like case might have a nonzero number of unit-like fields.
1060             // (e.d., Result of Either with (), as one side.)
1061             let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
1062             assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
1063             // The contents of memory at this pointer can't matter, but use
1064             // the value that's "reasonable" in case of pointer comparison.
1065             PointerCast(bcx, val, ty.ptr_to())
1066         }
1067         RawNullablePointer { nndiscr, nnty, .. } => {
1068             assert_eq!(ix, 0);
1069             assert_eq!(discr, nndiscr);
1070             let ty = type_of::type_of(bcx.ccx(), nnty);
1071             PointerCast(bcx, val, ty.ptr_to())
1072         }
1073         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1074             assert_eq!(discr, nndiscr);
1075             struct_field_ptr(bcx, nonnull, val, ix, false)
1076         }
1077     }
1078 }
1079
1080 pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, val: ValueRef,
1081                                     ix: usize, needs_cast: bool) -> ValueRef {
1082     let val = if needs_cast {
1083         let ccx = bcx.ccx();
1084         let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>();
1085         let real_ty = Type::struct_(ccx, &fields[..], st.packed);
1086         PointerCast(bcx, val, real_ty.ptr_to())
1087     } else {
1088         val
1089     };
1090
1091     StructGEP(bcx, val, ix)
1092 }
1093
1094 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1095                                     r: &Repr<'tcx>,
1096                                     value: ValueRef,
1097                                     mut f: F)
1098                                     -> Block<'blk, 'tcx> where
1099     F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1100 {
1101     let fcx = bcx.fcx;
1102     match *r {
1103         Univariant(ref st, _) => {
1104             f(bcx, st, value)
1105         }
1106         General(ity, ref cases, _) => {
1107             let ccx = bcx.ccx();
1108
1109             // See the comments in trans/base.rs for more information (inside
1110             // iter_structural_ty), but the gist here is that if the enum's
1111             // discriminant is *not* in the range that we're expecting (in which
1112             // case we'll take the fall-through branch on the switch
1113             // instruction) then we can't just optimize this to an Unreachable
1114             // block.
1115             //
1116             // Currently we still have filling drop, so this means that the drop
1117             // glue for enums may be called when the enum has been paved over
1118             // with the "I've been dropped" value. In this case the default
1119             // branch of the switch instruction will actually be taken at
1120             // runtime, so the basic block isn't actually unreachable, so we
1121             // need to make it do something with defined behavior. In this case
1122             // we just return early from the function.
1123             let ret_void_cx = fcx.new_temp_block("enum-variant-iter-ret-void");
1124             RetVoid(ret_void_cx, DebugLoc::None);
1125
1126             let discr_val = trans_get_discr(bcx, r, value, None);
1127             let llswitch = Switch(bcx, discr_val, ret_void_cx.llbb, cases.len());
1128             let bcx_next = fcx.new_temp_block("enum-variant-iter-next");
1129
1130             for (discr, case) in cases.iter().enumerate() {
1131                 let mut variant_cx = fcx.new_temp_block(
1132                     &format!("enum-variant-iter-{}", &discr.to_string())
1133                 );
1134                 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1135                 AddCase(llswitch, rhs_val, variant_cx.llbb);
1136
1137                 let fields = case.fields.iter().map(|&ty|
1138                     type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>();
1139                 let real_ty = Type::struct_(ccx, &fields[..], case.packed);
1140                 let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to());
1141
1142                 variant_cx = f(variant_cx, case, variant_value);
1143                 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1144             }
1145
1146             bcx_next
1147         }
1148         _ => unreachable!()
1149     }
1150 }
1151
1152 /// Access the struct drop flag, if present.
1153 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1154                                        r: &Repr<'tcx>,
1155                                        val: ValueRef)
1156                                        -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1157 {
1158     let tcx = bcx.tcx();
1159     let ptr_ty = bcx.tcx().mk_imm_ptr(tcx.dtor_type());
1160     match *r {
1161         Univariant(ref st, dtor) if dtor_active(dtor) => {
1162             let flag_ptr = StructGEP(bcx, val, st.fields.len() - 1);
1163             datum::immediate_rvalue_bcx(bcx, flag_ptr, ptr_ty).to_expr_datumblock()
1164         }
1165         General(_, _, dtor) if dtor_active(dtor) => {
1166             let fcx = bcx.fcx;
1167             let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1168             let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
1169                 bcx, tcx.dtor_type(), "drop_flag",
1170                 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
1171             ));
1172             bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
1173                 let ptr = struct_field_ptr(variant_cx, st, value, (st.fields.len() - 1), false);
1174                 datum::Datum::new(ptr, ptr_ty, datum::Lvalue::new("adt::trans_drop_flag_ptr"))
1175                     .store_to(variant_cx, scratch.val)
1176             });
1177             let expr_datum = scratch.to_expr_datum();
1178             fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1179             datum::DatumBlock::new(bcx, expr_datum)
1180         }
1181         _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1182     }
1183 }
1184
1185 /// Construct a constant value, suitable for initializing a
1186 /// GlobalVariable, given a case and constant values for its fields.
1187 /// Note that this may have a different LLVM type (and different
1188 /// alignment!) from the representation's `type_of`, so it needs a
1189 /// pointer cast before use.
1190 ///
1191 /// The LLVM type system does not directly support unions, and only
1192 /// pointers can be bitcast, so a constant (and, by extension, the
1193 /// GlobalVariable initialized by it) will have a type that can vary
1194 /// depending on which case of an enum it is.
1195 ///
1196 /// To understand the alignment situation, consider `enum E { V64(u64),
1197 /// V32(u32, u32) }` on Windows.  The type has 8-byte alignment to
1198 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1199 /// i32, i32}`, which is 4-byte aligned.
1200 ///
1201 /// Currently the returned value has the same size as the type, but
1202 /// this could be changed in the future to avoid allocating unnecessary
1203 /// space after values of shorter-than-maximum cases.
1204 pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr: Disr,
1205                              vals: &[ValueRef]) -> ValueRef {
1206     match *r {
1207         CEnum(ity, min, max) => {
1208             assert_eq!(vals.len(), 0);
1209             assert_discr_in_range(ity, min, max, discr);
1210             C_integral(ll_inttype(ccx, ity), discr as u64, true)
1211         }
1212         General(ity, ref cases, _) => {
1213             let case = &cases[discr as usize];
1214             let (max_sz, _) = union_size_and_align(&cases[..]);
1215             let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1216             let mut f = vec![lldiscr];
1217             f.push_all(vals);
1218             let mut contents = build_const_struct(ccx, case, &f[..]);
1219             contents.push_all(&[padding(ccx, max_sz - case.size)]);
1220             C_struct(ccx, &contents[..], false)
1221         }
1222         Univariant(ref st, _dro) => {
1223             assert!(discr == 0);
1224             let contents = build_const_struct(ccx, st, vals);
1225             C_struct(ccx, &contents[..], st.packed)
1226         }
1227         RawNullablePointer { nndiscr, nnty, .. } => {
1228             if discr == nndiscr {
1229                 assert_eq!(vals.len(), 1);
1230                 vals[0]
1231             } else {
1232                 C_null(type_of::sizing_type_of(ccx, nnty))
1233             }
1234         }
1235         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1236             if discr == nndiscr {
1237                 C_struct(ccx, &build_const_struct(ccx,
1238                                                  nonnull,
1239                                                  vals),
1240                          false)
1241             } else {
1242                 let vals = nonnull.fields.iter().map(|&ty| {
1243                     // Always use null even if it's not the `discrfield`th
1244                     // field; see #8506.
1245                     C_null(type_of::sizing_type_of(ccx, ty))
1246                 }).collect::<Vec<ValueRef>>();
1247                 C_struct(ccx, &build_const_struct(ccx,
1248                                                  nonnull,
1249                                                  &vals[..]),
1250                          false)
1251             }
1252         }
1253     }
1254 }
1255
1256 /// Compute struct field offsets relative to struct begin.
1257 fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1258                                           st: &Struct<'tcx>) -> Vec<u64> {
1259     let mut offsets = vec!();
1260
1261     let mut offset = 0;
1262     for &ty in &st.fields {
1263         let llty = type_of::sizing_type_of(ccx, ty);
1264         if !st.packed {
1265             let type_align = type_of::align_of(ccx, ty);
1266             offset = roundup(offset, type_align);
1267         }
1268         offsets.push(offset);
1269         offset += machine::llsize_of_alloc(ccx, llty);
1270     }
1271     assert_eq!(st.fields.len(), offsets.len());
1272     offsets
1273 }
1274
1275 /// Building structs is a little complicated, because we might need to
1276 /// insert padding if a field's value is less aligned than its type.
1277 ///
1278 /// Continuing the example from `trans_const`, a value of type `(u32,
1279 /// E)` should have the `E` at offset 8, but if that field's
1280 /// initializer is 4-byte aligned then simply translating the tuple as
1281 /// a two-element struct will locate it at offset 4, and accesses to it
1282 /// will read the wrong memory.
1283 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1284                                 st: &Struct<'tcx>, vals: &[ValueRef])
1285                                 -> Vec<ValueRef> {
1286     assert_eq!(vals.len(), st.fields.len());
1287
1288     let target_offsets = compute_struct_field_offsets(ccx, st);
1289
1290     // offset of current value
1291     let mut offset = 0;
1292     let mut cfields = Vec::new();
1293     for (&val, target_offset) in vals.iter().zip(target_offsets) {
1294         if !st.packed {
1295             let val_align = machine::llalign_of_min(ccx, val_ty(val));
1296             offset = roundup(offset, val_align);
1297         }
1298         if offset != target_offset {
1299             cfields.push(padding(ccx, target_offset - offset));
1300             offset = target_offset;
1301         }
1302         assert!(!is_undef(val));
1303         cfields.push(val);
1304         offset += machine::llsize_of_alloc(ccx, val_ty(val));
1305     }
1306
1307     assert!(st.sized && offset <= st.size);
1308     if offset != st.size {
1309         cfields.push(padding(ccx, st.size - offset));
1310     }
1311
1312     cfields
1313 }
1314
1315 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1316     C_undef(Type::array(&Type::i8(ccx), size))
1317 }
1318
1319 // FIXME this utility routine should be somewhere more general
1320 #[inline]
1321 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1322
1323 /// Get the discriminant of a constant value.
1324 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1325     match *r {
1326         CEnum(ity, _, _) => {
1327             match ity {
1328                 attr::SignedInt(..) => const_to_int(val) as Disr,
1329                 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1330             }
1331         }
1332         General(ity, _, _) => {
1333             match ity {
1334                 attr::SignedInt(..) => const_to_int(const_get_elt(ccx, val, &[0])) as Disr,
1335                 attr::UnsignedInt(..) => const_to_uint(const_get_elt(ccx, val, &[0])) as Disr
1336             }
1337         }
1338         Univariant(..) => 0,
1339         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1340             ccx.sess().bug("const discrim access of non c-like enum")
1341         }
1342     }
1343 }
1344
1345 /// Extract a field of a constant value, as appropriate for its
1346 /// representation.
1347 ///
1348 /// (Not to be confused with `common::const_get_elt`, which operates on
1349 /// raw LLVM-level structs and arrays.)
1350 pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
1351                        _discr: Disr, ix: usize) -> ValueRef {
1352     match *r {
1353         CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
1354         Univariant(..) => const_struct_field(ccx, val, ix),
1355         General(..) => const_struct_field(ccx, val, ix + 1),
1356         RawNullablePointer { .. } => {
1357             assert_eq!(ix, 0);
1358             val
1359         },
1360         StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1361     }
1362 }
1363
1364 /// Extract field of struct-like const, skipping our alignment padding.
1365 fn const_struct_field(ccx: &CrateContext, val: ValueRef, ix: usize) -> ValueRef {
1366     // Get the ix-th non-undef element of the struct.
1367     let mut real_ix = 0; // actual position in the struct
1368     let mut ix = ix; // logical index relative to real_ix
1369     let mut field;
1370     loop {
1371         loop {
1372             field = const_get_elt(ccx, val, &[real_ix]);
1373             if !is_undef(field) {
1374                 break;
1375             }
1376             real_ix = real_ix + 1;
1377         }
1378         if ix == 0 {
1379             return field;
1380         }
1381         ix = ix - 1;
1382         real_ix = real_ix + 1;
1383     }
1384 }