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