Clarify that constant folding of instructions applies when all operands
[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 == ':')
1165       Str[i] = '.';
1166   }
1167 }
1168
1169 /// getOrInsertFnSpecificMDNode - Return a NameMDNode that is suitable
1170 /// to hold function specific information.
1171 NamedMDNode *llvm::getOrInsertFnSpecificMDNode(Module &M, StringRef FuncName) {
1172   SmallString<32> Out;
1173   if (FuncName.find('[') == StringRef::npos)
1174     return M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", FuncName)
1175                                       .toStringRef(Out)); 
1176   std::string Name = FuncName;
1177   fixupObjcLikeName(Name);
1178   return M.getOrInsertNamedMetadata(Twine("llvm.dbg.lv.", Name)
1179                                     .toStringRef(Out));
1180 }
1181
1182 /// getFnSpecificMDNode - Return a NameMDNode, if available, that is 
1183 /// suitable to hold function specific information.
1184 NamedMDNode *llvm::getFnSpecificMDNode(const Module &M, StringRef FuncName) {
1185   if (FuncName.find('[') == StringRef::npos)
1186     return M.getNamedMetadata(Twine("llvm.dbg.lv.", FuncName));
1187   std::string Name = FuncName;
1188   fixupObjcLikeName(Name);
1189   return M.getNamedMetadata(Twine("llvm.dbg.lv.", Name));
1190 }
1191
1192 /// CreateVariable - Create a new descriptor for the specified variable.
1193 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
1194                                      StringRef Name,
1195                                      DIFile F,
1196                                      unsigned LineNo,
1197                                      DIType Ty, bool AlwaysPreserve,
1198                                      unsigned Flags) {
1199   Value *Elts[] = {
1200     GetTagConstant(Tag),
1201     Context,
1202     MDString::get(VMContext, Name),
1203     F,
1204     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1205     Ty,
1206     ConstantInt::get(Type::getInt32Ty(VMContext), Flags)
1207   };
1208   MDNode *Node = MDNode::get(VMContext, &Elts[0], 7);
1209   if (AlwaysPreserve) {
1210     // The optimizer may remove local variable. If there is an interest
1211     // to preserve variable info in such situation then stash it in a
1212     // named mdnode.
1213     DISubprogram Fn(getDISubprogram(Context));
1214     StringRef FName = "fn";
1215     if (Fn.getFunction())
1216       FName = Fn.getFunction()->getName();
1217     char One = '\1';
1218     if (FName.startswith(StringRef(&One, 1)))
1219       FName = FName.substr(1);
1220
1221
1222     NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, FName);
1223     FnLocals->addOperand(Node);
1224   }
1225   return DIVariable(Node);
1226 }
1227
1228
1229 /// CreateComplexVariable - Create a new descriptor for the specified variable
1230 /// which has a complex address expression for its address.
1231 DIVariable DIFactory::CreateComplexVariable(unsigned Tag, DIDescriptor Context,
1232                                             StringRef Name, DIFile F,
1233                                             unsigned LineNo,
1234                                             DIType Ty, Value *const *Addr,
1235                                             unsigned NumAddr) {
1236   SmallVector<Value *, 15> Elts;
1237   Elts.push_back(GetTagConstant(Tag));
1238   Elts.push_back(Context);
1239   Elts.push_back(MDString::get(VMContext, Name));
1240   Elts.push_back(F);
1241   Elts.push_back(ConstantInt::get(Type::getInt32Ty(VMContext), LineNo));
1242   Elts.push_back(Ty);
1243   Elts.append(Addr, Addr+NumAddr);
1244
1245   return DIVariable(MDNode::get(VMContext, Elts.data(), Elts.size()));
1246 }
1247
1248
1249 /// CreateBlock - This creates a descriptor for a lexical block with the
1250 /// specified parent VMContext.
1251 DILexicalBlock DIFactory::CreateLexicalBlock(DIDescriptor Context,
1252                                              DIFile F, unsigned LineNo,
1253                                              unsigned Col) {
1254   // Defeat MDNode uniqing for lexical blocks.
1255   static unsigned int unique_id = 0;
1256   Value *Elts[] = {
1257     GetTagConstant(dwarf::DW_TAG_lexical_block),
1258     Context,
1259     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1260     ConstantInt::get(Type::getInt32Ty(VMContext), Col),
1261     F,
1262     ConstantInt::get(Type::getInt32Ty(VMContext), unique_id++)
1263   };
1264   return DILexicalBlock(MDNode::get(VMContext, &Elts[0], 6));
1265 }
1266
1267 /// CreateNameSpace - This creates new descriptor for a namespace
1268 /// with the specified parent context.
1269 DINameSpace DIFactory::CreateNameSpace(DIDescriptor Context, StringRef Name,
1270                                        DIFile F,
1271                                        unsigned LineNo) {
1272   Value *Elts[] = {
1273     GetTagConstant(dwarf::DW_TAG_namespace),
1274     Context,
1275     MDString::get(VMContext, Name),
1276     F,
1277     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo)
1278   };
1279   return DINameSpace(MDNode::get(VMContext, &Elts[0], 5));
1280 }
1281
1282 /// CreateLocation - Creates a debug info location.
1283 DILocation DIFactory::CreateLocation(unsigned LineNo, unsigned ColumnNo,
1284                                      DIScope S, DILocation OrigLoc) {
1285   Value *Elts[] = {
1286     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
1287     ConstantInt::get(Type::getInt32Ty(VMContext), ColumnNo),
1288     S,
1289     OrigLoc,
1290   };
1291   return DILocation(MDNode::get(VMContext, &Elts[0], 4));
1292 }
1293
1294 //===----------------------------------------------------------------------===//
1295 // DIFactory: Routines for inserting code into a function
1296 //===----------------------------------------------------------------------===//
1297
1298 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1299 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1300                                       Instruction *InsertBefore) {
1301   assert(Storage && "no storage passed to dbg.declare");
1302   assert(D.Verify() && "empty DIVariable passed to dbg.declare");
1303   if (!DeclareFn)
1304     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1305
1306   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1307                     D };
1308   return CallInst::Create(DeclareFn, Args, Args+2, "", InsertBefore);
1309 }
1310
1311 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
1312 Instruction *DIFactory::InsertDeclare(Value *Storage, DIVariable D,
1313                                       BasicBlock *InsertAtEnd) {
1314   assert(Storage && "no storage passed to dbg.declare");
1315   assert(D.Verify() && "invalid DIVariable passed to dbg.declare");
1316   if (!DeclareFn)
1317     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1318
1319   Value *Args[] = { MDNode::get(Storage->getContext(), &Storage, 1),
1320                     D };
1321
1322   // If this block already has a terminator then insert this intrinsic
1323   // before the terminator.
1324   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1325     return CallInst::Create(DeclareFn, Args, Args+2, "", T);
1326   else
1327     return CallInst::Create(DeclareFn, Args, Args+2, "", InsertAtEnd);}
1328
1329 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1330 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1331                                                 DIVariable D,
1332                                                 Instruction *InsertBefore) {
1333   assert(V && "no value passed to dbg.value");
1334   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1335   if (!ValueFn)
1336     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1337
1338   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1339                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1340                     D };
1341   return CallInst::Create(ValueFn, Args, Args+3, "", InsertBefore);
1342 }
1343
1344 /// InsertDbgValueIntrinsic - Insert a new llvm.dbg.value intrinsic call.
1345 Instruction *DIFactory::InsertDbgValueIntrinsic(Value *V, uint64_t Offset,
1346                                                 DIVariable D,
1347                                                 BasicBlock *InsertAtEnd) {
1348   assert(V && "no value passed to dbg.value");
1349   assert(D.Verify() && "invalid DIVariable passed to dbg.value");
1350   if (!ValueFn)
1351     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1352
1353   Value *Args[] = { MDNode::get(V->getContext(), &V, 1),
1354                     ConstantInt::get(Type::getInt64Ty(V->getContext()), Offset),
1355                     D };
1356   return CallInst::Create(ValueFn, Args, Args+3, "", InsertAtEnd);
1357 }
1358
1359 // RecordType - Record DIType in a module such that it is not lost even if
1360 // it is not referenced through debug info anchors.
1361 void DIFactory::RecordType(DIType T) {
1362   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.ty");
1363   NMD->addOperand(T);
1364 }
1365
1366
1367 //===----------------------------------------------------------------------===//
1368 // DebugInfoFinder implementations.
1369 //===----------------------------------------------------------------------===//
1370
1371 /// processModule - Process entire module and collect debug info.
1372 void DebugInfoFinder::processModule(Module &M) {
1373   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
1374     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
1375       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
1376            ++BI) {
1377         if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1378           processDeclare(DDI);
1379
1380         DebugLoc Loc = BI->getDebugLoc();
1381         if (Loc.isUnknown())
1382           continue;
1383
1384         LLVMContext &Ctx = BI->getContext();
1385         DIDescriptor Scope(Loc.getScope(Ctx));
1386
1387         if (Scope.isCompileUnit())
1388           addCompileUnit(DICompileUnit(Scope));
1389         else if (Scope.isSubprogram())
1390           processSubprogram(DISubprogram(Scope));
1391         else if (Scope.isLexicalBlock())
1392           processLexicalBlock(DILexicalBlock(Scope));
1393
1394         if (MDNode *IA = Loc.getInlinedAt(Ctx))
1395           processLocation(DILocation(IA));
1396       }
1397
1398   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv")) {
1399     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1400       DIGlobalVariable DIG(cast<MDNode>(NMD->getOperand(i)));
1401       if (addGlobalVariable(DIG)) {
1402         addCompileUnit(DIG.getCompileUnit());
1403         processType(DIG.getType());
1404       }
1405     }
1406   }
1407
1408   if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
1409     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
1410       processSubprogram(DISubprogram(NMD->getOperand(i)));
1411 }
1412
1413 /// processLocation - Process DILocation.
1414 void DebugInfoFinder::processLocation(DILocation Loc) {
1415   if (!Loc.Verify()) return;
1416   DIDescriptor S(Loc.getScope());
1417   if (S.isCompileUnit())
1418     addCompileUnit(DICompileUnit(S));
1419   else if (S.isSubprogram())
1420     processSubprogram(DISubprogram(S));
1421   else if (S.isLexicalBlock())
1422     processLexicalBlock(DILexicalBlock(S));
1423   processLocation(Loc.getOrigLocation());
1424 }
1425
1426 /// processType - Process DIType.
1427 void DebugInfoFinder::processType(DIType DT) {
1428   if (!addType(DT))
1429     return;
1430
1431   addCompileUnit(DT.getCompileUnit());
1432   if (DT.isCompositeType()) {
1433     DICompositeType DCT(DT);
1434     processType(DCT.getTypeDerivedFrom());
1435     DIArray DA = DCT.getTypeArray();
1436     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
1437       DIDescriptor D = DA.getElement(i);
1438       if (D.isType())
1439         processType(DIType(D));
1440       else if (D.isSubprogram())
1441         processSubprogram(DISubprogram(D));
1442     }
1443   } else if (DT.isDerivedType()) {
1444     DIDerivedType DDT(DT);
1445     processType(DDT.getTypeDerivedFrom());
1446   }
1447 }
1448
1449 /// processLexicalBlock
1450 void DebugInfoFinder::processLexicalBlock(DILexicalBlock LB) {
1451   DIScope Context = LB.getContext();
1452   if (Context.isLexicalBlock())
1453     return processLexicalBlock(DILexicalBlock(Context));
1454   else
1455     return processSubprogram(DISubprogram(Context));
1456 }
1457
1458 /// processSubprogram - Process DISubprogram.
1459 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
1460   if (!addSubprogram(SP))
1461     return;
1462   addCompileUnit(SP.getCompileUnit());
1463   processType(SP.getType());
1464 }
1465
1466 /// processDeclare - Process DbgDeclareInst.
1467 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
1468   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
1469   if (!N) return;
1470
1471   DIDescriptor DV(N);
1472   if (!DV.isVariable())
1473     return;
1474
1475   if (!NodesSeen.insert(DV))
1476     return;
1477
1478   addCompileUnit(DIVariable(N).getCompileUnit());
1479   processType(DIVariable(N).getType());
1480 }
1481
1482 /// addType - Add type into Tys.
1483 bool DebugInfoFinder::addType(DIType DT) {
1484   if (!DT.isValid())
1485     return false;
1486
1487   if (!NodesSeen.insert(DT))
1488     return false;
1489
1490   TYs.push_back(DT);
1491   return true;
1492 }
1493
1494 /// addCompileUnit - Add compile unit into CUs.
1495 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
1496   if (!CU.Verify())
1497     return false;
1498
1499   if (!NodesSeen.insert(CU))
1500     return false;
1501
1502   CUs.push_back(CU);
1503   return true;
1504 }
1505
1506 /// addGlobalVariable - Add global variable into GVs.
1507 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
1508   if (!DIDescriptor(DIG).isGlobalVariable())
1509     return false;
1510
1511   if (!NodesSeen.insert(DIG))
1512     return false;
1513
1514   GVs.push_back(DIG);
1515   return true;
1516 }
1517
1518 // addSubprogram - Add subprgoram into SPs.
1519 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
1520   if (!DIDescriptor(SP).isSubprogram())
1521     return false;
1522
1523   if (!NodesSeen.insert(SP))
1524     return false;
1525
1526   SPs.push_back(SP);
1527   return true;
1528 }
1529
1530 /// Find the debug info descriptor corresponding to this global variable.
1531 static Value *findDbgGlobalDeclare(GlobalVariable *V) {
1532   const Module *M = V->getParent();
1533   NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1534   if (!NMD)
1535     return 0;
1536
1537   for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1538     DIDescriptor DIG(cast<MDNode>(NMD->getOperand(i)));
1539     if (!DIG.isGlobalVariable())
1540       continue;
1541     if (DIGlobalVariable(DIG).getGlobal() == V)
1542       return DIG;
1543   }
1544   return 0;
1545 }
1546
1547 /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1548 /// It looks through pointer casts too.
1549 static const DbgDeclareInst *findDbgDeclare(const Value *V) {
1550   V = V->stripPointerCasts();
1551
1552   if (!isa<Instruction>(V) && !isa<Argument>(V))
1553     return 0;
1554
1555   const Function *F = NULL;
1556   if (const Instruction *I = dyn_cast<Instruction>(V))
1557     F = I->getParent()->getParent();
1558   else if (const Argument *A = dyn_cast<Argument>(V))
1559     F = A->getParent();
1560
1561   for (Function::const_iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
1562     for (BasicBlock::const_iterator BI = (*FI).begin(), BE = (*FI).end();
1563          BI != BE; ++BI)
1564       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
1565         if (DDI->getAddress() == V)
1566           return DDI;
1567
1568   return 0;
1569 }
1570
1571 bool llvm::getLocationInfo(const Value *V, std::string &DisplayName,
1572                            std::string &Type, unsigned &LineNo,
1573                            std::string &File, std::string &Dir) {
1574   DICompileUnit Unit;
1575   DIType TypeD;
1576
1577   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1578     Value *DIGV = findDbgGlobalDeclare(GV);
1579     if (!DIGV) return false;
1580     DIGlobalVariable Var(cast<MDNode>(DIGV));
1581
1582     StringRef D = Var.getDisplayName();
1583     if (!D.empty())
1584       DisplayName = D;
1585     LineNo = Var.getLineNumber();
1586     Unit = Var.getCompileUnit();
1587     TypeD = Var.getType();
1588   } else {
1589     const DbgDeclareInst *DDI = findDbgDeclare(V);
1590     if (!DDI) return false;
1591     DIVariable Var(cast<MDNode>(DDI->getVariable()));
1592
1593     StringRef D = Var.getName();
1594     if (!D.empty())
1595       DisplayName = D;
1596     LineNo = Var.getLineNumber();
1597     Unit = Var.getCompileUnit();
1598     TypeD = Var.getType();
1599   }
1600
1601   StringRef T = TypeD.getName();
1602   if (!T.empty())
1603     Type = T;
1604   StringRef F = Unit.getFilename();
1605   if (!F.empty())
1606     File = F;
1607   StringRef D = Unit.getDirectory();
1608   if (!D.empty())
1609     Dir = D;
1610   return true;
1611 }
1612
1613 /// getDISubprogram - Find subprogram that is enclosing this scope.
1614 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
1615   DIDescriptor D(Scope);
1616   if (D.isSubprogram())
1617     return DISubprogram(Scope);
1618
1619   if (D.isLexicalBlock())
1620     return getDISubprogram(DILexicalBlock(Scope).getContext());
1621
1622   return DISubprogram();
1623 }
1624
1625 /// getDICompositeType - Find underlying composite type.
1626 DICompositeType llvm::getDICompositeType(DIType T) {
1627   if (T.isCompositeType())
1628     return DICompositeType(T);
1629
1630   if (T.isDerivedType())
1631     return getDICompositeType(DIDerivedType(T).getTypeDerivedFrom());
1632
1633   return DICompositeType();
1634 }