1 //===- lib/CodeGen/DIE.h - DWARF Info Entries -------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Data structures for DWARF info entries.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H
14 #define LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H
15 
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/PointerIntPair.h"
18 #include "llvm/ADT/PointerUnion.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/BinaryFormat/Dwarf.h"
24 #include "llvm/CodeGen/DwarfStringPoolEntry.h"
25 #include "llvm/Support/AlignOf.h"
26 #include "llvm/Support/Allocator.h"
27 #include <cassert>
28 #include <cstddef>
29 #include <cstdint>
30 #include <iterator>
31 #include <new>
32 #include <type_traits>
33 #include <utility>
34 #include <vector>
35 
36 namespace llvm {
37 
38 class AsmPrinter;
39 class DIE;
40 class DIEUnit;
41 class DwarfCompileUnit;
42 class MCExpr;
43 class MCSection;
44 class MCSymbol;
45 class raw_ostream;
46 
47 //===--------------------------------------------------------------------===//
48 /// Dwarf abbreviation data, describes one attribute of a Dwarf abbreviation.
49 class DIEAbbrevData {
50   /// Dwarf attribute code.
51   dwarf::Attribute Attribute;
52 
53   /// Dwarf form code.
54   dwarf::Form Form;
55 
56   /// Dwarf attribute value for DW_FORM_implicit_const
57   int64_t Value = 0;
58 
59 public:
60   DIEAbbrevData(dwarf::Attribute A, dwarf::Form F)
61       : Attribute(A), Form(F) {}
62   DIEAbbrevData(dwarf::Attribute A, int64_t V)
63       : Attribute(A), Form(dwarf::DW_FORM_implicit_const), Value(V) {}
64 
65   /// Accessors.
66   /// @{
67   dwarf::Attribute getAttribute() const { return Attribute; }
68   dwarf::Form getForm() const { return Form; }
69   int64_t getValue() const { return Value; }
70   /// @}
71 
72   /// Used to gather unique data for the abbreviation folding set.
73   void Profile(FoldingSetNodeID &ID) const;
74 };
75 
76 //===--------------------------------------------------------------------===//
77 /// Dwarf abbreviation, describes the organization of a debug information
78 /// object.
79 class DIEAbbrev : public FoldingSetNode {
80   /// Unique number for node.
81   unsigned Number = 0;
82 
83   /// Dwarf tag code.
84   dwarf::Tag Tag;
85 
86   /// Whether or not this node has children.
87   ///
88   /// This cheats a bit in all of the uses since the values in the standard
89   /// are 0 and 1 for no children and children respectively.
90   bool Children;
91 
92   /// Raw data bytes for abbreviation.
93   SmallVector<DIEAbbrevData, 12> Data;
94 
95 public:
96   DIEAbbrev(dwarf::Tag T, bool C) : Tag(T), Children(C) {}
97 
98   /// Accessors.
99   /// @{
100   dwarf::Tag getTag() const { return Tag; }
101   unsigned getNumber() const { return Number; }
102   bool hasChildren() const { return Children; }
103   const SmallVectorImpl<DIEAbbrevData> &getData() const { return Data; }
104   void setChildrenFlag(bool hasChild) { Children = hasChild; }
105   void setNumber(unsigned N) { Number = N; }
106   /// @}
107 
108   /// Adds another set of attribute information to the abbreviation.
109   void AddAttribute(dwarf::Attribute Attribute, dwarf::Form Form) {
110     Data.push_back(DIEAbbrevData(Attribute, Form));
111   }
112 
113   /// Adds attribute with DW_FORM_implicit_const value
114   void AddImplicitConstAttribute(dwarf::Attribute Attribute, int64_t Value) {
115     Data.push_back(DIEAbbrevData(Attribute, Value));
116   }
117 
118   /// Used to gather unique data for the abbreviation folding set.
119   void Profile(FoldingSetNodeID &ID) const;
120 
121   /// Print the abbreviation using the specified asm printer.
122   void Emit(const AsmPrinter *AP) const;
123 
124   void print(raw_ostream &O) const;
125   void dump() const;
126 };
127 
128 //===--------------------------------------------------------------------===//
129 /// Helps unique DIEAbbrev objects and assigns abbreviation numbers.
130 ///
131 /// This class will unique the DIE abbreviations for a llvm::DIE object and
132 /// assign a unique abbreviation number to each unique DIEAbbrev object it
133 /// finds. The resulting collection of DIEAbbrev objects can then be emitted
134 /// into the .debug_abbrev section.
135 class DIEAbbrevSet {
136   /// The bump allocator to use when creating DIEAbbrev objects in the uniqued
137   /// storage container.
138   BumpPtrAllocator &Alloc;
139   /// FoldingSet that uniques the abbreviations.
140   FoldingSet<DIEAbbrev> AbbreviationsSet;
141   /// A list of all the unique abbreviations in use.
142   std::vector<DIEAbbrev *> Abbreviations;
143 
144 public:
145   DIEAbbrevSet(BumpPtrAllocator &A) : Alloc(A) {}
146   ~DIEAbbrevSet();
147 
148   /// Generate the abbreviation declaration for a DIE and return a pointer to
149   /// the generated abbreviation.
150   ///
151   /// \param Die the debug info entry to generate the abbreviation for.
152   /// \returns A reference to the uniqued abbreviation declaration that is
153   /// owned by this class.
154   DIEAbbrev &uniqueAbbreviation(DIE &Die);
155 
156   /// Print all abbreviations using the specified asm printer.
157   void Emit(const AsmPrinter *AP, MCSection *Section) const;
158 };
159 
160 //===--------------------------------------------------------------------===//
161 /// An integer value DIE.
162 ///
163 class DIEInteger {
164   uint64_t Integer;
165 
166 public:
167   explicit DIEInteger(uint64_t I) : Integer(I) {}
168 
169   /// Choose the best form for integer.
170   static dwarf::Form BestForm(bool IsSigned, uint64_t Int) {
171     if (IsSigned) {
172       const int64_t SignedInt = Int;
173       if ((char)Int == SignedInt)
174         return dwarf::DW_FORM_data1;
175       if ((short)Int == SignedInt)
176         return dwarf::DW_FORM_data2;
177       if ((int)Int == SignedInt)
178         return dwarf::DW_FORM_data4;
179     } else {
180       if ((unsigned char)Int == Int)
181         return dwarf::DW_FORM_data1;
182       if ((unsigned short)Int == Int)
183         return dwarf::DW_FORM_data2;
184       if ((unsigned int)Int == Int)
185         return dwarf::DW_FORM_data4;
186     }
187     return dwarf::DW_FORM_data8;
188   }
189 
190   uint64_t getValue() const { return Integer; }
191   void setValue(uint64_t Val) { Integer = Val; }
192 
193   void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
194   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
195 
196   void print(raw_ostream &O) const;
197 };
198 
199 //===--------------------------------------------------------------------===//
200 /// An expression DIE.
201 class DIEExpr {
202   const MCExpr *Expr;
203 
204 public:
205   explicit DIEExpr(const MCExpr *E) : Expr(E) {}
206 
207   /// Get MCExpr.
208   const MCExpr *getValue() const { return Expr; }
209 
210   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
211   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
212 
213   void print(raw_ostream &O) const;
214 };
215 
216 //===--------------------------------------------------------------------===//
217 /// A label DIE.
218 class DIELabel {
219   const MCSymbol *Label;
220 
221 public:
222   explicit DIELabel(const MCSymbol *L) : Label(L) {}
223 
224   /// Get MCSymbol.
225   const MCSymbol *getValue() const { return Label; }
226 
227   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
228   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
229 
230   void print(raw_ostream &O) const;
231 };
232 
233 //===--------------------------------------------------------------------===//
234 /// A BaseTypeRef DIE.
235 class DIEBaseTypeRef {
236   const DwarfCompileUnit *CU;
237   const uint64_t Index;
238   static constexpr unsigned ULEB128PadSize = 4;
239 
240 public:
241   explicit DIEBaseTypeRef(const DwarfCompileUnit *TheCU, uint64_t Idx)
242     : CU(TheCU), Index(Idx) {}
243 
244   /// EmitValue - Emit base type reference.
245   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
246   /// SizeOf - Determine size of the base type reference in bytes.
247   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
248 
249   void print(raw_ostream &O) const;
250 };
251 
252 //===--------------------------------------------------------------------===//
253 /// A simple label difference DIE.
254 ///
255 class DIEDelta {
256   const MCSymbol *LabelHi;
257   const MCSymbol *LabelLo;
258 
259 public:
260   DIEDelta(const MCSymbol *Hi, const MCSymbol *Lo) : LabelHi(Hi), LabelLo(Lo) {}
261 
262   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
263   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
264 
265   void print(raw_ostream &O) const;
266 };
267 
268 //===--------------------------------------------------------------------===//
269 /// A container for string pool string values.
270 ///
271 /// This class is used with the DW_FORM_strp and DW_FORM_GNU_str_index forms.
272 class DIEString {
273   DwarfStringPoolEntryRef S;
274 
275 public:
276   DIEString(DwarfStringPoolEntryRef S) : S(S) {}
277 
278   /// Grab the string out of the object.
279   StringRef getString() const { return S.getString(); }
280 
281   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
282   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
283 
284   void print(raw_ostream &O) const;
285 };
286 
287 //===--------------------------------------------------------------------===//
288 /// A container for inline string values.
289 ///
290 /// This class is used with the DW_FORM_string form.
291 class DIEInlineString {
292   StringRef S;
293 
294 public:
295   template <typename Allocator>
296   explicit DIEInlineString(StringRef Str, Allocator &A) : S(Str.copy(A)) {}
297 
298   ~DIEInlineString() = default;
299 
300   /// Grab the string out of the object.
301   StringRef getString() const { return S; }
302 
303   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
304   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
305 
306   void print(raw_ostream &O) const;
307 };
308 
309 //===--------------------------------------------------------------------===//
310 /// A pointer to another debug information entry.  An instance of this class can
311 /// also be used as a proxy for a debug information entry not yet defined
312 /// (ie. types.)
313 class DIEEntry {
314   DIE *Entry;
315 
316 public:
317   DIEEntry() = delete;
318   explicit DIEEntry(DIE &E) : Entry(&E) {}
319 
320   DIE &getEntry() const { return *Entry; }
321 
322   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
323   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
324 
325   void print(raw_ostream &O) const;
326 };
327 
328 //===--------------------------------------------------------------------===//
329 /// Represents a pointer to a location list in the debug_loc
330 /// section.
331 class DIELocList {
332   /// Index into the .debug_loc vector.
333   size_t Index;
334 
335 public:
336   DIELocList(size_t I) : Index(I) {}
337 
338   /// Grab the current index out.
339   size_t getValue() const { return Index; }
340 
341   void EmitValue(const AsmPrinter *AP, dwarf::Form Form) const;
342   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
343 
344   void print(raw_ostream &O) const;
345 };
346 
347 //===--------------------------------------------------------------------===//
348 /// A debug information entry value. Some of these roughly correlate
349 /// to DWARF attribute classes.
350 class DIEBlock;
351 class DIELoc;
352 class DIEValue {
353 public:
354   enum Type {
355     isNone,
356 #define HANDLE_DIEVALUE(T) is##T,
357 #include "llvm/CodeGen/DIEValue.def"
358   };
359 
360 private:
361   /// Type of data stored in the value.
362   Type Ty = isNone;
363   dwarf::Attribute Attribute = (dwarf::Attribute)0;
364   dwarf::Form Form = (dwarf::Form)0;
365 
366   /// Storage for the value.
367   ///
368   /// All values that aren't standard layout (or are larger than 8 bytes)
369   /// should be stored by reference instead of by value.
370   using ValTy = AlignedCharArrayUnion<DIEInteger, DIEString, DIEExpr, DIELabel,
371                                       DIEDelta *, DIEEntry, DIEBlock *,
372                                       DIELoc *, DIELocList, DIEBaseTypeRef *>;
373 
374   static_assert(sizeof(ValTy) <= sizeof(uint64_t) ||
375                     sizeof(ValTy) <= sizeof(void *),
376                 "Expected all large types to be stored via pointer");
377 
378   /// Underlying stored value.
379   ValTy Val;
380 
381   template <class T> void construct(T V) {
382     static_assert(std::is_standard_layout<T>::value ||
383                       std::is_pointer<T>::value,
384                   "Expected standard layout or pointer");
385     new (reinterpret_cast<void *>(Val.buffer)) T(V);
386   }
387 
388   template <class T> T *get() { return reinterpret_cast<T *>(Val.buffer); }
389   template <class T> const T *get() const {
390     return reinterpret_cast<const T *>(Val.buffer);
391   }
392   template <class T> void destruct() { get<T>()->~T(); }
393 
394   /// Destroy the underlying value.
395   ///
396   /// This should get optimized down to a no-op.  We could skip it if we could
397   /// add a static assert on \a std::is_trivially_copyable(), but we currently
398   /// support versions of GCC that don't understand that.
399   void destroyVal() {
400     switch (Ty) {
401     case isNone:
402       return;
403 #define HANDLE_DIEVALUE_SMALL(T)                                               \
404   case is##T:                                                                  \
405     destruct<DIE##T>();                                                        \
406     return;
407 #define HANDLE_DIEVALUE_LARGE(T)                                               \
408   case is##T:                                                                  \
409     destruct<const DIE##T *>();                                                \
410     return;
411 #include "llvm/CodeGen/DIEValue.def"
412     }
413   }
414 
415   /// Copy the underlying value.
416   ///
417   /// This should get optimized down to a simple copy.  We need to actually
418   /// construct the value, rather than calling memcpy, to satisfy strict
419   /// aliasing rules.
420   void copyVal(const DIEValue &X) {
421     switch (Ty) {
422     case isNone:
423       return;
424 #define HANDLE_DIEVALUE_SMALL(T)                                               \
425   case is##T:                                                                  \
426     construct<DIE##T>(*X.get<DIE##T>());                                       \
427     return;
428 #define HANDLE_DIEVALUE_LARGE(T)                                               \
429   case is##T:                                                                  \
430     construct<const DIE##T *>(*X.get<const DIE##T *>());                       \
431     return;
432 #include "llvm/CodeGen/DIEValue.def"
433     }
434   }
435 
436 public:
437   DIEValue() = default;
438 
439   DIEValue(const DIEValue &X) : Ty(X.Ty), Attribute(X.Attribute), Form(X.Form) {
440     copyVal(X);
441   }
442 
443   DIEValue &operator=(const DIEValue &X) {
444     destroyVal();
445     Ty = X.Ty;
446     Attribute = X.Attribute;
447     Form = X.Form;
448     copyVal(X);
449     return *this;
450   }
451 
452   ~DIEValue() { destroyVal(); }
453 
454 #define HANDLE_DIEVALUE_SMALL(T)                                               \
455   DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T &V)      \
456       : Ty(is##T), Attribute(Attribute), Form(Form) {                          \
457     construct<DIE##T>(V);                                                      \
458   }
459 #define HANDLE_DIEVALUE_LARGE(T)                                               \
460   DIEValue(dwarf::Attribute Attribute, dwarf::Form Form, const DIE##T *V)      \
461       : Ty(is##T), Attribute(Attribute), Form(Form) {                          \
462     assert(V && "Expected valid value");                                       \
463     construct<const DIE##T *>(V);                                              \
464   }
465 #include "llvm/CodeGen/DIEValue.def"
466 
467   /// Accessors.
468   /// @{
469   Type getType() const { return Ty; }
470   dwarf::Attribute getAttribute() const { return Attribute; }
471   dwarf::Form getForm() const { return Form; }
472   explicit operator bool() const { return Ty; }
473   /// @}
474 
475 #define HANDLE_DIEVALUE_SMALL(T)                                               \
476   const DIE##T &getDIE##T() const {                                            \
477     assert(getType() == is##T && "Expected " #T);                              \
478     return *get<DIE##T>();                                                     \
479   }
480 #define HANDLE_DIEVALUE_LARGE(T)                                               \
481   const DIE##T &getDIE##T() const {                                            \
482     assert(getType() == is##T && "Expected " #T);                              \
483     return **get<const DIE##T *>();                                            \
484   }
485 #include "llvm/CodeGen/DIEValue.def"
486 
487   /// Emit value via the Dwarf writer.
488   void EmitValue(const AsmPrinter *AP) const;
489 
490   /// Return the size of a value in bytes.
491   unsigned SizeOf(const AsmPrinter *AP) const;
492 
493   void print(raw_ostream &O) const;
494   void dump() const;
495 };
496 
497 struct IntrusiveBackListNode {
498   PointerIntPair<IntrusiveBackListNode *, 1> Next;
499 
500   IntrusiveBackListNode() : Next(this, true) {}
501 
502   IntrusiveBackListNode *getNext() const {
503     return Next.getInt() ? nullptr : Next.getPointer();
504   }
505 };
506 
507 struct IntrusiveBackListBase {
508   using Node = IntrusiveBackListNode;
509 
510   Node *Last = nullptr;
511 
512   bool empty() const { return !Last; }
513 
514   void push_back(Node &N) {
515     assert(N.Next.getPointer() == &N && "Expected unlinked node");
516     assert(N.Next.getInt() == true && "Expected unlinked node");
517 
518     if (Last) {
519       N.Next = Last->Next;
520       Last->Next.setPointerAndInt(&N, false);
521     }
522     Last = &N;
523   }
524 
525   void push_front(Node &N) {
526     assert(N.Next.getPointer() == &N && "Expected unlinked node");
527     assert(N.Next.getInt() == true && "Expected unlinked node");
528 
529     if (Last) {
530       N.Next.setPointerAndInt(Last->Next.getPointer(), false);
531       Last->Next.setPointerAndInt(&N, true);
532     } else {
533       Last = &N;
534     }
535   }
536 };
537 
538 template <class T> class IntrusiveBackList : IntrusiveBackListBase {
539 public:
540   using IntrusiveBackListBase::empty;
541 
542   void push_back(T &N) { IntrusiveBackListBase::push_back(N); }
543   void push_front(T &N) { IntrusiveBackListBase::push_front(N); }
544   T &back() { return *static_cast<T *>(Last); }
545   const T &back() const { return *static_cast<T *>(Last); }
546   T &front() {
547     return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
548   }
549   const T &front() const {
550     return *static_cast<T *>(Last ? Last->Next.getPointer() : nullptr);
551   }
552 
553   void takeNodes(IntrusiveBackList<T> &Other) {
554     for (auto &N : Other) {
555       N.Next.setPointerAndInt(&N, true);
556       push_back(N);
557     }
558     Other.Last = nullptr;
559   }
560 
561   class const_iterator;
562   class iterator
563       : public iterator_facade_base<iterator, std::forward_iterator_tag, T> {
564     friend class const_iterator;
565 
566     Node *N = nullptr;
567 
568   public:
569     iterator() = default;
570     explicit iterator(T *N) : N(N) {}
571 
572     iterator &operator++() {
573       N = N->getNext();
574       return *this;
575     }
576 
577     explicit operator bool() const { return N; }
578     T &operator*() const { return *static_cast<T *>(N); }
579 
580     bool operator==(const iterator &X) const { return N == X.N; }
581     bool operator!=(const iterator &X) const { return N != X.N; }
582   };
583 
584   class const_iterator
585       : public iterator_facade_base<const_iterator, std::forward_iterator_tag,
586                                     const T> {
587     const Node *N = nullptr;
588 
589   public:
590     const_iterator() = default;
591     // Placate MSVC by explicitly scoping 'iterator'.
592     const_iterator(typename IntrusiveBackList<T>::iterator X) : N(X.N) {}
593     explicit const_iterator(const T *N) : N(N) {}
594 
595     const_iterator &operator++() {
596       N = N->getNext();
597       return *this;
598     }
599 
600     explicit operator bool() const { return N; }
601     const T &operator*() const { return *static_cast<const T *>(N); }
602 
603     bool operator==(const const_iterator &X) const { return N == X.N; }
604     bool operator!=(const const_iterator &X) const { return N != X.N; }
605   };
606 
607   iterator begin() {
608     return Last ? iterator(static_cast<T *>(Last->Next.getPointer())) : end();
609   }
610   const_iterator begin() const {
611     return const_cast<IntrusiveBackList *>(this)->begin();
612   }
613   iterator end() { return iterator(); }
614   const_iterator end() const { return const_iterator(); }
615 
616   static iterator toIterator(T &N) { return iterator(&N); }
617   static const_iterator toIterator(const T &N) { return const_iterator(&N); }
618 };
619 
620 /// A list of DIE values.
621 ///
622 /// This is a singly-linked list, but instead of reversing the order of
623 /// insertion, we keep a pointer to the back of the list so we can push in
624 /// order.
625 ///
626 /// There are two main reasons to choose a linked list over a customized
627 /// vector-like data structure.
628 ///
629 ///  1. For teardown efficiency, we want DIEs to be BumpPtrAllocated.  Using a
630 ///     linked list here makes this way easier to accomplish.
631 ///  2. Carrying an extra pointer per \a DIEValue isn't expensive.  45% of DIEs
632 ///     have 2 or fewer values, and 90% have 5 or fewer.  A vector would be
633 ///     over-allocated by 50% on average anyway, the same cost as the
634 ///     linked-list node.
635 class DIEValueList {
636   struct Node : IntrusiveBackListNode {
637     DIEValue V;
638 
639     explicit Node(DIEValue V) : V(V) {}
640   };
641 
642   using ListTy = IntrusiveBackList<Node>;
643 
644   ListTy List;
645 
646 public:
647   class const_value_iterator;
648   class value_iterator
649       : public iterator_adaptor_base<value_iterator, ListTy::iterator,
650                                      std::forward_iterator_tag, DIEValue> {
651     friend class const_value_iterator;
652 
653     using iterator_adaptor =
654         iterator_adaptor_base<value_iterator, ListTy::iterator,
655                               std::forward_iterator_tag, DIEValue>;
656 
657   public:
658     value_iterator() = default;
659     explicit value_iterator(ListTy::iterator X) : iterator_adaptor(X) {}
660 
661     explicit operator bool() const { return bool(wrapped()); }
662     DIEValue &operator*() const { return wrapped()->V; }
663   };
664 
665   class const_value_iterator : public iterator_adaptor_base<
666                                    const_value_iterator, ListTy::const_iterator,
667                                    std::forward_iterator_tag, const DIEValue> {
668     using iterator_adaptor =
669         iterator_adaptor_base<const_value_iterator, ListTy::const_iterator,
670                               std::forward_iterator_tag, const DIEValue>;
671 
672   public:
673     const_value_iterator() = default;
674     const_value_iterator(DIEValueList::value_iterator X)
675         : iterator_adaptor(X.wrapped()) {}
676     explicit const_value_iterator(ListTy::const_iterator X)
677         : iterator_adaptor(X) {}
678 
679     explicit operator bool() const { return bool(wrapped()); }
680     const DIEValue &operator*() const { return wrapped()->V; }
681   };
682 
683   using value_range = iterator_range<value_iterator>;
684   using const_value_range = iterator_range<const_value_iterator>;
685 
686   value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V) {
687     List.push_back(*new (Alloc) Node(V));
688     return value_iterator(ListTy::toIterator(List.back()));
689   }
690   template <class T>
691   value_iterator addValue(BumpPtrAllocator &Alloc, dwarf::Attribute Attribute,
692                     dwarf::Form Form, T &&Value) {
693     return addValue(Alloc, DIEValue(Attribute, Form, std::forward<T>(Value)));
694   }
695 
696   /// Take ownership of the nodes in \p Other, and append them to the back of
697   /// the list.
698   void takeValues(DIEValueList &Other) { List.takeNodes(Other.List); }
699 
700   value_range values() {
701     return make_range(value_iterator(List.begin()), value_iterator(List.end()));
702   }
703   const_value_range values() const {
704     return make_range(const_value_iterator(List.begin()),
705                       const_value_iterator(List.end()));
706   }
707 };
708 
709 //===--------------------------------------------------------------------===//
710 /// A structured debug information entry.  Has an abbreviation which
711 /// describes its organization.
712 class DIE : IntrusiveBackListNode, public DIEValueList {
713   friend class IntrusiveBackList<DIE>;
714   friend class DIEUnit;
715 
716   /// Dwarf unit relative offset.
717   unsigned Offset = 0;
718   /// Size of instance + children.
719   unsigned Size = 0;
720   unsigned AbbrevNumber = ~0u;
721   /// Dwarf tag code.
722   dwarf::Tag Tag = (dwarf::Tag)0;
723   /// Set to true to force a DIE to emit an abbreviation that says it has
724   /// children even when it doesn't. This is used for unit testing purposes.
725   bool ForceChildren = false;
726   /// Children DIEs.
727   IntrusiveBackList<DIE> Children;
728 
729   /// The owner is either the parent DIE for children of other DIEs, or a
730   /// DIEUnit which contains this DIE as its unit DIE.
731   PointerUnion<DIE *, DIEUnit *> Owner;
732 
733   explicit DIE(dwarf::Tag Tag) : Tag(Tag) {}
734 
735 public:
736   DIE() = delete;
737   DIE(const DIE &RHS) = delete;
738   DIE(DIE &&RHS) = delete;
739   DIE &operator=(const DIE &RHS) = delete;
740   DIE &operator=(const DIE &&RHS) = delete;
741 
742   static DIE *get(BumpPtrAllocator &Alloc, dwarf::Tag Tag) {
743     return new (Alloc) DIE(Tag);
744   }
745 
746   // Accessors.
747   unsigned getAbbrevNumber() const { return AbbrevNumber; }
748   dwarf::Tag getTag() const { return Tag; }
749   /// Get the compile/type unit relative offset of this DIE.
750   unsigned getOffset() const { return Offset; }
751   unsigned getSize() const { return Size; }
752   bool hasChildren() const { return ForceChildren || !Children.empty(); }
753   void setForceChildren(bool B) { ForceChildren = B; }
754 
755   using child_iterator = IntrusiveBackList<DIE>::iterator;
756   using const_child_iterator = IntrusiveBackList<DIE>::const_iterator;
757   using child_range = iterator_range<child_iterator>;
758   using const_child_range = iterator_range<const_child_iterator>;
759 
760   child_range children() {
761     return make_range(Children.begin(), Children.end());
762   }
763   const_child_range children() const {
764     return make_range(Children.begin(), Children.end());
765   }
766 
767   DIE *getParent() const;
768 
769   /// Generate the abbreviation for this DIE.
770   ///
771   /// Calculate the abbreviation for this, which should be uniqued and
772   /// eventually used to call \a setAbbrevNumber().
773   DIEAbbrev generateAbbrev() const;
774 
775   /// Set the abbreviation number for this DIE.
776   void setAbbrevNumber(unsigned I) { AbbrevNumber = I; }
777 
778   /// Get the absolute offset within the .debug_info or .debug_types section
779   /// for this DIE.
780   unsigned getDebugSectionOffset() const;
781 
782   /// Compute the offset of this DIE and all its children.
783   ///
784   /// This function gets called just before we are going to generate the debug
785   /// information and gives each DIE a chance to figure out its CU relative DIE
786   /// offset, unique its abbreviation and fill in the abbreviation code, and
787   /// return the unit offset that points to where the next DIE will be emitted
788   /// within the debug unit section. After this function has been called for all
789   /// DIE objects, the DWARF can be generated since all DIEs will be able to
790   /// properly refer to other DIE objects since all DIEs have calculated their
791   /// offsets.
792   ///
793   /// \param AP AsmPrinter to use when calculating sizes.
794   /// \param AbbrevSet the abbreviation used to unique DIE abbreviations.
795   /// \param CUOffset the compile/type unit relative offset in bytes.
796   /// \returns the offset for the DIE that follows this DIE within the
797   /// current compile/type unit.
798   unsigned computeOffsetsAndAbbrevs(const AsmPrinter *AP,
799                                     DIEAbbrevSet &AbbrevSet, unsigned CUOffset);
800 
801   /// Climb up the parent chain to get the compile unit or type unit DIE that
802   /// this DIE belongs to.
803   ///
804   /// \returns the compile or type unit DIE that owns this DIE, or NULL if
805   /// this DIE hasn't been added to a unit DIE.
806   const DIE *getUnitDie() const;
807 
808   /// Climb up the parent chain to get the compile unit or type unit that this
809   /// DIE belongs to.
810   ///
811   /// \returns the DIEUnit that represents the compile or type unit that owns
812   /// this DIE, or NULL if this DIE hasn't been added to a unit DIE.
813   DIEUnit *getUnit() const;
814 
815   void setOffset(unsigned O) { Offset = O; }
816   void setSize(unsigned S) { Size = S; }
817 
818   /// Add a child to the DIE.
819   DIE &addChild(DIE *Child) {
820     assert(!Child->getParent() && "Child should be orphaned");
821     Child->Owner = this;
822     Children.push_back(*Child);
823     return Children.back();
824   }
825 
826   DIE &addChildFront(DIE *Child) {
827     assert(!Child->getParent() && "Child should be orphaned");
828     Child->Owner = this;
829     Children.push_front(*Child);
830     return Children.front();
831   }
832 
833   /// Find a value in the DIE with the attribute given.
834   ///
835   /// Returns a default-constructed DIEValue (where \a DIEValue::getType()
836   /// gives \a DIEValue::isNone) if no such attribute exists.
837   DIEValue findAttribute(dwarf::Attribute Attribute) const;
838 
839   void print(raw_ostream &O, unsigned IndentCount = 0) const;
840   void dump() const;
841 };
842 
843 //===--------------------------------------------------------------------===//
844 /// Represents a compile or type unit.
845 class DIEUnit {
846   /// The compile unit or type unit DIE. This variable must be an instance of
847   /// DIE so that we can calculate the DIEUnit from any DIE by traversing the
848   /// parent backchain and getting the Unit DIE, and then casting itself to a
849   /// DIEUnit. This allows us to be able to find the DIEUnit for any DIE without
850   /// having to store a pointer to the DIEUnit in each DIE instance.
851   DIE Die;
852   /// The section this unit will be emitted in. This may or may not be set to
853   /// a valid section depending on the client that is emitting DWARF.
854   MCSection *Section;
855   uint64_t Offset; /// .debug_info or .debug_types absolute section offset.
856   uint32_t Length; /// The length in bytes of all of the DIEs in this unit.
857   const uint16_t Version; /// The Dwarf version number for this unit.
858   const uint8_t AddrSize; /// The size in bytes of an address for this unit.
859 protected:
860   virtual ~DIEUnit() = default;
861 
862 public:
863   DIEUnit(uint16_t Version, uint8_t AddrSize, dwarf::Tag UnitTag);
864   DIEUnit(const DIEUnit &RHS) = delete;
865   DIEUnit(DIEUnit &&RHS) = delete;
866   void operator=(const DIEUnit &RHS) = delete;
867   void operator=(const DIEUnit &&RHS) = delete;
868   /// Set the section that this DIEUnit will be emitted into.
869   ///
870   /// This function is used by some clients to set the section. Not all clients
871   /// that emit DWARF use this section variable.
872   void setSection(MCSection *Section) {
873     assert(!this->Section);
874     this->Section = Section;
875   }
876 
877   virtual const MCSymbol *getCrossSectionRelativeBaseAddress() const {
878     return nullptr;
879   }
880 
881   /// Return the section that this DIEUnit will be emitted into.
882   ///
883   /// \returns Section pointer which can be NULL.
884   MCSection *getSection() const { return Section; }
885   void setDebugSectionOffset(unsigned O) { Offset = O; }
886   unsigned getDebugSectionOffset() const { return Offset; }
887   void setLength(uint64_t L) { Length = L; }
888   uint64_t getLength() const { return Length; }
889   uint16_t getDwarfVersion() const { return Version; }
890   uint16_t getAddressSize() const { return AddrSize; }
891   DIE &getUnitDie() { return Die; }
892   const DIE &getUnitDie() const { return Die; }
893 };
894 
895 struct BasicDIEUnit final : DIEUnit {
896   BasicDIEUnit(uint16_t Version, uint8_t AddrSize, dwarf::Tag UnitTag)
897       : DIEUnit(Version, AddrSize, UnitTag) {}
898 };
899 
900 //===--------------------------------------------------------------------===//
901 /// DIELoc - Represents an expression location.
902 //
903 class DIELoc : public DIEValueList {
904   mutable unsigned Size = 0; // Size in bytes excluding size header.
905 
906 public:
907   DIELoc() = default;
908 
909   /// ComputeSize - Calculate the size of the location expression.
910   ///
911   unsigned ComputeSize(const AsmPrinter *AP) const;
912 
913   /// BestForm - Choose the best form for data.
914   ///
915   dwarf::Form BestForm(unsigned DwarfVersion) const {
916     if (DwarfVersion > 3)
917       return dwarf::DW_FORM_exprloc;
918     // Pre-DWARF4 location expressions were blocks and not exprloc.
919     if ((unsigned char)Size == Size)
920       return dwarf::DW_FORM_block1;
921     if ((unsigned short)Size == Size)
922       return dwarf::DW_FORM_block2;
923     if ((unsigned int)Size == Size)
924       return dwarf::DW_FORM_block4;
925     return dwarf::DW_FORM_block;
926   }
927 
928   void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
929   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
930 
931   void print(raw_ostream &O) const;
932 };
933 
934 //===--------------------------------------------------------------------===//
935 /// DIEBlock - Represents a block of values.
936 //
937 class DIEBlock : public DIEValueList {
938   mutable unsigned Size = 0; // Size in bytes excluding size header.
939 
940 public:
941   DIEBlock() = default;
942 
943   /// ComputeSize - Calculate the size of the location expression.
944   ///
945   unsigned ComputeSize(const AsmPrinter *AP) const;
946 
947   /// BestForm - Choose the best form for data.
948   ///
949   dwarf::Form BestForm() const {
950     if ((unsigned char)Size == Size)
951       return dwarf::DW_FORM_block1;
952     if ((unsigned short)Size == Size)
953       return dwarf::DW_FORM_block2;
954     if ((unsigned int)Size == Size)
955       return dwarf::DW_FORM_block4;
956     return dwarf::DW_FORM_block;
957   }
958 
959   void EmitValue(const AsmPrinter *Asm, dwarf::Form Form) const;
960   unsigned SizeOf(const AsmPrinter *AP, dwarf::Form Form) const;
961 
962   void print(raw_ostream &O) const;
963 };
964 
965 } // end namespace llvm
966 
967 #endif // LLVM_LIB_CODEGEN_ASMPRINTER_DIE_H
968