Optimize MDNode to coallocate the operand list immediately
[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/Target/TargetMachine.h"  // FIXME: LAYERING VIOLATION!
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Intrinsics.h"
20 #include "llvm/IntrinsicInst.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/DebugLoc.h"
28 #include "llvm/Support/raw_ostream.h"
29 using namespace llvm;
30 using namespace llvm::dwarf;
31
32 //===----------------------------------------------------------------------===//
33 // DIDescriptor
34 //===----------------------------------------------------------------------===//
35
36 /// ValidDebugInfo - Return true if V represents valid debug info value.
37 /// FIXME : Add DIDescriptor.isValid()
38 bool DIDescriptor::ValidDebugInfo(MDNode *N, unsigned OptLevel) {
39   if (!N)
40     return false;
41
42   DIDescriptor DI(N);
43
44   // Check current version. Allow Version6 for now.
45   unsigned Version = DI.getVersion();
46   if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
47     return false;
48
49   switch (DI.getTag()) {
50   case DW_TAG_variable:
51     assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
52     break;
53   case DW_TAG_compile_unit:
54     assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
55     break;
56   case DW_TAG_subprogram:
57     assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
58     break;
59   case DW_TAG_lexical_block:
60     // FIXME: This interfers with the quality of generated code during
61     // optimization.
62     if (OptLevel != CodeGenOpt::None)
63       return false;
64     // FALLTHROUGH
65   default:
66     break;
67   }
68
69   return true;
70 }
71
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
73   DbgNode = N;
74
75   // If this is non-null, check to see if the Tag matches. If not, set to null.
76   if (N && getTag() != RequiredTag) {
77     DbgNode = 0;
78   }
79 }
80
81 StringRef 
82 DIDescriptor::getStringField(unsigned Elt) const {
83   if (DbgNode == 0)
84     return StringRef();
85
86   if (Elt < DbgNode->getNumElements())
87     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt)))
88       return MDS->getString();
89
90   return StringRef();
91 }
92
93 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
94   if (DbgNode == 0)
95     return 0;
96
97   if (Elt < DbgNode->getNumElements())
98     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
99       return CI->getZExtValue();
100
101   return 0;
102 }
103
104 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
105   if (DbgNode == 0)
106     return DIDescriptor();
107
108   if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
109     return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
110
111   return DIDescriptor();
112 }
113
114 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
115   if (DbgNode == 0)
116     return 0;
117
118   if (Elt < DbgNode->getNumElements())
119       return dyn_cast_or_null<GlobalVariable>(DbgNode->getElement(Elt));
120   return 0;
121 }
122
123 //===----------------------------------------------------------------------===//
124 // Predicates
125 //===----------------------------------------------------------------------===//
126
127 /// isBasicType - Return true if the specified tag is legal for
128 /// DIBasicType.
129 bool DIDescriptor::isBasicType() const {
130   assert(!isNull() && "Invalid descriptor!");
131   return getTag() == dwarf::DW_TAG_base_type;
132 }
133
134 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
135 bool DIDescriptor::isDerivedType() const {
136   assert(!isNull() && "Invalid descriptor!");
137   switch (getTag()) {
138   case dwarf::DW_TAG_typedef:
139   case dwarf::DW_TAG_pointer_type:
140   case dwarf::DW_TAG_reference_type:
141   case dwarf::DW_TAG_const_type:
142   case dwarf::DW_TAG_volatile_type:
143   case dwarf::DW_TAG_restrict_type:
144   case dwarf::DW_TAG_member:
145   case dwarf::DW_TAG_inheritance:
146     return true;
147   default:
148     // CompositeTypes are currently modelled as DerivedTypes.
149     return isCompositeType();
150   }
151 }
152
153 /// isCompositeType - Return true if the specified tag is legal for
154 /// DICompositeType.
155 bool DIDescriptor::isCompositeType() const {
156   assert(!isNull() && "Invalid descriptor!");
157   switch (getTag()) {
158   case dwarf::DW_TAG_array_type:
159   case dwarf::DW_TAG_structure_type:
160   case dwarf::DW_TAG_union_type:
161   case dwarf::DW_TAG_enumeration_type:
162   case dwarf::DW_TAG_vector_type:
163   case dwarf::DW_TAG_subroutine_type:
164   case dwarf::DW_TAG_class_type:
165     return true;
166   default:
167     return false;
168   }
169 }
170
171 /// isVariable - Return true if the specified tag is legal for DIVariable.
172 bool DIDescriptor::isVariable() const {
173   assert(!isNull() && "Invalid descriptor!");
174   switch (getTag()) {
175   case dwarf::DW_TAG_auto_variable:
176   case dwarf::DW_TAG_arg_variable:
177   case dwarf::DW_TAG_return_variable:
178     return true;
179   default:
180     return false;
181   }
182 }
183
184 /// isType - Return true if the specified tag is legal for DIType.
185 bool DIDescriptor::isType() const {
186   return isBasicType() || isCompositeType() || isDerivedType();
187 }
188
189 /// isSubprogram - Return true if the specified tag is legal for
190 /// DISubprogram.
191 bool DIDescriptor::isSubprogram() const {
192   assert(!isNull() && "Invalid descriptor!");
193   return getTag() == dwarf::DW_TAG_subprogram;
194 }
195
196 /// isGlobalVariable - Return true if the specified tag is legal for
197 /// DIGlobalVariable.
198 bool DIDescriptor::isGlobalVariable() const {
199   assert(!isNull() && "Invalid descriptor!");
200   return getTag() == dwarf::DW_TAG_variable;
201 }
202
203 /// isGlobal - Return true if the specified tag is legal for DIGlobal.
204 bool DIDescriptor::isGlobal() const {
205   return isGlobalVariable();
206 }
207
208 /// isScope - Return true if the specified tag is one of the scope
209 /// related tag.
210 bool DIDescriptor::isScope() const {
211   assert(!isNull() && "Invalid descriptor!");
212   switch (getTag()) {
213   case dwarf::DW_TAG_compile_unit:
214   case dwarf::DW_TAG_lexical_block:
215   case dwarf::DW_TAG_subprogram:
216   case dwarf::DW_TAG_namespace:
217     return true;
218   default:
219     break;
220   }
221   return false;
222 }
223
224 /// isCompileUnit - Return true if the specified tag is DW_TAG_compile_unit.
225 bool DIDescriptor::isCompileUnit() const {
226   assert(!isNull() && "Invalid descriptor!");
227   return getTag() == dwarf::DW_TAG_compile_unit;
228 }
229
230 /// isNameSpace - Return true if the specified tag is DW_TAG_namespace.
231 bool DIDescriptor::isNameSpace() const {
232   assert(!isNull() && "Invalid descriptor!");
233   return getTag() == dwarf::DW_TAG_namespace;
234 }
235
236 /// isLexicalBlock - Return true if the specified tag is DW_TAG_lexical_block.
237 bool DIDescriptor::isLexicalBlock() const {
238   assert(!isNull() && "Invalid descriptor!");
239   return getTag() == dwarf::DW_TAG_lexical_block;
240 }
241
242 /// isSubrange - Return true if the specified tag is DW_TAG_subrange_type.
243 bool DIDescriptor::isSubrange() const {
244   assert(!isNull() && "Invalid descriptor!");
245   return getTag() == dwarf::DW_TAG_subrange_type;
246 }
247
248 /// isEnumerator - Return true if the specified tag is DW_TAG_enumerator.
249 bool DIDescriptor::isEnumerator() const {
250   assert(!isNull() && "Invalid descriptor!");
251   return getTag() == dwarf::DW_TAG_enumerator;
252 }
253
254 //===----------------------------------------------------------------------===//
255 // Simple Descriptor Constructors and other Methods
256 //===----------------------------------------------------------------------===//
257
258 DIType::DIType(MDNode *N) : DIDescriptor(N) {
259   if (!N) return;
260   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
261     DbgNode = 0;
262   }
263 }
264
265 unsigned DIArray::getNumElements() const {
266   assert(DbgNode && "Invalid DIArray");
267   return DbgNode->getNumElements();
268 }
269
270 /// replaceAllUsesWith - Replace all uses of debug info referenced by
271 /// this descriptor. After this completes, the current debug info value
272 /// is erased.
273 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
274   if (isNull())
275     return;
276
277   assert(!D.isNull() && "Can not replace with null");
278
279   // Since we use a TrackingVH for the node, its easy for clients to manufacture
280   // legitimate situations where they want to replaceAllUsesWith() on something
281   // which, due to uniquing, has merged with the source. We shield clients from
282   // this detail by allowing a value to be replaced with replaceAllUsesWith()
283   // itself.
284   if (getNode() != D.getNode()) {
285     MDNode *Node = DbgNode;
286     Node->replaceAllUsesWith(D.getNode());
287     Node->destroy();
288   }
289 }
290
291 /// Verify - Verify that a compile unit is well formed.
292 bool DICompileUnit::Verify() const {
293   if (isNull())
294     return false;
295   StringRef N = getFilename();
296   if (N.empty())
297     return false;
298   // It is possible that directory and produce string is empty.
299   return true;
300 }
301
302 /// Verify - Verify that a type descriptor is well formed.
303 bool DIType::Verify() const {
304   if (isNull())
305     return false;
306   if (getContext().isNull())
307     return false;
308
309   DICompileUnit CU = getCompileUnit();
310   if (!CU.isNull() && !CU.Verify())
311     return false;
312   return true;
313 }
314
315 /// Verify - Verify that a composite type descriptor is well formed.
316 bool DICompositeType::Verify() const {
317   if (isNull())
318     return false;
319   if (getContext().isNull())
320     return false;
321
322   DICompileUnit CU = getCompileUnit();
323   if (!CU.isNull() && !CU.Verify())
324     return false;
325   return true;
326 }
327
328 /// Verify - Verify that a subprogram descriptor is well formed.
329 bool DISubprogram::Verify() const {
330   if (isNull())
331     return false;
332
333   if (getContext().isNull())
334     return false;
335
336   DICompileUnit CU = getCompileUnit();
337   if (!CU.Verify())
338     return false;
339
340   DICompositeType Ty = getType();
341   if (!Ty.isNull() && !Ty.Verify())
342     return false;
343   return true;
344 }
345
346 /// Verify - Verify that a global variable descriptor is well formed.
347 bool DIGlobalVariable::Verify() const {
348   if (isNull())
349     return false;
350
351   if (getDisplayName().empty())
352     return false;
353
354   if (getContext().isNull())
355     return false;
356
357   DICompileUnit CU = getCompileUnit();
358   if (!CU.isNull() && !CU.Verify())
359     return false;
360
361   DIType Ty = getType();
362   if (!Ty.Verify())
363     return false;
364
365   if (!getGlobal())
366     return false;
367
368   return true;
369 }
370
371 /// Verify - Verify that a variable descriptor is well formed.
372 bool DIVariable::Verify() const {
373   if (isNull())
374     return false;
375
376   if (getContext().isNull())
377     return false;
378
379   DIType Ty = getType();
380   if (!Ty.Verify())
381     return false;
382
383   return true;
384 }
385
386 /// getOriginalTypeSize - If this type is derived from a base type then
387 /// return base type size.
388 uint64_t DIDerivedType::getOriginalTypeSize() const {
389   unsigned Tag = getTag();
390   if (Tag == dwarf::DW_TAG_member || Tag == dwarf::DW_TAG_typedef ||
391       Tag == dwarf::DW_TAG_const_type || Tag == dwarf::DW_TAG_volatile_type ||
392       Tag == dwarf::DW_TAG_restrict_type) {
393     DIType BaseType = getTypeDerivedFrom();
394     // If this type is not derived from any type then take conservative 
395     // approach.
396     if (BaseType.isNull())
397       return getSizeInBits();
398     if (BaseType.isDerivedType())
399       return DIDerivedType(BaseType.getNode()).getOriginalTypeSize();
400     else
401       return BaseType.getSizeInBits();
402   }
403     
404   return getSizeInBits();
405 }
406
407 /// describes - Return true if this subprogram provides debugging
408 /// information for the function F.
409 bool DISubprogram::describes(const Function *F) {
410   assert(F && "Invalid function");
411   StringRef Name = getLinkageName();
412   if (Name.empty())
413     Name = getName();
414   if (F->getName() == Name)
415     return true;
416   return false;
417 }
418
419 StringRef DIScope::getFilename() const {
420   if (isLexicalBlock()) 
421     return DILexicalBlock(DbgNode).getFilename();
422   if (isSubprogram())
423     return DISubprogram(DbgNode).getFilename();
424   if (isCompileUnit())
425     return DICompileUnit(DbgNode).getFilename();
426   if (isNameSpace())
427     return DINameSpace(DbgNode).getFilename();
428   assert(0 && "Invalid DIScope!");
429   return StringRef();
430 }
431
432 StringRef DIScope::getDirectory() const {
433   if (isLexicalBlock()) 
434     return DILexicalBlock(DbgNode).getDirectory();
435   if (isSubprogram())
436     return DISubprogram(DbgNode).getDirectory();
437   if (isCompileUnit())
438     return DICompileUnit(DbgNode).getDirectory();
439   if (isNameSpace())
440     return DINameSpace(DbgNode).getDirectory();
441   assert(0 && "Invalid DIScope!");
442   return StringRef();
443 }
444
445 //===----------------------------------------------------------------------===//
446 // DIDescriptor: dump routines for all descriptors.
447 //===----------------------------------------------------------------------===//
448
449
450 /// dump - Print descriptor.
451 void DIDescriptor::dump() const {
452   dbgs() << "[" << dwarf::TagString(getTag()) << "] ";
453   dbgs().write_hex((intptr_t) &*DbgNode) << ']';
454 }
455
456 /// dump - Print compile unit.
457 void DICompileUnit::dump() const {
458   if (getLanguage())
459     dbgs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
460
461   dbgs() << " [" << getDirectory() << "/" << getFilename() << " ]";
462 }
463
464 /// dump - Print type.
465 void DIType::dump() const {
466   if (isNull()) return;
467
468   StringRef Res = getName();
469   if (!Res.empty())
470     dbgs() << " [" << Res << "] ";
471
472   unsigned Tag = getTag();
473   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
474
475   // TODO : Print context
476   getCompileUnit().dump();
477   dbgs() << " ["
478          << getLineNumber() << ", "
479          << getSizeInBits() << ", "
480          << getAlignInBits() << ", "
481          << getOffsetInBits()
482          << "] ";
483
484   if (isPrivate())
485     dbgs() << " [private] ";
486   else if (isProtected())
487     dbgs() << " [protected] ";
488
489   if (isForwardDecl())
490     dbgs() << " [fwd] ";
491
492   if (isBasicType())
493     DIBasicType(DbgNode).dump();
494   else if (isDerivedType())
495     DIDerivedType(DbgNode).dump();
496   else if (isCompositeType())
497     DICompositeType(DbgNode).dump();
498   else {
499     dbgs() << "Invalid DIType\n";
500     return;
501   }
502
503   dbgs() << "\n";
504 }
505
506 /// dump - Print basic type.
507 void DIBasicType::dump() const {
508   dbgs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
509 }
510
511 /// dump - Print derived type.
512 void DIDerivedType::dump() const {
513   dbgs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
514 }
515
516 /// dump - Print composite type.
517 void DICompositeType::dump() const {
518   DIArray A = getTypeArray();
519   if (A.isNull())
520     return;
521   dbgs() << " [" << A.getNumElements() << " elements]";
522 }
523
524 /// dump - Print global.
525 void DIGlobal::dump() const {
526   StringRef Res = getName();
527   if (!Res.empty())
528     dbgs() << " [" << Res << "] ";
529
530   unsigned Tag = getTag();
531   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
532
533   // TODO : Print context
534   getCompileUnit().dump();
535   dbgs() << " [" << getLineNumber() << "] ";
536
537   if (isLocalToUnit())
538     dbgs() << " [local] ";
539
540   if (isDefinition())
541     dbgs() << " [def] ";
542
543   if (isGlobalVariable())
544     DIGlobalVariable(DbgNode).dump();
545
546   dbgs() << "\n";
547 }
548
549 /// dump - Print subprogram.
550 void DISubprogram::dump() const {
551   StringRef Res = getName();
552   if (!Res.empty())
553     dbgs() << " [" << Res << "] ";
554
555   unsigned Tag = getTag();
556   dbgs() << " [" << dwarf::TagString(Tag) << "] ";
557
558   // TODO : Print context
559   getCompileUnit().dump();
560   dbgs() << " [" << getLineNumber() << "] ";
561
562   if (isLocalToUnit())
563     dbgs() << " [local] ";
564
565   if (isDefinition())
566     dbgs() << " [def] ";
567
568   dbgs() << "\n";
569 }
570
571 /// dump - Print global variable.
572 void DIGlobalVariable::dump() const {
573   dbgs() << " [";
574   getGlobal()->dump();
575   dbgs() << "] ";
576 }
577
578 /// dump - Print variable.
579 void DIVariable::dump() const {
580   StringRef Res = getName();
581   if (!Res.empty())
582     dbgs() << " [" << Res << "] ";
583
584   getCompileUnit().dump();
585   dbgs() << " [" << getLineNumber() << "] ";
586   getType().dump();
587   dbgs() << "\n";
588
589   // FIXME: Dump complex addresses
590 }
591
592 //===----------------------------------------------------------------------===//
593 // DIFactory: Basic Helpers
594 //===----------------------------------------------------------------------===//
595
596 DIFactory::DIFactory(Module &m)
597   : M(m), VMContext(M.getContext()), DeclareFn(0) {
598   EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
599 }
600
601 Constant *DIFactory::GetTagConstant(unsigned TAG) {
602   assert((TAG & LLVMDebugVersionMask) == 0 &&
603          "Tag too large for debug encoding!");
604   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
605 }
606
607 //===----------------------------------------------------------------------===//
608 // DIFactory: Primary Constructors
609 //===----------------------------------------------------------------------===//
610
611 /// GetOrCreateArray - Create an descriptor for an array of descriptors.
612 /// This implicitly uniques the arrays created.
613 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
614   SmallVector<Value*, 16> Elts;
615
616   if (NumTys == 0)
617     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
618   else
619     for (unsigned i = 0; i != NumTys; ++i)
620       Elts.push_back(Tys[i].getNode());
621
622   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
623 }
624
625 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
626 /// implicitly uniques the values returned.
627 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
628   Value *Elts[] = {
629     GetTagConstant(dwarf::DW_TAG_subrange_type),
630     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
631     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
632   };
633
634   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
635 }
636
637
638
639 /// CreateCompileUnit - Create a new descriptor for the specified compile
640 /// unit.  Note that this does not unique compile units within the module.
641 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
642                                            StringRef Filename,
643                                            StringRef Directory,
644                                            StringRef Producer,
645                                            bool isMain,
646                                            bool isOptimized,
647                                            StringRef Flags,
648                                            unsigned RunTimeVer) {
649   Value *Elts[] = {
650     GetTagConstant(dwarf::DW_TAG_compile_unit),
651     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
652     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
653     MDString::get(VMContext, Filename),
654     MDString::get(VMContext, Directory),
655     MDString::get(VMContext, Producer),
656     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
657     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
658     MDString::get(VMContext, Flags),
659     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
660   };
661
662   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
663 }
664
665 /// CreateEnumerator - Create a single enumerator value.
666 DIEnumerator DIFactory::CreateEnumerator(StringRef Name, uint64_t Val){
667   Value *Elts[] = {
668     GetTagConstant(dwarf::DW_TAG_enumerator),
669     MDString::get(VMContext, Name),
670     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
671   };
672   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
673 }
674
675
676 /// CreateBasicType - Create a basic type like int, float, etc.
677 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
678                                        StringRef Name,
679                                        DICompileUnit CompileUnit,
680                                        unsigned LineNumber,
681                                        uint64_t SizeInBits,
682                                        uint64_t AlignInBits,
683                                        uint64_t OffsetInBits, unsigned Flags,
684                                        unsigned Encoding) {
685   Value *Elts[] = {
686     GetTagConstant(dwarf::DW_TAG_base_type),
687     Context.getNode(),
688     MDString::get(VMContext, Name),
689     CompileUnit.getNode(),
690     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
691     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
692     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
693     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
694     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
695     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
696   };
697   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
698 }
699
700
701 /// CreateBasicType - Create a basic type like int, float, etc.
702 DIBasicType DIFactory::CreateBasicTypeEx(DIDescriptor Context,
703                                          StringRef Name,
704                                          DICompileUnit CompileUnit,
705                                          unsigned LineNumber,
706                                          Constant *SizeInBits,
707                                          Constant *AlignInBits,
708                                          Constant *OffsetInBits, unsigned Flags,
709                                          unsigned Encoding) {
710   Value *Elts[] = {
711     GetTagConstant(dwarf::DW_TAG_base_type),
712     Context.getNode(),
713     MDString::get(VMContext, Name),
714     CompileUnit.getNode(),
715     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
716     SizeInBits,
717     AlignInBits,
718     OffsetInBits,
719     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
720     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
721   };
722   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
723 }
724
725
726 /// CreateDerivedType - Create a derived type like const qualified type,
727 /// pointer, typedef, etc.
728 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
729                                            DIDescriptor Context,
730                                            StringRef Name,
731                                            DICompileUnit CompileUnit,
732                                            unsigned LineNumber,
733                                            uint64_t SizeInBits,
734                                            uint64_t AlignInBits,
735                                            uint64_t OffsetInBits,
736                                            unsigned Flags,
737                                            DIType DerivedFrom) {
738   Value *Elts[] = {
739     GetTagConstant(Tag),
740     Context.getNode(),
741     MDString::get(VMContext, Name),
742     CompileUnit.getNode(),
743     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
744     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
745     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
746     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
747     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
748     DerivedFrom.getNode(),
749   };
750   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
751 }
752
753
754 /// CreateDerivedType - Create a derived type like const qualified type,
755 /// pointer, typedef, etc.
756 DIDerivedType DIFactory::CreateDerivedTypeEx(unsigned Tag,
757                                              DIDescriptor Context,
758                                              StringRef Name,
759                                              DICompileUnit CompileUnit,
760                                              unsigned LineNumber,
761                                              Constant *SizeInBits,
762                                              Constant *AlignInBits,
763                                              Constant *OffsetInBits,
764                                              unsigned Flags,
765                                              DIType DerivedFrom) {
766   Value *Elts[] = {
767     GetTagConstant(Tag),
768     Context.getNode(),
769     MDString::get(VMContext, Name),
770     CompileUnit.getNode(),
771     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
772     SizeInBits,
773     AlignInBits,
774     OffsetInBits,
775     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
776     DerivedFrom.getNode(),
777   };
778   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
779 }
780
781
782 /// CreateCompositeType - Create a composite type like array, struct, etc.
783 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
784                                                DIDescriptor Context,
785                                                StringRef Name,
786                                                DICompileUnit CompileUnit,
787                                                unsigned LineNumber,
788                                                uint64_t SizeInBits,
789                                                uint64_t AlignInBits,
790                                                uint64_t OffsetInBits,
791                                                unsigned Flags,
792                                                DIType DerivedFrom,
793                                                DIArray Elements,
794                                                unsigned RuntimeLang) {
795
796   Value *Elts[] = {
797     GetTagConstant(Tag),
798     Context.getNode(),
799     MDString::get(VMContext, Name),
800     CompileUnit.getNode(),
801     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
802     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
803     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
804     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
805     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
806     DerivedFrom.getNode(),
807     Elements.getNode(),
808     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
809   };
810   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
811 }
812
813
814 /// CreateCompositeType - Create a composite type like array, struct, etc.
815 DICompositeType DIFactory::CreateCompositeTypeEx(unsigned Tag,
816                                                  DIDescriptor Context,
817                                                  StringRef Name,
818                                                  DICompileUnit CompileUnit,
819                                                  unsigned LineNumber,
820                                                  Constant *SizeInBits,
821                                                  Constant *AlignInBits,
822                                                  Constant *OffsetInBits,
823                                                  unsigned Flags,
824                                                  DIType DerivedFrom,
825                                                  DIArray Elements,
826                                                  unsigned RuntimeLang) {
827
828   Value *Elts[] = {
829     GetTagConstant(Tag),
830     Context.getNode(),
831     MDString::get(VMContext, Name),
832     CompileUnit.getNode(),
833     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
834     SizeInBits,
835     AlignInBits,
836     OffsetInBits,
837     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
838     DerivedFrom.getNode(),
839     Elements.getNode(),
840     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
841   };
842   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
843 }
844
845
846 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
847 /// See comments in DISubprogram for descriptions of these fields.  This
848 /// method does not unique the generated descriptors.
849 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context,
850                                          StringRef Name,
851                                          StringRef DisplayName,
852                                          StringRef LinkageName,
853                                          DICompileUnit CompileUnit,
854                                          unsigned LineNo, DIType Type,
855                                          bool isLocalToUnit,
856                                          bool isDefinition,
857                                          unsigned VK, unsigned VIndex,
858                                          DIType ContainingType) {
859
860   Value *Elts[] = {
861     GetTagConstant(dwarf::DW_TAG_subprogram),
862     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
863     Context.getNode(),
864     MDString::get(VMContext, Name),
865     MDString::get(VMContext, DisplayName),
866     MDString::get(VMContext, LinkageName),
867     CompileUnit.getNode(),
868     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
869     Type.getNode(),
870     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
871     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
872     ConstantInt::get(Type::getInt32Ty(VMContext), (unsigned)VK),
873     ConstantInt::get(Type::getInt32Ty(VMContext), VIndex),
874     ContainingType.getNode()
875   };
876   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
877 }
878
879 /// CreateSubprogramDefinition - Create new subprogram descriptor for the
880 /// given declaration. 
881 DISubprogram DIFactory::CreateSubprogramDefinition(DISubprogram &SPDeclaration) {
882   if (SPDeclaration.isDefinition())
883     return DISubprogram(SPDeclaration.getNode());
884
885   MDNode *DeclNode = SPDeclaration.getNode();
886   Value *Elts[] = {
887     GetTagConstant(dwarf::DW_TAG_subprogram),
888     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
889     DeclNode->getElement(2), // Context
890     DeclNode->getElement(3), // Name
891     DeclNode->getElement(4), // DisplayName
892     DeclNode->getElement(5), // LinkageName
893     DeclNode->getElement(6), // CompileUnit
894     DeclNode->getElement(7), // LineNo
895     DeclNode->getElement(8), // Type
896     DeclNode->getElement(9), // isLocalToUnit
897     ConstantInt::get(Type::getInt1Ty(VMContext), true),
898     DeclNode->getElement(11), // Virtuality
899     DeclNode->getElement(12), // VIndex
900     DeclNode->getElement(13)  // Containting Type
901   };
902   return DISubprogram(MDNode::get(VMContext, &Elts[0], 14));
903 }
904
905 /// CreateGlobalVariable - Create a new descriptor for the specified global.
906 DIGlobalVariable
907 DIFactory::CreateGlobalVariable(DIDescriptor Context, StringRef Name,
908                                 StringRef DisplayName,
909                                 StringRef LinkageName,
910                                 DICompileUnit CompileUnit,
911                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
912                                 bool isDefinition, llvm::GlobalVariable *Val) {
913   Value *Elts[] = {
914     GetTagConstant(dwarf::DW_TAG_variable),
915     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
916     Context.getNode(),
917     MDString::get(VMContext, Name),
918     MDString::get(VMContext, DisplayName),
919     MDString::get(VMContext, LinkageName),
920     CompileUnit.getNode(),
921     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
922     Type.getNode(),
923     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
924     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
925     Val
926   };
927
928   Value *const *Vs = &Elts[0];
929   MDNode *Node = MDNode::get(VMContext,Vs, 12);
930
931   // Create a named metadata so that we do not lose this mdnode.
932   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
933   NMD->addElement(Node);
934
935   return DIGlobalVariable(Node);
936 }
937
938
939 /// CreateVariable - Create a new descriptor for the specified variable.
940 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
941                                      StringRef Name,
942                                      DICompileUnit CompileUnit, unsigned LineNo,
943                                      DIType Type) {
944   Value *Elts[] = {
945     GetTagConstant(Tag),
946     Context.getNode(),
947     MDString::get(VMContext, Name),
948     CompileUnit.getNode(),
949     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
950     Type.getNode(),
951   };
952   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
953 }
954
955
956 /// CreateComplexVariable - Create a new descriptor for the specified variable
957 /// which has a complex address expression for its address.
958 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
959                                             const std::string &Name,
960                                             DICompileUnit CompileUnit,
961                                             unsigned LineNo,
962                                    DIType Type, SmallVector<Value *, 9> &addr) {
963   SmallVector<Value *, 9> Elts;
964   Elts.push_back(GetTagConstant(Tag));
965   Elts.push_back(Context.getNode());
966   Elts.push_back(MDString::get(VMContext, Name));
967   Elts.push_back(CompileUnit.getNode());
968   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
969   Elts.push_back(Type.getNode());
970   Elts.insert(Elts.end(), addr.begin(), addr.end());
971
972   return DIVariable(MDNode::get(VMContext, &Elts[0], 6+addr.size()));
973 }
974
975
976 /// CreateBlock - This creates a descriptor for a lexical block with the
977 /// specified parent VMContext.
978 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context) {
979   Value *Elts[] = {
980     GetTagConstant(dwarf::DW_TAG_lexical_block),
981     Context.getNode()
982   };
983   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 2));
984 }
985
986 /// CreateNameSpace - This creates new descriptor for a namespace
987 /// with the specified parent context.
988 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
989                                        DICompileUnit CompileUnit, 
990                                        unsigned LineNo) {
991   Value *Elts[] = {
992     GetTagConstant(dwarf::DW_TAG_namespace),
993     Context.getNode(),
994     MDString::get(VMContext, Name),
995     CompileUnit.getNode(),
996     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
997   };
998   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
999 }
1000
1001 /// CreateLocation - Creates a debug info location.
1002 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1003                                      DIScope S, DILocation OrigLoc) {
1004   Value *Elts[] = {
1005     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1006     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1007     S.getNode(),
1008     OrigLoc.getNode(),
1009   };
1010   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1011 }
1012
1013 /// CreateLocation - Creates a debug info location.
1014 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1015                                      DIScope S, MDNode *OrigLoc) {
1016  Value *Elts[] = {
1017     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1018     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1019     S.getNode(),
1020     OrigLoc
1021   };
1022   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1023 }
1024
1025 //===----------------------------------------------------------------------===//
1026 // DIFactory: Routines for inserting code into a function
1027 //===----------------------------------------------------------------------===//
1028
1029 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1030 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1031                               Instruction *InsertBefore) {
1032   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1033   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertBefore);
1034
1035   if (!DeclareFn)
1036     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1037
1038   Value *Args[] = { Storage, D.getNode() };
1039   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1040 }
1041
1042 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1043 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1044                               BasicBlock *InsertAtEnd) {
1045   // Cast the storage to a {}* for the call to llvm.dbg.declare.
1046   Storage = new BitCastInst(Storage, EmptyStructPtr, "", InsertAtEnd);
1047
1048   if (!DeclareFn)
1049     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1050
1051   Value *Args[] = { Storage, D.getNode() };
1052   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);
1053 }
1054
1055 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1056 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1057                                                 DIVariable D,
1058                                                 Instruction *InsertBefore) {
1059   assert(V && "no value passed to dbg.value");
1060   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1061          "offset must be i64");
1062   if (!ValueFn)
1063     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1064
1065   Value *Elts[] = { V };
1066   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1067                     D.getNode() };
1068   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1069 }
1070
1071 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1072 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, Value *Offset,
1073                                                 DIVariable D,
1074                                                 BasicBlock *InsertAtEnd) {
1075   assert(V && "no value passed to dbg.value");
1076   assert(Offset->getType() == Type::getInt64Ty(V->getContext()) &&
1077          "offset must be i64");
1078   if (!ValueFn)
1079     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1080
1081   Value *Elts[] = { V };
1082   Value *Args[] = { MDNode::get(V->getContext(), Elts, 1), Offset,
1083                     D.getNode() };
1084   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1085 }
1086
1087 //===----------------------------------------------------------------------===//
1088 // DebugInfoFinder implementations.
1089 //===----------------------------------------------------------------------===//
1090
1091 /// processModule - Process entire module and collect debug info.
1092 void DebugInfoFinder::processModule(Module &M) {
1093   unsigned MDDbgKind = M.getMDKindID("dbg");
1094
1095   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1096     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1097       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1098            ++BI) {
1099         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1100           processDeclare(DDI);
1101         else if (MDNode *L = BI->getMetadata(MDDbgKind)) 
1102           processLocation(DILocation(L));
1103       }
1104
1105   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
1106   if (!NMD)
1107     return;
1108
1109   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1110     DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
1111     if (addGlobalVariable(DIG)) {
1112       addCompileUnit(DIG.getCompileUnit());
1113       processType(DIG.getType());
1114     }
1115   }
1116 }
1117
1118 /// processLocation - Process DILocation.
1119 void DebugInfoFinder::processLocation(DILocation Loc) {
1120   if (Loc.isNull()) return;
1121   DIScope S(Loc.getScope().getNode());
1122   if (S.isNull()) return;
1123   if (S.isCompileUnit())
1124     addCompileUnit(DICompileUnit(S.getNode()));
1125   else if (S.isSubprogram())
1126     processSubprogram(DISubprogram(S.getNode()));
1127   else if (S.isLexicalBlock())
1128     processLexicalBlock(DILexicalBlock(S.getNode()));
1129   processLocation(Loc.getOrigLocation());
1130 }
1131
1132 /// processType - Process DIType.
1133 void DebugInfoFinder::processType(DIType DT) {
1134   if (!addType(DT))
1135     return;
1136
1137   addCompileUnit(DT.getCompileUnit());
1138   if (DT.isCompositeType()) {
1139     DICompositeType DCT(DT.getNode());
1140     processType(DCT.getTypeDerivedFrom());
1141     DIArray DA = DCT.getTypeArray();
1142     if (!DA.isNull())
1143       for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1144         DIDescriptor D = DA.getElement(i);
1145         DIType TypeE = DIType(D.getNode());
1146         if (!TypeE.isNull())
1147           processType(TypeE);
1148         else
1149           processSubprogram(DISubprogram(D.getNode()));
1150       }
1151   } else if (DT.isDerivedType()) {
1152     DIDerivedType DDT(DT.getNode());
1153     if (!DDT.isNull())
1154       processType(DDT.getTypeDerivedFrom());
1155   }
1156 }
1157
1158 /// processLexicalBlock
1159 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1160   if (LB.isNull())
1161     return;
1162   DIScope Context = LB.getContext();
1163   if (Context.isLexicalBlock())
1164     return processLexicalBlock(DILexicalBlock(Context.getNode()));
1165   else
1166     return processSubprogram(DISubprogram(Context.getNode()));
1167 }
1168
1169 /// processSubprogram - Process DISubprogram.
1170 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1171   if (SP.isNull())
1172     return;
1173   if (!addSubprogram(SP))
1174     return;
1175   addCompileUnit(SP.getCompileUnit());
1176   processType(SP.getType());
1177 }
1178
1179 /// processDeclare - Process DbgDeclareInst.
1180 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1181   DIVariable DV(cast<MDNode>(DDI->getVariable()));
1182   if (DV.isNull())
1183     return;
1184
1185   if (!NodesSeen.insert(DV.getNode()))
1186     return;
1187
1188   addCompileUnit(DV.getCompileUnit());
1189   processType(DV.getType());
1190 }
1191
1192 /// addType - Add type into Tys.
1193 bool DebugInfoFinder::addType(DIType DT) {
1194   if (DT.isNull())
1195     return false;
1196
1197   if (!NodesSeen.insert(DT.getNode()))
1198     return false;
1199
1200   TYs.push_back(DT.getNode());
1201   return true;
1202 }
1203
1204 /// addCompileUnit - Add compile unit into CUs.
1205 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1206   if (CU.isNull())
1207     return false;
1208
1209   if (!NodesSeen.insert(CU.getNode()))
1210     return false;
1211
1212   CUs.push_back(CU.getNode());
1213   return true;
1214 }
1215
1216 /// addGlobalVariable - Add global variable into GVs.
1217 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1218   if (DIG.isNull())
1219     return false;
1220
1221   if (!NodesSeen.insert(DIG.getNode()))
1222     return false;
1223
1224   GVs.push_back(DIG.getNode());
1225   return true;
1226 }
1227
1228 // addSubprogram - Add subprgoram into SPs.
1229 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1230   if (SP.isNull())
1231     return false;
1232
1233   if (!NodesSeen.insert(SP.getNode()))
1234     return false;
1235
1236   SPs.push_back(SP.getNode());
1237   return true;
1238 }
1239
1240 /// findStopPoint - Find the stoppoint coressponding to this instruction, that
1241 /// is the stoppoint that dominates this instruction.
1242 const DbgStopPointInst *llvm::findStopPoint(const Instruction *Inst) {
1243   if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
1244     return DSI;
1245
1246   const BasicBlock *BB = Inst->getParent();
1247   BasicBlock::const_iterator I = Inst, B;
1248   while (BB) {
1249     B = BB->begin();
1250
1251     // A BB consisting only of a terminator can't have a stoppoint.
1252     while (I != B) {
1253       --I;
1254       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1255         return DSI;
1256     }
1257
1258     // This BB didn't have a stoppoint: if there is only one predecessor, look
1259     // for a stoppoint there. We could use getIDom(), but that would require
1260     // dominator info.
1261     BB = I->getParent()->getUniquePredecessor();
1262     if (BB)
1263       I = BB->getTerminator();
1264   }
1265
1266   return 0;
1267 }
1268
1269 /// findBBStopPoint - Find the stoppoint corresponding to first real
1270 /// (non-debug intrinsic) instruction in this Basic Block, and return the
1271 /// stoppoint for it.
1272 const DbgStopPointInst *llvm::findBBStopPoint(const BasicBlock *BB) {
1273   for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1274     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1275       return DSI;
1276
1277   // Fallback to looking for stoppoint of unique predecessor. Useful if this
1278   // BB contains no stoppoints, but unique predecessor does.
1279   BB = BB->getUniquePredecessor();
1280   if (BB)
1281     return findStopPoint(BB->getTerminator());
1282
1283   return 0;
1284 }
1285
1286 Value *llvm::findDbgGlobalDeclare(GlobalVariable *V) {
1287   const Module *M = V->getParent();
1288   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1289   if (!NMD)
1290     return 0;
1291
1292   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1293     DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1294     if (DIG.isNull())
1295       continue;
1296     if (DIG.getGlobal() == V)
1297       return DIG.getNode();
1298   }
1299   return 0;
1300 }
1301
1302 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1303 /// It looks through pointer casts too.
1304 const DbgDeclareInst *llvm::findDbgDeclare(const Value *V, bool stripCasts) {
1305   if (stripCasts) {
1306     V = V->stripPointerCasts();
1307
1308     // Look for the bitcast.
1309     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1310           I != E; ++I)
1311       if (isa<BitCastInst>(I)) {
1312         const DbgDeclareInst *DDI = findDbgDeclare(*I, false);
1313         if (DDI) return DDI;
1314       }
1315     return 0;
1316   }
1317
1318   // Find llvm.dbg.declare among uses of the instruction.
1319   for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1320         I != E; ++I)
1321     if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1322       return DDI;
1323
1324   return 0;
1325 }
1326
1327 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1328                            std::string &Type, unsigned &LineNo,
1329                            std::string &File, std::string &Dir) {
1330   DICompileUnit Unit;
1331   DIType TypeD;
1332
1333   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1334     Value *DIGV = findDbgGlobalDeclare(GV);
1335     if (!DIGV) return false;
1336     DIGlobalVariable Var(cast<MDNode>(DIGV));
1337
1338     StringRef D = Var.getDisplayName();
1339     if (!D.empty())
1340       DisplayName = D;
1341     LineNo = Var.getLineNumber();
1342     Unit = Var.getCompileUnit();
1343     TypeD = Var.getType();
1344   } else {
1345     const DbgDeclareInst *DDI = findDbgDeclare(V);
1346     if (!DDI) return false;
1347     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1348
1349     StringRef D = Var.getName();
1350     if (!D.empty())
1351       DisplayName = D;
1352     LineNo = Var.getLineNumber();
1353     Unit = Var.getCompileUnit();
1354     TypeD = Var.getType();
1355   }
1356
1357   StringRef T = TypeD.getName();
1358   if (!T.empty())
1359     Type = T;
1360   StringRef F = Unit.getFilename();
1361   if (!F.empty())
1362     File = F;
1363   StringRef D = Unit.getDirectory();
1364   if (!D.empty())
1365     Dir = D;
1366   return true;
1367 }
1368
1369 /// ExtractDebugLocation - Extract debug location information
1370 /// from llvm.dbg.stoppoint intrinsic.
1371 DebugLoc llvm::ExtractDebugLocation(DbgStopPointInst &SPI,
1372                                     DebugLocTracker &DebugLocInfo) {
1373   DebugLoc DL;
1374   Value *Context = SPI.getContext();
1375
1376   // If this location is already tracked then use it.
1377   DebugLocTuple Tuple(cast<MDNode>(Context), NULL, SPI.getLine(),
1378                       SPI.getColumn());
1379   DenseMap<DebugLocTuple, unsigned>::iterator II
1380     = DebugLocInfo.DebugIdMap.find(Tuple);
1381   if (II != DebugLocInfo.DebugIdMap.end())
1382     return DebugLoc::get(II->second);
1383
1384   // Add a new location entry.
1385   unsigned Id = DebugLocInfo.DebugLocations.size();
1386   DebugLocInfo.DebugLocations.push_back(Tuple);
1387   DebugLocInfo.DebugIdMap[Tuple] = Id;
1388
1389   return DebugLoc::get(Id);
1390 }
1391
1392 /// ExtractDebugLocation - Extract debug location information
1393 /// from DILocation.
1394 DebugLoc llvm::ExtractDebugLocation(DILocation &Loc,
1395                                     DebugLocTracker &DebugLocInfo) {
1396   DebugLoc DL;
1397   MDNode *Context = Loc.getScope().getNode();
1398   MDNode *InlinedLoc = NULL;
1399   if (!Loc.getOrigLocation().isNull())
1400     InlinedLoc = Loc.getOrigLocation().getNode();
1401   // If this location is already tracked then use it.
1402   DebugLocTuple Tuple(Context, InlinedLoc, Loc.getLineNumber(),
1403                       Loc.getColumnNumber());
1404   DenseMap<DebugLocTuple, unsigned>::iterator II
1405     = DebugLocInfo.DebugIdMap.find(Tuple);
1406   if (II != DebugLocInfo.DebugIdMap.end())
1407     return DebugLoc::get(II->second);
1408
1409   // Add a new location entry.
1410   unsigned Id = DebugLocInfo.DebugLocations.size();
1411   DebugLocInfo.DebugLocations.push_back(Tuple);
1412   DebugLocInfo.DebugIdMap[Tuple] = Id;
1413
1414   return DebugLoc::get(Id);
1415 }
1416
1417 /// ExtractDebugLocation - Extract debug location information
1418 /// from llvm.dbg.func_start intrinsic.
1419 DebugLoc llvm::ExtractDebugLocation(DbgFuncStartInst &FSI,
1420                                     DebugLocTracker &DebugLocInfo) {
1421   DebugLoc DL;
1422   Value *SP = FSI.getSubprogram();
1423
1424   DISubprogram Subprogram(cast<MDNode>(SP));
1425   unsigned Line = Subprogram.getLineNumber();
1426   DICompileUnit CU(Subprogram.getCompileUnit());
1427
1428   // If this location is already tracked then use it.
1429   DebugLocTuple Tuple(CU.getNode(), NULL, Line, /* Column */ 0);
1430   DenseMap<DebugLocTuple, unsigned>::iterator II
1431     = DebugLocInfo.DebugIdMap.find(Tuple);
1432   if (II != DebugLocInfo.DebugIdMap.end())
1433     return DebugLoc::get(II->second);
1434
1435   // Add a new location entry.
1436   unsigned Id = DebugLocInfo.DebugLocations.size();
1437   DebugLocInfo.DebugLocations.push_back(Tuple);
1438   DebugLocInfo.DebugIdMap[Tuple] = Id;
1439
1440   return DebugLoc::get(Id);
1441 }
1442
1443 /// getDISubprogram - Find subprogram that is enclosing this scope.
1444 DISubprogram llvm::getDISubprogram(MDNode *Scope) {
1445   DIDescriptor D(Scope);
1446   if (D.isNull())
1447     return DISubprogram();
1448   
1449   if (D.isCompileUnit())
1450     return DISubprogram();
1451   
1452   if (D.isSubprogram())
1453     return DISubprogram(Scope);
1454   
1455   if (D.isLexicalBlock())
1456     return getDISubprogram(DILexicalBlock(Scope).getContext().getNode());
1457   
1458   return DISubprogram();
1459 }
1460
1461 /// getDICompositeType - Find underlying composite type.
1462 DICompositeType llvm::getDICompositeType(DIType T) {
1463   if (T.isNull())
1464     return DICompositeType();
1465   
1466   if (T.isCompositeType())
1467     return DICompositeType(T.getNode());
1468   
1469   if (T.isDerivedType())
1470     return getDICompositeType(DIDerivedType(T.getNode()).getTypeDerivedFrom());
1471   
1472   return DICompositeType();
1473 }