• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/DerivedTypes.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/ValueHandle.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Dwarf.h"
30 #include "llvm/Support/raw_ostream.h"
31 using namespace llvm;
32 using namespace llvm::dwarf;
33 
34 //===----------------------------------------------------------------------===//
35 // DIDescriptor
36 //===----------------------------------------------------------------------===//
37 
Verify() const38 bool DIDescriptor::Verify() const {
39   return DbgNode &&
40          (DIDerivedType(DbgNode).Verify() ||
41           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
42           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
43           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
44           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
45           DILexicalBlock(DbgNode).Verify() ||
46           DILexicalBlockFile(DbgNode).Verify() ||
47           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
48           DIObjCProperty(DbgNode).Verify() ||
49           DIUnspecifiedParameter(DbgNode).Verify() ||
50           DITemplateTypeParameter(DbgNode).Verify() ||
51           DITemplateValueParameter(DbgNode).Verify() ||
52           DIImportedEntity(DbgNode).Verify());
53 }
54 
getField(const MDNode * DbgNode,unsigned Elt)55 static Value *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 (!DbgNode)
77     return 0;
78 
79   if (Elt < DbgNode->getNumOperands())
80     if (ConstantInt *CI =
81             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
82       return CI->getZExtValue();
83 
84   return 0;
85 }
86 
getInt64Field(unsigned Elt) const87 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
88   if (!DbgNode)
89     return 0;
90 
91   if (Elt < DbgNode->getNumOperands())
92     if (ConstantInt *CI =
93             dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
94       return CI->getSExtValue();
95 
96   return 0;
97 }
98 
getDescriptorField(unsigned Elt) const99 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
100   MDNode *Field = getNodeField(DbgNode, Elt);
101   return DIDescriptor(Field);
102 }
103 
getGlobalVariableField(unsigned Elt) const104 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
105   if (!DbgNode)
106     return nullptr;
107 
108   if (Elt < DbgNode->getNumOperands())
109     return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
110   return nullptr;
111 }
112 
getConstantField(unsigned Elt) const113 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
114   if (!DbgNode)
115     return nullptr;
116 
117   if (Elt < DbgNode->getNumOperands())
118     return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
119   return nullptr;
120 }
121 
getFunctionField(unsigned Elt) const122 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
123   if (!DbgNode)
124     return nullptr;
125 
126   if (Elt < DbgNode->getNumOperands())
127     return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
128   return nullptr;
129 }
130 
replaceFunctionField(unsigned Elt,Function * F)131 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
132   if (!DbgNode)
133     return;
134 
135   if (Elt < DbgNode->getNumOperands()) {
136     MDNode *Node = const_cast<MDNode *>(DbgNode);
137     Node->replaceOperandWith(Elt, F);
138   }
139 }
140 
getAddrElement(unsigned Idx) const141 uint64_t DIVariable::getAddrElement(unsigned Idx) const {
142   DIDescriptor ComplexExpr = getDescriptorField(8);
143   if (Idx < ComplexExpr->getNumOperands())
144     if (auto *CI = dyn_cast_or_null<ConstantInt>(ComplexExpr->getOperand(Idx)))
145       return CI->getZExtValue();
146 
147   assert(false && "non-existing complex address element requested");
148   return 0;
149 }
150 
151 /// getInlinedAt - If this variable is inlined then return inline location.
getInlinedAt() const152 MDNode *DIVariable::getInlinedAt() const { return getNodeField(DbgNode, 7); }
153 
154 //===----------------------------------------------------------------------===//
155 // Predicates
156 //===----------------------------------------------------------------------===//
157 
158 /// isBasicType - Return true if the specified tag is legal for
159 /// DIBasicType.
isBasicType() const160 bool DIDescriptor::isBasicType() const {
161   if (!DbgNode)
162     return false;
163   switch (getTag()) {
164   case dwarf::DW_TAG_base_type:
165   case dwarf::DW_TAG_unspecified_type:
166     return true;
167   default:
168     return false;
169   }
170 }
171 
172 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
isDerivedType() const173 bool DIDescriptor::isDerivedType() const {
174   if (!DbgNode)
175     return false;
176   switch (getTag()) {
177   case dwarf::DW_TAG_typedef:
178   case dwarf::DW_TAG_pointer_type:
179   case dwarf::DW_TAG_ptr_to_member_type:
180   case dwarf::DW_TAG_reference_type:
181   case dwarf::DW_TAG_rvalue_reference_type:
182   case dwarf::DW_TAG_const_type:
183   case dwarf::DW_TAG_volatile_type:
184   case dwarf::DW_TAG_restrict_type:
185   case dwarf::DW_TAG_member:
186   case dwarf::DW_TAG_inheritance:
187   case dwarf::DW_TAG_friend:
188     return true;
189   default:
190     // CompositeTypes are currently modelled as DerivedTypes.
191     return isCompositeType();
192   }
193 }
194 
195 /// isCompositeType - Return true if the specified tag is legal for
196 /// DICompositeType.
isCompositeType() const197 bool DIDescriptor::isCompositeType() const {
198   if (!DbgNode)
199     return false;
200   switch (getTag()) {
201   case dwarf::DW_TAG_array_type:
202   case dwarf::DW_TAG_structure_type:
203   case dwarf::DW_TAG_union_type:
204   case dwarf::DW_TAG_enumeration_type:
205   case dwarf::DW_TAG_subroutine_type:
206   case dwarf::DW_TAG_class_type:
207     return true;
208   default:
209     return false;
210   }
211 }
212 
213 /// isVariable - Return true if the specified tag is legal for DIVariable.
isVariable() const214 bool DIDescriptor::isVariable() const {
215   if (!DbgNode)
216     return false;
217   switch (getTag()) {
218   case dwarf::DW_TAG_auto_variable:
219   case dwarf::DW_TAG_arg_variable:
220     return true;
221   default:
222     return false;
223   }
224 }
225 
226 /// isType - Return true if the specified tag is legal for DIType.
isType() const227 bool DIDescriptor::isType() const {
228   return isBasicType() || isCompositeType() || isDerivedType();
229 }
230 
231 /// isSubprogram - Return true if the specified tag is legal for
232 /// DISubprogram.
isSubprogram() const233 bool DIDescriptor::isSubprogram() const {
234   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
235 }
236 
237 /// isGlobalVariable - Return true if the specified tag is legal for
238 /// DIGlobalVariable.
isGlobalVariable() const239 bool DIDescriptor::isGlobalVariable() const {
240   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
241                      getTag() == dwarf::DW_TAG_constant);
242 }
243 
244 /// isUnspecifiedParmeter - Return true if the specified tag is
245 /// DW_TAG_unspecified_parameters.
isUnspecifiedParameter() const246 bool DIDescriptor::isUnspecifiedParameter() const {
247   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
248 }
249 
250 /// isScope - Return true if the specified tag is one of the scope
251 /// related tag.
isScope() const252 bool DIDescriptor::isScope() const {
253   if (!DbgNode)
254     return false;
255   switch (getTag()) {
256   case dwarf::DW_TAG_compile_unit:
257   case dwarf::DW_TAG_lexical_block:
258   case dwarf::DW_TAG_subprogram:
259   case dwarf::DW_TAG_namespace:
260   case dwarf::DW_TAG_file_type:
261     return true;
262   default:
263     break;
264   }
265   return isType();
266 }
267 
268 /// isTemplateTypeParameter - Return true if the specified tag is
269 /// DW_TAG_template_type_parameter.
isTemplateTypeParameter() const270 bool DIDescriptor::isTemplateTypeParameter() const {
271   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
272 }
273 
274 /// isTemplateValueParameter - Return true if the specified tag is
275 /// DW_TAG_template_value_parameter.
isTemplateValueParameter() const276 bool DIDescriptor::isTemplateValueParameter() const {
277   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
278                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
279                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
280 }
281 
282 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
isCompileUnit() const283 bool DIDescriptor::isCompileUnit() const {
284   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
285 }
286 
287 /// isFile - Return true if the specified tag is DW_TAG_file_type.
isFile() const288 bool DIDescriptor::isFile() const {
289   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
290 }
291 
292 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
isNameSpace() const293 bool DIDescriptor::isNameSpace() const {
294   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
295 }
296 
297 /// isLexicalBlockFile - Return true if the specified descriptor is a
298 /// lexical block with an extra file.
isLexicalBlockFile() const299 bool DIDescriptor::isLexicalBlockFile() const {
300   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
301          (DbgNode->getNumOperands() == 3);
302 }
303 
304 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
isLexicalBlock() const305 bool DIDescriptor::isLexicalBlock() const {
306   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
307          (DbgNode->getNumOperands() > 3);
308 }
309 
310 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
isSubrange() const311 bool DIDescriptor::isSubrange() const {
312   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
313 }
314 
315 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
isEnumerator() const316 bool DIDescriptor::isEnumerator() const {
317   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
318 }
319 
320 /// isObjCProperty - Return true if the specified tag is DW_TAG_APPLE_property.
isObjCProperty() const321 bool DIDescriptor::isObjCProperty() const {
322   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
323 }
324 
325 /// \brief Return true if the specified tag is DW_TAG_imported_module or
326 /// DW_TAG_imported_declaration.
isImportedEntity() const327 bool DIDescriptor::isImportedEntity() const {
328   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
329                      getTag() == dwarf::DW_TAG_imported_declaration);
330 }
331 
332 //===----------------------------------------------------------------------===//
333 // Simple Descriptor Constructors and other Methods
334 //===----------------------------------------------------------------------===//
335 
getNumElements() const336 unsigned DIArray::getNumElements() const {
337   if (!DbgNode)
338     return 0;
339   return DbgNode->getNumOperands();
340 }
341 
342 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
343 /// type with the one in the passed descriptor.
replaceAllUsesWith(LLVMContext & VMContext,DIDescriptor D)344 void DIType::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
345 
346   assert(DbgNode && "Trying to replace an unverified type!");
347 
348   // Since we use a TrackingVH for the node, its easy for clients to manufacture
349   // legitimate situations where they want to replaceAllUsesWith() on something
350   // which, due to uniquing, has merged with the source. We shield clients from
351   // this detail by allowing a value to be replaced with replaceAllUsesWith()
352   // itself.
353   const MDNode *DN = D;
354   if (DbgNode == DN) {
355     SmallVector<Value*, 10> Ops(DbgNode->getNumOperands());
356     for (size_t i = 0; i != Ops.size(); ++i)
357       Ops[i] = DbgNode->getOperand(i);
358     DN = MDNode::get(VMContext, Ops);
359   }
360 
361   MDNode *Node = const_cast<MDNode *>(DbgNode);
362   const Value *V = cast_or_null<Value>(DN);
363   Node->replaceAllUsesWith(const_cast<Value *>(V));
364   MDNode::deleteTemporary(Node);
365   DbgNode = D;
366 }
367 
368 /// replaceAllUsesWith - Replace all uses of the MDNode used by this
369 /// type with the one in D.
replaceAllUsesWith(MDNode * D)370 void DIType::replaceAllUsesWith(MDNode *D) {
371 
372   assert(DbgNode && "Trying to replace an unverified type!");
373   assert(DbgNode != D && "This replacement should always happen");
374   MDNode *Node = const_cast<MDNode *>(DbgNode);
375   const MDNode *DN = D;
376   const Value *V = cast_or_null<Value>(DN);
377   Node->replaceAllUsesWith(const_cast<Value *>(V));
378   MDNode::deleteTemporary(Node);
379 }
380 
381 /// Verify - Verify that a compile unit is well formed.
Verify() const382 bool DICompileUnit::Verify() const {
383   if (!isCompileUnit())
384     return false;
385 
386   // Don't bother verifying the compilation directory or producer string
387   // as those could be empty.
388   if (getFilename().empty())
389     return false;
390 
391   return DbgNode->getNumOperands() == 14;
392 }
393 
394 /// Verify - Verify that an ObjC property is well formed.
Verify() const395 bool DIObjCProperty::Verify() const {
396   if (!isObjCProperty())
397     return false;
398 
399   // Don't worry about the rest of the strings for now.
400   return DbgNode->getNumOperands() == 8;
401 }
402 
403 /// Check if a field at position Elt of a MDNode is a MDNode.
404 /// We currently allow an empty string and an integer.
405 /// But we don't allow a non-empty string in a MDNode field.
fieldIsMDNode(const MDNode * DbgNode,unsigned Elt)406 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
407   // FIXME: This function should return true, if the field is null or the field
408   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
409   Value *Fld = getField(DbgNode, Elt);
410   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
411     return false;
412   return true;
413 }
414 
415 /// Check if a field at position Elt of a MDNode is a MDString.
fieldIsMDString(const MDNode * DbgNode,unsigned Elt)416 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
417   Value *Fld = getField(DbgNode, Elt);
418   return !Fld || isa<MDString>(Fld);
419 }
420 
421 /// Check if a value can be a reference to a type.
isTypeRef(const Value * Val)422 static bool isTypeRef(const Value *Val) {
423   return !Val ||
424          (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
425          (isa<MDNode>(Val) && DIType(cast<MDNode>(Val)).isType());
426 }
427 
428 /// Check if a field at position Elt of a MDNode can be a reference to a type.
fieldIsTypeRef(const MDNode * DbgNode,unsigned Elt)429 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
430   Value *Fld = getField(DbgNode, Elt);
431   return isTypeRef(Fld);
432 }
433 
434 /// Check if a value can be a ScopeRef.
isScopeRef(const Value * Val)435 static bool isScopeRef(const Value *Val) {
436   return !Val ||
437     (isa<MDString>(Val) && !cast<MDString>(Val)->getString().empty()) ||
438     // Not checking for Val->isScope() here, because it would work
439     // only for lexical scopes and not all subclasses of DIScope.
440     isa<MDNode>(Val);
441 }
442 
443 /// Check if a field at position Elt of a MDNode can be a ScopeRef.
fieldIsScopeRef(const MDNode * DbgNode,unsigned Elt)444 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
445   Value *Fld = getField(DbgNode, Elt);
446   return isScopeRef(Fld);
447 }
448 
449 /// Verify - Verify that a type descriptor is well formed.
Verify() const450 bool DIType::Verify() const {
451   if (!isType())
452     return false;
453   // Make sure Context @ field 2 is MDNode.
454   if (!fieldIsScopeRef(DbgNode, 2))
455     return false;
456 
457   // FIXME: Sink this into the various subclass verifies.
458   uint16_t Tag = getTag();
459   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
460       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
461       Tag != dwarf::DW_TAG_ptr_to_member_type &&
462       Tag != dwarf::DW_TAG_reference_type &&
463       Tag != dwarf::DW_TAG_rvalue_reference_type &&
464       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
465       Tag != dwarf::DW_TAG_enumeration_type &&
466       Tag != dwarf::DW_TAG_subroutine_type &&
467       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
468       getFilename().empty())
469     return false;
470   // DIType is abstract, it should be a BasicType, a DerivedType or
471   // a CompositeType.
472   if (isBasicType())
473     return DIBasicType(DbgNode).Verify();
474   else if (isCompositeType())
475     return DICompositeType(DbgNode).Verify();
476   else if (isDerivedType())
477     return DIDerivedType(DbgNode).Verify();
478   else
479     return false;
480 }
481 
482 /// Verify - Verify that a basic type descriptor is well formed.
Verify() const483 bool DIBasicType::Verify() const {
484   return isBasicType() && DbgNode->getNumOperands() == 10;
485 }
486 
487 /// Verify - Verify that a derived type descriptor is well formed.
Verify() const488 bool DIDerivedType::Verify() const {
489   // Make sure DerivedFrom @ field 9 is TypeRef.
490   if (!fieldIsTypeRef(DbgNode, 9))
491     return false;
492   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
493     // Make sure ClassType @ field 10 is a TypeRef.
494     if (!fieldIsTypeRef(DbgNode, 10))
495       return false;
496 
497   return isDerivedType() && DbgNode->getNumOperands() >= 10 &&
498          DbgNode->getNumOperands() <= 14;
499 }
500 
501 /// Verify - Verify that a composite type descriptor is well formed.
Verify() const502 bool DICompositeType::Verify() const {
503   if (!isCompositeType())
504     return false;
505 
506   // Make sure DerivedFrom @ field 9 and ContainingType @ field 12 are TypeRef.
507   if (!fieldIsTypeRef(DbgNode, 9))
508     return false;
509   if (!fieldIsTypeRef(DbgNode, 12))
510     return false;
511 
512   // Make sure the type identifier at field 14 is MDString, it can be null.
513   if (!fieldIsMDString(DbgNode, 14))
514     return false;
515 
516   // A subroutine type can't be both & and &&.
517   if (isLValueReference() && isRValueReference())
518     return false;
519 
520   return DbgNode->getNumOperands() == 15;
521 }
522 
523 /// Verify - Verify that a subprogram descriptor is well formed.
Verify() const524 bool DISubprogram::Verify() const {
525   if (!isSubprogram())
526     return false;
527 
528   // Make sure context @ field 2 is a ScopeRef and type @ field 7 is a MDNode.
529   if (!fieldIsScopeRef(DbgNode, 2))
530     return false;
531   if (!fieldIsMDNode(DbgNode, 7))
532     return false;
533   // Containing type @ field 12.
534   if (!fieldIsTypeRef(DbgNode, 12))
535     return false;
536 
537   // A subprogram can't be both & and &&.
538   if (isLValueReference() && isRValueReference())
539     return false;
540 
541   return DbgNode->getNumOperands() == 20;
542 }
543 
544 /// Verify - Verify that a global variable descriptor is well formed.
Verify() const545 bool DIGlobalVariable::Verify() const {
546   if (!isGlobalVariable())
547     return false;
548 
549   if (getDisplayName().empty())
550     return false;
551   // Make sure context @ field 2 is an MDNode.
552   if (!fieldIsMDNode(DbgNode, 2))
553     return false;
554   // Make sure that type @ field 8 is a DITypeRef.
555   if (!fieldIsTypeRef(DbgNode, 8))
556     return false;
557   // Make sure StaticDataMemberDeclaration @ field 12 is MDNode.
558   if (!fieldIsMDNode(DbgNode, 12))
559     return false;
560 
561   return DbgNode->getNumOperands() == 13;
562 }
563 
564 /// Verify - Verify that a variable descriptor is well formed.
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 5 is a DITypeRef.
573   if (!fieldIsTypeRef(DbgNode, 5))
574     return false;
575 
576   // Variable without a complex expression.
577   if (DbgNode->getNumOperands() == 8)
578     return true;
579 
580   // Make sure the complex expression is an MDNode.
581   return (DbgNode->getNumOperands() == 9 && fieldIsMDNode(DbgNode, 8));
582 }
583 
584 /// Verify - Verify that a location descriptor is well formed.
Verify() const585 bool DILocation::Verify() const {
586   if (!DbgNode)
587     return false;
588 
589   return DbgNode->getNumOperands() == 4;
590 }
591 
592 /// Verify - Verify that a namespace descriptor is well formed.
Verify() const593 bool DINameSpace::Verify() const {
594   if (!isNameSpace())
595     return false;
596   return DbgNode->getNumOperands() == 5;
597 }
598 
599 /// \brief Retrieve the MDNode for the directory/file pair.
getFileNode() const600 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
601 
602 /// \brief Verify that the file descriptor is well formed.
Verify() const603 bool DIFile::Verify() const {
604   return isFile() && DbgNode->getNumOperands() == 2;
605 }
606 
607 /// \brief Verify that the enumerator descriptor is well formed.
Verify() const608 bool DIEnumerator::Verify() const {
609   return isEnumerator() && DbgNode->getNumOperands() == 3;
610 }
611 
612 /// \brief Verify that the subrange descriptor is well formed.
Verify() const613 bool DISubrange::Verify() const {
614   return isSubrange() && DbgNode->getNumOperands() == 3;
615 }
616 
617 /// \brief Verify that the lexical block descriptor is well formed.
Verify() const618 bool DILexicalBlock::Verify() const {
619   return isLexicalBlock() && DbgNode->getNumOperands() == 7;
620 }
621 
622 /// \brief Verify that the file-scoped lexical block descriptor is well formed.
Verify() const623 bool DILexicalBlockFile::Verify() const {
624   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3;
625 }
626 
627 /// \brief Verify that an unspecified parameter descriptor is well formed.
Verify() const628 bool DIUnspecifiedParameter::Verify() const {
629   return isUnspecifiedParameter() && DbgNode->getNumOperands() == 1;
630 }
631 
632 /// \brief Verify that the template type parameter descriptor is well formed.
Verify() const633 bool DITemplateTypeParameter::Verify() const {
634   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 7;
635 }
636 
637 /// \brief Verify that the template value parameter descriptor is well formed.
Verify() const638 bool DITemplateValueParameter::Verify() const {
639   return isTemplateValueParameter() && DbgNode->getNumOperands() == 8;
640 }
641 
642 /// \brief Verify that the imported module descriptor is well formed.
Verify() const643 bool DIImportedEntity::Verify() const {
644   return isImportedEntity() &&
645          (DbgNode->getNumOperands() == 4 || DbgNode->getNumOperands() == 5);
646 }
647 
648 /// getObjCProperty - Return property node, if this ivar is associated with one.
getObjCProperty() const649 MDNode *DIDerivedType::getObjCProperty() const {
650   return getNodeField(DbgNode, 10);
651 }
652 
getIdentifier() const653 MDString *DICompositeType::getIdentifier() const {
654   return cast_or_null<MDString>(getField(DbgNode, 14));
655 }
656 
657 #ifndef NDEBUG
VerifySubsetOf(const MDNode * LHS,const MDNode * RHS)658 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
659   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
660     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
661     if (i == 0 && isa<ConstantInt>(LHS->getOperand(i)))
662       continue;
663     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
664     bool found = false;
665     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
666       found = E == RHS->getOperand(j);
667     assert(found && "Losing a member during member list replacement");
668   }
669 }
670 #endif
671 
672 /// \brief Set the array of member DITypes.
setTypeArray(DIArray Elements,DIArray TParams)673 void DICompositeType::setTypeArray(DIArray Elements, DIArray TParams) {
674   assert((!TParams || DbgNode->getNumOperands() == 15) &&
675          "If you're setting the template parameters this should include a slot "
676          "for that!");
677   TrackingVH<MDNode> N(*this);
678   if (Elements) {
679 #ifndef NDEBUG
680     // Check that the new list of members contains all the old members as well.
681     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(10)))
682       VerifySubsetOf(El, Elements);
683 #endif
684     N->replaceOperandWith(10, Elements);
685   }
686   if (TParams)
687     N->replaceOperandWith(13, TParams);
688   DbgNode = N;
689 }
690 
691 /// Generate a reference to this DIType. Uses the type identifier instead
692 /// of the actual MDNode if possible, to help type uniquing.
getRef() const693 DIScopeRef DIScope::getRef() const {
694   if (!isCompositeType())
695     return DIScopeRef(*this);
696   DICompositeType DTy(DbgNode);
697   if (!DTy.getIdentifier())
698     return DIScopeRef(*this);
699   return DIScopeRef(DTy.getIdentifier());
700 }
701 
702 /// \brief Set the containing type.
setContainingType(DICompositeType ContainingType)703 void DICompositeType::setContainingType(DICompositeType ContainingType) {
704   TrackingVH<MDNode> N(*this);
705   N->replaceOperandWith(12, ContainingType.getRef());
706   DbgNode = N;
707 }
708 
709 /// isInlinedFnArgument - Return true if this variable provides debugging
710 /// information for an inlined function arguments.
isInlinedFnArgument(const Function * CurFn)711 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
712   assert(CurFn && "Invalid function");
713   if (!getContext().isSubprogram())
714     return false;
715   // This variable is not inlined function argument if its scope
716   // does not describe current function.
717   return !DISubprogram(getContext()).describes(CurFn);
718 }
719 
720 /// describes - Return true if this subprogram provides debugging
721 /// information for the function F.
describes(const Function * F)722 bool DISubprogram::describes(const Function *F) {
723   assert(F && "Invalid function");
724   if (F == getFunction())
725     return true;
726   StringRef Name = getLinkageName();
727   if (Name.empty())
728     Name = getName();
729   if (F->getName() == Name)
730     return true;
731   return false;
732 }
733 
isOptimized() const734 unsigned DISubprogram::isOptimized() const {
735   assert(DbgNode && "Invalid subprogram descriptor!");
736   if (DbgNode->getNumOperands() == 15)
737     return getUnsignedField(14);
738   return 0;
739 }
740 
getVariablesNodes() const741 MDNode *DISubprogram::getVariablesNodes() const {
742   return getNodeField(DbgNode, 18);
743 }
744 
getVariables() const745 DIArray DISubprogram::getVariables() const {
746   return DIArray(getNodeField(DbgNode, 18));
747 }
748 
getValue() const749 Value *DITemplateValueParameter::getValue() const {
750   return getField(DbgNode, 4);
751 }
752 
753 // If the current node has a parent scope then return that,
754 // else return an empty scope.
getContext() const755 DIScopeRef DIScope::getContext() const {
756 
757   if (isType())
758     return DIType(DbgNode).getContext();
759 
760   if (isSubprogram())
761     return DIScopeRef(DISubprogram(DbgNode).getContext());
762 
763   if (isLexicalBlock())
764     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
765 
766   if (isLexicalBlockFile())
767     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
768 
769   if (isNameSpace())
770     return DIScopeRef(DINameSpace(DbgNode).getContext());
771 
772   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
773   return DIScopeRef(nullptr);
774 }
775 
776 // If the scope node has a name, return that, else return an empty string.
getName() const777 StringRef DIScope::getName() const {
778   if (isType())
779     return DIType(DbgNode).getName();
780   if (isSubprogram())
781     return DISubprogram(DbgNode).getName();
782   if (isNameSpace())
783     return DINameSpace(DbgNode).getName();
784   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
785           isCompileUnit()) &&
786          "Unhandled type of scope.");
787   return StringRef();
788 }
789 
getFilename() const790 StringRef DIScope::getFilename() const {
791   if (!DbgNode)
792     return StringRef();
793   return ::getStringField(getNodeField(DbgNode, 1), 0);
794 }
795 
getDirectory() const796 StringRef DIScope::getDirectory() const {
797   if (!DbgNode)
798     return StringRef();
799   return ::getStringField(getNodeField(DbgNode, 1), 1);
800 }
801 
getEnumTypes() const802 DIArray DICompileUnit::getEnumTypes() const {
803   if (!DbgNode || DbgNode->getNumOperands() < 13)
804     return DIArray();
805 
806   return DIArray(getNodeField(DbgNode, 7));
807 }
808 
getRetainedTypes() const809 DIArray DICompileUnit::getRetainedTypes() const {
810   if (!DbgNode || DbgNode->getNumOperands() < 13)
811     return DIArray();
812 
813   return DIArray(getNodeField(DbgNode, 8));
814 }
815 
getSubprograms() const816 DIArray DICompileUnit::getSubprograms() const {
817   if (!DbgNode || DbgNode->getNumOperands() < 13)
818     return DIArray();
819 
820   return DIArray(getNodeField(DbgNode, 9));
821 }
822 
getGlobalVariables() const823 DIArray DICompileUnit::getGlobalVariables() const {
824   if (!DbgNode || DbgNode->getNumOperands() < 13)
825     return DIArray();
826 
827   return DIArray(getNodeField(DbgNode, 10));
828 }
829 
getImportedEntities() const830 DIArray DICompileUnit::getImportedEntities() const {
831   if (!DbgNode || DbgNode->getNumOperands() < 13)
832     return DIArray();
833 
834   return DIArray(getNodeField(DbgNode, 11));
835 }
836 
837 /// copyWithNewScope - Return a copy of this location, replacing the
838 /// current scope with the given one.
copyWithNewScope(LLVMContext & Ctx,DILexicalBlock NewScope)839 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
840                                         DILexicalBlock NewScope) {
841   SmallVector<Value *, 10> Elts;
842   assert(Verify());
843   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
844     if (I != 2)
845       Elts.push_back(DbgNode->getOperand(I));
846     else
847       Elts.push_back(NewScope);
848   }
849   MDNode *NewDIL = MDNode::get(Ctx, Elts);
850   return DILocation(NewDIL);
851 }
852 
853 /// computeNewDiscriminator - Generate a new discriminator value for this
854 /// file and line location.
computeNewDiscriminator(LLVMContext & Ctx)855 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
856   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
857   return ++Ctx.pImpl->DiscriminatorTable[Key];
858 }
859 
860 /// fixupSubprogramName - Replace contains special characters used
861 /// in a typical Objective-C names with '.' in a given string.
fixupSubprogramName(DISubprogram Fn,SmallVectorImpl<char> & Out)862 static void fixupSubprogramName(DISubprogram Fn, SmallVectorImpl<char> &Out) {
863   StringRef FName =
864       Fn.getFunction() ? Fn.getFunction()->getName() : Fn.getName();
865   FName = Function::getRealLinkageName(FName);
866 
867   StringRef Prefix("llvm.dbg.lv.");
868   Out.reserve(FName.size() + Prefix.size());
869   Out.append(Prefix.begin(), Prefix.end());
870 
871   bool isObjCLike = false;
872   for (size_t i = 0, e = FName.size(); i < e; ++i) {
873     char C = FName[i];
874     if (C == '[')
875       isObjCLike = true;
876 
877     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
878                        C == '+' || C == '(' || C == ')'))
879       Out.push_back('.');
880     else
881       Out.push_back(C);
882   }
883 }
884 
885 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is
886 /// suitable to hold function specific information.
getFnSpecificMDNode(const Module & M,DISubprogram Fn)887 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
888   SmallString<32> Name;
889   fixupSubprogramName(Fn, Name);
890   return M.getNamedMetadata(Name.str());
891 }
892 
893 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
894 /// to hold function specific information.
getOrInsertFnSpecificMDNode(Module & M,DISubprogram Fn)895 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
896   SmallString<32> Name;
897   fixupSubprogramName(Fn, Name);
898   return M.getOrInsertNamedMetadata(Name.str());
899 }
900 
901 /// createInlinedVariable - Create a new inlined variable based on current
902 /// variable.
903 /// @param DV            Current Variable.
904 /// @param InlinedScope  Location at current variable is inlined.
createInlinedVariable(MDNode * DV,MDNode * InlinedScope,LLVMContext & VMContext)905 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
906                                        LLVMContext &VMContext) {
907   SmallVector<Value *, 16> Elts;
908   // Insert inlined scope as 7th element.
909   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
910     i == 7 ? Elts.push_back(InlinedScope) : Elts.push_back(DV->getOperand(i));
911   return DIVariable(MDNode::get(VMContext, Elts));
912 }
913 
914 /// cleanseInlinedVariable - Remove inlined scope from the variable.
cleanseInlinedVariable(MDNode * DV,LLVMContext & VMContext)915 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
916   SmallVector<Value *, 16> Elts;
917   // Insert inlined scope as 7th element.
918   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
919     i == 7 ? Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext)))
920            : Elts.push_back(DV->getOperand(i));
921   return DIVariable(MDNode::get(VMContext, Elts));
922 }
923 
924 /// getDISubprogram - Find subprogram that is enclosing this scope.
getDISubprogram(const MDNode * Scope)925 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
926   DIDescriptor D(Scope);
927   if (D.isSubprogram())
928     return DISubprogram(Scope);
929 
930   if (D.isLexicalBlockFile())
931     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
932 
933   if (D.isLexicalBlock())
934     return getDISubprogram(DILexicalBlock(Scope).getContext());
935 
936   return DISubprogram();
937 }
938 
939 /// getDICompositeType - Find underlying composite type.
getDICompositeType(DIType T)940 DICompositeType llvm::getDICompositeType(DIType T) {
941   if (T.isCompositeType())
942     return DICompositeType(T);
943 
944   if (T.isDerivedType()) {
945     // This function is currently used by dragonegg and dragonegg does
946     // not generate identifier for types, so using an empty map to resolve
947     // DerivedFrom should be fine.
948     DITypeIdentifierMap EmptyMap;
949     return getDICompositeType(
950         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
951   }
952 
953   return DICompositeType();
954 }
955 
956 /// Update DITypeIdentifierMap by going through retained types of each CU.
957 DITypeIdentifierMap
generateDITypeIdentifierMap(const NamedMDNode * CU_Nodes)958 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
959   DITypeIdentifierMap Map;
960   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
961     DICompileUnit CU(CU_Nodes->getOperand(CUi));
962     DIArray Retain = CU.getRetainedTypes();
963     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
964       if (!Retain.getElement(Ti).isCompositeType())
965         continue;
966       DICompositeType Ty(Retain.getElement(Ti));
967       if (MDString *TypeId = Ty.getIdentifier()) {
968         // Definition has priority over declaration.
969         // Try to insert (TypeId, Ty) to Map.
970         std::pair<DITypeIdentifierMap::iterator, bool> P =
971             Map.insert(std::make_pair(TypeId, Ty));
972         // If TypeId already exists in Map and this is a definition, replace
973         // whatever we had (declaration or definition) with the definition.
974         if (!P.second && !Ty.isForwardDecl())
975           P.first->second = Ty;
976       }
977     }
978   }
979   return Map;
980 }
981 
982 //===----------------------------------------------------------------------===//
983 // DebugInfoFinder implementations.
984 //===----------------------------------------------------------------------===//
985 
reset()986 void DebugInfoFinder::reset() {
987   CUs.clear();
988   SPs.clear();
989   GVs.clear();
990   TYs.clear();
991   Scopes.clear();
992   NodesSeen.clear();
993   TypeIdentifierMap.clear();
994   TypeMapInitialized = false;
995 }
996 
InitializeTypeMap(const Module & M)997 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
998   if (!TypeMapInitialized)
999     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1000       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
1001       TypeMapInitialized = true;
1002     }
1003 }
1004 
1005 /// processModule - Process entire module and collect debug info.
processModule(const Module & M)1006 void DebugInfoFinder::processModule(const Module &M) {
1007   InitializeTypeMap(M);
1008   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
1009     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
1010       DICompileUnit CU(CU_Nodes->getOperand(i));
1011       addCompileUnit(CU);
1012       DIArray GVs = CU.getGlobalVariables();
1013       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
1014         DIGlobalVariable DIG(GVs.getElement(i));
1015         if (addGlobalVariable(DIG)) {
1016           processScope(DIG.getContext());
1017           processType(DIG.getType().resolve(TypeIdentifierMap));
1018         }
1019       }
1020       DIArray SPs = CU.getSubprograms();
1021       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
1022         processSubprogram(DISubprogram(SPs.getElement(i)));
1023       DIArray EnumTypes = CU.getEnumTypes();
1024       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
1025         processType(DIType(EnumTypes.getElement(i)));
1026       DIArray RetainedTypes = CU.getRetainedTypes();
1027       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
1028         processType(DIType(RetainedTypes.getElement(i)));
1029       DIArray Imports = CU.getImportedEntities();
1030       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
1031         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
1032         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
1033         if (Entity.isType())
1034           processType(DIType(Entity));
1035         else if (Entity.isSubprogram())
1036           processSubprogram(DISubprogram(Entity));
1037         else if (Entity.isNameSpace())
1038           processScope(DINameSpace(Entity).getContext());
1039       }
1040     }
1041   }
1042 }
1043 
1044 /// processLocation - Process DILocation.
processLocation(const Module & M,DILocation Loc)1045 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
1046   if (!Loc)
1047     return;
1048   InitializeTypeMap(M);
1049   processScope(Loc.getScope());
1050   processLocation(M, Loc.getOrigLocation());
1051 }
1052 
1053 /// processType - Process DIType.
processType(DIType DT)1054 void DebugInfoFinder::processType(DIType DT) {
1055   if (!addType(DT))
1056     return;
1057   processScope(DT.getContext().resolve(TypeIdentifierMap));
1058   if (DT.isCompositeType()) {
1059     DICompositeType DCT(DT);
1060     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1061     DIArray DA = DCT.getTypeArray();
1062     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1063       DIDescriptor D = DA.getElement(i);
1064       if (D.isType())
1065         processType(DIType(D));
1066       else if (D.isSubprogram())
1067         processSubprogram(DISubprogram(D));
1068     }
1069   } else if (DT.isDerivedType()) {
1070     DIDerivedType DDT(DT);
1071     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
1072   }
1073 }
1074 
processScope(DIScope Scope)1075 void DebugInfoFinder::processScope(DIScope Scope) {
1076   if (Scope.isType()) {
1077     DIType Ty(Scope);
1078     processType(Ty);
1079     return;
1080   }
1081   if (Scope.isCompileUnit()) {
1082     addCompileUnit(DICompileUnit(Scope));
1083     return;
1084   }
1085   if (Scope.isSubprogram()) {
1086     processSubprogram(DISubprogram(Scope));
1087     return;
1088   }
1089   if (!addScope(Scope))
1090     return;
1091   if (Scope.isLexicalBlock()) {
1092     DILexicalBlock LB(Scope);
1093     processScope(LB.getContext());
1094   } else if (Scope.isLexicalBlockFile()) {
1095     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
1096     processScope(LBF.getScope());
1097   } else if (Scope.isNameSpace()) {
1098     DINameSpace NS(Scope);
1099     processScope(NS.getContext());
1100   }
1101 }
1102 
1103 /// processSubprogram - Process DISubprogram.
processSubprogram(DISubprogram SP)1104 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1105   if (!addSubprogram(SP))
1106     return;
1107   processScope(SP.getContext().resolve(TypeIdentifierMap));
1108   processType(SP.getType());
1109   DIArray TParams = SP.getTemplateParams();
1110   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
1111     DIDescriptor Element = TParams.getElement(I);
1112     if (Element.isTemplateTypeParameter()) {
1113       DITemplateTypeParameter TType(Element);
1114       processScope(TType.getContext().resolve(TypeIdentifierMap));
1115       processType(TType.getType().resolve(TypeIdentifierMap));
1116     } else if (Element.isTemplateValueParameter()) {
1117       DITemplateValueParameter TVal(Element);
1118       processScope(TVal.getContext().resolve(TypeIdentifierMap));
1119       processType(TVal.getType().resolve(TypeIdentifierMap));
1120     }
1121   }
1122 }
1123 
1124 /// processDeclare - Process DbgDeclareInst.
processDeclare(const Module & M,const DbgDeclareInst * DDI)1125 void DebugInfoFinder::processDeclare(const Module &M,
1126                                      const DbgDeclareInst *DDI) {
1127   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1128   if (!N)
1129     return;
1130   InitializeTypeMap(M);
1131 
1132   DIDescriptor DV(N);
1133   if (!DV.isVariable())
1134     return;
1135 
1136   if (!NodesSeen.insert(DV))
1137     return;
1138   processScope(DIVariable(N).getContext());
1139   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1140 }
1141 
processValue(const Module & M,const DbgValueInst * DVI)1142 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
1143   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
1144   if (!N)
1145     return;
1146   InitializeTypeMap(M);
1147 
1148   DIDescriptor DV(N);
1149   if (!DV.isVariable())
1150     return;
1151 
1152   if (!NodesSeen.insert(DV))
1153     return;
1154   processScope(DIVariable(N).getContext());
1155   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
1156 }
1157 
1158 /// addType - Add type into Tys.
addType(DIType DT)1159 bool DebugInfoFinder::addType(DIType DT) {
1160   if (!DT)
1161     return false;
1162 
1163   if (!NodesSeen.insert(DT))
1164     return false;
1165 
1166   TYs.push_back(DT);
1167   return true;
1168 }
1169 
1170 /// addCompileUnit - Add compile unit into CUs.
addCompileUnit(DICompileUnit CU)1171 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1172   if (!CU)
1173     return false;
1174   if (!NodesSeen.insert(CU))
1175     return false;
1176 
1177   CUs.push_back(CU);
1178   return true;
1179 }
1180 
1181 /// addGlobalVariable - Add global variable into GVs.
addGlobalVariable(DIGlobalVariable DIG)1182 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1183   if (!DIG)
1184     return false;
1185 
1186   if (!NodesSeen.insert(DIG))
1187     return false;
1188 
1189   GVs.push_back(DIG);
1190   return true;
1191 }
1192 
1193 // addSubprogram - Add subprgoram into SPs.
addSubprogram(DISubprogram SP)1194 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1195   if (!SP)
1196     return false;
1197 
1198   if (!NodesSeen.insert(SP))
1199     return false;
1200 
1201   SPs.push_back(SP);
1202   return true;
1203 }
1204 
addScope(DIScope Scope)1205 bool DebugInfoFinder::addScope(DIScope Scope) {
1206   if (!Scope)
1207     return false;
1208   // FIXME: Ocaml binding generates a scope with no content, we treat it
1209   // as null for now.
1210   if (Scope->getNumOperands() == 0)
1211     return false;
1212   if (!NodesSeen.insert(Scope))
1213     return false;
1214   Scopes.push_back(Scope);
1215   return true;
1216 }
1217 
1218 //===----------------------------------------------------------------------===//
1219 // DIDescriptor: dump routines for all descriptors.
1220 //===----------------------------------------------------------------------===//
1221 
1222 /// dump - Print descriptor to dbgs() with a newline.
dump() const1223 void DIDescriptor::dump() const {
1224   print(dbgs());
1225   dbgs() << '\n';
1226 }
1227 
1228 /// print - Print descriptor.
print(raw_ostream & OS) const1229 void DIDescriptor::print(raw_ostream &OS) const {
1230   if (!DbgNode)
1231     return;
1232 
1233   if (const char *Tag = dwarf::TagString(getTag()))
1234     OS << "[ " << Tag << " ]";
1235 
1236   if (this->isSubrange()) {
1237     DISubrange(DbgNode).printInternal(OS);
1238   } else if (this->isCompileUnit()) {
1239     DICompileUnit(DbgNode).printInternal(OS);
1240   } else if (this->isFile()) {
1241     DIFile(DbgNode).printInternal(OS);
1242   } else if (this->isEnumerator()) {
1243     DIEnumerator(DbgNode).printInternal(OS);
1244   } else if (this->isBasicType()) {
1245     DIType(DbgNode).printInternal(OS);
1246   } else if (this->isDerivedType()) {
1247     DIDerivedType(DbgNode).printInternal(OS);
1248   } else if (this->isCompositeType()) {
1249     DICompositeType(DbgNode).printInternal(OS);
1250   } else if (this->isSubprogram()) {
1251     DISubprogram(DbgNode).printInternal(OS);
1252   } else if (this->isGlobalVariable()) {
1253     DIGlobalVariable(DbgNode).printInternal(OS);
1254   } else if (this->isVariable()) {
1255     DIVariable(DbgNode).printInternal(OS);
1256   } else if (this->isObjCProperty()) {
1257     DIObjCProperty(DbgNode).printInternal(OS);
1258   } else if (this->isNameSpace()) {
1259     DINameSpace(DbgNode).printInternal(OS);
1260   } else if (this->isScope()) {
1261     DIScope(DbgNode).printInternal(OS);
1262   }
1263 }
1264 
printInternal(raw_ostream & OS) const1265 void DISubrange::printInternal(raw_ostream &OS) const {
1266   int64_t Count = getCount();
1267   if (Count != -1)
1268     OS << " [" << getLo() << ", " << Count - 1 << ']';
1269   else
1270     OS << " [unbounded]";
1271 }
1272 
printInternal(raw_ostream & OS) const1273 void DIScope::printInternal(raw_ostream &OS) const {
1274   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1275 }
1276 
printInternal(raw_ostream & OS) const1277 void DICompileUnit::printInternal(raw_ostream &OS) const {
1278   DIScope::printInternal(OS);
1279   OS << " [";
1280   unsigned Lang = getLanguage();
1281   if (const char *LangStr = dwarf::LanguageString(Lang))
1282     OS << LangStr;
1283   else
1284     (OS << "lang 0x").write_hex(Lang);
1285   OS << ']';
1286 }
1287 
printInternal(raw_ostream & OS) const1288 void DIEnumerator::printInternal(raw_ostream &OS) const {
1289   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1290 }
1291 
printInternal(raw_ostream & OS) const1292 void DIType::printInternal(raw_ostream &OS) const {
1293   if (!DbgNode)
1294     return;
1295 
1296   StringRef Res = getName();
1297   if (!Res.empty())
1298     OS << " [" << Res << "]";
1299 
1300   // TODO: Print context?
1301 
1302   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
1303      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
1304   if (isBasicType())
1305     if (const char *Enc =
1306             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1307       OS << ", enc " << Enc;
1308   OS << "]";
1309 
1310   if (isPrivate())
1311     OS << " [private]";
1312   else if (isProtected())
1313     OS << " [protected]";
1314 
1315   if (isArtificial())
1316     OS << " [artificial]";
1317 
1318   if (isForwardDecl())
1319     OS << " [decl]";
1320   else if (getTag() == dwarf::DW_TAG_structure_type ||
1321            getTag() == dwarf::DW_TAG_union_type ||
1322            getTag() == dwarf::DW_TAG_enumeration_type ||
1323            getTag() == dwarf::DW_TAG_class_type)
1324     OS << " [def]";
1325   if (isVector())
1326     OS << " [vector]";
1327   if (isStaticMember())
1328     OS << " [static]";
1329 
1330   if (isLValueReference())
1331     OS << " [reference]";
1332 
1333   if (isRValueReference())
1334     OS << " [rvalue reference]";
1335 }
1336 
printInternal(raw_ostream & OS) const1337 void DIDerivedType::printInternal(raw_ostream &OS) const {
1338   DIType::printInternal(OS);
1339   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1340 }
1341 
printInternal(raw_ostream & OS) const1342 void DICompositeType::printInternal(raw_ostream &OS) const {
1343   DIType::printInternal(OS);
1344   DIArray A = getTypeArray();
1345   OS << " [" << A.getNumElements() << " elements]";
1346 }
1347 
printInternal(raw_ostream & OS) const1348 void DINameSpace::printInternal(raw_ostream &OS) const {
1349   StringRef Name = getName();
1350   if (!Name.empty())
1351     OS << " [" << Name << ']';
1352 
1353   OS << " [line " << getLineNumber() << ']';
1354 }
1355 
printInternal(raw_ostream & OS) const1356 void DISubprogram::printInternal(raw_ostream &OS) const {
1357   // TODO : Print context
1358   OS << " [line " << getLineNumber() << ']';
1359 
1360   if (isLocalToUnit())
1361     OS << " [local]";
1362 
1363   if (isDefinition())
1364     OS << " [def]";
1365 
1366   if (getScopeLineNumber() != getLineNumber())
1367     OS << " [scope " << getScopeLineNumber() << "]";
1368 
1369   if (isPrivate())
1370     OS << " [private]";
1371   else if (isProtected())
1372     OS << " [protected]";
1373 
1374   if (isLValueReference())
1375     OS << " [reference]";
1376 
1377   if (isRValueReference())
1378     OS << " [rvalue reference]";
1379 
1380   StringRef Res = getName();
1381   if (!Res.empty())
1382     OS << " [" << Res << ']';
1383 }
1384 
printInternal(raw_ostream & OS) const1385 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1386   StringRef Res = getName();
1387   if (!Res.empty())
1388     OS << " [" << Res << ']';
1389 
1390   OS << " [line " << getLineNumber() << ']';
1391 
1392   // TODO : Print context
1393 
1394   if (isLocalToUnit())
1395     OS << " [local]";
1396 
1397   if (isDefinition())
1398     OS << " [def]";
1399 }
1400 
printInternal(raw_ostream & OS) const1401 void DIVariable::printInternal(raw_ostream &OS) const {
1402   StringRef Res = getName();
1403   if (!Res.empty())
1404     OS << " [" << Res << ']';
1405 
1406   OS << " [line " << getLineNumber() << ']';
1407 }
1408 
printInternal(raw_ostream & OS) const1409 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1410   StringRef Name = getObjCPropertyName();
1411   if (!Name.empty())
1412     OS << " [" << Name << ']';
1413 
1414   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
1415      << ']';
1416 }
1417 
printDebugLoc(DebugLoc DL,raw_ostream & CommentOS,const LLVMContext & Ctx)1418 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1419                           const LLVMContext &Ctx) {
1420   if (!DL.isUnknown()) { // Print source line info.
1421     DIScope Scope(DL.getScope(Ctx));
1422     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
1423     // Omit the directory, because it's likely to be long and uninteresting.
1424     CommentOS << Scope.getFilename();
1425     CommentOS << ':' << DL.getLine();
1426     if (DL.getCol() != 0)
1427       CommentOS << ':' << DL.getCol();
1428     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1429     if (!InlinedAtDL.isUnknown()) {
1430       CommentOS << " @[ ";
1431       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1432       CommentOS << " ]";
1433     }
1434   }
1435 }
1436 
printExtendedName(raw_ostream & OS) const1437 void DIVariable::printExtendedName(raw_ostream &OS) const {
1438   const LLVMContext &Ctx = DbgNode->getContext();
1439   StringRef Res = getName();
1440   if (!Res.empty())
1441     OS << Res << "," << getLineNumber();
1442   if (MDNode *InlinedAt = getInlinedAt()) {
1443     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1444     if (!InlinedAtDL.isUnknown()) {
1445       OS << " @[";
1446       printDebugLoc(InlinedAtDL, OS, Ctx);
1447       OS << "]";
1448     }
1449   }
1450 }
1451 
1452 /// Specialize constructor to make sure it has the correct type.
DIRef(const Value * V)1453 template <> DIRef<DIScope>::DIRef(const Value *V) : Val(V) {
1454   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
1455 }
DIRef(const Value * V)1456 template <> DIRef<DIType>::DIRef(const Value *V) : Val(V) {
1457   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
1458 }
1459 
1460 /// Specialize getFieldAs to handle fields that are references to DIScopes.
1461 template <>
getFieldAs(unsigned Elt) const1462 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
1463   return DIScopeRef(getField(DbgNode, Elt));
1464 }
1465 /// Specialize getFieldAs to handle fields that are references to DITypes.
getFieldAs(unsigned Elt) const1466 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
1467   return DITypeRef(getField(DbgNode, Elt));
1468 }
1469 
1470 /// Strip debug info in the module if it exists.
1471 /// To do this, we remove all calls to the debugger intrinsics and any named
1472 /// metadata for debugging. We also remove debug locations for instructions.
1473 /// Return true if module is modified.
StripDebugInfo(Module & M)1474 bool llvm::StripDebugInfo(Module &M) {
1475 
1476   bool Changed = false;
1477 
1478   // Remove all of the calls to the debugger intrinsics, and remove them from
1479   // the module.
1480   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
1481     while (!Declare->use_empty()) {
1482       CallInst *CI = cast<CallInst>(Declare->user_back());
1483       CI->eraseFromParent();
1484     }
1485     Declare->eraseFromParent();
1486     Changed = true;
1487   }
1488 
1489   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
1490     while (!DbgVal->use_empty()) {
1491       CallInst *CI = cast<CallInst>(DbgVal->user_back());
1492       CI->eraseFromParent();
1493     }
1494     DbgVal->eraseFromParent();
1495     Changed = true;
1496   }
1497 
1498   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
1499          NME = M.named_metadata_end(); NMI != NME;) {
1500     NamedMDNode *NMD = NMI;
1501     ++NMI;
1502     if (NMD->getName().startswith("llvm.dbg.")) {
1503       NMD->eraseFromParent();
1504       Changed = true;
1505     }
1506   }
1507 
1508   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
1509     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
1510          ++FI)
1511       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
1512            ++BI) {
1513         if (!BI->getDebugLoc().isUnknown()) {
1514           Changed = true;
1515           BI->setDebugLoc(DebugLoc());
1516         }
1517       }
1518 
1519   return Changed;
1520 }
1521 
1522 /// Return Debug Info Metadata Version by checking module flags.
getDebugMetadataVersionFromModule(const Module & M)1523 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
1524   Value *Val = M.getModuleFlag("Debug Info Version");
1525   if (!Val)
1526     return 0;
1527   return cast<ConstantInt>(Val)->getZExtValue();
1528 }
1529 
1530 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
makeSubprogramMap(const Module & M)1531 llvm::makeSubprogramMap(const Module &M) {
1532   DenseMap<const Function *, DISubprogram> R;
1533 
1534   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
1535   if (!CU_Nodes)
1536     return R;
1537 
1538   for (MDNode *N : CU_Nodes->operands()) {
1539     DICompileUnit CUNode(N);
1540     DIArray SPs = CUNode.getSubprograms();
1541     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
1542       DISubprogram SP(SPs.getElement(i));
1543       if (Function *F = SP.getFunction())
1544         R.insert(std::make_pair(F, SP));
1545     }
1546   }
1547   return R;
1548 }
1549