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