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