]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/debuginfo.rs
rollup merge of #21015: steveklabnik/gh20852
[rust.git] / src / librustc_trans / trans / debuginfo.rs
1 // Copyright 2012-2014 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 //! # Debug Info Module
12 //!
13 //! This module serves the purpose of generating debug symbols. We use LLVM's
14 //! [source level debugging](http://llvm.org/docs/SourceLevelDebugging.html)
15 //! features for generating the debug information. The general principle is this:
16 //!
17 //! Given the right metadata in the LLVM IR, the LLVM code generator is able to
18 //! create DWARF debug symbols for the given code. The
19 //! [metadata](http://llvm.org/docs/LangRef.html#metadata-type) is structured much
20 //! like DWARF *debugging information entries* (DIE), representing type information
21 //! such as datatype layout, function signatures, block layout, variable location
22 //! and scope information, etc. It is the purpose of this module to generate correct
23 //! metadata and insert it into the LLVM IR.
24 //!
25 //! As the exact format of metadata trees may change between different LLVM
26 //! versions, we now use LLVM
27 //! [DIBuilder](http://llvm.org/docs/doxygen/html/classllvm_1_1DIBuilder.html) to
28 //! create metadata where possible. This will hopefully ease the adaption of this
29 //! module to future LLVM versions.
30 //!
31 //! The public API of the module is a set of functions that will insert the correct
32 //! metadata into the LLVM IR when called with the right parameters. The module is
33 //! thus driven from an outside client with functions like
34 //! `debuginfo::create_local_var_metadata(bcx: block, local: &ast::local)`.
35 //!
36 //! Internally the module will try to reuse already created metadata by utilizing a
37 //! cache. The way to get a shared metadata node when needed is thus to just call
38 //! the corresponding function in this module:
39 //!
40 //!     let file_metadata = file_metadata(crate_context, path);
41 //!
42 //! The function will take care of probing the cache for an existing node for that
43 //! exact file path.
44 //!
45 //! All private state used by the module is stored within either the
46 //! CrateDebugContext struct (owned by the CrateContext) or the FunctionDebugContext
47 //! (owned by the FunctionContext).
48 //!
49 //! This file consists of three conceptual sections:
50 //! 1. The public interface of the module
51 //! 2. Module-internal metadata creation functions
52 //! 3. Minor utility functions
53 //!
54 //!
55 //! ## Recursive Types
56 //!
57 //! Some kinds of types, such as structs and enums can be recursive. That means that
58 //! the type definition of some type X refers to some other type which in turn
59 //! (transitively) refers to X. This introduces cycles into the type referral graph.
60 //! A naive algorithm doing an on-demand, depth-first traversal of this graph when
61 //! describing types, can get trapped in an endless loop when it reaches such a
62 //! cycle.
63 //!
64 //! For example, the following simple type for a singly-linked list...
65 //!
66 //! ```
67 //! struct List {
68 //!     value: int,
69 //!     tail: Option<Box<List>>,
70 //! }
71 //! ```
72 //!
73 //! will generate the following callstack with a naive DFS algorithm:
74 //!
75 //! ```
76 //! describe(t = List)
77 //!   describe(t = int)
78 //!   describe(t = Option<Box<List>>)
79 //!     describe(t = Box<List>)
80 //!       describe(t = List) // at the beginning again...
81 //!       ...
82 //! ```
83 //!
84 //! To break cycles like these, we use "forward declarations". That is, when the
85 //! algorithm encounters a possibly recursive type (any struct or enum), it
86 //! immediately creates a type description node and inserts it into the cache
87 //! *before* describing the members of the type. This type description is just a
88 //! stub (as type members are not described and added to it yet) but it allows the
89 //! algorithm to already refer to the type. After the stub is inserted into the
90 //! cache, the algorithm continues as before. If it now encounters a recursive
91 //! reference, it will hit the cache and does not try to describe the type anew.
92 //!
93 //! This behaviour is encapsulated in the 'RecursiveTypeDescription' enum, which
94 //! represents a kind of continuation, storing all state needed to continue
95 //! traversal at the type members after the type has been registered with the cache.
96 //! (This implementation approach might be a tad over-engineered and may change in
97 //! the future)
98 //!
99 //!
100 //! ## Source Locations and Line Information
101 //!
102 //! In addition to data type descriptions the debugging information must also allow
103 //! to map machine code locations back to source code locations in order to be useful.
104 //! This functionality is also handled in this module. The following functions allow
105 //! to control source mappings:
106 //!
107 //! + set_source_location()
108 //! + clear_source_location()
109 //! + start_emitting_source_locations()
110 //!
111 //! `set_source_location()` allows to set the current source location. All IR
112 //! instructions created after a call to this function will be linked to the given
113 //! source location, until another location is specified with
114 //! `set_source_location()` or the source location is cleared with
115 //! `clear_source_location()`. In the later case, subsequent IR instruction will not
116 //! be linked to any source location. As you can see, this is a stateful API
117 //! (mimicking the one in LLVM), so be careful with source locations set by previous
118 //! calls. It's probably best to not rely on any specific state being present at a
119 //! given point in code.
120 //!
121 //! One topic that deserves some extra attention is *function prologues*. At the
122 //! beginning of a function's machine code there are typically a few instructions
123 //! for loading argument values into allocas and checking if there's enough stack
124 //! space for the function to execute. This *prologue* is not visible in the source
125 //! code and LLVM puts a special PROLOGUE END marker into the line table at the
126 //! first non-prologue instruction of the function. In order to find out where the
127 //! prologue ends, LLVM looks for the first instruction in the function body that is
128 //! linked to a source location. So, when generating prologue instructions we have
129 //! to make sure that we don't emit source location information until the 'real'
130 //! function body begins. For this reason, source location emission is disabled by
131 //! default for any new function being translated and is only activated after a call
132 //! to the third function from the list above, `start_emitting_source_locations()`.
133 //! This function should be called right before regularly starting to translate the
134 //! top-level block of the given function.
135 //!
136 //! There is one exception to the above rule: `llvm.dbg.declare` instruction must be
137 //! linked to the source location of the variable being declared. For function
138 //! parameters these `llvm.dbg.declare` instructions typically occur in the middle
139 //! of the prologue, however, they are ignored by LLVM's prologue detection. The
140 //! `create_argument_metadata()` and related functions take care of linking the
141 //! `llvm.dbg.declare` instructions to the correct source locations even while
142 //! source location emission is still disabled, so there is no need to do anything
143 //! special with source location handling here.
144 //!
145 //! ## Unique Type Identification
146 //!
147 //! In order for link-time optimization to work properly, LLVM needs a unique type
148 //! identifier that tells it across compilation units which types are the same as
149 //! others. This type identifier is created by TypeMap::get_unique_type_id_of_type()
150 //! using the following algorithm:
151 //!
152 //! (1) Primitive types have their name as ID
153 //! (2) Structs, enums and traits have a multipart identifier
154 //!
155 //!     (1) The first part is the SVH (strict version hash) of the crate they were
156 //!         originally defined in
157 //!
158 //!     (2) The second part is the ast::NodeId of the definition in their original
159 //!         crate
160 //!
161 //!     (3) The final part is a concatenation of the type IDs of their concrete type
162 //!         arguments if they are generic types.
163 //!
164 //! (3) Tuple-, pointer and function types are structurally identified, which means
165 //!     that they are equivalent if their component types are equivalent (i.e. (int,
166 //!     int) is the same regardless in which crate it is used).
167 //!
168 //! This algorithm also provides a stable ID for types that are defined in one crate
169 //! but instantiated from metadata within another crate. We just have to take care
170 //! to always map crate and node IDs back to the original crate context.
171 //!
172 //! As a side-effect these unique type IDs also help to solve a problem arising from
173 //! lifetime parameters. Since lifetime parameters are completely omitted in
174 //! debuginfo, more than one `Ty` instance may map to the same debuginfo type
175 //! metadata, that is, some struct `Struct<'a>` may have N instantiations with
176 //! different concrete substitutions for `'a`, and thus there will be N `Ty`
177 //! instances for the type `Struct<'a>` even though it is not generic otherwise.
178 //! Unfortunately this means that we cannot use `ty::type_id()` as cheap identifier
179 //! for type metadata---we have done this in the past, but it led to unnecessary
180 //! metadata duplication in the best case and LLVM assertions in the worst. However,
181 //! the unique type ID as described above *can* be used as identifier. Since it is
182 //! comparatively expensive to construct, though, `ty::type_id()` is still used
183 //! additionally as an optimization for cases where the exact same type has been
184 //! seen before (which is most of the time).
185 use self::VariableAccess::*;
186 use self::VariableKind::*;
187 use self::MemberOffset::*;
188 use self::MemberDescriptionFactory::*;
189 use self::RecursiveTypeDescription::*;
190 use self::EnumDiscriminantInfo::*;
191 use self::DebugLocation::*;
192
193 use llvm;
194 use llvm::{ModuleRef, ContextRef, ValueRef};
195 use llvm::debuginfo::*;
196 use metadata::csearch;
197 use middle::subst::{self, Substs};
198 use trans::{self, adt, machine, type_of};
199 use trans::common::*;
200 use trans::_match::{BindingInfo, TrByCopy, TrByMove, TrByRef};
201 use trans::monomorphize;
202 use trans::type_::Type;
203 use middle::ty::{self, Ty, UnboxedClosureTyper};
204 use middle::pat_util;
205 use session::config::{self, FullDebugInfo, LimitedDebugInfo, NoDebugInfo};
206 use util::nodemap::{DefIdMap, NodeMap, FnvHashMap, FnvHashSet};
207 use util::ppaux;
208
209 use libc::c_uint;
210 use std::ffi::CString;
211 use std::cell::{Cell, RefCell};
212 use std::ptr;
213 use std::rc::{Rc, Weak};
214 use syntax::util::interner::Interner;
215 use syntax::codemap::{Span, Pos};
216 use syntax::{ast, codemap, ast_util, ast_map, attr};
217 use syntax::ast_util::PostExpansionMethod;
218 use syntax::parse::token::{self, special_idents};
219
220 const DW_LANG_RUST: c_uint = 0x9000;
221
222 #[allow(non_upper_case_globals)]
223 const DW_TAG_auto_variable: c_uint = 0x100;
224 #[allow(non_upper_case_globals)]
225 const DW_TAG_arg_variable: c_uint = 0x101;
226
227 #[allow(non_upper_case_globals)]
228 const DW_ATE_boolean: c_uint = 0x02;
229 #[allow(non_upper_case_globals)]
230 const DW_ATE_float: c_uint = 0x04;
231 #[allow(non_upper_case_globals)]
232 const DW_ATE_signed: c_uint = 0x05;
233 #[allow(non_upper_case_globals)]
234 const DW_ATE_unsigned: c_uint = 0x07;
235 #[allow(non_upper_case_globals)]
236 const DW_ATE_unsigned_char: c_uint = 0x08;
237
238 const UNKNOWN_LINE_NUMBER: c_uint = 0;
239 const UNKNOWN_COLUMN_NUMBER: c_uint = 0;
240
241 // ptr::null() doesn't work :(
242 const UNKNOWN_FILE_METADATA: DIFile = (0 as DIFile);
243 const UNKNOWN_SCOPE_METADATA: DIScope = (0 as DIScope);
244
245 const FLAGS_NONE: c_uint = 0;
246
247 //=-----------------------------------------------------------------------------
248 //  Public Interface of debuginfo module
249 //=-----------------------------------------------------------------------------
250
251 #[derive(Copy, Show, Hash, Eq, PartialEq, Clone)]
252 struct UniqueTypeId(ast::Name);
253
254 // The TypeMap is where the CrateDebugContext holds the type metadata nodes
255 // created so far. The metadata nodes are indexed by UniqueTypeId, and, for
256 // faster lookup, also by Ty. The TypeMap is responsible for creating
257 // UniqueTypeIds.
258 struct TypeMap<'tcx> {
259     // The UniqueTypeIds created so far
260     unique_id_interner: Interner<Rc<String>>,
261     // A map from UniqueTypeId to debuginfo metadata for that type. This is a 1:1 mapping.
262     unique_id_to_metadata: FnvHashMap<UniqueTypeId, DIType>,
263     // A map from types to debuginfo metadata. This is a N:1 mapping.
264     type_to_metadata: FnvHashMap<Ty<'tcx>, DIType>,
265     // A map from types to UniqueTypeId. This is a N:1 mapping.
266     type_to_unique_id: FnvHashMap<Ty<'tcx>, UniqueTypeId>
267 }
268
269 impl<'tcx> TypeMap<'tcx> {
270
271     fn new() -> TypeMap<'tcx> {
272         TypeMap {
273             unique_id_interner: Interner::new(),
274             type_to_metadata: FnvHashMap::new(),
275             unique_id_to_metadata: FnvHashMap::new(),
276             type_to_unique_id: FnvHashMap::new(),
277         }
278     }
279
280     // Adds a Ty to metadata mapping to the TypeMap. The method will fail if
281     // the mapping already exists.
282     fn register_type_with_metadata<'a>(&mut self,
283                                        cx: &CrateContext<'a, 'tcx>,
284                                        type_: Ty<'tcx>,
285                                        metadata: DIType) {
286         if self.type_to_metadata.insert(type_, metadata).is_some() {
287             cx.sess().bug(&format!("Type metadata for Ty '{}' is already in the TypeMap!",
288                                    ppaux::ty_to_string(cx.tcx(), type_))[]);
289         }
290     }
291
292     // Adds a UniqueTypeId to metadata mapping to the TypeMap. The method will
293     // fail if the mapping already exists.
294     fn register_unique_id_with_metadata(&mut self,
295                                         cx: &CrateContext,
296                                         unique_type_id: UniqueTypeId,
297                                         metadata: DIType) {
298         if self.unique_id_to_metadata.insert(unique_type_id, metadata).is_some() {
299             let unique_type_id_str = self.get_unique_type_id_as_string(unique_type_id);
300             cx.sess().bug(&format!("Type metadata for unique id '{}' is already in the TypeMap!",
301                                   &unique_type_id_str[])[]);
302         }
303     }
304
305     fn find_metadata_for_type(&self, type_: Ty<'tcx>) -> Option<DIType> {
306         self.type_to_metadata.get(&type_).cloned()
307     }
308
309     fn find_metadata_for_unique_id(&self, unique_type_id: UniqueTypeId) -> Option<DIType> {
310         self.unique_id_to_metadata.get(&unique_type_id).cloned()
311     }
312
313     // Get the string representation of a UniqueTypeId. This method will fail if
314     // the id is unknown.
315     fn get_unique_type_id_as_string(&self, unique_type_id: UniqueTypeId) -> Rc<String> {
316         let UniqueTypeId(interner_key) = unique_type_id;
317         self.unique_id_interner.get(interner_key)
318     }
319
320     // Get the UniqueTypeId for the given type. If the UniqueTypeId for the given
321     // type has been requested before, this is just a table lookup. Otherwise an
322     // ID will be generated and stored for later lookup.
323     fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
324                                       type_: Ty<'tcx>) -> UniqueTypeId {
325
326         // basic type               -> {:name of the type:}
327         // tuple                    -> {tuple_(:param-uid:)*}
328         // struct                   -> {struct_:svh: / :node-id:_<(:param-uid:),*> }
329         // enum                     -> {enum_:svh: / :node-id:_<(:param-uid:),*> }
330         // enum variant             -> {variant_:variant-name:_:enum-uid:}
331         // reference (&)            -> {& :pointee-uid:}
332         // mut reference (&mut)     -> {&mut :pointee-uid:}
333         // ptr (*)                  -> {* :pointee-uid:}
334         // mut ptr (*mut)           -> {*mut :pointee-uid:}
335         // unique ptr (~)           -> {~ :pointee-uid:}
336         // @-ptr (@)                -> {@ :pointee-uid:}
337         // sized vec ([T; x])       -> {[:size:] :element-uid:}
338         // unsized vec ([T])        -> {[] :element-uid:}
339         // trait (T)                -> {trait_:svh: / :node-id:_<(:param-uid:),*> }
340         // closure                  -> {<unsafe_> <once_> :store-sigil:
341         //                                  |(:param-uid:),* <,_...>| -> \
342         //                                  :return-type-uid: : (:bounds:)*}
343         // function                 -> {<unsafe_> <abi_> fn( (:param-uid:)* <,_...> ) -> \
344         //                                  :return-type-uid:}
345         // unique vec box (~[])     -> {HEAP_VEC_BOX<:pointee-uid:>}
346         // gc box                   -> {GC_BOX<:pointee-uid:>}
347         // projection (<T as U>::V) -> {<:ty-uid: as :trait-uid:> :: :name-uid: }
348
349         match self.type_to_unique_id.get(&type_).cloned() {
350             Some(unique_type_id) => return unique_type_id,
351             None => { /* generate one */}
352         };
353
354         let mut unique_type_id = String::with_capacity(256);
355         unique_type_id.push('{');
356
357         match type_.sty {
358             ty::ty_bool     |
359             ty::ty_char     |
360             ty::ty_str      |
361             ty::ty_int(_)   |
362             ty::ty_uint(_)  |
363             ty::ty_float(_) => {
364                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
365             },
366             ty::ty_enum(def_id, substs) => {
367                 unique_type_id.push_str("enum ");
368                 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
369             },
370             ty::ty_struct(def_id, substs) => {
371                 unique_type_id.push_str("struct ");
372                 from_def_id_and_substs(self, cx, def_id, substs, &mut unique_type_id);
373             },
374             ty::ty_tup(ref component_types) if component_types.is_empty() => {
375                 push_debuginfo_type_name(cx, type_, false, &mut unique_type_id);
376             },
377             ty::ty_tup(ref component_types) => {
378                 unique_type_id.push_str("tuple ");
379                 for &component_type in component_types.iter() {
380                     let component_type_id =
381                         self.get_unique_type_id_of_type(cx, component_type);
382                     let component_type_id =
383                         self.get_unique_type_id_as_string(component_type_id);
384                     unique_type_id.push_str(&component_type_id[]);
385                 }
386             },
387             ty::ty_uniq(inner_type) => {
388                 unique_type_id.push('~');
389                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
390                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
391                 unique_type_id.push_str(&inner_type_id[]);
392             },
393             ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => {
394                 unique_type_id.push('*');
395                 if mutbl == ast::MutMutable {
396                     unique_type_id.push_str("mut");
397                 }
398
399                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
400                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
401                 unique_type_id.push_str(&inner_type_id[]);
402             },
403             ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => {
404                 unique_type_id.push('&');
405                 if mutbl == ast::MutMutable {
406                     unique_type_id.push_str("mut");
407                 }
408
409                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
410                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
411                 unique_type_id.push_str(&inner_type_id[]);
412             },
413             ty::ty_vec(inner_type, optional_length) => {
414                 match optional_length {
415                     Some(len) => {
416                         unique_type_id.push_str(&format!("[{}]", len)[]);
417                     }
418                     None => {
419                         unique_type_id.push_str("[]");
420                     }
421                 };
422
423                 let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type);
424                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
425                 unique_type_id.push_str(&inner_type_id[]);
426             },
427             ty::ty_trait(ref trait_data) => {
428                 unique_type_id.push_str("trait ");
429
430                 let principal =
431                     ty::erase_late_bound_regions(cx.tcx(),
432                                                  &trait_data.principal);
433
434                 from_def_id_and_substs(self,
435                                        cx,
436                                        principal.def_id,
437                                        principal.substs,
438                                        &mut unique_type_id);
439             },
440             ty::ty_projection(ref projection) => {
441                 unique_type_id.push_str("<");
442
443                 let self_ty = projection.trait_ref.self_ty();
444                 let self_type_id = self.get_unique_type_id_of_type(cx, self_ty);
445                 let self_type_id = self.get_unique_type_id_as_string(self_type_id);
446                 unique_type_id.push_str(&self_type_id[]);
447
448                 unique_type_id.push_str(" as ");
449
450                 from_def_id_and_substs(self,
451                                        cx,
452                                        projection.trait_ref.def_id,
453                                        projection.trait_ref.substs,
454                                        &mut unique_type_id);
455
456                 unique_type_id.push_str(">::");
457                 unique_type_id.push_str(token::get_name(projection.item_name).get());
458             },
459             ty::ty_bare_fn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => {
460                 if unsafety == ast::Unsafety::Unsafe {
461                     unique_type_id.push_str("unsafe ");
462                 }
463
464                 unique_type_id.push_str(abi.name());
465
466                 unique_type_id.push_str(" fn(");
467
468                 let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
469
470                 for &parameter_type in sig.inputs.iter() {
471                     let parameter_type_id =
472                         self.get_unique_type_id_of_type(cx, parameter_type);
473                     let parameter_type_id =
474                         self.get_unique_type_id_as_string(parameter_type_id);
475                     unique_type_id.push_str(&parameter_type_id[]);
476                     unique_type_id.push(',');
477                 }
478
479                 if sig.variadic {
480                     unique_type_id.push_str("...");
481                 }
482
483                 unique_type_id.push_str(")->");
484                 match sig.output {
485                     ty::FnConverging(ret_ty) => {
486                         let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
487                         let return_type_id = self.get_unique_type_id_as_string(return_type_id);
488                         unique_type_id.push_str(&return_type_id[]);
489                     }
490                     ty::FnDiverging => {
491                         unique_type_id.push_str("!");
492                     }
493                 }
494             },
495             ty::ty_unboxed_closure(def_id, _, substs) => {
496                 let typer = NormalizingUnboxedClosureTyper::new(cx.tcx());
497                 let closure_ty = typer.unboxed_closure_type(def_id, substs);
498                 self.get_unique_type_id_of_closure_type(cx,
499                                                         closure_ty,
500                                                         &mut unique_type_id);
501             },
502             ty::ty_err |
503             ty::ty_infer(_) |
504             ty::ty_open(_) |
505             ty::ty_param(_) => {
506                 cx.sess().bug(&format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}",
507                                       &ppaux::ty_to_string(cx.tcx(), type_)[],
508                                       type_.sty)[])
509             }
510         };
511
512         unique_type_id.push('}');
513
514         // Trim to size before storing permanently
515         unique_type_id.shrink_to_fit();
516
517         let key = self.unique_id_interner.intern(Rc::new(unique_type_id));
518         self.type_to_unique_id.insert(type_, UniqueTypeId(key));
519
520         return UniqueTypeId(key);
521
522         fn from_def_id_and_substs<'a, 'tcx>(type_map: &mut TypeMap<'tcx>,
523                                             cx: &CrateContext<'a, 'tcx>,
524                                             def_id: ast::DefId,
525                                             substs: &subst::Substs<'tcx>,
526                                             output: &mut String) {
527             // First, find out the 'real' def_id of the type. Items inlined from
528             // other crates have to be mapped back to their source.
529             let source_def_id = if def_id.krate == ast::LOCAL_CRATE {
530                 match cx.external_srcs().borrow().get(&def_id.node).cloned() {
531                     Some(source_def_id) => {
532                         // The given def_id identifies the inlined copy of a
533                         // type definition, let's take the source of the copy.
534                         source_def_id
535                     }
536                     None => def_id
537                 }
538             } else {
539                 def_id
540             };
541
542             // Get the crate hash as first part of the identifier.
543             let crate_hash = if source_def_id.krate == ast::LOCAL_CRATE {
544                 cx.link_meta().crate_hash.clone()
545             } else {
546                 cx.sess().cstore.get_crate_hash(source_def_id.krate)
547             };
548
549             output.push_str(crate_hash.as_str());
550             output.push_str("/");
551             output.push_str(&format!("{:x}", def_id.node)[]);
552
553             // Maybe check that there is no self type here.
554
555             let tps = substs.types.get_slice(subst::TypeSpace);
556             if tps.len() > 0 {
557                 output.push('<');
558
559                 for &type_parameter in tps.iter() {
560                     let param_type_id =
561                         type_map.get_unique_type_id_of_type(cx, type_parameter);
562                     let param_type_id =
563                         type_map.get_unique_type_id_as_string(param_type_id);
564                     output.push_str(&param_type_id[]);
565                     output.push(',');
566                 }
567
568                 output.push('>');
569             }
570         }
571     }
572
573     fn get_unique_type_id_of_closure_type<'a>(&mut self,
574                                               cx: &CrateContext<'a, 'tcx>,
575                                               closure_ty: ty::ClosureTy<'tcx>,
576                                               unique_type_id: &mut String) {
577         let ty::ClosureTy { unsafety,
578                             onceness,
579                             store,
580                             ref bounds,
581                             ref sig,
582                             abi: _ } = closure_ty;
583         if unsafety == ast::Unsafety::Unsafe {
584             unique_type_id.push_str("unsafe ");
585         }
586
587         if onceness == ast::Once {
588             unique_type_id.push_str("once ");
589         }
590
591         match store {
592             ty::UniqTraitStore => unique_type_id.push_str("~|"),
593             ty::RegionTraitStore(_, ast::MutMutable) => {
594                 unique_type_id.push_str("&mut|")
595             }
596             ty::RegionTraitStore(_, ast::MutImmutable) => {
597                 unique_type_id.push_str("&|")
598             }
599         };
600
601         let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
602
603         for &parameter_type in sig.inputs.iter() {
604             let parameter_type_id =
605                 self.get_unique_type_id_of_type(cx, parameter_type);
606             let parameter_type_id =
607                 self.get_unique_type_id_as_string(parameter_type_id);
608             unique_type_id.push_str(&parameter_type_id[]);
609             unique_type_id.push(',');
610         }
611
612         if sig.variadic {
613             unique_type_id.push_str("...");
614         }
615
616         unique_type_id.push_str("|->");
617
618         match sig.output {
619             ty::FnConverging(ret_ty) => {
620                 let return_type_id = self.get_unique_type_id_of_type(cx, ret_ty);
621                 let return_type_id = self.get_unique_type_id_as_string(return_type_id);
622                 unique_type_id.push_str(&return_type_id[]);
623             }
624             ty::FnDiverging => {
625                 unique_type_id.push_str("!");
626             }
627         }
628
629         unique_type_id.push(':');
630
631         for bound in bounds.builtin_bounds.iter() {
632             match bound {
633                 ty::BoundSend => unique_type_id.push_str("Send"),
634                 ty::BoundSized => unique_type_id.push_str("Sized"),
635                 ty::BoundCopy => unique_type_id.push_str("Copy"),
636                 ty::BoundSync => unique_type_id.push_str("Sync"),
637             };
638             unique_type_id.push('+');
639         }
640     }
641
642     // Get the UniqueTypeId for an enum variant. Enum variants are not really
643     // types of their own, so they need special handling. We still need a
644     // UniqueTypeId for them, since to debuginfo they *are* real types.
645     fn get_unique_type_id_of_enum_variant<'a>(&mut self,
646                                               cx: &CrateContext<'a, 'tcx>,
647                                               enum_type: Ty<'tcx>,
648                                               variant_name: &str)
649                                               -> UniqueTypeId {
650         let enum_type_id = self.get_unique_type_id_of_type(cx, enum_type);
651         let enum_variant_type_id = format!("{}::{}",
652                                            &self.get_unique_type_id_as_string(enum_type_id)[],
653                                            variant_name);
654         let interner_key = self.unique_id_interner.intern(Rc::new(enum_variant_type_id));
655         UniqueTypeId(interner_key)
656     }
657 }
658
659 // Returns from the enclosing function if the type metadata with the given
660 // unique id can be found in the type map
661 macro_rules! return_if_metadata_created_in_meantime {
662     ($cx: expr, $unique_type_id: expr) => (
663         match debug_context($cx).type_map
664                                 .borrow()
665                                 .find_metadata_for_unique_id($unique_type_id) {
666             Some(metadata) => return MetadataCreationResult::new(metadata, true),
667             None => { /* proceed normally */ }
668         };
669     )
670 }
671
672
673 /// A context object for maintaining all state needed by the debuginfo module.
674 pub struct CrateDebugContext<'tcx> {
675     llcontext: ContextRef,
676     builder: DIBuilderRef,
677     current_debug_location: Cell<DebugLocation>,
678     created_files: RefCell<FnvHashMap<String, DIFile>>,
679     created_enum_disr_types: RefCell<DefIdMap<DIType>>,
680
681     type_map: RefCell<TypeMap<'tcx>>,
682     namespace_map: RefCell<FnvHashMap<Vec<ast::Name>, Rc<NamespaceTreeNode>>>,
683
684     // This collection is used to assert that composite types (structs, enums,
685     // ...) have their members only set once:
686     composite_types_completed: RefCell<FnvHashSet<DIType>>,
687 }
688
689 impl<'tcx> CrateDebugContext<'tcx> {
690     pub fn new(llmod: ModuleRef) -> CrateDebugContext<'tcx> {
691         debug!("CrateDebugContext::new");
692         let builder = unsafe { llvm::LLVMDIBuilderCreate(llmod) };
693         // DIBuilder inherits context from the module, so we'd better use the same one
694         let llcontext = unsafe { llvm::LLVMGetModuleContext(llmod) };
695         return CrateDebugContext {
696             llcontext: llcontext,
697             builder: builder,
698             current_debug_location: Cell::new(UnknownLocation),
699             created_files: RefCell::new(FnvHashMap::new()),
700             created_enum_disr_types: RefCell::new(DefIdMap::new()),
701             type_map: RefCell::new(TypeMap::new()),
702             namespace_map: RefCell::new(FnvHashMap::new()),
703             composite_types_completed: RefCell::new(FnvHashSet::new()),
704         };
705     }
706 }
707
708 pub enum FunctionDebugContext {
709     RegularContext(Box<FunctionDebugContextData>),
710     DebugInfoDisabled,
711     FunctionWithoutDebugInfo,
712 }
713
714 impl FunctionDebugContext {
715     fn get_ref<'a>(&'a self,
716                    cx: &CrateContext,
717                    span: Span)
718                    -> &'a FunctionDebugContextData {
719         match *self {
720             FunctionDebugContext::RegularContext(box ref data) => data,
721             FunctionDebugContext::DebugInfoDisabled => {
722                 cx.sess().span_bug(span,
723                                    FunctionDebugContext::debuginfo_disabled_message());
724             }
725             FunctionDebugContext::FunctionWithoutDebugInfo => {
726                 cx.sess().span_bug(span,
727                                    FunctionDebugContext::should_be_ignored_message());
728             }
729         }
730     }
731
732     fn debuginfo_disabled_message() -> &'static str {
733         "debuginfo: Error trying to access FunctionDebugContext although debug info is disabled!"
734     }
735
736     fn should_be_ignored_message() -> &'static str {
737         "debuginfo: Error trying to access FunctionDebugContext for function that should be \
738          ignored by debug info!"
739     }
740 }
741
742 struct FunctionDebugContextData {
743     scope_map: RefCell<NodeMap<DIScope>>,
744     fn_metadata: DISubprogram,
745     argument_counter: Cell<uint>,
746     source_locations_enabled: Cell<bool>,
747 }
748
749 enum VariableAccess<'a> {
750     // The llptr given is an alloca containing the variable's value
751     DirectVariable { alloca: ValueRef },
752     // The llptr given is an alloca containing the start of some pointer chain
753     // leading to the variable's content.
754     IndirectVariable { alloca: ValueRef, address_operations: &'a [ValueRef] }
755 }
756
757 enum VariableKind {
758     ArgumentVariable(uint /*index*/),
759     LocalVariable,
760     CapturedVariable,
761 }
762
763 /// Create any deferred debug metadata nodes
764 pub fn finalize(cx: &CrateContext) {
765     if cx.dbg_cx().is_none() {
766         return;
767     }
768
769     debug!("finalize");
770     let _ = compile_unit_metadata(cx);
771
772     if needs_gdb_debug_scripts_section(cx) {
773         // Add a .debug_gdb_scripts section to this compile-unit. This will
774         // cause GDB to try and load the gdb_load_rust_pretty_printers.py file,
775         // which activates the Rust pretty printers for binary this section is
776         // contained in.
777         get_or_insert_gdb_debug_scripts_section_global(cx);
778     }
779
780     unsafe {
781         llvm::LLVMDIBuilderFinalize(DIB(cx));
782         llvm::LLVMDIBuilderDispose(DIB(cx));
783         // Debuginfo generation in LLVM by default uses a higher
784         // version of dwarf than OS X currently understands. We can
785         // instruct LLVM to emit an older version of dwarf, however,
786         // for OS X to understand. For more info see #11352
787         // This can be overridden using --llvm-opts -dwarf-version,N.
788         if cx.sess().target.target.options.is_like_osx {
789             llvm::LLVMRustAddModuleFlag(cx.llmod(),
790                                         "Dwarf Version\0".as_ptr() as *const _,
791                                         2)
792         }
793
794         // Prevent bitcode readers from deleting the debug info.
795         let ptr = "Debug Info Version\0".as_ptr();
796         llvm::LLVMRustAddModuleFlag(cx.llmod(), ptr as *const _,
797                                     llvm::LLVMRustDebugMetadataVersion);
798     };
799 }
800
801 /// Creates debug information for the given global variable.
802 ///
803 /// Adds the created metadata nodes directly to the crate's IR.
804 pub fn create_global_var_metadata(cx: &CrateContext,
805                                   node_id: ast::NodeId,
806                                   global: ValueRef) {
807     if cx.dbg_cx().is_none() {
808         return;
809     }
810
811     // Don't create debuginfo for globals inlined from other crates. The other
812     // crate should already contain debuginfo for it. More importantly, the
813     // global might not even exist in un-inlined form anywhere which would lead
814     // to a linker errors.
815     if cx.external_srcs().borrow().contains_key(&node_id) {
816         return;
817     }
818
819     let var_item = cx.tcx().map.get(node_id);
820
821     let (ident, span) = match var_item {
822         ast_map::NodeItem(item) => {
823             match item.node {
824                 ast::ItemStatic(..) => (item.ident, item.span),
825                 ast::ItemConst(..) => (item.ident, item.span),
826                 _ => {
827                     cx.sess()
828                       .span_bug(item.span,
829                                 &format!("debuginfo::\
830                                          create_global_var_metadata() -
831                                          Captured var-id refers to \
832                                          unexpected ast_item variant: {:?}",
833                                         var_item)[])
834                 }
835             }
836         },
837         _ => cx.sess().bug(&format!("debuginfo::create_global_var_metadata() \
838                                     - Captured var-id refers to unexpected \
839                                     ast_map variant: {:?}",
840                                    var_item)[])
841     };
842
843     let (file_metadata, line_number) = if span != codemap::DUMMY_SP {
844         let loc = span_start(cx, span);
845         (file_metadata(cx, &loc.file.name[]), loc.line as c_uint)
846     } else {
847         (UNKNOWN_FILE_METADATA, UNKNOWN_LINE_NUMBER)
848     };
849
850     let is_local_to_unit = is_node_local_to_unit(cx, node_id);
851     let variable_type = ty::node_id_to_type(cx.tcx(), node_id);
852     let type_metadata = type_metadata(cx, variable_type, span);
853     let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id));
854     let var_name = token::get_ident(ident).get().to_string();
855     let linkage_name =
856         namespace_node.mangled_name_of_contained_item(&var_name[]);
857     let var_scope = namespace_node.scope;
858
859     let var_name = CString::from_slice(var_name.as_bytes());
860     let linkage_name = CString::from_slice(linkage_name.as_bytes());
861     unsafe {
862         llvm::LLVMDIBuilderCreateStaticVariable(DIB(cx),
863                                                 var_scope,
864                                                 var_name.as_ptr(),
865                                                 linkage_name.as_ptr(),
866                                                 file_metadata,
867                                                 line_number,
868                                                 type_metadata,
869                                                 is_local_to_unit,
870                                                 global,
871                                                 ptr::null_mut());
872     }
873 }
874
875 /// Creates debug information for the given local variable.
876 ///
877 /// This function assumes that there's a datum for each pattern component of the
878 /// local in `bcx.fcx.lllocals`.
879 /// Adds the created metadata nodes directly to the crate's IR.
880 pub fn create_local_var_metadata(bcx: Block, local: &ast::Local) {
881     if bcx.unreachable.get() || fn_should_be_ignored(bcx.fcx) {
882         return;
883     }
884
885     let cx = bcx.ccx();
886     let def_map = &cx.tcx().def_map;
887     let locals = bcx.fcx.lllocals.borrow();
888
889     pat_util::pat_bindings(def_map, &*local.pat, |_, node_id, span, var_ident| {
890         let datum = match locals.get(&node_id) {
891             Some(datum) => datum,
892             None => {
893                 bcx.sess().span_bug(span,
894                     &format!("no entry in lllocals table for {}",
895                             node_id)[]);
896             }
897         };
898
899         if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
900             cx.sess().span_bug(span, "debuginfo::create_local_var_metadata() - \
901                                       Referenced variable location is not an alloca!");
902         }
903
904         let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
905
906         declare_local(bcx,
907                       var_ident.node,
908                       datum.ty,
909                       scope_metadata,
910                       DirectVariable { alloca: datum.val },
911                       LocalVariable,
912                       span);
913     })
914 }
915
916 /// Creates debug information for a variable captured in a closure.
917 ///
918 /// Adds the created metadata nodes directly to the crate's IR.
919 pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
920                                                 node_id: ast::NodeId,
921                                                 env_pointer: ValueRef,
922                                                 env_index: uint,
923                                                 captured_by_ref: bool,
924                                                 span: Span) {
925     if bcx.unreachable.get() || fn_should_be_ignored(bcx.fcx) {
926         return;
927     }
928
929     let cx = bcx.ccx();
930
931     let ast_item = cx.tcx().map.find(node_id);
932
933     let variable_ident = match ast_item {
934         None => {
935             cx.sess().span_bug(span, "debuginfo::create_captured_var_metadata: node not found");
936         }
937         Some(ast_map::NodeLocal(pat)) | Some(ast_map::NodeArg(pat)) => {
938             match pat.node {
939                 ast::PatIdent(_, ref path1, _) => {
940                     path1.node
941                 }
942                 _ => {
943                     cx.sess()
944                       .span_bug(span,
945                                 &format!(
946                                 "debuginfo::create_captured_var_metadata() - \
947                                  Captured var-id refers to unexpected \
948                                  ast_map variant: {:?}",
949                                  ast_item)[]);
950                 }
951             }
952         }
953         _ => {
954             cx.sess()
955               .span_bug(span,
956                         &format!("debuginfo::create_captured_var_metadata() - \
957                                  Captured var-id refers to unexpected \
958                                  ast_map variant: {:?}",
959                                 ast_item)[]);
960         }
961     };
962
963     let variable_type = node_id_type(bcx, node_id);
964     let scope_metadata = bcx.fcx.debug_context.get_ref(cx, span).fn_metadata;
965
966     // env_pointer is the alloca containing the pointer to the environment,
967     // so it's type is **EnvironmentType. In order to find out the type of
968     // the environment we have to "dereference" two times.
969     let llvm_env_data_type = val_ty(env_pointer).element_type().element_type();
970     let byte_offset_of_var_in_env = machine::llelement_offset(cx,
971                                                               llvm_env_data_type,
972                                                               env_index);
973
974     let address_operations = unsafe {
975         [llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref()),
976          llvm::LLVMDIBuilderCreateOpPlus(Type::i64(cx).to_ref()),
977          C_i64(cx, byte_offset_of_var_in_env as i64),
978          llvm::LLVMDIBuilderCreateOpDeref(Type::i64(cx).to_ref())]
979     };
980
981     let address_op_count = if captured_by_ref {
982         address_operations.len()
983     } else {
984         address_operations.len() - 1
985     };
986
987     let variable_access = IndirectVariable {
988         alloca: env_pointer,
989         address_operations: &address_operations[..address_op_count]
990     };
991
992     declare_local(bcx,
993                   variable_ident,
994                   variable_type,
995                   scope_metadata,
996                   variable_access,
997                   CapturedVariable,
998                   span);
999 }
1000
1001 /// Creates debug information for a local variable introduced in the head of a
1002 /// match-statement arm.
1003 ///
1004 /// Adds the created metadata nodes directly to the crate's IR.
1005 pub fn create_match_binding_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1006                                                  variable_ident: ast::Ident,
1007                                                  binding: BindingInfo<'tcx>) {
1008     if bcx.unreachable.get() || fn_should_be_ignored(bcx.fcx) {
1009         return;
1010     }
1011
1012     let scope_metadata = scope_metadata(bcx.fcx, binding.id, binding.span);
1013     let aops = unsafe {
1014         [llvm::LLVMDIBuilderCreateOpDeref(bcx.ccx().int_type().to_ref())]
1015     };
1016     // Regardless of the actual type (`T`) we're always passed the stack slot (alloca)
1017     // for the binding. For ByRef bindings that's a `T*` but for ByMove bindings we
1018     // actually have `T**`. So to get the actual variable we need to dereference once
1019     // more. For ByCopy we just use the stack slot we created for the binding.
1020     let var_access = match binding.trmode {
1021         TrByCopy(llbinding) => DirectVariable {
1022             alloca: llbinding
1023         },
1024         TrByMove => IndirectVariable {
1025             alloca: binding.llmatch,
1026             address_operations: &aops
1027         },
1028         TrByRef => DirectVariable {
1029             alloca: binding.llmatch
1030         }
1031     };
1032
1033     declare_local(bcx,
1034                   variable_ident,
1035                   binding.ty,
1036                   scope_metadata,
1037                   var_access,
1038                   LocalVariable,
1039                   binding.span);
1040 }
1041
1042 /// Creates debug information for the given function argument.
1043 ///
1044 /// This function assumes that there's a datum for each pattern component of the
1045 /// argument in `bcx.fcx.lllocals`.
1046 /// Adds the created metadata nodes directly to the crate's IR.
1047 pub fn create_argument_metadata(bcx: Block, arg: &ast::Arg) {
1048     if bcx.unreachable.get() || fn_should_be_ignored(bcx.fcx) {
1049         return;
1050     }
1051
1052     let def_map = &bcx.tcx().def_map;
1053     let scope_metadata = bcx
1054                          .fcx
1055                          .debug_context
1056                          .get_ref(bcx.ccx(), arg.pat.span)
1057                          .fn_metadata;
1058     let locals = bcx.fcx.lllocals.borrow();
1059
1060     pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, span, var_ident| {
1061         let datum = match locals.get(&node_id) {
1062             Some(v) => v,
1063             None => {
1064                 bcx.sess().span_bug(span,
1065                     &format!("no entry in lllocals table for {}",
1066                             node_id)[]);
1067             }
1068         };
1069
1070         if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
1071             bcx.sess().span_bug(span, "debuginfo::create_argument_metadata() - \
1072                                        Referenced variable location is not an alloca!");
1073         }
1074
1075         let argument_index = {
1076             let counter = &bcx
1077                           .fcx
1078                           .debug_context
1079                           .get_ref(bcx.ccx(), span)
1080                           .argument_counter;
1081             let argument_index = counter.get();
1082             counter.set(argument_index + 1);
1083             argument_index
1084         };
1085
1086         declare_local(bcx,
1087                       var_ident.node,
1088                       datum.ty,
1089                       scope_metadata,
1090                       DirectVariable { alloca: datum.val },
1091                       ArgumentVariable(argument_index),
1092                       span);
1093     })
1094 }
1095
1096 /// Creates debug information for the given for-loop variable.
1097 ///
1098 /// This function assumes that there's a datum for each pattern component of the
1099 /// loop variable in `bcx.fcx.lllocals`.
1100 /// Adds the created metadata nodes directly to the crate's IR.
1101 pub fn create_for_loop_var_metadata(bcx: Block, pat: &ast::Pat) {
1102     if bcx.unreachable.get() || fn_should_be_ignored(bcx.fcx) {
1103         return;
1104     }
1105
1106     let def_map = &bcx.tcx().def_map;
1107     let locals = bcx.fcx.lllocals.borrow();
1108
1109     pat_util::pat_bindings(def_map, pat, |_, node_id, span, var_ident| {
1110         let datum = match locals.get(&node_id) {
1111             Some(datum) => datum,
1112             None => {
1113                 bcx.sess().span_bug(span,
1114                     format!("no entry in lllocals table for {}",
1115                             node_id).as_slice());
1116             }
1117         };
1118
1119         if unsafe { llvm::LLVMIsAAllocaInst(datum.val) } == ptr::null_mut() {
1120             bcx.sess().span_bug(span, "debuginfo::create_for_loop_var_metadata() - \
1121                                        Referenced variable location is not an alloca!");
1122         }
1123
1124         let scope_metadata = scope_metadata(bcx.fcx, node_id, span);
1125
1126         declare_local(bcx,
1127                       var_ident.node,
1128                       datum.ty,
1129                       scope_metadata,
1130                       DirectVariable { alloca: datum.val },
1131                       LocalVariable,
1132                       span);
1133     })
1134 }
1135
1136 pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1137                                                     node_id: ast::NodeId,
1138                                                     node_span: Span,
1139                                                     is_block: bool)
1140                                                  -> NodeInfo {
1141     // A debug location needs two things:
1142     // (1) A span (of which only the beginning will actually be used)
1143     // (2) An AST node-id which will be used to look up the lexical scope
1144     //     for the location in the functions scope-map
1145     //
1146     // This function will calculate the debug location for compiler-generated
1147     // cleanup calls that are executed when control-flow leaves the
1148     // scope identified by `node_id`.
1149     //
1150     // For everything but block-like things we can simply take id and span of
1151     // the given expression, meaning that from a debugger's view cleanup code is
1152     // executed at the same source location as the statement/expr itself.
1153     //
1154     // Blocks are a special case. Here we want the cleanup to be linked to the
1155     // closing curly brace of the block. The *scope* the cleanup is executed in
1156     // is up to debate: It could either still be *within* the block being
1157     // cleaned up, meaning that locals from the block are still visible in the
1158     // debugger.
1159     // Or it could be in the scope that the block is contained in, so any locals
1160     // from within the block are already considered out-of-scope and thus not
1161     // accessible in the debugger anymore.
1162     //
1163     // The current implementation opts for the second option: cleanup of a block
1164     // already happens in the parent scope of the block. The main reason for
1165     // this decision is that scoping becomes controlflow dependent when variable
1166     // shadowing is involved and it's impossible to decide statically which
1167     // scope is actually left when the cleanup code is executed.
1168     // In practice it shouldn't make much of a difference.
1169
1170     let mut cleanup_span = node_span;
1171
1172     if is_block {
1173         // Not all blocks actually have curly braces (e.g. simple closure
1174         // bodies), in which case we also just want to return the span of the
1175         // whole expression.
1176         let code_snippet = cx.sess().codemap().span_to_snippet(node_span);
1177         if let Some(code_snippet) = code_snippet {
1178             let bytes = code_snippet.as_bytes();
1179
1180             if bytes.len() > 0 && &bytes[(bytes.len()-1)..] == b"}" {
1181                 cleanup_span = Span {
1182                     lo: node_span.hi - codemap::BytePos(1),
1183                     hi: node_span.hi,
1184                     expn_id: node_span.expn_id
1185                 };
1186             }
1187         }
1188     }
1189
1190     NodeInfo {
1191         id: node_id,
1192         span: cleanup_span
1193     }
1194 }
1195
1196 /// Sets the current debug location at the beginning of the span.
1197 ///
1198 /// Maps to a call to llvm::LLVMSetCurrentDebugLocation(...). The node_id
1199 /// parameter is used to reliably find the correct visibility scope for the code
1200 /// position.
1201 pub fn set_source_location(fcx: &FunctionContext,
1202                            node_id: ast::NodeId,
1203                            span: Span) {
1204     match fcx.debug_context {
1205         FunctionDebugContext::DebugInfoDisabled => return,
1206         FunctionDebugContext::FunctionWithoutDebugInfo => {
1207             set_debug_location(fcx.ccx, UnknownLocation);
1208             return;
1209         }
1210         FunctionDebugContext::RegularContext(box ref function_debug_context) => {
1211             let cx = fcx.ccx;
1212
1213             debug!("set_source_location: {}", cx.sess().codemap().span_to_string(span));
1214
1215             if function_debug_context.source_locations_enabled.get() {
1216                 let loc = span_start(cx, span);
1217                 let scope = scope_metadata(fcx, node_id, span);
1218
1219                 set_debug_location(cx, DebugLocation::new(scope,
1220                                                           loc.line,
1221                                                           loc.col.to_uint()));
1222             } else {
1223                 set_debug_location(cx, UnknownLocation);
1224             }
1225         }
1226     }
1227 }
1228
1229 /// Clears the current debug location.
1230 ///
1231 /// Instructions generated hereafter won't be assigned a source location.
1232 pub fn clear_source_location(fcx: &FunctionContext) {
1233     if fn_should_be_ignored(fcx) {
1234         return;
1235     }
1236
1237     set_debug_location(fcx.ccx, UnknownLocation);
1238 }
1239
1240 /// Enables emitting source locations for the given functions.
1241 ///
1242 /// Since we don't want source locations to be emitted for the function prelude,
1243 /// they are disabled when beginning to translate a new function. This functions
1244 /// switches source location emitting on and must therefore be called before the
1245 /// first real statement/expression of the function is translated.
1246 pub fn start_emitting_source_locations(fcx: &FunctionContext) {
1247     match fcx.debug_context {
1248         FunctionDebugContext::RegularContext(box ref data) => {
1249             data.source_locations_enabled.set(true)
1250         },
1251         _ => { /* safe to ignore */ }
1252     }
1253 }
1254
1255 /// Creates the function-specific debug context.
1256 ///
1257 /// Returns the FunctionDebugContext for the function which holds state needed
1258 /// for debug info creation. The function may also return another variant of the
1259 /// FunctionDebugContext enum which indicates why no debuginfo should be created
1260 /// for the function.
1261 pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1262                                                fn_ast_id: ast::NodeId,
1263                                                param_substs: &Substs<'tcx>,
1264                                                llfn: ValueRef) -> FunctionDebugContext {
1265     if cx.sess().opts.debuginfo == NoDebugInfo {
1266         return FunctionDebugContext::DebugInfoDisabled;
1267     }
1268
1269     // Clear the debug location so we don't assign them in the function prelude.
1270     // Do this here already, in case we do an early exit from this function.
1271     set_debug_location(cx, UnknownLocation);
1272
1273     if fn_ast_id == ast::DUMMY_NODE_ID {
1274         // This is a function not linked to any source location, so don't
1275         // generate debuginfo for it.
1276         return FunctionDebugContext::FunctionWithoutDebugInfo;
1277     }
1278
1279     let empty_generics = ast_util::empty_generics();
1280
1281     let fnitem = cx.tcx().map.get(fn_ast_id);
1282
1283     let (ident, fn_decl, generics, top_level_block, span, has_path) = match fnitem {
1284         ast_map::NodeItem(ref item) => {
1285             if contains_nodebug_attribute(item.attrs.as_slice()) {
1286                 return FunctionDebugContext::FunctionWithoutDebugInfo;
1287             }
1288
1289             match item.node {
1290                 ast::ItemFn(ref fn_decl, _, _, ref generics, ref top_level_block) => {
1291                     (item.ident, &**fn_decl, generics, &**top_level_block, item.span, true)
1292                 }
1293                 _ => {
1294                     cx.sess().span_bug(item.span,
1295                         "create_function_debug_context: item bound to non-function");
1296                 }
1297             }
1298         }
1299         ast_map::NodeImplItem(ref item) => {
1300             match **item {
1301                 ast::MethodImplItem(ref method) => {
1302                     if contains_nodebug_attribute(method.attrs.as_slice()) {
1303                         return FunctionDebugContext::FunctionWithoutDebugInfo;
1304                     }
1305
1306                     (method.pe_ident(),
1307                      method.pe_fn_decl(),
1308                      method.pe_generics(),
1309                      method.pe_body(),
1310                      method.span,
1311                      true)
1312                 }
1313                 ast::TypeImplItem(ref typedef) => {
1314                     cx.sess().span_bug(typedef.span,
1315                                        "create_function_debug_context() \
1316                                         called on associated type?!")
1317                 }
1318             }
1319         }
1320         ast_map::NodeExpr(ref expr) => {
1321             match expr.node {
1322                 ast::ExprClosure(_, _, ref fn_decl, ref top_level_block) => {
1323                     let name = format!("fn{}", token::gensym("fn"));
1324                     let name = token::str_to_ident(&name[]);
1325                     (name, &**fn_decl,
1326                         // This is not quite right. It should actually inherit
1327                         // the generics of the enclosing function.
1328                         &empty_generics,
1329                         &**top_level_block,
1330                         expr.span,
1331                         // Don't try to lookup the item path:
1332                         false)
1333                 }
1334                 _ => cx.sess().span_bug(expr.span,
1335                         "create_function_debug_context: expected an expr_fn_block here")
1336             }
1337         }
1338         ast_map::NodeTraitItem(ref trait_method) => {
1339             match **trait_method {
1340                 ast::ProvidedMethod(ref method) => {
1341                     if contains_nodebug_attribute(method.attrs.as_slice()) {
1342                         return FunctionDebugContext::FunctionWithoutDebugInfo;
1343                     }
1344
1345                     (method.pe_ident(),
1346                      method.pe_fn_decl(),
1347                      method.pe_generics(),
1348                      method.pe_body(),
1349                      method.span,
1350                      true)
1351                 }
1352                 _ => {
1353                     cx.sess()
1354                       .bug(&format!("create_function_debug_context: \
1355                                     unexpected sort of node: {:?}",
1356                                     fnitem)[])
1357                 }
1358             }
1359         }
1360         ast_map::NodeForeignItem(..) |
1361         ast_map::NodeVariant(..) |
1362         ast_map::NodeStructCtor(..) => {
1363             return FunctionDebugContext::FunctionWithoutDebugInfo;
1364         }
1365         _ => cx.sess().bug(&format!("create_function_debug_context: \
1366                                     unexpected sort of node: {:?}",
1367                                    fnitem)[])
1368     };
1369
1370     // This can be the case for functions inlined from another crate
1371     if span == codemap::DUMMY_SP {
1372         return FunctionDebugContext::FunctionWithoutDebugInfo;
1373     }
1374
1375     let loc = span_start(cx, span);
1376     let file_metadata = file_metadata(cx, &loc.file.name[]);
1377
1378     let function_type_metadata = unsafe {
1379         let fn_signature = get_function_signature(cx,
1380                                                   fn_ast_id,
1381                                                   &*fn_decl,
1382                                                   param_substs,
1383                                                   span);
1384         llvm::LLVMDIBuilderCreateSubroutineType(DIB(cx), file_metadata, fn_signature)
1385     };
1386
1387     // Get_template_parameters() will append a `<...>` clause to the function
1388     // name if necessary.
1389     let mut function_name = String::from_str(token::get_ident(ident).get());
1390     let template_parameters = get_template_parameters(cx,
1391                                                       generics,
1392                                                       param_substs,
1393                                                       file_metadata,
1394                                                       &mut function_name);
1395
1396     // There is no ast_map::Path for ast::ExprClosure-type functions. For now,
1397     // just don't put them into a namespace. In the future this could be improved
1398     // somehow (storing a path in the ast_map, or construct a path using the
1399     // enclosing function).
1400     let (linkage_name, containing_scope) = if has_path {
1401         let namespace_node = namespace_for_item(cx, ast_util::local_def(fn_ast_id));
1402         let linkage_name = namespace_node.mangled_name_of_contained_item(
1403             &function_name[]);
1404         let containing_scope = namespace_node.scope;
1405         (linkage_name, containing_scope)
1406     } else {
1407         (function_name.clone(), file_metadata)
1408     };
1409
1410     // Clang sets this parameter to the opening brace of the function's block,
1411     // so let's do this too.
1412     let scope_line = span_start(cx, top_level_block.span).line;
1413
1414     let is_local_to_unit = is_node_local_to_unit(cx, fn_ast_id);
1415
1416     let function_name = CString::from_slice(function_name.as_bytes());
1417     let linkage_name = CString::from_slice(linkage_name.as_bytes());
1418     let fn_metadata = unsafe {
1419         llvm::LLVMDIBuilderCreateFunction(
1420             DIB(cx),
1421             containing_scope,
1422             function_name.as_ptr(),
1423             linkage_name.as_ptr(),
1424             file_metadata,
1425             loc.line as c_uint,
1426             function_type_metadata,
1427             is_local_to_unit,
1428             true,
1429             scope_line as c_uint,
1430             FlagPrototyped as c_uint,
1431             cx.sess().opts.optimize != config::No,
1432             llfn,
1433             template_parameters,
1434             ptr::null_mut())
1435     };
1436
1437     let scope_map = create_scope_map(cx,
1438                                      fn_decl.inputs.as_slice(),
1439                                      &*top_level_block,
1440                                      fn_metadata,
1441                                      fn_ast_id);
1442
1443     // Initialize fn debug context (including scope map and namespace map)
1444     let fn_debug_context = box FunctionDebugContextData {
1445         scope_map: RefCell::new(scope_map),
1446         fn_metadata: fn_metadata,
1447         argument_counter: Cell::new(1),
1448         source_locations_enabled: Cell::new(false),
1449     };
1450
1451
1452
1453     return FunctionDebugContext::RegularContext(fn_debug_context);
1454
1455     fn get_function_signature<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1456                                         fn_ast_id: ast::NodeId,
1457                                         fn_decl: &ast::FnDecl,
1458                                         param_substs: &Substs<'tcx>,
1459                                         error_reporting_span: Span) -> DIArray {
1460         if cx.sess().opts.debuginfo == LimitedDebugInfo {
1461             return create_DIArray(DIB(cx), &[]);
1462         }
1463
1464         let mut signature = Vec::with_capacity(fn_decl.inputs.len() + 1);
1465
1466         // Return type -- llvm::DIBuilder wants this at index 0
1467         match fn_decl.output {
1468             ast::Return(ref ret_ty) if ret_ty.node == ast::TyTup(vec![]) =>
1469                 signature.push(ptr::null_mut()),
1470             _ => {
1471                 assert_type_for_node_id(cx, fn_ast_id, error_reporting_span);
1472
1473                 let return_type = ty::node_id_to_type(cx.tcx(), fn_ast_id);
1474                 let return_type = monomorphize::apply_param_substs(cx.tcx(),
1475                                                                    param_substs,
1476                                                                    &return_type);
1477                 signature.push(type_metadata(cx, return_type, codemap::DUMMY_SP));
1478             }
1479         }
1480
1481         // Arguments types
1482         for arg in fn_decl.inputs.iter() {
1483             assert_type_for_node_id(cx, arg.pat.id, arg.pat.span);
1484             let arg_type = ty::node_id_to_type(cx.tcx(), arg.pat.id);
1485             let arg_type = monomorphize::apply_param_substs(cx.tcx(),
1486                                                             param_substs,
1487                                                             &arg_type);
1488             signature.push(type_metadata(cx, arg_type, codemap::DUMMY_SP));
1489         }
1490
1491         return create_DIArray(DIB(cx), &signature[]);
1492     }
1493
1494     fn get_template_parameters<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1495                                          generics: &ast::Generics,
1496                                          param_substs: &Substs<'tcx>,
1497                                          file_metadata: DIFile,
1498                                          name_to_append_suffix_to: &mut String)
1499                                          -> DIArray
1500     {
1501         let self_type = param_substs.self_ty();
1502         let self_type = monomorphize::normalize_associated_type(cx.tcx(), &self_type);
1503
1504         // Only true for static default methods:
1505         let has_self_type = self_type.is_some();
1506
1507         if !generics.is_type_parameterized() && !has_self_type {
1508             return create_DIArray(DIB(cx), &[]);
1509         }
1510
1511         name_to_append_suffix_to.push('<');
1512
1513         // The list to be filled with template parameters:
1514         let mut template_params: Vec<DIDescriptor> =
1515             Vec::with_capacity(generics.ty_params.len() + 1);
1516
1517         // Handle self type
1518         if has_self_type {
1519             let actual_self_type = self_type.unwrap();
1520             // Add self type name to <...> clause of function name
1521             let actual_self_type_name = compute_debuginfo_type_name(
1522                 cx,
1523                 actual_self_type,
1524                 true);
1525
1526             name_to_append_suffix_to.push_str(&actual_self_type_name[]);
1527
1528             if generics.is_type_parameterized() {
1529                 name_to_append_suffix_to.push_str(",");
1530             }
1531
1532             // Only create type information if full debuginfo is enabled
1533             if cx.sess().opts.debuginfo == FullDebugInfo {
1534                 let actual_self_type_metadata = type_metadata(cx,
1535                                                               actual_self_type,
1536                                                               codemap::DUMMY_SP);
1537
1538                 let ident = special_idents::type_self;
1539
1540                 let ident = token::get_ident(ident);
1541                 let name = CString::from_slice(ident.get().as_bytes());
1542                 let param_metadata = unsafe {
1543                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
1544                         DIB(cx),
1545                         file_metadata,
1546                         name.as_ptr(),
1547                         actual_self_type_metadata,
1548                         ptr::null_mut(),
1549                         0,
1550                         0)
1551                 };
1552
1553                 template_params.push(param_metadata);
1554             }
1555         }
1556
1557         // Handle other generic parameters
1558         let actual_types = param_substs.types.get_slice(subst::FnSpace);
1559         for (index, &ast::TyParam{ ident, .. }) in generics.ty_params.iter().enumerate() {
1560             let actual_type = actual_types[index];
1561             // Add actual type name to <...> clause of function name
1562             let actual_type_name = compute_debuginfo_type_name(cx,
1563                                                                actual_type,
1564                                                                true);
1565             name_to_append_suffix_to.push_str(&actual_type_name[]);
1566
1567             if index != generics.ty_params.len() - 1 {
1568                 name_to_append_suffix_to.push_str(",");
1569             }
1570
1571             // Again, only create type information if full debuginfo is enabled
1572             if cx.sess().opts.debuginfo == FullDebugInfo {
1573                 let actual_type_metadata = type_metadata(cx, actual_type, codemap::DUMMY_SP);
1574                 let ident = token::get_ident(ident);
1575                 let name = CString::from_slice(ident.get().as_bytes());
1576                 let param_metadata = unsafe {
1577                     llvm::LLVMDIBuilderCreateTemplateTypeParameter(
1578                         DIB(cx),
1579                         file_metadata,
1580                         name.as_ptr(),
1581                         actual_type_metadata,
1582                         ptr::null_mut(),
1583                         0,
1584                         0)
1585                 };
1586                 template_params.push(param_metadata);
1587             }
1588         }
1589
1590         name_to_append_suffix_to.push('>');
1591
1592         return create_DIArray(DIB(cx), &template_params[]);
1593     }
1594 }
1595
1596 //=-----------------------------------------------------------------------------
1597 // Module-Internal debug info creation functions
1598 //=-----------------------------------------------------------------------------
1599
1600 fn is_node_local_to_unit(cx: &CrateContext, node_id: ast::NodeId) -> bool
1601 {
1602     // The is_local_to_unit flag indicates whether a function is local to the
1603     // current compilation unit (i.e. if it is *static* in the C-sense). The
1604     // *reachable* set should provide a good approximation of this, as it
1605     // contains everything that might leak out of the current crate (by being
1606     // externally visible or by being inlined into something externally visible).
1607     // It might better to use the `exported_items` set from `driver::CrateAnalysis`
1608     // in the future, but (atm) this set is not available in the translation pass.
1609     !cx.reachable().contains(&node_id)
1610 }
1611
1612 #[allow(non_snake_case)]
1613 fn create_DIArray(builder: DIBuilderRef, arr: &[DIDescriptor]) -> DIArray {
1614     return unsafe {
1615         llvm::LLVMDIBuilderGetOrCreateArray(builder, arr.as_ptr(), arr.len() as u32)
1616     };
1617 }
1618
1619 fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor {
1620     let work_dir = &cx.sess().working_dir;
1621     let compile_unit_name = match cx.sess().local_crate_source_file {
1622         None => fallback_path(cx),
1623         Some(ref abs_path) => {
1624             if abs_path.is_relative() {
1625                 cx.sess().warn("debuginfo: Invalid path to crate's local root source file!");
1626                 fallback_path(cx)
1627             } else {
1628                 match abs_path.path_relative_from(work_dir) {
1629                     Some(ref p) if p.is_relative() => {
1630                         // prepend "./" if necessary
1631                         let dotdot = b"..";
1632                         let prefix: &[u8] = &[dotdot[0], ::std::path::SEP_BYTE];
1633                         let mut path_bytes = p.as_vec().to_vec();
1634
1635                         if path_bytes.slice_to(2) != prefix &&
1636                            path_bytes.slice_to(2) != dotdot {
1637                             path_bytes.insert(0, prefix[0]);
1638                             path_bytes.insert(1, prefix[1]);
1639                         }
1640
1641                         CString::from_vec(path_bytes)
1642                     }
1643                     _ => fallback_path(cx)
1644                 }
1645             }
1646         }
1647     };
1648
1649     debug!("compile_unit_metadata: {:?}", compile_unit_name);
1650     let producer = format!("rustc version {}",
1651                            (option_env!("CFG_VERSION")).expect("CFG_VERSION"));
1652
1653     let compile_unit_name = compile_unit_name.as_ptr();
1654     let work_dir = CString::from_slice(work_dir.as_vec());
1655     let producer = CString::from_slice(producer.as_bytes());
1656     let flags = "\0";
1657     let split_name = "\0";
1658     return unsafe {
1659         llvm::LLVMDIBuilderCreateCompileUnit(
1660             debug_context(cx).builder,
1661             DW_LANG_RUST,
1662             compile_unit_name,
1663             work_dir.as_ptr(),
1664             producer.as_ptr(),
1665             cx.sess().opts.optimize != config::No,
1666             flags.as_ptr() as *const _,
1667             0,
1668             split_name.as_ptr() as *const _)
1669     };
1670
1671     fn fallback_path(cx: &CrateContext) -> CString {
1672         CString::from_slice(cx.link_meta().crate_name.as_bytes())
1673     }
1674 }
1675
1676 fn declare_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1677                              variable_ident: ast::Ident,
1678                              variable_type: Ty<'tcx>,
1679                              scope_metadata: DIScope,
1680                              variable_access: VariableAccess,
1681                              variable_kind: VariableKind,
1682                              span: Span) {
1683     let cx: &CrateContext = bcx.ccx();
1684
1685     let filename = span_start(cx, span).file.name.clone();
1686     let file_metadata = file_metadata(cx, &filename[]);
1687
1688     let name = token::get_ident(variable_ident);
1689     let loc = span_start(cx, span);
1690     let type_metadata = type_metadata(cx, variable_type, span);
1691
1692     let (argument_index, dwarf_tag) = match variable_kind {
1693         ArgumentVariable(index) => (index as c_uint, DW_TAG_arg_variable),
1694         LocalVariable    |
1695         CapturedVariable => (0, DW_TAG_auto_variable)
1696     };
1697
1698     let name = CString::from_slice(name.get().as_bytes());
1699     let (var_alloca, var_metadata) = match variable_access {
1700         DirectVariable { alloca } => (
1701             alloca,
1702             unsafe {
1703                 llvm::LLVMDIBuilderCreateLocalVariable(
1704                     DIB(cx),
1705                     dwarf_tag,
1706                     scope_metadata,
1707                     name.as_ptr(),
1708                     file_metadata,
1709                     loc.line as c_uint,
1710                     type_metadata,
1711                     cx.sess().opts.optimize != config::No,
1712                     0,
1713                     argument_index)
1714             }
1715         ),
1716         IndirectVariable { alloca, address_operations } => (
1717             alloca,
1718             unsafe {
1719                 llvm::LLVMDIBuilderCreateComplexVariable(
1720                     DIB(cx),
1721                     dwarf_tag,
1722                     scope_metadata,
1723                     name.as_ptr(),
1724                     file_metadata,
1725                     loc.line as c_uint,
1726                     type_metadata,
1727                     address_operations.as_ptr(),
1728                     address_operations.len() as c_uint,
1729                     argument_index)
1730             }
1731         )
1732     };
1733
1734     set_debug_location(cx, DebugLocation::new(scope_metadata,
1735                                               loc.line,
1736                                               loc.col.to_uint()));
1737     unsafe {
1738         let instr = llvm::LLVMDIBuilderInsertDeclareAtEnd(
1739             DIB(cx),
1740             var_alloca,
1741             var_metadata,
1742             bcx.llbb);
1743
1744         llvm::LLVMSetInstDebugLocation(trans::build::B(bcx).llbuilder, instr);
1745     }
1746
1747     match variable_kind {
1748         ArgumentVariable(_) | CapturedVariable => {
1749             assert!(!bcx.fcx
1750                         .debug_context
1751                         .get_ref(cx, span)
1752                         .source_locations_enabled
1753                         .get());
1754             set_debug_location(cx, UnknownLocation);
1755         }
1756         _ => { /* nothing to do */ }
1757     }
1758 }
1759
1760 fn file_metadata(cx: &CrateContext, full_path: &str) -> DIFile {
1761     match debug_context(cx).created_files.borrow().get(full_path) {
1762         Some(file_metadata) => return *file_metadata,
1763         None => ()
1764     }
1765
1766     debug!("file_metadata: {}", full_path);
1767
1768     // FIXME (#9639): This needs to handle non-utf8 paths
1769     let work_dir = cx.sess().working_dir.as_str().unwrap();
1770     let file_name =
1771         if full_path.starts_with(work_dir) {
1772             &full_path[(work_dir.len() + 1u)..full_path.len()]
1773         } else {
1774             full_path
1775         };
1776
1777     let file_name = CString::from_slice(file_name.as_bytes());
1778     let work_dir = CString::from_slice(work_dir.as_bytes());
1779     let file_metadata = unsafe {
1780         llvm::LLVMDIBuilderCreateFile(DIB(cx), file_name.as_ptr(),
1781                                       work_dir.as_ptr())
1782     };
1783
1784     let mut created_files = debug_context(cx).created_files.borrow_mut();
1785     created_files.insert(full_path.to_string(), file_metadata);
1786     return file_metadata;
1787 }
1788
1789 /// Finds the scope metadata node for the given AST node.
1790 fn scope_metadata(fcx: &FunctionContext,
1791                   node_id: ast::NodeId,
1792                   error_reporting_span: Span)
1793                -> DIScope {
1794     let scope_map = &fcx.debug_context
1795                         .get_ref(fcx.ccx, error_reporting_span)
1796                         .scope_map;
1797     match scope_map.borrow().get(&node_id).cloned() {
1798         Some(scope_metadata) => scope_metadata,
1799         None => {
1800             let node = fcx.ccx.tcx().map.get(node_id);
1801
1802             fcx.ccx.sess().span_bug(error_reporting_span,
1803                 &format!("debuginfo: Could not find scope info for node {:?}",
1804                         node)[]);
1805         }
1806     }
1807 }
1808
1809 fn diverging_type_metadata(cx: &CrateContext) -> DIType {
1810     unsafe {
1811         llvm::LLVMDIBuilderCreateBasicType(
1812             DIB(cx),
1813             "!\0".as_ptr() as *const _,
1814             bytes_to_bits(0),
1815             bytes_to_bits(0),
1816             DW_ATE_unsigned)
1817     }
1818 }
1819
1820 fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1821                                  t: Ty<'tcx>) -> DIType {
1822
1823     debug!("basic_type_metadata: {:?}", t);
1824
1825     let (name, encoding) = match t.sty {
1826         ty::ty_tup(ref elements) if elements.is_empty() =>
1827             ("()".to_string(), DW_ATE_unsigned),
1828         ty::ty_bool => ("bool".to_string(), DW_ATE_boolean),
1829         ty::ty_char => ("char".to_string(), DW_ATE_unsigned_char),
1830         ty::ty_int(int_ty) => match int_ty {
1831             ast::TyIs(_) => ("isize".to_string(), DW_ATE_signed),
1832             ast::TyI8 => ("i8".to_string(), DW_ATE_signed),
1833             ast::TyI16 => ("i16".to_string(), DW_ATE_signed),
1834             ast::TyI32 => ("i32".to_string(), DW_ATE_signed),
1835             ast::TyI64 => ("i64".to_string(), DW_ATE_signed)
1836         },
1837         ty::ty_uint(uint_ty) => match uint_ty {
1838             ast::TyUs(_) => ("usize".to_string(), DW_ATE_unsigned),
1839             ast::TyU8 => ("u8".to_string(), DW_ATE_unsigned),
1840             ast::TyU16 => ("u16".to_string(), DW_ATE_unsigned),
1841             ast::TyU32 => ("u32".to_string(), DW_ATE_unsigned),
1842             ast::TyU64 => ("u64".to_string(), DW_ATE_unsigned)
1843         },
1844         ty::ty_float(float_ty) => match float_ty {
1845             ast::TyF32 => ("f32".to_string(), DW_ATE_float),
1846             ast::TyF64 => ("f64".to_string(), DW_ATE_float),
1847         },
1848         _ => cx.sess().bug("debuginfo::basic_type_metadata - t is invalid type")
1849     };
1850
1851     let llvm_type = type_of::type_of(cx, t);
1852     let (size, align) = size_and_align_of(cx, llvm_type);
1853     let name = CString::from_slice(name.as_bytes());
1854     let ty_metadata = unsafe {
1855         llvm::LLVMDIBuilderCreateBasicType(
1856             DIB(cx),
1857             name.as_ptr(),
1858             bytes_to_bits(size),
1859             bytes_to_bits(align),
1860             encoding)
1861     };
1862
1863     return ty_metadata;
1864 }
1865
1866 fn pointer_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
1867                                    pointer_type: Ty<'tcx>,
1868                                    pointee_type_metadata: DIType)
1869                                    -> DIType {
1870     let pointer_llvm_type = type_of::type_of(cx, pointer_type);
1871     let (pointer_size, pointer_align) = size_and_align_of(cx, pointer_llvm_type);
1872     let name = compute_debuginfo_type_name(cx, pointer_type, false);
1873     let name = CString::from_slice(name.as_bytes());
1874     let ptr_metadata = unsafe {
1875         llvm::LLVMDIBuilderCreatePointerType(
1876             DIB(cx),
1877             pointee_type_metadata,
1878             bytes_to_bits(pointer_size),
1879             bytes_to_bits(pointer_align),
1880             name.as_ptr())
1881     };
1882     return ptr_metadata;
1883 }
1884
1885 //=-----------------------------------------------------------------------------
1886 // Common facilities for record-like types (structs, enums, tuples)
1887 //=-----------------------------------------------------------------------------
1888
1889 enum MemberOffset {
1890     FixedMemberOffset { bytes: uint },
1891     // For ComputedMemberOffset, the offset is read from the llvm type definition
1892     ComputedMemberOffset
1893 }
1894
1895 // Description of a type member, which can either be a regular field (as in
1896 // structs or tuples) or an enum variant
1897 struct MemberDescription {
1898     name: String,
1899     llvm_type: Type,
1900     type_metadata: DIType,
1901     offset: MemberOffset,
1902     flags: c_uint
1903 }
1904
1905 // A factory for MemberDescriptions. It produces a list of member descriptions
1906 // for some record-like type. MemberDescriptionFactories are used to defer the
1907 // creation of type member descriptions in order to break cycles arising from
1908 // recursive type definitions.
1909 enum MemberDescriptionFactory<'tcx> {
1910     StructMDF(StructMemberDescriptionFactory<'tcx>),
1911     TupleMDF(TupleMemberDescriptionFactory<'tcx>),
1912     EnumMDF(EnumMemberDescriptionFactory<'tcx>),
1913     VariantMDF(VariantMemberDescriptionFactory<'tcx>)
1914 }
1915
1916 impl<'tcx> MemberDescriptionFactory<'tcx> {
1917     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
1918                                       -> Vec<MemberDescription> {
1919         match *self {
1920             StructMDF(ref this) => {
1921                 this.create_member_descriptions(cx)
1922             }
1923             TupleMDF(ref this) => {
1924                 this.create_member_descriptions(cx)
1925             }
1926             EnumMDF(ref this) => {
1927                 this.create_member_descriptions(cx)
1928             }
1929             VariantMDF(ref this) => {
1930                 this.create_member_descriptions(cx)
1931             }
1932         }
1933     }
1934 }
1935
1936 // A description of some recursive type. It can either be already finished (as
1937 // with FinalMetadata) or it is not yet finished, but contains all information
1938 // needed to generate the missing parts of the description. See the documentation
1939 // section on Recursive Types at the top of this file for more information.
1940 enum RecursiveTypeDescription<'tcx> {
1941     UnfinishedMetadata {
1942         unfinished_type: Ty<'tcx>,
1943         unique_type_id: UniqueTypeId,
1944         metadata_stub: DICompositeType,
1945         llvm_type: Type,
1946         member_description_factory: MemberDescriptionFactory<'tcx>,
1947     },
1948     FinalMetadata(DICompositeType)
1949 }
1950
1951 fn create_and_register_recursive_type_forward_declaration<'a, 'tcx>(
1952     cx: &CrateContext<'a, 'tcx>,
1953     unfinished_type: Ty<'tcx>,
1954     unique_type_id: UniqueTypeId,
1955     metadata_stub: DICompositeType,
1956     llvm_type: Type,
1957     member_description_factory: MemberDescriptionFactory<'tcx>)
1958  -> RecursiveTypeDescription<'tcx> {
1959
1960     // Insert the stub into the TypeMap in order to allow for recursive references
1961     let mut type_map = debug_context(cx).type_map.borrow_mut();
1962     type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata_stub);
1963     type_map.register_type_with_metadata(cx, unfinished_type, metadata_stub);
1964
1965     UnfinishedMetadata {
1966         unfinished_type: unfinished_type,
1967         unique_type_id: unique_type_id,
1968         metadata_stub: metadata_stub,
1969         llvm_type: llvm_type,
1970         member_description_factory: member_description_factory,
1971     }
1972 }
1973
1974 impl<'tcx> RecursiveTypeDescription<'tcx> {
1975     // Finishes up the description of the type in question (mostly by providing
1976     // descriptions of the fields of the given type) and returns the final type metadata.
1977     fn finalize<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> MetadataCreationResult {
1978         match *self {
1979             FinalMetadata(metadata) => MetadataCreationResult::new(metadata, false),
1980             UnfinishedMetadata {
1981                 unfinished_type,
1982                 unique_type_id,
1983                 metadata_stub,
1984                 llvm_type,
1985                 ref member_description_factory,
1986                 ..
1987             } => {
1988                 // Make sure that we have a forward declaration of the type in
1989                 // the TypeMap so that recursive references are possible. This
1990                 // will always be the case if the RecursiveTypeDescription has
1991                 // been properly created through the
1992                 // create_and_register_recursive_type_forward_declaration() function.
1993                 {
1994                     let type_map = debug_context(cx).type_map.borrow();
1995                     if type_map.find_metadata_for_unique_id(unique_type_id).is_none() ||
1996                        type_map.find_metadata_for_type(unfinished_type).is_none() {
1997                         cx.sess().bug(&format!("Forward declaration of potentially recursive type \
1998                                               '{}' was not found in TypeMap!",
1999                                               ppaux::ty_to_string(cx.tcx(), unfinished_type))
2000                                       []);
2001                     }
2002                 }
2003
2004                 // ... then create the member descriptions ...
2005                 let member_descriptions =
2006                     member_description_factory.create_member_descriptions(cx);
2007
2008                 // ... and attach them to the stub to complete it.
2009                 set_members_of_composite_type(cx,
2010                                               metadata_stub,
2011                                               llvm_type,
2012                                               &member_descriptions[]);
2013                 return MetadataCreationResult::new(metadata_stub, true);
2014             }
2015         }
2016     }
2017 }
2018
2019
2020 //=-----------------------------------------------------------------------------
2021 // Structs
2022 //=-----------------------------------------------------------------------------
2023
2024 // Creates MemberDescriptions for the fields of a struct
2025 struct StructMemberDescriptionFactory<'tcx> {
2026     fields: Vec<ty::field<'tcx>>,
2027     is_simd: bool,
2028     span: Span,
2029 }
2030
2031 impl<'tcx> StructMemberDescriptionFactory<'tcx> {
2032     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2033                                       -> Vec<MemberDescription> {
2034         if self.fields.len() == 0 {
2035             return Vec::new();
2036         }
2037
2038         let field_size = if self.is_simd {
2039             machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields[0].mt.ty)) as uint
2040         } else {
2041             0xdeadbeef
2042         };
2043
2044         self.fields.iter().enumerate().map(|(i, field)| {
2045             let name = if field.name == special_idents::unnamed_field.name {
2046                 "".to_string()
2047             } else {
2048                 token::get_name(field.name).get().to_string()
2049             };
2050
2051             let offset = if self.is_simd {
2052                 assert!(field_size != 0xdeadbeef);
2053                 FixedMemberOffset { bytes: i * field_size }
2054             } else {
2055                 ComputedMemberOffset
2056             };
2057
2058             MemberDescription {
2059                 name: name,
2060                 llvm_type: type_of::type_of(cx, field.mt.ty),
2061                 type_metadata: type_metadata(cx, field.mt.ty, self.span),
2062                 offset: offset,
2063                 flags: FLAGS_NONE,
2064             }
2065         }).collect()
2066     }
2067 }
2068
2069
2070 fn prepare_struct_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2071                                      struct_type: Ty<'tcx>,
2072                                      def_id: ast::DefId,
2073                                      substs: &subst::Substs<'tcx>,
2074                                      unique_type_id: UniqueTypeId,
2075                                      span: Span)
2076                                      -> RecursiveTypeDescription<'tcx> {
2077     let struct_name = compute_debuginfo_type_name(cx, struct_type, false);
2078     let struct_llvm_type = type_of::type_of(cx, struct_type);
2079
2080     let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
2081
2082     let struct_metadata_stub = create_struct_stub(cx,
2083                                                   struct_llvm_type,
2084                                                   &struct_name[],
2085                                                   unique_type_id,
2086                                                   containing_scope);
2087
2088     let fields = ty::struct_fields(cx.tcx(), def_id, substs);
2089
2090     create_and_register_recursive_type_forward_declaration(
2091         cx,
2092         struct_type,
2093         unique_type_id,
2094         struct_metadata_stub,
2095         struct_llvm_type,
2096         StructMDF(StructMemberDescriptionFactory {
2097             fields: fields,
2098             is_simd: ty::type_is_simd(cx.tcx(), struct_type),
2099             span: span,
2100         })
2101     )
2102 }
2103
2104
2105 //=-----------------------------------------------------------------------------
2106 // Tuples
2107 //=-----------------------------------------------------------------------------
2108
2109 // Creates MemberDescriptions for the fields of a tuple
2110 struct TupleMemberDescriptionFactory<'tcx> {
2111     component_types: Vec<Ty<'tcx>>,
2112     span: Span,
2113 }
2114
2115 impl<'tcx> TupleMemberDescriptionFactory<'tcx> {
2116     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2117                                       -> Vec<MemberDescription> {
2118         self.component_types.iter().map(|&component_type| {
2119             MemberDescription {
2120                 name: "".to_string(),
2121                 llvm_type: type_of::type_of(cx, component_type),
2122                 type_metadata: type_metadata(cx, component_type, self.span),
2123                 offset: ComputedMemberOffset,
2124                 flags: FLAGS_NONE,
2125             }
2126         }).collect()
2127     }
2128 }
2129
2130 fn prepare_tuple_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2131                                     tuple_type: Ty<'tcx>,
2132                                     component_types: &[Ty<'tcx>],
2133                                     unique_type_id: UniqueTypeId,
2134                                     span: Span)
2135                                     -> RecursiveTypeDescription<'tcx> {
2136     let tuple_name = compute_debuginfo_type_name(cx, tuple_type, false);
2137     let tuple_llvm_type = type_of::type_of(cx, tuple_type);
2138
2139     create_and_register_recursive_type_forward_declaration(
2140         cx,
2141         tuple_type,
2142         unique_type_id,
2143         create_struct_stub(cx,
2144                            tuple_llvm_type,
2145                            &tuple_name[],
2146                            unique_type_id,
2147                            UNKNOWN_SCOPE_METADATA),
2148         tuple_llvm_type,
2149         TupleMDF(TupleMemberDescriptionFactory {
2150             component_types: component_types.to_vec(),
2151             span: span,
2152         })
2153     )
2154 }
2155
2156
2157 //=-----------------------------------------------------------------------------
2158 // Enums
2159 //=-----------------------------------------------------------------------------
2160
2161 // Describes the members of an enum value: An enum is described as a union of
2162 // structs in DWARF. This MemberDescriptionFactory provides the description for
2163 // the members of this union; so for every variant of the given enum, this factory
2164 // will produce one MemberDescription (all with no name and a fixed offset of
2165 // zero bytes).
2166 struct EnumMemberDescriptionFactory<'tcx> {
2167     enum_type: Ty<'tcx>,
2168     type_rep: Rc<adt::Repr<'tcx>>,
2169     variants: Rc<Vec<Rc<ty::VariantInfo<'tcx>>>>,
2170     discriminant_type_metadata: Option<DIType>,
2171     containing_scope: DIScope,
2172     file_metadata: DIFile,
2173     span: Span,
2174 }
2175
2176 impl<'tcx> EnumMemberDescriptionFactory<'tcx> {
2177     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2178                                       -> Vec<MemberDescription> {
2179         match *self.type_rep {
2180             adt::General(_, ref struct_defs, _) => {
2181                 let discriminant_info = RegularDiscriminant(self.discriminant_type_metadata
2182                     .expect(""));
2183
2184                 struct_defs
2185                     .iter()
2186                     .enumerate()
2187                     .map(|(i, struct_def)| {
2188                         let (variant_type_metadata,
2189                              variant_llvm_type,
2190                              member_desc_factory) =
2191                             describe_enum_variant(cx,
2192                                                   self.enum_type,
2193                                                   struct_def,
2194                                                   &*(*self.variants)[i],
2195                                                   discriminant_info,
2196                                                   self.containing_scope,
2197                                                   self.span);
2198
2199                         let member_descriptions = member_desc_factory
2200                             .create_member_descriptions(cx);
2201
2202                         set_members_of_composite_type(cx,
2203                                                       variant_type_metadata,
2204                                                       variant_llvm_type,
2205                                                       &member_descriptions[]);
2206                         MemberDescription {
2207                             name: "".to_string(),
2208                             llvm_type: variant_llvm_type,
2209                             type_metadata: variant_type_metadata,
2210                             offset: FixedMemberOffset { bytes: 0 },
2211                             flags: FLAGS_NONE
2212                         }
2213                     }).collect()
2214             },
2215             adt::Univariant(ref struct_def, _) => {
2216                 assert!(self.variants.len() <= 1);
2217
2218                 if self.variants.len() == 0 {
2219                     vec![]
2220                 } else {
2221                     let (variant_type_metadata,
2222                          variant_llvm_type,
2223                          member_description_factory) =
2224                         describe_enum_variant(cx,
2225                                               self.enum_type,
2226                                               struct_def,
2227                                               &*(*self.variants)[0],
2228                                               NoDiscriminant,
2229                                               self.containing_scope,
2230                                               self.span);
2231
2232                     let member_descriptions =
2233                         member_description_factory.create_member_descriptions(cx);
2234
2235                     set_members_of_composite_type(cx,
2236                                                   variant_type_metadata,
2237                                                   variant_llvm_type,
2238                                                   &member_descriptions[]);
2239                     vec![
2240                         MemberDescription {
2241                             name: "".to_string(),
2242                             llvm_type: variant_llvm_type,
2243                             type_metadata: variant_type_metadata,
2244                             offset: FixedMemberOffset { bytes: 0 },
2245                             flags: FLAGS_NONE
2246                         }
2247                     ]
2248                 }
2249             }
2250             adt::RawNullablePointer { nndiscr: non_null_variant_index, nnty, .. } => {
2251                 // As far as debuginfo is concerned, the pointer this enum
2252                 // represents is still wrapped in a struct. This is to make the
2253                 // DWARF representation of enums uniform.
2254
2255                 // First create a description of the artificial wrapper struct:
2256                 let non_null_variant = &(*self.variants)[non_null_variant_index as uint];
2257                 let non_null_variant_name = token::get_name(non_null_variant.name);
2258
2259                 // The llvm type and metadata of the pointer
2260                 let non_null_llvm_type = type_of::type_of(cx, nnty);
2261                 let non_null_type_metadata = type_metadata(cx, nnty, self.span);
2262
2263                 // The type of the artificial struct wrapping the pointer
2264                 let artificial_struct_llvm_type = Type::struct_(cx,
2265                                                                 &[non_null_llvm_type],
2266                                                                 false);
2267
2268                 // For the metadata of the wrapper struct, we need to create a
2269                 // MemberDescription of the struct's single field.
2270                 let sole_struct_member_description = MemberDescription {
2271                     name: match non_null_variant.arg_names {
2272                         Some(ref names) => token::get_ident(names[0]).get().to_string(),
2273                         None => "".to_string()
2274                     },
2275                     llvm_type: non_null_llvm_type,
2276                     type_metadata: non_null_type_metadata,
2277                     offset: FixedMemberOffset { bytes: 0 },
2278                     flags: FLAGS_NONE
2279                 };
2280
2281                 let unique_type_id = debug_context(cx).type_map
2282                                                       .borrow_mut()
2283                                                       .get_unique_type_id_of_enum_variant(
2284                                                           cx,
2285                                                           self.enum_type,
2286                                                           non_null_variant_name.get());
2287
2288                 // Now we can create the metadata of the artificial struct
2289                 let artificial_struct_metadata =
2290                     composite_type_metadata(cx,
2291                                             artificial_struct_llvm_type,
2292                                             non_null_variant_name.get(),
2293                                             unique_type_id,
2294                                             &[sole_struct_member_description],
2295                                             self.containing_scope,
2296                                             self.file_metadata,
2297                                             codemap::DUMMY_SP);
2298
2299                 // Encode the information about the null variant in the union
2300                 // member's name.
2301                 let null_variant_index = (1 - non_null_variant_index) as uint;
2302                 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
2303                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
2304                                                 0u,
2305                                                 null_variant_name);
2306
2307                 // Finally create the (singleton) list of descriptions of union
2308                 // members.
2309                 vec![
2310                     MemberDescription {
2311                         name: union_member_name,
2312                         llvm_type: artificial_struct_llvm_type,
2313                         type_metadata: artificial_struct_metadata,
2314                         offset: FixedMemberOffset { bytes: 0 },
2315                         flags: FLAGS_NONE
2316                     }
2317                 ]
2318             },
2319             adt::StructWrappedNullablePointer { nonnull: ref struct_def,
2320                                                 nndiscr,
2321                                                 ref discrfield, ..} => {
2322                 // Create a description of the non-null variant
2323                 let (variant_type_metadata, variant_llvm_type, member_description_factory) =
2324                     describe_enum_variant(cx,
2325                                           self.enum_type,
2326                                           struct_def,
2327                                           &*(*self.variants)[nndiscr as uint],
2328                                           OptimizedDiscriminant,
2329                                           self.containing_scope,
2330                                           self.span);
2331
2332                 let variant_member_descriptions =
2333                     member_description_factory.create_member_descriptions(cx);
2334
2335                 set_members_of_composite_type(cx,
2336                                               variant_type_metadata,
2337                                               variant_llvm_type,
2338                                               &variant_member_descriptions[]);
2339
2340                 // Encode the information about the null variant in the union
2341                 // member's name.
2342                 let null_variant_index = (1 - nndiscr) as uint;
2343                 let null_variant_name = token::get_name((*self.variants)[null_variant_index].name);
2344                 let discrfield = discrfield.iter()
2345                                            .skip(1)
2346                                            .map(|x| x.to_string())
2347                                            .collect::<Vec<_>>().connect("$");
2348                 let union_member_name = format!("RUST$ENCODED$ENUM${}${}",
2349                                                 discrfield,
2350                                                 null_variant_name);
2351
2352                 // Create the (singleton) list of descriptions of union members.
2353                 vec![
2354                     MemberDescription {
2355                         name: union_member_name,
2356                         llvm_type: variant_llvm_type,
2357                         type_metadata: variant_type_metadata,
2358                         offset: FixedMemberOffset { bytes: 0 },
2359                         flags: FLAGS_NONE
2360                     }
2361                 ]
2362             },
2363             adt::CEnum(..) => cx.sess().span_bug(self.span, "This should be unreachable.")
2364         }
2365     }
2366 }
2367
2368 // Creates MemberDescriptions for the fields of a single enum variant.
2369 struct VariantMemberDescriptionFactory<'tcx> {
2370     args: Vec<(String, Ty<'tcx>)>,
2371     discriminant_type_metadata: Option<DIType>,
2372     span: Span,
2373 }
2374
2375 impl<'tcx> VariantMemberDescriptionFactory<'tcx> {
2376     fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
2377                                       -> Vec<MemberDescription> {
2378         self.args.iter().enumerate().map(|(i, &(ref name, ty))| {
2379             MemberDescription {
2380                 name: name.to_string(),
2381                 llvm_type: type_of::type_of(cx, ty),
2382                 type_metadata: match self.discriminant_type_metadata {
2383                     Some(metadata) if i == 0 => metadata,
2384                     _ => type_metadata(cx, ty, self.span)
2385                 },
2386                 offset: ComputedMemberOffset,
2387                 flags: FLAGS_NONE
2388             }
2389         }).collect()
2390     }
2391 }
2392
2393 #[derive(Copy)]
2394 enum EnumDiscriminantInfo {
2395     RegularDiscriminant(DIType),
2396     OptimizedDiscriminant,
2397     NoDiscriminant
2398 }
2399
2400 // Returns a tuple of (1) type_metadata_stub of the variant, (2) the llvm_type
2401 // of the variant, and (3) a MemberDescriptionFactory for producing the
2402 // descriptions of the fields of the variant. This is a rudimentary version of a
2403 // full RecursiveTypeDescription.
2404 fn describe_enum_variant<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2405                                    enum_type: Ty<'tcx>,
2406                                    struct_def: &adt::Struct<'tcx>,
2407                                    variant_info: &ty::VariantInfo<'tcx>,
2408                                    discriminant_info: EnumDiscriminantInfo,
2409                                    containing_scope: DIScope,
2410                                    span: Span)
2411                                    -> (DICompositeType, Type, MemberDescriptionFactory<'tcx>) {
2412     let variant_llvm_type =
2413         Type::struct_(cx, &struct_def.fields
2414                                     .iter()
2415                                     .map(|&t| type_of::type_of(cx, t))
2416                                     .collect::<Vec<_>>()
2417                                     [],
2418                       struct_def.packed);
2419     // Could do some consistency checks here: size, align, field count, discr type
2420
2421     let variant_name = token::get_name(variant_info.name);
2422     let variant_name = variant_name.get();
2423     let unique_type_id = debug_context(cx).type_map
2424                                           .borrow_mut()
2425                                           .get_unique_type_id_of_enum_variant(
2426                                               cx,
2427                                               enum_type,
2428                                               variant_name);
2429
2430     let metadata_stub = create_struct_stub(cx,
2431                                            variant_llvm_type,
2432                                            variant_name,
2433                                            unique_type_id,
2434                                            containing_scope);
2435
2436     // Get the argument names from the enum variant info
2437     let mut arg_names: Vec<_> = match variant_info.arg_names {
2438         Some(ref names) => {
2439             names.iter()
2440                  .map(|ident| {
2441                      token::get_ident(*ident).get().to_string()
2442                  }).collect()
2443         }
2444         None => variant_info.args.iter().map(|_| "".to_string()).collect()
2445     };
2446
2447     // If this is not a univariant enum, there is also the discriminant field.
2448     match discriminant_info {
2449         RegularDiscriminant(_) => arg_names.insert(0, "RUST$ENUM$DISR".to_string()),
2450         _ => { /* do nothing */ }
2451     };
2452
2453     // Build an array of (field name, field type) pairs to be captured in the factory closure.
2454     let args: Vec<(String, Ty)> = arg_names.iter()
2455         .zip(struct_def.fields.iter())
2456         .map(|(s, &t)| (s.to_string(), t))
2457         .collect();
2458
2459     let member_description_factory =
2460         VariantMDF(VariantMemberDescriptionFactory {
2461             args: args,
2462             discriminant_type_metadata: match discriminant_info {
2463                 RegularDiscriminant(discriminant_type_metadata) => {
2464                     Some(discriminant_type_metadata)
2465                 }
2466                 _ => None
2467             },
2468             span: span,
2469         });
2470
2471     (metadata_stub, variant_llvm_type, member_description_factory)
2472 }
2473
2474 fn prepare_enum_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2475                                    enum_type: Ty<'tcx>,
2476                                    enum_def_id: ast::DefId,
2477                                    unique_type_id: UniqueTypeId,
2478                                    span: Span)
2479                                    -> RecursiveTypeDescription<'tcx> {
2480     let enum_name = compute_debuginfo_type_name(cx, enum_type, false);
2481
2482     let (containing_scope, definition_span) = get_namespace_and_span_for_item(cx, enum_def_id);
2483     let loc = span_start(cx, definition_span);
2484     let file_metadata = file_metadata(cx, &loc.file.name[]);
2485
2486     let variants = ty::enum_variants(cx.tcx(), enum_def_id);
2487
2488     let enumerators_metadata: Vec<DIDescriptor> = variants
2489         .iter()
2490         .map(|v| {
2491             let token = token::get_name(v.name);
2492             let name = CString::from_slice(token.get().as_bytes());
2493             unsafe {
2494                 llvm::LLVMDIBuilderCreateEnumerator(
2495                     DIB(cx),
2496                     name.as_ptr(),
2497                     v.disr_val as u64)
2498             }
2499         })
2500         .collect();
2501
2502     let discriminant_type_metadata = |&: inttype| {
2503         // We can reuse the type of the discriminant for all monomorphized
2504         // instances of an enum because it doesn't depend on any type parameters.
2505         // The def_id, uniquely identifying the enum's polytype acts as key in
2506         // this cache.
2507         let cached_discriminant_type_metadata = debug_context(cx).created_enum_disr_types
2508                                                                  .borrow()
2509                                                                  .get(&enum_def_id).cloned();
2510         match cached_discriminant_type_metadata {
2511             Some(discriminant_type_metadata) => discriminant_type_metadata,
2512             None => {
2513                 let discriminant_llvm_type = adt::ll_inttype(cx, inttype);
2514                 let (discriminant_size, discriminant_align) =
2515                     size_and_align_of(cx, discriminant_llvm_type);
2516                 let discriminant_base_type_metadata =
2517                     type_metadata(cx,
2518                                   adt::ty_of_inttype(cx.tcx(), inttype),
2519                                   codemap::DUMMY_SP);
2520                 let discriminant_name = get_enum_discriminant_name(cx, enum_def_id);
2521
2522                 let name = CString::from_slice(discriminant_name.get().as_bytes());
2523                 let discriminant_type_metadata = unsafe {
2524                     llvm::LLVMDIBuilderCreateEnumerationType(
2525                         DIB(cx),
2526                         containing_scope,
2527                         name.as_ptr(),
2528                         UNKNOWN_FILE_METADATA,
2529                         UNKNOWN_LINE_NUMBER,
2530                         bytes_to_bits(discriminant_size),
2531                         bytes_to_bits(discriminant_align),
2532                         create_DIArray(DIB(cx), enumerators_metadata.as_slice()),
2533                         discriminant_base_type_metadata)
2534                 };
2535
2536                 debug_context(cx).created_enum_disr_types
2537                                  .borrow_mut()
2538                                  .insert(enum_def_id, discriminant_type_metadata);
2539
2540                 discriminant_type_metadata
2541             }
2542         }
2543     };
2544
2545     let type_rep = adt::represent_type(cx, enum_type);
2546
2547     let discriminant_type_metadata = match *type_rep {
2548         adt::CEnum(inttype, _, _) => {
2549             return FinalMetadata(discriminant_type_metadata(inttype))
2550         },
2551         adt::RawNullablePointer { .. }           |
2552         adt::StructWrappedNullablePointer { .. } |
2553         adt::Univariant(..)                      => None,
2554         adt::General(inttype, _, _) => Some(discriminant_type_metadata(inttype)),
2555     };
2556
2557     let enum_llvm_type = type_of::type_of(cx, enum_type);
2558     let (enum_type_size, enum_type_align) = size_and_align_of(cx, enum_llvm_type);
2559
2560     let unique_type_id_str = debug_context(cx)
2561                              .type_map
2562                              .borrow()
2563                              .get_unique_type_id_as_string(unique_type_id);
2564
2565     let enum_name = CString::from_slice(enum_name.as_bytes());
2566     let unique_type_id_str = CString::from_slice(unique_type_id_str.as_bytes());
2567     let enum_metadata = unsafe {
2568         llvm::LLVMDIBuilderCreateUnionType(
2569         DIB(cx),
2570         containing_scope,
2571         enum_name.as_ptr(),
2572         UNKNOWN_FILE_METADATA,
2573         UNKNOWN_LINE_NUMBER,
2574         bytes_to_bits(enum_type_size),
2575         bytes_to_bits(enum_type_align),
2576         0, // Flags
2577         ptr::null_mut(),
2578         0, // RuntimeLang
2579         unique_type_id_str.as_ptr())
2580     };
2581
2582     return create_and_register_recursive_type_forward_declaration(
2583         cx,
2584         enum_type,
2585         unique_type_id,
2586         enum_metadata,
2587         enum_llvm_type,
2588         EnumMDF(EnumMemberDescriptionFactory {
2589             enum_type: enum_type,
2590             type_rep: type_rep.clone(),
2591             variants: variants,
2592             discriminant_type_metadata: discriminant_type_metadata,
2593             containing_scope: containing_scope,
2594             file_metadata: file_metadata,
2595             span: span,
2596         }),
2597     );
2598
2599     fn get_enum_discriminant_name(cx: &CrateContext,
2600                                   def_id: ast::DefId)
2601                                   -> token::InternedString {
2602         let name = if def_id.krate == ast::LOCAL_CRATE {
2603             cx.tcx().map.get_path_elem(def_id.node).name()
2604         } else {
2605             csearch::get_item_path(cx.tcx(), def_id).last().unwrap().name()
2606         };
2607
2608         token::get_name(name)
2609     }
2610 }
2611
2612 /// Creates debug information for a composite type, that is, anything that
2613 /// results in a LLVM struct.
2614 ///
2615 /// Examples of Rust types to use this are: structs, tuples, boxes, vecs, and enums.
2616 fn composite_type_metadata(cx: &CrateContext,
2617                            composite_llvm_type: Type,
2618                            composite_type_name: &str,
2619                            composite_type_unique_id: UniqueTypeId,
2620                            member_descriptions: &[MemberDescription],
2621                            containing_scope: DIScope,
2622
2623                            // Ignore source location information as long as it
2624                            // can't be reconstructed for non-local crates.
2625                            _file_metadata: DIFile,
2626                            _definition_span: Span)
2627                         -> DICompositeType {
2628     // Create the (empty) struct metadata node ...
2629     let composite_type_metadata = create_struct_stub(cx,
2630                                                      composite_llvm_type,
2631                                                      composite_type_name,
2632                                                      composite_type_unique_id,
2633                                                      containing_scope);
2634     // ... and immediately create and add the member descriptions.
2635     set_members_of_composite_type(cx,
2636                                   composite_type_metadata,
2637                                   composite_llvm_type,
2638                                   member_descriptions);
2639
2640     return composite_type_metadata;
2641 }
2642
2643 fn set_members_of_composite_type(cx: &CrateContext,
2644                                  composite_type_metadata: DICompositeType,
2645                                  composite_llvm_type: Type,
2646                                  member_descriptions: &[MemberDescription]) {
2647     // In some rare cases LLVM metadata uniquing would lead to an existing type
2648     // description being used instead of a new one created in create_struct_stub.
2649     // This would cause a hard to trace assertion in DICompositeType::SetTypeArray().
2650     // The following check makes sure that we get a better error message if this
2651     // should happen again due to some regression.
2652     {
2653         let mut composite_types_completed =
2654             debug_context(cx).composite_types_completed.borrow_mut();
2655         if composite_types_completed.contains(&composite_type_metadata) {
2656             let (llvm_version_major, llvm_version_minor) = unsafe {
2657                 (llvm::LLVMVersionMajor(), llvm::LLVMVersionMinor())
2658             };
2659
2660             let actual_llvm_version = llvm_version_major * 1000000 + llvm_version_minor * 1000;
2661             let min_supported_llvm_version = 3 * 1000000 + 4 * 1000;
2662
2663             if actual_llvm_version < min_supported_llvm_version {
2664                 cx.sess().warn(&format!("This version of rustc was built with LLVM \
2665                                         {}.{}. Rustc just ran into a known \
2666                                         debuginfo corruption problem thatoften \
2667                                         occurs with LLVM versions below 3.4. \
2668                                         Please use a rustc built with anewer \
2669                                         version of LLVM.",
2670                                        llvm_version_major,
2671                                        llvm_version_minor)[]);
2672             } else {
2673                 cx.sess().bug("debuginfo::set_members_of_composite_type() - \
2674                                Already completed forward declaration re-encountered.");
2675             }
2676         } else {
2677             composite_types_completed.insert(composite_type_metadata);
2678         }
2679     }
2680
2681     let member_metadata: Vec<DIDescriptor> = member_descriptions
2682         .iter()
2683         .enumerate()
2684         .map(|(i, member_description)| {
2685             let (member_size, member_align) = size_and_align_of(cx, member_description.llvm_type);
2686             let member_offset = match member_description.offset {
2687                 FixedMemberOffset { bytes } => bytes as u64,
2688                 ComputedMemberOffset => machine::llelement_offset(cx, composite_llvm_type, i)
2689             };
2690
2691             let member_name = CString::from_slice(member_description.name.as_bytes());
2692             unsafe {
2693                 llvm::LLVMDIBuilderCreateMemberType(
2694                     DIB(cx),
2695                     composite_type_metadata,
2696                     member_name.as_ptr(),
2697                     UNKNOWN_FILE_METADATA,
2698                     UNKNOWN_LINE_NUMBER,
2699                     bytes_to_bits(member_size),
2700                     bytes_to_bits(member_align),
2701                     bytes_to_bits(member_offset),
2702                     member_description.flags,
2703                     member_description.type_metadata)
2704             }
2705         })
2706         .collect();
2707
2708     unsafe {
2709         let type_array = create_DIArray(DIB(cx), &member_metadata[]);
2710         llvm::LLVMDICompositeTypeSetTypeArray(composite_type_metadata, type_array);
2711     }
2712 }
2713
2714 // A convenience wrapper around LLVMDIBuilderCreateStructType(). Does not do any
2715 // caching, does not add any fields to the struct. This can be done later with
2716 // set_members_of_composite_type().
2717 fn create_struct_stub(cx: &CrateContext,
2718                       struct_llvm_type: Type,
2719                       struct_type_name: &str,
2720                       unique_type_id: UniqueTypeId,
2721                       containing_scope: DIScope)
2722                    -> DICompositeType {
2723     let (struct_size, struct_align) = size_and_align_of(cx, struct_llvm_type);
2724
2725     let unique_type_id_str = debug_context(cx).type_map
2726                                               .borrow()
2727                                               .get_unique_type_id_as_string(unique_type_id);
2728     let name = CString::from_slice(struct_type_name.as_bytes());
2729     let unique_type_id = CString::from_slice(unique_type_id_str.as_bytes());
2730     let metadata_stub = unsafe {
2731         // LLVMDIBuilderCreateStructType() wants an empty array. A null
2732         // pointer will lead to hard to trace and debug LLVM assertions
2733         // later on in llvm/lib/IR/Value.cpp.
2734         let empty_array = create_DIArray(DIB(cx), &[]);
2735
2736         llvm::LLVMDIBuilderCreateStructType(
2737             DIB(cx),
2738             containing_scope,
2739             name.as_ptr(),
2740             UNKNOWN_FILE_METADATA,
2741             UNKNOWN_LINE_NUMBER,
2742             bytes_to_bits(struct_size),
2743             bytes_to_bits(struct_align),
2744             0,
2745             ptr::null_mut(),
2746             empty_array,
2747             0,
2748             ptr::null_mut(),
2749             unique_type_id.as_ptr())
2750     };
2751
2752     return metadata_stub;
2753 }
2754
2755 fn fixed_vec_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2756                                 unique_type_id: UniqueTypeId,
2757                                 element_type: Ty<'tcx>,
2758                                 len: uint,
2759                                 span: Span)
2760                                 -> MetadataCreationResult {
2761     let element_type_metadata = type_metadata(cx, element_type, span);
2762
2763     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2764
2765     let element_llvm_type = type_of::type_of(cx, element_type);
2766     let (element_type_size, element_type_align) = size_and_align_of(cx, element_llvm_type);
2767
2768     let subrange = unsafe {
2769         llvm::LLVMDIBuilderGetOrCreateSubrange(
2770             DIB(cx),
2771             0,
2772             len as i64)
2773     };
2774
2775     let subscripts = create_DIArray(DIB(cx), &[subrange]);
2776     let metadata = unsafe {
2777         llvm::LLVMDIBuilderCreateArrayType(
2778             DIB(cx),
2779             bytes_to_bits(element_type_size * (len as u64)),
2780             bytes_to_bits(element_type_align),
2781             element_type_metadata,
2782             subscripts)
2783     };
2784
2785     return MetadataCreationResult::new(metadata, false);
2786 }
2787
2788 fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2789                                 vec_type: Ty<'tcx>,
2790                                 element_type: Ty<'tcx>,
2791                                 unique_type_id: UniqueTypeId,
2792                                 span: Span)
2793                                 -> MetadataCreationResult {
2794     let data_ptr_type = ty::mk_ptr(cx.tcx(), ty::mt {
2795         ty: element_type,
2796         mutbl: ast::MutImmutable
2797     });
2798
2799     let element_type_metadata = type_metadata(cx, data_ptr_type, span);
2800
2801     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2802
2803     let slice_llvm_type = type_of::type_of(cx, vec_type);
2804     let slice_type_name = compute_debuginfo_type_name(cx, vec_type, true);
2805
2806     let member_llvm_types = slice_llvm_type.field_types();
2807     assert!(slice_layout_is_correct(cx,
2808                                     &member_llvm_types[],
2809                                     element_type));
2810     let member_descriptions = [
2811         MemberDescription {
2812             name: "data_ptr".to_string(),
2813             llvm_type: member_llvm_types[0],
2814             type_metadata: element_type_metadata,
2815             offset: ComputedMemberOffset,
2816             flags: FLAGS_NONE
2817         },
2818         MemberDescription {
2819             name: "length".to_string(),
2820             llvm_type: member_llvm_types[1],
2821             type_metadata: type_metadata(cx, cx.tcx().types.uint, span),
2822             offset: ComputedMemberOffset,
2823             flags: FLAGS_NONE
2824         },
2825     ];
2826
2827     assert!(member_descriptions.len() == member_llvm_types.len());
2828
2829     let loc = span_start(cx, span);
2830     let file_metadata = file_metadata(cx, &loc.file.name[]);
2831
2832     let metadata = composite_type_metadata(cx,
2833                                            slice_llvm_type,
2834                                            &slice_type_name[],
2835                                            unique_type_id,
2836                                            &member_descriptions,
2837                                            UNKNOWN_SCOPE_METADATA,
2838                                            file_metadata,
2839                                            span);
2840     return MetadataCreationResult::new(metadata, false);
2841
2842     fn slice_layout_is_correct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2843                                          member_llvm_types: &[Type],
2844                                          element_type: Ty<'tcx>)
2845                                          -> bool {
2846         member_llvm_types.len() == 2 &&
2847         member_llvm_types[0] == type_of::type_of(cx, element_type).ptr_to() &&
2848         member_llvm_types[1] == cx.int_type()
2849     }
2850 }
2851
2852 fn subroutine_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2853                                       unique_type_id: UniqueTypeId,
2854                                       signature: &ty::PolyFnSig<'tcx>,
2855                                       span: Span)
2856                                       -> MetadataCreationResult
2857 {
2858     let signature = ty::erase_late_bound_regions(cx.tcx(), signature);
2859
2860     let mut signature_metadata: Vec<DIType> = Vec::with_capacity(signature.inputs.len() + 1);
2861
2862     // return type
2863     signature_metadata.push(match signature.output {
2864         ty::FnConverging(ret_ty) => match ret_ty.sty {
2865             ty::ty_tup(ref tys) if tys.is_empty() => ptr::null_mut(),
2866             _ => type_metadata(cx, ret_ty, span)
2867         },
2868         ty::FnDiverging => diverging_type_metadata(cx)
2869     });
2870
2871     // regular arguments
2872     for &argument_type in signature.inputs.iter() {
2873         signature_metadata.push(type_metadata(cx, argument_type, span));
2874     }
2875
2876     return_if_metadata_created_in_meantime!(cx, unique_type_id);
2877
2878     return MetadataCreationResult::new(
2879         unsafe {
2880             llvm::LLVMDIBuilderCreateSubroutineType(
2881                 DIB(cx),
2882                 UNKNOWN_FILE_METADATA,
2883                 create_DIArray(DIB(cx), &signature_metadata[]))
2884         },
2885         false);
2886 }
2887
2888 // FIXME(1563) This is all a bit of a hack because 'trait pointer' is an ill-
2889 // defined concept. For the case of an actual trait pointer (i.e., Box<Trait>,
2890 // &Trait), trait_object_type should be the whole thing (e.g, Box<Trait>) and
2891 // trait_type should be the actual trait (e.g., Trait). Where the trait is part
2892 // of a DST struct, there is no trait_object_type and the results of this
2893 // function will be a little bit weird.
2894 fn trait_pointer_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2895                                     trait_type: Ty<'tcx>,
2896                                     trait_object_type: Option<Ty<'tcx>>,
2897                                     unique_type_id: UniqueTypeId)
2898                                     -> DIType {
2899     // The implementation provided here is a stub. It makes sure that the trait
2900     // type is assigned the correct name, size, namespace, and source location.
2901     // But it does not describe the trait's methods.
2902
2903     let def_id = match trait_type.sty {
2904         ty::ty_trait(ref data) => data.principal_def_id(),
2905         _ => {
2906             let pp_type_name = ppaux::ty_to_string(cx.tcx(), trait_type);
2907             cx.sess().bug(&format!("debuginfo: Unexpected trait-object type in \
2908                                    trait_pointer_metadata(): {}",
2909                                    &pp_type_name[])[]);
2910         }
2911     };
2912
2913     let trait_object_type = trait_object_type.unwrap_or(trait_type);
2914     let trait_type_name =
2915         compute_debuginfo_type_name(cx, trait_object_type, false);
2916
2917     let (containing_scope, _) = get_namespace_and_span_for_item(cx, def_id);
2918
2919     let trait_llvm_type = type_of::type_of(cx, trait_object_type);
2920
2921     composite_type_metadata(cx,
2922                             trait_llvm_type,
2923                             &trait_type_name[],
2924                             unique_type_id,
2925                             &[],
2926                             containing_scope,
2927                             UNKNOWN_FILE_METADATA,
2928                             codemap::DUMMY_SP)
2929 }
2930
2931 fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
2932                            t: Ty<'tcx>,
2933                            usage_site_span: Span)
2934                            -> DIType {
2935     // Get the unique type id of this type.
2936     let unique_type_id = {
2937         let mut type_map = debug_context(cx).type_map.borrow_mut();
2938         // First, try to find the type in TypeMap. If we have seen it before, we
2939         // can exit early here.
2940         match type_map.find_metadata_for_type(t) {
2941             Some(metadata) => {
2942                 return metadata;
2943             },
2944             None => {
2945                 // The Ty is not in the TypeMap but maybe we have already seen
2946                 // an equivalent type (e.g. only differing in region arguments).
2947                 // In order to find out, generate the unique type id and look
2948                 // that up.
2949                 let unique_type_id = type_map.get_unique_type_id_of_type(cx, t);
2950                 match type_map.find_metadata_for_unique_id(unique_type_id) {
2951                     Some(metadata) => {
2952                         // There is already an equivalent type in the TypeMap.
2953                         // Register this Ty as an alias in the cache and
2954                         // return the cached metadata.
2955                         type_map.register_type_with_metadata(cx, t, metadata);
2956                         return metadata;
2957                     },
2958                     None => {
2959                         // There really is no type metadata for this type, so
2960                         // proceed by creating it.
2961                         unique_type_id
2962                     }
2963                 }
2964             }
2965         }
2966     };
2967
2968     debug!("type_metadata: {:?}", t);
2969
2970     let sty = &t.sty;
2971     let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty {
2972         ty::ty_bool     |
2973         ty::ty_char     |
2974         ty::ty_int(_)   |
2975         ty::ty_uint(_)  |
2976         ty::ty_float(_) => {
2977             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
2978         }
2979         ty::ty_tup(ref elements) if elements.is_empty() => {
2980             MetadataCreationResult::new(basic_type_metadata(cx, t), false)
2981         }
2982         ty::ty_enum(def_id, _) => {
2983             prepare_enum_metadata(cx, t, def_id, unique_type_id, usage_site_span).finalize(cx)
2984         }
2985         ty::ty_vec(typ, Some(len)) => {
2986             fixed_vec_metadata(cx, unique_type_id, typ, len, usage_site_span)
2987         }
2988         // FIXME Can we do better than this for unsized vec/str fields?
2989         ty::ty_vec(typ, None) => fixed_vec_metadata(cx, unique_type_id, typ, 0, usage_site_span),
2990         ty::ty_str => fixed_vec_metadata(cx, unique_type_id, cx.tcx().types.i8, 0, usage_site_span),
2991         ty::ty_trait(..) => {
2992             MetadataCreationResult::new(
2993                         trait_pointer_metadata(cx, t, None, unique_type_id),
2994             false)
2995         }
2996         ty::ty_uniq(ty) | ty::ty_ptr(ty::mt{ty, ..}) | ty::ty_rptr(_, ty::mt{ty, ..}) => {
2997             match ty.sty {
2998                 ty::ty_vec(typ, None) => {
2999                     vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
3000                 }
3001                 ty::ty_str => {
3002                     vec_slice_metadata(cx, t, cx.tcx().types.u8, unique_type_id, usage_site_span)
3003                 }
3004                 ty::ty_trait(..) => {
3005                     MetadataCreationResult::new(
3006                         trait_pointer_metadata(cx, ty, Some(t), unique_type_id),
3007                         false)
3008                 }
3009                 _ => {
3010                     let pointee_metadata = type_metadata(cx, ty, usage_site_span);
3011
3012                     match debug_context(cx).type_map
3013                                            .borrow()
3014                                            .find_metadata_for_unique_id(unique_type_id) {
3015                         Some(metadata) => return metadata,
3016                         None => { /* proceed normally */ }
3017                     };
3018
3019                     MetadataCreationResult::new(pointer_type_metadata(cx, t, pointee_metadata),
3020                                                 false)
3021                 }
3022             }
3023         }
3024         ty::ty_bare_fn(_, ref barefnty) => {
3025             subroutine_type_metadata(cx, unique_type_id, &barefnty.sig, usage_site_span)
3026         }
3027         ty::ty_unboxed_closure(def_id, _, substs) => {
3028             let typer = NormalizingUnboxedClosureTyper::new(cx.tcx());
3029             let sig = typer.unboxed_closure_type(def_id, substs).sig;
3030             subroutine_type_metadata(cx, unique_type_id, &sig, usage_site_span)
3031         }
3032         ty::ty_struct(def_id, substs) => {
3033             prepare_struct_metadata(cx,
3034                                     t,
3035                                     def_id,
3036                                     substs,
3037                                     unique_type_id,
3038                                     usage_site_span).finalize(cx)
3039         }
3040         ty::ty_tup(ref elements) => {
3041             prepare_tuple_metadata(cx,
3042                                    t,
3043                                    &elements[],
3044                                    unique_type_id,
3045                                    usage_site_span).finalize(cx)
3046         }
3047         _ => {
3048             cx.sess().bug(&format!("debuginfo: unexpected type in type_metadata: {:?}",
3049                                   sty)[])
3050         }
3051     };
3052
3053     {
3054         let mut type_map = debug_context(cx).type_map.borrow_mut();
3055
3056         if already_stored_in_typemap {
3057             // Also make sure that we already have a TypeMap entry entry for the unique type id.
3058             let metadata_for_uid = match type_map.find_metadata_for_unique_id(unique_type_id) {
3059                 Some(metadata) => metadata,
3060                 None => {
3061                     let unique_type_id_str =
3062                         type_map.get_unique_type_id_as_string(unique_type_id);
3063                     let error_message = format!("Expected type metadata for unique \
3064                                                  type id '{}' to already be in \
3065                                                  the debuginfo::TypeMap but it \
3066                                                  was not. (Ty = {})",
3067                                                 &unique_type_id_str[],
3068                                                 ppaux::ty_to_string(cx.tcx(), t));
3069                     cx.sess().span_bug(usage_site_span, &error_message[]);
3070                 }
3071             };
3072
3073             match type_map.find_metadata_for_type(t) {
3074                 Some(metadata) => {
3075                     if metadata != metadata_for_uid {
3076                         let unique_type_id_str =
3077                             type_map.get_unique_type_id_as_string(unique_type_id);
3078                         let error_message = format!("Mismatch between Ty and \
3079                                                      UniqueTypeId maps in \
3080                                                      debuginfo::TypeMap. \
3081                                                      UniqueTypeId={}, Ty={}",
3082                             &unique_type_id_str[],
3083                             ppaux::ty_to_string(cx.tcx(), t));
3084                         cx.sess().span_bug(usage_site_span, &error_message[]);
3085                     }
3086                 }
3087                 None => {
3088                     type_map.register_type_with_metadata(cx, t, metadata);
3089                 }
3090             }
3091         } else {
3092             type_map.register_type_with_metadata(cx, t, metadata);
3093             type_map.register_unique_id_with_metadata(cx, unique_type_id, metadata);
3094         }
3095     }
3096
3097     metadata
3098 }
3099
3100 struct MetadataCreationResult {
3101     metadata: DIType,
3102     already_stored_in_typemap: bool
3103 }
3104
3105 impl MetadataCreationResult {
3106     fn new(metadata: DIType, already_stored_in_typemap: bool) -> MetadataCreationResult {
3107         MetadataCreationResult {
3108             metadata: metadata,
3109             already_stored_in_typemap: already_stored_in_typemap
3110         }
3111     }
3112 }
3113
3114 #[derive(Copy, PartialEq)]
3115 enum DebugLocation {
3116     KnownLocation { scope: DIScope, line: uint, col: uint },
3117     UnknownLocation
3118 }
3119
3120 impl DebugLocation {
3121     fn new(scope: DIScope, line: uint, col: uint) -> DebugLocation {
3122         KnownLocation {
3123             scope: scope,
3124             line: line,
3125             col: col,
3126         }
3127     }
3128 }
3129
3130 fn set_debug_location(cx: &CrateContext, debug_location: DebugLocation) {
3131     if debug_location == debug_context(cx).current_debug_location.get() {
3132         return;
3133     }
3134
3135     let metadata_node;
3136
3137     match debug_location {
3138         KnownLocation { scope, line, .. } => {
3139             // Always set the column to zero like Clang and GCC
3140             let col = UNKNOWN_COLUMN_NUMBER;
3141             debug!("setting debug location to {} {}", line, col);
3142             let elements = [C_i32(cx, line as i32), C_i32(cx, col as i32),
3143                             scope, ptr::null_mut()];
3144             unsafe {
3145                 metadata_node = llvm::LLVMMDNodeInContext(debug_context(cx).llcontext,
3146                                                           elements.as_ptr(),
3147                                                           elements.len() as c_uint);
3148             }
3149         }
3150         UnknownLocation => {
3151             debug!("clearing debug location ");
3152             metadata_node = ptr::null_mut();
3153         }
3154     };
3155
3156     unsafe {
3157         llvm::LLVMSetCurrentDebugLocation(cx.raw_builder(), metadata_node);
3158     }
3159
3160     debug_context(cx).current_debug_location.set(debug_location);
3161 }
3162
3163 //=-----------------------------------------------------------------------------
3164 //  Utility Functions
3165 //=-----------------------------------------------------------------------------
3166
3167 fn contains_nodebug_attribute(attributes: &[ast::Attribute]) -> bool {
3168     attributes.iter().any(|attr| {
3169         let meta_item: &ast::MetaItem = &*attr.node.value;
3170         match meta_item.node {
3171             ast::MetaWord(ref value) => value.get() == "no_debug",
3172             _ => false
3173         }
3174     })
3175 }
3176
3177 /// Return codemap::Loc corresponding to the beginning of the span
3178 fn span_start(cx: &CrateContext, span: Span) -> codemap::Loc {
3179     cx.sess().codemap().lookup_char_pos(span.lo)
3180 }
3181
3182 fn size_and_align_of(cx: &CrateContext, llvm_type: Type) -> (u64, u64) {
3183     (machine::llsize_of_alloc(cx, llvm_type), machine::llalign_of_min(cx, llvm_type) as u64)
3184 }
3185
3186 fn bytes_to_bits(bytes: u64) -> u64 {
3187     bytes * 8
3188 }
3189
3190 #[inline]
3191 fn debug_context<'a, 'tcx>(cx: &'a CrateContext<'a, 'tcx>)
3192                            -> &'a CrateDebugContext<'tcx> {
3193     let debug_context: &'a CrateDebugContext<'tcx> = cx.dbg_cx().as_ref().unwrap();
3194     debug_context
3195 }
3196
3197 #[inline]
3198 #[allow(non_snake_case)]
3199 fn DIB(cx: &CrateContext) -> DIBuilderRef {
3200     cx.dbg_cx().as_ref().unwrap().builder
3201 }
3202
3203 fn fn_should_be_ignored(fcx: &FunctionContext) -> bool {
3204     match fcx.debug_context {
3205         FunctionDebugContext::RegularContext(_) => false,
3206         _ => true
3207     }
3208 }
3209
3210 fn assert_type_for_node_id(cx: &CrateContext,
3211                            node_id: ast::NodeId,
3212                            error_reporting_span: Span) {
3213     if !cx.tcx().node_types.borrow().contains_key(&node_id) {
3214         cx.sess().span_bug(error_reporting_span,
3215                            "debuginfo: Could not find type for node id!");
3216     }
3217 }
3218
3219 fn get_namespace_and_span_for_item(cx: &CrateContext, def_id: ast::DefId)
3220                                    -> (DIScope, Span) {
3221     let containing_scope = namespace_for_item(cx, def_id).scope;
3222     let definition_span = if def_id.krate == ast::LOCAL_CRATE {
3223         cx.tcx().map.span(def_id.node)
3224     } else {
3225         // For external items there is no span information
3226         codemap::DUMMY_SP
3227     };
3228
3229     (containing_scope, definition_span)
3230 }
3231
3232 // This procedure builds the *scope map* for a given function, which maps any
3233 // given ast::NodeId in the function's AST to the correct DIScope metadata instance.
3234 //
3235 // This builder procedure walks the AST in execution order and keeps track of
3236 // what belongs to which scope, creating DIScope DIEs along the way, and
3237 // introducing *artificial* lexical scope descriptors where necessary. These
3238 // artificial scopes allow GDB to correctly handle name shadowing.
3239 fn create_scope_map(cx: &CrateContext,
3240                     args: &[ast::Arg],
3241                     fn_entry_block: &ast::Block,
3242                     fn_metadata: DISubprogram,
3243                     fn_ast_id: ast::NodeId)
3244                  -> NodeMap<DIScope> {
3245     let mut scope_map = NodeMap::new();
3246
3247     let def_map = &cx.tcx().def_map;
3248
3249     struct ScopeStackEntry {
3250         scope_metadata: DIScope,
3251         ident: Option<ast::Ident>
3252     }
3253
3254     let mut scope_stack = vec!(ScopeStackEntry { scope_metadata: fn_metadata,
3255                                                  ident: None });
3256     scope_map.insert(fn_ast_id, fn_metadata);
3257
3258     // Push argument identifiers onto the stack so arguments integrate nicely
3259     // with variable shadowing.
3260     for arg in args.iter() {
3261         pat_util::pat_bindings(def_map, &*arg.pat, |_, node_id, _, path1| {
3262             scope_stack.push(ScopeStackEntry { scope_metadata: fn_metadata,
3263                                                ident: Some(path1.node) });
3264             scope_map.insert(node_id, fn_metadata);
3265         })
3266     }
3267
3268     // Clang creates a separate scope for function bodies, so let's do this too.
3269     with_new_scope(cx,
3270                    fn_entry_block.span,
3271                    &mut scope_stack,
3272                    &mut scope_map,
3273                    |cx, scope_stack, scope_map| {
3274         walk_block(cx, fn_entry_block, scope_stack, scope_map);
3275     });
3276
3277     return scope_map;
3278
3279
3280     // local helper functions for walking the AST.
3281     fn with_new_scope<F>(cx: &CrateContext,
3282                          scope_span: Span,
3283                          scope_stack: &mut Vec<ScopeStackEntry> ,
3284                          scope_map: &mut NodeMap<DIScope>,
3285                          inner_walk: F) where
3286         F: FnOnce(&CrateContext, &mut Vec<ScopeStackEntry>, &mut NodeMap<DIScope>),
3287     {
3288         // Create a new lexical scope and push it onto the stack
3289         let loc = cx.sess().codemap().lookup_char_pos(scope_span.lo);
3290         let file_metadata = file_metadata(cx, &loc.file.name[]);
3291         let parent_scope = scope_stack.last().unwrap().scope_metadata;
3292
3293         let scope_metadata = unsafe {
3294             llvm::LLVMDIBuilderCreateLexicalBlock(
3295                 DIB(cx),
3296                 parent_scope,
3297                 file_metadata,
3298                 loc.line as c_uint,
3299                 loc.col.to_uint() as c_uint)
3300         };
3301
3302         scope_stack.push(ScopeStackEntry { scope_metadata: scope_metadata,
3303                                            ident: None });
3304
3305         inner_walk(cx, scope_stack, scope_map);
3306
3307         // pop artificial scopes
3308         while scope_stack.last().unwrap().ident.is_some() {
3309             scope_stack.pop();
3310         }
3311
3312         if scope_stack.last().unwrap().scope_metadata != scope_metadata {
3313             cx.sess().span_bug(scope_span, "debuginfo: Inconsistency in scope management.");
3314         }
3315
3316         scope_stack.pop();
3317     }
3318
3319     fn walk_block(cx: &CrateContext,
3320                   block: &ast::Block,
3321                   scope_stack: &mut Vec<ScopeStackEntry> ,
3322                   scope_map: &mut NodeMap<DIScope>) {
3323         scope_map.insert(block.id, scope_stack.last().unwrap().scope_metadata);
3324
3325         // The interesting things here are statements and the concluding expression.
3326         for statement in block.stmts.iter() {
3327             scope_map.insert(ast_util::stmt_id(&**statement),
3328                              scope_stack.last().unwrap().scope_metadata);
3329
3330             match statement.node {
3331                 ast::StmtDecl(ref decl, _) =>
3332                     walk_decl(cx, &**decl, scope_stack, scope_map),
3333                 ast::StmtExpr(ref exp, _) |
3334                 ast::StmtSemi(ref exp, _) =>
3335                     walk_expr(cx, &**exp, scope_stack, scope_map),
3336                 ast::StmtMac(..) => () // Ignore macros (which should be expanded anyway).
3337             }
3338         }
3339
3340         for exp in block.expr.iter() {
3341             walk_expr(cx, &**exp, scope_stack, scope_map);
3342         }
3343     }
3344
3345     fn walk_decl(cx: &CrateContext,
3346                  decl: &ast::Decl,
3347                  scope_stack: &mut Vec<ScopeStackEntry> ,
3348                  scope_map: &mut NodeMap<DIScope>) {
3349         match *decl {
3350             codemap::Spanned { node: ast::DeclLocal(ref local), .. } => {
3351                 scope_map.insert(local.id, scope_stack.last().unwrap().scope_metadata);
3352
3353                 walk_pattern(cx, &*local.pat, scope_stack, scope_map);
3354
3355                 for exp in local.init.iter() {
3356                     walk_expr(cx, &**exp, scope_stack, scope_map);
3357                 }
3358             }
3359             _ => ()
3360         }
3361     }
3362
3363     fn walk_pattern(cx: &CrateContext,
3364                     pat: &ast::Pat,
3365                     scope_stack: &mut Vec<ScopeStackEntry> ,
3366                     scope_map: &mut NodeMap<DIScope>) {
3367
3368         let def_map = &cx.tcx().def_map;
3369
3370         // Unfortunately, we cannot just use pat_util::pat_bindings() or
3371         // ast_util::walk_pat() here because we have to visit *all* nodes in
3372         // order to put them into the scope map. The above functions don't do that.
3373         match pat.node {
3374             ast::PatIdent(_, ref path1, ref sub_pat_opt) => {
3375
3376                 // Check if this is a binding. If so we need to put it on the
3377                 // scope stack and maybe introduce an artificial scope
3378                 if pat_util::pat_is_binding(def_map, &*pat) {
3379
3380                     let ident = path1.node;
3381
3382                     // LLVM does not properly generate 'DW_AT_start_scope' fields
3383                     // for variable DIEs. For this reason we have to introduce
3384                     // an artificial scope at bindings whenever a variable with
3385                     // the same name is declared in *any* parent scope.
3386                     //
3387                     // Otherwise the following error occurs:
3388                     //
3389                     // let x = 10;
3390                     //
3391                     // do_something(); // 'gdb print x' correctly prints 10
3392                     //
3393                     // {
3394                     //     do_something(); // 'gdb print x' prints 0, because it
3395                     //                     // already reads the uninitialized 'x'
3396                     //                     // from the next line...
3397                     //     let x = 100;
3398                     //     do_something(); // 'gdb print x' correctly prints 100
3399                     // }
3400
3401                     // Is there already a binding with that name?
3402                     // N.B.: this comparison must be UNhygienic... because
3403                     // gdb knows nothing about the context, so any two
3404                     // variables with the same name will cause the problem.
3405                     let need_new_scope = scope_stack
3406                         .iter()
3407                         .any(|entry| entry.ident.iter().any(|i| i.name == ident.name));
3408
3409                     if need_new_scope {
3410                         // Create a new lexical scope and push it onto the stack
3411                         let loc = cx.sess().codemap().lookup_char_pos(pat.span.lo);
3412                         let file_metadata = file_metadata(cx, &loc.file.name[]);
3413                         let parent_scope = scope_stack.last().unwrap().scope_metadata;
3414
3415                         let scope_metadata = unsafe {
3416                             llvm::LLVMDIBuilderCreateLexicalBlock(
3417                                 DIB(cx),
3418                                 parent_scope,
3419                                 file_metadata,
3420                                 loc.line as c_uint,
3421                                 loc.col.to_uint() as c_uint)
3422                         };
3423
3424                         scope_stack.push(ScopeStackEntry {
3425                             scope_metadata: scope_metadata,
3426                             ident: Some(ident)
3427                         });
3428
3429                     } else {
3430                         // Push a new entry anyway so the name can be found
3431                         let prev_metadata = scope_stack.last().unwrap().scope_metadata;
3432                         scope_stack.push(ScopeStackEntry {
3433                             scope_metadata: prev_metadata,
3434                             ident: Some(ident)
3435                         });
3436                     }
3437                 }
3438
3439                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3440
3441                 for sub_pat in sub_pat_opt.iter() {
3442                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3443                 }
3444             }
3445
3446             ast::PatWild(_) => {
3447                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3448             }
3449
3450             ast::PatEnum(_, ref sub_pats_opt) => {
3451                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3452
3453                 for sub_pats in sub_pats_opt.iter() {
3454                     for p in sub_pats.iter() {
3455                         walk_pattern(cx, &**p, scope_stack, scope_map);
3456                     }
3457                 }
3458             }
3459
3460             ast::PatStruct(_, ref field_pats, _) => {
3461                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3462
3463                 for &codemap::Spanned {
3464                     node: ast::FieldPat { pat: ref sub_pat, .. },
3465                     ..
3466                 } in field_pats.iter() {
3467                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3468                 }
3469             }
3470
3471             ast::PatTup(ref sub_pats) => {
3472                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3473
3474                 for sub_pat in sub_pats.iter() {
3475                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3476                 }
3477             }
3478
3479             ast::PatBox(ref sub_pat) | ast::PatRegion(ref sub_pat, _) => {
3480                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3481                 walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3482             }
3483
3484             ast::PatLit(ref exp) => {
3485                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3486                 walk_expr(cx, &**exp, scope_stack, scope_map);
3487             }
3488
3489             ast::PatRange(ref exp1, ref exp2) => {
3490                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3491                 walk_expr(cx, &**exp1, scope_stack, scope_map);
3492                 walk_expr(cx, &**exp2, scope_stack, scope_map);
3493             }
3494
3495             ast::PatVec(ref front_sub_pats, ref middle_sub_pats, ref back_sub_pats) => {
3496                 scope_map.insert(pat.id, scope_stack.last().unwrap().scope_metadata);
3497
3498                 for sub_pat in front_sub_pats.iter() {
3499                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3500                 }
3501
3502                 for sub_pat in middle_sub_pats.iter() {
3503                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3504                 }
3505
3506                 for sub_pat in back_sub_pats.iter() {
3507                     walk_pattern(cx, &**sub_pat, scope_stack, scope_map);
3508                 }
3509             }
3510
3511             ast::PatMac(_) => {
3512                 cx.sess().span_bug(pat.span, "debuginfo::create_scope_map() - \
3513                                               Found unexpanded macro.");
3514             }
3515         }
3516     }
3517
3518     fn walk_expr(cx: &CrateContext,
3519                  exp: &ast::Expr,
3520                  scope_stack: &mut Vec<ScopeStackEntry> ,
3521                  scope_map: &mut NodeMap<DIScope>) {
3522
3523         scope_map.insert(exp.id, scope_stack.last().unwrap().scope_metadata);
3524
3525         match exp.node {
3526             ast::ExprLit(_)   |
3527             ast::ExprBreak(_) |
3528             ast::ExprAgain(_) |
3529             ast::ExprPath(_)  |
3530             ast::ExprQPath(_) => {}
3531
3532             ast::ExprCast(ref sub_exp, _)     |
3533             ast::ExprAddrOf(_, ref sub_exp)  |
3534             ast::ExprField(ref sub_exp, _) |
3535             ast::ExprTupField(ref sub_exp, _) |
3536             ast::ExprParen(ref sub_exp) =>
3537                 walk_expr(cx, &**sub_exp, scope_stack, scope_map),
3538
3539             ast::ExprBox(ref place, ref sub_expr) => {
3540                 place.as_ref().map(
3541                     |e| walk_expr(cx, &**e, scope_stack, scope_map));
3542                 walk_expr(cx, &**sub_expr, scope_stack, scope_map);
3543             }
3544
3545             ast::ExprRet(ref exp_opt) => match *exp_opt {
3546                 Some(ref sub_exp) => walk_expr(cx, &**sub_exp, scope_stack, scope_map),
3547                 None => ()
3548             },
3549
3550             ast::ExprUnary(_, ref sub_exp) => {
3551                 walk_expr(cx, &**sub_exp, scope_stack, scope_map);
3552             }
3553
3554             ast::ExprAssignOp(_, ref lhs, ref rhs) |
3555             ast::ExprIndex(ref lhs, ref rhs) |
3556             ast::ExprBinary(_, ref lhs, ref rhs)    => {
3557                 walk_expr(cx, &**lhs, scope_stack, scope_map);
3558                 walk_expr(cx, &**rhs, scope_stack, scope_map);
3559             }
3560
3561             ast::ExprRange(ref start, ref end) => {
3562                 start.as_ref().map(|e| walk_expr(cx, &**e, scope_stack, scope_map));
3563                 end.as_ref().map(|e| walk_expr(cx, &**e, scope_stack, scope_map));
3564             }
3565
3566             ast::ExprVec(ref init_expressions) |
3567             ast::ExprTup(ref init_expressions) => {
3568                 for ie in init_expressions.iter() {
3569                     walk_expr(cx, &**ie, scope_stack, scope_map);
3570                 }
3571             }
3572
3573             ast::ExprAssign(ref sub_exp1, ref sub_exp2) |
3574             ast::ExprRepeat(ref sub_exp1, ref sub_exp2) => {
3575                 walk_expr(cx, &**sub_exp1, scope_stack, scope_map);
3576                 walk_expr(cx, &**sub_exp2, scope_stack, scope_map);
3577             }
3578
3579             ast::ExprIf(ref cond_exp, ref then_block, ref opt_else_exp) => {
3580                 walk_expr(cx, &**cond_exp, scope_stack, scope_map);
3581
3582                 with_new_scope(cx,
3583                                then_block.span,
3584                                scope_stack,
3585                                scope_map,
3586                                |cx, scope_stack, scope_map| {
3587                     walk_block(cx, &**then_block, scope_stack, scope_map);
3588                 });
3589
3590                 match *opt_else_exp {
3591                     Some(ref else_exp) =>
3592                         walk_expr(cx, &**else_exp, scope_stack, scope_map),
3593                     _ => ()
3594                 }
3595             }
3596
3597             ast::ExprIfLet(..) => {
3598                 cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
3599                                               Found unexpanded if-let.");
3600             }
3601
3602             ast::ExprWhile(ref cond_exp, ref loop_body, _) => {
3603                 walk_expr(cx, &**cond_exp, scope_stack, scope_map);
3604
3605                 with_new_scope(cx,
3606                                loop_body.span,
3607                                scope_stack,
3608                                scope_map,
3609                                |cx, scope_stack, scope_map| {
3610                     walk_block(cx, &**loop_body, scope_stack, scope_map);
3611                 })
3612             }
3613
3614             ast::ExprWhileLet(..) => {
3615                 cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
3616                                               Found unexpanded while-let.");
3617             }
3618
3619             ast::ExprForLoop(ref pattern, ref head, ref body, _) => {
3620                 walk_expr(cx, &**head, scope_stack, scope_map);
3621
3622                 with_new_scope(cx,
3623                                exp.span,
3624                                scope_stack,
3625                                scope_map,
3626                                |cx, scope_stack, scope_map| {
3627                     scope_map.insert(exp.id,
3628                                      scope_stack.last()
3629                                                 .unwrap()
3630                                                 .scope_metadata);
3631                     walk_pattern(cx,
3632                                  &**pattern,
3633                                  scope_stack,
3634                                  scope_map);
3635                     walk_block(cx, &**body, scope_stack, scope_map);
3636                 })
3637             }
3638
3639             ast::ExprMac(_) => {
3640                 cx.sess().span_bug(exp.span, "debuginfo::create_scope_map() - \
3641                                               Found unexpanded macro.");
3642             }
3643
3644             ast::ExprLoop(ref block, _) |
3645             ast::ExprBlock(ref block)   => {
3646                 with_new_scope(cx,
3647                                block.span,
3648                                scope_stack,
3649                                scope_map,
3650                                |cx, scope_stack, scope_map| {
3651                     walk_block(cx, &**block, scope_stack, scope_map);
3652                 })
3653             }
3654
3655             ast::ExprClosure(_, _, ref decl, ref block) => {
3656                 with_new_scope(cx,
3657                                block.span,
3658                                scope_stack,
3659                                scope_map,
3660                                |cx, scope_stack, scope_map| {
3661                     for &ast::Arg { pat: ref pattern, .. } in decl.inputs.iter() {
3662                         walk_pattern(cx, &**pattern, scope_stack, scope_map);
3663                     }
3664
3665                     walk_block(cx, &**block, scope_stack, scope_map);
3666                 })
3667             }
3668
3669             ast::ExprCall(ref fn_exp, ref args) => {
3670                 walk_expr(cx, &**fn_exp, scope_stack, scope_map);
3671
3672                 for arg_exp in args.iter() {
3673                     walk_expr(cx, &**arg_exp, scope_stack, scope_map);
3674                 }
3675             }
3676
3677             ast::ExprMethodCall(_, _, ref args) => {
3678                 for arg_exp in args.iter() {
3679                     walk_expr(cx, &**arg_exp, scope_stack, scope_map);
3680                 }
3681             }
3682
3683             ast::ExprMatch(ref discriminant_exp, ref arms, _) => {
3684                 walk_expr(cx, &**discriminant_exp, scope_stack, scope_map);
3685
3686                 // For each arm we have to first walk the pattern as these might
3687                 // introduce new artificial scopes. It should be sufficient to
3688                 // walk only one pattern per arm, as they all must contain the
3689                 // same binding names.
3690
3691                 for arm_ref in arms.iter() {
3692                     let arm_span = arm_ref.pats[0].span;
3693
3694                     with_new_scope(cx,
3695                                    arm_span,
3696                                    scope_stack,
3697                                    scope_map,
3698                                    |cx, scope_stack, scope_map| {
3699                         for pat in arm_ref.pats.iter() {
3700                             walk_pattern(cx, &**pat, scope_stack, scope_map);
3701                         }
3702
3703                         for guard_exp in arm_ref.guard.iter() {
3704                             walk_expr(cx, &**guard_exp, scope_stack, scope_map)
3705                         }
3706
3707                         walk_expr(cx, &*arm_ref.body, scope_stack, scope_map);
3708                     })
3709                 }
3710             }
3711
3712             ast::ExprStruct(_, ref fields, ref base_exp) => {
3713                 for &ast::Field { expr: ref exp, .. } in fields.iter() {
3714                     walk_expr(cx, &**exp, scope_stack, scope_map);
3715                 }
3716
3717                 match *base_exp {
3718                     Some(ref exp) => walk_expr(cx, &**exp, scope_stack, scope_map),
3719                     None => ()
3720                 }
3721             }
3722
3723             ast::ExprInlineAsm(ast::InlineAsm { ref inputs,
3724                                                 ref outputs,
3725                                                 .. }) => {
3726                 // inputs, outputs: Vec<(String, P<Expr>)>
3727                 for &(_, ref exp) in inputs.iter() {
3728                     walk_expr(cx, &**exp, scope_stack, scope_map);
3729                 }
3730
3731                 for &(_, ref exp, _) in outputs.iter() {
3732                     walk_expr(cx, &**exp, scope_stack, scope_map);
3733                 }
3734             }
3735         }
3736     }
3737 }
3738
3739
3740 //=-----------------------------------------------------------------------------
3741 // Type Names for Debug Info
3742 //=-----------------------------------------------------------------------------
3743
3744 // Compute the name of the type as it should be stored in debuginfo. Does not do
3745 // any caching, i.e. calling the function twice with the same type will also do
3746 // the work twice. The `qualified` parameter only affects the first level of the
3747 // type name, further levels (i.e. type parameters) are always fully qualified.
3748 fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3749                                          t: Ty<'tcx>,
3750                                          qualified: bool)
3751                                          -> String {
3752     let mut result = String::with_capacity(64);
3753     push_debuginfo_type_name(cx, t, qualified, &mut result);
3754     result
3755 }
3756
3757 // Pushes the name of the type as it should be stored in debuginfo on the
3758 // `output` String. See also compute_debuginfo_type_name().
3759 fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3760                                       t: Ty<'tcx>,
3761                                       qualified: bool,
3762                                       output: &mut String) {
3763     match t.sty {
3764         ty::ty_bool              => output.push_str("bool"),
3765         ty::ty_char              => output.push_str("char"),
3766         ty::ty_str               => output.push_str("str"),
3767         ty::ty_int(ast::TyIs(_))     => output.push_str("isize"),
3768         ty::ty_int(ast::TyI8)    => output.push_str("i8"),
3769         ty::ty_int(ast::TyI16)   => output.push_str("i16"),
3770         ty::ty_int(ast::TyI32)   => output.push_str("i32"),
3771         ty::ty_int(ast::TyI64)   => output.push_str("i64"),
3772         ty::ty_uint(ast::TyUs(_))    => output.push_str("usize"),
3773         ty::ty_uint(ast::TyU8)   => output.push_str("u8"),
3774         ty::ty_uint(ast::TyU16)  => output.push_str("u16"),
3775         ty::ty_uint(ast::TyU32)  => output.push_str("u32"),
3776         ty::ty_uint(ast::TyU64)  => output.push_str("u64"),
3777         ty::ty_float(ast::TyF32) => output.push_str("f32"),
3778         ty::ty_float(ast::TyF64) => output.push_str("f64"),
3779         ty::ty_struct(def_id, substs) |
3780         ty::ty_enum(def_id, substs) => {
3781             push_item_name(cx, def_id, qualified, output);
3782             push_type_params(cx, substs, output);
3783         },
3784         ty::ty_tup(ref component_types) => {
3785             output.push('(');
3786             for &component_type in component_types.iter() {
3787                 push_debuginfo_type_name(cx, component_type, true, output);
3788                 output.push_str(", ");
3789             }
3790             if !component_types.is_empty() {
3791                 output.pop();
3792                 output.pop();
3793             }
3794             output.push(')');
3795         },
3796         ty::ty_uniq(inner_type) => {
3797             output.push_str("Box<");
3798             push_debuginfo_type_name(cx, inner_type, true, output);
3799             output.push('>');
3800         },
3801         ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => {
3802             output.push('*');
3803             match mutbl {
3804                 ast::MutImmutable => output.push_str("const "),
3805                 ast::MutMutable => output.push_str("mut "),
3806             }
3807
3808             push_debuginfo_type_name(cx, inner_type, true, output);
3809         },
3810         ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => {
3811             output.push('&');
3812             if mutbl == ast::MutMutable {
3813                 output.push_str("mut ");
3814             }
3815
3816             push_debuginfo_type_name(cx, inner_type, true, output);
3817         },
3818         ty::ty_vec(inner_type, optional_length) => {
3819             output.push('[');
3820             push_debuginfo_type_name(cx, inner_type, true, output);
3821
3822             match optional_length {
3823                 Some(len) => {
3824                     output.push_str(format!("; {}", len).as_slice());
3825                 }
3826                 None => { /* nothing to do */ }
3827             };
3828
3829             output.push(']');
3830         },
3831         ty::ty_trait(ref trait_data) => {
3832             let principal = ty::erase_late_bound_regions(cx.tcx(), &trait_data.principal);
3833             push_item_name(cx, principal.def_id, false, output);
3834             push_type_params(cx, principal.substs, output);
3835         },
3836         ty::ty_bare_fn(_, &ty::BareFnTy{ unsafety, abi, ref sig } ) => {
3837             if unsafety == ast::Unsafety::Unsafe {
3838                 output.push_str("unsafe ");
3839             }
3840
3841             if abi != ::syntax::abi::Rust {
3842                 output.push_str("extern \"");
3843                 output.push_str(abi.name());
3844                 output.push_str("\" ");
3845             }
3846
3847             output.push_str("fn(");
3848
3849             let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
3850             if sig.inputs.len() > 0 {
3851                 for &parameter_type in sig.inputs.iter() {
3852                     push_debuginfo_type_name(cx, parameter_type, true, output);
3853                     output.push_str(", ");
3854                 }
3855                 output.pop();
3856                 output.pop();
3857             }
3858
3859             if sig.variadic {
3860                 if sig.inputs.len() > 0 {
3861                     output.push_str(", ...");
3862                 } else {
3863                     output.push_str("...");
3864                 }
3865             }
3866
3867             output.push(')');
3868
3869             match sig.output {
3870                 ty::FnConverging(result_type) if ty::type_is_nil(result_type) => {}
3871                 ty::FnConverging(result_type) => {
3872                     output.push_str(" -> ");
3873                     push_debuginfo_type_name(cx, result_type, true, output);
3874                 }
3875                 ty::FnDiverging => {
3876                     output.push_str(" -> !");
3877                 }
3878             }
3879         },
3880         ty::ty_unboxed_closure(..) => {
3881             output.push_str("closure");
3882         }
3883         ty::ty_projection(ref projection) => {
3884             output.push_str("<");
3885             let self_ty = projection.trait_ref.self_ty();
3886             push_debuginfo_type_name(cx, self_ty, true, output);
3887
3888             output.push_str(" as ");
3889
3890             push_item_name(cx, projection.trait_ref.def_id, false, output);
3891             push_type_params(cx, projection.trait_ref.substs, output);
3892
3893             output.push_str(">::");
3894             output.push_str(token::get_name(projection.item_name).get());
3895         }
3896         ty::ty_err |
3897         ty::ty_infer(_) |
3898         ty::ty_open(_) |
3899         ty::ty_param(_) => {
3900             cx.sess().bug(&format!("debuginfo: Trying to create type name for \
3901                 unexpected type: {}", ppaux::ty_to_string(cx.tcx(), t))[]);
3902         }
3903     }
3904
3905     fn push_item_name(cx: &CrateContext,
3906                       def_id: ast::DefId,
3907                       qualified: bool,
3908                       output: &mut String) {
3909         ty::with_path(cx.tcx(), def_id, |mut path| {
3910             if qualified {
3911                 if def_id.krate == ast::LOCAL_CRATE {
3912                     output.push_str(crate_root_namespace(cx));
3913                     output.push_str("::");
3914                 }
3915
3916                 let mut path_element_count = 0u;
3917                 for path_element in path {
3918                     let name = token::get_name(path_element.name());
3919                     output.push_str(name.get());
3920                     output.push_str("::");
3921                     path_element_count += 1;
3922                 }
3923
3924                 if path_element_count == 0 {
3925                     cx.sess().bug("debuginfo: Encountered empty item path!");
3926                 }
3927
3928                 output.pop();
3929                 output.pop();
3930             } else {
3931                 let name = token::get_name(path.last()
3932                                                .expect("debuginfo: Empty item path?")
3933                                                .name());
3934                 output.push_str(name.get());
3935             }
3936         });
3937     }
3938
3939     // Pushes the type parameters in the given `Substs` to the output string.
3940     // This ignores region parameters, since they can't reliably be
3941     // reconstructed for items from non-local crates. For local crates, this
3942     // would be possible but with inlining and LTO we have to use the least
3943     // common denominator - otherwise we would run into conflicts.
3944     fn push_type_params<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
3945                                   substs: &subst::Substs<'tcx>,
3946                                   output: &mut String) {
3947         if substs.types.is_empty() {
3948             return;
3949         }
3950
3951         output.push('<');
3952
3953         for &type_parameter in substs.types.iter() {
3954             push_debuginfo_type_name(cx, type_parameter, true, output);
3955             output.push_str(", ");
3956         }
3957
3958         output.pop();
3959         output.pop();
3960
3961         output.push('>');
3962     }
3963 }
3964
3965
3966 //=-----------------------------------------------------------------------------
3967 // Namespace Handling
3968 //=-----------------------------------------------------------------------------
3969
3970 struct NamespaceTreeNode {
3971     name: ast::Name,
3972     scope: DIScope,
3973     parent: Option<Weak<NamespaceTreeNode>>,
3974 }
3975
3976 impl NamespaceTreeNode {
3977     fn mangled_name_of_contained_item(&self, item_name: &str) -> String {
3978         fn fill_nested(node: &NamespaceTreeNode, output: &mut String) {
3979             match node.parent {
3980                 Some(ref parent) => fill_nested(&*parent.upgrade().unwrap(), output),
3981                 None => {}
3982             }
3983             let string = token::get_name(node.name);
3984             output.push_str(&format!("{}", string.get().len())[]);
3985             output.push_str(string.get());
3986         }
3987
3988         let mut name = String::from_str("_ZN");
3989         fill_nested(self, &mut name);
3990         name.push_str(&format!("{}", item_name.len())[]);
3991         name.push_str(item_name);
3992         name.push('E');
3993         name
3994     }
3995 }
3996
3997 fn crate_root_namespace<'a>(cx: &'a CrateContext) -> &'a str {
3998     &cx.link_meta().crate_name[]
3999 }
4000
4001 fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTreeNode> {
4002     ty::with_path(cx.tcx(), def_id, |path| {
4003         // prepend crate name if not already present
4004         let krate = if def_id.krate == ast::LOCAL_CRATE {
4005             let crate_namespace_ident = token::str_to_ident(crate_root_namespace(cx));
4006             Some(ast_map::PathMod(crate_namespace_ident.name))
4007         } else {
4008             None
4009         };
4010         let mut path = krate.into_iter().chain(path).peekable();
4011
4012         let mut current_key = Vec::new();
4013         let mut parent_node: Option<Rc<NamespaceTreeNode>> = None;
4014
4015         // Create/Lookup namespace for each element of the path.
4016         loop {
4017             // Emulate a for loop so we can use peek below.
4018             let path_element = match path.next() {
4019                 Some(e) => e,
4020                 None => break
4021             };
4022             // Ignore the name of the item (the last path element).
4023             if path.peek().is_none() {
4024                 break;
4025             }
4026
4027             let name = path_element.name();
4028             current_key.push(name);
4029
4030             let existing_node = debug_context(cx).namespace_map.borrow()
4031                                                  .get(&current_key).cloned();
4032             let current_node = match existing_node {
4033                 Some(existing_node) => existing_node,
4034                 None => {
4035                     // create and insert
4036                     let parent_scope = match parent_node {
4037                         Some(ref node) => node.scope,
4038                         None => ptr::null_mut()
4039                     };
4040                     let namespace_name = token::get_name(name);
4041                     let namespace_name = CString::from_slice(namespace_name
4042                                                                 .get().as_bytes());
4043                     let scope = unsafe {
4044                         llvm::LLVMDIBuilderCreateNameSpace(
4045                             DIB(cx),
4046                             parent_scope,
4047                             namespace_name.as_ptr(),
4048                             // cannot reconstruct file ...
4049                             ptr::null_mut(),
4050                             // ... or line information, but that's not so important.
4051                             0)
4052                     };
4053
4054                     let node = Rc::new(NamespaceTreeNode {
4055                         name: name,
4056                         scope: scope,
4057                         parent: parent_node.map(|parent| parent.downgrade()),
4058                     });
4059
4060                     debug_context(cx).namespace_map.borrow_mut()
4061                                      .insert(current_key.clone(), node.clone());
4062
4063                     node
4064                 }
4065             };
4066
4067             parent_node = Some(current_node);
4068         }
4069
4070         match parent_node {
4071             Some(node) => node,
4072             None => {
4073                 cx.sess().bug(&format!("debuginfo::namespace_for_item(): \
4074                                        path too short for {:?}",
4075                                       def_id)[]);
4076             }
4077         }
4078     })
4079 }
4080
4081
4082 //=-----------------------------------------------------------------------------
4083 // .debug_gdb_scripts binary section
4084 //=-----------------------------------------------------------------------------
4085
4086 /// Inserts a side-effect free instruction sequence that makes sure that the
4087 /// .debug_gdb_scripts global is referenced, so it isn't removed by the linker.
4088 pub fn insert_reference_to_gdb_debug_scripts_section_global(ccx: &CrateContext) {
4089     if needs_gdb_debug_scripts_section(ccx) {
4090         let empty = CString::from_slice(b"");
4091         let gdb_debug_scripts_section_global =
4092             get_or_insert_gdb_debug_scripts_section_global(ccx);
4093         unsafe {
4094             let volative_load_instruction =
4095                 llvm::LLVMBuildLoad(ccx.raw_builder(),
4096                                     gdb_debug_scripts_section_global,
4097                                     empty.as_ptr());
4098             llvm::LLVMSetVolatile(volative_load_instruction, llvm::True);
4099         }
4100     }
4101 }
4102
4103 /// Allocates the global variable responsible for the .debug_gdb_scripts binary
4104 /// section.
4105 fn get_or_insert_gdb_debug_scripts_section_global(ccx: &CrateContext)
4106                                                   -> llvm::ValueRef {
4107     let section_var_name = b"__rustc_debug_gdb_scripts_section__\0";
4108
4109     let section_var = unsafe {
4110         llvm::LLVMGetNamedGlobal(ccx.llmod(),
4111                                  section_var_name.as_ptr() as *const _)
4112     };
4113
4114     if section_var == ptr::null_mut() {
4115         let section_name = b".debug_gdb_scripts\0";
4116         let section_contents = b"\x01gdb_load_rust_pretty_printers.py\0";
4117
4118         unsafe {
4119             let llvm_type = Type::array(&Type::i8(ccx),
4120                                         section_contents.len() as u64);
4121             let section_var = llvm::LLVMAddGlobal(ccx.llmod(),
4122                                                   llvm_type.to_ref(),
4123                                                   section_var_name.as_ptr()
4124                                                     as *const _);
4125             llvm::LLVMSetSection(section_var, section_name.as_ptr() as *const _);
4126             llvm::LLVMSetInitializer(section_var, C_bytes(ccx, section_contents));
4127             llvm::LLVMSetGlobalConstant(section_var, llvm::True);
4128             llvm::LLVMSetUnnamedAddr(section_var, llvm::True);
4129             llvm::SetLinkage(section_var, llvm::Linkage::LinkOnceODRLinkage);
4130             // This should make sure that the whole section is not larger than
4131             // the string it contains. Otherwise we get a warning from GDB.
4132             llvm::LLVMSetAlignment(section_var, 1);
4133             section_var
4134         }
4135     } else {
4136         section_var
4137     }
4138 }
4139
4140 fn needs_gdb_debug_scripts_section(ccx: &CrateContext) -> bool {
4141     let omit_gdb_pretty_printer_section =
4142         attr::contains_name(ccx.tcx()
4143                                .map
4144                                .krate()
4145                                .attrs
4146                                .as_slice(),
4147                             "omit_gdb_pretty_printer_section");
4148
4149     !omit_gdb_pretty_printer_section &&
4150     !ccx.sess().target.target.options.is_like_osx &&
4151     !ccx.sess().target.target.options.is_like_windows &&
4152     ccx.sess().opts.debuginfo != NoDebugInfo
4153 }
4154