[dfsan] Try not to create too many additional basic blocks in functions which
[oota-llvm.git] / docs / SourceLevelDebugging.rst
1 ================================
2 Source Level Debugging with LLVM
3 ================================
4
5 .. contents::
6    :local:
7
8 Introduction
9 ============
10
11 This document is the central repository for all information pertaining to debug
12 information in LLVM.  It describes the :ref:`actual format that the LLVM debug
13 information takes <format>`, which is useful for those interested in creating
14 front-ends or dealing directly with the information.  Further, this document
15 provides specific examples of what debug information for C/C++ looks like.
16
17 Philosophy behind LLVM debugging information
18 --------------------------------------------
19
20 The idea of the LLVM debugging information is to capture how the important
21 pieces of the source-language's Abstract Syntax Tree map onto LLVM code.
22 Several design aspects have shaped the solution that appears here.  The
23 important ones are:
24
25 * Debugging information should have very little impact on the rest of the
26   compiler.  No transformations, analyses, or code generators should need to
27   be modified because of debugging information.
28
29 * LLVM optimizations should interact in :ref:`well-defined and easily described
30   ways <intro_debugopt>` with the debugging information.
31
32 * Because LLVM is designed to support arbitrary programming languages,
33   LLVM-to-LLVM tools should not need to know anything about the semantics of
34   the source-level-language.
35
36 * Source-level languages are often **widely** different from one another.
37   LLVM should not put any restrictions of the flavor of the source-language,
38   and the debugging information should work with any language.
39
40 * With code generator support, it should be possible to use an LLVM compiler
41   to compile a program to native machine code and standard debugging
42   formats.  This allows compatibility with traditional machine-code level
43   debuggers, like GDB or DBX.
44
45 The approach used by the LLVM implementation is to use a small set of
46 :ref:`intrinsic functions <format_common_intrinsics>` to define a mapping
47 between LLVM program objects and the source-level objects.  The description of
48 the source-level program is maintained in LLVM metadata in an
49 :ref:`implementation-defined format <ccxx_frontend>` (the C/C++ front-end
50 currently uses working draft 7 of the `DWARF 3 standard
51 <http://www.eagercon.com/dwarf/dwarf3std.htm>`_).
52
53 When a program is being debugged, a debugger interacts with the user and turns
54 the stored debug information into source-language specific information.  As
55 such, a debugger must be aware of the source-language, and is thus tied to a
56 specific language or family of languages.
57
58 Debug information consumers
59 ---------------------------
60
61 The role of debug information is to provide meta information normally stripped
62 away during the compilation process.  This meta information provides an LLVM
63 user a relationship between generated code and the original program source
64 code.
65
66 Currently, debug information is consumed by DwarfDebug to produce dwarf
67 information used by the gdb debugger.  Other targets could use the same
68 information to produce stabs or other debug forms.
69
70 It would also be reasonable to use debug information to feed profiling tools
71 for analysis of generated code, or, tools for reconstructing the original
72 source from generated code.
73
74 TODO - expound a bit more.
75
76 .. _intro_debugopt:
77
78 Debugging optimized code
79 ------------------------
80
81 An extremely high priority of LLVM debugging information is to make it interact
82 well with optimizations and analysis.  In particular, the LLVM debug
83 information provides the following guarantees:
84
85 * LLVM debug information **always provides information to accurately read
86   the source-level state of the program**, regardless of which LLVM
87   optimizations have been run, and without any modification to the
88   optimizations themselves.  However, some optimizations may impact the
89   ability to modify the current state of the program with a debugger, such
90   as setting program variables, or calling functions that have been
91   deleted.
92
93 * As desired, LLVM optimizations can be upgraded to be aware of the LLVM
94   debugging information, allowing them to update the debugging information
95   as they perform aggressive optimizations.  This means that, with effort,
96   the LLVM optimizers could optimize debug code just as well as non-debug
97   code.
98
99 * LLVM debug information does not prevent optimizations from
100   happening (for example inlining, basic block reordering/merging/cleanup,
101   tail duplication, etc).
102
103 * LLVM debug information is automatically optimized along with the rest of
104   the program, using existing facilities.  For example, duplicate
105   information is automatically merged by the linker, and unused information
106   is automatically removed.
107
108 Basically, the debug information allows you to compile a program with
109 "``-O0 -g``" and get full debug information, allowing you to arbitrarily modify
110 the program as it executes from a debugger.  Compiling a program with
111 "``-O3 -g``" gives you full debug information that is always available and
112 accurate for reading (e.g., you get accurate stack traces despite tail call
113 elimination and inlining), but you might lose the ability to modify the program
114 and call functions where were optimized out of the program, or inlined away
115 completely.
116
117 :ref:`LLVM test suite <test-suite-quickstart>` provides a framework to test
118 optimizer's handling of debugging information.  It can be run like this:
119
120 .. code-block:: bash
121
122   % cd llvm/projects/test-suite/MultiSource/Benchmarks  # or some other level
123   % make TEST=dbgopt
124
125 This will test impact of debugging information on optimization passes.  If
126 debugging information influences optimization passes then it will be reported
127 as a failure.  See :doc:`TestingGuide` for more information on LLVM test
128 infrastructure and how to run various tests.
129
130 .. _format:
131
132 Debugging information format
133 ============================
134
135 LLVM debugging information has been carefully designed to make it possible for
136 the optimizer to optimize the program and debugging information without
137 necessarily having to know anything about debugging information.  In
138 particular, the use of metadata avoids duplicated debugging information from
139 the beginning, and the global dead code elimination pass automatically deletes
140 debugging information for a function if it decides to delete the function.
141
142 To do this, most of the debugging information (descriptors for types,
143 variables, functions, source files, etc) is inserted by the language front-end
144 in the form of LLVM metadata.
145
146 Debug information is designed to be agnostic about the target debugger and
147 debugging information representation (e.g. DWARF/Stabs/etc).  It uses a generic
148 pass to decode the information that represents variables, types, functions,
149 namespaces, etc: this allows for arbitrary source-language semantics and
150 type-systems to be used, as long as there is a module written for the target
151 debugger to interpret the information.
152
153 To provide basic functionality, the LLVM debugger does have to make some
154 assumptions about the source-level language being debugged, though it keeps
155 these to a minimum.  The only common features that the LLVM debugger assumes
156 exist are :ref:`source files <format_files>`, and :ref:`program objects
157 <format_global_variables>`.  These abstract objects are used by a debugger to
158 form stack traces, show information about local variables, etc.
159
160 This section of the documentation first describes the representation aspects
161 common to any source-language.  :ref:`ccxx_frontend` describes the data layout
162 conventions used by the C and C++ front-ends.
163
164 Debug information descriptors
165 -----------------------------
166
167 In consideration of the complexity and volume of debug information, LLVM
168 provides a specification for well formed debug descriptors.
169
170 Consumers of LLVM debug information expect the descriptors for program objects
171 to start in a canonical format, but the descriptors can include additional
172 information appended at the end that is source-language specific.  All debugging
173 information objects start with a tag to indicate what type of object it is.
174 The source-language is allowed to define its own objects, by using unreserved
175 tag numbers.  We recommend using with tags in the range 0x1000 through 0x2000
176 (there is a defined ``enum DW_TAG_user_base = 0x1000``.)
177
178 The fields of debug descriptors used internally by LLVM are restricted to only
179 the simple data types ``i32``, ``i1``, ``float``, ``double``, ``mdstring`` and
180 ``mdnode``.
181
182 .. code-block:: llvm
183
184   !1 = metadata !{
185     i32,   ;; A tag
186     ...
187   }
188
189 <a name="LLVMDebugVersion">The first field of a descriptor is always an
190 ``i32`` containing a tag value identifying the content of the descriptor.
191 The remaining fields are specific to the descriptor.  The values of tags are
192 loosely bound to the tag values of DWARF information entries.  However, that
193 does not restrict the use of the information supplied to DWARF targets.
194
195 The details of the various descriptors follow.
196
197 Compile unit descriptors
198 ^^^^^^^^^^^^^^^^^^^^^^^^
199
200 .. code-block:: llvm
201
202   !0 = metadata !{
203     i32,       ;; Tag = 17 (DW_TAG_compile_unit)
204     metadata,  ;; Source directory (including trailing slash) & file pair
205     i32,       ;; DWARF language identifier (ex. DW_LANG_C89)
206     metadata   ;; Producer (ex. "4.0.1 LLVM (LLVM research group)")
207     i1,        ;; True if this is optimized.
208     metadata,  ;; Flags
209     i32        ;; Runtime version
210     metadata   ;; List of enums types
211     metadata   ;; List of retained types
212     metadata   ;; List of subprograms
213     metadata   ;; List of global variables
214     metadata   ;; List of imported entities
215     metadata   ;; Split debug filename
216     i32        ;; Debug info emission kind (1 = Full Debug Info, 2 = Line Tables Only)
217   }
218
219 These descriptors contain a source language ID for the file (we use the DWARF
220 3.0 ID numbers, such as ``DW_LANG_C89``, ``DW_LANG_C_plus_plus``,
221 ``DW_LANG_Cobol74``, etc), a reference to a metadata node containing a pair of
222 strings for the source file name and the working directory, as well as an
223 identifier string for the compiler that produced it.
224
225 Compile unit descriptors provide the root context for objects declared in a
226 specific compilation unit.  File descriptors are defined using this context.
227 These descriptors are collected by a named metadata ``!llvm.dbg.cu``.  They
228 keep track of subprograms, global variables, type information, and imported
229 entities (declarations and namespaces).
230
231 .. _format_files:
232
233 File descriptors
234 ^^^^^^^^^^^^^^^^
235
236 .. code-block:: llvm
237
238   !0 = metadata !{
239     i32,      ;; Tag = 41 (DW_TAG_file_type)
240     metadata, ;; Source directory (including trailing slash) & file pair
241   }
242
243 These descriptors contain information for a file.  Global variables and top
244 level functions would be defined using this context.  File descriptors also
245 provide context for source line correspondence.
246
247 Each input file is encoded as a separate file descriptor in LLVM debugging
248 information output.
249
250 .. _format_global_variables:
251
252 Global variable descriptors
253 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
254
255 .. code-block:: llvm
256
257   !1 = metadata !{
258     i32,      ;; Tag = 52 (DW_TAG_variable)
259     i32,      ;; Unused field.
260     metadata, ;; Reference to context descriptor
261     metadata, ;; Name
262     metadata, ;; Display name (fully qualified C++ name)
263     metadata, ;; MIPS linkage name (for C++)
264     metadata, ;; Reference to file where defined
265     i32,      ;; Line number where defined
266     metadata, ;; Reference to type descriptor
267     i1,       ;; True if the global is local to compile unit (static)
268     i1,       ;; True if the global is defined in the compile unit (not extern)
269     {}*,      ;; Reference to the global variable
270     metadata, ;; The static member declaration, if any
271   }
272
273 These descriptors provide debug information about global variables.  They
274 provide details such as name, type and where the variable is defined.  All
275 global variables are collected inside the named metadata ``!llvm.dbg.cu``.
276
277 .. _format_subprograms:
278
279 Subprogram descriptors
280 ^^^^^^^^^^^^^^^^^^^^^^
281
282 .. code-block:: llvm
283
284   !2 = metadata !{
285     i32,      ;; Tag = 46 (DW_TAG_subprogram)
286     metadata, ;; Source directory (including trailing slash) & file pair
287     metadata, ;; Reference to context descriptor
288     metadata, ;; Name
289     metadata, ;; Display name (fully qualified C++ name)
290     metadata, ;; MIPS linkage name (for C++)
291     i32,      ;; Line number where defined
292     metadata, ;; Reference to type descriptor
293     i1,       ;; True if the global is local to compile unit (static)
294     i1,       ;; True if the global is defined in the compile unit (not extern)
295     i32,      ;; Virtuality, e.g. dwarf::DW_VIRTUALITY__virtual
296     i32,      ;; Index into a virtual function
297     metadata, ;; indicates which base type contains the vtable pointer for the
298               ;; derived class
299     i32,      ;; Flags - Artificial, Private, Protected, Explicit, Prototyped.
300     i1,       ;; isOptimized
301     {}*,      ;; Reference to the LLVM function
302     metadata, ;; Lists function template parameters
303     metadata, ;; Function declaration descriptor
304     metadata, ;; List of function variables
305     i32       ;; Line number where the scope of the subprogram begins
306   }
307
308 These descriptors provide debug information about functions, methods and
309 subprograms.  They provide details such as name, return types and the source
310 location where the subprogram is defined.
311
312 Block descriptors
313 ^^^^^^^^^^^^^^^^^
314
315 .. code-block:: llvm
316
317   !3 = metadata !{
318     i32,      ;; Tag = 11 (DW_TAG_lexical_block)
319     metadata, ;; Source directory (including trailing slash) & file pair
320     metadata, ;; Reference to context descriptor
321     i32,      ;; Line number
322     i32,      ;; Column number
323     i32,      ;; DWARF path discriminator value
324     i32       ;; Unique ID to identify blocks from a template function
325   }
326
327 This descriptor provides debug information about nested blocks within a
328 subprogram.  The line number and column numbers are used to dinstinguish two
329 lexical blocks at same depth.
330
331 .. code-block:: llvm
332
333   !3 = metadata !{
334     i32,      ;; Tag = 11 (DW_TAG_lexical_block)
335     metadata, ;; Source directory (including trailing slash) & file pair
336     metadata  ;; Reference to the scope we're annotating with a file change
337   }
338
339 This descriptor provides a wrapper around a lexical scope to handle file
340 changes in the middle of a lexical block.
341
342 .. _format_basic_type:
343
344 Basic type descriptors
345 ^^^^^^^^^^^^^^^^^^^^^^
346
347 .. code-block:: llvm
348
349   !4 = metadata !{
350     i32,      ;; Tag = 36 (DW_TAG_base_type)
351     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
352     metadata, ;; Reference to context
353     metadata, ;; Name (may be "" for anonymous types)
354     i32,      ;; Line number where defined (may be 0)
355     i64,      ;; Size in bits
356     i64,      ;; Alignment in bits
357     i64,      ;; Offset in bits
358     i32,      ;; Flags
359     i32       ;; DWARF type encoding
360   }
361
362 These descriptors define primitive types used in the code.  Example ``int``,
363 ``bool`` and ``float``.  The context provides the scope of the type, which is
364 usually the top level.  Since basic types are not usually user defined the
365 context and line number can be left as NULL and 0.  The size, alignment and
366 offset are expressed in bits and can be 64 bit values.  The alignment is used
367 to round the offset when embedded in a :ref:`composite type
368 <format_composite_type>` (example to keep float doubles on 64 bit boundaries).
369 The offset is the bit offset if embedded in a :ref:`composite type
370 <format_composite_type>`.
371
372 The type encoding provides the details of the type.  The values are typically
373 one of the following:
374
375 .. code-block:: llvm
376
377   DW_ATE_address       = 1
378   DW_ATE_boolean       = 2
379   DW_ATE_float         = 4
380   DW_ATE_signed        = 5
381   DW_ATE_signed_char   = 6
382   DW_ATE_unsigned      = 7
383   DW_ATE_unsigned_char = 8
384
385 .. _format_derived_type:
386
387 Derived type descriptors
388 ^^^^^^^^^^^^^^^^^^^^^^^^
389
390 .. code-block:: llvm
391
392   !5 = metadata !{
393     i32,      ;; Tag (see below)
394     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
395     metadata, ;; Reference to context
396     metadata, ;; Name (may be "" for anonymous types)
397     i32,      ;; Line number where defined (may be 0)
398     i64,      ;; Size in bits
399     i64,      ;; Alignment in bits
400     i64,      ;; Offset in bits
401     i32,      ;; Flags to encode attributes, e.g. private
402     metadata, ;; Reference to type derived from
403     metadata, ;; (optional) Name of the Objective C property associated with
404               ;; Objective-C an ivar, or the type of which this
405               ;; pointer-to-member is pointing to members of.
406     metadata, ;; (optional) Name of the Objective C property getter selector.
407     metadata, ;; (optional) Name of the Objective C property setter selector.
408     i32       ;; (optional) Objective C property attributes.
409   }
410
411 These descriptors are used to define types derived from other types.  The value
412 of the tag varies depending on the meaning.  The following are possible tag
413 values:
414
415 .. code-block:: llvm
416
417   DW_TAG_formal_parameter   = 5
418   DW_TAG_member             = 13
419   DW_TAG_pointer_type       = 15
420   DW_TAG_reference_type     = 16
421   DW_TAG_typedef            = 22
422   DW_TAG_ptr_to_member_type = 31
423   DW_TAG_const_type         = 38
424   DW_TAG_volatile_type      = 53
425   DW_TAG_restrict_type      = 55
426
427 ``DW_TAG_member`` is used to define a member of a :ref:`composite type
428 <format_composite_type>` or :ref:`subprogram <format_subprograms>`.  The type
429 of the member is the :ref:`derived type <format_derived_type>`.
430 ``DW_TAG_formal_parameter`` is used to define a member which is a formal
431 argument of a subprogram.
432
433 ``DW_TAG_typedef`` is used to provide a name for the derived type.
434
435 ``DW_TAG_pointer_type``, ``DW_TAG_reference_type``, ``DW_TAG_const_type``,
436 ``DW_TAG_volatile_type`` and ``DW_TAG_restrict_type`` are used to qualify the
437 :ref:`derived type <format_derived_type>`.
438
439 :ref:`Derived type <format_derived_type>` location can be determined from the
440 context and line number.  The size, alignment and offset are expressed in bits
441 and can be 64 bit values.  The alignment is used to round the offset when
442 embedded in a :ref:`composite type <format_composite_type>`  (example to keep
443 float doubles on 64 bit boundaries.) The offset is the bit offset if embedded
444 in a :ref:`composite type <format_composite_type>`.
445
446 Note that the ``void *`` type is expressed as a type derived from NULL.
447
448 .. _format_composite_type:
449
450 Composite type descriptors
451 ^^^^^^^^^^^^^^^^^^^^^^^^^^
452
453 .. code-block:: llvm
454
455   !6 = metadata !{
456     i32,      ;; Tag (see below)
457     metadata, ;; Source directory (including trailing slash) & file pair (may be null)
458     metadata, ;; Reference to context
459     metadata, ;; Name (may be "" for anonymous types)
460     i32,      ;; Line number where defined (may be 0)
461     i64,      ;; Size in bits
462     i64,      ;; Alignment in bits
463     i64,      ;; Offset in bits
464     i32,      ;; Flags
465     metadata, ;; Reference to type derived from
466     metadata, ;; Reference to array of member descriptors
467     i32,      ;; Runtime languages
468     metadata, ;; Base type containing the vtable pointer for this type
469     metadata, ;; Template parameters
470     metadata  ;; A unique identifier for type uniquing purpose (may be null)
471   }
472
473 These descriptors are used to define types that are composed of 0 or more
474 elements.  The value of the tag varies depending on the meaning.  The following
475 are possible tag values:
476
477 .. code-block:: llvm
478
479   DW_TAG_array_type       = 1
480   DW_TAG_enumeration_type = 4
481   DW_TAG_structure_type   = 19
482   DW_TAG_union_type       = 23
483   DW_TAG_subroutine_type  = 21
484   DW_TAG_inheritance      = 28
485
486 The vector flag indicates that an array type is a native packed vector.
487
488 The members of array types (tag = ``DW_TAG_array_type``) are
489 :ref:`subrange descriptors <format_subrange>`, each
490 representing the range of subscripts at that level of indexing.
491
492 The members of enumeration types (tag = ``DW_TAG_enumeration_type``) are
493 :ref:`enumerator descriptors <format_enumerator>`, each representing the
494 definition of enumeration value for the set.  All enumeration type descriptors
495 are collected inside the named metadata ``!llvm.dbg.cu``.
496
497 The members of structure (tag = ``DW_TAG_structure_type``) or union (tag =
498 ``DW_TAG_union_type``) types are any one of the :ref:`basic
499 <format_basic_type>`, :ref:`derived <format_derived_type>` or :ref:`composite
500 <format_composite_type>` type descriptors, each representing a field member of
501 the structure or union.
502
503 For C++ classes (tag = ``DW_TAG_structure_type``), member descriptors provide
504 information about base classes, static members and member functions.  If a
505 member is a :ref:`derived type descriptor <format_derived_type>` and has a tag
506 of ``DW_TAG_inheritance``, then the type represents a base class.  If the member
507 of is a :ref:`global variable descriptor <format_global_variables>` then it
508 represents a static member.  And, if the member is a :ref:`subprogram
509 descriptor <format_subprograms>` then it represents a member function.  For
510 static members and member functions, ``getName()`` returns the members link or
511 the C++ mangled name.  ``getDisplayName()`` the simplied version of the name.
512
513 The first member of subroutine (tag = ``DW_TAG_subroutine_type``) type elements
514 is the return type for the subroutine.  The remaining elements are the formal
515 arguments to the subroutine.
516
517 :ref:`Composite type <format_composite_type>` location can be determined from
518 the context and line number.  The size, alignment and offset are expressed in
519 bits and can be 64 bit values.  The alignment is used to round the offset when
520 embedded in a :ref:`composite type <format_composite_type>` (as an example, to
521 keep float doubles on 64 bit boundaries).  The offset is the bit offset if
522 embedded in a :ref:`composite type <format_composite_type>`.
523
524 .. _format_subrange:
525
526 Subrange descriptors
527 ^^^^^^^^^^^^^^^^^^^^
528
529 .. code-block:: llvm
530
531   !42 = metadata !{
532     i32,      ;; Tag = 33 (DW_TAG_subrange_type)
533     i64,      ;; Low value
534     i64       ;; High value
535   }
536
537 These descriptors are used to define ranges of array subscripts for an array
538 :ref:`composite type <format_composite_type>`.  The low value defines the lower
539 bounds typically zero for C/C++.  The high value is the upper bounds.  Values
540 are 64 bit.  ``High - Low + 1`` is the size of the array.  If ``Low > High``
541 the array bounds are not included in generated debugging information.
542
543 .. _format_enumerator:
544
545 Enumerator descriptors
546 ^^^^^^^^^^^^^^^^^^^^^^
547
548 .. code-block:: llvm
549
550   !6 = metadata !{
551     i32,      ;; Tag = 40 (DW_TAG_enumerator)
552     metadata, ;; Name
553     i64       ;; Value
554   }
555
556 These descriptors are used to define members of an enumeration :ref:`composite
557 type <format_composite_type>`, it associates the name to the value.
558
559 Local variables
560 ^^^^^^^^^^^^^^^
561
562 .. code-block:: llvm
563
564   !7 = metadata !{
565     i32,      ;; Tag (see below)
566     metadata, ;; Context
567     metadata, ;; Name
568     metadata, ;; Reference to file where defined
569     i32,      ;; 24 bit - Line number where defined
570               ;; 8 bit - Argument number. 1 indicates 1st argument.
571     metadata, ;; Reference to the type descriptor
572     i32,      ;; flags
573     metadata  ;; (optional) Reference to inline location
574     metadata  ;; (optional) Reference to a complex expression (see below)
575   }
576
577 These descriptors are used to define variables local to a sub program.  The
578 value of the tag depends on the usage of the variable:
579
580 .. code-block:: llvm
581
582   DW_TAG_auto_variable   = 256
583   DW_TAG_arg_variable    = 257
584
585 An auto variable is any variable declared in the body of the function.  An
586 argument variable is any variable that appears as a formal argument to the
587 function.
588
589 The context is either the subprogram or block where the variable is defined.
590 Name the source variable name.  Context and line indicate where the variable
591 was defined.  Type descriptor defines the declared type of the variable.
592
593 The ``OpPiece`` operator is used for (typically larger aggregate)
594 variables that are fragmented across several locations. It takes two
595 i32 arguments, an offset and a size in bytes to describe which piece
596 of the variable is at this location.
597
598
599 .. _format_common_intrinsics:
600
601 Debugger intrinsic functions
602 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
603
604 LLVM uses several intrinsic functions (name prefixed with "``llvm.dbg``") to
605 provide debug information at various points in generated code.
606
607 ``llvm.dbg.declare``
608 ^^^^^^^^^^^^^^^^^^^^
609
610 .. code-block:: llvm
611
612   void %llvm.dbg.declare(metadata, metadata)
613
614 This intrinsic provides information about a local element (e.g., variable).
615 The first argument is metadata holding the alloca for the variable.  The second
616 argument is metadata containing a description of the variable.
617
618 ``llvm.dbg.value``
619 ^^^^^^^^^^^^^^^^^^
620
621 .. code-block:: llvm
622
623   void %llvm.dbg.value(metadata, i64, metadata)
624
625 This intrinsic provides information when a user source variable is set to a new
626 value.  The first argument is the new value (wrapped as metadata).  The second
627 argument is the offset in the user source variable where the new value is
628 written.  The third argument is metadata containing a description of the user
629 source variable.
630
631 Object lifetimes and scoping
632 ============================
633
634 In many languages, the local variables in functions can have their lifetimes or
635 scopes limited to a subset of a function.  In the C family of languages, for
636 example, variables are only live (readable and writable) within the source
637 block that they are defined in.  In functional languages, values are only
638 readable after they have been defined.  Though this is a very obvious concept,
639 it is non-trivial to model in LLVM, because it has no notion of scoping in this
640 sense, and does not want to be tied to a language's scoping rules.
641
642 In order to handle this, the LLVM debug format uses the metadata attached to
643 llvm instructions to encode line number and scoping information.  Consider the
644 following C fragment, for example:
645
646 .. code-block:: c
647
648   1.  void foo() {
649   2.    int X = 21;
650   3.    int Y = 22;
651   4.    {
652   5.      int Z = 23;
653   6.      Z = X;
654   7.    }
655   8.    X = Y;
656   9.  }
657
658 Compiled to LLVM, this function would be represented like this:
659
660 .. code-block:: llvm
661
662   define void @foo() #0 {
663   entry:
664    %X = alloca i32, align 4
665     %Y = alloca i32, align 4
666     %Z = alloca i32, align 4
667     call void @llvm.dbg.declare(metadata !{i32* %X}, metadata !10), !dbg !12
668       ; [debug line = 2:7] [debug variable = X]
669     store i32 21, i32* %X, align 4, !dbg !12
670     call void @llvm.dbg.declare(metadata !{i32* %Y}, metadata !13), !dbg !14
671       ; [debug line = 3:7] [debug variable = Y]
672     store i32 22, i32* %Y, align 4, !dbg !14
673     call void @llvm.dbg.declare(metadata !{i32* %Z}, metadata !15), !dbg !17
674       ; [debug line = 5:9] [debug variable = Z]
675     store i32 23, i32* %Z, align 4, !dbg !17
676     %0 = load i32* %X, align 4, !dbg !18
677       [debug line = 6:5]
678     store i32 %0, i32* %Z, align 4, !dbg !18
679     %1 = load i32* %Y, align 4, !dbg !19
680       [debug line = 8:3]
681     store i32 %1, i32* %X, align 4, !dbg !19
682     ret void, !dbg !20
683   }
684
685   ; Function Attrs: nounwind readnone
686   declare void @llvm.dbg.declare(metadata, metadata) #1
687
688   attributes #0 = { nounwind ssp uwtable "less-precise-fpmad"="false"
689     "no-frame-pointer-elim"="true" "no-frame-pointer-elim-non-leaf"
690     "no-infs-fp-math"="false" "no-nans-fp-math"="false"
691     "stack-protector-buffer-size"="8" "unsafe-fp-math"="false"
692     "use-soft-float"="false" }
693   attributes #1 = { nounwind readnone }
694
695   !llvm.dbg.cu = !{!0}
696   !llvm.module.flags = !{!8}
697   !llvm.ident = !{!9}
698
699   !0 = metadata !{i32 786449, metadata !1, i32 12,
700                   metadata !"clang version 3.4 (trunk 193128) (llvm/trunk 193139)",
701                   i1 false, metadata !"", i32 0, metadata !2, metadata !2, metadata !3,
702                   metadata !2, metadata !2, metadata !""} ; [ DW_TAG_compile_unit ] \
703                     [/private/tmp/foo.c] \
704                     [DW_LANG_C99]
705   !1 = metadata !{metadata !"t.c", metadata !"/private/tmp"}
706   !2 = metadata !{i32 0}
707   !3 = metadata !{metadata !4}
708   !4 = metadata !{i32 786478, metadata !1, metadata !5, metadata !"foo",
709                   metadata !"foo", metadata !"", i32 1, metadata !6,
710                   i1 false, i1 true, i32 0, i32 0, null, i32 0, i1 false,
711                   void ()* @foo, null, null, metadata !2, i32 1}
712                   ; [ DW_TAG_subprogram ] [line 1] [def] [foo]
713   !5 = metadata !{i32 786473, metadata !1}  ; [ DW_TAG_file_type ] \
714                     [/private/tmp/t.c]
715   !6 = metadata !{i32 786453, i32 0, null, metadata !"", i32 0, i64 0, i64 0,
716                   i64 0, i32 0, null, metadata !7, i32 0, null, null, null}
717                   ; [ DW_TAG_subroutine_type ] \
718                     [line 0, size 0, align 0, offset 0] [from ]
719   !7 = metadata !{null}
720   !8 = metadata !{i32 2, metadata !"Dwarf Version", i32 2}
721   !9 = metadata !{metadata !"clang version 3.4 (trunk 193128) (llvm/trunk 193139)"}
722   !10 = metadata !{i32 786688, metadata !4, metadata !"X", metadata !5, i32 2,
723                    metadata !11, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [X] \
724                      [line 2]
725   !11 = metadata !{i32 786468, null, null, metadata !"int", i32 0, i64 32,
726                    i64 32, i64 0, i32 0, i32 5} ; [ DW_TAG_base_type ] [int] \
727                      [line 0, size 32, align 32, offset 0, enc DW_ATE_signed]
728   !12 = metadata !{i32 2, i32 0, metadata !4, null}
729   !13 = metadata !{i32 786688, metadata !4, metadata !"Y", metadata !5, i32 3,
730                    metadata !11, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [Y] \
731                      [line 3]
732   !14 = metadata !{i32 3, i32 0, metadata !4, null}
733   !15 = metadata !{i32 786688, metadata !16, metadata !"Z", metadata !5, i32 5,
734                    metadata !11, i32 0, i32 0} ; [ DW_TAG_auto_variable ] [Z] \
735                      [line 5]
736   !16 = metadata !{i32 786443, metadata !1, metadata !4, i32 4, i32 0, i32 0,
737                    i32 0} \
738                    ; [ DW_TAG_lexical_block ] [/private/tmp/t.c]
739   !17 = metadata !{i32 5, i32 0, metadata !16, null}
740   !18 = metadata !{i32 6, i32 0, metadata !16, null}
741   !19 = metadata !{i32 8, i32 0, metadata !4, null} ; [ DW_TAG_imported_declaration ]
742   !20 = metadata !{i32 9, i32 0, metadata !4, null}
743
744 This example illustrates a few important details about LLVM debugging
745 information.  In particular, it shows how the ``llvm.dbg.declare`` intrinsic and
746 location information, which are attached to an instruction, are applied
747 together to allow a debugger to analyze the relationship between statements,
748 variable definitions, and the code used to implement the function.
749
750 .. code-block:: llvm
751
752   call void @llvm.dbg.declare(metadata !{i32* %X}, metadata !10), !dbg !12
753     ; [debug line = 2:7] [debug variable = X]
754
755 The first intrinsic ``%llvm.dbg.declare`` encodes debugging information for the
756 variable ``X``.  The metadata ``!dbg !12`` attached to the intrinsic provides
757 scope information for the variable ``X``.
758
759 .. code-block:: llvm
760
761   !12 = metadata !{i32 2, i32 0, metadata !4, null}
762   !4 = metadata !{i32 786478, metadata !1, metadata !5, metadata !"foo",
763                   metadata !"foo", metadata !"", i32 1, metadata !6,
764                   i1 false, i1 true, i32 0, i32 0, null, i32 0, i1 false,
765                   void ()* @foo, null, null, metadata !2, i32 1}
766                     ; [ DW_TAG_subprogram ] [line 1] [def] [foo]
767
768 Here ``!12`` is metadata providing location information.  It has four fields:
769 line number, column number, scope, and original scope.  The original scope
770 represents inline location if this instruction is inlined inside a caller, and
771 is null otherwise.  In this example, scope is encoded by ``!4``, a
772 :ref:`subprogram descriptor <format_subprograms>`.  This way the location
773 information attached to the intrinsics indicates that the variable ``X`` is
774 declared at line number 2 at a function level scope in function ``foo``.
775
776 Now lets take another example.
777
778 .. code-block:: llvm
779
780   call void @llvm.dbg.declare(metadata !{i32* %Z}, metadata !15), !dbg !17
781     ; [debug line = 5:9] [debug variable = Z]
782
783 The third intrinsic ``%llvm.dbg.declare`` encodes debugging information for
784 variable ``Z``.  The metadata ``!dbg !17`` attached to the intrinsic provides
785 scope information for the variable ``Z``.
786
787 .. code-block:: llvm
788
789   !16 = metadata !{i32 786443, metadata !1, metadata !4, i32 4, i32 0, i32 0,
790                    i32 0}
791                    ; [ DW_TAG_lexical_block ] [/private/tmp/t.c]
792   !17 = metadata !{i32 5, i32 0, metadata !16, null}
793
794 Here ``!15`` indicates that ``Z`` is declared at line number 5 and
795 column number 0 inside of lexical scope ``!16``.  The lexical scope itself
796 resides inside of subprogram ``!4`` described above.
797
798 The scope information attached with each instruction provides a straightforward
799 way to find instructions covered by a scope.
800
801 .. _ccxx_frontend:
802
803 C/C++ front-end specific debug information
804 ==========================================
805
806 The C and C++ front-ends represent information about the program in a format
807 that is effectively identical to `DWARF 3.0
808 <http://www.eagercon.com/dwarf/dwarf3std.htm>`_ in terms of information
809 content.  This allows code generators to trivially support native debuggers by
810 generating standard dwarf information, and contains enough information for
811 non-dwarf targets to translate it as needed.
812
813 This section describes the forms used to represent C and C++ programs.  Other
814 languages could pattern themselves after this (which itself is tuned to
815 representing programs in the same way that DWARF 3 does), or they could choose
816 to provide completely different forms if they don't fit into the DWARF model.
817 As support for debugging information gets added to the various LLVM
818 source-language front-ends, the information used should be documented here.
819
820 The following sections provide examples of various C/C++ constructs and the
821 debug information that would best describe those constructs.
822
823 C/C++ source file information
824 -----------------------------
825
826 Given the source files ``MySource.cpp`` and ``MyHeader.h`` located in the
827 directory ``/Users/mine/sources``, the following code:
828
829 .. code-block:: c
830
831   #include "MyHeader.h"
832
833   int main(int argc, char *argv[]) {
834     return 0;
835   }
836
837 a C/C++ front-end would generate the following descriptors:
838
839 .. code-block:: llvm
840
841   ...
842   ;;
843   ;; Define the compile unit for the main source file "/Users/mine/sources/MySource.cpp".
844   ;;
845   !0 = metadata !{
846     i32 786449,   ;; Tag
847     metadata !1,  ;; File/directory name
848     i32 4,        ;; Language Id
849     metadata !"clang version 3.4 ",
850     i1 false,     ;; Optimized compile unit
851     metadata !"", ;; Compiler flags
852     i32 0,        ;; Runtime version
853     metadata !2,  ;; Enumeration types
854     metadata !2,  ;; Retained types
855     metadata !3,  ;; Subprograms
856     metadata !2,  ;; Global variables
857     metadata !2,  ;; Imported entities (declarations and namespaces)
858     metadata !""  ;; Split debug filename
859     1,            ;; Full debug info
860   }
861
862   ;;
863   ;; Define the file for the file "/Users/mine/sources/MySource.cpp".
864   ;;
865   !1 = metadata !{
866     metadata !"MySource.cpp",
867     metadata !"/Users/mine/sources"
868   }
869   !5 = metadata !{
870     i32 786473, ;; Tag
871     metadata !1
872   }
873
874   ;;
875   ;; Define the file for the file "/Users/mine/sources/Myheader.h"
876   ;;
877   !14 = metadata !{
878     i32 786473, ;; Tag
879     metadata !15
880   }
881   !15 = metadata !{
882     metadata !"./MyHeader.h",
883     metadata !"/Users/mine/sources",
884   }
885
886   ...
887
888 ``llvm::Instruction`` provides easy access to metadata attached with an
889 instruction.  One can extract line number information encoded in LLVM IR using
890 ``Instruction::getMetadata()`` and ``DILocation::getLineNumber()``.
891
892 .. code-block:: c++
893
894   if (MDNode *N = I->getMetadata("dbg")) {  // Here I is an LLVM instruction
895     DILocation Loc(N);                      // DILocation is in DebugInfo.h
896     unsigned Line = Loc.getLineNumber();
897     StringRef File = Loc.getFilename();
898     StringRef Dir = Loc.getDirectory();
899   }
900
901 C/C++ global variable information
902 ---------------------------------
903
904 Given an integer global variable declared as follows:
905
906 .. code-block:: c
907
908   int MyGlobal = 100;
909
910 a C/C++ front-end would generate the following descriptors:
911
912 .. code-block:: llvm
913
914   ;;
915   ;; Define the global itself.
916   ;;
917   %MyGlobal = global int 100
918   ...
919   ;;
920   ;; List of debug info of globals
921   ;;
922   !llvm.dbg.cu = !{!0}
923
924   ;; Define the compile unit.
925   !0 = metadata !{
926     i32 786449,                       ;; Tag
927     i32 0,                            ;; Context
928     i32 4,                            ;; Language
929     metadata !"foo.cpp",              ;; File
930     metadata !"/Volumes/Data/tmp",    ;; Directory
931     metadata !"clang version 3.1 ",   ;; Producer
932     i1 true,                          ;; Deprecated field
933     i1 false,                         ;; "isOptimized"?
934     metadata !"",                     ;; Flags
935     i32 0,                            ;; Runtime Version
936     metadata !1,                      ;; Enum Types
937     metadata !1,                      ;; Retained Types
938     metadata !1,                      ;; Subprograms
939     metadata !3,                      ;; Global Variables
940     metadata !1,                      ;; Imported entities
941     "",                               ;; Split debug filename
942     1,                                ;; Full debug info
943   } ; [ DW_TAG_compile_unit ]
944
945   ;; The Array of Global Variables
946   !3 = metadata !{
947     metadata !4
948   }
949
950   ;;
951   ;; Define the global variable itself.
952   ;;
953   !4 = metadata !{
954     i32 786484,                        ;; Tag
955     i32 0,                             ;; Unused
956     null,                              ;; Unused
957     metadata !"MyGlobal",              ;; Name
958     metadata !"MyGlobal",              ;; Display Name
959     metadata !"",                      ;; Linkage Name
960     metadata !6,                       ;; File
961     i32 1,                             ;; Line
962     metadata !7,                       ;; Type
963     i32 0,                             ;; IsLocalToUnit
964     i32 1,                             ;; IsDefinition
965     i32* @MyGlobal,                    ;; LLVM-IR Value
966     null                               ;; Static member declaration
967   } ; [ DW_TAG_variable ]
968
969   ;;
970   ;; Define the file
971   ;;
972   !5 = metadata !{
973     metadata !"foo.cpp",               ;; File
974     metadata !"/Volumes/Data/tmp",     ;; Directory
975   }
976   !6 = metadata !{
977     i32 786473,                        ;; Tag
978     metadata !5                        ;; Unused
979   } ; [ DW_TAG_file_type ]
980
981   ;;
982   ;; Define the type
983   ;;
984   !7 = metadata !{
985     i32 786468,                         ;; Tag
986     null,                               ;; Unused
987     null,                               ;; Unused
988     metadata !"int",                    ;; Name
989     i32 0,                              ;; Line
990     i64 32,                             ;; Size in Bits
991     i64 32,                             ;; Align in Bits
992     i64 0,                              ;; Offset
993     i32 0,                              ;; Flags
994     i32 5                               ;; Encoding
995   } ; [ DW_TAG_base_type ]
996
997 C/C++ function information
998 --------------------------
999
1000 Given a function declared as follows:
1001
1002 .. code-block:: c
1003
1004   int main(int argc, char *argv[]) {
1005     return 0;
1006   }
1007
1008 a C/C++ front-end would generate the following descriptors:
1009
1010 .. code-block:: llvm
1011
1012   ;;
1013   ;; Define the anchor for subprograms.
1014   ;;
1015   !6 = metadata !{
1016     i32 786484,        ;; Tag
1017     metadata !1,       ;; File
1018     metadata !1,       ;; Context
1019     metadata !"main",  ;; Name
1020     metadata !"main",  ;; Display name
1021     metadata !"main",  ;; Linkage name
1022     i32 1,             ;; Line number
1023     metadata !4,       ;; Type
1024     i1 false,          ;; Is local
1025     i1 true,           ;; Is definition
1026     i32 0,             ;; Virtuality attribute, e.g. pure virtual function
1027     i32 0,             ;; Index into virtual table for C++ methods
1028     i32 0,             ;; Type that holds virtual table.
1029     i32 0,             ;; Flags
1030     i1 false,          ;; True if this function is optimized
1031     Function *,        ;; Pointer to llvm::Function
1032     null,              ;; Function template parameters
1033     null,              ;; List of function variables (emitted when optimizing)
1034     1                  ;; Line number of the opening '{' of the function
1035   }
1036   ;;
1037   ;; Define the subprogram itself.
1038   ;;
1039   define i32 @main(i32 %argc, i8** %argv) {
1040   ...
1041   }
1042
1043 C/C++ basic types
1044 -----------------
1045
1046 The following are the basic type descriptors for C/C++ core types:
1047
1048 bool
1049 ^^^^
1050
1051 .. code-block:: llvm
1052
1053   !2 = metadata !{
1054     i32 786468,        ;; Tag
1055     null,              ;; File
1056     null,              ;; Context
1057     metadata !"bool",  ;; Name
1058     i32 0,             ;; Line number
1059     i64 8,             ;; Size in Bits
1060     i64 8,             ;; Align in Bits
1061     i64 0,             ;; Offset in Bits
1062     i32 0,             ;; Flags
1063     i32 2              ;; Encoding
1064   }
1065
1066 char
1067 ^^^^
1068
1069 .. code-block:: llvm
1070
1071   !2 = metadata !{
1072     i32 786468,        ;; Tag
1073     null,              ;; File
1074     null,              ;; Context
1075     metadata !"char",  ;; Name
1076     i32 0,             ;; Line number
1077     i64 8,             ;; Size in Bits
1078     i64 8,             ;; Align in Bits
1079     i64 0,             ;; Offset in Bits
1080     i32 0,             ;; Flags
1081     i32 6              ;; Encoding
1082   }
1083
1084 unsigned char
1085 ^^^^^^^^^^^^^
1086
1087 .. code-block:: llvm
1088
1089   !2 = metadata !{
1090     i32 786468,        ;; Tag
1091     null,              ;; File
1092     null,              ;; Context
1093     metadata !"unsigned char",
1094     i32 0,             ;; Line number
1095     i64 8,             ;; Size in Bits
1096     i64 8,             ;; Align in Bits
1097     i64 0,             ;; Offset in Bits
1098     i32 0,             ;; Flags
1099     i32 8              ;; Encoding
1100   }
1101
1102 short
1103 ^^^^^
1104
1105 .. code-block:: llvm
1106
1107   !2 = metadata !{
1108     i32 786468,        ;; Tag
1109     null,              ;; File
1110     null,              ;; Context
1111     metadata !"short int",
1112     i32 0,             ;; Line number
1113     i64 16,            ;; Size in Bits
1114     i64 16,            ;; Align in Bits
1115     i64 0,             ;; Offset in Bits
1116     i32 0,             ;; Flags
1117     i32 5              ;; Encoding
1118   }
1119
1120 unsigned short
1121 ^^^^^^^^^^^^^^
1122
1123 .. code-block:: llvm
1124
1125   !2 = metadata !{
1126     i32 786468,        ;; Tag
1127     null,              ;; File
1128     null,              ;; Context
1129     metadata !"short unsigned int",
1130     i32 0,             ;; Line number
1131     i64 16,            ;; Size in Bits
1132     i64 16,            ;; Align in Bits
1133     i64 0,             ;; Offset in Bits
1134     i32 0,             ;; Flags
1135     i32 7              ;; Encoding
1136   }
1137
1138 int
1139 ^^^
1140
1141 .. code-block:: llvm
1142
1143   !2 = metadata !{
1144     i32 786468,        ;; Tag
1145     null,              ;; File
1146     null,              ;; Context
1147     metadata !"int",   ;; Name
1148     i32 0,             ;; Line number
1149     i64 32,            ;; Size in Bits
1150     i64 32,            ;; Align in Bits
1151     i64 0,             ;; Offset in Bits
1152     i32 0,             ;; Flags
1153     i32 5              ;; Encoding
1154   }
1155
1156 unsigned int
1157 ^^^^^^^^^^^^
1158
1159 .. code-block:: llvm
1160
1161   !2 = metadata !{
1162     i32 786468,        ;; Tag
1163     null,              ;; File
1164     null,              ;; Context
1165     metadata !"unsigned int",
1166     i32 0,             ;; Line number
1167     i64 32,            ;; Size in Bits
1168     i64 32,            ;; Align in Bits
1169     i64 0,             ;; Offset in Bits
1170     i32 0,             ;; Flags
1171     i32 7              ;; Encoding
1172   }
1173
1174 long long
1175 ^^^^^^^^^
1176
1177 .. code-block:: llvm
1178
1179   !2 = metadata !{
1180     i32 786468,        ;; Tag
1181     null,              ;; File
1182     null,              ;; Context
1183     metadata !"long long int",
1184     i32 0,             ;; Line number
1185     i64 64,            ;; Size in Bits
1186     i64 64,            ;; Align in Bits
1187     i64 0,             ;; Offset in Bits
1188     i32 0,             ;; Flags
1189     i32 5              ;; Encoding
1190   }
1191
1192 unsigned long long
1193 ^^^^^^^^^^^^^^^^^^
1194
1195 .. code-block:: llvm
1196
1197   !2 = metadata !{
1198     i32 786468,        ;; Tag
1199     null,              ;; File
1200     null,              ;; Context
1201     metadata !"long long unsigned int",
1202     i32 0,             ;; Line number
1203     i64 64,            ;; Size in Bits
1204     i64 64,            ;; Align in Bits
1205     i64 0,             ;; Offset in Bits
1206     i32 0,             ;; Flags
1207     i32 7              ;; Encoding
1208   }
1209
1210 float
1211 ^^^^^
1212
1213 .. code-block:: llvm
1214
1215   !2 = metadata !{
1216     i32 786468,        ;; Tag
1217     null,              ;; File
1218     null,              ;; Context
1219     metadata !"float",
1220     i32 0,             ;; Line number
1221     i64 32,            ;; Size in Bits
1222     i64 32,            ;; Align in Bits
1223     i64 0,             ;; Offset in Bits
1224     i32 0,             ;; Flags
1225     i32 4              ;; Encoding
1226   }
1227
1228 double
1229 ^^^^^^
1230
1231 .. code-block:: llvm
1232
1233   !2 = metadata !{
1234     i32 786468,        ;; Tag
1235     null,              ;; File
1236     null,              ;; Context
1237     metadata !"double",;; Name
1238     i32 0,             ;; Line number
1239     i64 64,            ;; Size in Bits
1240     i64 64,            ;; Align in Bits
1241     i64 0,             ;; Offset in Bits
1242     i32 0,             ;; Flags
1243     i32 4              ;; Encoding
1244   }
1245
1246 C/C++ derived types
1247 -------------------
1248
1249 Given the following as an example of C/C++ derived type:
1250
1251 .. code-block:: c
1252
1253   typedef const int *IntPtr;
1254
1255 a C/C++ front-end would generate the following descriptors:
1256
1257 .. code-block:: llvm
1258
1259   ;;
1260   ;; Define the typedef "IntPtr".
1261   ;;
1262   !2 = metadata !{
1263     i32 786454,          ;; Tag
1264     metadata !3,         ;; File
1265     metadata !1,         ;; Context
1266     metadata !"IntPtr",  ;; Name
1267     i32 0,               ;; Line number
1268     i64 0,               ;; Size in bits
1269     i64 0,               ;; Align in bits
1270     i64 0,               ;; Offset in bits
1271     i32 0,               ;; Flags
1272     metadata !4          ;; Derived From type
1273   }
1274   ;;
1275   ;; Define the pointer type.
1276   ;;
1277   !4 = metadata !{
1278     i32 786447,          ;; Tag
1279     null,                ;; File
1280     null,                ;; Context
1281     metadata !"",        ;; Name
1282     i32 0,               ;; Line number
1283     i64 64,              ;; Size in bits
1284     i64 64,              ;; Align in bits
1285     i64 0,               ;; Offset in bits
1286     i32 0,               ;; Flags
1287     metadata !5          ;; Derived From type
1288   }
1289   ;;
1290   ;; Define the const type.
1291   ;;
1292   !5 = metadata !{
1293     i32 786470,          ;; Tag
1294     null,                ;; File
1295     null,                ;; Context
1296     metadata !"",        ;; Name
1297     i32 0,               ;; Line number
1298     i64 0,               ;; Size in bits
1299     i64 0,               ;; Align in bits
1300     i64 0,               ;; Offset in bits
1301     i32 0,               ;; Flags
1302     metadata !6          ;; Derived From type
1303   }
1304   ;;
1305   ;; Define the int type.
1306   ;;
1307   !6 = metadata !{
1308     i32 786468,          ;; Tag
1309     null,                ;; File
1310     null,                ;; Context
1311     metadata !"int",     ;; Name
1312     i32 0,               ;; Line number
1313     i64 32,              ;; Size in bits
1314     i64 32,              ;; Align in bits
1315     i64 0,               ;; Offset in bits
1316     i32 0,               ;; Flags
1317     i32 5                ;; Encoding
1318   }
1319
1320 C/C++ struct/union types
1321 ------------------------
1322
1323 Given the following as an example of C/C++ struct type:
1324
1325 .. code-block:: c
1326
1327   struct Color {
1328     unsigned Red;
1329     unsigned Green;
1330     unsigned Blue;
1331   };
1332
1333 a C/C++ front-end would generate the following descriptors:
1334
1335 .. code-block:: llvm
1336
1337   ;;
1338   ;; Define basic type for unsigned int.
1339   ;;
1340   !5 = metadata !{
1341     i32 786468,        ;; Tag
1342     null,              ;; File
1343     null,              ;; Context
1344     metadata !"unsigned int",
1345     i32 0,             ;; Line number
1346     i64 32,            ;; Size in Bits
1347     i64 32,            ;; Align in Bits
1348     i64 0,             ;; Offset in Bits
1349     i32 0,             ;; Flags
1350     i32 7              ;; Encoding
1351   }
1352   ;;
1353   ;; Define composite type for struct Color.
1354   ;;
1355   !2 = metadata !{
1356     i32 786451,        ;; Tag
1357     metadata !1,       ;; Compile unit
1358     null,              ;; Context
1359     metadata !"Color", ;; Name
1360     i32 1,             ;; Line number
1361     i64 96,            ;; Size in bits
1362     i64 32,            ;; Align in bits
1363     i64 0,             ;; Offset in bits
1364     i32 0,             ;; Flags
1365     null,              ;; Derived From
1366     metadata !3,       ;; Elements
1367     i32 0,             ;; Runtime Language
1368     null,              ;; Base type containing the vtable pointer for this type
1369     null               ;; Template parameters
1370   }
1371
1372   ;;
1373   ;; Define the Red field.
1374   ;;
1375   !4 = metadata !{
1376     i32 786445,        ;; Tag
1377     metadata !1,       ;; File
1378     metadata !1,       ;; Context
1379     metadata !"Red",   ;; Name
1380     i32 2,             ;; Line number
1381     i64 32,            ;; Size in bits
1382     i64 32,            ;; Align in bits
1383     i64 0,             ;; Offset in bits
1384     i32 0,             ;; Flags
1385     metadata !5        ;; Derived From type
1386   }
1387
1388   ;;
1389   ;; Define the Green field.
1390   ;;
1391   !6 = metadata !{
1392     i32 786445,        ;; Tag
1393     metadata !1,       ;; File
1394     metadata !1,       ;; Context
1395     metadata !"Green", ;; Name
1396     i32 3,             ;; Line number
1397     i64 32,            ;; Size in bits
1398     i64 32,            ;; Align in bits
1399     i64 32,             ;; Offset in bits
1400     i32 0,             ;; Flags
1401     metadata !5        ;; Derived From type
1402   }
1403
1404   ;;
1405   ;; Define the Blue field.
1406   ;;
1407   !7 = metadata !{
1408     i32 786445,        ;; Tag
1409     metadata !1,       ;; File
1410     metadata !1,       ;; Context
1411     metadata !"Blue",  ;; Name
1412     i32 4,             ;; Line number
1413     i64 32,            ;; Size in bits
1414     i64 32,            ;; Align in bits
1415     i64 64,             ;; Offset in bits
1416     i32 0,             ;; Flags
1417     metadata !5        ;; Derived From type
1418   }
1419
1420   ;;
1421   ;; Define the array of fields used by the composite type Color.
1422   ;;
1423   !3 = metadata !{metadata !4, metadata !6, metadata !7}
1424
1425 C/C++ enumeration types
1426 -----------------------
1427
1428 Given the following as an example of C/C++ enumeration type:
1429
1430 .. code-block:: c
1431
1432   enum Trees {
1433     Spruce = 100,
1434     Oak = 200,
1435     Maple = 300
1436   };
1437
1438 a C/C++ front-end would generate the following descriptors:
1439
1440 .. code-block:: llvm
1441
1442   ;;
1443   ;; Define composite type for enum Trees
1444   ;;
1445   !2 = metadata !{
1446     i32 786436,        ;; Tag
1447     metadata !1,       ;; File
1448     metadata !1,       ;; Context
1449     metadata !"Trees", ;; Name
1450     i32 1,             ;; Line number
1451     i64 32,            ;; Size in bits
1452     i64 32,            ;; Align in bits
1453     i64 0,             ;; Offset in bits
1454     i32 0,             ;; Flags
1455     null,              ;; Derived From type
1456     metadata !3,       ;; Elements
1457     i32 0              ;; Runtime language
1458   }
1459
1460   ;;
1461   ;; Define the array of enumerators used by composite type Trees.
1462   ;;
1463   !3 = metadata !{metadata !4, metadata !5, metadata !6}
1464
1465   ;;
1466   ;; Define Spruce enumerator.
1467   ;;
1468   !4 = metadata !{i32 786472, metadata !"Spruce", i64 100}
1469
1470   ;;
1471   ;; Define Oak enumerator.
1472   ;;
1473   !5 = metadata !{i32 786472, metadata !"Oak", i64 200}
1474
1475   ;;
1476   ;; Define Maple enumerator.
1477   ;;
1478   !6 = metadata !{i32 786472, metadata !"Maple", i64 300}
1479
1480 Debugging information format
1481 ============================
1482
1483 Debugging Information Extension for Objective C Properties
1484 ----------------------------------------------------------
1485
1486 Introduction
1487 ^^^^^^^^^^^^
1488
1489 Objective C provides a simpler way to declare and define accessor methods using
1490 declared properties.  The language provides features to declare a property and
1491 to let compiler synthesize accessor methods.
1492
1493 The debugger lets developer inspect Objective C interfaces and their instance
1494 variables and class variables.  However, the debugger does not know anything
1495 about the properties defined in Objective C interfaces.  The debugger consumes
1496 information generated by compiler in DWARF format.  The format does not support
1497 encoding of Objective C properties.  This proposal describes DWARF extensions to
1498 encode Objective C properties, which the debugger can use to let developers
1499 inspect Objective C properties.
1500
1501 Proposal
1502 ^^^^^^^^
1503
1504 Objective C properties exist separately from class members.  A property can be
1505 defined only by "setter" and "getter" selectors, and be calculated anew on each
1506 access.  Or a property can just be a direct access to some declared ivar.
1507 Finally it can have an ivar "automatically synthesized" for it by the compiler,
1508 in which case the property can be referred to in user code directly using the
1509 standard C dereference syntax as well as through the property "dot" syntax, but
1510 there is no entry in the ``@interface`` declaration corresponding to this ivar.
1511
1512 To facilitate debugging, these properties we will add a new DWARF TAG into the
1513 ``DW_TAG_structure_type`` definition for the class to hold the description of a
1514 given property, and a set of DWARF attributes that provide said description.
1515 The property tag will also contain the name and declared type of the property.
1516
1517 If there is a related ivar, there will also be a DWARF property attribute placed
1518 in the ``DW_TAG_member`` DIE for that ivar referring back to the property TAG
1519 for that property.  And in the case where the compiler synthesizes the ivar
1520 directly, the compiler is expected to generate a ``DW_TAG_member`` for that
1521 ivar (with the ``DW_AT_artificial`` set to 1), whose name will be the name used
1522 to access this ivar directly in code, and with the property attribute pointing
1523 back to the property it is backing.
1524
1525 The following examples will serve as illustration for our discussion:
1526
1527 .. code-block:: objc
1528
1529   @interface I1 {
1530     int n2;
1531   }
1532
1533   @property int p1;
1534   @property int p2;
1535   @end
1536
1537   @implementation I1
1538   @synthesize p1;
1539   @synthesize p2 = n2;
1540   @end
1541
1542 This produces the following DWARF (this is a "pseudo dwarfdump" output):
1543
1544 .. code-block:: none
1545
1546   0x00000100:  TAG_structure_type [7] *
1547                  AT_APPLE_runtime_class( 0x10 )
1548                  AT_name( "I1" )
1549                  AT_decl_file( "Objc_Property.m" )
1550                  AT_decl_line( 3 )
1551
1552   0x00000110    TAG_APPLE_property
1553                   AT_name ( "p1" )
1554                   AT_type ( {0x00000150} ( int ) )
1555
1556   0x00000120:   TAG_APPLE_property
1557                   AT_name ( "p2" )
1558                   AT_type ( {0x00000150} ( int ) )
1559
1560   0x00000130:   TAG_member [8]
1561                   AT_name( "_p1" )
1562                   AT_APPLE_property ( {0x00000110} "p1" )
1563                   AT_type( {0x00000150} ( int ) )
1564                   AT_artificial ( 0x1 )
1565
1566   0x00000140:    TAG_member [8]
1567                    AT_name( "n2" )
1568                    AT_APPLE_property ( {0x00000120} "p2" )
1569                    AT_type( {0x00000150} ( int ) )
1570
1571   0x00000150:  AT_type( ( int ) )
1572
1573 Note, the current convention is that the name of the ivar for an
1574 auto-synthesized property is the name of the property from which it derives
1575 with an underscore prepended, as is shown in the example.  But we actually
1576 don't need to know this convention, since we are given the name of the ivar
1577 directly.
1578
1579 Also, it is common practice in ObjC to have different property declarations in
1580 the @interface and @implementation - e.g. to provide a read-only property in
1581 the interface,and a read-write interface in the implementation.  In that case,
1582 the compiler should emit whichever property declaration will be in force in the
1583 current translation unit.
1584
1585 Developers can decorate a property with attributes which are encoded using
1586 ``DW_AT_APPLE_property_attribute``.
1587
1588 .. code-block:: objc
1589
1590   @property (readonly, nonatomic) int pr;
1591
1592 .. code-block:: none
1593
1594   TAG_APPLE_property [8]
1595     AT_name( "pr" )
1596     AT_type ( {0x00000147} (int) )
1597     AT_APPLE_property_attribute (DW_APPLE_PROPERTY_readonly, DW_APPLE_PROPERTY_nonatomic)
1598
1599 The setter and getter method names are attached to the property using
1600 ``DW_AT_APPLE_property_setter`` and ``DW_AT_APPLE_property_getter`` attributes.
1601
1602 .. code-block:: objc
1603
1604   @interface I1
1605   @property (setter=myOwnP3Setter:) int p3;
1606   -(void)myOwnP3Setter:(int)a;
1607   @end
1608
1609   @implementation I1
1610   @synthesize p3;
1611   -(void)myOwnP3Setter:(int)a{ }
1612   @end
1613
1614 The DWARF for this would be:
1615
1616 .. code-block:: none
1617
1618   0x000003bd: TAG_structure_type [7] *
1619                 AT_APPLE_runtime_class( 0x10 )
1620                 AT_name( "I1" )
1621                 AT_decl_file( "Objc_Property.m" )
1622                 AT_decl_line( 3 )
1623
1624   0x000003cd      TAG_APPLE_property
1625                     AT_name ( "p3" )
1626                     AT_APPLE_property_setter ( "myOwnP3Setter:" )
1627                     AT_type( {0x00000147} ( int ) )
1628
1629   0x000003f3:     TAG_member [8]
1630                     AT_name( "_p3" )
1631                     AT_type ( {0x00000147} ( int ) )
1632                     AT_APPLE_property ( {0x000003cd} )
1633                     AT_artificial ( 0x1 )
1634
1635 New DWARF Tags
1636 ^^^^^^^^^^^^^^
1637
1638 +-----------------------+--------+
1639 | TAG                   | Value  |
1640 +=======================+========+
1641 | DW_TAG_APPLE_property | 0x4200 |
1642 +-----------------------+--------+
1643
1644 New DWARF Attributes
1645 ^^^^^^^^^^^^^^^^^^^^
1646
1647 +--------------------------------+--------+-----------+
1648 | Attribute                      | Value  | Classes   |
1649 +================================+========+===========+
1650 | DW_AT_APPLE_property           | 0x3fed | Reference |
1651 +--------------------------------+--------+-----------+
1652 | DW_AT_APPLE_property_getter    | 0x3fe9 | String    |
1653 +--------------------------------+--------+-----------+
1654 | DW_AT_APPLE_property_setter    | 0x3fea | String    |
1655 +--------------------------------+--------+-----------+
1656 | DW_AT_APPLE_property_attribute | 0x3feb | Constant  |
1657 +--------------------------------+--------+-----------+
1658
1659 New DWARF Constants
1660 ^^^^^^^^^^^^^^^^^^^
1661
1662 +--------------------------------+-------+
1663 | Name                           | Value |
1664 +================================+=======+
1665 | DW_AT_APPLE_PROPERTY_readonly  | 0x1   |
1666 +--------------------------------+-------+
1667 | DW_AT_APPLE_PROPERTY_readwrite | 0x2   |
1668 +--------------------------------+-------+
1669 | DW_AT_APPLE_PROPERTY_assign    | 0x4   |
1670 +--------------------------------+-------+
1671 | DW_AT_APPLE_PROPERTY_retain    | 0x8   |
1672 +--------------------------------+-------+
1673 | DW_AT_APPLE_PROPERTY_copy      | 0x10  |
1674 +--------------------------------+-------+
1675 | DW_AT_APPLE_PROPERTY_nonatomic | 0x20  |
1676 +--------------------------------+-------+
1677
1678 Name Accelerator Tables
1679 -----------------------
1680
1681 Introduction
1682 ^^^^^^^^^^^^
1683
1684 The "``.debug_pubnames``" and "``.debug_pubtypes``" formats are not what a
1685 debugger needs.  The "``pub``" in the section name indicates that the entries
1686 in the table are publicly visible names only.  This means no static or hidden
1687 functions show up in the "``.debug_pubnames``".  No static variables or private
1688 class variables are in the "``.debug_pubtypes``".  Many compilers add different
1689 things to these tables, so we can't rely upon the contents between gcc, icc, or
1690 clang.
1691
1692 The typical query given by users tends not to match up with the contents of
1693 these tables.  For example, the DWARF spec states that "In the case of the name
1694 of a function member or static data member of a C++ structure, class or union,
1695 the name presented in the "``.debug_pubnames``" section is not the simple name
1696 given by the ``DW_AT_name attribute`` of the referenced debugging information
1697 entry, but rather the fully qualified name of the data or function member."
1698 So the only names in these tables for complex C++ entries is a fully
1699 qualified name.  Debugger users tend not to enter their search strings as
1700 "``a::b::c(int,const Foo&) const``", but rather as "``c``", "``b::c``" , or
1701 "``a::b::c``".  So the name entered in the name table must be demangled in
1702 order to chop it up appropriately and additional names must be manually entered
1703 into the table to make it effective as a name lookup table for debuggers to
1704 se.
1705
1706 All debuggers currently ignore the "``.debug_pubnames``" table as a result of
1707 its inconsistent and useless public-only name content making it a waste of
1708 space in the object file.  These tables, when they are written to disk, are not
1709 sorted in any way, leaving every debugger to do its own parsing and sorting.
1710 These tables also include an inlined copy of the string values in the table
1711 itself making the tables much larger than they need to be on disk, especially
1712 for large C++ programs.
1713
1714 Can't we just fix the sections by adding all of the names we need to this
1715 table? No, because that is not what the tables are defined to contain and we
1716 won't know the difference between the old bad tables and the new good tables.
1717 At best we could make our own renamed sections that contain all of the data we
1718 need.
1719
1720 These tables are also insufficient for what a debugger like LLDB needs.  LLDB
1721 uses clang for its expression parsing where LLDB acts as a PCH.  LLDB is then
1722 often asked to look for type "``foo``" or namespace "``bar``", or list items in
1723 namespace "``baz``".  Namespaces are not included in the pubnames or pubtypes
1724 tables.  Since clang asks a lot of questions when it is parsing an expression,
1725 we need to be very fast when looking up names, as it happens a lot.  Having new
1726 accelerator tables that are optimized for very quick lookups will benefit this
1727 type of debugging experience greatly.
1728
1729 We would like to generate name lookup tables that can be mapped into memory
1730 from disk, and used as is, with little or no up-front parsing.  We would also
1731 be able to control the exact content of these different tables so they contain
1732 exactly what we need.  The Name Accelerator Tables were designed to fix these
1733 issues.  In order to solve these issues we need to:
1734
1735 * Have a format that can be mapped into memory from disk and used as is
1736 * Lookups should be very fast
1737 * Extensible table format so these tables can be made by many producers
1738 * Contain all of the names needed for typical lookups out of the box
1739 * Strict rules for the contents of tables
1740
1741 Table size is important and the accelerator table format should allow the reuse
1742 of strings from common string tables so the strings for the names are not
1743 duplicated.  We also want to make sure the table is ready to be used as-is by
1744 simply mapping the table into memory with minimal header parsing.
1745
1746 The name lookups need to be fast and optimized for the kinds of lookups that
1747 debuggers tend to do.  Optimally we would like to touch as few parts of the
1748 mapped table as possible when doing a name lookup and be able to quickly find
1749 the name entry we are looking for, or discover there are no matches.  In the
1750 case of debuggers we optimized for lookups that fail most of the time.
1751
1752 Each table that is defined should have strict rules on exactly what is in the
1753 accelerator tables and documented so clients can rely on the content.
1754
1755 Hash Tables
1756 ^^^^^^^^^^^
1757
1758 Standard Hash Tables
1759 """"""""""""""""""""
1760
1761 Typical hash tables have a header, buckets, and each bucket points to the
1762 bucket contents:
1763
1764 .. code-block:: none
1765
1766   .------------.
1767   |  HEADER    |
1768   |------------|
1769   |  BUCKETS   |
1770   |------------|
1771   |  DATA      |
1772   `------------'
1773
1774 The BUCKETS are an array of offsets to DATA for each hash:
1775
1776 .. code-block:: none
1777
1778   .------------.
1779   | 0x00001000 | BUCKETS[0]
1780   | 0x00002000 | BUCKETS[1]
1781   | 0x00002200 | BUCKETS[2]
1782   | 0x000034f0 | BUCKETS[3]
1783   |            | ...
1784   | 0xXXXXXXXX | BUCKETS[n_buckets]
1785   '------------'
1786
1787 So for ``bucket[3]`` in the example above, we have an offset into the table
1788 0x000034f0 which points to a chain of entries for the bucket.  Each bucket must
1789 contain a next pointer, full 32 bit hash value, the string itself, and the data
1790 for the current string value.
1791
1792 .. code-block:: none
1793
1794               .------------.
1795   0x000034f0: | 0x00003500 | next pointer
1796               | 0x12345678 | 32 bit hash
1797               | "erase"    | string value
1798               | data[n]    | HashData for this bucket
1799               |------------|
1800   0x00003500: | 0x00003550 | next pointer
1801               | 0x29273623 | 32 bit hash
1802               | "dump"     | string value
1803               | data[n]    | HashData for this bucket
1804               |------------|
1805   0x00003550: | 0x00000000 | next pointer
1806               | 0x82638293 | 32 bit hash
1807               | "main"     | string value
1808               | data[n]    | HashData for this bucket
1809               `------------'
1810
1811 The problem with this layout for debuggers is that we need to optimize for the
1812 negative lookup case where the symbol we're searching for is not present.  So
1813 if we were to lookup "``printf``" in the table above, we would make a 32 hash
1814 for "``printf``", it might match ``bucket[3]``.  We would need to go to the
1815 offset 0x000034f0 and start looking to see if our 32 bit hash matches.  To do
1816 so, we need to read the next pointer, then read the hash, compare it, and skip
1817 to the next bucket.  Each time we are skipping many bytes in memory and
1818 touching new cache pages just to do the compare on the full 32 bit hash.  All
1819 of these accesses then tell us that we didn't have a match.
1820
1821 Name Hash Tables
1822 """"""""""""""""
1823
1824 To solve the issues mentioned above we have structured the hash tables a bit
1825 differently: a header, buckets, an array of all unique 32 bit hash values,
1826 followed by an array of hash value data offsets, one for each hash value, then
1827 the data for all hash values:
1828
1829 .. code-block:: none
1830
1831   .-------------.
1832   |  HEADER     |
1833   |-------------|
1834   |  BUCKETS    |
1835   |-------------|
1836   |  HASHES     |
1837   |-------------|
1838   |  OFFSETS    |
1839   |-------------|
1840   |  DATA       |
1841   `-------------'
1842
1843 The ``BUCKETS`` in the name tables are an index into the ``HASHES`` array.  By
1844 making all of the full 32 bit hash values contiguous in memory, we allow
1845 ourselves to efficiently check for a match while touching as little memory as
1846 possible.  Most often checking the 32 bit hash values is as far as the lookup
1847 goes.  If it does match, it usually is a match with no collisions.  So for a
1848 table with "``n_buckets``" buckets, and "``n_hashes``" unique 32 bit hash
1849 values, we can clarify the contents of the ``BUCKETS``, ``HASHES`` and
1850 ``OFFSETS`` as:
1851
1852 .. code-block:: none
1853
1854   .-------------------------.
1855   |  HEADER.magic           | uint32_t
1856   |  HEADER.version         | uint16_t
1857   |  HEADER.hash_function   | uint16_t
1858   |  HEADER.bucket_count    | uint32_t
1859   |  HEADER.hashes_count    | uint32_t
1860   |  HEADER.header_data_len | uint32_t
1861   |  HEADER_DATA            | HeaderData
1862   |-------------------------|
1863   |  BUCKETS                | uint32_t[n_buckets] // 32 bit hash indexes
1864   |-------------------------|
1865   |  HASHES                 | uint32_t[n_hashes] // 32 bit hash values
1866   |-------------------------|
1867   |  OFFSETS                | uint32_t[n_hashes] // 32 bit offsets to hash value data
1868   |-------------------------|
1869   |  ALL HASH DATA          |
1870   `-------------------------'
1871
1872 So taking the exact same data from the standard hash example above we end up
1873 with:
1874
1875 .. code-block:: none
1876
1877               .------------.
1878               | HEADER     |
1879               |------------|
1880               |          0 | BUCKETS[0]
1881               |          2 | BUCKETS[1]
1882               |          5 | BUCKETS[2]
1883               |          6 | BUCKETS[3]
1884               |            | ...
1885               |        ... | BUCKETS[n_buckets]
1886               |------------|
1887               | 0x........ | HASHES[0]
1888               | 0x........ | HASHES[1]
1889               | 0x........ | HASHES[2]
1890               | 0x........ | HASHES[3]
1891               | 0x........ | HASHES[4]
1892               | 0x........ | HASHES[5]
1893               | 0x12345678 | HASHES[6]    hash for BUCKETS[3]
1894               | 0x29273623 | HASHES[7]    hash for BUCKETS[3]
1895               | 0x82638293 | HASHES[8]    hash for BUCKETS[3]
1896               | 0x........ | HASHES[9]
1897               | 0x........ | HASHES[10]
1898               | 0x........ | HASHES[11]
1899               | 0x........ | HASHES[12]
1900               | 0x........ | HASHES[13]
1901               | 0x........ | HASHES[n_hashes]
1902               |------------|
1903               | 0x........ | OFFSETS[0]
1904               | 0x........ | OFFSETS[1]
1905               | 0x........ | OFFSETS[2]
1906               | 0x........ | OFFSETS[3]
1907               | 0x........ | OFFSETS[4]
1908               | 0x........ | OFFSETS[5]
1909               | 0x000034f0 | OFFSETS[6]   offset for BUCKETS[3]
1910               | 0x00003500 | OFFSETS[7]   offset for BUCKETS[3]
1911               | 0x00003550 | OFFSETS[8]   offset for BUCKETS[3]
1912               | 0x........ | OFFSETS[9]
1913               | 0x........ | OFFSETS[10]
1914               | 0x........ | OFFSETS[11]
1915               | 0x........ | OFFSETS[12]
1916               | 0x........ | OFFSETS[13]
1917               | 0x........ | OFFSETS[n_hashes]
1918               |------------|
1919               |            |
1920               |            |
1921               |            |
1922               |            |
1923               |            |
1924               |------------|
1925   0x000034f0: | 0x00001203 | .debug_str ("erase")
1926               | 0x00000004 | A 32 bit array count - number of HashData with name "erase"
1927               | 0x........ | HashData[0]
1928               | 0x........ | HashData[1]
1929               | 0x........ | HashData[2]
1930               | 0x........ | HashData[3]
1931               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1932               |------------|
1933   0x00003500: | 0x00001203 | String offset into .debug_str ("collision")
1934               | 0x00000002 | A 32 bit array count - number of HashData with name "collision"
1935               | 0x........ | HashData[0]
1936               | 0x........ | HashData[1]
1937               | 0x00001203 | String offset into .debug_str ("dump")
1938               | 0x00000003 | A 32 bit array count - number of HashData with name "dump"
1939               | 0x........ | HashData[0]
1940               | 0x........ | HashData[1]
1941               | 0x........ | HashData[2]
1942               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1943               |------------|
1944   0x00003550: | 0x00001203 | String offset into .debug_str ("main")
1945               | 0x00000009 | A 32 bit array count - number of HashData with name "main"
1946               | 0x........ | HashData[0]
1947               | 0x........ | HashData[1]
1948               | 0x........ | HashData[2]
1949               | 0x........ | HashData[3]
1950               | 0x........ | HashData[4]
1951               | 0x........ | HashData[5]
1952               | 0x........ | HashData[6]
1953               | 0x........ | HashData[7]
1954               | 0x........ | HashData[8]
1955               | 0x00000000 | String offset into .debug_str (terminate data for hash)
1956               `------------'
1957
1958 So we still have all of the same data, we just organize it more efficiently for
1959 debugger lookup.  If we repeat the same "``printf``" lookup from above, we
1960 would hash "``printf``" and find it matches ``BUCKETS[3]`` by taking the 32 bit
1961 hash value and modulo it by ``n_buckets``.  ``BUCKETS[3]`` contains "6" which
1962 is the index into the ``HASHES`` table.  We would then compare any consecutive
1963 32 bit hashes values in the ``HASHES`` array as long as the hashes would be in
1964 ``BUCKETS[3]``.  We do this by verifying that each subsequent hash value modulo
1965 ``n_buckets`` is still 3.  In the case of a failed lookup we would access the
1966 memory for ``BUCKETS[3]``, and then compare a few consecutive 32 bit hashes
1967 before we know that we have no match.  We don't end up marching through
1968 multiple words of memory and we really keep the number of processor data cache
1969 lines being accessed as small as possible.
1970
1971 The string hash that is used for these lookup tables is the Daniel J.
1972 Bernstein hash which is also used in the ELF ``GNU_HASH`` sections.  It is a
1973 very good hash for all kinds of names in programs with very few hash
1974 collisions.
1975
1976 Empty buckets are designated by using an invalid hash index of ``UINT32_MAX``.
1977
1978 Details
1979 ^^^^^^^
1980
1981 These name hash tables are designed to be generic where specializations of the
1982 table get to define additional data that goes into the header ("``HeaderData``"),
1983 how the string value is stored ("``KeyType``") and the content of the data for each
1984 hash value.
1985
1986 Header Layout
1987 """""""""""""
1988
1989 The header has a fixed part, and the specialized part.  The exact format of the
1990 header is:
1991
1992 .. code-block:: c
1993
1994   struct Header
1995   {
1996     uint32_t   magic;           // 'HASH' magic value to allow endian detection
1997     uint16_t   version;         // Version number
1998     uint16_t   hash_function;   // The hash function enumeration that was used
1999     uint32_t   bucket_count;    // The number of buckets in this hash table
2000     uint32_t   hashes_count;    // The total number of unique hash values and hash data offsets in this table
2001     uint32_t   header_data_len; // The bytes to skip to get to the hash indexes (buckets) for correct alignment
2002                                 // Specifically the length of the following HeaderData field - this does not
2003                                 // include the size of the preceding fields
2004     HeaderData header_data;     // Implementation specific header data
2005   };
2006
2007 The header starts with a 32 bit "``magic``" value which must be ``'HASH'``
2008 encoded as an ASCII integer.  This allows the detection of the start of the
2009 hash table and also allows the table's byte order to be determined so the table
2010 can be correctly extracted.  The "``magic``" value is followed by a 16 bit
2011 ``version`` number which allows the table to be revised and modified in the
2012 future.  The current version number is 1. ``hash_function`` is a ``uint16_t``
2013 enumeration that specifies which hash function was used to produce this table.
2014 The current values for the hash function enumerations include:
2015
2016 .. code-block:: c
2017
2018   enum HashFunctionType
2019   {
2020     eHashFunctionDJB = 0u, // Daniel J Bernstein hash function
2021   };
2022
2023 ``bucket_count`` is a 32 bit unsigned integer that represents how many buckets
2024 are in the ``BUCKETS`` array.  ``hashes_count`` is the number of unique 32 bit
2025 hash values that are in the ``HASHES`` array, and is the same number of offsets
2026 are contained in the ``OFFSETS`` array.  ``header_data_len`` specifies the size
2027 in bytes of the ``HeaderData`` that is filled in by specialized versions of
2028 this table.
2029
2030 Fixed Lookup
2031 """"""""""""
2032
2033 The header is followed by the buckets, hashes, offsets, and hash value data.
2034
2035 .. code-block:: c
2036
2037   struct FixedTable
2038   {
2039     uint32_t buckets[Header.bucket_count];  // An array of hash indexes into the "hashes[]" array below
2040     uint32_t hashes [Header.hashes_count];  // Every unique 32 bit hash for the entire table is in this table
2041     uint32_t offsets[Header.hashes_count];  // An offset that corresponds to each item in the "hashes[]" array above
2042   };
2043
2044 ``buckets`` is an array of 32 bit indexes into the ``hashes`` array.  The
2045 ``hashes`` array contains all of the 32 bit hash values for all names in the
2046 hash table.  Each hash in the ``hashes`` table has an offset in the ``offsets``
2047 array that points to the data for the hash value.
2048
2049 This table setup makes it very easy to repurpose these tables to contain
2050 different data, while keeping the lookup mechanism the same for all tables.
2051 This layout also makes it possible to save the table to disk and map it in
2052 later and do very efficient name lookups with little or no parsing.
2053
2054 DWARF lookup tables can be implemented in a variety of ways and can store a lot
2055 of information for each name.  We want to make the DWARF tables extensible and
2056 able to store the data efficiently so we have used some of the DWARF features
2057 that enable efficient data storage to define exactly what kind of data we store
2058 for each name.
2059
2060 The ``HeaderData`` contains a definition of the contents of each HashData chunk.
2061 We might want to store an offset to all of the debug information entries (DIEs)
2062 for each name.  To keep things extensible, we create a list of items, or
2063 Atoms, that are contained in the data for each name.  First comes the type of
2064 the data in each atom:
2065
2066 .. code-block:: c
2067
2068   enum AtomType
2069   {
2070     eAtomTypeNULL       = 0u,
2071     eAtomTypeDIEOffset  = 1u,   // DIE offset, check form for encoding
2072     eAtomTypeCUOffset   = 2u,   // DIE offset of the compiler unit header that contains the item in question
2073     eAtomTypeTag        = 3u,   // DW_TAG_xxx value, should be encoded as DW_FORM_data1 (if no tags exceed 255) or DW_FORM_data2
2074     eAtomTypeNameFlags  = 4u,   // Flags from enum NameFlags
2075     eAtomTypeTypeFlags  = 5u,   // Flags from enum TypeFlags
2076   };
2077
2078 The enumeration values and their meanings are:
2079
2080 .. code-block:: none
2081
2082   eAtomTypeNULL       - a termination atom that specifies the end of the atom list
2083   eAtomTypeDIEOffset  - an offset into the .debug_info section for the DWARF DIE for this name
2084   eAtomTypeCUOffset   - an offset into the .debug_info section for the CU that contains the DIE
2085   eAtomTypeDIETag     - The DW_TAG_XXX enumeration value so you don't have to parse the DWARF to see what it is
2086   eAtomTypeNameFlags  - Flags for functions and global variables (isFunction, isInlined, isExternal...)
2087   eAtomTypeTypeFlags  - Flags for types (isCXXClass, isObjCClass, ...)
2088
2089 Then we allow each atom type to define the atom type and how the data for each
2090 atom type data is encoded:
2091
2092 .. code-block:: c
2093
2094   struct Atom
2095   {
2096     uint16_t type;  // AtomType enum value
2097     uint16_t form;  // DWARF DW_FORM_XXX defines
2098   };
2099
2100 The ``form`` type above is from the DWARF specification and defines the exact
2101 encoding of the data for the Atom type.  See the DWARF specification for the
2102 ``DW_FORM_`` definitions.
2103
2104 .. code-block:: c
2105
2106   struct HeaderData
2107   {
2108     uint32_t die_offset_base;
2109     uint32_t atom_count;
2110     Atoms    atoms[atom_count0];
2111   };
2112
2113 ``HeaderData`` defines the base DIE offset that should be added to any atoms
2114 that are encoded using the ``DW_FORM_ref1``, ``DW_FORM_ref2``,
2115 ``DW_FORM_ref4``, ``DW_FORM_ref8`` or ``DW_FORM_ref_udata``.  It also defines
2116 what is contained in each ``HashData`` object -- ``Atom.form`` tells us how large
2117 each field will be in the ``HashData`` and the ``Atom.type`` tells us how this data
2118 should be interpreted.
2119
2120 For the current implementations of the "``.apple_names``" (all functions +
2121 globals), the "``.apple_types``" (names of all types that are defined), and
2122 the "``.apple_namespaces``" (all namespaces), we currently set the ``Atom``
2123 array to be:
2124
2125 .. code-block:: c
2126
2127   HeaderData.atom_count = 1;
2128   HeaderData.atoms[0].type = eAtomTypeDIEOffset;
2129   HeaderData.atoms[0].form = DW_FORM_data4;
2130
2131 This defines the contents to be the DIE offset (eAtomTypeDIEOffset) that is
2132 encoded as a 32 bit value (DW_FORM_data4).  This allows a single name to have
2133 multiple matching DIEs in a single file, which could come up with an inlined
2134 function for instance.  Future tables could include more information about the
2135 DIE such as flags indicating if the DIE is a function, method, block,
2136 or inlined.
2137
2138 The KeyType for the DWARF table is a 32 bit string table offset into the
2139 ".debug_str" table.  The ".debug_str" is the string table for the DWARF which
2140 may already contain copies of all of the strings.  This helps make sure, with
2141 help from the compiler, that we reuse the strings between all of the DWARF
2142 sections and keeps the hash table size down.  Another benefit to having the
2143 compiler generate all strings as DW_FORM_strp in the debug info, is that
2144 DWARF parsing can be made much faster.
2145
2146 After a lookup is made, we get an offset into the hash data.  The hash data
2147 needs to be able to deal with 32 bit hash collisions, so the chunk of data
2148 at the offset in the hash data consists of a triple:
2149
2150 .. code-block:: c
2151
2152   uint32_t str_offset
2153   uint32_t hash_data_count
2154   HashData[hash_data_count]
2155
2156 If "str_offset" is zero, then the bucket contents are done. 99.9% of the
2157 hash data chunks contain a single item (no 32 bit hash collision):
2158
2159 .. code-block:: none
2160
2161   .------------.
2162   | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
2163   | 0x00000004 | uint32_t HashData count
2164   | 0x........ | uint32_t HashData[0] DIE offset
2165   | 0x........ | uint32_t HashData[1] DIE offset
2166   | 0x........ | uint32_t HashData[2] DIE offset
2167   | 0x........ | uint32_t HashData[3] DIE offset
2168   | 0x00000000 | uint32_t KeyType (end of hash chain)
2169   `------------'
2170
2171 If there are collisions, you will have multiple valid string offsets:
2172
2173 .. code-block:: none
2174
2175   .------------.
2176   | 0x00001023 | uint32_t KeyType (.debug_str[0x0001023] => "main")
2177   | 0x00000004 | uint32_t HashData count
2178   | 0x........ | uint32_t HashData[0] DIE offset
2179   | 0x........ | uint32_t HashData[1] DIE offset
2180   | 0x........ | uint32_t HashData[2] DIE offset
2181   | 0x........ | uint32_t HashData[3] DIE offset
2182   | 0x00002023 | uint32_t KeyType (.debug_str[0x0002023] => "print")
2183   | 0x00000002 | uint32_t HashData count
2184   | 0x........ | uint32_t HashData[0] DIE offset
2185   | 0x........ | uint32_t HashData[1] DIE offset
2186   | 0x00000000 | uint32_t KeyType (end of hash chain)
2187   `------------'
2188
2189 Current testing with real world C++ binaries has shown that there is around 1
2190 32 bit hash collision per 100,000 name entries.
2191
2192 Contents
2193 ^^^^^^^^
2194
2195 As we said, we want to strictly define exactly what is included in the
2196 different tables.  For DWARF, we have 3 tables: "``.apple_names``",
2197 "``.apple_types``", and "``.apple_namespaces``".
2198
2199 "``.apple_names``" sections should contain an entry for each DWARF DIE whose
2200 ``DW_TAG`` is a ``DW_TAG_label``, ``DW_TAG_inlined_subroutine``, or
2201 ``DW_TAG_subprogram`` that has address attributes: ``DW_AT_low_pc``,
2202 ``DW_AT_high_pc``, ``DW_AT_ranges`` or ``DW_AT_entry_pc``.  It also contains
2203 ``DW_TAG_variable`` DIEs that have a ``DW_OP_addr`` in the location (global and
2204 static variables).  All global and static variables should be included,
2205 including those scoped within functions and classes.  For example using the
2206 following code:
2207
2208 .. code-block:: c
2209
2210   static int var = 0;
2211
2212   void f ()
2213   {
2214     static int var = 0;
2215   }
2216
2217 Both of the static ``var`` variables would be included in the table.  All
2218 functions should emit both their full names and their basenames.  For C or C++,
2219 the full name is the mangled name (if available) which is usually in the
2220 ``DW_AT_MIPS_linkage_name`` attribute, and the ``DW_AT_name`` contains the
2221 function basename.  If global or static variables have a mangled name in a
2222 ``DW_AT_MIPS_linkage_name`` attribute, this should be emitted along with the
2223 simple name found in the ``DW_AT_name`` attribute.
2224
2225 "``.apple_types``" sections should contain an entry for each DWARF DIE whose
2226 tag is one of:
2227
2228 * DW_TAG_array_type
2229 * DW_TAG_class_type
2230 * DW_TAG_enumeration_type
2231 * DW_TAG_pointer_type
2232 * DW_TAG_reference_type
2233 * DW_TAG_string_type
2234 * DW_TAG_structure_type
2235 * DW_TAG_subroutine_type
2236 * DW_TAG_typedef
2237 * DW_TAG_union_type
2238 * DW_TAG_ptr_to_member_type
2239 * DW_TAG_set_type
2240 * DW_TAG_subrange_type
2241 * DW_TAG_base_type
2242 * DW_TAG_const_type
2243 * DW_TAG_constant
2244 * DW_TAG_file_type
2245 * DW_TAG_namelist
2246 * DW_TAG_packed_type
2247 * DW_TAG_volatile_type
2248 * DW_TAG_restrict_type
2249 * DW_TAG_interface_type
2250 * DW_TAG_unspecified_type
2251 * DW_TAG_shared_type
2252
2253 Only entries with a ``DW_AT_name`` attribute are included, and the entry must
2254 not be a forward declaration (``DW_AT_declaration`` attribute with a non-zero
2255 value).  For example, using the following code:
2256
2257 .. code-block:: c
2258
2259   int main ()
2260   {
2261     int *b = 0;
2262     return *b;
2263   }
2264
2265 We get a few type DIEs:
2266
2267 .. code-block:: none
2268
2269   0x00000067:     TAG_base_type [5]
2270                   AT_encoding( DW_ATE_signed )
2271                   AT_name( "int" )
2272                   AT_byte_size( 0x04 )
2273
2274   0x0000006e:     TAG_pointer_type [6]
2275                   AT_type( {0x00000067} ( int ) )
2276                   AT_byte_size( 0x08 )
2277
2278 The DW_TAG_pointer_type is not included because it does not have a ``DW_AT_name``.
2279
2280 "``.apple_namespaces``" section should contain all ``DW_TAG_namespace`` DIEs.
2281 If we run into a namespace that has no name this is an anonymous namespace, and
2282 the name should be output as "``(anonymous namespace)``" (without the quotes).
2283 Why?  This matches the output of the ``abi::cxa_demangle()`` that is in the
2284 standard C++ library that demangles mangled names.
2285
2286
2287 Language Extensions and File Format Changes
2288 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2289
2290 Objective-C Extensions
2291 """"""""""""""""""""""
2292
2293 "``.apple_objc``" section should contain all ``DW_TAG_subprogram`` DIEs for an
2294 Objective-C class.  The name used in the hash table is the name of the
2295 Objective-C class itself.  If the Objective-C class has a category, then an
2296 entry is made for both the class name without the category, and for the class
2297 name with the category.  So if we have a DIE at offset 0x1234 with a name of
2298 method "``-[NSString(my_additions) stringWithSpecialString:]``", we would add
2299 an entry for "``NSString``" that points to DIE 0x1234, and an entry for
2300 "``NSString(my_additions)``" that points to 0x1234.  This allows us to quickly
2301 track down all Objective-C methods for an Objective-C class when doing
2302 expressions.  It is needed because of the dynamic nature of Objective-C where
2303 anyone can add methods to a class.  The DWARF for Objective-C methods is also
2304 emitted differently from C++ classes where the methods are not usually
2305 contained in the class definition, they are scattered about across one or more
2306 compile units.  Categories can also be defined in different shared libraries.
2307 So we need to be able to quickly find all of the methods and class functions
2308 given the Objective-C class name, or quickly find all methods and class
2309 functions for a class + category name.  This table does not contain any
2310 selector names, it just maps Objective-C class names (or class names +
2311 category) to all of the methods and class functions.  The selectors are added
2312 as function basenames in the "``.debug_names``" section.
2313
2314 In the "``.apple_names``" section for Objective-C functions, the full name is
2315 the entire function name with the brackets ("``-[NSString
2316 stringWithCString:]``") and the basename is the selector only
2317 ("``stringWithCString:``").
2318
2319 Mach-O Changes
2320 """"""""""""""
2321
2322 The sections names for the apple hash tables are for non-mach-o files.  For
2323 mach-o files, the sections should be contained in the ``__DWARF`` segment with
2324 names as follows:
2325
2326 * "``.apple_names``" -> "``__apple_names``"
2327 * "``.apple_types``" -> "``__apple_types``"
2328 * "``.apple_namespaces``" -> "``__apple_namespac``" (16 character limit)
2329 * "``.apple_objc``" -> "``__apple_objc``"
2330