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