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