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