]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/consts.rs
doc: remove incomplete sentence
[rust.git] / src / librustc_trans / trans / consts.rs
1 // Copyright 2012 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
12 use back::abi;
13 use llvm;
14 use llvm::{ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, Bool, True, False};
15 use llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE,
16            RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE};
17 use metadata::csearch;
18 use middle::{const_eval, def};
19 use trans::{adt, closure, consts, debuginfo, expr, inline, machine};
20 use trans::base::{mod, push_ctxt};
21 use trans::common::*;
22 use trans::type_::Type;
23 use trans::type_of;
24 use middle::ty::{mod, Ty};
25 use util::ppaux::{Repr, ty_to_string};
26
27 use std::c_str::ToCStr;
28 use std::iter::repeat;
29 use libc::c_uint;
30 use syntax::{ast, ast_util};
31 use syntax::ptr::P;
32
33 pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
34     -> ValueRef {
35     let _icx = push_ctxt("trans_lit");
36     debug!("const_lit: {}", lit);
37     match lit.node {
38         ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
39         ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
40         ast::LitInt(i, ast::SignedIntLit(t, _)) => {
41             C_integral(Type::int_from_ty(cx, t), i, true)
42         }
43         ast::LitInt(u, ast::UnsignedIntLit(t)) => {
44             C_integral(Type::uint_from_ty(cx, t), u, false)
45         }
46         ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
47             let lit_int_ty = ty::node_id_to_type(cx.tcx(), e.id);
48             match lit_int_ty.sty {
49                 ty::ty_int(t) => {
50                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
51                 }
52                 ty::ty_uint(t) => {
53                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
54                 }
55                 _ => cx.sess().span_bug(lit.span,
56                         format!("integer literal has type {} (expected int \
57                                  or uint)",
58                                 ty_to_string(cx.tcx(), lit_int_ty))[])
59             }
60         }
61         ast::LitFloat(ref fs, t) => {
62             C_floating(fs.get(), Type::float_from_ty(cx, t))
63         }
64         ast::LitFloatUnsuffixed(ref fs) => {
65             let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id);
66             match lit_float_ty.sty {
67                 ty::ty_float(t) => {
68                     C_floating(fs.get(), Type::float_from_ty(cx, t))
69                 }
70                 _ => {
71                     cx.sess().span_bug(lit.span,
72                         "floating point literal doesn't have the right type");
73                 }
74             }
75         }
76         ast::LitBool(b) => C_bool(cx, b),
77         ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
78         ast::LitBinary(ref data) => C_binary_slice(cx, data[]),
79     }
80 }
81
82 pub fn const_ptrcast(cx: &CrateContext, a: ValueRef, t: Type) -> ValueRef {
83     unsafe {
84         let b = llvm::LLVMConstPointerCast(a, t.ptr_to().to_ref());
85         assert!(cx.const_globals().borrow_mut().insert(b as int, a).is_none());
86         b
87     }
88 }
89
90 fn const_vec(cx: &CrateContext, e: &ast::Expr,
91              es: &[P<ast::Expr>]) -> (ValueRef, Type) {
92     let vec_ty = ty::expr_ty(cx.tcx(), e);
93     let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty);
94     let llunitty = type_of::type_of(cx, unit_ty);
95     let vs = es.iter().map(|e| const_expr(cx, &**e).0)
96                       .collect::<Vec<_>>();
97     // If the vector contains enums, an LLVM array won't work.
98     let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
99         C_struct(cx, vs[], false)
100     } else {
101         C_array(llunitty, vs[])
102     };
103     (v, llunitty)
104 }
105
106 pub fn const_addr_of(cx: &CrateContext, cv: ValueRef, mutbl: ast::Mutability) -> ValueRef {
107     unsafe {
108         let gv = "const".with_c_str(|name| {
109             llvm::LLVMAddGlobal(cx.llmod(), val_ty(cv).to_ref(), name)
110         });
111         llvm::LLVMSetInitializer(gv, cv);
112         llvm::LLVMSetGlobalConstant(gv,
113                                     if mutbl == ast::MutImmutable {True} else {False});
114         SetLinkage(gv, PrivateLinkage);
115         gv
116     }
117 }
118
119 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
120     let v = match cx.const_globals().borrow().get(&(v as int)) {
121         Some(&v) => v,
122         None => v
123     };
124     unsafe {
125         llvm::LLVMGetInitializer(v)
126     }
127 }
128
129 fn const_deref_newtype<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef, t: Ty<'tcx>)
130     -> ValueRef {
131     let repr = adt::represent_type(cx, t);
132     adt::const_get_field(cx, &*repr, v, 0, 0)
133 }
134
135 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef,
136                          t: Ty<'tcx>, explicit: bool)
137                          -> (ValueRef, Ty<'tcx>) {
138     match ty::deref(t, explicit) {
139         Some(ref mt) => {
140             match t.sty {
141                 ty::ty_ptr(mt) | ty::ty_rptr(_, mt) => {
142                     if type_is_sized(cx.tcx(), mt.ty) {
143                         (const_deref_ptr(cx, v), mt.ty)
144                     } else {
145                         // Derefing a fat pointer does not change the representation,
146                         // just the type to ty_open.
147                         (v, ty::mk_open(cx.tcx(), mt.ty))
148                     }
149                 }
150                 ty::ty_enum(..) | ty::ty_struct(..) => {
151                     assert!(mt.mutbl != ast::MutMutable);
152                     (const_deref_newtype(cx, v, t), mt.ty)
153                 }
154                 _ => {
155                     cx.sess().bug(format!("unexpected dereferenceable type {}",
156                                           ty_to_string(cx.tcx(), t))[])
157                 }
158             }
159         }
160         None => {
161             cx.sess().bug(format!("cannot dereference const of type {}",
162                                   ty_to_string(cx.tcx(), t))[])
163         }
164     }
165 }
166
167 pub fn get_const_val(cx: &CrateContext,
168                      mut def_id: ast::DefId) -> ValueRef {
169     let contains_key = cx.const_values().borrow().contains_key(&def_id.node);
170     if !ast_util::is_local(def_id) || !contains_key {
171         if !ast_util::is_local(def_id) {
172             def_id = inline::maybe_instantiate_inline(cx, def_id);
173         }
174
175         if let ast::ItemConst(..) = cx.tcx().map.expect_item(def_id.node).node {
176             base::get_item_val(cx, def_id.node);
177         }
178     }
179
180     cx.const_values().borrow()[def_id.node].clone()
181 }
182
183 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr)
184                             -> (ValueRef, Ty<'tcx>) {
185     let llconst = const_expr_unadjusted(cx, e);
186     let mut llconst = llconst;
187     let ety = ty::expr_ty(cx.tcx(), e);
188     let mut ety_adjusted = ty::expr_ty_adjusted(cx.tcx(), e);
189     let opt_adj = cx.tcx().adjustments.borrow().get(&e.id).cloned();
190     match opt_adj {
191         None => { }
192         Some(adj) => {
193             match adj {
194                 ty::AdjustAddEnv(def_id, ty::RegionTraitStore(ty::ReStatic, _)) => {
195                     let wrapper = closure::get_wrapper_for_bare_fn(cx,
196                                                                    ety_adjusted,
197                                                                    def_id,
198                                                                    llconst,
199                                                                    true);
200                     llconst = C_struct(cx, &[wrapper, C_null(Type::i8p(cx))], false)
201                 }
202                 ty::AdjustAddEnv(_, store) => {
203                     cx.sess()
204                       .span_bug(e.span,
205                                 format!("unexpected static function: {}",
206                                         store)[])
207                 }
208                 ty::AdjustReifyFnPointer(_def_id) => {
209                     // FIXME(#19925) once fn item types are
210                     // zero-sized, we'll need to do something here
211                 }
212                 ty::AdjustDerefRef(ref adj) => {
213                     let mut ty = ety;
214                     // Save the last autoderef in case we can avoid it.
215                     if adj.autoderefs > 0 {
216                         for _ in range(0, adj.autoderefs-1) {
217                             let (dv, dt) = const_deref(cx, llconst, ty, false);
218                             llconst = dv;
219                             ty = dt;
220                         }
221                     }
222
223                     match adj.autoref {
224                         None => {
225                             let (dv, dt) = const_deref(cx, llconst, ty, false);
226                             llconst = dv;
227
228                             // If we derefed a fat pointer then we will have an
229                             // open type here. So we need to update the type with
230                             // the one returned from const_deref.
231                             ety_adjusted = dt;
232                         }
233                         Some(ref autoref) => {
234                             match *autoref {
235                                 ty::AutoUnsafe(_, None) |
236                                 ty::AutoPtr(ty::ReStatic, _, None) => {
237                                     // Don't copy data to do a deref+ref
238                                     // (i.e., skip the last auto-deref).
239                                     if adj.autoderefs == 0 {
240                                         llconst = const_addr_of(cx, llconst, ast::MutImmutable);
241                                     }
242                                 }
243                                 ty::AutoPtr(ty::ReStatic, _, Some(box ty::AutoUnsize(..))) => {
244                                     if adj.autoderefs > 0 {
245                                         // Seeing as we are deref'ing here and take a reference
246                                         // again to make the pointer part of the far pointer below,
247                                         // we just skip the whole thing. We still need the type
248                                         // though. This works even if we don't need to deref
249                                         // because of byref semantics. Note that this is not just
250                                         // an optimisation, it is necessary for mutable vectors to
251                                         // work properly.
252                                         let (_, dt) = const_deref(cx, llconst, ty, false);
253                                         ty = dt;
254                                     } else {
255                                         llconst = const_addr_of(cx, llconst, ast::MutImmutable)
256                                     }
257
258                                     match ty.sty {
259                                         ty::ty_vec(unit_ty, Some(len)) => {
260                                             let llunitty = type_of::type_of(cx, unit_ty);
261                                             let llptr = const_ptrcast(cx, llconst, llunitty);
262                                             assert_eq!(abi::FAT_PTR_ADDR, 0);
263                                             assert_eq!(abi::FAT_PTR_EXTRA, 1);
264                                             llconst = C_struct(cx, &[
265                                                 llptr,
266                                                 C_uint(cx, len)
267                                             ], false);
268                                         }
269                                         _ => cx.sess().span_bug(e.span,
270                                             format!("unimplemented type in const unsize: {}",
271                                                     ty_to_string(cx.tcx(), ty))[])
272                                     }
273                                 }
274                                 _ => {
275                                     cx.sess()
276                                       .span_bug(e.span,
277                                                 format!("unimplemented const \
278                                                          autoref {}",
279                                                         autoref)[])
280                                 }
281                             }
282                         }
283                     }
284                 }
285             }
286         }
287     }
288
289     let llty = type_of::sizing_type_of(cx, ety_adjusted);
290     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
291     let tsize = machine::llsize_of_alloc(cx, llty);
292     if csize != tsize {
293         unsafe {
294             // FIXME these values could use some context
295             llvm::LLVMDumpValue(llconst);
296             llvm::LLVMDumpValue(C_undef(llty));
297         }
298         cx.sess().bug(format!("const {} of type {} has size {} instead of {}",
299                          e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety),
300                          csize, tsize)[]);
301     }
302     (llconst, ety_adjusted)
303 }
304
305 // the bool returned is whether this expression can be inlined into other crates
306 // if it's assigned to a static.
307 fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef {
308     let map_list = |&: exprs: &[P<ast::Expr>]| {
309         exprs.iter().map(|e| const_expr(cx, &**e).0)
310              .fold(Vec::new(), |mut l, val| { l.push(val); l })
311     };
312     unsafe {
313         let _icx = push_ctxt("const_expr");
314         return match e.node {
315           ast::ExprLit(ref lit) => {
316               consts::const_lit(cx, e, &**lit)
317           }
318           ast::ExprBinary(b, ref e1, ref e2) => {
319             let (te1, _) = const_expr(cx, &**e1);
320             let (te2, _) = const_expr(cx, &**e2);
321
322             let te2 = base::cast_shift_const_rhs(b, te1, te2);
323
324             /* Neither type is bottom, and we expect them to be unified
325              * already, so the following is safe. */
326             let ty = ty::expr_ty(cx.tcx(), &**e1);
327             let is_float = ty::type_is_fp(ty);
328             let signed = ty::type_is_signed(ty);
329             return match b {
330               ast::BiAdd   => {
331                 if is_float { llvm::LLVMConstFAdd(te1, te2) }
332                 else        { llvm::LLVMConstAdd(te1, te2) }
333               }
334               ast::BiSub => {
335                 if is_float { llvm::LLVMConstFSub(te1, te2) }
336                 else        { llvm::LLVMConstSub(te1, te2) }
337               }
338               ast::BiMul    => {
339                 if is_float { llvm::LLVMConstFMul(te1, te2) }
340                 else        { llvm::LLVMConstMul(te1, te2) }
341               }
342               ast::BiDiv    => {
343                 if is_float    { llvm::LLVMConstFDiv(te1, te2) }
344                 else if signed { llvm::LLVMConstSDiv(te1, te2) }
345                 else           { llvm::LLVMConstUDiv(te1, te2) }
346               }
347               ast::BiRem    => {
348                 if is_float    { llvm::LLVMConstFRem(te1, te2) }
349                 else if signed { llvm::LLVMConstSRem(te1, te2) }
350                 else           { llvm::LLVMConstURem(te1, te2) }
351               }
352               ast::BiAnd    => llvm::LLVMConstAnd(te1, te2),
353               ast::BiOr     => llvm::LLVMConstOr(te1, te2),
354               ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
355               ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
356               ast::BiBitOr  => llvm::LLVMConstOr(te1, te2),
357               ast::BiShl    => llvm::LLVMConstShl(te1, te2),
358               ast::BiShr    => {
359                 if signed { llvm::LLVMConstAShr(te1, te2) }
360                 else      { llvm::LLVMConstLShr(te1, te2) }
361               }
362               ast::BiEq     => {
363                   if is_float { ConstFCmp(RealOEQ, te1, te2) }
364                   else        { ConstICmp(IntEQ, te1, te2)   }
365               },
366               ast::BiLt     => {
367                   if is_float { ConstFCmp(RealOLT, te1, te2) }
368                   else        {
369                       if signed { ConstICmp(IntSLT, te1, te2) }
370                       else      { ConstICmp(IntULT, te1, te2) }
371                   }
372               },
373               ast::BiLe     => {
374                   if is_float { ConstFCmp(RealOLE, te1, te2) }
375                   else        {
376                       if signed { ConstICmp(IntSLE, te1, te2) }
377                       else      { ConstICmp(IntULE, te1, te2) }
378                   }
379               },
380               ast::BiNe     => {
381                   if is_float { ConstFCmp(RealONE, te1, te2) }
382                   else        { ConstICmp(IntNE, te1, te2) }
383               },
384               ast::BiGe     => {
385                   if is_float { ConstFCmp(RealOGE, te1, te2) }
386                   else        {
387                       if signed { ConstICmp(IntSGE, te1, te2) }
388                       else      { ConstICmp(IntUGE, te1, te2) }
389                   }
390               },
391               ast::BiGt     => {
392                   if is_float { ConstFCmp(RealOGT, te1, te2) }
393                   else        {
394                       if signed { ConstICmp(IntSGT, te1, te2) }
395                       else      { ConstICmp(IntUGT, te1, te2) }
396                   }
397               },
398             }
399           },
400           ast::ExprUnary(u, ref e) => {
401             let (te, _) = const_expr(cx, &**e);
402             let ty = ty::expr_ty(cx.tcx(), &**e);
403             let is_float = ty::type_is_fp(ty);
404             return match u {
405               ast::UnUniq | ast::UnDeref => {
406                 let (dv, _dt) = const_deref(cx, te, ty, true);
407                 dv
408               }
409               ast::UnNot    => llvm::LLVMConstNot(te),
410               ast::UnNeg    => {
411                 if is_float { llvm::LLVMConstFNeg(te) }
412                 else        { llvm::LLVMConstNeg(te) }
413               }
414             }
415           }
416           ast::ExprField(ref base, field) => {
417               let (bv, bt) = const_expr(cx, &**base);
418               let brepr = adt::represent_type(cx, bt);
419               expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| {
420                   let ix = ty::field_idx_strict(cx.tcx(), field.node.name, field_tys);
421                   adt::const_get_field(cx, &*brepr, bv, discr, ix)
422               })
423           }
424           ast::ExprTupField(ref base, idx) => {
425               let (bv, bt) = const_expr(cx, &**base);
426               let brepr = adt::represent_type(cx, bt);
427               expr::with_field_tys(cx.tcx(), bt, None, |discr, _| {
428                   adt::const_get_field(cx, &*brepr, bv, discr, idx.node)
429               })
430           }
431
432           ast::ExprIndex(ref base, ref index) => {
433               let (bv, bt) = const_expr(cx, &**base);
434               let iv = match const_eval::eval_const_expr(cx.tcx(), &**index) {
435                   const_eval::const_int(i) => i as u64,
436                   const_eval::const_uint(u) => u,
437                   _ => cx.sess().span_bug(index.span,
438                                           "index is not an integer-constant expression")
439               };
440               let (arr, len) = match bt.sty {
441                   ty::ty_vec(_, Some(u)) => (bv, C_uint(cx, u)),
442                   ty::ty_open(ty) => match ty.sty {
443                       ty::ty_vec(_, None) | ty::ty_str => {
444                           let e1 = const_get_elt(cx, bv, &[0]);
445                           (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
446                       },
447                       _ => cx.sess().span_bug(base.span,
448                                               format!("index-expr base must be a vector \
449                                                        or string type, found {}",
450                                                       ty_to_string(cx.tcx(), bt))[])
451                   },
452                   ty::ty_rptr(_, mt) => match mt.ty.sty {
453                       ty::ty_vec(_, Some(u)) => {
454                           (const_deref_ptr(cx, bv), C_uint(cx, u))
455                       },
456                       _ => cx.sess().span_bug(base.span,
457                                               format!("index-expr base must be a vector \
458                                                        or string type, found {}",
459                                                       ty_to_string(cx.tcx(), bt))[])
460                   },
461                   _ => cx.sess().span_bug(base.span,
462                                           format!("index-expr base must be a vector \
463                                                    or string type, found {}",
464                                                   ty_to_string(cx.tcx(), bt))[])
465               };
466
467               let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
468               let len = match bt.sty {
469                   ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty.sty {
470                       ty::ty_str => {
471                           assert!(len > 0);
472                           len - 1
473                       }
474                       _ => len
475                   },
476                   _ => len
477               };
478               if iv >= len {
479                   // FIXME #3170: report this earlier on in the const-eval
480                   // pass. Reporting here is a bit late.
481                   cx.sess().span_err(e.span,
482                                      "const index-expr is out of bounds");
483               }
484               const_get_elt(cx, arr, &[iv as c_uint])
485           }
486           ast::ExprCast(ref base, _) => {
487             let ety = ty::expr_ty(cx.tcx(), e);
488             let llty = type_of::type_of(cx, ety);
489             let (v, basety) = const_expr(cx, &**base);
490             return match (expr::cast_type_kind(cx.tcx(), basety),
491                            expr::cast_type_kind(cx.tcx(), ety)) {
492
493               (expr::cast_integral, expr::cast_integral) => {
494                 let s = ty::type_is_signed(basety) as Bool;
495                 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
496               }
497               (expr::cast_integral, expr::cast_float) => {
498                 if ty::type_is_signed(basety) {
499                     llvm::LLVMConstSIToFP(v, llty.to_ref())
500                 } else {
501                     llvm::LLVMConstUIToFP(v, llty.to_ref())
502                 }
503               }
504               (expr::cast_float, expr::cast_float) => {
505                 llvm::LLVMConstFPCast(v, llty.to_ref())
506               }
507               (expr::cast_float, expr::cast_integral) => {
508                 if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
509                 else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
510               }
511               (expr::cast_enum, expr::cast_integral) => {
512                 let repr = adt::represent_type(cx, basety);
513                 let discr = adt::const_get_discrim(cx, &*repr, v);
514                 let iv = C_integral(cx.int_type(), discr, false);
515                 let ety_cast = expr::cast_type_kind(cx.tcx(), ety);
516                 match ety_cast {
517                     expr::cast_integral => {
518                         let s = ty::type_is_signed(ety) as Bool;
519                         llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
520                     }
521                     _ => cx.sess().bug("enum cast destination is not \
522                                         integral")
523                 }
524               }
525               (expr::cast_pointer, expr::cast_pointer) => {
526                 llvm::LLVMConstPointerCast(v, llty.to_ref())
527               }
528               (expr::cast_integral, expr::cast_pointer) => {
529                 llvm::LLVMConstIntToPtr(v, llty.to_ref())
530               }
531               (expr::cast_pointer, expr::cast_integral) => {
532                 llvm::LLVMConstPtrToInt(v, llty.to_ref())
533               }
534               _ => {
535                 cx.sess().impossible_case(e.span,
536                                           "bad combination of types for cast")
537               }
538             }
539           }
540           ast::ExprAddrOf(mutbl, ref sub) => {
541               // If this is the address of some static, then we need to return
542               // the actual address of the static itself (short circuit the rest
543               // of const eval).
544               let mut cur = sub;
545               loop {
546                   match cur.node {
547                       ast::ExprParen(ref sub) => cur = sub,
548                       _ => break,
549                   }
550               }
551               let opt_def = cx.tcx().def_map.borrow().get(&cur.id).cloned();
552               if let Some(def::DefStatic(def_id, _)) = opt_def {
553                   let ty = ty::expr_ty(cx.tcx(), e);
554                   return get_static_val(cx, def_id, ty);
555               }
556
557               // If this isn't the address of a static, then keep going through
558               // normal constant evaluation.
559               let (e, _) = const_expr(cx, &**sub);
560               const_addr_of(cx, e, mutbl)
561           }
562           ast::ExprTup(ref es) => {
563               let ety = ty::expr_ty(cx.tcx(), e);
564               let repr = adt::represent_type(cx, ety);
565               let vals = map_list(es[]);
566               adt::trans_const(cx, &*repr, 0, vals[])
567           }
568           ast::ExprStruct(_, ref fs, ref base_opt) => {
569               let ety = ty::expr_ty(cx.tcx(), e);
570               let repr = adt::represent_type(cx, ety);
571               let tcx = cx.tcx();
572
573               let base_val = match *base_opt {
574                 Some(ref base) => Some(const_expr(cx, &**base)),
575                 None => None
576               };
577
578               expr::with_field_tys(tcx, ety, Some(e.id), |discr, field_tys| {
579                   let cs = field_tys.iter().enumerate()
580                                     .map(|(ix, &field_ty)| {
581                       match fs.iter().find(|f| field_ty.name == f.ident.node.name) {
582                           Some(ref f) => const_expr(cx, &*f.expr).0,
583                           None => {
584                               match base_val {
585                                   Some((bv, _)) => {
586                                       adt::const_get_field(cx, &*repr, bv,
587                                                            discr, ix)
588                                   }
589                                   None => {
590                                       cx.sess().span_bug(e.span,
591                                                          "missing struct field")
592                                   }
593                               }
594                           }
595                       }
596                   }).collect::<Vec<_>>();
597                   adt::trans_const(cx, &*repr, discr, cs[])
598               })
599           }
600           ast::ExprVec(ref es) => {
601             const_vec(cx, e, es.as_slice()).0
602           }
603           ast::ExprRepeat(ref elem, ref count) => {
604             let vec_ty = ty::expr_ty(cx.tcx(), e);
605             let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty);
606             let llunitty = type_of::type_of(cx, unit_ty);
607             let n = match const_eval::eval_const_expr(cx.tcx(), &**count) {
608                 const_eval::const_int(i)  => i as uint,
609                 const_eval::const_uint(i) => i as uint,
610                 _ => cx.sess().span_bug(count.span, "count must be integral const expression.")
611             };
612             let vs: Vec<_> = repeat(const_expr(cx, &**elem).0).take(n).collect();
613             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
614                 C_struct(cx, vs[], false)
615             } else {
616                 C_array(llunitty, vs[])
617             }
618           }
619           ast::ExprPath(ref pth) => {
620             // Assert that there are no type parameters in this path.
621             assert!(pth.segments.iter().all(|seg| !seg.parameters.has_types()));
622
623             let opt_def = cx.tcx().def_map.borrow().get(&e.id).cloned();
624             match opt_def {
625                 Some(def::DefFn(def_id, _)) => {
626                     if !ast_util::is_local(def_id) {
627                         let ty = csearch::get_type(cx.tcx(), def_id).ty;
628                         base::trans_external_path(cx, def_id, ty)
629                     } else {
630                         assert!(ast_util::is_local(def_id));
631                         base::get_item_val(cx, def_id.node)
632                     }
633                 }
634                 Some(def::DefConst(def_id)) => {
635                     get_const_val(cx, def_id)
636                 }
637                 Some(def::DefVariant(enum_did, variant_did, _)) => {
638                     let ety = ty::expr_ty(cx.tcx(), e);
639                     let repr = adt::represent_type(cx, ety);
640                     let vinfo = ty::enum_variant_with_id(cx.tcx(),
641                                                          enum_did,
642                                                          variant_did);
643                     adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
644                 }
645                 Some(def::DefStruct(_)) => {
646                     let ety = ty::expr_ty(cx.tcx(), e);
647                     let llty = type_of::type_of(cx, ety);
648                     C_null(llty)
649                 }
650                 _ => {
651                     cx.sess().span_bug(e.span, "expected a const, fn, struct, \
652                                                 or variant def")
653                 }
654             }
655           }
656           ast::ExprCall(ref callee, ref args) => {
657               let opt_def = cx.tcx().def_map.borrow().get(&callee.id).cloned();
658               match opt_def {
659                   Some(def::DefStruct(_)) => {
660                       let ety = ty::expr_ty(cx.tcx(), e);
661                       let repr = adt::represent_type(cx, ety);
662                       let arg_vals = map_list(args[]);
663                       adt::trans_const(cx, &*repr, 0, arg_vals[])
664                   }
665                   Some(def::DefVariant(enum_did, variant_did, _)) => {
666                       let ety = ty::expr_ty(cx.tcx(), e);
667                       let repr = adt::represent_type(cx, ety);
668                       let vinfo = ty::enum_variant_with_id(cx.tcx(),
669                                                            enum_did,
670                                                            variant_did);
671                       let arg_vals = map_list(args[]);
672                       adt::trans_const(cx,
673                                        &*repr,
674                                        vinfo.disr_val,
675                                        arg_vals[])
676                   }
677                   _ => cx.sess().span_bug(e.span, "expected a struct or variant def")
678               }
679           }
680           ast::ExprParen(ref e) => const_expr(cx, &**e).0,
681           ast::ExprBlock(ref block) => {
682             match block.expr {
683                 Some(ref expr) => const_expr(cx, &**expr).0,
684                 None => C_nil(cx)
685             }
686           }
687           _ => cx.sess().span_bug(e.span,
688                   "bad constant expression type in consts::const_expr")
689         };
690     }
691 }
692
693 pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) {
694     unsafe {
695         let _icx = push_ctxt("trans_static");
696         let g = base::get_item_val(ccx, id);
697         // At this point, get_item_val has already translated the
698         // constant's initializer to determine its LLVM type.
699         let v = ccx.static_values().borrow()[id].clone();
700         // boolean SSA values are i1, but they have to be stored in i8 slots,
701         // otherwise some LLVM optimization passes don't work as expected
702         let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
703             llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref())
704         } else {
705             v
706         };
707         llvm::LLVMSetInitializer(g, v);
708
709         // As an optimization, all shared statics which do not have interior
710         // mutability are placed into read-only memory.
711         if m != ast::MutMutable {
712             let node_ty = ty::node_id_to_type(ccx.tcx(), id);
713             let tcontents = ty::type_contents(ccx.tcx(), node_ty);
714             if !tcontents.interior_unsafe() {
715                 llvm::LLVMSetGlobalConstant(g, True);
716             }
717         }
718         debuginfo::create_global_var_metadata(ccx, id, g);
719     }
720 }
721
722 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
723                             ty: Ty<'tcx>) -> ValueRef {
724     if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) }
725     base::trans_external_path(ccx, did, ty)
726 }