]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/adt.rs
Implement `repr(simd)` as an alias for `#[simd]`.
[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 macro_rules! repeat_u8_as_u32 {
181     ($name:expr) => { (($name as u32) << 24 |
182                        ($name as u32) << 16 |
183                        ($name as u32) <<  8 |
184                        ($name as u32)) }
185 }
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)) }
189 }
190
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;
195
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."
198 ///
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;
204
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);
208 #[allow(dead_code)]
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),
214     }
215 }
216
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);
220 #[allow(dead_code)]
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),
226     }
227 }
228
229 fn dtor_to_init_u8(dtor: bool) -> u8 {
230     if dtor { DTOR_NEEDED } else { 0 }
231 }
232
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 }
236 }
237
238 fn dtor_active(flag: u8) -> bool {
239     flag != 0
240 }
241
242 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
243                                      t: Ty<'tcx>) -> Repr<'tcx> {
244     match t.sty {
245         ty::TyTuple(ref elems) => {
246             Univariant(mk_struct(cx, &elems[..], false, t), 0)
247         }
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();
254             if dtor {
255                 ftys.push(cx.tcx().dtor_type());
256             }
257
258             Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
259         }
260         ty::TyClosure(_, ref substs) => {
261             Univariant(mk_struct(cx, &substs.upvar_tys, false, t), 0)
262         }
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);
267
268             let dtor = cx.tcx().ty_dtor(def.did).has_drop_flag();
269
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));
277             }
278
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()
287                 };
288                 return mk_cenum(cx, hint, &bounds);
289             }
290
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 \
296                                         discriminants",
297                                        cx.tcx().item_path_str(def.did)));
298             }
299
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));
308             }
309
310             if !dtor && cases.len() == 2 && hint == attr::ReprAny {
311                 // Nullable pointer optimization
312                 let mut discr = 0;
313                 while discr < 2 {
314                     if cases[1 - discr].is_zerolen(cx, t) {
315                         let st = mk_struct(cx, &cases[discr].tys,
316                                            false, t);
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,
321                                     nnty: st.fields[0],
322                                     nullfields: cases[1 - discr].tys.clone()
323                                 };
324                             }
325                             Some(mut discrfield) => {
326                                 discrfield.push(0);
327                                 discrfield.reverse();
328                                 return StructWrappedNullablePointer {
329                                     nndiscr: discr as Disr,
330                                     nonnull: st,
331                                     discrfield: discrfield,
332                                     nullfields: cases[1 - discr].tys.clone()
333                                 };
334                             }
335                             None => {}
336                         }
337                     }
338                     discr += 1;
339                 }
340             }
341
342             // The general case.
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);
347
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)
355             }).collect();
356
357
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;
372             for st in &fields {
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
379                 }).next();
380
381                 if let Some(field) = field {
382                     let field_align = type_of::align_of(cx, *field);
383                     if field_align != align {
384                         use_align = false;
385                         break;
386                     }
387                 }
388             }
389             let ity = if use_align {
390                 // Use the overall alignment
391                 match align {
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
398                 }
399             } else {
400                 min_ity
401             };
402
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)
408             }).collect();
409
410             ensure_enum_fits_in_address_space(cx, &fields[..], t);
411
412             General(ity, fields, dtor_to_init_u8(dtor))
413         }
414         _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}", t))
415     }
416 }
417
418 // this should probably all be in ty
419 struct Case<'tcx> {
420     discr: Disr,
421     tys: Vec<Ty<'tcx>>
422 }
423
424 /// This represents the (GEP) indices to follow to get to the discriminant field
425 pub type DiscrField = Vec<usize>;
426
427 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
428                                     ty: Ty<'tcx>,
429                                     mut path: DiscrField) -> Option<DiscrField> {
430     match ty.sty {
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);
434             Some(path)
435         },
436
437         // Regular thin pointer: &T/&mut T/Box<T>
438         ty::TyRef(..) | ty::TyBox(..) => Some(path),
439
440         // Functions are just pointers
441         ty::TyBareFn(..) => Some(path),
442
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]);
448             match field_ty.sty {
449                 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) if !type_is_sized(tcx, ty) => {
450                     path.push_all(&[0, FAT_PTR_ADDR]);
451                     Some(path)
452                 },
453                 ty::TyRawPtr(..) | ty::TyInt(..) | ty::TyUint(..) => {
454                     path.push(0);
455                     Some(path)
456                 },
457                 _ => None
458             }
459         },
460
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()) {
467                     fpath.push(j);
468                     return Some(fpath);
469                 }
470             }
471             None
472         },
473
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()) {
479                     fpath.push(j);
480                     return Some(fpath);
481                 }
482             }
483             None
484         },
485
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()) {
490                     fpath.push(j);
491                     return Some(fpath);
492                 }
493             }
494             None
495         },
496
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) {
501                 vpath.push(0);
502                 Some(vpath)
503             } else {
504                 None
505             }
506         },
507
508         // Anything else is not a pointer
509         _ => None
510     }
511 }
512
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
516     }
517
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![]) {
521                 path.push(i);
522                 return Some(path);
523             }
524         }
525         None
526     }
527 }
528
529 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
530                    adt: ty::AdtDef<'tcx>,
531                    substs: &subst::Substs<'tcx>)
532                    -> Vec<Case<'tcx>> {
533     adt.variants.iter().map(|vi| {
534         let field_tys = vi.fields.iter().map(|field| {
535             monomorphize::field_ty(tcx, substs, field)
536         }).collect();
537         Case { discr: vi.disr_val, tys: field_tys }
538     }).collect()
539 }
540
541 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
542                        tys: &[Ty<'tcx>], packed: bool,
543                        scapegoat: Ty<'tcx>)
544                        -> Struct<'tcx> {
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()
548     } else {
549         tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
550            .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
551     };
552
553     ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
554
555     let llty_rec = Type::struct_(cx, &lltys[..], packed);
556     Struct {
557         size: machine::llsize_of_alloc(cx, llty_rec),
558         align: machine::llalign_of_min(cx, llty_rec),
559         sized: sized,
560         packed: packed,
561         fields: tys.to_vec(),
562     }
563 }
564
565 #[derive(Debug)]
566 struct IntBounds {
567     slo: i64,
568     shi: i64,
569     ulo: u64,
570     uhi: u64
571 }
572
573 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
574                       hint: Hint, bounds: &IntBounds)
575                       -> Repr<'tcx> {
576     let it = range_to_inttype(cx, hint, bounds);
577     match it {
578         attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
579         attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
580     }
581 }
582
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)];
594
595     let attempts;
596     match hint {
597         attr::ReprInt(span, ity) => {
598             if !bounds_usable(cx, ity, bounds) {
599                 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
600             }
601             return ity;
602         }
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,
609                 _ => at_least_32,
610             }
611         }
612         attr::ReprAny => {
613             attempts = choose_shortest;
614         },
615         attr::ReprPacked => {
616             cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
617         }
618         attr::ReprSimd => {
619             cx.tcx().sess.bug("range_to_inttype: found ReprSimd on an enum");
620         }
621     }
622     for &ity in attempts {
623         if bounds_usable(cx, ity, bounds) {
624             return ity;
625         }
626     }
627     return attr::UnsignedInt(ast::TyU64);
628 }
629
630 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
631     match ity {
632         attr::SignedInt(t) => Type::int_from_ty(cx, t),
633         attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
634     }
635 }
636
637 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
638     debug!("bounds_usable: {:?} {:?}", ity, bounds);
639     match ity {
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
644         }
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
649         }
650     }
651 }
652
653 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
654     match ity {
655         attr::SignedInt(t) => tcx.mk_mach_int(t),
656         attr::UnsignedInt(t) => tcx.mk_mach_uint(t)
657     }
658 }
659
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>,
662                                                  fields: &[Type],
663                                                  packed: bool,
664                                                  scapegoat: Ty<'tcx>) {
665     let mut offset = 0;
666     for &llty in fields {
667         // Invariant: offset < ccx.obj_size_bound() <= 1<<61
668         if !packed {
669             let type_align = machine::llalign_of_min(ccx, llty);
670             offset = roundup(offset, type_align);
671         }
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);
676
677         if offset >= ccx.obj_size_bound() {
678             ccx.report_overbig_object(scapegoat);
679         }
680     }
681 }
682
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)
687 }
688
689 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
690                                                fields: &[Struct],
691                                                scapegoat: Ty<'tcx>) {
692     let (total_size, _) = union_size_and_align(fields);
693
694     if total_size >= ccx.obj_size_bound() {
695         ccx.report_overbig_object(scapegoat);
696     }
697 }
698
699
700 /// LLVM-level types are a little complicated.
701 ///
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).
704 ///
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);
711     c.prefix
712 }
713
714
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);
722     c.prefix
723 }
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)
727 }
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);
732     c.prefix
733 }
734 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
735                                 r: &Repr<'tcx>, llty: &mut Type) {
736     match *r {
737         CEnum(..) | General(..) | RawNullablePointer { .. } => { }
738         Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
739             llty.set_struct_body(&struct_llfields(cx, st, false, false),
740                                  st.packed)
741     }
742 }
743
744 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
745                              r: &Repr<'tcx>,
746                              name: Option<&str>,
747                              sizing: bool,
748                              dst: bool,
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);
752     match *r {
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, .. } => {
757             match name {
758                 None => {
759                     TypeContext::direct(
760                         Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
761                                       st.packed))
762                 }
763                 Some(name) => {
764                     assert_eq!(sizing, false);
765                     TypeContext::direct(Type::named_struct(cx, name))
766                 }
767             }
768         }
769         Univariant(ref st, dtor_needed) => {
770             let dtor_needed = dtor_needed != 0;
771             match name {
772                 None => {
773                     let mut fields = struct_llfields(cx, st, sizing, dst);
774                     if delay_drop_flag && dtor_needed {
775                         fields.pop();
776                     }
777                     TypeContext::may_need_drop_flag(
778                         Type::struct_(cx, &fields,
779                                       st.packed),
780                         delay_drop_flag && dtor_needed)
781                 }
782                 Some(name) => {
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))
787                 }
788             }
789         }
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.
798             //
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
801             // of the size.
802             //
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;
808
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),
818                                                               align_units),
819                 _ => panic!("unsupported enum alignment: {}", align)
820             };
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> =
824                 [discr_ty,
825                  Type::array(&discr_ty, align_s / discr_size - 1),
826                  fill_ty].iter().cloned().collect();
827             if delay_drop_flag && dtor_needed {
828                 fields.pop();
829             }
830             match name {
831                 None => {
832                     TypeContext::may_need_drop_flag(
833                         Type::struct_(cx, &fields[..], false),
834                         delay_drop_flag && dtor_needed)
835                 }
836                 Some(name) => {
837                     let mut llty = Type::named_struct(cx, name);
838                     llty.set_struct_body(&fields[..], false);
839                     TypeContext::may_need_drop_flag(
840                         llty,
841                         delay_drop_flag && dtor_needed)
842                 }
843             }
844         }
845     }
846 }
847
848 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
849                              sizing: bool, dst: bool) -> Vec<Type> {
850     if sizing {
851         st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
852             .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
853     } else {
854         st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
855     }
856 }
857
858 /// Obtain a representation of the discriminant sufficient to translate
859 /// destructuring; this may or may not involve the actual discriminant.
860 ///
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>) {
865     match *r {
866         CEnum(..) | General(..) |
867         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
868             (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
869         }
870         Univariant(..) => {
871             // N.B.: Univariant means <= 1 enum variants (*not* == 1 variants).
872             (_match::Single, None)
873         }
874     }
875 }
876
877 pub fn is_discr_signed<'tcx>(r: &Repr<'tcx>) -> bool {
878     match *r {
879         CEnum(ity, _, _) => ity.is_signed(),
880         General(ity, _, _) => ity.is_signed(),
881         Univariant(..) => false,
882         RawNullablePointer { .. } => false,
883         StructWrappedNullablePointer { .. } => false,
884     }
885 }
886
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>)
890     -> ValueRef {
891     debug!("trans_get_discr r: {:?}", r);
892     let val = match *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)
897         }
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)
903         }
904         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
905             struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee)
906         }
907     };
908     match cast_to {
909         None => val,
910         Some(llty) => if is_discr_signed(r) { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
911     }
912 }
913
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)
920 }
921
922 /// Helper for cases where the discriminant is simply loaded.
923 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
924     -> ValueRef {
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);
928     assert!(bits <= 64);
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).
938         Load(bcx, ptr)
939     } else {
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)
943     }
944 }
945
946 /// Yield information about how to dispatch a case of the
947 /// discriminant-like value returned by `trans_switch`.
948 ///
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> {
952     match *r {
953         CEnum(ity, _, _) => {
954             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
955                                                               discr as u64, true)))
956         }
957         General(ity, _, _) => {
958             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
959                                                               discr as u64, true)))
960         }
961         Univariant(..) => {
962             bcx.ccx().sess().bug("no cases for univariants or structs")
963         }
964         RawNullablePointer { .. } |
965         StructWrappedNullablePointer { .. } => {
966             assert!(discr == 0 || discr == 1);
967             _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
968         }
969     }
970 }
971
972 /// Set the discriminant for a new value of the given case of the given
973 /// representation.
974 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
975                                    val: ValueRef, discr: Disr) {
976     match *r {
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),
980                   val);
981         }
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);
987             }
988             Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
989                   GEPi(bcx, val, &[0, 0]));
990         }
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]));
996             }
997         }
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);
1002             }
1003         }
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);
1009             }
1010         }
1011     }
1012 }
1013
1014 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
1015     match ity {
1016         attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
1017         attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
1018     }
1019 }
1020
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 {
1024     match *r {
1025         CEnum(..) => 0,
1026         Univariant(ref st, dtor) => {
1027             assert_eq!(discr, 0);
1028             st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
1029         }
1030         General(_, ref cases, dtor) => {
1031             cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
1032         }
1033         RawNullablePointer { nndiscr, ref nullfields, .. } => {
1034             if discr == nndiscr { 1 } else { nullfields.len() }
1035         }
1036         StructWrappedNullablePointer { ref nonnull, nndiscr,
1037                                        ref nullfields, .. } => {
1038             if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
1039         }
1040     }
1041 }
1042
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.
1049     match *r {
1050         CEnum(..) => {
1051             bcx.ccx().sess().bug("element access in C-like enum")
1052         }
1053         Univariant(ref st, _dtor) => {
1054             assert_eq!(discr, 0);
1055             struct_field_ptr(bcx, st, val, ix, false)
1056         }
1057         General(_, ref cases, _) => {
1058             struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
1059         }
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())
1069         }
1070         RawNullablePointer { nndiscr, nnty, .. } => {
1071             assert_eq!(ix, 0);
1072             assert_eq!(discr, nndiscr);
1073             let ty = type_of::type_of(bcx.ccx(), nnty);
1074             PointerCast(bcx, val, ty.ptr_to())
1075         }
1076         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1077             assert_eq!(discr, nndiscr);
1078             struct_field_ptr(bcx, nonnull, val, ix, false)
1079         }
1080     }
1081 }
1082
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())
1090     } else {
1091         val
1092     };
1093
1094     GEPi(bcx, val, &[0, ix])
1095 }
1096
1097 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1098                                     r: &Repr<'tcx>,
1099                                     value: ValueRef,
1100                                     mut f: F)
1101                                     -> Block<'blk, 'tcx> where
1102     F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1103 {
1104     let fcx = bcx.fcx;
1105     match *r {
1106         Univariant(ref st, _) => {
1107             f(bcx, st, value)
1108         }
1109         General(ity, ref cases, _) => {
1110             let ccx = bcx.ccx();
1111
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
1117             // block.
1118             //
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);
1128
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");
1132
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())
1136                 );
1137                 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1138                 AddCase(llswitch, rhs_val, variant_cx.llbb);
1139
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());
1144
1145                 variant_cx = f(variant_cx, case, variant_value);
1146                 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1147             }
1148
1149             bcx_next
1150         }
1151         _ => unreachable!()
1152     }
1153 }
1154
1155 /// Access the struct drop flag, if present.
1156 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1157                                        r: &Repr<'tcx>,
1158                                        val: ValueRef)
1159                                        -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1160 {
1161     let tcx = bcx.tcx();
1162     let ptr_ty = bcx.tcx().mk_imm_ptr(tcx.dtor_type());
1163     match *r {
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()
1167         }
1168         General(_, _, dtor) if dtor_active(dtor) => {
1169             let fcx = bcx.fcx;
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
1174             ));
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)
1179             });
1180             let expr_datum = scratch.to_expr_datum();
1181             fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1182             datum::DatumBlock::new(bcx, expr_datum)
1183         }
1184         _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1185     }
1186 }
1187
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.
1193 ///
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.
1198 ///
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.
1203 ///
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 {
1209     match *r {
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)
1214         }
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];
1220             f.push_all(vals);
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)
1224         }
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)
1229         }
1230         RawNullablePointer { nndiscr, nnty, .. } => {
1231             if discr == nndiscr {
1232                 assert_eq!(vals.len(), 1);
1233                 vals[0]
1234             } else {
1235                 C_null(type_of::sizing_type_of(ccx, nnty))
1236             }
1237         }
1238         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1239             if discr == nndiscr {
1240                 C_struct(ccx, &build_const_struct(ccx,
1241                                                  nonnull,
1242                                                  vals),
1243                          false)
1244             } else {
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,
1251                                                  nonnull,
1252                                                  &vals[..]),
1253                          false)
1254             }
1255         }
1256     }
1257 }
1258
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!();
1263
1264     let mut offset = 0;
1265     for &ty in &st.fields {
1266         let llty = type_of::sizing_type_of(ccx, ty);
1267         if !st.packed {
1268             let type_align = type_of::align_of(ccx, ty);
1269             offset = roundup(offset, type_align);
1270         }
1271         offsets.push(offset);
1272         offset += machine::llsize_of_alloc(ccx, llty);
1273     }
1274     assert_eq!(st.fields.len(), offsets.len());
1275     offsets
1276 }
1277
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.
1280 ///
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])
1288                                 -> Vec<ValueRef> {
1289     assert_eq!(vals.len(), st.fields.len());
1290
1291     let target_offsets = compute_struct_field_offsets(ccx, st);
1292
1293     // offset of current value
1294     let mut offset = 0;
1295     let mut cfields = Vec::new();
1296     for (&val, target_offset) in vals.iter().zip(target_offsets) {
1297         if !st.packed {
1298             let val_align = machine::llalign_of_min(ccx, val_ty(val));
1299             offset = roundup(offset, val_align);
1300         }
1301         if offset != target_offset {
1302             cfields.push(padding(ccx, target_offset - offset));
1303             offset = target_offset;
1304         }
1305         assert!(!is_undef(val));
1306         cfields.push(val);
1307         offset += machine::llsize_of_alloc(ccx, val_ty(val));
1308     }
1309
1310     assert!(st.sized && offset <= st.size);
1311     if offset != st.size {
1312         cfields.push(padding(ccx, st.size - offset));
1313     }
1314
1315     cfields
1316 }
1317
1318 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1319     C_undef(Type::array(&Type::i8(ccx), size))
1320 }
1321
1322 // FIXME this utility routine should be somewhere more general
1323 #[inline]
1324 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1325
1326 /// Get the discriminant of a constant value.
1327 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1328     match *r {
1329         CEnum(ity, _, _) => {
1330             match ity {
1331                 attr::SignedInt(..) => const_to_int(val) as Disr,
1332                 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1333             }
1334         }
1335         General(ity, _, _) => {
1336             match 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
1339             }
1340         }
1341         Univariant(..) => 0,
1342         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1343             ccx.sess().bug("const discrim access of non c-like enum")
1344         }
1345     }
1346 }
1347
1348 /// Extract a field of a constant value, as appropriate for its
1349 /// representation.
1350 ///
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 {
1355     match *r {
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 { .. } => {
1360             assert_eq!(ix, 0);
1361             val
1362         },
1363         StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1364     }
1365 }
1366
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
1372     let mut field;
1373     loop {
1374         loop {
1375             field = const_get_elt(ccx, val, &[real_ix]);
1376             if !is_undef(field) {
1377                 break;
1378             }
1379             real_ix = real_ix + 1;
1380         }
1381         if ix == 0 {
1382             return field;
1383         }
1384         ix = ix - 1;
1385         real_ix = real_ix + 1;
1386     }
1387 }