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