1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/DebugInfo.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DIBuilder.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/ValueHandle.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Dwarf.h"
31 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm;
33 using namespace llvm::dwarf;
34
35 //===----------------------------------------------------------------------===//
36 // DIDescriptor
37 //===----------------------------------------------------------------------===//
38
Verify() const39 bool DIDescriptor::Verify() const {
40 return DbgNode &&
41 (DIDerivedType(DbgNode).Verify() ||
42 DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
43 DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
44 DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
45 DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
46 DILexicalBlock(DbgNode).Verify() ||
47 DILexicalBlockFile(DbgNode).Verify() ||
48 DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
49 DIObjCProperty(DbgNode).Verify() ||
50 DITemplateTypeParameter(DbgNode).Verify() ||
51 DITemplateValueParameter(DbgNode).Verify() ||
52 DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
53 }
54
getField(const MDNode * DbgNode,unsigned Elt)55 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
56 if (!DbgNode || Elt >= DbgNode->getNumOperands())
57 return nullptr;
58 return DbgNode->getOperand(Elt);
59 }
60
getNodeField(const MDNode * DbgNode,unsigned Elt)61 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
62 return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
63 }
64
getStringField(const MDNode * DbgNode,unsigned Elt)65 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
66 if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
67 return MDS->getString();
68 return StringRef();
69 }
70
getStringField(unsigned Elt) const71 StringRef DIDescriptor::getStringField(unsigned Elt) const {
72 return ::getStringField(DbgNode, Elt);
73 }
74
getUInt64Field(unsigned Elt) const75 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
76 if (auto *C = getConstantField(Elt))
77 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
78 return CI->getZExtValue();
79
80 return 0;
81 }
82
getInt64Field(unsigned Elt) const83 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
84 if (auto *C = getConstantField(Elt))
85 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
86 return CI->getZExtValue();
87
88 return 0;
89 }
90
getDescriptorField(unsigned Elt) const91 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
92 MDNode *Field = getNodeField(DbgNode, Elt);
93 return DIDescriptor(Field);
94 }
95
getGlobalVariableField(unsigned Elt) const96 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
97 return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
98 }
99
getConstantField(unsigned Elt) const100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
101 if (!DbgNode)
102 return nullptr;
103
104 if (Elt < DbgNode->getNumOperands())
105 if (auto *C =
106 dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
107 return C->getValue();
108 return nullptr;
109 }
110
getFunctionField(unsigned Elt) const111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
112 return dyn_cast_or_null<Function>(getConstantField(Elt));
113 }
114
replaceFunctionField(unsigned Elt,Function * F)115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
116 if (!DbgNode)
117 return;
118
119 if (Elt < DbgNode->getNumOperands()) {
120 MDNode *Node = const_cast<MDNode *>(DbgNode);
121 Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
122 }
123 }
124
125 static unsigned DIVariableInlinedAtIndex = 4;
getInlinedAt() const126 MDNode *DIVariable::getInlinedAt() const {
127 return getNodeField(DbgNode, DIVariableInlinedAtIndex);
128 }
129
130 /// \brief Return the size reported by the variable's type.
getSizeInBits(const DITypeIdentifierMap & Map)131 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
132 DIType Ty = getType().resolve(Map);
133 // Follow derived types until we reach a type that
134 // reports back a size.
135 while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
136 DIDerivedType DT(&*Ty);
137 Ty = DT.getTypeDerivedFrom().resolve(Map);
138 }
139 assert(Ty.getSizeInBits() && "type with size 0");
140 return Ty.getSizeInBits();
141 }
142
getElement(unsigned Idx) const143 uint64_t DIExpression::getElement(unsigned Idx) const {
144 unsigned I = Idx + 1;
145 assert(I < getNumHeaderFields() &&
146 "non-existing complex address element requested");
147 return getHeaderFieldAs<int64_t>(I);
148 }
149
isVariablePiece() const150 bool DIExpression::isVariablePiece() const {
151 return getNumElements() && getElement(0) == dwarf::DW_OP_piece;
152 }
153
getPieceOffset() const154 uint64_t DIExpression::getPieceOffset() const {
155 assert(isVariablePiece());
156 return getElement(1);
157 }
158
getPieceSize() const159 uint64_t DIExpression::getPieceSize() const {
160 assert(isVariablePiece());
161 return getElement(2);
162 }
163
164 //===----------------------------------------------------------------------===//
165 // Predicates
166 //===----------------------------------------------------------------------===//
167
isSubroutineType() const168 bool DIDescriptor::isSubroutineType() const {
169 return DbgNode && getTag() == dwarf::DW_TAG_subroutine_type;
170 }
171
isBasicType() const172 bool DIDescriptor::isBasicType() const {
173 if (!DbgNode)
174 return false;
175 switch (getTag()) {
176 case dwarf::DW_TAG_base_type:
177 case dwarf::DW_TAG_unspecified_type:
178 return true;
179 default:
180 return false;
181 }
182 }
183
isDerivedType() const184 bool DIDescriptor::isDerivedType() const {
185 if (!DbgNode)
186 return false;
187 switch (getTag()) {
188 case dwarf::DW_TAG_typedef:
189 case dwarf::DW_TAG_pointer_type:
190 case dwarf::DW_TAG_ptr_to_member_type:
191 case dwarf::DW_TAG_reference_type:
192 case dwarf::DW_TAG_rvalue_reference_type:
193 case dwarf::DW_TAG_const_type:
194 case dwarf::DW_TAG_volatile_type:
195 case dwarf::DW_TAG_restrict_type:
196 case dwarf::DW_TAG_member:
197 case dwarf::DW_TAG_inheritance:
198 case dwarf::DW_TAG_friend:
199 return true;
200 default:
201 // CompositeTypes are currently modelled as DerivedTypes.
202 return isCompositeType();
203 }
204 }
205
isCompositeType() const206 bool DIDescriptor::isCompositeType() const {
207 if (!DbgNode)
208 return false;
209 switch (getTag()) {
210 case dwarf::DW_TAG_array_type:
211 case dwarf::DW_TAG_structure_type:
212 case dwarf::DW_TAG_union_type:
213 case dwarf::DW_TAG_enumeration_type:
214 case dwarf::DW_TAG_subroutine_type:
215 case dwarf::DW_TAG_class_type:
216 return true;
217 default:
218 return false;
219 }
220 }
221
isVariable() const222 bool DIDescriptor::isVariable() const {
223 if (!DbgNode)
224 return false;
225 switch (getTag()) {
226 case dwarf::DW_TAG_auto_variable:
227 case dwarf::DW_TAG_arg_variable:
228 return true;
229 default:
230 return false;
231 }
232 }
233
isType() const234 bool DIDescriptor::isType() const {
235 return isBasicType() || isCompositeType() || isDerivedType();
236 }
237
isSubprogram() const238 bool DIDescriptor::isSubprogram() const {
239 return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
240 }
241
isGlobalVariable() const242 bool DIDescriptor::isGlobalVariable() const {
243 return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
244 getTag() == dwarf::DW_TAG_constant);
245 }
246
isScope() const247 bool DIDescriptor::isScope() const {
248 if (!DbgNode)
249 return false;
250 switch (getTag()) {
251 case dwarf::DW_TAG_compile_unit:
252 case dwarf::DW_TAG_lexical_block:
253 case dwarf::DW_TAG_subprogram:
254 case dwarf::DW_TAG_namespace:
255 case dwarf::DW_TAG_file_type:
256 return true;
257 default:
258 break;
259 }
260 return isType();
261 }
262
isTemplateTypeParameter() const263 bool DIDescriptor::isTemplateTypeParameter() const {
264 return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
265 }
266
isTemplateValueParameter() const267 bool DIDescriptor::isTemplateValueParameter() const {
268 return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
269 getTag() == dwarf::DW_TAG_GNU_template_template_param ||
270 getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
271 }
272
isCompileUnit() const273 bool DIDescriptor::isCompileUnit() const {
274 return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
275 }
276
isFile() const277 bool DIDescriptor::isFile() const {
278 return DbgNode && getTag() == dwarf::DW_TAG_file_type;
279 }
280
isNameSpace() const281 bool DIDescriptor::isNameSpace() const {
282 return DbgNode && getTag() == dwarf::DW_TAG_namespace;
283 }
284
isLexicalBlockFile() const285 bool DIDescriptor::isLexicalBlockFile() const {
286 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
287 DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
288 }
289
isLexicalBlock() const290 bool DIDescriptor::isLexicalBlock() const {
291 // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
292 // something relies on this returning true for DILexicalBlockFile.
293 return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
294 DbgNode->getNumOperands() == 3 &&
295 (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
296 }
297
isSubrange() const298 bool DIDescriptor::isSubrange() const {
299 return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
300 }
301
isEnumerator() const302 bool DIDescriptor::isEnumerator() const {
303 return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
304 }
305
isObjCProperty() const306 bool DIDescriptor::isObjCProperty() const {
307 return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
308 }
309
isImportedEntity() const310 bool DIDescriptor::isImportedEntity() const {
311 return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
312 getTag() == dwarf::DW_TAG_imported_declaration);
313 }
314
isExpression() const315 bool DIDescriptor::isExpression() const {
316 return DbgNode && (getTag() == dwarf::DW_TAG_expression);
317 }
318
319 //===----------------------------------------------------------------------===//
320 // Simple Descriptor Constructors and other Methods
321 //===----------------------------------------------------------------------===//
322
replaceAllUsesWith(LLVMContext & VMContext,DIDescriptor D)323 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
324
325 assert(DbgNode && "Trying to replace an unverified type!");
326
327 // Since we use a TrackingVH for the node, its easy for clients to manufacture
328 // legitimate situations where they want to replaceAllUsesWith() on something
329 // which, due to uniquing, has merged with the source. We shield clients from
330 // this detail by allowing a value to be replaced with replaceAllUsesWith()
331 // itself.
332 const MDNode *DN = D;
333 if (DbgNode == DN) {
334 SmallVector<Metadata *, 10> Ops(DbgNode->getNumOperands());
335 for (size_t i = 0; i != Ops.size(); ++i)
336 Ops[i] = DbgNode->getOperand(i);
337 DN = MDNode::get(VMContext, Ops);
338 }
339
340 auto *Node = cast<MDNodeFwdDecl>(const_cast<MDNode *>(DbgNode));
341 Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
342 MDNode::deleteTemporary(Node);
343 DbgNode = DN;
344 }
345
replaceAllUsesWith(MDNode * D)346 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
347 assert(DbgNode && "Trying to replace an unverified type!");
348 assert(DbgNode != D && "This replacement should always happen");
349 auto *Node = cast<MDNodeFwdDecl>(const_cast<MDNode *>(DbgNode));
350 Node->replaceAllUsesWith(D);
351 MDNode::deleteTemporary(Node);
352 }
353
Verify() const354 bool DICompileUnit::Verify() const {
355 if (!isCompileUnit())
356 return false;
357
358 // Don't bother verifying the compilation directory or producer string
359 // as those could be empty.
360 if (getFilename().empty())
361 return false;
362
363 return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
364 }
365
Verify() const366 bool DIObjCProperty::Verify() const {
367 if (!isObjCProperty())
368 return false;
369
370 // Don't worry about the rest of the strings for now.
371 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
372 }
373
374 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
375 ///
376 /// We currently allow an empty string and an integer.
377 /// But we don't allow a non-empty string in a MDNode field.
fieldIsMDNode(const MDNode * DbgNode,unsigned Elt)378 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
379 // FIXME: This function should return true, if the field is null or the field
380 // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
381 Metadata *Fld = getField(DbgNode, Elt);
382 if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
383 return false;
384 return true;
385 }
386
387 /// \brief Check if a field at position Elt of a MDNode is a MDString.
fieldIsMDString(const MDNode * DbgNode,unsigned Elt)388 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
389 Metadata *Fld = getField(DbgNode, Elt);
390 return !Fld || isa<MDString>(Fld);
391 }
392
393 /// \brief Check if a value can be a reference to a type.
isTypeRef(const Metadata * MD)394 static bool isTypeRef(const Metadata *MD) {
395 if (!MD)
396 return true;
397 if (auto *S = dyn_cast<MDString>(MD))
398 return !S->getString().empty();
399 if (auto *N = dyn_cast<MDNode>(MD))
400 return DIType(N).isType();
401 return false;
402 }
403
404 /// \brief Check if referenced field might be a type.
fieldIsTypeRef(const MDNode * DbgNode,unsigned Elt)405 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
406 return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
407 }
408
409 /// \brief Check if a value can be a ScopeRef.
isScopeRef(const Metadata * MD)410 static bool isScopeRef(const Metadata *MD) {
411 if (!MD)
412 return true;
413 if (auto *S = dyn_cast<MDString>(MD))
414 return !S->getString().empty();
415 return isa<MDNode>(MD);
416 }
417
418 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
fieldIsScopeRef(const MDNode * DbgNode,unsigned Elt)419 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
420 return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
421 }
422
Verify() const423 bool DIType::Verify() const {
424 if (!isType())
425 return false;
426 // Make sure Context @ field 2 is MDNode.
427 if (!fieldIsScopeRef(DbgNode, 2))
428 return false;
429
430 // FIXME: Sink this into the various subclass verifies.
431 uint16_t Tag = getTag();
432 if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
433 Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
434 Tag != dwarf::DW_TAG_ptr_to_member_type &&
435 Tag != dwarf::DW_TAG_reference_type &&
436 Tag != dwarf::DW_TAG_rvalue_reference_type &&
437 Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
438 Tag != dwarf::DW_TAG_enumeration_type &&
439 Tag != dwarf::DW_TAG_subroutine_type &&
440 Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
441 getFilename().empty())
442 return false;
443
444 // DIType is abstract, it should be a BasicType, a DerivedType or
445 // a CompositeType.
446 if (isBasicType())
447 return DIBasicType(DbgNode).Verify();
448 else if (isCompositeType())
449 return DICompositeType(DbgNode).Verify();
450 else if (isDerivedType())
451 return DIDerivedType(DbgNode).Verify();
452 else
453 return false;
454 }
455
Verify() const456 bool DIBasicType::Verify() const {
457 return isBasicType() && DbgNode->getNumOperands() == 3 &&
458 getNumHeaderFields() == 8;
459 }
460
Verify() const461 bool DIDerivedType::Verify() const {
462 // Make sure DerivedFrom @ field 3 is TypeRef.
463 if (!fieldIsTypeRef(DbgNode, 3))
464 return false;
465 if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
466 // Make sure ClassType @ field 4 is a TypeRef.
467 if (!fieldIsTypeRef(DbgNode, 4))
468 return false;
469
470 return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
471 DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
472 getNumHeaderFields() <= 8;
473 }
474
Verify() const475 bool DICompositeType::Verify() const {
476 if (!isCompositeType())
477 return false;
478
479 // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
480 if (!fieldIsTypeRef(DbgNode, 3))
481 return false;
482 if (!fieldIsTypeRef(DbgNode, 5))
483 return false;
484
485 // Make sure the type identifier at field 7 is MDString, it can be null.
486 if (!fieldIsMDString(DbgNode, 7))
487 return false;
488
489 // A subroutine type can't be both & and &&.
490 if (isLValueReference() && isRValueReference())
491 return false;
492
493 return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
494 }
495
Verify() const496 bool DISubprogram::Verify() const {
497 if (!isSubprogram())
498 return false;
499
500 // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
501 if (!fieldIsScopeRef(DbgNode, 2))
502 return false;
503 if (!fieldIsMDNode(DbgNode, 3))
504 return false;
505 // Containing type @ field 4.
506 if (!fieldIsTypeRef(DbgNode, 4))
507 return false;
508
509 // A subprogram can't be both & and &&.
510 if (isLValueReference() && isRValueReference())
511 return false;
512
513 // If a DISubprogram has an llvm::Function*, then scope chains from all
514 // instructions within the function should lead to this DISubprogram.
515 if (auto *F = getFunction()) {
516 for (auto &BB : *F) {
517 for (auto &I : BB) {
518 DebugLoc DL = I.getDebugLoc();
519 if (DL.isUnknown())
520 continue;
521
522 MDNode *Scope = nullptr;
523 MDNode *IA = nullptr;
524 // walk the inlined-at scopes
525 while ((IA = DL.getInlinedAt()))
526 DL = DebugLoc::getFromDILocation(IA);
527 DL.getScopeAndInlinedAt(Scope, IA);
528 if (!Scope)
529 return false;
530 assert(!IA);
531 while (!DIDescriptor(Scope).isSubprogram()) {
532 DILexicalBlockFile D(Scope);
533 Scope = D.isLexicalBlockFile()
534 ? D.getScope()
535 : DebugLoc::getFromDILexicalBlock(Scope).getScope();
536 assert(Scope && "lexical block file has no scope");
537 }
538 if (!DISubprogram(Scope).describes(F))
539 return false;
540 }
541 }
542 }
543 return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
544 }
545
Verify() const546 bool DIGlobalVariable::Verify() const {
547 if (!isGlobalVariable())
548 return false;
549
550 if (getDisplayName().empty())
551 return false;
552 // Make sure context @ field 1 is an MDNode.
553 if (!fieldIsMDNode(DbgNode, 1))
554 return false;
555 // Make sure that type @ field 3 is a DITypeRef.
556 if (!fieldIsTypeRef(DbgNode, 3))
557 return false;
558 // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
559 if (!fieldIsMDNode(DbgNode, 5))
560 return false;
561
562 return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
563 }
564
Verify() const565 bool DIVariable::Verify() const {
566 if (!isVariable())
567 return false;
568
569 // Make sure context @ field 1 is an MDNode.
570 if (!fieldIsMDNode(DbgNode, 1))
571 return false;
572 // Make sure that type @ field 3 is a DITypeRef.
573 if (!fieldIsTypeRef(DbgNode, 3))
574 return false;
575
576 // Check the number of header fields, which is common between complex and
577 // simple variables.
578 if (getNumHeaderFields() != 4)
579 return false;
580
581 // Variable without an inline location.
582 if (DbgNode->getNumOperands() == 4)
583 return true;
584
585 // Variable with an inline location.
586 return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
587 }
588
Verify() const589 bool DIExpression::Verify() const {
590 // Empty DIExpressions may be represented as a nullptr.
591 if (!DbgNode)
592 return true;
593
594 return isExpression() && DbgNode->getNumOperands() == 1;
595 }
596
Verify() const597 bool DILocation::Verify() const {
598 return DbgNode && isa<MDLocation>(DbgNode);
599 }
600
Verify() const601 bool DINameSpace::Verify() const {
602 if (!isNameSpace())
603 return false;
604 return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
605 }
606
getFileNode() const607 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
608
Verify() const609 bool DIFile::Verify() const {
610 return isFile() && DbgNode->getNumOperands() == 2;
611 }
612
Verify() const613 bool DIEnumerator::Verify() const {
614 return isEnumerator() && DbgNode->getNumOperands() == 1 &&
615 getNumHeaderFields() == 3;
616 }
617
Verify() const618 bool DISubrange::Verify() const {
619 return isSubrange() && DbgNode->getNumOperands() == 1 &&
620 getNumHeaderFields() == 3;
621 }
622
Verify() const623 bool DILexicalBlock::Verify() const {
624 return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
625 getNumHeaderFields() == 4;
626 }
627
Verify() const628 bool DILexicalBlockFile::Verify() const {
629 return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
630 getNumHeaderFields() == 2;
631 }
632
Verify() const633 bool DITemplateTypeParameter::Verify() const {
634 return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
635 getNumHeaderFields() == 4;
636 }
637
Verify() const638 bool DITemplateValueParameter::Verify() const {
639 return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
640 getNumHeaderFields() == 4;
641 }
642
Verify() const643 bool DIImportedEntity::Verify() const {
644 return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
645 getNumHeaderFields() == 3;
646 }
647
getObjCProperty() const648 MDNode *DIDerivedType::getObjCProperty() const {
649 return getNodeField(DbgNode, 4);
650 }
651
getIdentifier() const652 MDString *DICompositeType::getIdentifier() const {
653 return cast_or_null<MDString>(getField(DbgNode, 7));
654 }
655
656 #ifndef NDEBUG
VerifySubsetOf(const MDNode * LHS,const MDNode * RHS)657 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
658 for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
659 // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
660 if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
661 continue;
662 const MDNode *E = cast<MDNode>(LHS->getOperand(i));
663 bool found = false;
664 for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
665 found = (E == cast<MDNode>(RHS->getOperand(j)));
666 assert(found && "Losing a member during member list replacement");
667 }
668 }
669 #endif
670
setArraysHelper(MDNode * Elements,MDNode * TParams)671 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
672 TrackingMDNodeRef N(*this);
673 if (Elements) {
674 #ifndef NDEBUG
675 // Check that the new list of members contains all the old members as well.
676 if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
677 VerifySubsetOf(El, Elements);
678 #endif
679 N->replaceOperandWith(4, Elements);
680 }
681 if (TParams)
682 N->replaceOperandWith(6, TParams);
683 DbgNode = N;
684 }
685
getRef() const686 DIScopeRef DIScope::getRef() const {
687 if (!isCompositeType())
688 return DIScopeRef(*this);
689 DICompositeType DTy(DbgNode);
690 if (!DTy.getIdentifier())
691 return DIScopeRef(*this);
692 return DIScopeRef(DTy.getIdentifier());
693 }
694
setContainingType(DICompositeType ContainingType)695 void DICompositeType::setContainingType(DICompositeType ContainingType) {
696 TrackingMDNodeRef N(*this);
697 N->replaceOperandWith(5, ContainingType.getRef());
698 DbgNode = N;
699 }
700
isInlinedFnArgument(const Function * CurFn)701 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
702 assert(CurFn && "Invalid function");
703 if (!getContext().isSubprogram())
704 return false;
705 // This variable is not inlined function argument if its scope
706 // does not describe current function.
707 return !DISubprogram(getContext()).describes(CurFn);
708 }
709
describes(const Function * F)710 bool DISubprogram::describes(const Function *F) {
711 assert(F && "Invalid function");
712 if (F == getFunction())
713 return true;
714 StringRef Name = getLinkageName();
715 if (Name.empty())
716 Name = getName();
717 if (F->getName() == Name)
718 return true;
719 return false;
720 }
721
getVariablesNodes() const722 MDNode *DISubprogram::getVariablesNodes() const {
723 return getNodeField(DbgNode, 8);
724 }
725
getVariables() const726 DIArray DISubprogram::getVariables() const {
727 return DIArray(getNodeField(DbgNode, 8));
728 }
729
getValue() const730 Metadata *DITemplateValueParameter::getValue() const {
731 return DbgNode->getOperand(3);
732 }
733
getContext() const734 DIScopeRef DIScope::getContext() const {
735
736 if (isType())
737 return DIType(DbgNode).getContext();
738
739 if (isSubprogram())
740 return DIScopeRef(DISubprogram(DbgNode).getContext());
741
742 if (isLexicalBlock())
743 return DIScopeRef(DILexicalBlock(DbgNode).getContext());
744
745 if (isLexicalBlockFile())
746 return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
747
748 if (isNameSpace())
749 return DIScopeRef(DINameSpace(DbgNode).getContext());
750
751 assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
752 return DIScopeRef(nullptr);
753 }
754
getName() const755 StringRef DIScope::getName() const {
756 if (isType())
757 return DIType(DbgNode).getName();
758 if (isSubprogram())
759 return DISubprogram(DbgNode).getName();
760 if (isNameSpace())
761 return DINameSpace(DbgNode).getName();
762 assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
763 isCompileUnit()) &&
764 "Unhandled type of scope.");
765 return StringRef();
766 }
767
getFilename() const768 StringRef DIScope::getFilename() const {
769 if (!DbgNode)
770 return StringRef();
771 return ::getStringField(getNodeField(DbgNode, 1), 0);
772 }
773
getDirectory() const774 StringRef DIScope::getDirectory() const {
775 if (!DbgNode)
776 return StringRef();
777 return ::getStringField(getNodeField(DbgNode, 1), 1);
778 }
779
getEnumTypes() const780 DIArray DICompileUnit::getEnumTypes() const {
781 if (!DbgNode || DbgNode->getNumOperands() < 7)
782 return DIArray();
783
784 return DIArray(getNodeField(DbgNode, 2));
785 }
786
getRetainedTypes() const787 DIArray DICompileUnit::getRetainedTypes() const {
788 if (!DbgNode || DbgNode->getNumOperands() < 7)
789 return DIArray();
790
791 return DIArray(getNodeField(DbgNode, 3));
792 }
793
getSubprograms() const794 DIArray DICompileUnit::getSubprograms() const {
795 if (!DbgNode || DbgNode->getNumOperands() < 7)
796 return DIArray();
797
798 return DIArray(getNodeField(DbgNode, 4));
799 }
800
getGlobalVariables() const801 DIArray DICompileUnit::getGlobalVariables() const {
802 if (!DbgNode || DbgNode->getNumOperands() < 7)
803 return DIArray();
804
805 return DIArray(getNodeField(DbgNode, 5));
806 }
807
getImportedEntities() const808 DIArray DICompileUnit::getImportedEntities() const {
809 if (!DbgNode || DbgNode->getNumOperands() < 7)
810 return DIArray();
811
812 return DIArray(getNodeField(DbgNode, 6));
813 }
814
replaceSubprograms(DIArray Subprograms)815 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
816 assert(Verify() && "Expected compile unit");
817 if (Subprograms == getSubprograms())
818 return;
819
820 const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
821 }
822
replaceGlobalVariables(DIArray GlobalVariables)823 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
824 assert(Verify() && "Expected compile unit");
825 if (GlobalVariables == getGlobalVariables())
826 return;
827
828 const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
829 }
830
copyWithNewScope(LLVMContext & Ctx,DILexicalBlockFile NewScope)831 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
832 DILexicalBlockFile NewScope) {
833 assert(Verify());
834 assert(NewScope && "Expected valid scope");
835
836 const auto *Old = cast<MDLocation>(DbgNode);
837 return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
838 NewScope, Old->getInlinedAt()));
839 }
840
computeNewDiscriminator(LLVMContext & Ctx)841 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
842 std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
843 return ++Ctx.pImpl->DiscriminatorTable[Key];
844 }
845
createInlinedVariable(MDNode * DV,MDNode * InlinedScope,LLVMContext & VMContext)846 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
847 LLVMContext &VMContext) {
848 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
849 if (!InlinedScope)
850 return cleanseInlinedVariable(DV, VMContext);
851
852 // Insert inlined scope.
853 SmallVector<Metadata *, 8> Elts;
854 for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
855 Elts.push_back(DV->getOperand(I));
856 Elts.push_back(InlinedScope);
857
858 DIVariable Inlined(MDNode::get(VMContext, Elts));
859 assert(Inlined.Verify() && "Expected to create a DIVariable");
860 return Inlined;
861 }
862
cleanseInlinedVariable(MDNode * DV,LLVMContext & VMContext)863 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
864 assert(DIVariable(DV).Verify() && "Expected a DIVariable");
865 if (!DIVariable(DV).getInlinedAt())
866 return DIVariable(DV);
867
868 // Remove inlined scope.
869 SmallVector<Metadata *, 8> Elts;
870 for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
871 Elts.push_back(DV->getOperand(I));
872
873 DIVariable Cleansed(MDNode::get(VMContext, Elts));
874 assert(Cleansed.Verify() && "Expected to create a DIVariable");
875 return Cleansed;
876 }
877
getDISubprogram(const MDNode * Scope)878 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
879 DIDescriptor D(Scope);
880 if (D.isSubprogram())
881 return DISubprogram(Scope);
882
883 if (D.isLexicalBlockFile())
884 return getDISubprogram(DILexicalBlockFile(Scope).getContext());
885
886 if (D.isLexicalBlock())
887 return getDISubprogram(DILexicalBlock(Scope).getContext());
888
889 return DISubprogram();
890 }
891
getDISubprogram(const Function * F)892 DISubprogram llvm::getDISubprogram(const Function *F) {
893 // We look for the first instr that has a debug annotation leading back to F.
894 for (auto &BB : *F) {
895 auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
896 return !Inst.getDebugLoc().isUnknown();
897 });
898 if (Inst == BB.end())
899 continue;
900 DebugLoc DLoc = Inst->getDebugLoc();
901 const MDNode *Scope = DLoc.getScopeNode();
902 DISubprogram Subprogram = getDISubprogram(Scope);
903 return Subprogram.describes(F) ? Subprogram : DISubprogram();
904 }
905
906 return DISubprogram();
907 }
908
getDICompositeType(DIType T)909 DICompositeType llvm::getDICompositeType(DIType T) {
910 if (T.isCompositeType())
911 return DICompositeType(T);
912
913 if (T.isDerivedType()) {
914 // This function is currently used by dragonegg and dragonegg does
915 // not generate identifier for types, so using an empty map to resolve
916 // DerivedFrom should be fine.
917 DITypeIdentifierMap EmptyMap;
918 return getDICompositeType(
919 DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
920 }
921
922 return DICompositeType();
923 }
924
925 DITypeIdentifierMap
generateDITypeIdentifierMap(const NamedMDNode * CU_Nodes)926 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
927 DITypeIdentifierMap Map;
928 for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
929 DICompileUnit CU(CU_Nodes->getOperand(CUi));
930 DIArray Retain = CU.getRetainedTypes();
931 for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
932 if (!Retain.getElement(Ti).isCompositeType())
933 continue;
934 DICompositeType Ty(Retain.getElement(Ti));
935 if (MDString *TypeId = Ty.getIdentifier()) {
936 // Definition has priority over declaration.
937 // Try to insert (TypeId, Ty) to Map.
938 std::pair<DITypeIdentifierMap::iterator, bool> P =
939 Map.insert(std::make_pair(TypeId, Ty));
940 // If TypeId already exists in Map and this is a definition, replace
941 // whatever we had (declaration or definition) with the definition.
942 if (!P.second && !Ty.isForwardDecl())
943 P.first->second = Ty;
944 }
945 }
946 }
947 return Map;
948 }
949
950 //===----------------------------------------------------------------------===//
951 // DebugInfoFinder implementations.
952 //===----------------------------------------------------------------------===//
953
reset()954 void DebugInfoFinder::reset() {
955 CUs.clear();
956 SPs.clear();
957 GVs.clear();
958 TYs.clear();
959 Scopes.clear();
960 NodesSeen.clear();
961 TypeIdentifierMap.clear();
962 TypeMapInitialized = false;
963 }
964
InitializeTypeMap(const Module & M)965 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
966 if (!TypeMapInitialized)
967 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
968 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
969 TypeMapInitialized = true;
970 }
971 }
972
processModule(const Module & M)973 void DebugInfoFinder::processModule(const Module &M) {
974 InitializeTypeMap(M);
975 if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
976 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
977 DICompileUnit CU(CU_Nodes->getOperand(i));
978 addCompileUnit(CU);
979 DIArray GVs = CU.getGlobalVariables();
980 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
981 DIGlobalVariable DIG(GVs.getElement(i));
982 if (addGlobalVariable(DIG)) {
983 processScope(DIG.getContext());
984 processType(DIG.getType().resolve(TypeIdentifierMap));
985 }
986 }
987 DIArray SPs = CU.getSubprograms();
988 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
989 processSubprogram(DISubprogram(SPs.getElement(i)));
990 DIArray EnumTypes = CU.getEnumTypes();
991 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
992 processType(DIType(EnumTypes.getElement(i)));
993 DIArray RetainedTypes = CU.getRetainedTypes();
994 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
995 processType(DIType(RetainedTypes.getElement(i)));
996 DIArray Imports = CU.getImportedEntities();
997 for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
998 DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
999 DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1000 if (Entity.isType())
1001 processType(DIType(Entity));
1002 else if (Entity.isSubprogram())
1003 processSubprogram(DISubprogram(Entity));
1004 else if (Entity.isNameSpace())
1005 processScope(DINameSpace(Entity).getContext());
1006 }
1007 }
1008 }
1009 }
1010
processLocation(const Module & M,DILocation Loc)1011 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1012 if (!Loc)
1013 return;
1014 InitializeTypeMap(M);
1015 processScope(Loc.getScope());
1016 processLocation(M, Loc.getOrigLocation());
1017 }
1018
processType(DIType DT)1019 void DebugInfoFinder::processType(DIType DT) {
1020 if (!addType(DT))
1021 return;
1022 processScope(DT.getContext().resolve(TypeIdentifierMap));
1023 if (DT.isCompositeType()) {
1024 DICompositeType DCT(DT);
1025 processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1026 if (DT.isSubroutineType()) {
1027 DITypeArray DTA = DISubroutineType(DT).getTypeArray();
1028 for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
1029 processType(DTA.getElement(i).resolve(TypeIdentifierMap));
1030 return;
1031 }
1032 DIArray DA = DCT.getElements();
1033 for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1034 DIDescriptor D = DA.getElement(i);
1035 if (D.isType())
1036 processType(DIType(D));
1037 else if (D.isSubprogram())
1038 processSubprogram(DISubprogram(D));
1039 }
1040 } else if (DT.isDerivedType()) {
1041 DIDerivedType DDT(DT);
1042 processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1043 }
1044 }
1045
processScope(DIScope Scope)1046 void DebugInfoFinder::processScope(DIScope Scope) {
1047 if (Scope.isType()) {
1048 DIType Ty(Scope);
1049 processType(Ty);
1050 return;
1051 }
1052 if (Scope.isCompileUnit()) {
1053 addCompileUnit(DICompileUnit(Scope));
1054 return;
1055 }
1056 if (Scope.isSubprogram()) {
1057 processSubprogram(DISubprogram(Scope));
1058 return;
1059 }
1060 if (!addScope(Scope))
1061 return;
1062 if (Scope.isLexicalBlock()) {
1063 DILexicalBlock LB(Scope);
1064 processScope(LB.getContext());
1065 } else if (Scope.isLexicalBlockFile()) {
1066 DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1067 processScope(LBF.getScope());
1068 } else if (Scope.isNameSpace()) {
1069 DINameSpace NS(Scope);
1070 processScope(NS.getContext());
1071 }
1072 }
1073
processSubprogram(DISubprogram SP)1074 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1075 if (!addSubprogram(SP))
1076 return;
1077 processScope(SP.getContext().resolve(TypeIdentifierMap));
1078 processType(SP.getType());
1079 DIArray TParams = SP.getTemplateParams();
1080 for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1081 DIDescriptor Element = TParams.getElement(I);
1082 if (Element.isTemplateTypeParameter()) {
1083 DITemplateTypeParameter TType(Element);
1084 processScope(TType.getContext().resolve(TypeIdentifierMap));
1085 processType(TType.getType().resolve(TypeIdentifierMap));
1086 } else if (Element.isTemplateValueParameter()) {
1087 DITemplateValueParameter TVal(Element);
1088 processScope(TVal.getContext().resolve(TypeIdentifierMap));
1089 processType(TVal.getType().resolve(TypeIdentifierMap));
1090 }
1091 }
1092 }
1093
processDeclare(const Module & M,const DbgDeclareInst * DDI)1094 void DebugInfoFinder::processDeclare(const Module &M,
1095 const DbgDeclareInst *DDI) {
1096 MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1097 if (!N)
1098 return;
1099 InitializeTypeMap(M);
1100
1101 DIDescriptor DV(N);
1102 if (!DV.isVariable())
1103 return;
1104
1105 if (!NodesSeen.insert(DV).second)
1106 return;
1107 processScope(DIVariable(N).getContext());
1108 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1109 }
1110
processValue(const Module & M,const DbgValueInst * DVI)1111 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1112 MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1113 if (!N)
1114 return;
1115 InitializeTypeMap(M);
1116
1117 DIDescriptor DV(N);
1118 if (!DV.isVariable())
1119 return;
1120
1121 if (!NodesSeen.insert(DV).second)
1122 return;
1123 processScope(DIVariable(N).getContext());
1124 processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1125 }
1126
addType(DIType DT)1127 bool DebugInfoFinder::addType(DIType DT) {
1128 if (!DT)
1129 return false;
1130
1131 if (!NodesSeen.insert(DT).second)
1132 return false;
1133
1134 TYs.push_back(DT);
1135 return true;
1136 }
1137
addCompileUnit(DICompileUnit CU)1138 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1139 if (!CU)
1140 return false;
1141 if (!NodesSeen.insert(CU).second)
1142 return false;
1143
1144 CUs.push_back(CU);
1145 return true;
1146 }
1147
addGlobalVariable(DIGlobalVariable DIG)1148 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1149 if (!DIG)
1150 return false;
1151
1152 if (!NodesSeen.insert(DIG).second)
1153 return false;
1154
1155 GVs.push_back(DIG);
1156 return true;
1157 }
1158
addSubprogram(DISubprogram SP)1159 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1160 if (!SP)
1161 return false;
1162
1163 if (!NodesSeen.insert(SP).second)
1164 return false;
1165
1166 SPs.push_back(SP);
1167 return true;
1168 }
1169
addScope(DIScope Scope)1170 bool DebugInfoFinder::addScope(DIScope Scope) {
1171 if (!Scope)
1172 return false;
1173 // FIXME: Ocaml binding generates a scope with no content, we treat it
1174 // as null for now.
1175 if (Scope->getNumOperands() == 0)
1176 return false;
1177 if (!NodesSeen.insert(Scope).second)
1178 return false;
1179 Scopes.push_back(Scope);
1180 return true;
1181 }
1182
1183 //===----------------------------------------------------------------------===//
1184 // DIDescriptor: dump routines for all descriptors.
1185 //===----------------------------------------------------------------------===//
1186
dump() const1187 void DIDescriptor::dump() const {
1188 print(dbgs());
1189 dbgs() << '\n';
1190 }
1191
print(raw_ostream & OS) const1192 void DIDescriptor::print(raw_ostream &OS) const {
1193 if (!DbgNode)
1194 return;
1195
1196 if (const char *Tag = dwarf::TagString(getTag()))
1197 OS << "[ " << Tag << " ]";
1198
1199 if (this->isSubrange()) {
1200 DISubrange(DbgNode).printInternal(OS);
1201 } else if (this->isCompileUnit()) {
1202 DICompileUnit(DbgNode).printInternal(OS);
1203 } else if (this->isFile()) {
1204 DIFile(DbgNode).printInternal(OS);
1205 } else if (this->isEnumerator()) {
1206 DIEnumerator(DbgNode).printInternal(OS);
1207 } else if (this->isBasicType()) {
1208 DIType(DbgNode).printInternal(OS);
1209 } else if (this->isDerivedType()) {
1210 DIDerivedType(DbgNode).printInternal(OS);
1211 } else if (this->isCompositeType()) {
1212 DICompositeType(DbgNode).printInternal(OS);
1213 } else if (this->isSubprogram()) {
1214 DISubprogram(DbgNode).printInternal(OS);
1215 } else if (this->isGlobalVariable()) {
1216 DIGlobalVariable(DbgNode).printInternal(OS);
1217 } else if (this->isVariable()) {
1218 DIVariable(DbgNode).printInternal(OS);
1219 } else if (this->isObjCProperty()) {
1220 DIObjCProperty(DbgNode).printInternal(OS);
1221 } else if (this->isNameSpace()) {
1222 DINameSpace(DbgNode).printInternal(OS);
1223 } else if (this->isScope()) {
1224 DIScope(DbgNode).printInternal(OS);
1225 } else if (this->isExpression()) {
1226 DIExpression(DbgNode).printInternal(OS);
1227 }
1228 }
1229
printInternal(raw_ostream & OS) const1230 void DISubrange::printInternal(raw_ostream &OS) const {
1231 int64_t Count = getCount();
1232 if (Count != -1)
1233 OS << " [" << getLo() << ", " << Count - 1 << ']';
1234 else
1235 OS << " [unbounded]";
1236 }
1237
printInternal(raw_ostream & OS) const1238 void DIScope::printInternal(raw_ostream &OS) const {
1239 OS << " [" << getDirectory() << "/" << getFilename() << ']';
1240 }
1241
printInternal(raw_ostream & OS) const1242 void DICompileUnit::printInternal(raw_ostream &OS) const {
1243 DIScope::printInternal(OS);
1244 OS << " [";
1245 unsigned Lang = getLanguage();
1246 if (const char *LangStr = dwarf::LanguageString(Lang))
1247 OS << LangStr;
1248 else
1249 (OS << "lang 0x").write_hex(Lang);
1250 OS << ']';
1251 }
1252
printInternal(raw_ostream & OS) const1253 void DIEnumerator::printInternal(raw_ostream &OS) const {
1254 OS << " [" << getName() << " :: " << getEnumValue() << ']';
1255 }
1256
printInternal(raw_ostream & OS) const1257 void DIType::printInternal(raw_ostream &OS) const {
1258 if (!DbgNode)
1259 return;
1260
1261 StringRef Res = getName();
1262 if (!Res.empty())
1263 OS << " [" << Res << "]";
1264
1265 // TODO: Print context?
1266
1267 OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1268 << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1269 if (isBasicType())
1270 if (const char *Enc =
1271 dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1272 OS << ", enc " << Enc;
1273 OS << "]";
1274
1275 if (isPrivate())
1276 OS << " [private]";
1277 else if (isProtected())
1278 OS << " [protected]";
1279 else if (isPublic())
1280 OS << " [public]";
1281
1282 if (isArtificial())
1283 OS << " [artificial]";
1284
1285 if (isForwardDecl())
1286 OS << " [decl]";
1287 else if (getTag() == dwarf::DW_TAG_structure_type ||
1288 getTag() == dwarf::DW_TAG_union_type ||
1289 getTag() == dwarf::DW_TAG_enumeration_type ||
1290 getTag() == dwarf::DW_TAG_class_type)
1291 OS << " [def]";
1292 if (isVector())
1293 OS << " [vector]";
1294 if (isStaticMember())
1295 OS << " [static]";
1296
1297 if (isLValueReference())
1298 OS << " [reference]";
1299
1300 if (isRValueReference())
1301 OS << " [rvalue reference]";
1302 }
1303
printInternal(raw_ostream & OS) const1304 void DIDerivedType::printInternal(raw_ostream &OS) const {
1305 DIType::printInternal(OS);
1306 OS << " [from " << getTypeDerivedFrom().getName() << ']';
1307 }
1308
printInternal(raw_ostream & OS) const1309 void DICompositeType::printInternal(raw_ostream &OS) const {
1310 DIType::printInternal(OS);
1311 DIArray A = getElements();
1312 OS << " [" << A.getNumElements() << " elements]";
1313 }
1314
printInternal(raw_ostream & OS) const1315 void DINameSpace::printInternal(raw_ostream &OS) const {
1316 StringRef Name = getName();
1317 if (!Name.empty())
1318 OS << " [" << Name << ']';
1319
1320 OS << " [line " << getLineNumber() << ']';
1321 }
1322
printInternal(raw_ostream & OS) const1323 void DISubprogram::printInternal(raw_ostream &OS) const {
1324 // TODO : Print context
1325 OS << " [line " << getLineNumber() << ']';
1326
1327 if (isLocalToUnit())
1328 OS << " [local]";
1329
1330 if (isDefinition())
1331 OS << " [def]";
1332
1333 if (getScopeLineNumber() != getLineNumber())
1334 OS << " [scope " << getScopeLineNumber() << "]";
1335
1336 if (isPrivate())
1337 OS << " [private]";
1338 else if (isProtected())
1339 OS << " [protected]";
1340 else if (isPublic())
1341 OS << " [public]";
1342
1343 if (isLValueReference())
1344 OS << " [reference]";
1345
1346 if (isRValueReference())
1347 OS << " [rvalue reference]";
1348
1349 StringRef Res = getName();
1350 if (!Res.empty())
1351 OS << " [" << Res << ']';
1352 }
1353
printInternal(raw_ostream & OS) const1354 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1355 StringRef Res = getName();
1356 if (!Res.empty())
1357 OS << " [" << Res << ']';
1358
1359 OS << " [line " << getLineNumber() << ']';
1360
1361 // TODO : Print context
1362
1363 if (isLocalToUnit())
1364 OS << " [local]";
1365
1366 if (isDefinition())
1367 OS << " [def]";
1368 }
1369
printInternal(raw_ostream & OS) const1370 void DIVariable::printInternal(raw_ostream &OS) const {
1371 StringRef Res = getName();
1372 if (!Res.empty())
1373 OS << " [" << Res << ']';
1374
1375 OS << " [line " << getLineNumber() << ']';
1376 }
1377
printInternal(raw_ostream & OS) const1378 void DIExpression::printInternal(raw_ostream &OS) const {
1379 for (unsigned I = 0; I < getNumElements(); ++I) {
1380 uint64_t OpCode = getElement(I);
1381 OS << " [" << OperationEncodingString(OpCode);
1382 switch (OpCode) {
1383 case DW_OP_plus: {
1384 OS << " " << getElement(++I);
1385 break;
1386 }
1387 case DW_OP_piece: {
1388 unsigned Offset = getElement(++I);
1389 unsigned Size = getElement(++I);
1390 OS << " offset=" << Offset << ", size=" << Size;
1391 break;
1392 }
1393 case DW_OP_deref:
1394 // No arguments.
1395 break;
1396 default:
1397 // Else bail out early. This may be a line table entry.
1398 OS << "Unknown]";
1399 return;
1400 }
1401 OS << "]";
1402 }
1403 }
1404
printInternal(raw_ostream & OS) const1405 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1406 StringRef Name = getObjCPropertyName();
1407 if (!Name.empty())
1408 OS << " [" << Name << ']';
1409
1410 OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1411 << ']';
1412 }
1413
printDebugLoc(DebugLoc DL,raw_ostream & CommentOS,const LLVMContext & Ctx)1414 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1415 const LLVMContext &Ctx) {
1416 if (!DL.isUnknown()) { // Print source line info.
1417 DIScope Scope(DL.getScope(Ctx));
1418 assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1419 // Omit the directory, because it's likely to be long and uninteresting.
1420 CommentOS << Scope.getFilename();
1421 CommentOS << ':' << DL.getLine();
1422 if (DL.getCol() != 0)
1423 CommentOS << ':' << DL.getCol();
1424 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1425 if (!InlinedAtDL.isUnknown()) {
1426 CommentOS << " @[ ";
1427 printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1428 CommentOS << " ]";
1429 }
1430 }
1431 }
1432
printExtendedName(raw_ostream & OS) const1433 void DIVariable::printExtendedName(raw_ostream &OS) const {
1434 const LLVMContext &Ctx = DbgNode->getContext();
1435 StringRef Res = getName();
1436 if (!Res.empty())
1437 OS << Res << "," << getLineNumber();
1438 if (MDNode *InlinedAt = getInlinedAt()) {
1439 DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1440 if (!InlinedAtDL.isUnknown()) {
1441 OS << " @[";
1442 printDebugLoc(InlinedAtDL, OS, Ctx);
1443 OS << "]";
1444 }
1445 }
1446 }
1447
DIRef(const Metadata * V)1448 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
1449 assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1450 }
DIRef(const Metadata * V)1451 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
1452 assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1453 }
1454
1455 template <>
getFieldAs(unsigned Elt) const1456 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1457 return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1458 }
getFieldAs(unsigned Elt) const1459 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1460 return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
1461 }
1462
StripDebugInfo(Module & M)1463 bool llvm::StripDebugInfo(Module &M) {
1464 bool Changed = false;
1465
1466 // Remove all of the calls to the debugger intrinsics, and remove them from
1467 // the module.
1468 if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1469 while (!Declare->use_empty()) {
1470 CallInst *CI = cast<CallInst>(Declare->user_back());
1471 CI->eraseFromParent();
1472 }
1473 Declare->eraseFromParent();
1474 Changed = true;
1475 }
1476
1477 if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1478 while (!DbgVal->use_empty()) {
1479 CallInst *CI = cast<CallInst>(DbgVal->user_back());
1480 CI->eraseFromParent();
1481 }
1482 DbgVal->eraseFromParent();
1483 Changed = true;
1484 }
1485
1486 for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1487 NME = M.named_metadata_end(); NMI != NME;) {
1488 NamedMDNode *NMD = NMI;
1489 ++NMI;
1490 if (NMD->getName().startswith("llvm.dbg.")) {
1491 NMD->eraseFromParent();
1492 Changed = true;
1493 }
1494 }
1495
1496 for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1497 for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1498 ++FI)
1499 for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1500 ++BI) {
1501 if (!BI->getDebugLoc().isUnknown()) {
1502 Changed = true;
1503 BI->setDebugLoc(DebugLoc());
1504 }
1505 }
1506
1507 return Changed;
1508 }
1509
getDebugMetadataVersionFromModule(const Module & M)1510 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1511 if (auto *Val = mdconst::extract_or_null<ConstantInt>(
1512 M.getModuleFlag("Debug Info Version")))
1513 return Val->getZExtValue();
1514 return 0;
1515 }
1516
1517 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
makeSubprogramMap(const Module & M)1518 llvm::makeSubprogramMap(const Module &M) {
1519 DenseMap<const Function *, DISubprogram> R;
1520
1521 NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1522 if (!CU_Nodes)
1523 return R;
1524
1525 for (MDNode *N : CU_Nodes->operands()) {
1526 DICompileUnit CUNode(N);
1527 DIArray SPs = CUNode.getSubprograms();
1528 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1529 DISubprogram SP(SPs.getElement(i));
1530 if (Function *F = SP.getFunction())
1531 R.insert(std::make_pair(F, SP));
1532 }
1533 }
1534 return R;
1535 }
1536