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