Remove a function argument and propagate const around accordingly.
[oota-llvm.git] / lib / VMCore / DebugInfo.cpp
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/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/Dwarf.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 DIDescriptor::DIDescriptor(const DIFile F) : DbgNode(F.DbgNode) {
37 }
38
39 DIDescriptor::DIDescriptor(const DISubprogram F) : DbgNode(F.DbgNode) {
40 }
41
42 DIDescriptor::DIDescriptor(const DILexicalBlockFile F) : DbgNode(F.DbgNode) {
43 }
44
45 DIDescriptor::DIDescriptor(const DILexicalBlock F) : DbgNode(F.DbgNode) {
46 }
47
48 DIDescriptor::DIDescriptor(const DIVariable F) : DbgNode(F.DbgNode) {
49 }
50
51 DIDescriptor::DIDescriptor(const DIType F) : DbgNode(F.DbgNode) {
52 }
53
54 StringRef
55 DIDescriptor::getStringField(unsigned Elt) const {
56   if (DbgNode == 0)
57     return StringRef();
58
59   if (Elt < DbgNode->getNumOperands())
60     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getOperand(Elt)))
61       return MDS->getString();
62
63   return StringRef();
64 }
65
66 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
67   if (DbgNode == 0)
68     return 0;
69
70   if (Elt < DbgNode->getNumOperands())
71     if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(DbgNode->getOperand(Elt)))
72       return CI->getZExtValue();
73
74   return 0;
75 }
76
77 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
78   if (DbgNode == 0)
79     return DIDescriptor();
80
81   if (Elt < DbgNode->getNumOperands())
82     return
83       DIDescriptor(dyn_cast_or_null<const MDNode>(DbgNode->getOperand(Elt)));
84   return DIDescriptor();
85 }
86
87 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
88   if (DbgNode == 0)
89     return 0;
90
91   if (Elt < DbgNode->getNumOperands())
92       return dyn_cast_or_null<GlobalVariable>(DbgNode->getOperand(Elt));
93   return 0;
94 }
95
96 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
97   if (DbgNode == 0)
98     return 0;
99
100   if (Elt < DbgNode->getNumOperands())
101       return dyn_cast_or_null<Constant>(DbgNode->getOperand(Elt));
102   return 0;
103 }
104
105 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
106   if (DbgNode == 0)
107     return 0;
108
109   if (Elt < DbgNode->getNumOperands())
110       return dyn_cast_or_null<Function>(DbgNode->getOperand(Elt));
111   return 0;
112 }
113
114 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
115   if (DbgNode == 0)
116     return;
117
118   if (Elt < DbgNode->getNumOperands()) {
119     MDNode *Node = const_cast<MDNode*>(DbgNode);
120     Node->replaceOperandWith(Elt, F);
121   }
122 }
123
124 unsigned DIVariable::getNumAddrElements() const {
125   if (getVersion() <= LLVMDebugVersion8)
126     return DbgNode->getNumOperands()-6;
127   if (getVersion() == LLVMDebugVersion9)
128     return DbgNode->getNumOperands()-7;
129   return DbgNode->getNumOperands()-8;
130 }
131
132 /// getInlinedAt - If this variable is inlined then return inline location.
133 MDNode *DIVariable::getInlinedAt() const {
134   if (getVersion() <= LLVMDebugVersion9)
135     return NULL;
136   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(7));
137 }
138
139 //===----------------------------------------------------------------------===//
140 // Predicates
141 //===----------------------------------------------------------------------===//
142
143 /// isBasicType - Return true if the specified tag is legal for
144 /// DIBasicType.
145 bool DIDescriptor::isBasicType() const {
146   if (!DbgNode) return false;
147   switch (getTag()) {
148   case dwarf::DW_TAG_base_type:
149   case dwarf::DW_TAG_unspecified_type:
150     return true;
151   default:
152     return false;
153   }
154 }
155
156 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
157 bool DIDescriptor::isDerivedType() const {
158   if (!DbgNode) return false;
159   switch (getTag()) {
160   case dwarf::DW_TAG_typedef:
161   case dwarf::DW_TAG_pointer_type:
162   case dwarf::DW_TAG_reference_type:
163   case dwarf::DW_TAG_rvalue_reference_type:
164   case dwarf::DW_TAG_const_type:
165   case dwarf::DW_TAG_volatile_type:
166   case dwarf::DW_TAG_restrict_type:
167   case dwarf::DW_TAG_member:
168   case dwarf::DW_TAG_inheritance:
169   case dwarf::DW_TAG_friend:
170     return true;
171   default:
172     // CompositeTypes are currently modelled as DerivedTypes.
173     return isCompositeType();
174   }
175 }
176
177 /// isCompositeType - Return true if the specified tag is legal for
178 /// DICompositeType.
179 bool DIDescriptor::isCompositeType() const {
180   if (!DbgNode) return false;
181   switch (getTag()) {
182   case dwarf::DW_TAG_array_type:
183   case dwarf::DW_TAG_structure_type:
184   case dwarf::DW_TAG_union_type:
185   case dwarf::DW_TAG_enumeration_type:
186   case dwarf::DW_TAG_vector_type:
187   case dwarf::DW_TAG_subroutine_type:
188   case dwarf::DW_TAG_class_type:
189     return true;
190   default:
191     return false;
192   }
193 }
194
195 /// isVariable - Return true if the specified tag is legal for DIVariable.
196 bool DIDescriptor::isVariable() const {
197   if (!DbgNode) return false;
198   switch (getTag()) {
199   case dwarf::DW_TAG_auto_variable:
200   case dwarf::DW_TAG_arg_variable:
201   case dwarf::DW_TAG_return_variable:
202     return true;
203   default:
204     return false;
205   }
206 }
207
208 /// isType - Return true if the specified tag is legal for DIType.
209 bool DIDescriptor::isType() const {
210   return isBasicType() || isCompositeType() || isDerivedType();
211 }
212
213 /// isSubprogram - Return true if the specified tag is legal for
214 /// DISubprogram.
215 bool DIDescriptor::isSubprogram() const {
216   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
217 }
218
219 /// isGlobalVariable - Return true if the specified tag is legal for
220 /// DIGlobalVariable.
221 bool DIDescriptor::isGlobalVariable() const {
222   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
223                      getTag() == dwarf::DW_TAG_constant);
224 }
225
226 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
227 bool DIDescriptor::isGlobal() const {
228   return isGlobalVariable();
229 }
230
231 /// isUnspecifiedParmeter - Return true if the specified tag is
232 /// DW_TAG_unspecified_parameters.
233 bool DIDescriptor::isUnspecifiedParameter() const {
234   return DbgNode && getTag() == dwarf::DW_TAG_unspecified_parameters;
235 }
236
237 /// isScope - Return true if the specified tag is one of the scope
238 /// related tag.
239 bool DIDescriptor::isScope() const {
240   if (!DbgNode) return false;
241   switch (getTag()) {
242   case dwarf::DW_TAG_compile_unit:
243   case dwarf::DW_TAG_lexical_block:
244   case dwarf::DW_TAG_subprogram:
245   case dwarf::DW_TAG_namespace:
246     return true;
247   default:
248     break;
249   }
250   return false;
251 }
252
253 /// isTemplateTypeParameter - Return true if the specified tag is
254 /// DW_TAG_template_type_parameter.
255 bool DIDescriptor::isTemplateTypeParameter() const {
256   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
257 }
258
259 /// isTemplateValueParameter - Return true if the specified tag is
260 /// DW_TAG_template_value_parameter.
261 bool DIDescriptor::isTemplateValueParameter() const {
262   return DbgNode && getTag() == dwarf::DW_TAG_template_value_parameter;
263 }
264
265 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
266 bool DIDescriptor::isCompileUnit() const {
267   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
268 }
269
270 /// isFile - Return true if the specified tag is DW_TAG_file_type.
271 bool DIDescriptor::isFile() const {
272   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
273 }
274
275 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
276 bool DIDescriptor::isNameSpace() const {
277   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
278 }
279
280 /// isLexicalBlockFile - Return true if the specified descriptor is a
281 /// lexical block with an extra file.
282 bool DIDescriptor::isLexicalBlockFile() const {
283   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
284     (DbgNode->getNumOperands() == 3);
285 }
286
287 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
288 bool DIDescriptor::isLexicalBlock() const {
289   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
290     (DbgNode->getNumOperands() > 3);
291 }
292
293 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
294 bool DIDescriptor::isSubrange() const {
295   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
296 }
297
298 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
299 bool DIDescriptor::isEnumerator() const {
300   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
301 }
302
303 /// isObjCProperty - Return true if the specified tag is DW_TAG
304 bool DIDescriptor::isObjCProperty() const {
305   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
306 }
307 //===----------------------------------------------------------------------===//
308 // Simple Descriptor Constructors and other Methods
309 //===----------------------------------------------------------------------===//
310
311 DIType::DIType(const MDNode *N) : DIScope(N) {
312   if (!N) return;
313   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
314     DbgNode = 0;
315   }
316 }
317
318 unsigned DIArray::getNumElements() const {
319   if (!DbgNode)
320     return 0;
321   return DbgNode->getNumOperands();
322 }
323
324 /// replaceAllUsesWith - Replace all uses of debug info referenced by
325 /// this descriptor.
326 void DIType::replaceAllUsesWith(DIDescriptor &D) {
327   if (!DbgNode)
328     return;
329
330   // Since we use a TrackingVH for the node, its easy for clients to manufacture
331   // legitimate situations where they want to replaceAllUsesWith() on something
332   // which, due to uniquing, has merged with the source. We shield clients from
333   // this detail by allowing a value to be replaced with replaceAllUsesWith()
334   // itself.
335   if (DbgNode != D) {
336     MDNode *Node = const_cast<MDNode*>(DbgNode);
337     const MDNode *DN = D;
338     const Value *V = cast_or_null<Value>(DN);
339     Node->replaceAllUsesWith(const_cast<Value*>(V));
340     MDNode::deleteTemporary(Node);
341   }
342 }
343
344 /// replaceAllUsesWith - Replace all uses of debug info referenced by
345 /// this descriptor.
346 void DIType::replaceAllUsesWith(MDNode *D) {
347   if (!DbgNode)
348     return;
349
350   // Since we use a TrackingVH for the node, its easy for clients to manufacture
351   // legitimate situations where they want to replaceAllUsesWith() on something
352   // which, due to uniquing, has merged with the source. We shield clients from
353   // this detail by allowing a value to be replaced with replaceAllUsesWith()
354   // itself.
355   if (DbgNode != D) {
356     MDNode *Node = const_cast<MDNode*>(DbgNode);
357     const MDNode *DN = D;
358     const Value *V = cast_or_null<Value>(DN);
359     Node->replaceAllUsesWith(const_cast<Value*>(V));
360     MDNode::deleteTemporary(Node);
361   }
362 }
363
364 /// isUnsignedDIType - Return true if type encoding is unsigned.
365 bool DIType::isUnsignedDIType() {
366   DIDerivedType DTy(DbgNode);
367   if (DTy.Verify())
368     return DTy.getTypeDerivedFrom().isUnsignedDIType();
369
370   DIBasicType BTy(DbgNode);
371   if (BTy.Verify()) {
372     unsigned Encoding = BTy.getEncoding();
373     if (Encoding == dwarf::DW_ATE_unsigned ||
374         Encoding == dwarf::DW_ATE_unsigned_char)
375       return true;
376   }
377   return false;
378 }
379
380 /// Verify - Verify that a compile unit is well formed.
381 bool DICompileUnit::Verify() const {
382   if (!DbgNode)
383     return false;
384   StringRef N = getFilename();
385   if (N.empty())
386     return false;
387   // It is possible that directory and produce string is empty.
388   return true;
389 }
390
391 /// Verify - Verify that an ObjC property is well formed.
392 bool DIObjCProperty::Verify() const {
393   if (!DbgNode)
394     return false;
395   unsigned Tag = getTag();
396   if (Tag != dwarf::DW_TAG_APPLE_property) return false;
397   DIType Ty = getType();
398   if (!Ty.Verify()) return false;
399
400   // Don't worry about the rest of the strings for now.
401   return true;
402 }
403
404 /// Verify - Verify that a type descriptor is well formed.
405 bool DIType::Verify() const {
406   if (!DbgNode)
407     return false;
408   if (getContext() && !getContext().Verify())
409     return false;
410   unsigned Tag = getTag();
411   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
412       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
413       Tag != dwarf::DW_TAG_reference_type &&
414       Tag != dwarf::DW_TAG_rvalue_reference_type &&
415       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_vector_type &&
416       Tag != dwarf::DW_TAG_array_type &&
417       Tag != dwarf::DW_TAG_enumeration_type &&
418       Tag != dwarf::DW_TAG_subroutine_type &&
419       getFilename().empty())
420     return false;
421   return true;
422 }
423
424 /// Verify - Verify that a basic type descriptor is well formed.
425 bool DIBasicType::Verify() const {
426   return isBasicType();
427 }
428
429 /// Verify - Verify that a derived type descriptor is well formed.
430 bool DIDerivedType::Verify() const {
431   return isDerivedType();
432 }
433
434 /// Verify - Verify that a composite type descriptor is well formed.
435 bool DICompositeType::Verify() const {
436   if (!DbgNode)
437     return false;
438   if (getContext() && !getContext().Verify())
439     return false;
440
441   return true;
442 }
443
444 /// Verify - Verify that a subprogram descriptor is well formed.
445 bool DISubprogram::Verify() const {
446   if (!DbgNode)
447     return false;
448
449   if (getContext() && !getContext().Verify())
450     return false;
451
452   DICompositeType Ty = getType();
453   if (!Ty.Verify())
454     return false;
455   return true;
456 }
457
458 /// Verify - Verify that a global variable descriptor is well formed.
459 bool DIGlobalVariable::Verify() const {
460   if (!DbgNode)
461     return false;
462
463   if (getDisplayName().empty())
464     return false;
465
466   if (getContext() && !getContext().Verify())
467     return false;
468
469   DIType Ty = getType();
470   if (!Ty.Verify())
471     return false;
472
473   if (!getGlobal() && !getConstant())
474     return false;
475
476   return true;
477 }
478
479 /// Verify - Verify that a variable descriptor is well formed.
480 bool DIVariable::Verify() const {
481   if (!DbgNode)
482     return false;
483
484   if (getContext() && !getContext().Verify())
485     return false;
486
487   DIType Ty = getType();
488   if (!Ty.Verify())
489     return false;
490
491   return true;
492 }
493
494 /// Verify - Verify that a location descriptor is well formed.
495 bool DILocation::Verify() const {
496   if (!DbgNode)
497     return false;
498
499   return DbgNode->getNumOperands() == 4;
500 }
501
502 /// Verify - Verify that a namespace descriptor is well formed.
503 bool DINameSpace::Verify() const {
504   if (!DbgNode)
505     return false;
506   if (getName().empty())
507     return false;
508   return true;
509 }
510
511 /// getOriginalTypeSize - If this type is derived from a base type then
512 /// return base type size.
513 uint64_t DIDerivedType::getOriginalTypeSize() const {
514   unsigned Tag = getTag();
515
516   if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef &&
517       Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
518       Tag != dwarf::DW_TAG_restrict_type)
519     return getSizeInBits();
520
521   DIType BaseType = getTypeDerivedFrom();
522
523   // If this type is not derived from any type then take conservative approach.
524   if (!BaseType.isValid())
525     return getSizeInBits();
526
527   // If this is a derived type, go ahead and get the base type, unless it's a
528   // reference then it's just the size of the field. Pointer types have no need
529   // of this since they're a different type of qualification on the type.
530   if (BaseType.getTag() == dwarf::DW_TAG_reference_type ||
531       BaseType.getTag() == dwarf::DW_TAG_rvalue_reference_type)
532     return getSizeInBits();
533
534   if (BaseType.isDerivedType())
535     return DIDerivedType(BaseType).getOriginalTypeSize();
536
537   return BaseType.getSizeInBits();
538 }
539
540 /// getObjCProperty - Return property node, if this ivar is associated with one.
541 MDNode *DIDerivedType::getObjCProperty() const {
542   if (getVersion() <= LLVMDebugVersion11 || DbgNode->getNumOperands() <= 10)
543     return NULL;
544   return dyn_cast_or_null<MDNode>(DbgNode->getOperand(10));
545 }
546
547 /// isInlinedFnArgument - Return true if this variable provides debugging
548 /// information for an inlined function arguments.
549 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
550   assert(CurFn && "Invalid function");
551   if (!getContext().isSubprogram())
552     return false;
553   // This variable is not inlined function argument if its scope
554   // does not describe current function.
555   return !DISubprogram(getContext()).describes(CurFn);
556 }
557
558 /// describes - Return true if this subprogram provides debugging
559 /// information for the function F.
560 bool DISubprogram::describes(const Function *F) {
561   assert(F && "Invalid function");
562   if (F == getFunction())
563     return true;
564   StringRef Name = getLinkageName();
565   if (Name.empty())
566     Name = getName();
567   if (F->getName() == Name)
568     return true;
569   return false;
570 }
571
572 unsigned DISubprogram::isOptimized() const {
573   assert (DbgNode && "Invalid subprogram descriptor!");
574   if (DbgNode->getNumOperands() == 16)
575     return getUnsignedField(15);
576   return 0;
577 }
578
579 MDNode *DISubprogram::getVariablesNodes() const {
580   if (!DbgNode || DbgNode->getNumOperands() <= 19)
581     return NULL;
582   if (MDNode *Temp = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19)))
583     return dyn_cast_or_null<MDNode>(Temp->getOperand(0));
584   return NULL;
585 }
586
587 DIArray DISubprogram::getVariables() const {
588   if (!DbgNode || DbgNode->getNumOperands() <= 19)
589     return DIArray();
590   if (MDNode *T = dyn_cast_or_null<MDNode>(DbgNode->getOperand(19)))
591     if (MDNode *A = dyn_cast_or_null<MDNode>(T->getOperand(0)))
592       return DIArray(A);
593   return DIArray();
594 }
595
596 StringRef DIScope::getFilename() const {
597   if (!DbgNode)
598     return StringRef();
599   if (isLexicalBlockFile())
600     return DILexicalBlockFile(DbgNode).getFilename();
601   if (isLexicalBlock())
602     return DILexicalBlock(DbgNode).getFilename();
603   if (isSubprogram())
604     return DISubprogram(DbgNode).getFilename();
605   if (isCompileUnit())
606     return DICompileUnit(DbgNode).getFilename();
607   if (isNameSpace())
608     return DINameSpace(DbgNode).getFilename();
609   if (isType())
610     return DIType(DbgNode).getFilename();
611   if (isFile())
612     return DIFile(DbgNode).getFilename();
613   llvm_unreachable("Invalid DIScope!");
614 }
615
616 StringRef DIScope::getDirectory() const {
617   if (!DbgNode)
618     return StringRef();
619   if (isLexicalBlockFile())
620     return DILexicalBlockFile(DbgNode).getDirectory();
621   if (isLexicalBlock())
622     return DILexicalBlock(DbgNode).getDirectory();
623   if (isSubprogram())
624     return DISubprogram(DbgNode).getDirectory();
625   if (isCompileUnit())
626     return DICompileUnit(DbgNode).getDirectory();
627   if (isNameSpace())
628     return DINameSpace(DbgNode).getDirectory();
629   if (isType())
630     return DIType(DbgNode).getDirectory();
631   if (isFile())
632     return DIFile(DbgNode).getDirectory();
633   llvm_unreachable("Invalid DIScope!");
634 }
635
636 DIArray DICompileUnit::getEnumTypes() const {
637   if (!DbgNode || DbgNode->getNumOperands() < 14)
638     return DIArray();
639
640   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(10)))
641     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
642       return DIArray(A);
643   return DIArray();
644 }
645
646 DIArray DICompileUnit::getRetainedTypes() const {
647   if (!DbgNode || DbgNode->getNumOperands() < 14)
648     return DIArray();
649
650   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(11)))
651     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
652       return DIArray(A);
653   return DIArray();
654 }
655
656 DIArray DICompileUnit::getSubprograms() const {
657   if (!DbgNode || DbgNode->getNumOperands() < 14)
658     return DIArray();
659
660   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(12)))
661     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
662       return DIArray(A);
663   return DIArray();
664 }
665
666
667 DIArray DICompileUnit::getGlobalVariables() const {
668   if (!DbgNode || DbgNode->getNumOperands() < 14)
669     return DIArray();
670
671   if (MDNode *N = dyn_cast_or_null<MDNode>(DbgNode->getOperand(13)))
672     if (MDNode *A = dyn_cast_or_null<MDNode>(N->getOperand(0)))
673       return DIArray(A);
674   return DIArray();
675 }
676
677 /// fixupObjcLikeName - Replace contains special characters used
678 /// in a typical Objective-C names with '.' in a given string.
679 static void fixupObjcLikeName(StringRef Str, SmallVectorImpl<char> &Out) {
680   bool isObjCLike = false;
681   for (size_t i = 0, e = Str.size(); i < e; ++i) {
682     char C = Str[i];
683     if (C == '[')
684       isObjCLike = true;
685
686     if (isObjCLike && (C == '[' || C == ']' || C == ' ' || C == ':' ||
687                        C == '+' || C == '(' || C == ')'))
688       Out.push_back('.');
689     else
690       Out.push_back(C);
691   }
692 }
693
694 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is 
695 /// suitable to hold function specific information.
696 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, DISubprogram Fn) {
697   SmallString<32> Name = StringRef("llvm.dbg.lv.");
698   StringRef FName = "fn";
699   if (Fn.getFunction())
700     FName = Fn.getFunction()->getName();
701   else
702     FName = Fn.getName();
703   char One = '\1';
704   if (FName.startswith(StringRef(&One, 1)))
705     FName = FName.substr(1);
706   fixupObjcLikeName(FName, Name);
707   return M.getNamedMetadata(Name.str());
708 }
709
710 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
711 /// to hold function specific information.
712 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, DISubprogram Fn) {
713   SmallString<32> Name = StringRef("llvm.dbg.lv.");
714   StringRef FName = "fn";
715   if (Fn.getFunction())
716     FName = Fn.getFunction()->getName();
717   else
718     FName = Fn.getName();
719   char One = '\1';
720   if (FName.startswith(StringRef(&One, 1)))
721     FName = FName.substr(1);
722   fixupObjcLikeName(FName, Name);
723   
724   return M.getOrInsertNamedMetadata(Name.str());
725 }
726
727 /// createInlinedVariable - Create a new inlined variable based on current
728 /// variable.
729 /// @param DV            Current Variable.
730 /// @param InlinedScope  Location at current variable is inlined.
731 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
732                                        LLVMContext &VMContext) {
733   SmallVector<Value *, 16> Elts;
734   // Insert inlined scope as 7th element.
735   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
736     i == 7 ? Elts.push_back(InlinedScope) :
737              Elts.push_back(DV->getOperand(i));
738   return DIVariable(MDNode::get(VMContext, Elts));
739 }
740
741 /// cleanseInlinedVariable - Remove inlined scope from the variable.
742 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
743   SmallVector<Value *, 16> Elts;
744   // Insert inlined scope as 7th element.
745   for (unsigned i = 0, e = DV->getNumOperands(); i != e; ++i)
746     i == 7 ? 
747       Elts.push_back(Constant::getNullValue(Type::getInt32Ty(VMContext))):
748       Elts.push_back(DV->getOperand(i));
749   return DIVariable(MDNode::get(VMContext, Elts));
750 }
751
752 /// getDISubprogram - Find subprogram that is enclosing this scope.
753 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
754   DIDescriptor D(Scope);
755   if (D.isSubprogram())
756     return DISubprogram(Scope);
757
758   if (D.isLexicalBlockFile())
759     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
760   
761   if (D.isLexicalBlock())
762     return getDISubprogram(DILexicalBlock(Scope).getContext());
763
764   return DISubprogram();
765 }
766
767 /// getDICompositeType - Find underlying composite type.
768 DICompositeType llvm::getDICompositeType(DIType T) {
769   if (T.isCompositeType())
770     return DICompositeType(T);
771
772   if (T.isDerivedType())
773     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
774
775   return DICompositeType();
776 }
777
778 /// isSubprogramContext - Return true if Context is either a subprogram
779 /// or another context nested inside a subprogram.
780 bool llvm::isSubprogramContext(const MDNode *Context) {
781   if (!Context)
782     return false;
783   DIDescriptor D(Context);
784   if (D.isSubprogram())
785     return true;
786   if (D.isType())
787     return isSubprogramContext(DIType(Context).getContext());
788   return false;
789 }
790
791 //===----------------------------------------------------------------------===//
792 // DebugInfoFinder implementations.
793 //===----------------------------------------------------------------------===//
794
795 /// processModule - Process entire module and collect debug info.
796 void DebugInfoFinder::processModule(const Module &M) {
797   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
798     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
799       DICompileUnit CU(CU_Nodes->getOperand(i));
800       addCompileUnit(CU);
801       if (CU.getVersion() > LLVMDebugVersion10) {
802         DIArray GVs = CU.getGlobalVariables();
803         for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
804           DIGlobalVariable DIG(GVs.getElement(i));
805           if (addGlobalVariable(DIG))
806             processType(DIG.getType());
807         }
808         DIArray SPs = CU.getSubprograms();
809         for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
810           processSubprogram(DISubprogram(SPs.getElement(i)));
811         DIArray EnumTypes = CU.getEnumTypes();
812         for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
813           processType(DIType(EnumTypes.getElement(i)));
814         DIArray RetainedTypes = CU.getRetainedTypes();
815         for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
816           processType(DIType(RetainedTypes.getElement(i)));
817         return;
818       }
819     }
820   }
821
822   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
823     for (Function::const_iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
824       for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
825            ++BI) {
826         if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
827           processDeclare(DDI);
828
829         DebugLoc Loc = BI->getDebugLoc();
830         if (Loc.isUnknown())
831           continue;
832
833         LLVMContext &Ctx = BI->getContext();
834         DIDescriptor Scope(Loc.getScope(Ctx));
835
836         if (Scope.isCompileUnit())
837           addCompileUnit(DICompileUnit(Scope));
838         else if (Scope.isSubprogram())
839           processSubprogram(DISubprogram(Scope));
840         else if (Scope.isLexicalBlockFile()) {
841           DILexicalBlockFile DBF = DILexicalBlockFile(Scope);
842           processLexicalBlock(DILexicalBlock(DBF.getScope()));
843         }
844         else if (Scope.isLexicalBlock())
845           processLexicalBlock(DILexicalBlock(Scope));
846
847         if (MDNode *IA = Loc.getInlinedAt(Ctx))
848           processLocation(DILocation(IA));
849       }
850
851   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
852     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
853       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
854       if (addGlobalVariable(DIG)) {
855         if (DIG.getVersion() <= LLVMDebugVersion10)
856           addCompileUnit(DIG.getCompileUnit());
857         processType(DIG.getType());
858       }
859     }
860   }
861
862   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
863     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
864       processSubprogram(DISubprogram(NMD->getOperand(i)));
865 }
866
867 /// processLocation - Process DILocation.
868 void DebugInfoFinder::processLocation(DILocation Loc) {
869   if (!Loc.Verify()) return;
870   DIDescriptor S(Loc.getScope());
871   if (S.isCompileUnit())
872     addCompileUnit(DICompileUnit(S));
873   else if (S.isSubprogram())
874     processSubprogram(DISubprogram(S));
875   else if (S.isLexicalBlock())
876     processLexicalBlock(DILexicalBlock(S));
877   else if (S.isLexicalBlockFile()) {
878     DILexicalBlockFile DBF = DILexicalBlockFile(S);
879     processLexicalBlock(DILexicalBlock(DBF.getScope()));
880   }
881   processLocation(Loc.getOrigLocation());
882 }
883
884 /// processType - Process DIType.
885 void DebugInfoFinder::processType(DIType DT) {
886   if (!addType(DT))
887     return;
888   if (DT.getVersion() <= LLVMDebugVersion10)
889     addCompileUnit(DT.getCompileUnit());
890   if (DT.isCompositeType()) {
891     DICompositeType DCT(DT);
892     processType(DCT.getTypeDerivedFrom());
893     DIArray DA = DCT.getTypeArray();
894     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
895       DIDescriptor D = DA.getElement(i);
896       if (D.isType())
897         processType(DIType(D));
898       else if (D.isSubprogram())
899         processSubprogram(DISubprogram(D));
900     }
901   } else if (DT.isDerivedType()) {
902     DIDerivedType DDT(DT);
903     processType(DDT.getTypeDerivedFrom());
904   }
905 }
906
907 /// processLexicalBlock
908 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
909   DIScope Context = LB.getContext();
910   if (Context.isLexicalBlock())
911     return processLexicalBlock(DILexicalBlock(Context));
912   else if (Context.isLexicalBlockFile()) {
913     DILexicalBlockFile DBF = DILexicalBlockFile(Context);
914     return processLexicalBlock(DILexicalBlock(DBF.getScope()));
915   }
916   else
917     return processSubprogram(DISubprogram(Context));
918 }
919
920 /// processSubprogram - Process DISubprogram.
921 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
922   if (!addSubprogram(SP))
923     return;
924   if (SP.getVersion() <= LLVMDebugVersion10)
925     addCompileUnit(SP.getCompileUnit());
926   processType(SP.getType());
927 }
928
929 /// processDeclare - Process DbgDeclareInst.
930 void DebugInfoFinder::processDeclare(const DbgDeclareInst *DDI) {
931   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
932   if (!N) return;
933
934   DIDescriptor DV(N);
935   if (!DV.isVariable())
936     return;
937
938   if (!NodesSeen.insert(DV))
939     return;
940   if (DIVariable(N).getVersion() <= LLVMDebugVersion10)
941     addCompileUnit(DIVariable(N).getCompileUnit());
942   processType(DIVariable(N).getType());
943 }
944
945 /// addType - Add type into Tys.
946 bool DebugInfoFinder::addType(DIType DT) {
947   if (!DT.isValid())
948     return false;
949
950   if (!NodesSeen.insert(DT))
951     return false;
952
953   TYs.push_back(DT);
954   return true;
955 }
956
957 /// addCompileUnit - Add compile unit into CUs.
958 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
959   if (!CU.Verify())
960     return false;
961
962   if (!NodesSeen.insert(CU))
963     return false;
964
965   CUs.push_back(CU);
966   return true;
967 }
968
969 /// addGlobalVariable - Add global variable into GVs.
970 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
971   if (!DIDescriptor(DIG).isGlobalVariable())
972     return false;
973
974   if (!NodesSeen.insert(DIG))
975     return false;
976
977   GVs.push_back(DIG);
978   return true;
979 }
980
981 // addSubprogram - Add subprgoram into SPs.
982 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
983   if (!DIDescriptor(SP).isSubprogram())
984     return false;
985
986   if (!NodesSeen.insert(SP))
987     return false;
988
989   SPs.push_back(SP);
990   return true;
991 }
992
993 //===----------------------------------------------------------------------===//
994 // DIDescriptor: dump routines for all descriptors.
995 //===----------------------------------------------------------------------===//
996
997 /// dump - Print descriptor to dbgs() with a newline.
998 void DIDescriptor::dump() const {
999   print(dbgs()); dbgs() << '\n';
1000 }
1001
1002 /// print - Print descriptor.
1003 void DIDescriptor::print(raw_ostream &OS) const {
1004   if (!DbgNode) return;
1005
1006   if (const char *Tag = dwarf::TagString(getTag()))
1007     OS << "[ " << Tag << " ]";
1008
1009   if (this->isSubrange()) {
1010     DISubrange(DbgNode).printInternal(OS);
1011   } else if (this->isCompileUnit()) {
1012     DICompileUnit(DbgNode).printInternal(OS);
1013   } else if (this->isFile()) {
1014     DIFile(DbgNode).printInternal(OS);
1015   } else if (this->isEnumerator()) {
1016     DIEnumerator(DbgNode).printInternal(OS);
1017   } else if (this->isBasicType()) {
1018     DIType(DbgNode).printInternal(OS);
1019   } else if (this->isDerivedType()) {
1020     DIDerivedType(DbgNode).printInternal(OS);
1021   } else if (this->isCompositeType()) {
1022     DICompositeType(DbgNode).printInternal(OS);
1023   } else if (this->isSubprogram()) {
1024     DISubprogram(DbgNode).printInternal(OS);
1025   } else if (this->isGlobalVariable()) {
1026     DIGlobalVariable(DbgNode).printInternal(OS);
1027   } else if (this->isVariable()) {
1028     DIVariable(DbgNode).printInternal(OS);
1029   } else if (this->isObjCProperty()) {
1030     DIObjCProperty(DbgNode).printInternal(OS);
1031   } else if (this->isScope()) {
1032     DIScope(DbgNode).printInternal(OS);
1033   }
1034 }
1035
1036 void DISubrange::printInternal(raw_ostream &OS) const {
1037   OS << " [" << getLo() << ", " << getHi() << ']';
1038 }
1039
1040 void DIScope::printInternal(raw_ostream &OS) const {
1041   OS << " [" << getDirectory() << "/" << getFilename() << ']';
1042 }
1043
1044 void DICompileUnit::printInternal(raw_ostream &OS) const {
1045   DIScope::printInternal(OS);
1046   if (unsigned Lang = getLanguage())
1047     OS << " [" << dwarf::LanguageString(Lang) << ']';
1048 }
1049
1050 void DIEnumerator::printInternal(raw_ostream &OS) const {
1051   OS << " [" << getName() << " :: " << getEnumValue() << ']';
1052 }
1053
1054 void DIType::printInternal(raw_ostream &OS) const {
1055   if (!DbgNode) return;
1056
1057   StringRef Res = getName();
1058   if (!Res.empty())
1059     OS << " [" << Res << "]";
1060
1061   // TODO: Print context?
1062
1063   OS << " [line " << getLineNumber()
1064      << ", size " << getSizeInBits()
1065      << ", align " << getAlignInBits()
1066      << ", offset " << getOffsetInBits();
1067   if (isBasicType())
1068     if (const char *Enc = 
1069         dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
1070       OS << ", enc " << Enc;
1071   OS << "]";
1072
1073   if (isPrivate())
1074     OS << " [private]";
1075   else if (isProtected())
1076     OS << " [protected]";
1077
1078   if (isForwardDecl())
1079     OS << " [fwd]";
1080 }
1081
1082 void DIDerivedType::printInternal(raw_ostream &OS) const {
1083   DIType::printInternal(OS);
1084   OS << " [from " << getTypeDerivedFrom().getName() << ']';
1085 }
1086
1087 void DICompositeType::printInternal(raw_ostream &OS) const {
1088   DIType::printInternal(OS);
1089   DIArray A = getTypeArray();
1090   OS << " [" << A.getNumElements() << " elements]";
1091 }
1092
1093 void DISubprogram::printInternal(raw_ostream &OS) const {
1094   // TODO : Print context
1095   OS << " [line " << getLineNumber() << ']';
1096
1097   if (isLocalToUnit())
1098     OS << " [local]";
1099
1100   if (isDefinition())
1101     OS << " [def]";
1102
1103   if (getScopeLineNumber() != getLineNumber())
1104     OS << " [scope " << getScopeLineNumber() << "]";
1105
1106   StringRef Res = getName();
1107   if (!Res.empty())
1108     OS << " [" << Res << ']';
1109 }
1110
1111 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
1112   StringRef Res = getName();
1113   if (!Res.empty())
1114     OS << " [" << Res << ']';
1115
1116   OS << " [line " << getLineNumber() << ']';
1117
1118   // TODO : Print context
1119
1120   if (isLocalToUnit())
1121     OS << " [local]";
1122
1123   if (isDefinition())
1124     OS << " [def]";
1125 }
1126
1127 void DIVariable::printInternal(raw_ostream &OS) const {
1128   StringRef Res = getName();
1129   if (!Res.empty())
1130     OS << " [" << Res << ']';
1131
1132   OS << " [line " << getLineNumber() << ']';
1133 }
1134
1135 void DIObjCProperty::printInternal(raw_ostream &OS) const {
1136   StringRef Name = getObjCPropertyName();
1137   if (!Name.empty())
1138     OS << " [" << Name << ']';
1139
1140   OS << " [line " << getLineNumber()
1141      << ", properties " << getUnsignedField(6) << ']';
1142 }
1143
1144 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
1145                           const LLVMContext &Ctx) {
1146   if (!DL.isUnknown()) {          // Print source line info.
1147     DIScope Scope(DL.getScope(Ctx));
1148     // Omit the directory, because it's likely to be long and uninteresting.
1149     if (Scope.Verify())
1150       CommentOS << Scope.getFilename();
1151     else
1152       CommentOS << "<unknown>";
1153     CommentOS << ':' << DL.getLine();
1154     if (DL.getCol() != 0)
1155       CommentOS << ':' << DL.getCol();
1156     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
1157     if (!InlinedAtDL.isUnknown()) {
1158       CommentOS << " @[ ";
1159       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
1160       CommentOS << " ]";
1161     }
1162   }
1163 }
1164
1165 void DIVariable::printExtendedName(raw_ostream &OS) const {
1166   const LLVMContext &Ctx = DbgNode->getContext();
1167   StringRef Res = getName();
1168   if (!Res.empty())
1169     OS << Res << "," << getLineNumber();
1170   if (MDNode *InlinedAt = getInlinedAt()) {
1171     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
1172     if (!InlinedAtDL.isUnknown()) {
1173       OS << " @[";
1174       printDebugLoc(InlinedAtDL, OS, Ctx);
1175       OS << "]";
1176     }
1177   }
1178 }