]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/consts.rs
librustc: Combine C_struct and C_packed_struct.
[rust.git] / src / librustc / middle / 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 lib::llvm::{llvm, ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, Bool, True};
14 use lib::llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE,
15     RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE};
16
17 use metadata::csearch;
18 use middle::const_eval;
19 use middle::trans::adt;
20 use middle::trans::base;
21 use middle::trans::base::push_ctxt;
22 use middle::trans::common::*;
23 use middle::trans::consts;
24 use middle::trans::expr;
25 use middle::trans::inline;
26 use middle::trans::machine;
27 use middle::trans::type_of;
28 use middle::ty;
29 use util::ppaux::{Repr, ty_to_str};
30
31 use middle::trans::type_::Type;
32
33 use std::c_str::ToCStr;
34 use std::libc::c_uint;
35 use std::vec;
36 use syntax::{ast, ast_util, ast_map};
37
38 pub fn const_lit(cx: &mut CrateContext, e: &ast::Expr, lit: ast::lit)
39     -> ValueRef {
40     let _icx = push_ctxt("trans_lit");
41     match lit.node {
42       ast::lit_char(i) => C_integral(Type::char(), i as u64, false),
43       ast::lit_int(i, t) => C_integral(Type::int_from_ty(cx, t), i as u64, true),
44       ast::lit_uint(u, t) => C_integral(Type::uint_from_ty(cx, t), u, false),
45       ast::lit_int_unsuffixed(i) => {
46         let lit_int_ty = ty::node_id_to_type(cx.tcx, e.id);
47         match ty::get(lit_int_ty).sty {
48           ty::ty_int(t) => {
49             C_integral(Type::int_from_ty(cx, t), i as u64, true)
50           }
51           ty::ty_uint(t) => {
52             C_integral(Type::uint_from_ty(cx, t), i as u64, false)
53           }
54           _ => cx.sess.span_bug(lit.span,
55                    format!("integer literal has type {} (expected int or uint)",
56                         ty_to_str(cx.tcx, lit_int_ty)))
57         }
58       }
59       ast::lit_float(fs, t) => C_floating(fs, Type::float_from_ty(t)),
60       ast::lit_float_unsuffixed(fs) => {
61         let lit_float_ty = ty::node_id_to_type(cx.tcx, e.id);
62         match ty::get(lit_float_ty).sty {
63           ty::ty_float(t) => {
64             C_floating(fs, Type::float_from_ty(t))
65           }
66           _ => {
67             cx.sess.span_bug(lit.span,
68                              "floating point literal doesn't have the right type");
69           }
70         }
71       }
72       ast::lit_bool(b) => C_bool(b),
73       ast::lit_nil => C_nil(),
74       ast::lit_str(s, _) => C_estr_slice(cx, s)
75     }
76 }
77
78 pub fn const_ptrcast(cx: &mut CrateContext, a: ValueRef, t: Type) -> ValueRef {
79     unsafe {
80         let b = llvm::LLVMConstPointerCast(a, t.ptr_to().to_ref());
81         assert!(cx.const_globals.insert(b as int, a));
82         b
83     }
84 }
85
86 pub fn const_vec(cx: @mut CrateContext, e: &ast::Expr, es: &[@ast::Expr])
87     -> (ValueRef, ValueRef, Type, bool) {
88     unsafe {
89         let vec_ty = ty::expr_ty(cx.tcx, e);
90         let unit_ty = ty::sequence_element_type(cx.tcx, vec_ty);
91         let llunitty = type_of::type_of(cx, unit_ty);
92         let unit_sz = machine::llsize_of(cx, llunitty);
93         let sz = llvm::LLVMConstMul(C_uint(cx, es.len()), unit_sz);
94         let (vs, inlineable) = vec::unzip(es.iter().map(|e| const_expr(cx, *e)));
95         // If the vector contains enums, an LLVM array won't work.
96         let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
97             C_struct(vs, false)
98         } else {
99             C_array(llunitty, vs)
100         };
101         return (v, sz, llunitty, inlineable.iter().fold(true, |a, &b| a && b));
102     }
103 }
104
105 fn const_addr_of(cx: &mut CrateContext, cv: ValueRef) -> ValueRef {
106     unsafe {
107         let gv = do "const".with_c_str |name| {
108             llvm::LLVMAddGlobal(cx.llmod, val_ty(cv).to_ref(), name)
109         };
110         llvm::LLVMSetInitializer(gv, cv);
111         llvm::LLVMSetGlobalConstant(gv, True);
112         SetLinkage(gv, PrivateLinkage);
113         gv
114     }
115 }
116
117 fn const_deref_ptr(cx: &mut CrateContext, v: ValueRef) -> ValueRef {
118     let v = match cx.const_globals.find(&(v as int)) {
119         Some(&v) => v,
120         None => v
121     };
122     unsafe {
123         assert_eq!(llvm::LLVMIsGlobalConstant(v), True);
124         llvm::LLVMGetInitializer(v)
125     }
126 }
127
128 fn const_deref_newtype(cx: &mut CrateContext, v: ValueRef, t: ty::t)
129     -> ValueRef {
130     let repr = adt::represent_type(cx, t);
131     adt::const_get_field(cx, repr, v, 0, 0)
132 }
133
134 fn const_deref(cx: &mut CrateContext, v: ValueRef, t: ty::t, explicit: bool)
135     -> (ValueRef, ty::t) {
136     match ty::deref(cx.tcx, t, explicit) {
137         Some(ref mt) => {
138             assert!(mt.mutbl != ast::MutMutable);
139             let dv = match ty::get(t).sty {
140                 ty::ty_ptr(*) | ty::ty_rptr(*) => {
141                      const_deref_ptr(cx, v)
142                 }
143                 ty::ty_enum(*) | ty::ty_struct(*) => {
144                     const_deref_newtype(cx, v, t)
145                 }
146                 _ => {
147                     cx.sess.bug(format!("Unexpected dereferenceable type {}",
148                                      ty_to_str(cx.tcx, t)))
149                 }
150             };
151             (dv, mt.ty)
152         }
153         None => {
154             cx.sess.bug(format!("Can't dereference const of type {}",
155                              ty_to_str(cx.tcx, t)))
156         }
157     }
158 }
159
160 pub fn get_const_val(cx: @mut CrateContext,
161                      mut def_id: ast::DefId) -> (ValueRef, bool) {
162     let contains_key = cx.const_values.contains_key(&def_id.node);
163     if !ast_util::is_local(def_id) || !contains_key {
164         if !ast_util::is_local(def_id) {
165             def_id = inline::maybe_instantiate_inline(cx, def_id);
166         }
167         match cx.tcx.items.get_copy(&def_id.node) {
168             ast_map::node_item(@ast::item {
169                 node: ast::item_static(_, ast::MutImmutable, _), _
170             }, _) => {
171                 trans_const(cx, ast::MutImmutable, def_id.node);
172             }
173             _ => cx.tcx.sess.bug("expected a const to be an item")
174         }
175     }
176     (cx.const_values.get_copy(&def_id.node),
177      !cx.non_inlineable_statics.contains(&def_id.node))
178 }
179
180 pub fn const_expr(cx: @mut CrateContext, e: &ast::Expr) -> (ValueRef, bool) {
181     let (llconst, inlineable) = const_expr_unadjusted(cx, e);
182     let mut llconst = llconst;
183     let mut inlineable = inlineable;
184     let ety = ty::expr_ty(cx.tcx, e);
185     let adjustment = cx.tcx.adjustments.find_copy(&e.id);
186     match adjustment {
187         None => { }
188         Some(@ty::AutoAddEnv(ty::re_static, ast::BorrowedSigil)) => {
189             llconst = C_struct([llconst, C_null(Type::opaque_box(cx).ptr_to())], false)
190         }
191         Some(@ty::AutoAddEnv(ref r, ref s)) => {
192             cx.sess.span_bug(e.span, format!("unexpected static function: \
193                                            region {:?} sigil {:?}", *r, *s))
194         }
195         Some(@ty::AutoDerefRef(ref adj)) => {
196             let mut ty = ety;
197             let mut maybe_ptr = None;
198             do adj.autoderefs.times {
199                 let (dv, dt) = const_deref(cx, llconst, ty, false);
200                 maybe_ptr = Some(llconst);
201                 llconst = dv;
202                 ty = dt;
203             }
204
205             match adj.autoref {
206                 None => { }
207                 Some(ref autoref) => {
208                     // Don't copy data to do a deref+ref.
209                     let llptr = match maybe_ptr {
210                         Some(ptr) => ptr,
211                         None => {
212                             inlineable = false;
213                             const_addr_of(cx, llconst)
214                         }
215                     };
216                     match *autoref {
217                         ty::AutoUnsafe(m) |
218                         ty::AutoPtr(ty::re_static, m) => {
219                             assert!(m != ast::MutMutable);
220                             llconst = llptr;
221                         }
222                         ty::AutoBorrowVec(ty::re_static, m) => {
223                             assert!(m != ast::MutMutable);
224                             assert_eq!(abi::slice_elt_base, 0);
225                             assert_eq!(abi::slice_elt_len, 1);
226
227                             match ty::get(ty).sty {
228                                 ty::ty_evec(_, ty::vstore_fixed(*)) => {
229                                     let size = machine::llsize_of(cx, val_ty(llconst));
230                                     llconst = C_struct([llptr, size], false);
231                                 }
232                                 _ => {}
233                             }
234                         }
235                         _ => {
236                             cx.sess.span_bug(e.span,
237                                              format!("unimplemented const \
238                                                    autoref {:?}", autoref))
239                         }
240                     }
241                 }
242             }
243         }
244     }
245
246     let ety_adjusted = ty::expr_ty_adjusted(cx.tcx, e);
247     let llty = type_of::sizing_type_of(cx, ety_adjusted);
248     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
249     let tsize = machine::llsize_of_alloc(cx, llty);
250     if csize != tsize {
251         unsafe {
252             // XXX these values could use some context
253             llvm::LLVMDumpValue(llconst);
254             llvm::LLVMDumpValue(C_undef(llty));
255         }
256         cx.sess.bug(format!("const {} of type {} has size {} instead of {}",
257                          e.repr(cx.tcx), ty_to_str(cx.tcx, ety),
258                          csize, tsize));
259     }
260     (llconst, inlineable)
261 }
262
263 // the bool returned is whether this expression can be inlined into other crates
264 // if it's assigned to a static.
265 fn const_expr_unadjusted(cx: @mut CrateContext,
266                          e: &ast::Expr) -> (ValueRef, bool) {
267     fn map_list(cx: @mut CrateContext,
268                 exprs: &[@ast::Expr]) -> (~[ValueRef], bool) {
269         exprs.iter().map(|&e| const_expr(cx, e))
270              .fold((~[], true), |(L, all_inlineable), (val, inlineable)| {
271                     (vec::append_one(L, val), all_inlineable && inlineable)
272              })
273     }
274     unsafe {
275         let _icx = push_ctxt("const_expr");
276         return match e.node {
277           ast::ExprLit(lit) => (consts::const_lit(cx, e, *lit), true),
278           ast::ExprBinary(_, b, e1, e2) => {
279             let (te1, _) = const_expr(cx, e1);
280             let (te2, _) = const_expr(cx, e2);
281
282             let te2 = base::cast_shift_const_rhs(b, te1, te2);
283
284             /* Neither type is bottom, and we expect them to be unified
285              * already, so the following is safe. */
286             let ty = ty::expr_ty(cx.tcx, e1);
287             let is_float = ty::type_is_fp(ty);
288             let signed = ty::type_is_signed(ty);
289             return (match b {
290               ast::BiAdd   => {
291                 if is_float { llvm::LLVMConstFAdd(te1, te2) }
292                 else        { llvm::LLVMConstAdd(te1, te2) }
293               }
294               ast::BiSub => {
295                 if is_float { llvm::LLVMConstFSub(te1, te2) }
296                 else        { llvm::LLVMConstSub(te1, te2) }
297               }
298               ast::BiMul    => {
299                 if is_float { llvm::LLVMConstFMul(te1, te2) }
300                 else        { llvm::LLVMConstMul(te1, te2) }
301               }
302               ast::BiDiv    => {
303                 if is_float    { llvm::LLVMConstFDiv(te1, te2) }
304                 else if signed { llvm::LLVMConstSDiv(te1, te2) }
305                 else           { llvm::LLVMConstUDiv(te1, te2) }
306               }
307               ast::BiRem    => {
308                 if is_float    { llvm::LLVMConstFRem(te1, te2) }
309                 else if signed { llvm::LLVMConstSRem(te1, te2) }
310                 else           { llvm::LLVMConstURem(te1, te2) }
311               }
312               ast::BiAnd    => llvm::LLVMConstAnd(te1, te2),
313               ast::BiOr     => llvm::LLVMConstOr(te1, te2),
314               ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
315               ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
316               ast::BiBitOr  => llvm::LLVMConstOr(te1, te2),
317               ast::BiShl    => llvm::LLVMConstShl(te1, te2),
318               ast::BiShr    => {
319                 if signed { llvm::LLVMConstAShr(te1, te2) }
320                 else      { llvm::LLVMConstLShr(te1, te2) }
321               }
322               ast::BiEq     => {
323                   if is_float { ConstFCmp(RealOEQ, te1, te2) }
324                   else        { ConstICmp(IntEQ, te1, te2)   }
325               },
326               ast::BiLt     => {
327                   if is_float { ConstFCmp(RealOLT, te1, te2) }
328                   else        {
329                       if signed { ConstICmp(IntSLT, te1, te2) }
330                       else      { ConstICmp(IntULT, te1, te2) }
331                   }
332               },
333               ast::BiLe     => {
334                   if is_float { ConstFCmp(RealOLE, te1, te2) }
335                   else        {
336                       if signed { ConstICmp(IntSLE, te1, te2) }
337                       else      { ConstICmp(IntULE, te1, te2) }
338                   }
339               },
340               ast::BiNe     => {
341                   if is_float { ConstFCmp(RealONE, te1, te2) }
342                   else        { ConstICmp(IntNE, te1, te2) }
343               },
344               ast::BiGe     => {
345                   if is_float { ConstFCmp(RealOGE, te1, te2) }
346                   else        {
347                       if signed { ConstICmp(IntSGE, te1, te2) }
348                       else      { ConstICmp(IntUGE, te1, te2) }
349                   }
350               },
351               ast::BiGt     => {
352                   if is_float { ConstFCmp(RealOGT, te1, te2) }
353                   else        {
354                       if signed { ConstICmp(IntSGT, te1, te2) }
355                       else      { ConstICmp(IntUGT, te1, te2) }
356                   }
357               },
358             }, true)
359           },
360           ast::ExprUnary(_, u, e) => {
361             let (te, _) = const_expr(cx, e);
362             let ty = ty::expr_ty(cx.tcx, e);
363             let is_float = ty::type_is_fp(ty);
364             return (match u {
365               ast::UnBox(_)  |
366               ast::UnUniq |
367               ast::UnDeref  => {
368                 let (dv, _dt) = const_deref(cx, te, ty, true);
369                 dv
370               }
371               ast::UnNot    => {
372                 match ty::get(ty).sty {
373                     ty::ty_bool => {
374                         // Somewhat questionable, but I believe this is
375                         // correct.
376                         let te = llvm::LLVMConstTrunc(te, Type::i1().to_ref());
377                         let te = llvm::LLVMConstNot(te);
378                         llvm::LLVMConstZExt(te, Type::bool().to_ref())
379                     }
380                     _ => llvm::LLVMConstNot(te),
381                 }
382               }
383               ast::UnNeg    => {
384                 if is_float { llvm::LLVMConstFNeg(te) }
385                 else        { llvm::LLVMConstNeg(te) }
386               }
387             }, true)
388           }
389           ast::ExprField(base, field, _) => {
390               let bt = ty::expr_ty_adjusted(cx.tcx, base);
391               let brepr = adt::represent_type(cx, bt);
392               let (bv, inlineable) = const_expr(cx, base);
393               do expr::with_field_tys(cx.tcx, bt, None) |discr, field_tys| {
394                   let ix = ty::field_idx_strict(cx.tcx, field.name, field_tys);
395                   (adt::const_get_field(cx, brepr, bv, discr, ix), inlineable)
396               }
397           }
398
399           ast::ExprIndex(_, base, index) => {
400               let bt = ty::expr_ty_adjusted(cx.tcx, base);
401               let (bv, inlineable) = const_expr(cx, base);
402               let iv = match const_eval::eval_const_expr(cx.tcx, index) {
403                   const_eval::const_int(i) => i as u64,
404                   const_eval::const_uint(u) => u,
405                   _ => cx.sess.span_bug(index.span,
406                                         "index is not an integer-constant expression")
407               };
408               let (arr, len) = match ty::get(bt).sty {
409                   ty::ty_evec(_, vstore) | ty::ty_estr(vstore) =>
410                       match vstore {
411                       ty::vstore_fixed(u) =>
412                           (bv, C_uint(cx, u)),
413
414                       ty::vstore_slice(_) => {
415                           let unit_ty = ty::sequence_element_type(cx.tcx, bt);
416                           let llunitty = type_of::type_of(cx, unit_ty);
417                           let unit_sz = machine::llsize_of(cx, llunitty);
418
419                           let e1 = const_get_elt(cx, bv, [0]);
420                           (const_deref_ptr(cx, e1),
421                            llvm::LLVMConstUDiv(const_get_elt(cx, bv, [1]),
422                                                unit_sz))
423                       },
424                       _ => cx.sess.span_bug(base.span,
425                                             "index-expr base must be fixed-size or slice")
426                   },
427                   _ =>  cx.sess.span_bug(base.span,
428                                          "index-expr base must be a vector or string type")
429               };
430
431               let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
432               let len = match ty::get(bt).sty {
433                   ty::ty_estr(*) => {assert!(len > 0); len - 1},
434                   _ => len
435               };
436               if iv >= len {
437                   // FIXME #3170: report this earlier on in the const-eval
438                   // pass. Reporting here is a bit late.
439                   cx.sess.span_err(e.span,
440                                    "const index-expr is out of bounds");
441               }
442               (const_get_elt(cx, arr, [iv as c_uint]), inlineable)
443           }
444           ast::ExprCast(base, _) => {
445             let ety = ty::expr_ty(cx.tcx, e);
446             let llty = type_of::type_of(cx, ety);
447             let basety = ty::expr_ty(cx.tcx, base);
448             let (v, inlineable) = const_expr(cx, base);
449             return (match (expr::cast_type_kind(basety),
450                            expr::cast_type_kind(ety)) {
451
452               (expr::cast_integral, expr::cast_integral) => {
453                 let s = ty::type_is_signed(basety) as Bool;
454                 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
455               }
456               (expr::cast_integral, expr::cast_float) => {
457                 if ty::type_is_signed(basety) {
458                     llvm::LLVMConstSIToFP(v, llty.to_ref())
459                 } else {
460                     llvm::LLVMConstUIToFP(v, llty.to_ref())
461                 }
462               }
463               (expr::cast_float, expr::cast_float) => {
464                 llvm::LLVMConstFPCast(v, llty.to_ref())
465               }
466               (expr::cast_float, expr::cast_integral) => {
467                 if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
468                 else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
469               }
470               (expr::cast_enum, expr::cast_integral) |
471               (expr::cast_enum, expr::cast_float)  => {
472                 let repr = adt::represent_type(cx, basety);
473                 let discr = adt::const_get_discrim(cx, repr, v);
474                 let iv = C_integral(cx.int_type, discr, false);
475                 let ety_cast = expr::cast_type_kind(ety);
476                 match ety_cast {
477                     expr::cast_integral => {
478                         let s = ty::type_is_signed(ety) as Bool;
479                         llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
480                     }
481                     expr::cast_float => llvm::LLVMConstUIToFP(iv, llty.to_ref()),
482                     _ => cx.sess.bug("enum cast destination is not \
483                                       integral or float")
484                 }
485               }
486               (expr::cast_pointer, expr::cast_pointer) => {
487                 llvm::LLVMConstPointerCast(v, llty.to_ref())
488               }
489               (expr::cast_integral, expr::cast_pointer) => {
490                 llvm::LLVMConstIntToPtr(v, llty.to_ref())
491               }
492               _ => {
493                 cx.sess.impossible_case(e.span,
494                                         "bad combination of types for cast")
495               }
496             }, inlineable)
497           }
498           ast::ExprAddrOf(ast::MutImmutable, sub) => {
499               let (e, _) = const_expr(cx, sub);
500               (const_addr_of(cx, e), false)
501           }
502           ast::ExprTup(ref es) => {
503               let ety = ty::expr_ty(cx.tcx, e);
504               let repr = adt::represent_type(cx, ety);
505               let (vals, inlineable) = map_list(cx, *es);
506               (adt::trans_const(cx, repr, 0, vals), inlineable)
507           }
508           ast::ExprStruct(_, ref fs, ref base_opt) => {
509               let ety = ty::expr_ty(cx.tcx, e);
510               let repr = adt::represent_type(cx, ety);
511               let tcx = cx.tcx;
512
513               let base_val = match *base_opt {
514                 Some(base) => Some(const_expr(cx, base)),
515                 None => None
516               };
517
518               do expr::with_field_tys(tcx, ety, Some(e.id))
519                   |discr, field_tys| {
520                   let cs = field_tys.iter().enumerate()
521                       .map(|(ix, &field_ty)| {
522                       match fs.iter().find(|f| field_ty.ident.name == f.ident.name) {
523                           Some(f) => const_expr(cx, (*f).expr),
524                           None => {
525                               match base_val {
526                                 Some((bv, inlineable)) => {
527                                     (adt::const_get_field(cx, repr, bv, discr, ix),
528                                      inlineable)
529                                 }
530                                 None => cx.tcx.sess.span_bug(e.span, "missing struct field")
531                               }
532                           }
533                       }
534                   }).to_owned_vec();
535                   let (cs, inlineable) = vec::unzip(cs.move_iter());
536                   (adt::trans_const(cx, repr, discr, cs),
537                    inlineable.iter().fold(true, |a, &b| a && b))
538               }
539           }
540           ast::ExprVec(ref es, ast::MutImmutable) => {
541             let (v, _, _, inlineable) = const_vec(cx, e, *es);
542             (v, inlineable)
543           }
544           ast::ExprVstore(sub, ast::ExprVstoreSlice) => {
545             match sub.node {
546               ast::ExprLit(ref lit) => {
547                 match lit.node {
548                   ast::lit_str(*) => { const_expr(cx, sub) }
549                   _ => { cx.sess.span_bug(e.span, "bad const-slice lit") }
550                 }
551               }
552               ast::ExprVec(ref es, ast::MutImmutable) => {
553                 let (cv, sz, llunitty, _) = const_vec(cx, e, *es);
554                 let llty = val_ty(cv);
555                 let gv = do "const".with_c_str |name| {
556                     llvm::LLVMAddGlobal(cx.llmod, llty.to_ref(), name)
557                 };
558                 llvm::LLVMSetInitializer(gv, cv);
559                 llvm::LLVMSetGlobalConstant(gv, True);
560                 SetLinkage(gv, PrivateLinkage);
561                 let p = const_ptrcast(cx, gv, llunitty);
562                 (C_struct([p, sz], false), false)
563               }
564               _ => cx.sess.span_bug(e.span, "bad const-slice expr")
565             }
566           }
567           ast::ExprRepeat(elem, count, _) => {
568             let vec_ty = ty::expr_ty(cx.tcx, e);
569             let unit_ty = ty::sequence_element_type(cx.tcx, vec_ty);
570             let llunitty = type_of::type_of(cx, unit_ty);
571             let n = match const_eval::eval_const_expr(cx.tcx, count) {
572                 const_eval::const_int(i)  => i as uint,
573                 const_eval::const_uint(i) => i as uint,
574                 _ => cx.sess.span_bug(count.span, "count must be integral const expression.")
575             };
576             let vs = vec::from_elem(n, const_expr(cx, elem).first());
577             let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
578                 C_struct(vs, false)
579             } else {
580                 C_array(llunitty, vs)
581             };
582             (v, true)
583           }
584           ast::ExprPath(ref pth) => {
585             // Assert that there are no type parameters in this path.
586             assert!(pth.segments.iter().all(|seg| seg.types.is_empty()));
587
588             let tcx = cx.tcx;
589             match tcx.def_map.find(&e.id) {
590                 Some(&ast::DefFn(def_id, _purity)) => {
591                     if !ast_util::is_local(def_id) {
592                         let ty = csearch::get_type(cx.tcx, def_id).ty;
593                         (base::trans_external_path(cx, def_id, ty), true)
594                     } else {
595                         assert!(ast_util::is_local(def_id));
596                         (base::get_item_val(cx, def_id.node), true)
597                     }
598                 }
599                 Some(&ast::DefStatic(def_id, false)) => {
600                     get_const_val(cx, def_id)
601                 }
602                 Some(&ast::DefVariant(enum_did, variant_did, _)) => {
603                     let ety = ty::expr_ty(cx.tcx, e);
604                     let repr = adt::represent_type(cx, ety);
605                     let vinfo = ty::enum_variant_with_id(cx.tcx,
606                                                          enum_did,
607                                                          variant_did);
608                     (adt::trans_const(cx, repr, vinfo.disr_val, []), true)
609                 }
610                 Some(&ast::DefStruct(_)) => {
611                     let ety = ty::expr_ty(cx.tcx, e);
612                     let llty = type_of::type_of(cx, ety);
613                     (C_null(llty), true)
614                 }
615                 _ => {
616                     cx.sess.span_bug(e.span, "expected a const, fn, struct, or variant def")
617                 }
618             }
619           }
620           ast::ExprCall(callee, ref args, _) => {
621               let tcx = cx.tcx;
622               match tcx.def_map.find(&callee.id) {
623                   Some(&ast::DefStruct(_)) => {
624                       let ety = ty::expr_ty(cx.tcx, e);
625                       let repr = adt::represent_type(cx, ety);
626                       let (arg_vals, inlineable) = map_list(cx, *args);
627                       (adt::trans_const(cx, repr, 0, arg_vals), inlineable)
628                   }
629                   Some(&ast::DefVariant(enum_did, variant_did, _)) => {
630                       let ety = ty::expr_ty(cx.tcx, e);
631                       let repr = adt::represent_type(cx, ety);
632                       let vinfo = ty::enum_variant_with_id(cx.tcx,
633                                                            enum_did,
634                                                            variant_did);
635                       let (arg_vals, inlineable) = map_list(cx, *args);
636                       (adt::trans_const(cx, repr, vinfo.disr_val, arg_vals),
637                        inlineable)
638                   }
639                   _ => cx.sess.span_bug(e.span, "expected a struct or variant def")
640               }
641           }
642           ast::ExprParen(e) => { const_expr(cx, e) }
643           _ => cx.sess.span_bug(e.span,
644                   "bad constant expression type in consts::const_expr")
645         };
646     }
647 }
648
649 pub fn trans_const(ccx: @mut CrateContext, m: ast::Mutability, id: ast::NodeId) {
650     unsafe {
651         let _icx = push_ctxt("trans_const");
652         let g = base::get_item_val(ccx, id);
653         // At this point, get_item_val has already translated the
654         // constant's initializer to determine its LLVM type.
655         let v = ccx.const_values.get_copy(&id);
656         llvm::LLVMSetInitializer(g, v);
657         if m != ast::MutMutable {
658             llvm::LLVMSetGlobalConstant(g, True);
659         }
660     }
661 }