fix build
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/DataTypes.h"
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Module.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/Support/Dwarf.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Target/TargetMachine.h"
25
26 #include <iostream>
27
28 using namespace llvm;
29
30 static cl::opt<bool>
31 DwarfVerbose("dwarf-verbose", cl::Hidden,
32                                 cl::desc("Add comments to Dwarf directives."));
33
34 //===----------------------------------------------------------------------===//
35
36 /// TagString - Return the string for the specified tag.
37 ///
38 static const char *TagString(unsigned Tag) {
39   switch(Tag) {
40     case DW_TAG_array_type:                return "TAG_array_type";
41     case DW_TAG_class_type:                return "TAG_class_type";
42     case DW_TAG_entry_point:               return "TAG_entry_point";
43     case DW_TAG_enumeration_type:          return "TAG_enumeration_type";
44     case DW_TAG_formal_parameter:          return "TAG_formal_parameter";
45     case DW_TAG_imported_declaration:      return "TAG_imported_declaration";
46     case DW_TAG_label:                     return "TAG_label";
47     case DW_TAG_lexical_block:             return "TAG_lexical_block";
48     case DW_TAG_member:                    return "TAG_member";
49     case DW_TAG_pointer_type:              return "TAG_pointer_type";
50     case DW_TAG_reference_type:            return "TAG_reference_type";
51     case DW_TAG_compile_unit:              return "TAG_compile_unit";
52     case DW_TAG_string_type:               return "TAG_string_type";
53     case DW_TAG_structure_type:            return "TAG_structure_type";
54     case DW_TAG_subroutine_type:           return "TAG_subroutine_type";
55     case DW_TAG_typedef:                   return "TAG_typedef";
56     case DW_TAG_union_type:                return "TAG_union_type";
57     case DW_TAG_unspecified_parameters:    return "TAG_unspecified_parameters";
58     case DW_TAG_variant:                   return "TAG_variant";
59     case DW_TAG_common_block:              return "TAG_common_block";
60     case DW_TAG_common_inclusion:          return "TAG_common_inclusion";
61     case DW_TAG_inheritance:               return "TAG_inheritance";
62     case DW_TAG_inlined_subroutine:        return "TAG_inlined_subroutine";
63     case DW_TAG_module:                    return "TAG_module";
64     case DW_TAG_ptr_to_member_type:        return "TAG_ptr_to_member_type";
65     case DW_TAG_set_type:                  return "TAG_set_type";
66     case DW_TAG_subrange_type:             return "TAG_subrange_type";
67     case DW_TAG_with_stmt:                 return "TAG_with_stmt";
68     case DW_TAG_access_declaration:        return "TAG_access_declaration";
69     case DW_TAG_base_type:                 return "TAG_base_type";
70     case DW_TAG_catch_block:               return "TAG_catch_block";
71     case DW_TAG_const_type:                return "TAG_const_type";
72     case DW_TAG_constant:                  return "TAG_constant";
73     case DW_TAG_enumerator:                return "TAG_enumerator";
74     case DW_TAG_file_type:                 return "TAG_file_type";
75     case DW_TAG_friend:                    return "TAG_friend";
76     case DW_TAG_namelist:                  return "TAG_namelist";
77     case DW_TAG_namelist_item:             return "TAG_namelist_item";
78     case DW_TAG_packed_type:               return "TAG_packed_type";
79     case DW_TAG_subprogram:                return "TAG_subprogram";
80     case DW_TAG_template_type_parameter:   return "TAG_template_type_parameter";
81     case DW_TAG_template_value_parameter: return "TAG_template_value_parameter";
82     case DW_TAG_thrown_type:               return "TAG_thrown_type";
83     case DW_TAG_try_block:                 return "TAG_try_block";
84     case DW_TAG_variant_part:              return "TAG_variant_part";
85     case DW_TAG_variable:                  return "TAG_variable";
86     case DW_TAG_volatile_type:             return "TAG_volatile_type";
87     case DW_TAG_dwarf_procedure:           return "TAG_dwarf_procedure";
88     case DW_TAG_restrict_type:             return "TAG_restrict_type";
89     case DW_TAG_interface_type:            return "TAG_interface_type";
90     case DW_TAG_namespace:                 return "TAG_namespace";
91     case DW_TAG_imported_module:           return "TAG_imported_module";
92     case DW_TAG_unspecified_type:          return "TAG_unspecified_type";
93     case DW_TAG_partial_unit:              return "TAG_partial_unit";
94     case DW_TAG_imported_unit:             return "TAG_imported_unit";
95     case DW_TAG_condition:                 return "TAG_condition";
96     case DW_TAG_shared_type:               return "TAG_shared_type";
97     case DW_TAG_lo_user:                   return "TAG_lo_user";
98     case DW_TAG_hi_user:                   return "TAG_hi_user";
99   }
100   assert(0 && "Unknown Dwarf Tag");
101   return "";
102 }
103
104 /// ChildrenString - Return the string for the specified children flag.
105 ///
106 static const char *ChildrenString(unsigned Children) {
107   switch(Children) {
108     case DW_CHILDREN_no:                   return "CHILDREN_no";
109     case DW_CHILDREN_yes:                  return "CHILDREN_yes";
110   }
111   assert(0 && "Unknown Dwarf ChildrenFlag");
112   return "";
113 }
114
115 /// AttributeString - Return the string for the specified attribute.
116 ///
117 static const char *AttributeString(unsigned Attribute) {
118   switch(Attribute) {
119     case DW_AT_sibling:                    return "AT_sibling";
120     case DW_AT_location:                   return "AT_location";
121     case DW_AT_name:                       return "AT_name";
122     case DW_AT_ordering:                   return "AT_ordering";
123     case DW_AT_byte_size:                  return "AT_byte_size";
124     case DW_AT_bit_offset:                 return "AT_bit_offset";
125     case DW_AT_bit_size:                   return "AT_bit_size";
126     case DW_AT_stmt_list:                  return "AT_stmt_list";
127     case DW_AT_low_pc:                     return "AT_low_pc";
128     case DW_AT_high_pc:                    return "AT_high_pc";
129     case DW_AT_language:                   return "AT_language";
130     case DW_AT_discr:                      return "AT_discr";
131     case DW_AT_discr_value:                return "AT_discr_value";
132     case DW_AT_visibility:                 return "AT_visibility";
133     case DW_AT_import:                     return "AT_import";
134     case DW_AT_string_length:              return "AT_string_length";
135     case DW_AT_common_reference:           return "AT_common_reference";
136     case DW_AT_comp_dir:                   return "AT_comp_dir";
137     case DW_AT_const_value:                return "AT_const_value";
138     case DW_AT_containing_type:            return "AT_containing_type";
139     case DW_AT_default_value:              return "AT_default_value";
140     case DW_AT_inline:                     return "AT_inline";
141     case DW_AT_is_optional:                return "AT_is_optional";
142     case DW_AT_lower_bound:                return "AT_lower_bound";
143     case DW_AT_producer:                   return "AT_producer";
144     case DW_AT_prototyped:                 return "AT_prototyped";
145     case DW_AT_return_addr:                return "AT_return_addr";
146     case DW_AT_start_scope:                return "AT_start_scope";
147     case DW_AT_bit_stride:                 return "AT_bit_stride";
148     case DW_AT_upper_bound:                return "AT_upper_bound";
149     case DW_AT_abstract_origin:            return "AT_abstract_origin";
150     case DW_AT_accessibility:              return "AT_accessibility";
151     case DW_AT_address_class:              return "AT_address_class";
152     case DW_AT_artificial:                 return "AT_artificial";
153     case DW_AT_base_types:                 return "AT_base_types";
154     case DW_AT_calling_convention:         return "AT_calling_convention";
155     case DW_AT_count:                      return "AT_count";
156     case DW_AT_data_member_location:       return "AT_data_member_location";
157     case DW_AT_decl_column:                return "AT_decl_column";
158     case DW_AT_decl_file:                  return "AT_decl_file";
159     case DW_AT_decl_line:                  return "AT_decl_line";
160     case DW_AT_declaration:                return "AT_declaration";
161     case DW_AT_discr_list:                 return "AT_discr_list";
162     case DW_AT_encoding:                   return "AT_encoding";
163     case DW_AT_external:                   return "AT_external";
164     case DW_AT_frame_base:                 return "AT_frame_base";
165     case DW_AT_friend:                     return "AT_friend";
166     case DW_AT_identifier_case:            return "AT_identifier_case";
167     case DW_AT_macro_info:                 return "AT_macro_info";
168     case DW_AT_namelist_item:              return "AT_namelist_item";
169     case DW_AT_priority:                   return "AT_priority";
170     case DW_AT_segment:                    return "AT_segment";
171     case DW_AT_specification:              return "AT_specification";
172     case DW_AT_static_link:                return "AT_static_link";
173     case DW_AT_type:                       return "AT_type";
174     case DW_AT_use_location:               return "AT_use_location";
175     case DW_AT_variable_parameter:         return "AT_variable_parameter";
176     case DW_AT_virtuality:                 return "AT_virtuality";
177     case DW_AT_vtable_elem_location:       return "AT_vtable_elem_location";
178     case DW_AT_allocated:                  return "AT_allocated";
179     case DW_AT_associated:                 return "AT_associated";
180     case DW_AT_data_location:              return "AT_data_location";
181     case DW_AT_byte_stride:                return "AT_byte_stride";
182     case DW_AT_entry_pc:                   return "AT_entry_pc";
183     case DW_AT_use_UTF8:                   return "AT_use_UTF8";
184     case DW_AT_extension:                  return "AT_extension";
185     case DW_AT_ranges:                     return "AT_ranges";
186     case DW_AT_trampoline:                 return "AT_trampoline";
187     case DW_AT_call_column:                return "AT_call_column";
188     case DW_AT_call_file:                  return "AT_call_file";
189     case DW_AT_call_line:                  return "AT_call_line";
190     case DW_AT_description:                return "AT_description";
191     case DW_AT_binary_scale:               return "AT_binary_scale";
192     case DW_AT_decimal_scale:              return "AT_decimal_scale";
193     case DW_AT_small:                      return "AT_small";
194     case DW_AT_decimal_sign:               return "AT_decimal_sign";
195     case DW_AT_digit_count:                return "AT_digit_count";
196     case DW_AT_picture_string:             return "AT_picture_string";
197     case DW_AT_mutable:                    return "AT_mutable";
198     case DW_AT_threads_scaled:             return "AT_threads_scaled";
199     case DW_AT_explicit:                   return "AT_explicit";
200     case DW_AT_object_pointer:             return "AT_object_pointer";
201     case DW_AT_endianity:                  return "AT_endianity";
202     case DW_AT_elemental:                  return "AT_elemental";
203     case DW_AT_pure:                       return "AT_pure";
204     case DW_AT_recursive:                  return "AT_recursive";
205     case DW_AT_lo_user:                    return "AT_lo_user";
206     case DW_AT_hi_user:                    return "AT_hi_user";
207   }
208   assert(0 && "Unknown Dwarf Attribute");
209   return "";
210 }
211
212 /// FormEncodingString - Return the string for the specified form encoding.
213 ///
214 static const char *FormEncodingString(unsigned Encoding) {
215   switch(Encoding) {
216     case DW_FORM_addr:                     return "FORM_addr";
217     case DW_FORM_block2:                   return "FORM_block2";
218     case DW_FORM_block4:                   return "FORM_block4";
219     case DW_FORM_data2:                    return "FORM_data2";
220     case DW_FORM_data4:                    return "FORM_data4";
221     case DW_FORM_data8:                    return "FORM_data8";
222     case DW_FORM_string:                   return "FORM_string";
223     case DW_FORM_block:                    return "FORM_block";
224     case DW_FORM_block1:                   return "FORM_block1";
225     case DW_FORM_data1:                    return "FORM_data1";
226     case DW_FORM_flag:                     return "FORM_flag";
227     case DW_FORM_sdata:                    return "FORM_sdata";
228     case DW_FORM_strp:                     return "FORM_strp";
229     case DW_FORM_udata:                    return "FORM_udata";
230     case DW_FORM_ref_addr:                 return "FORM_ref_addr";
231     case DW_FORM_ref1:                     return "FORM_ref1";
232     case DW_FORM_ref2:                     return "FORM_ref2";
233     case DW_FORM_ref4:                     return "FORM_ref4";
234     case DW_FORM_ref8:                     return "FORM_ref8";
235     case DW_FORM_ref_udata:                return "FORM_ref_udata";
236     case DW_FORM_indirect:                 return "FORM_indirect";
237   }
238   assert(0 && "Unknown Dwarf Form Encoding");
239   return "";
240 }
241
242 /// OperationEncodingString - Return the string for the specified operation
243 /// encoding.
244 static const char *OperationEncodingString(unsigned Encoding) {
245   switch(Encoding) {
246     case DW_OP_addr:                       return "OP_addr";
247     case DW_OP_deref:                      return "OP_deref";
248     case DW_OP_const1u:                    return "OP_const1u";
249     case DW_OP_const1s:                    return "OP_const1s";
250     case DW_OP_const2u:                    return "OP_const2u";
251     case DW_OP_const2s:                    return "OP_const2s";
252     case DW_OP_const4u:                    return "OP_const4u";
253     case DW_OP_const4s:                    return "OP_const4s";
254     case DW_OP_const8u:                    return "OP_const8u";
255     case DW_OP_const8s:                    return "OP_const8s";
256     case DW_OP_constu:                     return "OP_constu";
257     case DW_OP_consts:                     return "OP_consts";
258     case DW_OP_dup:                        return "OP_dup";
259     case DW_OP_drop:                       return "OP_drop";
260     case DW_OP_over:                       return "OP_over";
261     case DW_OP_pick:                       return "OP_pick";
262     case DW_OP_swap:                       return "OP_swap";
263     case DW_OP_rot:                        return "OP_rot";
264     case DW_OP_xderef:                     return "OP_xderef";
265     case DW_OP_abs:                        return "OP_abs";
266     case DW_OP_and:                        return "OP_and";
267     case DW_OP_div:                        return "OP_div";
268     case DW_OP_minus:                      return "OP_minus";
269     case DW_OP_mod:                        return "OP_mod";
270     case DW_OP_mul:                        return "OP_mul";
271     case DW_OP_neg:                        return "OP_neg";
272     case DW_OP_not:                        return "OP_not";
273     case DW_OP_or:                         return "OP_or";
274     case DW_OP_plus:                       return "OP_plus";
275     case DW_OP_plus_uconst:                return "OP_plus_uconst";
276     case DW_OP_shl:                        return "OP_shl";
277     case DW_OP_shr:                        return "OP_shr";
278     case DW_OP_shra:                       return "OP_shra";
279     case DW_OP_xor:                        return "OP_xor";
280     case DW_OP_skip:                       return "OP_skip";
281     case DW_OP_bra:                        return "OP_bra";
282     case DW_OP_eq:                         return "OP_eq";
283     case DW_OP_ge:                         return "OP_ge";
284     case DW_OP_gt:                         return "OP_gt";
285     case DW_OP_le:                         return "OP_le";
286     case DW_OP_lt:                         return "OP_lt";
287     case DW_OP_ne:                         return "OP_ne";
288     case DW_OP_lit0:                       return "OP_lit0";
289     case DW_OP_lit1:                       return "OP_lit1";
290     case DW_OP_lit31:                      return "OP_lit31";
291     case DW_OP_reg0:                       return "OP_reg0";
292     case DW_OP_reg1:                       return "OP_reg1";
293     case DW_OP_reg31:                      return "OP_reg31";
294     case DW_OP_breg0:                      return "OP_breg0";
295     case DW_OP_breg1:                      return "OP_breg1";
296     case DW_OP_breg31:                     return "OP_breg31";
297     case DW_OP_regx:                       return "OP_regx";
298     case DW_OP_fbreg:                      return "OP_fbreg";
299     case DW_OP_bregx:                      return "OP_bregx";
300     case DW_OP_piece:                      return "OP_piece";
301     case DW_OP_deref_size:                 return "OP_deref_size";
302     case DW_OP_xderef_size:                return "OP_xderef_size";
303     case DW_OP_nop:                        return "OP_nop";
304     case DW_OP_push_object_address:        return "OP_push_object_address";
305     case DW_OP_call2:                      return "OP_call2";
306     case DW_OP_call4:                      return "OP_call4";
307     case DW_OP_call_ref:                   return "OP_call_ref";
308     case DW_OP_form_tls_address:           return "OP_form_tls_address";
309     case DW_OP_call_frame_cfa:             return "OP_call_frame_cfa";
310     case DW_OP_lo_user:                    return "OP_lo_user";
311     case DW_OP_hi_user:                    return "OP_hi_user";
312   }
313   assert(0 && "Unknown Dwarf Operation Encoding");
314   return "";
315 }
316
317 /// AttributeEncodingString - Return the string for the specified attribute
318 /// encoding.
319 static const char *AttributeEncodingString(unsigned Encoding) {
320   switch(Encoding) {
321     case DW_ATE_address:                   return "ATE_address";
322     case DW_ATE_boolean:                   return "ATE_boolean";
323     case DW_ATE_complex_float:             return "ATE_complex_float";
324     case DW_ATE_float:                     return "ATE_float";
325     case DW_ATE_signed:                    return "ATE_signed";
326     case DW_ATE_signed_char:               return "ATE_signed_char";
327     case DW_ATE_unsigned:                  return "ATE_unsigned";
328     case DW_ATE_unsigned_char:             return "ATE_unsigned_char";
329     case DW_ATE_imaginary_float:           return "ATE_imaginary_float";
330     case DW_ATE_packed_decimal:            return "ATE_packed_decimal";
331     case DW_ATE_numeric_string:            return "ATE_numeric_string";
332     case DW_ATE_edited:                    return "ATE_edited";
333     case DW_ATE_signed_fixed:              return "ATE_signed_fixed";
334     case DW_ATE_unsigned_fixed:            return "ATE_unsigned_fixed";
335     case DW_ATE_decimal_float:             return "ATE_decimal_float";
336     case DW_ATE_lo_user:                   return "ATE_lo_user";
337     case DW_ATE_hi_user:                   return "ATE_hi_user";
338   }
339   assert(0 && "Unknown Dwarf Attribute Encoding");
340   return "";
341 }
342
343 /// DecimalSignString - Return the string for the specified decimal sign
344 /// attribute.
345 static const char *DecimalSignString(unsigned Sign) {
346   switch(Sign) {
347     case DW_DS_unsigned:                   return "DS_unsigned";
348     case DW_DS_leading_overpunch:          return "DS_leading_overpunch";
349     case DW_DS_trailing_overpunch:         return "DS_trailing_overpunch";
350     case DW_DS_leading_separate:           return "DS_leading_separate";
351     case DW_DS_trailing_separate:          return "DS_trailing_separate";
352   }
353   assert(0 && "Unknown Dwarf Decimal Sign Attribute");
354   return "";
355 }
356
357 /// EndianityString - Return the string for the specified endianity.
358 ///
359 static const char *EndianityString(unsigned Endian) {
360   switch(Endian) {
361     case DW_END_default:                   return "END_default";
362     case DW_END_big:                       return "END_big";
363     case DW_END_little:                    return "END_little";
364     case DW_END_lo_user:                   return "END_lo_user";
365     case DW_END_hi_user:                   return "END_hi_user";
366   }
367   assert(0 && "Unknown Dwarf Endianity");
368   return "";
369 }
370
371 /// AccessibilityString - Return the string for the specified accessibility.
372 ///
373 static const char *AccessibilityString(unsigned Access) {
374   switch(Access) {
375     // Accessibility codes
376     case DW_ACCESS_public:                 return "ACCESS_public";
377     case DW_ACCESS_protected:              return "ACCESS_protected";
378     case DW_ACCESS_private:                return "ACCESS_private";
379   }
380   assert(0 && "Unknown Dwarf Accessibility");
381   return "";
382 }
383
384 /// VisibilityString - Return the string for the specified visibility.
385 ///
386 static const char *VisibilityString(unsigned Visibility) {
387   switch(Visibility) {
388     case DW_VIS_local:                     return "VIS_local";
389     case DW_VIS_exported:                  return "VIS_exported";
390     case DW_VIS_qualified:                 return "VIS_qualified";
391   }
392   assert(0 && "Unknown Dwarf Visibility");
393   return "";
394 }
395
396 /// VirtualityString - Return the string for the specified virtuality.
397 ///
398 static const char *VirtualityString(unsigned Virtuality) {
399   switch(Virtuality) {
400     case DW_VIRTUALITY_none:               return "VIRTUALITY_none";
401     case DW_VIRTUALITY_virtual:            return "VIRTUALITY_virtual";
402     case DW_VIRTUALITY_pure_virtual:       return "VIRTUALITY_pure_virtual";
403   }
404   assert(0 && "Unknown Dwarf Virtuality");
405   return "";
406 }
407
408 /// LanguageString - Return the string for the specified language.
409 ///
410 static const char *LanguageString(unsigned Language) {
411   switch(Language) {
412     case DW_LANG_C89:                      return "LANG_C89";
413     case DW_LANG_C:                        return "LANG_C";
414     case DW_LANG_Ada83:                    return "LANG_Ada83";
415     case DW_LANG_C_plus_plus:              return "LANG_C_plus_plus";
416     case DW_LANG_Cobol74:                  return "LANG_Cobol74";
417     case DW_LANG_Cobol85:                  return "LANG_Cobol85";
418     case DW_LANG_Fortran77:                return "LANG_Fortran77";
419     case DW_LANG_Fortran90:                return "LANG_Fortran90";
420     case DW_LANG_Pascal83:                 return "LANG_Pascal83";
421     case DW_LANG_Modula2:                  return "LANG_Modula2";
422     case DW_LANG_Java:                     return "LANG_Java";
423     case DW_LANG_C99:                      return "LANG_C99";
424     case DW_LANG_Ada95:                    return "LANG_Ada95";
425     case DW_LANG_Fortran95:                return "LANG_Fortran95";
426     case DW_LANG_PLI:                      return "LANG_PLI";
427     case DW_LANG_ObjC:                     return "LANG_ObjC";
428     case DW_LANG_ObjC_plus_plus:           return "LANG_ObjC_plus_plus";
429     case DW_LANG_UPC:                      return "LANG_UPC";
430     case DW_LANG_D:                        return "LANG_D";
431     case DW_LANG_lo_user:                  return "LANG_lo_user";
432     case DW_LANG_hi_user:                  return "LANG_hi_user";
433   }
434   assert(0 && "Unknown Dwarf Language");
435   return "";
436 }
437
438 /// CaseString - Return the string for the specified identifier case.
439 ///
440 static const char *CaseString(unsigned Case) {
441    switch(Case) {
442     case DW_ID_case_sensitive:             return "ID_case_sensitive";
443     case DW_ID_up_case:                    return "ID_up_case";
444     case DW_ID_down_case:                  return "ID_down_case";
445     case DW_ID_case_insensitive:           return "ID_case_insensitive";
446   }
447   assert(0 && "Unknown Dwarf Identifier Case");
448   return "";
449 }
450
451 /// ConventionString - Return the string for the specified calling convention.
452 ///
453 static const char *ConventionString(unsigned Convention) {
454    switch(Convention) {
455     case DW_CC_normal:                     return "CC_normal";
456     case DW_CC_program:                    return "CC_program";
457     case DW_CC_nocall:                     return "CC_nocall";
458     case DW_CC_lo_user:                    return "CC_lo_user";
459     case DW_CC_hi_user:                    return "CC_hi_user";
460   }
461   assert(0 && "Unknown Dwarf Calling Convention");
462   return "";
463 }
464
465 /// InlineCodeString - Return the string for the specified inline code.
466 ///
467 static const char *InlineCodeString(unsigned Code) {
468    switch(Code) {
469     case DW_INL_not_inlined:               return "INL_not_inlined";
470     case DW_INL_inlined:                   return "INL_inlined";
471     case DW_INL_declared_not_inlined:      return "INL_declared_not_inlined";
472     case DW_INL_declared_inlined:          return "INL_declared_inlined";
473   }
474   assert(0 && "Unknown Dwarf Inline Code");
475   return "";
476 }
477
478 /// ArrayOrderString - Return the string for the specified array order.
479 ///
480 static const char *ArrayOrderString(unsigned Order) {
481    switch(Order) {
482     case DW_ORD_row_major:                 return "ORD_row_major";
483     case DW_ORD_col_major:                 return "ORD_col_major";
484   }
485   assert(0 && "Unknown Dwarf Array Order");
486   return "";
487 }
488
489 /// DiscriminantString - Return the string for the specified discriminant
490 /// descriptor.
491 static const char *DiscriminantString(unsigned Discriminant) {
492    switch(Discriminant) {
493     case DW_DSC_label:                     return "DSC_label";
494     case DW_DSC_range:                     return "DSC_range";
495   }
496   assert(0 && "Unknown Dwarf Discriminant Descriptor");
497   return "";
498 }
499
500 /// LNStandardString - Return the string for the specified line number standard.
501 ///
502 static const char *LNStandardString(unsigned Standard) {
503    switch(Standard) {
504     case DW_LNS_copy:                      return "LNS_copy";
505     case DW_LNS_advance_pc:                return "LNS_advance_pc";
506     case DW_LNS_advance_line:              return "LNS_advance_line";
507     case DW_LNS_set_file:                  return "LNS_set_file";
508     case DW_LNS_set_column:                return "LNS_set_column";
509     case DW_LNS_negate_stmt:               return "LNS_negate_stmt";
510     case DW_LNS_set_basic_block:           return "LNS_set_basic_block";
511     case DW_LNS_const_add_pc:              return "LNS_const_add_pc";
512     case DW_LNS_fixed_advance_pc:          return "LNS_fixed_advance_pc";
513     case DW_LNS_set_prologue_end:          return "LNS_set_prologue_end";
514     case DW_LNS_set_epilogue_begin:        return "LNS_set_epilogue_begin";
515     case DW_LNS_set_isa:                   return "LNS_set_isa";
516   }
517   assert(0 && "Unknown Dwarf Line Number Standard");
518   return "";
519 }
520
521 /// LNExtendedString - Return the string for the specified line number extended
522 /// opcode encodings.
523 static const char *LNExtendedString(unsigned Encoding) {
524    switch(Encoding) {
525     // Line Number Extended Opcode Encodings
526     case DW_LNE_end_sequence:              return "LNE_end_sequence";
527     case DW_LNE_set_address:               return "LNE_set_address";
528     case DW_LNE_define_file:               return "LNE_define_file";
529     case DW_LNE_lo_user:                   return "LNE_lo_user";
530     case DW_LNE_hi_user:                   return "LNE_hi_user";
531   }
532   assert(0 && "Unknown Dwarf Line Number Extended Opcode Encoding");
533   return "";
534 }
535
536 /// MacinfoString - Return the string for the specified macinfo type encodings.
537 ///
538 static const char *MacinfoString(unsigned Encoding) {
539    switch(Encoding) {
540     // Macinfo Type Encodings
541     case DW_MACINFO_define:                return "MACINFO_define";
542     case DW_MACINFO_undef:                 return "MACINFO_undef";
543     case DW_MACINFO_start_file:            return "MACINFO_start_file";
544     case DW_MACINFO_end_file:              return "MACINFO_end_file";
545     case DW_MACINFO_vendor_ext:            return "MACINFO_vendor_ext";
546   }
547   assert(0 && "Unknown Dwarf Macinfo Type Encodings");
548   return "";
549 }
550
551 /// CallFrameString - Return the string for the specified call frame instruction
552 /// encodings.
553 static const char *CallFrameString(unsigned Encoding) {
554    switch(Encoding) {
555     case DW_CFA_advance_loc:               return "CFA_advance_loc";
556     case DW_CFA_offset:                    return "CFA_offset";
557     case DW_CFA_restore:                   return "CFA_restore";
558     case DW_CFA_set_loc:                   return "CFA_set_loc";
559     case DW_CFA_advance_loc1:              return "CFA_advance_loc1";
560     case DW_CFA_advance_loc2:              return "CFA_advance_loc2";
561     case DW_CFA_advance_loc4:              return "CFA_advance_loc4";
562     case DW_CFA_offset_extended:           return "CFA_offset_extended";
563     case DW_CFA_restore_extended:          return "CFA_restore_extended";
564     case DW_CFA_undefined:                 return "CFA_undefined";
565     case DW_CFA_same_value:                return "CFA_same_value";
566     case DW_CFA_register:                  return "CFA_register";
567     case DW_CFA_remember_state:            return "CFA_remember_state";
568     case DW_CFA_restore_state:             return "CFA_restore_state";
569     case DW_CFA_def_cfa:                   return "CFA_def_cfa";
570     case DW_CFA_def_cfa_register:          return "CFA_def_cfa_register";
571     case DW_CFA_def_cfa_offset:            return "CFA_def_cfa_offset";
572     case DW_CFA_def_cfa_expression:        return "CFA_def_cfa_expression";
573     case DW_CFA_expression:                return "CFA_expression";
574     case DW_CFA_offset_extended_sf:        return "CFA_offset_extended_sf";
575     case DW_CFA_def_cfa_sf:                return "CFA_def_cfa_sf";
576     case DW_CFA_def_cfa_offset_sf:         return "CFA_def_cfa_offset_sf";
577     case DW_CFA_val_offset:                return "CFA_val_offset";
578     case DW_CFA_val_offset_sf:             return "CFA_val_offset_sf";
579     case DW_CFA_val_expression:            return "CFA_val_expression";
580     case DW_CFA_lo_user:                   return "CFA_lo_user";
581     case DW_CFA_hi_user:                   return "CFA_hi_user";
582   }
583   assert(0 && "Unknown Dwarf Call Frame Instruction Encodings");
584   return "";
585 }
586
587 //===----------------------------------------------------------------------===//
588
589 /// operator== - Used by UniqueVector to locate entry.
590 ///
591 bool DIEAbbrev::operator==(const DIEAbbrev &DA) const {
592   if (Tag != DA.Tag) return false;
593   if (ChildrenFlag != DA.ChildrenFlag) return false;
594   if (Data.size() != DA.Data.size()) return false;
595   
596   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
597     if (Data[i] != DA.Data[i]) return false;
598   }
599   
600   return true;
601 }
602
603 /// operator< - Used by UniqueVector to locate entry.
604 ///
605 bool DIEAbbrev::operator<(const DIEAbbrev &DA) const {
606   if (Tag != DA.Tag) return Tag < DA.Tag;
607   if (ChildrenFlag != DA.ChildrenFlag) return ChildrenFlag < DA.ChildrenFlag;
608   if (Data.size() != DA.Data.size()) return Data.size() < DA.Data.size();
609   
610   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
611     if (Data[i] != DA.Data[i]) return Data[i] < DA.Data[i];
612   }
613   
614   return false;
615 }
616     
617 /// Emit - Print the abbreviation using the specified Dwarf writer.
618 ///
619 void DIEAbbrev::Emit(const DwarfWriter &DW) const {
620   // Emit its Dwarf tag type.
621   DW.EmitULEB128Bytes(Tag);
622   DW.EOL(TagString(Tag));
623   
624   // Emit whether it has children DIEs.
625   DW.EmitULEB128Bytes(ChildrenFlag);
626   DW.EOL(ChildrenString(ChildrenFlag));
627   
628   // For each attribute description.
629   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
630     const DIEAbbrevData &AttrData = Data[i];
631     
632     // Emit attribute type.
633     DW.EmitULEB128Bytes(AttrData.getAttribute());
634     DW.EOL(AttributeString(AttrData.getAttribute()));
635     
636     // Emit form type.
637     DW.EmitULEB128Bytes(AttrData.getForm());
638     DW.EOL(FormEncodingString(AttrData.getForm()));
639   }
640
641   // Mark end of abbreviation.
642   DW.EmitULEB128Bytes(0); DW.EOL("EOM(1)");
643   DW.EmitULEB128Bytes(0); DW.EOL("EOM(2)");
644 }
645
646 #ifndef NDEBUG
647   void DIEAbbrev::print(std::ostream &O) {
648     O << "Abbreviation @"
649       << std::hex << (intptr_t)this << std::dec
650       << "  "
651       << TagString(Tag)
652       << " "
653       << ChildrenString(ChildrenFlag)
654       << "\n";
655     
656     for (unsigned i = 0, N = Data.size(); i < N; ++i) {
657       O << "  "
658         << AttributeString(Data[i].getAttribute())
659         << "  "
660         << FormEncodingString(Data[i].getForm())
661         << "\n";
662     }
663   }
664   void DIEAbbrev::dump() { print(std::cerr); }
665 #endif
666
667 //===----------------------------------------------------------------------===//
668
669 /// EmitValue - Emit integer of appropriate size.
670 ///
671 void DIEInteger::EmitValue(const DwarfWriter &DW, unsigned Form) const {
672   switch (Form) {
673   case DW_FORM_flag:  // Fall thru
674   case DW_FORM_data1: DW.EmitByte(Integer);         break;
675   case DW_FORM_data2: DW.EmitShort(Integer);        break;
676   case DW_FORM_data4: DW.EmitLong(Integer);         break;
677   case DW_FORM_data8: DW.EmitLongLong(Integer);     break;
678   case DW_FORM_udata: DW.EmitULEB128Bytes(Integer); break;
679   case DW_FORM_sdata: DW.EmitSLEB128Bytes(Integer); break;
680   default: assert(0 && "DIE Value form not supported yet"); break;
681   }
682 }
683
684 /// SizeOf - Determine size of integer value in bytes.
685 ///
686 unsigned DIEInteger::SizeOf(const DwarfWriter &DW, unsigned Form) const {
687   switch (Form) {
688   case DW_FORM_flag:  // Fall thru
689   case DW_FORM_data1: return sizeof(int8_t);
690   case DW_FORM_data2: return sizeof(int16_t);
691   case DW_FORM_data4: return sizeof(int32_t);
692   case DW_FORM_data8: return sizeof(int64_t);
693   case DW_FORM_udata: return DW.SizeULEB128(Integer);
694   case DW_FORM_sdata: return DW.SizeSLEB128(Integer);
695   default: assert(0 && "DIE Value form not supported yet"); break;
696   }
697   return 0;
698 }
699
700 //===----------------------------------------------------------------------===//
701
702 /// EmitValue - Emit string value.
703 ///
704 void DIEString::EmitValue(const DwarfWriter &DW, unsigned Form) const {
705   DW.EmitString(String);
706 }
707
708 /// SizeOf - Determine size of string value in bytes.
709 ///
710 unsigned DIEString::SizeOf(const DwarfWriter &DW, unsigned Form) const {
711   return String.size() + sizeof(char); // sizeof('\0');
712 }
713
714 //===----------------------------------------------------------------------===//
715
716 /// EmitValue - Emit label value.
717 ///
718 void DIEDwarfLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
719   DW.EmitReference(Label);
720 }
721
722 /// SizeOf - Determine size of label value in bytes.
723 ///
724 unsigned DIEDwarfLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
725   return DW.getAddressSize();
726 }
727     
728 //===----------------------------------------------------------------------===//
729
730 /// EmitValue - Emit label value.
731 ///
732 void DIEObjectLabel::EmitValue(const DwarfWriter &DW, unsigned Form) const {
733   DW.EmitByte(sizeof(int8_t) + DW.getAddressSize());
734   DW.EOL("DW_FORM_block1 length");
735   
736   DW.EmitByte(DW_OP_addr);
737   DW.EOL("DW_OP_addr");
738   
739   DW.EmitReference(Label);
740 }
741
742 /// SizeOf - Determine size of label value in bytes.
743 ///
744 unsigned DIEObjectLabel::SizeOf(const DwarfWriter &DW, unsigned Form) const {
745   return sizeof(int8_t) + sizeof(int8_t) + DW.getAddressSize();
746 }
747     
748 //===----------------------------------------------------------------------===//
749
750 /// EmitValue - Emit delta value.
751 ///
752 void DIEDelta::EmitValue(const DwarfWriter &DW, unsigned Form) const {
753   DW.EmitDifference(LabelHi, LabelLo);
754 }
755
756 /// SizeOf - Determine size of delta value in bytes.
757 ///
758 unsigned DIEDelta::SizeOf(const DwarfWriter &DW, unsigned Form) const {
759   return DW.getAddressSize();
760 }
761
762 //===----------------------------------------------------------------------===//
763 /// EmitValue - Emit extry offset.
764 ///
765 void DIEntry::EmitValue(const DwarfWriter &DW, unsigned Form) const {
766   DW.EmitLong(Entry->getOffset());
767 }
768
769 /// SizeOf - Determine size of label value in bytes.
770 ///
771 unsigned DIEntry::SizeOf(const DwarfWriter &DW, unsigned Form) const {
772   return sizeof(int32_t);
773 }
774     
775 //===----------------------------------------------------------------------===//
776
777 DIE::DIE(unsigned Tag, unsigned ChildrenFlag)
778 : Abbrev(new DIEAbbrev(Tag, ChildrenFlag))
779 , AbbrevID(0)
780 , Offset(0)
781 , Size(0)
782 , Context(NULL)
783 , Children()
784 , Values()
785 {}
786
787 DIE::~DIE() {
788   if (Abbrev) delete Abbrev;
789   
790   for (unsigned i = 0, N = Children.size(); i < N; ++i) {
791     delete Children[i];
792   }
793
794   for (unsigned j = 0, M = Values.size(); j < M; ++j) {
795     delete Values[j];
796   }
797   
798   if (Context) delete Context;
799 }
800     
801 /// AddUInt - Add an unsigned integer attribute data and value.
802 ///
803 void DIE::AddUInt(unsigned Attribute, unsigned Form, uint64_t Integer) {
804   if (Form == 0) {
805       if ((unsigned char)Integer == Integer)       Form = DW_FORM_data1;
806       else if ((unsigned short)Integer == Integer) Form = DW_FORM_data2;
807       else if ((unsigned int)Integer == Integer)   Form = DW_FORM_data4;
808       else                                         Form = DW_FORM_data8;
809   }
810   Abbrev->AddAttribute(Attribute, Form);
811   Values.push_back(new DIEInteger(Integer));
812 }
813     
814 /// AddSInt - Add an signed integer attribute data and value.
815 ///
816 void DIE::AddSInt(unsigned Attribute, unsigned Form, int64_t Integer) {
817   if (Form == 0) {
818       if ((char)Integer == Integer)       Form = DW_FORM_data1;
819       else if ((short)Integer == Integer) Form = DW_FORM_data2;
820       else if ((int)Integer == Integer)   Form = DW_FORM_data4;
821       else                                Form = DW_FORM_data8;
822   }
823   Abbrev->AddAttribute(Attribute, Form);
824   Values.push_back(new DIEInteger(Integer));
825 }
826     
827 /// AddString - Add a std::string attribute data and value.
828 ///
829 void DIE::AddString(unsigned Attribute, unsigned Form,
830                     const std::string &String) {
831   Abbrev->AddAttribute(Attribute, Form);
832   Values.push_back(new DIEString(String));
833 }
834     
835 /// AddLabel - Add a Dwarf label attribute data and value.
836 ///
837 void DIE::AddLabel(unsigned Attribute, unsigned Form,
838                    const DWLabel &Label) {
839   Abbrev->AddAttribute(Attribute, Form);
840   Values.push_back(new DIEDwarfLabel(Label));
841 }
842     
843 /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
844 ///
845 void DIE::AddObjectLabel(unsigned Attribute, unsigned Form,
846                          const std::string &Label) {
847   Abbrev->AddAttribute(Attribute, Form);
848   Values.push_back(new DIEObjectLabel(Label));
849 }
850     
851 /// AddDelta - Add a label delta attribute data and value.
852 ///
853 void DIE::AddDelta(unsigned Attribute, unsigned Form,
854                    const DWLabel &Hi, const DWLabel &Lo) {
855   Abbrev->AddAttribute(Attribute, Form);
856   Values.push_back(new DIEDelta(Hi, Lo));
857 }
858     
859 /// AddDIEntry - Add a DIE attribute data and value.
860 ///
861 void DIE::AddDIEntry(unsigned Attribute,
862                      unsigned Form, DIE *Entry) {
863   Abbrev->AddAttribute(Attribute, Form);
864   Values.push_back(new DIEntry(Entry));
865 }
866
867 /// Complete - Indicate that all attributes have been added and ready to get an
868 /// abbreviation ID.
869 void DIE::Complete(DwarfWriter &DW) {
870   AbbrevID = DW.NewAbbreviation(Abbrev);
871   delete Abbrev;
872   Abbrev = NULL;
873 }
874
875 /// AddChild - Add a child to the DIE.
876 ///
877 void DIE::AddChild(DIE *Child) {
878   Children.push_back(Child);
879 }
880
881 //===----------------------------------------------------------------------===//
882
883 /// NewBasicType - Creates a new basic type if necessary, then adds to the
884 /// context and owner.
885 DIE *DWContext::NewBasicType(const Type *Ty, unsigned Size, unsigned Align) {
886   DIE *TypeDie = Types[Ty];
887   
888   // If first occurance of type.
889   if (!TypeDie) {
890     const char *Name;
891     unsigned Encoding = 0;
892     
893     switch (Ty->getTypeID()) {
894     case Type::UByteTyID:
895       Name = "unsigned char";
896       Encoding = DW_ATE_unsigned_char;
897       break;
898     case Type::SByteTyID:
899       Name = "char";
900       Encoding = DW_ATE_signed_char;
901       break;
902     case Type::UShortTyID:
903       Name = "unsigned short";
904       Encoding = DW_ATE_unsigned;
905       break;
906     case Type::ShortTyID:
907       Name = "short";
908       Encoding = DW_ATE_signed;
909       break;
910     case Type::UIntTyID:
911       Name = "unsigned int";
912       Encoding = DW_ATE_unsigned;
913       break;
914     case Type::IntTyID:
915       Name = "int";
916       Encoding = DW_ATE_signed;
917       break;
918     case Type::ULongTyID:
919       Name = "unsigned long long";
920       Encoding = DW_ATE_unsigned;
921       break;
922     case Type::LongTyID:
923       Name = "long long";
924       Encoding = DW_ATE_signed;
925       break;
926     case Type::FloatTyID:
927       Name = "float";
928       Encoding = DW_ATE_float;
929       break;
930     case Type::DoubleTyID:
931       Name = "float";
932       Encoding = DW_ATE_float;
933       break;
934     default: 
935     // FIXME - handle more complex types.
936       Name = "unknown";
937       Encoding = DW_ATE_address;
938       break;
939     }
940     
941     // construct the type DIE.
942     TypeDie = new DIE(DW_TAG_base_type, DW_CHILDREN_no);
943     TypeDie->AddString(DW_AT_name,      DW_FORM_string, Name);
944     TypeDie->AddUInt  (DW_AT_byte_size, DW_FORM_data1,  Size);
945     TypeDie->AddUInt  (DW_AT_encoding,  DW_FORM_data1,  Encoding);
946     TypeDie->Complete(DW);
947     
948     // Add to context owner.
949     Owner->AddChild(TypeDie);
950
951     // Add to map.
952     Types[Ty] = TypeDie;
953   }
954   
955   return TypeDie;
956 }
957
958 /// NewGlobalVariable - Creates a global variable, if necessary, then adds in
959 /// the context and owner.
960 DIE *DWContext::NewGlobalVariable(const std::string &Name,
961                                   const std::string &MangledName,
962                                   DIE *Type) {
963   DIE *VariableDie = Variables[MangledName];
964   
965   // If first occurance of variable.
966   if (!VariableDie) {
967     // FIXME - need source file name line number.
968     VariableDie = new DIE(DW_TAG_variable, DW_CHILDREN_no);
969     VariableDie->AddString     (DW_AT_name,      DW_FORM_string, Name);
970     VariableDie->AddUInt       (DW_AT_decl_file, 0,              0);
971     VariableDie->AddUInt       (DW_AT_decl_line, 0,              0);
972     VariableDie->AddDIEntry    (DW_AT_type,      DW_FORM_ref4,   Type);
973     VariableDie->AddUInt       (DW_AT_external,  DW_FORM_flag,   1);
974     // FIXME - needs to be a proper expression.
975     VariableDie->AddObjectLabel(DW_AT_location,  DW_FORM_block1, MangledName);
976     VariableDie->Complete(DW);
977  
978     // Add to context owner.
979     Owner->AddChild(VariableDie);
980     
981     // Add to map.
982     Variables[MangledName] = VariableDie;
983   }
984   
985   return VariableDie;
986 }
987
988 //===----------------------------------------------------------------------===//
989
990 /// PrintHex - Print a value as a hexidecimal value.
991 ///
992 void DwarfWriter::PrintHex(int Value) const { 
993   O << "0x" << std::hex << Value << std::dec;
994 }
995
996 /// EOL - Print a newline character to asm stream.  If a comment is present
997 /// then it will be printed first.  Comments should not contain '\n'.
998 void DwarfWriter::EOL(const std::string &Comment) const {
999   if (DwarfVerbose) {
1000     O << "\t"
1001       << Asm->CommentString
1002       << " "
1003       << Comment;
1004   }
1005   O << "\n";
1006 }
1007
1008 /// EmitULEB128Bytes - Emit an assembler byte data directive to compose an
1009 /// unsigned leb128 value.
1010 void DwarfWriter::EmitULEB128Bytes(unsigned Value) const {
1011   if (hasLEB128) {
1012     O << "\t.uleb128\t"
1013       << Value;
1014   } else {
1015     O << Asm->Data8bitsDirective;
1016     PrintULEB128(Value);
1017   }
1018 }
1019
1020 /// EmitSLEB128Bytes - Emit an assembler byte data directive to compose a
1021 /// signed leb128 value.
1022 void DwarfWriter::EmitSLEB128Bytes(int Value) const {
1023   if (hasLEB128) {
1024     O << "\t.sleb128\t"
1025       << Value;
1026   } else {
1027     O << Asm->Data8bitsDirective;
1028     PrintSLEB128(Value);
1029   }
1030 }
1031
1032 /// PrintULEB128 - Print a series of hexidecimal values (separated by commas)
1033 /// representing an unsigned leb128 value.
1034 void DwarfWriter::PrintULEB128(unsigned Value) const {
1035   do {
1036     unsigned Byte = Value & 0x7f;
1037     Value >>= 7;
1038     if (Value) Byte |= 0x80;
1039     PrintHex(Byte);
1040     if (Value) O << ", ";
1041   } while (Value);
1042 }
1043
1044 /// SizeULEB128 - Compute the number of bytes required for an unsigned leb128
1045 /// value.
1046 unsigned DwarfWriter::SizeULEB128(unsigned Value) {
1047   unsigned Size = 0;
1048   do {
1049     Value >>= 7;
1050     Size += sizeof(int8_t);
1051   } while (Value);
1052   return Size;
1053 }
1054
1055 /// PrintSLEB128 - Print a series of hexidecimal values (separated by commas)
1056 /// representing a signed leb128 value.
1057 void DwarfWriter::PrintSLEB128(int Value) const {
1058   int Sign = Value >> (8 * sizeof(Value) - 1);
1059   bool IsMore;
1060   
1061   do {
1062     unsigned Byte = Value & 0x7f;
1063     Value >>= 7;
1064     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1065     if (IsMore) Byte |= 0x80;
1066     PrintHex(Byte);
1067     if (IsMore) O << ", ";
1068   } while (IsMore);
1069 }
1070
1071 /// SizeSLEB128 - Compute the number of bytes required for a signed leb128
1072 /// value.
1073 unsigned DwarfWriter::SizeSLEB128(int Value) {
1074   unsigned Size = 0;
1075   int Sign = Value >> (8 * sizeof(Value) - 1);
1076   bool IsMore;
1077   
1078   do {
1079     unsigned Byte = Value & 0x7f;
1080     Value >>= 7;
1081     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
1082     Size += sizeof(int8_t);
1083   } while (IsMore);
1084   return Size;
1085 }
1086
1087 /// EmitByte - Emit a byte directive and value.
1088 ///
1089 void DwarfWriter::EmitByte(int Value) const {
1090   O << Asm->Data8bitsDirective;
1091   PrintHex(Value);
1092 }
1093
1094 /// EmitShort - Emit a short directive and value.
1095 ///
1096 void DwarfWriter::EmitShort(int Value) const {
1097   O << Asm->Data16bitsDirective;
1098   PrintHex(Value);
1099 }
1100
1101 /// EmitLong - Emit a long directive and value.
1102 ///
1103 void DwarfWriter::EmitLong(int Value) const {
1104   O << Asm->Data32bitsDirective;
1105   PrintHex(Value);
1106 }
1107
1108 /// EmitLongLong - Emit a long long directive and value.
1109 ///
1110 void DwarfWriter::EmitLongLong(uint64_t Value) const {
1111   if (Asm->Data64bitsDirective) {
1112     O << Asm->Data64bitsDirective << "0x" << std::hex << Value << std::dec;
1113   } else {
1114     const TargetData &TD = Asm->TM.getTargetData();
1115     
1116     if (TD.isBigEndian()) {
1117       EmitLong(unsigned(Value >> 32)); O << "\n";
1118       EmitLong(unsigned(Value));
1119     } else {
1120       EmitLong(unsigned(Value)); O << "\n";
1121       EmitLong(unsigned(Value >> 32));
1122     }
1123   }
1124 }
1125
1126 /// EmitString - Emit a string with quotes and a null terminator.
1127 /// Special characters are emitted properly. (Eg. '\t')
1128 void DwarfWriter::EmitString(const std::string &String) const {
1129   O << Asm->AsciiDirective
1130     << "\"";
1131   for (unsigned i = 0, N = String.size(); i < N; ++i) {
1132     unsigned char C = String[i];
1133     
1134     if (!isascii(C) || iscntrl(C)) {
1135       switch(C) {
1136       case '\b': O << "\\b"; break;
1137       case '\f': O << "\\f"; break;
1138       case '\n': O << "\\n"; break;
1139       case '\r': O << "\\r"; break;
1140       case '\t': O << "\\t"; break;
1141       default:
1142         O << '\\';
1143         O << char('0' + (C >> 6));
1144         O << char('0' + (C >> 3));
1145         O << char('0' + (C >> 0));
1146         break;
1147       }
1148     } else if (C == '\"') {
1149       O << "\\\"";
1150     } else if (C == '\'') {
1151       O << "\\\'";
1152     } else {
1153      O << C;
1154     }
1155   }
1156   O << "\\0\"";
1157 }
1158
1159 /// PrintLabelName - Print label name in form used by Dwarf writer.
1160 ///
1161 void DwarfWriter::PrintLabelName(const char *Tag, unsigned Number) const {
1162   O << Asm->PrivateGlobalPrefix
1163     << "debug_"
1164     << Tag
1165     << Number;
1166 }
1167
1168 /// EmitLabel - Emit location label for internal use by Dwarf.
1169 ///
1170 void DwarfWriter::EmitLabel(const char *Tag, unsigned Number) const {
1171   PrintLabelName(Tag, Number);
1172   O << ":\n";
1173 }
1174
1175 /// EmitReference - Emit a reference to a label.
1176 ///
1177 void DwarfWriter::EmitReference(const char *Tag, unsigned Number) const {
1178   if (AddressSize == 4)
1179     O << Asm->Data32bitsDirective;
1180   else
1181     O << Asm->Data64bitsDirective;
1182     
1183   PrintLabelName(Tag, Number);
1184 }
1185 void DwarfWriter::EmitReference(const std::string &Name) const {
1186   if (AddressSize == 4)
1187     O << Asm->Data32bitsDirective;
1188   else
1189     O << Asm->Data64bitsDirective;
1190     
1191   O << Name;
1192 }
1193
1194 /// EmitDifference - Emit an label difference as sizeof(pointer) value.  Some
1195 /// assemblers do not accept absolute expressions with data directives, so there 
1196 /// is an option (needsSet) to use an intermediary 'set' expression.
1197 void DwarfWriter::EmitDifference(const char *TagHi, unsigned NumberHi,
1198                                  const char *TagLo, unsigned NumberLo) const {
1199   if (needsSet) {
1200     static unsigned SetCounter = 0;
1201     
1202     O << "\t.set\t";
1203     PrintLabelName("set", SetCounter);
1204     O << ",";
1205     PrintLabelName(TagHi, NumberHi);
1206     O << "-";
1207     PrintLabelName(TagLo, NumberLo);
1208     O << "\n";
1209     
1210     if (AddressSize == sizeof(int32_t))
1211       O << Asm->Data32bitsDirective;
1212     else
1213       O << Asm->Data64bitsDirective;
1214       
1215     PrintLabelName("set", SetCounter);
1216     
1217     ++SetCounter;
1218   } else {
1219     if (AddressSize == sizeof(int32_t))
1220       O << Asm->Data32bitsDirective;
1221     else
1222       O << Asm->Data64bitsDirective;
1223       
1224     PrintLabelName(TagHi, NumberHi);
1225     O << "-";
1226     PrintLabelName(TagLo, NumberLo);
1227   }
1228 }
1229
1230 /// NewAbbreviation - Add the abbreviation to the Abbreviation vector.
1231 ///  
1232 unsigned DwarfWriter::NewAbbreviation(DIEAbbrev *Abbrev) {
1233   return Abbreviations.insert(*Abbrev);
1234 }
1235
1236 /// NewString - Add a string to the constant pool and returns a label.
1237 ///
1238 DWLabel DwarfWriter::NewString(const std::string &String) {
1239   unsigned StringID = StringPool.insert(String);
1240   return DWLabel("string", StringID);
1241 }
1242
1243 /// NewGlobalType - Make the type visible globally using the given name.
1244 ///
1245 void DwarfWriter::NewGlobalType(const std::string &Name, DIE *Type) {
1246   assert(!GlobalTypes[Name] && "Duplicate global type");
1247   GlobalTypes[Name] = Type;
1248 }
1249
1250 /// NewGlobalEntity - Make the entity visible globally using the given name.
1251 ///
1252 void DwarfWriter::NewGlobalEntity(const std::string &Name, DIE *Entity) {
1253   assert(!GlobalEntities[Name] && "Duplicate global variable or function");
1254   GlobalEntities[Name] = Entity;
1255 }
1256
1257 /// NewGlobalVariable - Add a new global variable DIE to the context.
1258 ///
1259 void DwarfWriter::NewGlobalVariable(DWContext *Context,
1260                                     const std::string &Name,
1261                                     const std::string &MangledName,
1262                                     const Type *Ty,
1263                                     unsigned Size, unsigned Align) {
1264   // Get the DIE type for the global.
1265   DIE *Type = Context->NewBasicType(Ty, Size, Align);
1266   DIE *Variable = Context->NewGlobalVariable(Name, MangledName, Type);
1267   NewGlobalEntity(Name, Variable);
1268 }
1269
1270 /// NewCompileUnit - Create new compile unit information.
1271 ///
1272 DIE *DwarfWriter::NewCompileUnit(const CompileUnitWrapper &CompileUnit) {
1273   DIE *Unit = new DIE(DW_TAG_compile_unit, DW_CHILDREN_yes);
1274   // FIXME - use the correct line set.
1275   Unit->AddLabel (DW_AT_stmt_list, DW_FORM_data4,  DWLabel("line", 0));
1276   Unit->AddLabel (DW_AT_high_pc,   DW_FORM_addr,   DWLabel("text_end", 0));
1277   Unit->AddLabel (DW_AT_low_pc,    DW_FORM_addr,   DWLabel("text_begin", 0));
1278   Unit->AddString(DW_AT_producer,  DW_FORM_string, CompileUnit.getProducer());
1279   Unit->AddUInt  (DW_AT_language,  DW_FORM_data1,  CompileUnit.getLanguage());
1280   Unit->AddString(DW_AT_name,      DW_FORM_string, CompileUnit.getFileName());
1281   Unit->AddString(DW_AT_comp_dir,  DW_FORM_string, CompileUnit.getDirectory());
1282   Unit->Complete(*this);
1283   
1284   return Unit;
1285 }
1286
1287 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1288 /// tools to recognize the object file contains Dwarf information.
1289 ///
1290 void DwarfWriter::EmitInitial() const {
1291   // Dwarf sections base addresses.
1292   Asm->SwitchSection(DwarfAbbrevSection, 0);
1293   EmitLabel("abbrev", 0);
1294   Asm->SwitchSection(DwarfInfoSection, 0);
1295   EmitLabel("info", 0);
1296   Asm->SwitchSection(DwarfLineSection, 0);
1297   EmitLabel("line", 0);
1298   
1299   // Standard sections base addresses.
1300   Asm->SwitchSection(TextSection, 0);
1301   EmitLabel("text_begin", 0);
1302   Asm->SwitchSection(DataSection, 0);
1303   EmitLabel("data_begin", 0);
1304 }
1305
1306 /// EmitDIE - Recusively Emits a debug information entry.
1307 ///
1308 void DwarfWriter::EmitDIE(DIE *Die) const {
1309   // Get the abbreviation for this DIE.
1310   unsigned AbbrevID = Die->getAbbrevID();
1311   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1312
1313   // Emit the code (index) for the abbreviation.
1314   EmitULEB128Bytes(AbbrevID);
1315   EOL(std::string("Abbrev [" +
1316       utostr(AbbrevID) +
1317       "] " +
1318       TagString(Abbrev.getTag())) +
1319       " ");
1320   
1321   const std::vector<DIEValue *> &Values = Die->getValues();
1322   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1323   
1324   // Emit the DIE attribute values.
1325   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1326     unsigned Attr = AbbrevData[i].getAttribute();
1327     unsigned Form = AbbrevData[i].getForm();
1328     assert(Form && "Too many attributes for DIE (check abbreviation)");
1329     
1330     switch (Attr) {
1331     case DW_AT_sibling: {
1332       EmitLong(Die->SiblingOffset());
1333       break;
1334     }
1335     default: {
1336       // Emit an attribute using the defined form.
1337       Values[i]->EmitValue(*this, Form);
1338       break;
1339     }
1340     }
1341     
1342     EOL(AttributeString(Attr));
1343   }
1344   
1345   // Emit the DIE children if any.
1346   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1347     const std::vector<DIE *> &Children = Die->getChildren();
1348     
1349     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1350       // FIXME - handle sibling offsets.
1351       // FIXME - handle all DIE types.
1352       EmitDIE(Children[j]);
1353     }
1354     
1355     EmitByte(0); EOL("End Of Children Mark");
1356   }
1357 }
1358
1359 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1360 ///
1361 unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset) const {
1362   // Get the abbreviation for this DIE.
1363   unsigned AbbrevID = Die->getAbbrevID();
1364   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1365
1366   // Set DIE offset
1367   Die->setOffset(Offset);
1368   
1369   // Start the size with the size of abbreviation code.
1370   Offset += SizeULEB128(AbbrevID);
1371   
1372   const std::vector<DIEValue *> &Values = Die->getValues();
1373   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1374
1375   // Emit the DIE attribute values.
1376   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1377     // Size attribute value.
1378     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
1379   }
1380   
1381   // Emit the DIE children if any.
1382   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1383     const std::vector<DIE *> &Children = Die->getChildren();
1384     
1385     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1386       // FIXME - handle sibling offsets.
1387       // FIXME - handle all DIE types.
1388       Offset = SizeAndOffsetDie(Children[j], Offset);
1389     }
1390     
1391     // End of children marker.
1392     Offset += sizeof(int8_t);
1393   }
1394
1395   Die->setSize(Offset - Die->getOffset());
1396   return Offset;
1397 }
1398
1399 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1400 ///
1401 void DwarfWriter::SizeAndOffsets() {
1402   // Compute size of debug unit header
1403   unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
1404                     sizeof(int16_t) + // DWARF version number
1405                     sizeof(int32_t) + // Offset Into Abbrev. Section
1406                     sizeof(int8_t);   // Pointer Size (in bytes)
1407   
1408   // Process each compile unit.
1409   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1410     Offset = SizeAndOffsetDie(CompileUnits[i], Offset);
1411   }
1412 }
1413
1414 /// EmitDebugInfo - Emit the debug info section.
1415 ///
1416 void DwarfWriter::EmitDebugInfo() const {
1417   // Start debug info section.
1418   Asm->SwitchSection(DwarfInfoSection, 0);
1419   
1420   // Get the number of compile units.
1421   unsigned N = CompileUnits.size();
1422   
1423   // If there are any compile units.
1424   if (N) {
1425     EmitLabel("info_begin", 0);
1426     
1427     // Emit the compile units header.
1428
1429     // Emit size of content not including length itself
1430     unsigned ContentSize = CompileUnits[N - 1]->SiblingOffset();
1431     EmitLong(ContentSize - sizeof(int32_t));
1432     EOL("Length of Compilation Unit Info");
1433     
1434     EmitShort(DWARF_VERSION); EOL("DWARF version number");
1435
1436     EmitReference("abbrev_begin", 0); EOL("Offset Into Abbrev. Section");
1437
1438     EmitByte(AddressSize); EOL("Address Size (in bytes)");
1439     
1440     // Process each compile unit.
1441     for (unsigned i = 0; i < N; ++i) {
1442       EmitDIE(CompileUnits[i]);
1443     }
1444     
1445     EmitLabel("info_end", 0);
1446   }
1447 }
1448
1449 /// EmitAbbreviations - Emit the abbreviation section.
1450 ///
1451 void DwarfWriter::EmitAbbreviations() const {
1452   // Check to see if it is worth the effort.
1453   if (!Abbreviations.empty()) {
1454     // Start the debug abbrev section.
1455     Asm->SwitchSection(DwarfAbbrevSection, 0);
1456     
1457     EmitLabel("abbrev_begin", 0);
1458     
1459     // For each abbrevation.
1460     for (unsigned AbbrevID = 1, NAID = Abbreviations.size();
1461                   AbbrevID <= NAID; ++AbbrevID) {
1462       // Get abbreviation data
1463       const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1464       
1465       // Emit the abbrevations code (base 1 index.)
1466       EmitULEB128Bytes(AbbrevID); EOL("Abbreviation Code");
1467       
1468       // Emit the abbreviations data.
1469       Abbrev.Emit(*this);
1470     }
1471     
1472     EmitLabel("abbrev_end", 0);
1473   }
1474 }
1475
1476 /// EmitDebugLines - Emit source line information.
1477 ///
1478 void DwarfWriter::EmitDebugLines() const {
1479   // Minimum line delta, thus ranging from -10..(255-10).
1480   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
1481   // Maximum line delta, thus ranging from -10..(255-10).
1482   const int MaxLineDelta = 255 + MinLineDelta;
1483
1484   // Start the dwarf line section.
1485   Asm->SwitchSection(DwarfLineSection, 0);
1486   
1487   // Construct the section header.
1488   
1489   EmitDifference("line_end", 0, "line_begin", 0);
1490   EOL("Length of Source Line Info");
1491   EmitLabel("line_begin", 0);
1492   
1493   EmitShort(DWARF_VERSION); EOL("DWARF version number");
1494   
1495   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
1496   EOL("Prolog Length");
1497   EmitLabel("line_prolog_begin", 0);
1498   
1499   EmitByte(1); EOL("Minimum Instruction Length");
1500
1501   EmitByte(1); EOL("Default is_stmt_start flag");
1502
1503   EmitByte(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
1504   
1505   EmitByte(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
1506
1507   EmitByte(-MinLineDelta); EOL("Special Opcode Base");
1508   
1509   // Line number standard opcode encodings argument count
1510   EmitByte(0); EOL("DW_LNS_copy arg count");
1511   EmitByte(1); EOL("DW_LNS_advance_pc arg count");
1512   EmitByte(1); EOL("DW_LNS_advance_line arg count");
1513   EmitByte(1); EOL("DW_LNS_set_file arg count");
1514   EmitByte(1); EOL("DW_LNS_set_column arg count");
1515   EmitByte(0); EOL("DW_LNS_negate_stmt arg count");
1516   EmitByte(0); EOL("DW_LNS_set_basic_block arg count");
1517   EmitByte(0); EOL("DW_LNS_const_add_pc arg count");
1518   EmitByte(1); EOL("DW_LNS_fixed_advance_pc arg count");
1519
1520   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
1521   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
1522
1523   // Emit directories.
1524   for (unsigned DirectoryID = 1, NDID = Directories.size();
1525                 DirectoryID <= NDID; ++DirectoryID) {
1526     EmitString(Directories[DirectoryID]); EOL("Directory");
1527   }
1528   EmitByte(0); EOL("End of directories");
1529   
1530   // Emit files.
1531   for (unsigned SourceID = 1, NSID = SourceFiles.size();
1532                SourceID <= NSID; ++SourceID) {
1533     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
1534     EmitString(SourceFile.getName()); EOL("Source");
1535     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
1536     EmitULEB128Bytes(0);  EOL("Mod date");
1537     EmitULEB128Bytes(0);  EOL("File size");
1538   }
1539   EmitByte(0); EOL("End of files");
1540   
1541   EmitLabel("line_prolog_end", 0);
1542   
1543   // Emit line information
1544   const std::vector<SourceLineInfo *> &LineInfos = DebugInfo->getSourceLines();
1545   
1546   // Dwarf assumes we start with first line of first source file.
1547   unsigned Source = 1;
1548   unsigned Line = 1;
1549   
1550   // Construct rows of the address, source, line, column matrix.
1551   for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
1552     SourceLineInfo *LineInfo = LineInfos[i];
1553
1554     // Define the line address.
1555     EmitByte(0); EOL("Extended Op");
1556     EmitByte(4 + 1); EOL("Op size");
1557     EmitByte(DW_LNE_set_address); EOL("DW_LNE_set_address");
1558     EmitReference("loc", i + 1); EOL("Location label");
1559     
1560     // If change of source, then switch to the new source.
1561     if (Source != LineInfo->getSourceID()) {
1562       Source = LineInfo->getSourceID();
1563       EmitByte(DW_LNS_set_file); EOL("DW_LNS_set_file");
1564       EmitULEB128Bytes(0); EOL("New Source");
1565     }
1566     
1567     // If change of line.
1568     if (Line != LineInfo->getLine()) {
1569       // Determine offset.
1570       int Offset = LineInfo->getLine() - Line;
1571       int Delta = Offset - MinLineDelta;
1572       
1573       // Update line.
1574       Line = LineInfo->getLine();
1575       
1576       // If delta is small enough and in range...
1577       if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
1578         // ... then use fast opcode.
1579         EmitByte(Delta - MinLineDelta); EOL("Line Delta");
1580       } else {
1581         // ... otherwise use long hand.
1582         EmitByte(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
1583         EmitSLEB128Bytes(Offset); EOL("Line Offset");
1584         EmitByte(DW_LNS_copy); EOL("DW_LNS_copy");
1585       }
1586     } else {
1587       // Copy the previous row (different address or source)
1588       EmitByte(DW_LNS_copy); EOL("DW_LNS_copy");
1589     }
1590   }
1591
1592   // Mark end of matrix.
1593   EmitByte(0); EOL("DW_LNE_end_sequence");
1594   EmitULEB128Bytes(1);  O << "\n";
1595   EmitByte(1); O << "\n";
1596   
1597   EmitLabel("line_end", 0);
1598 }
1599   
1600 /// EmitDebugFrame - Emit visible names into a debug frame section.
1601 ///
1602 void DwarfWriter::EmitDebugFrame() {
1603   // FIXME - Should be per frame
1604 }
1605
1606 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
1607 ///
1608 void DwarfWriter::EmitDebugPubNames() {
1609   // Check to see if it is worth the effort.
1610   if (!GlobalEntities.empty()) {
1611     // Start the dwarf pubnames section.
1612     Asm->SwitchSection(DwarfPubNamesSection, 0);
1613     
1614     EmitDifference("pubnames_end", 0, "pubnames_begin", 0);
1615     EOL("Length of Public Names Info");
1616     
1617     EmitLabel("pubnames_begin", 0);
1618     
1619     EmitShort(DWARF_VERSION); EOL("DWARF Version");
1620     
1621     EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
1622
1623     EmitDifference("info_end", 0, "info_begin", 0);
1624     EOL("Compilation Unit Length");
1625     
1626     for (std::map<std::string, DIE *>::iterator GI = GlobalEntities.begin(),
1627                                                 GE = GlobalEntities.end();
1628          GI != GE; ++GI) {
1629       const std::string &Name = GI->first;
1630       DIE * Entity = GI->second;
1631       
1632       EmitLong(Entity->getOffset()); EOL("DIE offset");
1633       EmitString(Name); EOL("External Name");
1634       
1635     }
1636   
1637     EmitLong(0); EOL("End Mark");
1638     EmitLabel("pubnames_end", 0);
1639   }
1640 }
1641
1642 /// EmitDebugPubTypes - Emit visible names into a debug pubtypes section.
1643 ///
1644 void DwarfWriter::EmitDebugPubTypes() {
1645   // Check to see if it is worth the effort.
1646   if (!GlobalTypes.empty()) {
1647     // Start the dwarf pubtypes section.
1648     Asm->SwitchSection(DwarfPubTypesSection, 0);
1649   }
1650 }
1651
1652 /// EmitDebugStr - Emit visible names into a debug str section.
1653 ///
1654 void DwarfWriter::EmitDebugStr() {
1655   // Check to see if it is worth the effort.
1656   if (!StringPool.empty()) {
1657     // Start the dwarf str section.
1658     Asm->SwitchSection(DwarfStrSection, 0);
1659     
1660     // For each of strings in teh string pool.
1661     for (unsigned StringID = 1, N = StringPool.size();
1662          StringID <= N; ++StringID) {
1663       // Emit a label for reference from debug information entries.
1664       EmitLabel("string", StringID);
1665       // Emit the string itself.
1666       const std::string &String = StringPool[StringID];
1667       EmitString(String); O << "\n";
1668     }
1669   }
1670 }
1671
1672 /// EmitDebugLoc - Emit visible names into a debug loc section.
1673 ///
1674 void DwarfWriter::EmitDebugLoc() {
1675   // Start the dwarf loc section.
1676   Asm->SwitchSection(DwarfLocSection, 0);
1677 }
1678
1679 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1680 ///
1681 void DwarfWriter::EmitDebugARanges() {
1682   // Start the dwarf aranges section.
1683   Asm->SwitchSection(DwarfARangesSection, 0);
1684   
1685   // FIXME - Mock up
1686
1687   // Don't include size of length
1688   EmitLong(0x1c); EOL("Length of Address Ranges Info");
1689   
1690   EmitShort(DWARF_VERSION); EOL("Dwarf Version");
1691   
1692   EmitReference("info_begin", 0); EOL("Offset of Compilation Unit Info");
1693
1694   EmitByte(AddressSize); EOL("Size of Address");
1695
1696   EmitByte(0); EOL("Size of Segment Descriptor");
1697
1698   EmitShort(0);  EOL("Pad (1)");
1699   EmitShort(0);  EOL("Pad (2)");
1700
1701   // Range 1
1702   EmitReference("text_begin", 0); EOL("Address");
1703   EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
1704
1705   EmitLong(0); EOL("EOM (1)");
1706   EmitLong(0); EOL("EOM (2)");
1707 }
1708
1709 /// EmitDebugRanges - Emit visible names into a debug ranges section.
1710 ///
1711 void DwarfWriter::EmitDebugRanges() {
1712   // Start the dwarf ranges section.
1713   Asm->SwitchSection(DwarfRangesSection, 0);
1714 }
1715
1716 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
1717 ///
1718 void DwarfWriter::EmitDebugMacInfo() {
1719   // Start the dwarf macinfo section.
1720   Asm->SwitchSection(DwarfMacInfoSection, 0);
1721 }
1722
1723 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
1724 /// header file.
1725 void DwarfWriter::ConstructCompileUnitDIEs() {
1726   const UniqueVector<CompileUnitWrapper> CUW = DebugInfo->getCompileUnits();
1727   
1728   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
1729     const CompileUnitWrapper &CompileUnit = CUW[i];
1730     DIE *Unit = NewCompileUnit(CompileUnit);
1731     DWContext *Context = new DWContext(*this, NULL, Unit);
1732     CompileUnits.push_back(Unit);
1733   }
1734 }
1735
1736 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
1737 /// variables.
1738 void DwarfWriter::ConstructGlobalDIEs(Module &M) {
1739   const TargetData &TD = Asm->TM.getTargetData();
1740   
1741   std::vector<GlobalWrapper> GlobalVariables = DebugInfo->getGlobalVariables(M);
1742   
1743   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
1744     GlobalWrapper &GW = GlobalVariables[i];
1745     GlobalVariable *GV = GW.getGlobalVariable();
1746     
1747     if (!GV->hasInitializer()) continue;   // External global require no code
1748     
1749     // FIXME - Use global info type information when available.
1750     std::string Name = Asm->Mang->getValueName(GV);
1751     Constant *C = GV->getInitializer();
1752     const Type *Ty = C->getType();
1753     unsigned Size = TD.getTypeSize(Ty);
1754     unsigned Align = TD.getTypeAlignmentShift(Ty);
1755
1756     if (C->isNullValue() && /* FIXME: Verify correct */
1757         (GV->hasInternalLinkage() || GV->hasWeakLinkage() ||
1758          GV->hasLinkOnceLinkage())) {
1759       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1760     }
1761
1762     /// FIXME - Get correct compile unit context.
1763     assert(CompileUnits.size() && "No compile units");
1764     DWContext *Context = CompileUnits[0]->getContext();
1765     
1766     /// Create new global.
1767     NewGlobalVariable(Context, GV->getName(), Name, Ty, Size, Align);
1768   }
1769 }
1770
1771
1772 /// ShouldEmitDwarf - Determine if Dwarf declarations should be made.
1773 ///
1774 bool DwarfWriter::ShouldEmitDwarf() {
1775   // Check if debug info is present.
1776   if (!DebugInfo || !DebugInfo->hasInfo()) return false;
1777   
1778   // Make sure initial declarations are made.
1779   if (!didInitial) {
1780     EmitInitial();
1781     didInitial = true;
1782   }
1783   
1784   // Okay to emit.
1785   return true;
1786 }
1787
1788 //===----------------------------------------------------------------------===//
1789 // Main entry points.
1790 //
1791   
1792 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A)
1793 : O(OS)
1794 , Asm(A)
1795 , DebugInfo(NULL)
1796 , didInitial(false)
1797 , CompileUnits()
1798 , Abbreviations()
1799 , GlobalTypes()
1800 , GlobalEntities()
1801 , StringPool()
1802 , AddressSize(sizeof(int32_t))
1803 , hasLEB128(false)
1804 , hasDotLoc(false)
1805 , hasDotFile(false)
1806 , needsSet(false)
1807 , DwarfAbbrevSection(".debug_abbrev")
1808 , DwarfInfoSection(".debug_info")
1809 , DwarfLineSection(".debug_line")
1810 , DwarfFrameSection(".debug_frame")
1811 , DwarfPubNamesSection(".debug_pubnames")
1812 , DwarfPubTypesSection(".debug_pubtypes")
1813 , DwarfStrSection(".debug_str")
1814 , DwarfLocSection(".debug_loc")
1815 , DwarfARangesSection(".debug_aranges")
1816 , DwarfRangesSection(".debug_ranges")
1817 , DwarfMacInfoSection(".debug_macinfo")
1818 , TextSection(".text")
1819 , DataSection(".data")
1820 {}
1821 DwarfWriter::~DwarfWriter() {
1822   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1823     delete CompileUnits[i];
1824   }
1825 }
1826
1827 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
1828 ///
1829 void DwarfWriter::BeginModule(Module &M) {
1830   if (!ShouldEmitDwarf()) return;
1831   EOL("Dwarf Begin Module");
1832 }
1833
1834 /// EndModule - Emit all Dwarf sections that should come after the content.
1835 ///
1836 void DwarfWriter::EndModule(Module &M) {
1837   if (!ShouldEmitDwarf()) return;
1838   EOL("Dwarf End Module");
1839   
1840   // Standard sections final addresses.
1841   Asm->SwitchSection(TextSection, 0);
1842   EmitLabel("text_end", 0);
1843   Asm->SwitchSection(DataSection, 0);
1844   EmitLabel("data_end", 0);
1845   
1846   // Create all the compile unit DIEs.
1847   ConstructCompileUnitDIEs();
1848   
1849   // Create DIEs for each of the externally visible global variables.
1850   ConstructGlobalDIEs(M);
1851
1852   // Compute DIE offsets and sizes.
1853   SizeAndOffsets();
1854   
1855   // Emit all the DIEs into a debug info section
1856   EmitDebugInfo();
1857   
1858   // Corresponding abbreviations into a abbrev section.
1859   EmitAbbreviations();
1860   
1861   // Emit source line correspondence into a debug line section.
1862   EmitDebugLines();
1863   
1864   // Emit info into a debug frame section.
1865   EmitDebugFrame();
1866   
1867   // Emit info into a debug pubnames section.
1868   EmitDebugPubNames();
1869   
1870   // Emit info into a debug pubtypes section.
1871   EmitDebugPubTypes();
1872   
1873   // Emit info into a debug str section.
1874   EmitDebugStr();
1875   
1876   // Emit info into a debug loc section.
1877   EmitDebugLoc();
1878   
1879   // Emit info into a debug aranges section.
1880   EmitDebugARanges();
1881   
1882   // Emit info into a debug ranges section.
1883   EmitDebugRanges();
1884   
1885   // Emit info into a debug macinfo section.
1886   EmitDebugMacInfo();
1887 }
1888
1889 /// BeginFunction - Gather pre-function debug information.
1890 ///
1891 void DwarfWriter::BeginFunction(MachineFunction &MF) {
1892   if (!ShouldEmitDwarf()) return;
1893   EOL("Dwarf Begin Function");
1894 }
1895
1896 /// EndFunction - Gather and emit post-function debug information.
1897 ///
1898 void DwarfWriter::EndFunction(MachineFunction &MF) {
1899   if (!ShouldEmitDwarf()) return;
1900   EOL("Dwarf End Function");
1901 }