Extend the ValuesAtScope cache to cover all expressions, not just
[oota-llvm.git] / lib / Analysis / DebugInfo.cpp
1 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the helper classes used to build and interpret debug
11 // information in LLVM IR form.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Analysis/DebugInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/IntrinsicInst.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/ValueTracking.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/DebugLoc.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 using namespace llvm::dwarf;
30
31 //===----------------------------------------------------------------------===//
32 // DIDescriptor
33 //===----------------------------------------------------------------------===//
34
35 /// ValidDebugInfo - Return true if V represents valid debug info value.
36 /// FIXME : Add DIDescriptor.isValid()
37 bool DIDescriptor::ValidDebugInfo(MDNode *N, CodeGenOpt::Level OptLevel) {
38   if (!N)
39     return false;
40
41   DIDescriptor DI(N);
42
43   // Check current version. Allow Version6 for now.
44   unsigned Version = DI.getVersion();
45   if (Version != LLVMDebugVersion && Version != LLVMDebugVersion6)
46     return false;
47
48   unsigned Tag = DI.getTag();
49   switch (Tag) {
50   case DW_TAG_variable:
51     assert(DIVariable(N).Verify() && "Invalid DebugInfo value");
52     break;
53   case DW_TAG_compile_unit:
54     assert(DICompileUnit(N).Verify() && "Invalid DebugInfo value");
55     break;
56   case DW_TAG_subprogram:
57     assert(DISubprogram(N).Verify() && "Invalid DebugInfo value");
58     break;
59   case DW_TAG_lexical_block:
60     // FIXME: This interfers with the quality of generated code during
61     // optimization.
62     if (OptLevel != CodeGenOpt::None)
63       return false;
64     // FALLTHROUGH
65   default:
66     break;
67   }
68
69   return true;
70 }
71
72 DIDescriptor::DIDescriptor(MDNode *N, unsigned RequiredTag) {
73   DbgNode = N;
74   
75   // If this is non-null, check to see if the Tag matches. If not, set to null.
76   if (N && getTag() != RequiredTag) {
77     DbgNode = 0;
78   }
79 }
80
81 const std::string &
82 DIDescriptor::getStringField(unsigned Elt, std::string &Result) const {
83   Result.clear();
84   if (DbgNode == 0)
85     return Result;
86
87   if (Elt < DbgNode->getNumElements()) 
88     if (MDString *MDS = dyn_cast_or_null<MDString>(DbgNode->getElement(Elt))) {
89       Result.assign(MDS->begin(), MDS->begin() + MDS->length());
90       return Result;
91     }
92   
93   return Result;
94 }
95
96 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
97   if (DbgNode == 0) 
98     return 0;
99
100   if (Elt < DbgNode->getNumElements())
101     if (ConstantInt *CI = dyn_cast<ConstantInt>(DbgNode->getElement(Elt)))
102       return CI->getZExtValue();
103   
104   return 0;
105 }
106
107 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
108   if (DbgNode == 0) 
109     return DIDescriptor();
110
111   if (Elt < DbgNode->getNumElements() && DbgNode->getElement(Elt))
112     return DIDescriptor(dyn_cast<MDNode>(DbgNode->getElement(Elt)));
113
114   return DIDescriptor();
115 }
116
117 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
118   if (DbgNode == 0) 
119     return 0;
120
121   if (Elt < DbgNode->getNumElements())
122       return dyn_cast<GlobalVariable>(DbgNode->getElement(Elt));
123   return 0;
124 }
125
126 //===----------------------------------------------------------------------===//
127 // Predicates
128 //===----------------------------------------------------------------------===//
129
130 /// isBasicType - Return true if the specified tag is legal for
131 /// DIBasicType.
132 bool DIDescriptor::isBasicType() const {
133   assert (!isNull() && "Invalid descriptor!");
134   unsigned Tag = getTag();
135   
136   return Tag == dwarf::DW_TAG_base_type;
137 }
138
139 /// isDerivedType - Return true if the specified tag is legal for DIDerivedType.
140 bool DIDescriptor::isDerivedType() const {
141   assert (!isNull() && "Invalid descriptor!");
142   unsigned Tag = getTag();
143
144   switch (Tag) {
145   case dwarf::DW_TAG_typedef:
146   case dwarf::DW_TAG_pointer_type:
147   case dwarf::DW_TAG_reference_type:
148   case dwarf::DW_TAG_const_type:
149   case dwarf::DW_TAG_volatile_type:
150   case dwarf::DW_TAG_restrict_type:
151   case dwarf::DW_TAG_member:
152   case dwarf::DW_TAG_inheritance:
153     return true;
154   default:
155     // CompositeTypes are currently modelled as DerivedTypes.
156     return isCompositeType();
157   }
158 }
159
160 /// isCompositeType - Return true if the specified tag is legal for
161 /// DICompositeType.
162 bool DIDescriptor::isCompositeType() const {
163   assert (!isNull() && "Invalid descriptor!");
164   unsigned Tag = getTag();
165
166   switch (Tag) {
167   case dwarf::DW_TAG_array_type:
168   case dwarf::DW_TAG_structure_type:
169   case dwarf::DW_TAG_union_type:
170   case dwarf::DW_TAG_enumeration_type:
171   case dwarf::DW_TAG_vector_type:
172   case dwarf::DW_TAG_subroutine_type:
173   case dwarf::DW_TAG_class_type:
174     return true;
175   default:
176     return false;
177   }
178 }
179
180 /// isVariable - Return true if the specified tag is legal for DIVariable.
181 bool DIDescriptor::isVariable() const {
182   assert (!isNull() && "Invalid descriptor!");
183   unsigned Tag = getTag();
184
185   switch (Tag) {
186   case dwarf::DW_TAG_auto_variable:
187   case dwarf::DW_TAG_arg_variable:
188   case dwarf::DW_TAG_return_variable:
189     return true;
190   default:
191     return false;
192   }
193 }
194
195 /// isSubprogram - Return true if the specified tag is legal for
196 /// DISubprogram.
197 bool DIDescriptor::isSubprogram() const {
198   assert (!isNull() && "Invalid descriptor!");
199   unsigned Tag = getTag();
200   
201   return Tag == dwarf::DW_TAG_subprogram;
202 }
203
204 /// isGlobalVariable - Return true if the specified tag is legal for
205 /// DIGlobalVariable.
206 bool DIDescriptor::isGlobalVariable() const {
207   assert (!isNull() && "Invalid descriptor!");
208   unsigned Tag = getTag();
209
210   return Tag == dwarf::DW_TAG_variable;
211 }
212
213 /// isScope - Return true if the specified tag is one of the scope 
214 /// related tag.
215 bool DIDescriptor::isScope() const {
216   assert (!isNull() && "Invalid descriptor!");
217   unsigned Tag = getTag();
218
219   switch (Tag) {
220     case dwarf::DW_TAG_compile_unit:
221     case dwarf::DW_TAG_lexical_block:
222     case dwarf::DW_TAG_subprogram:
223       return true;
224     default:
225       break;
226   }
227   return false;
228 }
229
230 //===----------------------------------------------------------------------===//
231 // Simple Descriptor Constructors and other Methods
232 //===----------------------------------------------------------------------===//
233
234 DIType::DIType(MDNode *N) : DIDescriptor(N) {
235   if (!N) return;
236   if (!isBasicType() && !isDerivedType() && !isCompositeType()) {
237     DbgNode = 0;
238   }
239 }
240
241 unsigned DIArray::getNumElements() const {
242   assert (DbgNode && "Invalid DIArray");
243   return DbgNode->getNumElements();
244 }
245
246 /// replaceAllUsesWith - Replace all uses of debug info referenced by
247 /// this descriptor. After this completes, the current debug info value
248 /// is erased.
249 void DIDerivedType::replaceAllUsesWith(DIDescriptor &D) {
250   if (isNull())
251     return;
252
253   assert (!D.isNull() && "Can not replace with null");
254   DbgNode->replaceAllUsesWith(D.getNode());
255   delete DbgNode;
256 }
257
258 /// Verify - Verify that a compile unit is well formed.
259 bool DICompileUnit::Verify() const {
260   if (isNull()) 
261     return false;
262   std::string Res;
263   if (getFilename(Res).empty()) 
264     return false;
265   // It is possible that directory and produce string is empty.
266   return true;
267 }
268
269 /// Verify - Verify that a type descriptor is well formed.
270 bool DIType::Verify() const {
271   if (isNull()) 
272     return false;
273   if (getContext().isNull()) 
274     return false;
275
276   DICompileUnit CU = getCompileUnit();
277   if (!CU.isNull() && !CU.Verify()) 
278     return false;
279   return true;
280 }
281
282 /// Verify - Verify that a composite type descriptor is well formed.
283 bool DICompositeType::Verify() const {
284   if (isNull()) 
285     return false;
286   if (getContext().isNull()) 
287     return false;
288
289   DICompileUnit CU = getCompileUnit();
290   if (!CU.isNull() && !CU.Verify()) 
291     return false;
292   return true;
293 }
294
295 /// Verify - Verify that a subprogram descriptor is well formed.
296 bool DISubprogram::Verify() const {
297   if (isNull())
298     return false;
299   
300   if (getContext().isNull())
301     return false;
302
303   DICompileUnit CU = getCompileUnit();
304   if (!CU.Verify()) 
305     return false;
306
307   DICompositeType Ty = getType();
308   if (!Ty.isNull() && !Ty.Verify())
309     return false;
310   return true;
311 }
312
313 /// Verify - Verify that a global variable descriptor is well formed.
314 bool DIGlobalVariable::Verify() const {
315   if (isNull())
316     return false;
317   
318   if (getContext().isNull())
319     return false;
320
321   DICompileUnit CU = getCompileUnit();
322   if (!CU.isNull() && !CU.Verify()) 
323     return false;
324
325   DIType Ty = getType();
326   if (!Ty.Verify())
327     return false;
328
329   if (!getGlobal())
330     return false;
331
332   return true;
333 }
334
335 /// Verify - Verify that a variable descriptor is well formed.
336 bool DIVariable::Verify() const {
337   if (isNull())
338     return false;
339   
340   if (getContext().isNull())
341     return false;
342
343   DIType Ty = getType();
344   if (!Ty.Verify())
345     return false;
346
347   return true;
348 }
349
350 /// getOriginalTypeSize - If this type is derived from a base type then
351 /// return base type size.
352 uint64_t DIDerivedType::getOriginalTypeSize() const {
353   if (getTag() != dwarf::DW_TAG_member)
354     return getSizeInBits();
355   DIType BT = getTypeDerivedFrom();
356   if (BT.getTag() != dwarf::DW_TAG_base_type)
357     return getSizeInBits();
358   return BT.getSizeInBits();
359 }
360
361 /// describes - Return true if this subprogram provides debugging
362 /// information for the function F.
363 bool DISubprogram::describes(const Function *F) {
364   assert (F && "Invalid function");
365   std::string Name;
366   getLinkageName(Name);
367   if (Name.empty())
368     getName(Name);
369   if (F->getName() == Name)
370     return true;
371   return false;
372 }
373
374 //===----------------------------------------------------------------------===//
375 // DIDescriptor: dump routines for all descriptors.
376 //===----------------------------------------------------------------------===//
377
378
379 /// dump - Print descriptor.
380 void DIDescriptor::dump() const {
381   errs() << "[" << dwarf::TagString(getTag()) << "] ";
382   errs().write_hex((intptr_t)DbgNode) << ']';
383 }
384
385 /// dump - Print compile unit.
386 void DICompileUnit::dump() const {
387   if (getLanguage())
388     errs() << " [" << dwarf::LanguageString(getLanguage()) << "] ";
389
390   std::string Res1, Res2;
391   errs() << " [" << getDirectory(Res1) << "/" << getFilename(Res2) << " ]";
392 }
393
394 /// dump - Print type.
395 void DIType::dump() const {
396   if (isNull()) return;
397
398   std::string Res;
399   if (!getName(Res).empty())
400     errs() << " [" << Res << "] ";
401
402   unsigned Tag = getTag();
403   errs() << " [" << dwarf::TagString(Tag) << "] ";
404
405   // TODO : Print context
406   getCompileUnit().dump();
407   errs() << " [" 
408          << getLineNumber() << ", " 
409          << getSizeInBits() << ", "
410          << getAlignInBits() << ", "
411          << getOffsetInBits() 
412          << "] ";
413
414   if (isPrivate()) 
415     errs() << " [private] ";
416   else if (isProtected())
417     errs() << " [protected] ";
418
419   if (isForwardDecl())
420     errs() << " [fwd] ";
421
422   if (isBasicType())
423     DIBasicType(DbgNode).dump();
424   else if (isDerivedType())
425     DIDerivedType(DbgNode).dump();
426   else if (isCompositeType())
427     DICompositeType(DbgNode).dump();
428   else {
429     errs() << "Invalid DIType\n";
430     return;
431   }
432
433   errs() << "\n";
434 }
435
436 /// dump - Print basic type.
437 void DIBasicType::dump() const {
438   errs() << " [" << dwarf::AttributeEncodingString(getEncoding()) << "] ";
439 }
440
441 /// dump - Print derived type.
442 void DIDerivedType::dump() const {
443   errs() << "\n\t Derived From: "; getTypeDerivedFrom().dump();
444 }
445
446 /// dump - Print composite type.
447 void DICompositeType::dump() const {
448   DIArray A = getTypeArray();
449   if (A.isNull())
450     return;
451   errs() << " [" << A.getNumElements() << " elements]";
452 }
453
454 /// dump - Print global.
455 void DIGlobal::dump() const {
456   std::string Res;
457   if (!getName(Res).empty())
458     errs() << " [" << Res << "] ";
459
460   unsigned Tag = getTag();
461   errs() << " [" << dwarf::TagString(Tag) << "] ";
462
463   // TODO : Print context
464   getCompileUnit().dump();
465   errs() << " [" << getLineNumber() << "] ";
466
467   if (isLocalToUnit())
468     errs() << " [local] ";
469
470   if (isDefinition())
471     errs() << " [def] ";
472
473   if (isGlobalVariable())
474     DIGlobalVariable(DbgNode).dump();
475
476   errs() << "\n";
477 }
478
479 /// dump - Print subprogram.
480 void DISubprogram::dump() const {
481   DIGlobal::dump();
482 }
483
484 /// dump - Print global variable.
485 void DIGlobalVariable::dump() const {
486   errs() << " [";
487   getGlobal()->dump();
488   errs() << "] ";
489 }
490
491 /// dump - Print variable.
492 void DIVariable::dump() const {
493   std::string Res;
494   if (!getName(Res).empty())
495     errs() << " [" << Res << "] ";
496
497   getCompileUnit().dump();
498   errs() << " [" << getLineNumber() << "] ";
499   getType().dump();
500   errs() << "\n";
501 }
502
503 //===----------------------------------------------------------------------===//
504 // DIFactory: Basic Helpers
505 //===----------------------------------------------------------------------===//
506
507 DIFactory::DIFactory(Module &m)
508   : M(m), VMContext(M.getContext()), StopPointFn(0), FuncStartFn(0), 
509     RegionStartFn(0), RegionEndFn(0),
510     DeclareFn(0) {
511   EmptyStructPtr = PointerType::getUnqual(StructType::get(VMContext));
512 }
513
514 Constant *DIFactory::GetTagConstant(unsigned TAG) {
515   assert((TAG & LLVMDebugVersionMask) == 0 &&
516          "Tag too large for debug encoding!");
517   return ConstantInt::get(Type::getInt32Ty(VMContext), TAG | LLVMDebugVersion);
518 }
519
520 //===----------------------------------------------------------------------===//
521 // DIFactory: Primary Constructors
522 //===----------------------------------------------------------------------===//
523
524 /// GetOrCreateArray - Create an descriptor for an array of descriptors. 
525 /// This implicitly uniques the arrays created.
526 DIArray DIFactory::GetOrCreateArray(DIDescriptor *Tys, unsigned NumTys) {
527   SmallVector<Value*, 16> Elts;
528   
529   if (NumTys == 0)
530     Elts.push_back(llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)));
531   else
532     for (unsigned i = 0; i != NumTys; ++i)
533       Elts.push_back(Tys[i].getNode());
534
535   return DIArray(MDNode::get(VMContext,Elts.data(), Elts.size()));
536 }
537
538 /// GetOrCreateSubrange - Create a descriptor for a value range.  This
539 /// implicitly uniques the values returned.
540 DISubrange DIFactory::GetOrCreateSubrange(int64_t Lo, int64_t Hi) {
541   Value *Elts[] = {
542     GetTagConstant(dwarf::DW_TAG_subrange_type),
543     ConstantInt::get(Type::getInt64Ty(VMContext), Lo),
544     ConstantInt::get(Type::getInt64Ty(VMContext), Hi)
545   };
546   
547   return DISubrange(MDNode::get(VMContext, &Elts[0], 3));
548 }
549
550
551
552 /// CreateCompileUnit - Create a new descriptor for the specified compile
553 /// unit.  Note that this does not unique compile units within the module.
554 DICompileUnit DIFactory::CreateCompileUnit(unsigned LangID,
555                                            const std::string &Filename,
556                                            const std::string &Directory,
557                                            const std::string &Producer,
558                                            bool isMain,
559                                            bool isOptimized,
560                                            const char *Flags,
561                                            unsigned RunTimeVer) {
562   Value *Elts[] = {
563     GetTagConstant(dwarf::DW_TAG_compile_unit),
564     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
565     ConstantInt::get(Type::getInt32Ty(VMContext), LangID),
566     MDString::get(VMContext, Filename),
567     MDString::get(VMContext, Directory),
568     MDString::get(VMContext, Producer),
569     ConstantInt::get(Type::getInt1Ty(VMContext), isMain),
570     ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized),
571     MDString::get(VMContext, Flags),
572     ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer)
573   };
574
575   return DICompileUnit(MDNode::get(VMContext, &Elts[0], 10));
576 }
577
578 /// CreateEnumerator - Create a single enumerator value.
579 DIEnumerator DIFactory::CreateEnumerator(const std::string &Name, uint64_t Val){
580   Value *Elts[] = {
581     GetTagConstant(dwarf::DW_TAG_enumerator),
582     MDString::get(VMContext, Name),
583     ConstantInt::get(Type::getInt64Ty(VMContext), Val)
584   };
585   return DIEnumerator(MDNode::get(VMContext, &Elts[0], 3));
586 }
587
588
589 /// CreateBasicType - Create a basic type like int, float, etc.
590 DIBasicType DIFactory::CreateBasicType(DIDescriptor Context,
591                                       const std::string &Name,
592                                        DICompileUnit CompileUnit,
593                                        unsigned LineNumber,
594                                        uint64_t SizeInBits,
595                                        uint64_t AlignInBits,
596                                        uint64_t OffsetInBits, unsigned Flags,
597                                        unsigned Encoding) {
598   Value *Elts[] = {
599     GetTagConstant(dwarf::DW_TAG_base_type),
600     Context.getNode(),
601     MDString::get(VMContext, Name),
602     CompileUnit.getNode(),
603     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
604     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
605     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
606     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
607     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
608     ConstantInt::get(Type::getInt32Ty(VMContext), Encoding)
609   };
610   return DIBasicType(MDNode::get(VMContext, &Elts[0], 10));
611 }
612
613 /// CreateDerivedType - Create a derived type like const qualified type,
614 /// pointer, typedef, etc.
615 DIDerivedType DIFactory::CreateDerivedType(unsigned Tag,
616                                            DIDescriptor Context,
617                                            const std::string &Name,
618                                            DICompileUnit CompileUnit,
619                                            unsigned LineNumber,
620                                            uint64_t SizeInBits,
621                                            uint64_t AlignInBits,
622                                            uint64_t OffsetInBits,
623                                            unsigned Flags,
624                                            DIType DerivedFrom) {
625   Value *Elts[] = {
626     GetTagConstant(Tag),
627     Context.getNode(),
628     MDString::get(VMContext, Name),
629     CompileUnit.getNode(),
630     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
631     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
632     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
633     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
634     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
635     DerivedFrom.getNode(),
636   };
637   return DIDerivedType(MDNode::get(VMContext, &Elts[0], 10));
638 }
639
640 /// CreateCompositeType - Create a composite type like array, struct, etc.
641 DICompositeType DIFactory::CreateCompositeType(unsigned Tag,
642                                                DIDescriptor Context,
643                                                const std::string &Name,
644                                                DICompileUnit CompileUnit,
645                                                unsigned LineNumber,
646                                                uint64_t SizeInBits,
647                                                uint64_t AlignInBits,
648                                                uint64_t OffsetInBits,
649                                                unsigned Flags,
650                                                DIType DerivedFrom,
651                                                DIArray Elements,
652                                                unsigned RuntimeLang) {
653
654   Value *Elts[] = {
655     GetTagConstant(Tag),
656     Context.getNode(),
657     MDString::get(VMContext, Name),
658     CompileUnit.getNode(),
659     ConstantInt::get(Type::getInt32Ty(VMContext), LineNumber),
660     ConstantInt::get(Type::getInt64Ty(VMContext), SizeInBits),
661     ConstantInt::get(Type::getInt64Ty(VMContext), AlignInBits),
662     ConstantInt::get(Type::getInt64Ty(VMContext), OffsetInBits),
663     ConstantInt::get(Type::getInt32Ty(VMContext), Flags),
664     DerivedFrom.getNode(),
665     Elements.getNode(),
666     ConstantInt::get(Type::getInt32Ty(VMContext), RuntimeLang)
667   };
668   return DICompositeType(MDNode::get(VMContext, &Elts[0], 12));
669 }
670
671
672 /// CreateSubprogram - Create a new descriptor for the specified subprogram.
673 /// See comments in DISubprogram for descriptions of these fields.  This
674 /// method does not unique the generated descriptors.
675 DISubprogram DIFactory::CreateSubprogram(DIDescriptor Context, 
676                                          const std::string &Name,
677                                          const std::string &DisplayName,
678                                          const std::string &LinkageName,
679                                          DICompileUnit CompileUnit,
680                                          unsigned LineNo, DIType Type,
681                                          bool isLocalToUnit,
682                                          bool isDefinition) {
683
684   Value *Elts[] = {
685     GetTagConstant(dwarf::DW_TAG_subprogram),
686     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
687     Context.getNode(),
688     MDString::get(VMContext, Name),
689     MDString::get(VMContext, DisplayName),
690     MDString::get(VMContext, LinkageName),
691     CompileUnit.getNode(),
692     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
693     Type.getNode(),
694     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
695     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition)
696   };
697   return DISubprogram(MDNode::get(VMContext, &Elts[0], 11));
698 }
699
700 /// CreateGlobalVariable - Create a new descriptor for the specified global.
701 DIGlobalVariable
702 DIFactory::CreateGlobalVariable(DIDescriptor Context, const std::string &Name,
703                                 const std::string &DisplayName,
704                                 const std::string &LinkageName,
705                                 DICompileUnit CompileUnit,
706                                 unsigned LineNo, DIType Type,bool isLocalToUnit,
707                                 bool isDefinition, llvm::GlobalVariable *Val) {
708   Value *Elts[] = { 
709     GetTagConstant(dwarf::DW_TAG_variable),
710     llvm::Constant::getNullValue(Type::getInt32Ty(VMContext)),
711     Context.getNode(),
712     MDString::get(VMContext, Name),
713     MDString::get(VMContext, DisplayName),
714     MDString::get(VMContext, LinkageName),
715     CompileUnit.getNode(),
716     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
717     Type.getNode(),
718     ConstantInt::get(Type::getInt1Ty(VMContext), isLocalToUnit),
719     ConstantInt::get(Type::getInt1Ty(VMContext), isDefinition),
720     Val
721   };
722
723   Value *const *Vs = &Elts[0];
724   MDNode *Node = MDNode::get(VMContext,Vs, 12);
725
726   // Create a named metadata so that we do not lose this mdnode.
727   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.gv");
728   NMD->addElement(Node);
729
730   return DIGlobalVariable(Node);
731 }
732
733
734 /// CreateVariable - Create a new descriptor for the specified variable.
735 DIVariable DIFactory::CreateVariable(unsigned Tag, DIDescriptor Context,
736                                      const std::string &Name,
737                                      DICompileUnit CompileUnit, unsigned LineNo,
738                                      DIType Type) {
739   Value *Elts[] = {
740     GetTagConstant(Tag),
741     Context.getNode(),
742     MDString::get(VMContext, Name),
743     CompileUnit.getNode(),
744     ConstantInt::get(Type::getInt32Ty(VMContext), LineNo),
745     Type.getNode(),
746   };
747   return DIVariable(MDNode::get(VMContext, &Elts[0], 6));
748 }
749
750
751 /// CreateBlock - This creates a descriptor for a lexical block with the
752 /// specified parent VMContext.
753 DIBlock DIFactory::CreateBlock(DIDescriptor Context) {
754   Value *Elts[] = {
755     GetTagConstant(dwarf::DW_TAG_lexical_block),
756     Context.getNode()
757   };
758   return DIBlock(MDNode::get(VMContext, &Elts[0], 2));
759 }
760
761
762 //===----------------------------------------------------------------------===//
763 // DIFactory: Routines for inserting code into a function
764 //===----------------------------------------------------------------------===//
765
766 /// InsertStopPoint - Create a new llvm.dbg.stoppoint intrinsic invocation,
767 /// inserting it at the end of the specified basic block.
768 void DIFactory::InsertStopPoint(DICompileUnit CU, unsigned LineNo,
769                                 unsigned ColNo, BasicBlock *BB) {
770   
771   // Lazily construct llvm.dbg.stoppoint function.
772   if (!StopPointFn)
773     StopPointFn = llvm::Intrinsic::getDeclaration(&M, 
774                                               llvm::Intrinsic::dbg_stoppoint);
775   
776   // Invoke llvm.dbg.stoppoint
777   Value *Args[] = {
778     ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo),
779     ConstantInt::get(llvm::Type::getInt32Ty(VMContext), ColNo),
780     CU.getNode()
781   };
782   CallInst::Create(StopPointFn, Args, Args+3, "", BB);
783 }
784
785 /// InsertSubprogramStart - Create a new llvm.dbg.func.start intrinsic to
786 /// mark the start of the specified subprogram.
787 void DIFactory::InsertSubprogramStart(DISubprogram SP, BasicBlock *BB) {
788   // Lazily construct llvm.dbg.func.start.
789   if (!FuncStartFn)
790     FuncStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_func_start);
791   
792   // Call llvm.dbg.func.start which also implicitly sets a stoppoint.
793   CallInst::Create(FuncStartFn, SP.getNode(), "", BB);
794 }
795
796 /// InsertRegionStart - Insert a new llvm.dbg.region.start intrinsic call to
797 /// mark the start of a region for the specified scoping descriptor.
798 void DIFactory::InsertRegionStart(DIDescriptor D, BasicBlock *BB) {
799   // Lazily construct llvm.dbg.region.start function.
800   if (!RegionStartFn)
801     RegionStartFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_start);
802
803   // Call llvm.dbg.func.start.
804   CallInst::Create(RegionStartFn, D.getNode(), "", BB);
805 }
806
807 /// InsertRegionEnd - Insert a new llvm.dbg.region.end intrinsic call to
808 /// mark the end of a region for the specified scoping descriptor.
809 void DIFactory::InsertRegionEnd(DIDescriptor D, BasicBlock *BB) {
810   // Lazily construct llvm.dbg.region.end function.
811   if (!RegionEndFn)
812     RegionEndFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_region_end);
813
814   // Call llvm.dbg.region.end.
815   CallInst::Create(RegionEndFn, D.getNode(), "", BB);
816 }
817
818 /// InsertDeclare - Insert a new llvm.dbg.declare intrinsic call.
819 void DIFactory::InsertDeclare(Value *Storage, DIVariable D, BasicBlock *BB) {
820   // Cast the storage to a {}* for the call to llvm.dbg.declare.
821   Storage = new BitCastInst(Storage, EmptyStructPtr, "", BB);
822   
823   if (!DeclareFn)
824     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
825
826   Value *Args[] = { Storage, D.getNode() };
827   CallInst::Create(DeclareFn, Args, Args+2, "", BB);
828 }
829
830
831 //===----------------------------------------------------------------------===//
832 // DebugInfoFinder implementations.
833 //===----------------------------------------------------------------------===//
834
835 /// processModule - Process entire module and collect debug info.
836 void DebugInfoFinder::processModule(Module &M) {
837
838
839   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
840     for (Function::iterator FI = (*I).begin(), FE = (*I).end(); FI != FE; ++FI)
841       for (BasicBlock::iterator BI = (*FI).begin(), BE = (*FI).end(); BI != BE;
842            ++BI) {
843         if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(BI))
844           processStopPoint(SPI);
845         else if (DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI))
846           processFuncStart(FSI);
847         else if (DbgRegionStartInst *DRS = dyn_cast<DbgRegionStartInst>(BI))
848           processRegionStart(DRS);
849         else if (DbgRegionEndInst *DRE = dyn_cast<DbgRegionEndInst>(BI))
850           processRegionEnd(DRE);
851         else if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(BI))
852           processDeclare(DDI);
853       }
854
855   NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.gv");
856   if (!NMD)
857     return;
858
859   for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
860     DIGlobalVariable DIG(cast<MDNode>(NMD->getElement(i)));
861     if (addGlobalVariable(DIG)) {
862       addCompileUnit(DIG.getCompileUnit());
863       processType(DIG.getType());
864     }
865   }
866 }
867     
868 /// processType - Process DIType.
869 void DebugInfoFinder::processType(DIType DT) {
870   if (!addType(DT))
871     return;
872
873   addCompileUnit(DT.getCompileUnit());
874   if (DT.isCompositeType()) {
875     DICompositeType DCT(DT.getNode());
876     processType(DCT.getTypeDerivedFrom());
877     DIArray DA = DCT.getTypeArray();
878     if (!DA.isNull())
879       for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
880         DIDescriptor D = DA.getElement(i);
881         DIType TypeE = DIType(D.getNode());
882         if (!TypeE.isNull())
883           processType(TypeE);
884         else 
885           processSubprogram(DISubprogram(D.getNode()));
886       }
887   } else if (DT.isDerivedType()) {
888     DIDerivedType DDT(DT.getNode());
889     if (!DDT.isNull()) 
890       processType(DDT.getTypeDerivedFrom());
891   }
892 }
893
894 /// processSubprogram - Process DISubprogram.
895 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
896   if (SP.isNull())
897     return;
898   if (!addSubprogram(SP))
899     return;
900   addCompileUnit(SP.getCompileUnit());
901   processType(SP.getType());
902 }
903
904 /// processStopPoint - Process DbgStopPointInst.
905 void DebugInfoFinder::processStopPoint(DbgStopPointInst *SPI) {
906   MDNode *Context = dyn_cast<MDNode>(SPI->getContext());
907   addCompileUnit(DICompileUnit(Context));
908 }
909
910 /// processFuncStart - Process DbgFuncStartInst.
911 void DebugInfoFinder::processFuncStart(DbgFuncStartInst *FSI) {
912   MDNode *SP = dyn_cast<MDNode>(FSI->getSubprogram());
913   processSubprogram(DISubprogram(SP));
914 }
915
916 /// processRegionStart - Process DbgRegionStart.
917 void DebugInfoFinder::processRegionStart(DbgRegionStartInst *DRS) {
918   MDNode *SP = dyn_cast<MDNode>(DRS->getContext());
919   processSubprogram(DISubprogram(SP));
920 }
921
922 /// processRegionEnd - Process DbgRegionEnd.
923 void DebugInfoFinder::processRegionEnd(DbgRegionEndInst *DRE) {
924   MDNode *SP = dyn_cast<MDNode>(DRE->getContext());
925   processSubprogram(DISubprogram(SP));
926 }
927
928 /// processDeclare - Process DbgDeclareInst.
929 void DebugInfoFinder::processDeclare(DbgDeclareInst *DDI) {
930   DIVariable DV(cast<MDNode>(DDI->getVariable()));
931   if (DV.isNull())
932     return;
933
934   if (!NodesSeen.insert(DV.getNode()))
935     return;
936
937   addCompileUnit(DV.getCompileUnit());
938   processType(DV.getType());
939 }
940
941 /// addType - Add type into Tys.
942 bool DebugInfoFinder::addType(DIType DT) {
943   if (DT.isNull())
944     return false;
945
946   if (!NodesSeen.insert(DT.getNode()))
947     return false;
948
949   TYs.push_back(DT.getNode());
950   return true;
951 }
952
953 /// addCompileUnit - Add compile unit into CUs.
954 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
955   if (CU.isNull())
956     return false;
957
958   if (!NodesSeen.insert(CU.getNode()))
959     return false;
960
961   CUs.push_back(CU.getNode());
962   return true;
963 }
964     
965 /// addGlobalVariable - Add global variable into GVs.
966 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
967   if (DIG.isNull())
968     return false;
969
970   if (!NodesSeen.insert(DIG.getNode()))
971     return false;
972
973   GVs.push_back(DIG.getNode());
974   return true;
975 }
976
977 // addSubprogram - Add subprgoram into SPs.
978 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
979   if (SP.isNull())
980     return false;
981   
982   if (!NodesSeen.insert(SP.getNode()))
983     return false;
984
985   SPs.push_back(SP.getNode());
986   return true;
987 }
988
989 namespace llvm {
990   /// findStopPoint - Find the stoppoint coressponding to this instruction, that
991   /// is the stoppoint that dominates this instruction.
992   const DbgStopPointInst *findStopPoint(const Instruction *Inst) {
993     if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(Inst))
994       return DSI;
995
996     const BasicBlock *BB = Inst->getParent();
997     BasicBlock::const_iterator I = Inst, B;
998     while (BB) {
999       B = BB->begin();
1000
1001       // A BB consisting only of a terminator can't have a stoppoint.
1002       while (I != B) {
1003         --I;
1004         if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1005           return DSI;
1006       }
1007
1008       // This BB didn't have a stoppoint: if there is only one predecessor, look
1009       // for a stoppoint there. We could use getIDom(), but that would require
1010       // dominator info.
1011       BB = I->getParent()->getUniquePredecessor();
1012       if (BB)
1013         I = BB->getTerminator();
1014     }
1015
1016     return 0;
1017   }
1018
1019   /// findBBStopPoint - Find the stoppoint corresponding to first real
1020   /// (non-debug intrinsic) instruction in this Basic Block, and return the
1021   /// stoppoint for it.
1022   const DbgStopPointInst *findBBStopPoint(const BasicBlock *BB) {
1023     for(BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1024       if (const DbgStopPointInst *DSI = dyn_cast<DbgStopPointInst>(I))
1025         return DSI;
1026
1027     // Fallback to looking for stoppoint of unique predecessor. Useful if this
1028     // BB contains no stoppoints, but unique predecessor does.
1029     BB = BB->getUniquePredecessor();
1030     if (BB)
1031       return findStopPoint(BB->getTerminator());
1032
1033     return 0;
1034   }
1035
1036   Value *findDbgGlobalDeclare(GlobalVariable *V) {
1037     const Module *M = V->getParent();
1038     NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv");
1039     if (!NMD)
1040       return 0;
1041     
1042     for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
1043       DIGlobalVariable DIG(cast_or_null<MDNode>(NMD->getElement(i)));
1044       if (DIG.isNull())
1045         continue;
1046       if (DIG.getGlobal() == V)
1047         return DIG.getNode();
1048     }
1049     return 0;
1050   }
1051
1052   /// Finds the llvm.dbg.declare intrinsic corresponding to this value if any.
1053   /// It looks through pointer casts too.
1054   const DbgDeclareInst *findDbgDeclare(const Value *V, bool stripCasts) {
1055     if (stripCasts) {
1056       V = V->stripPointerCasts();
1057
1058       // Look for the bitcast.
1059       for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1060             I != E; ++I)
1061         if (isa<BitCastInst>(I))
1062           return findDbgDeclare(*I, false);
1063
1064       return 0;
1065     }
1066
1067     // Find llvm.dbg.declare among uses of the instruction.
1068     for (Value::use_const_iterator I = V->use_begin(), E =V->use_end();
1069           I != E; ++I)
1070       if (const DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I))
1071         return DDI;
1072
1073     return 0;
1074   }
1075
1076   bool getLocationInfo(const Value *V, std::string &DisplayName,
1077                        std::string &Type, unsigned &LineNo, std::string &File,
1078                        std::string &Dir) {
1079     DICompileUnit Unit;
1080     DIType TypeD;
1081
1082     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(const_cast<Value*>(V))) {
1083       Value *DIGV = findDbgGlobalDeclare(GV);
1084       if (!DIGV) return false;
1085       DIGlobalVariable Var(cast<MDNode>(DIGV));
1086
1087       Var.getDisplayName(DisplayName);
1088       LineNo = Var.getLineNumber();
1089       Unit = Var.getCompileUnit();
1090       TypeD = Var.getType();
1091     } else {
1092       const DbgDeclareInst *DDI = findDbgDeclare(V);
1093       if (!DDI) return false;
1094       DIVariable Var(cast<MDNode>(DDI->getVariable()));
1095
1096       Var.getName(DisplayName);
1097       LineNo = Var.getLineNumber();
1098       Unit = Var.getCompileUnit();
1099       TypeD = Var.getType();
1100     }
1101
1102     TypeD.getName(Type);
1103     Unit.getFilename(File);
1104     Unit.getDirectory(Dir);
1105     return true;
1106   }
1107
1108   /// isValidDebugInfoIntrinsic - Return true if SPI is a valid debug 
1109   /// info intrinsic.
1110   bool isValidDebugInfoIntrinsic(DbgStopPointInst &SPI, 
1111                                  CodeGenOpt::Level OptLev) {
1112     return DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLev);
1113   }
1114
1115   /// isValidDebugInfoIntrinsic - Return true if FSI is a valid debug 
1116   /// info intrinsic.
1117   bool isValidDebugInfoIntrinsic(DbgFuncStartInst &FSI,
1118                                  CodeGenOpt::Level OptLev) {
1119     return DIDescriptor::ValidDebugInfo(FSI.getSubprogram(), OptLev);
1120   }
1121
1122   /// isValidDebugInfoIntrinsic - Return true if RSI is a valid debug 
1123   /// info intrinsic.
1124   bool isValidDebugInfoIntrinsic(DbgRegionStartInst &RSI,
1125                                  CodeGenOpt::Level OptLev) {
1126     return DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLev);
1127   }
1128
1129   /// isValidDebugInfoIntrinsic - Return true if REI is a valid debug 
1130   /// info intrinsic.
1131   bool isValidDebugInfoIntrinsic(DbgRegionEndInst &REI,
1132                                  CodeGenOpt::Level OptLev) {
1133     return DIDescriptor::ValidDebugInfo(REI.getContext(), OptLev);
1134   }
1135
1136
1137   /// isValidDebugInfoIntrinsic - Return true if DI is a valid debug 
1138   /// info intrinsic.
1139   bool isValidDebugInfoIntrinsic(DbgDeclareInst &DI,
1140                                  CodeGenOpt::Level OptLev) {
1141     return DIDescriptor::ValidDebugInfo(DI.getVariable(), OptLev);
1142   }
1143
1144   /// ExtractDebugLocation - Extract debug location information 
1145   /// from llvm.dbg.stoppoint intrinsic.
1146   DebugLoc ExtractDebugLocation(DbgStopPointInst &SPI,
1147                                 DebugLocTracker &DebugLocInfo) {
1148     DebugLoc DL;
1149     Value *Context = SPI.getContext();
1150
1151     // If this location is already tracked then use it.
1152     DebugLocTuple Tuple(cast<MDNode>(Context), SPI.getLine(), 
1153                         SPI.getColumn());
1154     DenseMap<DebugLocTuple, unsigned>::iterator II
1155       = DebugLocInfo.DebugIdMap.find(Tuple);
1156     if (II != DebugLocInfo.DebugIdMap.end())
1157       return DebugLoc::get(II->second);
1158
1159     // Add a new location entry.
1160     unsigned Id = DebugLocInfo.DebugLocations.size();
1161     DebugLocInfo.DebugLocations.push_back(Tuple);
1162     DebugLocInfo.DebugIdMap[Tuple] = Id;
1163     
1164     return DebugLoc::get(Id);
1165   }
1166
1167   /// ExtractDebugLocation - Extract debug location information 
1168   /// from llvm.dbg.func_start intrinsic.
1169   DebugLoc ExtractDebugLocation(DbgFuncStartInst &FSI,
1170                                 DebugLocTracker &DebugLocInfo) {
1171     DebugLoc DL;
1172     Value *SP = FSI.getSubprogram();
1173
1174     DISubprogram Subprogram(cast<MDNode>(SP));
1175     unsigned Line = Subprogram.getLineNumber();
1176     DICompileUnit CU(Subprogram.getCompileUnit());
1177
1178     // If this location is already tracked then use it.
1179     DebugLocTuple Tuple(CU.getNode(), Line, /* Column */ 0);
1180     DenseMap<DebugLocTuple, unsigned>::iterator II
1181       = DebugLocInfo.DebugIdMap.find(Tuple);
1182     if (II != DebugLocInfo.DebugIdMap.end())
1183       return DebugLoc::get(II->second);
1184
1185     // Add a new location entry.
1186     unsigned Id = DebugLocInfo.DebugLocations.size();
1187     DebugLocInfo.DebugLocations.push_back(Tuple);
1188     DebugLocInfo.DebugIdMap[Tuple] = Id;
1189     
1190     return DebugLoc::get(Id);
1191   }
1192
1193   /// isInlinedFnStart - Return true if FSI is starting an inlined function.
1194   bool isInlinedFnStart(DbgFuncStartInst &FSI, const Function *CurrentFn) {
1195     DISubprogram Subprogram(cast<MDNode>(FSI.getSubprogram()));
1196     if (Subprogram.describes(CurrentFn))
1197       return false;
1198
1199     return true;
1200   }
1201
1202   /// isInlinedFnEnd - Return true if REI is ending an inlined function.
1203   bool isInlinedFnEnd(DbgRegionEndInst &REI, const Function *CurrentFn) {
1204     DISubprogram Subprogram(cast<MDNode>(REI.getContext()));
1205     if (Subprogram.isNull() || Subprogram.describes(CurrentFn))
1206       return false;
1207
1208     return true;
1209   }
1210 }