]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/context.rs
Add ToCStr method .with_c_str()
[rust.git] / src / librustc / middle / trans / context.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
12 use back::{upcall};
13 use driver::session;
14 use lib::llvm::{ContextRef, ModuleRef, ValueRef};
15 use lib::llvm::{llvm, TargetData, TypeNames};
16 use lib::llvm::{mk_target_data, False};
17 use metadata::common::LinkMeta;
18 use middle::astencode;
19 use middle::resolve;
20 use middle::trans::adt;
21 use middle::trans::base;
22 use middle::trans::builder::Builder;
23 use middle::trans::debuginfo;
24 use middle::trans::type_use;
25 use middle::trans::common::{C_i32, C_null};
26 use middle::ty;
27
28 use middle::trans::type_::Type;
29
30 use std::c_str::ToCStr;
31 use std::hash;
32 use std::hashmap::{HashMap, HashSet};
33 use std::local_data;
34 use std::vec;
35 use std::libc::c_uint;
36 use syntax::ast;
37
38 use middle::trans::common::{mono_id,ExternMap,tydesc_info,BuilderRef_res,Stats};
39
40 use middle::trans::base::{decl_crate_map};
41
42 pub struct CrateContext {
43      sess: session::Session,
44      llmod: ModuleRef,
45      llcx: ContextRef,
46      td: TargetData,
47      tn: TypeNames,
48      externs: ExternMap,
49      intrinsics: HashMap<&'static str, ValueRef>,
50      item_vals: HashMap<ast::NodeId, ValueRef>,
51      exp_map2: resolve::ExportMap2,
52      reachable: @mut HashSet<ast::NodeId>,
53      item_symbols: HashMap<ast::NodeId, ~str>,
54      link_meta: LinkMeta,
55      enum_sizes: HashMap<ty::t, uint>,
56      discrims: HashMap<ast::def_id, ValueRef>,
57      discrim_symbols: HashMap<ast::NodeId, @str>,
58      tydescs: HashMap<ty::t, @mut tydesc_info>,
59      // Set when running emit_tydescs to enforce that no more tydescs are
60      // created.
61      finished_tydescs: bool,
62      // Track mapping of external ids to local items imported for inlining
63      external: HashMap<ast::def_id, Option<ast::NodeId>>,
64      // Cache instances of monomorphized functions
65      monomorphized: HashMap<mono_id, ValueRef>,
66      monomorphizing: HashMap<ast::def_id, uint>,
67      // Cache computed type parameter uses (see type_use.rs)
68      type_use_cache: HashMap<ast::def_id, @~[type_use::type_uses]>,
69      // Cache generated vtables
70      vtables: HashMap<mono_id, ValueRef>,
71      // Cache of constant strings,
72      const_cstr_cache: HashMap<@str, ValueRef>,
73
74      // Reverse-direction for const ptrs cast from globals.
75      // Key is an int, cast from a ValueRef holding a *T,
76      // Val is a ValueRef holding a *[T].
77      //
78      // Needed because LLVM loses pointer->pointee association
79      // when we ptrcast, and we have to ptrcast during translation
80      // of a [T] const because we form a slice, a [*T,int] pair, not
81      // a pointer to an LLVM array type.
82      const_globals: HashMap<int, ValueRef>,
83
84      // Cache of emitted const values
85      const_values: HashMap<ast::NodeId, ValueRef>,
86
87      // Cache of external const values
88      extern_const_values: HashMap<ast::def_id, ValueRef>,
89
90      impl_method_cache: HashMap<(ast::def_id, ast::ident), ast::def_id>,
91
92      module_data: HashMap<~str, ValueRef>,
93      lltypes: HashMap<ty::t, Type>,
94      llsizingtypes: HashMap<ty::t, Type>,
95      adt_reprs: HashMap<ty::t, @adt::Repr>,
96      symbol_hasher: hash::State,
97      type_hashcodes: HashMap<ty::t, @str>,
98      type_short_names: HashMap<ty::t, ~str>,
99      all_llvm_symbols: HashSet<@str>,
100      tcx: ty::ctxt,
101      maps: astencode::Maps,
102      stats: @mut Stats,
103      upcalls: @upcall::Upcalls,
104      tydesc_type: Type,
105      int_type: Type,
106      float_type: Type,
107      opaque_vec_type: Type,
108      builder: BuilderRef_res,
109      crate_map: ValueRef,
110      // Set when at least one function uses GC. Needed so that
111      // decl_gc_metadata knows whether to link to the module metadata, which
112      // is not emitted by LLVM's GC pass when no functions use GC.
113      uses_gc: bool,
114      dbg_cx: Option<debuginfo::DebugContext>,
115      do_not_commit_warning_issued: bool
116 }
117
118 impl CrateContext {
119     pub fn new(sess: session::Session,
120                name: &str,
121                tcx: ty::ctxt,
122                emap2: resolve::ExportMap2,
123                maps: astencode::Maps,
124                symbol_hasher: hash::State,
125                link_meta: LinkMeta,
126                reachable: @mut HashSet<ast::NodeId>)
127                -> CrateContext {
128         unsafe {
129             let llcx = llvm::LLVMContextCreate();
130             set_task_llcx(llcx);
131             let llmod = do name.with_c_str |buf| {
132                 llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
133             };
134             let data_layout: &str = sess.targ_cfg.target_strs.data_layout;
135             let targ_triple: &str = sess.targ_cfg.target_strs.target_triple;
136             do data_layout.with_c_str |buf| {
137                 llvm::LLVMSetDataLayout(llmod, buf)
138             };
139             do targ_triple.with_c_str |buf| {
140                 llvm::LLVMSetTarget(llmod, buf)
141             };
142             let targ_cfg = sess.targ_cfg;
143
144             let td = mk_target_data(sess.targ_cfg.target_strs.data_layout);
145             let mut tn = TypeNames::new();
146
147             let mut intrinsics = base::declare_intrinsics(llmod);
148             if sess.opts.extra_debuginfo {
149                 base::declare_dbg_intrinsics(llmod, &mut intrinsics);
150             }
151             let int_type = Type::int(targ_cfg.arch);
152             let float_type = Type::float(targ_cfg.arch);
153             let tydesc_type = Type::tydesc(targ_cfg.arch);
154             let opaque_vec_type = Type::opaque_vec(targ_cfg.arch);
155
156             let mut str_slice_ty = Type::named_struct("str_slice");
157             str_slice_ty.set_struct_body([Type::i8p(), int_type], false);
158
159             tn.associate_type("tydesc", &tydesc_type);
160             tn.associate_type("str_slice", &str_slice_ty);
161
162             let crate_map = decl_crate_map(sess, link_meta, llmod);
163             let dbg_cx = if sess.opts.debuginfo {
164                 Some(debuginfo::DebugContext::new(llmod, name.to_owned()))
165             } else {
166                 None
167             };
168
169             if sess.count_llvm_insns() {
170                 base::init_insn_ctxt()
171             }
172
173             CrateContext {
174                   sess: sess,
175                   llmod: llmod,
176                   llcx: llcx,
177                   td: td,
178                   tn: tn,
179                   externs: HashMap::new(),
180                   intrinsics: intrinsics,
181                   item_vals: HashMap::new(),
182                   exp_map2: emap2,
183                   reachable: reachable,
184                   item_symbols: HashMap::new(),
185                   link_meta: link_meta,
186                   enum_sizes: HashMap::new(),
187                   discrims: HashMap::new(),
188                   discrim_symbols: HashMap::new(),
189                   tydescs: HashMap::new(),
190                   finished_tydescs: false,
191                   external: HashMap::new(),
192                   monomorphized: HashMap::new(),
193                   monomorphizing: HashMap::new(),
194                   type_use_cache: HashMap::new(),
195                   vtables: HashMap::new(),
196                   const_cstr_cache: HashMap::new(),
197                   const_globals: HashMap::new(),
198                   const_values: HashMap::new(),
199                   extern_const_values: HashMap::new(),
200                   impl_method_cache: HashMap::new(),
201                   module_data: HashMap::new(),
202                   lltypes: HashMap::new(),
203                   llsizingtypes: HashMap::new(),
204                   adt_reprs: HashMap::new(),
205                   symbol_hasher: symbol_hasher,
206                   type_hashcodes: HashMap::new(),
207                   type_short_names: HashMap::new(),
208                   all_llvm_symbols: HashSet::new(),
209                   tcx: tcx,
210                   maps: maps,
211                   stats: @mut Stats {
212                     n_static_tydescs: 0u,
213                     n_glues_created: 0u,
214                     n_null_glues: 0u,
215                     n_real_glues: 0u,
216                     n_fns: 0u,
217                     n_monos: 0u,
218                     n_inlines: 0u,
219                     n_closures: 0u,
220                     n_llvm_insns: 0u,
221                     llvm_insn_ctxt: ~[],
222                     llvm_insns: HashMap::new(),
223                     fn_stats: ~[]
224                   },
225                   upcalls: upcall::declare_upcalls(targ_cfg, llmod),
226                   tydesc_type: tydesc_type,
227                   int_type: int_type,
228                   float_type: float_type,
229                   opaque_vec_type: opaque_vec_type,
230                   builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
231                   crate_map: crate_map,
232                   uses_gc: false,
233                   dbg_cx: dbg_cx,
234                   do_not_commit_warning_issued: false
235             }
236         }
237     }
238
239     pub fn builder(@mut self) -> Builder {
240         Builder::new(self)
241     }
242
243     pub fn const_inbounds_gepi(&self,
244                                pointer: ValueRef,
245                                indices: &[uint]) -> ValueRef {
246         debug!("const_inbounds_gepi: pointer=%s indices=%?",
247                self.tn.val_to_str(pointer), indices);
248         let v: ~[ValueRef] =
249             indices.iter().map(|i| C_i32(*i as i32)).collect();
250         unsafe {
251             llvm::LLVMConstInBoundsGEP(pointer,
252                                        vec::raw::to_ptr(v),
253                                        indices.len() as c_uint)
254         }
255     }
256
257     pub fn offsetof_gep(&self,
258                         llptr_ty: Type,
259                         indices: &[uint]) -> ValueRef {
260         /*!
261          * Returns the offset of applying the given GEP indices
262          * to an instance of `llptr_ty`. Similar to `offsetof` in C,
263          * except that `llptr_ty` must be a pointer type.
264          */
265
266         unsafe {
267             let null = C_null(llptr_ty);
268             llvm::LLVMConstPtrToInt(self.const_inbounds_gepi(null, indices),
269                                     self.int_type.to_ref())
270         }
271     }
272 }
273
274 #[unsafe_destructor]
275 impl Drop for CrateContext {
276     fn drop(&self) {
277         unset_task_llcx();
278     }
279 }
280
281 static task_local_llcx_key: local_data::Key<@ContextRef> = &local_data::Key;
282
283 pub fn task_llcx() -> ContextRef {
284     let opt = local_data::get(task_local_llcx_key, |k| k.map_move(|k| *k));
285     *opt.expect("task-local LLVMContextRef wasn't ever set!")
286 }
287
288 fn set_task_llcx(c: ContextRef) {
289     local_data::set(task_local_llcx_key, @c);
290 }
291
292 fn unset_task_llcx() {
293     local_data::pop(task_local_llcx_key);
294 }