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