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