xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DIEHash.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 //===-- llvm/CodeGen/DIEHash.cpp - Dwarf Hashing Framework ----------------===//
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 // This file contains support for DWARF4 hashing of DIEs.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DIEHash.h"
14 #include "ByteStreamer.h"
15 #include "DwarfDebug.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace llvm;
25 
26 #define DEBUG_TYPE "dwarfdebug"
27 
28 /// Grabs the string in whichever attribute is passed in and returns
29 /// a reference to it.
30 static StringRef getDIEStringAttr(const DIE &Die, uint16_t Attr) {
31   // Iterate through all the attributes until we find the one we're
32   // looking for, if we can't find it return an empty string.
33   for (const auto &V : Die.values())
34     if (V.getAttribute() == Attr)
35       return V.getDIEString().getString();
36 
37   return StringRef("");
38 }
39 
40 /// Adds the string in \p Str to the hash. This also hashes
41 /// a trailing NULL with the string.
42 void DIEHash::addString(StringRef Str) {
43   LLVM_DEBUG(dbgs() << "Adding string " << Str << " to hash.\n");
44   Hash.update(Str);
45   Hash.update(makeArrayRef((uint8_t)'\0'));
46 }
47 
48 // FIXME: The LEB128 routines are copied and only slightly modified out of
49 // LEB128.h.
50 
51 /// Adds the unsigned in \p Value to the hash encoded as a ULEB128.
52 void DIEHash::addULEB128(uint64_t Value) {
53   LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
54   do {
55     uint8_t Byte = Value & 0x7f;
56     Value >>= 7;
57     if (Value != 0)
58       Byte |= 0x80; // Mark this byte to show that more bytes will follow.
59     Hash.update(Byte);
60   } while (Value != 0);
61 }
62 
63 void DIEHash::addSLEB128(int64_t Value) {
64   LLVM_DEBUG(dbgs() << "Adding ULEB128 " << Value << " to hash.\n");
65   bool More;
66   do {
67     uint8_t Byte = Value & 0x7f;
68     Value >>= 7;
69     More = !((((Value == 0) && ((Byte & 0x40) == 0)) ||
70               ((Value == -1) && ((Byte & 0x40) != 0))));
71     if (More)
72       Byte |= 0x80; // Mark this byte to show that more bytes will follow.
73     Hash.update(Byte);
74   } while (More);
75 }
76 
77 /// Including \p Parent adds the context of Parent to the hash..
78 void DIEHash::addParentContext(const DIE &Parent) {
79 
80   LLVM_DEBUG(dbgs() << "Adding parent context to hash...\n");
81 
82   // [7.27.2] For each surrounding type or namespace beginning with the
83   // outermost such construct...
84   SmallVector<const DIE *, 1> Parents;
85   const DIE *Cur = &Parent;
86   while (Cur->getParent()) {
87     Parents.push_back(Cur);
88     Cur = Cur->getParent();
89   }
90   assert(Cur->getTag() == dwarf::DW_TAG_compile_unit ||
91          Cur->getTag() == dwarf::DW_TAG_type_unit);
92 
93   // Reverse iterate over our list to go from the outermost construct to the
94   // innermost.
95   for (SmallVectorImpl<const DIE *>::reverse_iterator I = Parents.rbegin(),
96                                                       E = Parents.rend();
97        I != E; ++I) {
98     const DIE &Die = **I;
99 
100     // ... Append the letter "C" to the sequence...
101     addULEB128('C');
102 
103     // ... Followed by the DWARF tag of the construct...
104     addULEB128(Die.getTag());
105 
106     // ... Then the name, taken from the DW_AT_name attribute.
107     StringRef Name = getDIEStringAttr(Die, dwarf::DW_AT_name);
108     LLVM_DEBUG(dbgs() << "... adding context: " << Name << "\n");
109     if (!Name.empty())
110       addString(Name);
111   }
112 }
113 
114 // Collect all of the attributes for a particular DIE in single structure.
115 void DIEHash::collectAttributes(const DIE &Die, DIEAttrs &Attrs) {
116 
117   for (const auto &V : Die.values()) {
118     LLVM_DEBUG(dbgs() << "Attribute: "
119                       << dwarf::AttributeString(V.getAttribute())
120                       << " added.\n");
121     switch (V.getAttribute()) {
122 #define HANDLE_DIE_HASH_ATTR(NAME)                                             \
123   case dwarf::NAME:                                                            \
124     Attrs.NAME = V;                                                            \
125     break;
126 #include "DIEHashAttributes.def"
127     default:
128       break;
129     }
130   }
131 }
132 
133 void DIEHash::hashShallowTypeReference(dwarf::Attribute Attribute,
134                                        const DIE &Entry, StringRef Name) {
135   // append the letter 'N'
136   addULEB128('N');
137 
138   // the DWARF attribute code (DW_AT_type or DW_AT_friend),
139   addULEB128(Attribute);
140 
141   // the context of the tag,
142   if (const DIE *Parent = Entry.getParent())
143     addParentContext(*Parent);
144 
145   // the letter 'E',
146   addULEB128('E');
147 
148   // and the name of the type.
149   addString(Name);
150 
151   // Currently DW_TAG_friends are not used by Clang, but if they do become so,
152   // here's the relevant spec text to implement:
153   //
154   // For DW_TAG_friend, if the referenced entry is the DW_TAG_subprogram,
155   // the context is omitted and the name to be used is the ABI-specific name
156   // of the subprogram (e.g., the mangled linker name).
157 }
158 
159 void DIEHash::hashRepeatedTypeReference(dwarf::Attribute Attribute,
160                                         unsigned DieNumber) {
161   // a) If T is in the list of [previously hashed types], use the letter
162   // 'R' as the marker
163   addULEB128('R');
164 
165   addULEB128(Attribute);
166 
167   // and use the unsigned LEB128 encoding of [the index of T in the
168   // list] as the attribute value;
169   addULEB128(DieNumber);
170 }
171 
172 void DIEHash::hashDIEEntry(dwarf::Attribute Attribute, dwarf::Tag Tag,
173                            const DIE &Entry) {
174   assert(Tag != dwarf::DW_TAG_friend && "No current LLVM clients emit friend "
175                                         "tags. Add support here when there's "
176                                         "a use case");
177   // Step 5
178   // If the tag in Step 3 is one of [the below tags]
179   if ((Tag == dwarf::DW_TAG_pointer_type ||
180        Tag == dwarf::DW_TAG_reference_type ||
181        Tag == dwarf::DW_TAG_rvalue_reference_type ||
182        Tag == dwarf::DW_TAG_ptr_to_member_type) &&
183       // and the referenced type (via the [below attributes])
184       // FIXME: This seems overly restrictive, and causes hash mismatches
185       // there's a decl/def difference in the containing type of a
186       // ptr_to_member_type, but it's what DWARF says, for some reason.
187       Attribute == dwarf::DW_AT_type) {
188     // ... has a DW_AT_name attribute,
189     StringRef Name = getDIEStringAttr(Entry, dwarf::DW_AT_name);
190     if (!Name.empty()) {
191       hashShallowTypeReference(Attribute, Entry, Name);
192       return;
193     }
194   }
195 
196   unsigned &DieNumber = Numbering[&Entry];
197   if (DieNumber) {
198     hashRepeatedTypeReference(Attribute, DieNumber);
199     return;
200   }
201 
202   // otherwise, b) use the letter 'T' as the marker, ...
203   addULEB128('T');
204 
205   addULEB128(Attribute);
206 
207   // ... process the type T recursively by performing Steps 2 through 7, and
208   // use the result as the attribute value.
209   DieNumber = Numbering.size();
210   computeHash(Entry);
211 }
212 
213 // Hash all of the values in a block like set of values. This assumes that
214 // all of the data is going to be added as integers.
215 void DIEHash::hashBlockData(const DIE::const_value_range &Values) {
216   for (const auto &V : Values)
217     Hash.update((uint64_t)V.getDIEInteger().getValue());
218 }
219 
220 // Hash the contents of a loclistptr class.
221 void DIEHash::hashLocList(const DIELocList &LocList) {
222   HashingByteStreamer Streamer(*this);
223   DwarfDebug &DD = *AP->getDwarfDebug();
224   const DebugLocStream &Locs = DD.getDebugLocs();
225   const DebugLocStream::List &List = Locs.getList(LocList.getValue());
226   for (const DebugLocStream::Entry &Entry : Locs.getEntries(List))
227     DD.emitDebugLocEntry(Streamer, Entry, List.CU);
228 }
229 
230 // Hash an individual attribute \param Attr based on the type of attribute and
231 // the form.
232 void DIEHash::hashAttribute(const DIEValue &Value, dwarf::Tag Tag) {
233   dwarf::Attribute Attribute = Value.getAttribute();
234 
235   // Other attribute values use the letter 'A' as the marker, and the value
236   // consists of the form code (encoded as an unsigned LEB128 value) followed by
237   // the encoding of the value according to the form code. To ensure
238   // reproducibility of the signature, the set of forms used in the signature
239   // computation is limited to the following: DW_FORM_sdata, DW_FORM_flag,
240   // DW_FORM_string, and DW_FORM_block.
241 
242   switch (Value.getType()) {
243   case DIEValue::isNone:
244     llvm_unreachable("Expected valid DIEValue");
245 
246     // 7.27 Step 3
247     // ... An attribute that refers to another type entry T is processed as
248     // follows:
249   case DIEValue::isEntry:
250     hashDIEEntry(Attribute, Tag, Value.getDIEEntry().getEntry());
251     break;
252   case DIEValue::isInteger: {
253     addULEB128('A');
254     addULEB128(Attribute);
255     switch (Value.getForm()) {
256     case dwarf::DW_FORM_data1:
257     case dwarf::DW_FORM_data2:
258     case dwarf::DW_FORM_data4:
259     case dwarf::DW_FORM_data8:
260     case dwarf::DW_FORM_udata:
261     case dwarf::DW_FORM_sdata:
262       addULEB128(dwarf::DW_FORM_sdata);
263       addSLEB128((int64_t)Value.getDIEInteger().getValue());
264       break;
265     // DW_FORM_flag_present is just flag with a value of one. We still give it a
266     // value so just use the value.
267     case dwarf::DW_FORM_flag_present:
268     case dwarf::DW_FORM_flag:
269       addULEB128(dwarf::DW_FORM_flag);
270       addULEB128((int64_t)Value.getDIEInteger().getValue());
271       break;
272     default:
273       llvm_unreachable("Unknown integer form!");
274     }
275     break;
276   }
277   case DIEValue::isString:
278     addULEB128('A');
279     addULEB128(Attribute);
280     addULEB128(dwarf::DW_FORM_string);
281     addString(Value.getDIEString().getString());
282     break;
283   case DIEValue::isInlineString:
284     addULEB128('A');
285     addULEB128(Attribute);
286     addULEB128(dwarf::DW_FORM_string);
287     addString(Value.getDIEInlineString().getString());
288     break;
289   case DIEValue::isBlock:
290   case DIEValue::isLoc:
291   case DIEValue::isLocList:
292     addULEB128('A');
293     addULEB128(Attribute);
294     addULEB128(dwarf::DW_FORM_block);
295     if (Value.getType() == DIEValue::isBlock) {
296       addULEB128(Value.getDIEBlock().ComputeSize(AP));
297       hashBlockData(Value.getDIEBlock().values());
298     } else if (Value.getType() == DIEValue::isLoc) {
299       addULEB128(Value.getDIELoc().ComputeSize(AP));
300       hashBlockData(Value.getDIELoc().values());
301     } else {
302       // We could add the block length, but that would take
303       // a bit of work and not add a lot of uniqueness
304       // to the hash in some way we could test.
305       hashLocList(Value.getDIELocList());
306     }
307     break;
308     // FIXME: It's uncertain whether or not we should handle this at the moment.
309   case DIEValue::isExpr:
310   case DIEValue::isLabel:
311   case DIEValue::isBaseTypeRef:
312   case DIEValue::isDelta:
313     llvm_unreachable("Add support for additional value types.");
314   }
315 }
316 
317 // Go through the attributes from \param Attrs in the order specified in 7.27.4
318 // and hash them.
319 void DIEHash::hashAttributes(const DIEAttrs &Attrs, dwarf::Tag Tag) {
320 #define HANDLE_DIE_HASH_ATTR(NAME)                                             \
321   {                                                                            \
322     if (Attrs.NAME)                                                           \
323       hashAttribute(Attrs.NAME, Tag);                                         \
324   }
325 #include "DIEHashAttributes.def"
326   // FIXME: Add the extended attributes.
327 }
328 
329 // Add all of the attributes for \param Die to the hash.
330 void DIEHash::addAttributes(const DIE &Die) {
331   DIEAttrs Attrs = {};
332   collectAttributes(Die, Attrs);
333   hashAttributes(Attrs, Die.getTag());
334 }
335 
336 void DIEHash::hashNestedType(const DIE &Die, StringRef Name) {
337   // 7.27 Step 7
338   // ... append the letter 'S',
339   addULEB128('S');
340 
341   // the tag of C,
342   addULEB128(Die.getTag());
343 
344   // and the name.
345   addString(Name);
346 }
347 
348 // Compute the hash of a DIE. This is based on the type signature computation
349 // given in section 7.27 of the DWARF4 standard. It is the md5 hash of a
350 // flattened description of the DIE.
351 void DIEHash::computeHash(const DIE &Die) {
352   // Append the letter 'D', followed by the DWARF tag of the DIE.
353   addULEB128('D');
354   addULEB128(Die.getTag());
355 
356   // Add each of the attributes of the DIE.
357   addAttributes(Die);
358 
359   // Then hash each of the children of the DIE.
360   for (auto &C : Die.children()) {
361     // 7.27 Step 7
362     // If C is a nested type entry or a member function entry, ...
363     if (isType(C.getTag()) || (C.getTag() == dwarf::DW_TAG_subprogram && isType(C.getParent()->getTag()))) {
364       StringRef Name = getDIEStringAttr(C, dwarf::DW_AT_name);
365       // ... and has a DW_AT_name attribute
366       if (!Name.empty()) {
367         hashNestedType(C, Name);
368         continue;
369       }
370     }
371     computeHash(C);
372   }
373 
374   // Following the last (or if there are no children), append a zero byte.
375   Hash.update(makeArrayRef((uint8_t)'\0'));
376 }
377 
378 /// This is based on the type signature computation given in section 7.27 of the
379 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
380 /// with the inclusion of the full CU and all top level CU entities.
381 // TODO: Initialize the type chain at 0 instead of 1 for CU signatures.
382 uint64_t DIEHash::computeCUSignature(StringRef DWOName, const DIE &Die) {
383   Numbering.clear();
384   Numbering[&Die] = 1;
385 
386   if (!DWOName.empty())
387     Hash.update(DWOName);
388   // Hash the DIE.
389   computeHash(Die);
390 
391   // Now return the result.
392   MD5::MD5Result Result;
393   Hash.final(Result);
394 
395   // ... take the least significant 8 bytes and return those. Our MD5
396   // implementation always returns its results in little endian, so we actually
397   // need the "high" word.
398   return Result.high();
399 }
400 
401 /// This is based on the type signature computation given in section 7.27 of the
402 /// DWARF4 standard. It is an md5 hash of the flattened description of the DIE
403 /// with the inclusion of additional forms not specifically called out in the
404 /// standard.
405 uint64_t DIEHash::computeTypeSignature(const DIE &Die) {
406   Numbering.clear();
407   Numbering[&Die] = 1;
408 
409   if (const DIE *Parent = Die.getParent())
410     addParentContext(*Parent);
411 
412   // Hash the DIE.
413   computeHash(Die);
414 
415   // Now return the result.
416   MD5::MD5Result Result;
417   Hash.final(Result);
418 
419   // ... take the least significant 8 bytes and return those. Our MD5
420   // implementation always returns its results in little endian, so we actually
421   // need the "high" word.
422   return Result.high();
423 }
424