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