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