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