Fix CodeGen/Alpha/2006-07-03-ASMFormalLowering.ll and PR818.
[oota-llvm.git] / lib / CodeGen / MachineDebugInfo.cpp
1 //===-- llvm/CodeGen/MachineDebugInfo.cpp -----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/MachineDebugInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/CodeGen/MachineLocation.h"
14 #include "llvm/DerivedTypes.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/Intrinsics.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/Support/Dwarf.h"
20
21 #include <iostream>
22
23 using namespace llvm;
24 using namespace llvm::dwarf;
25
26 // Handle the Pass registration stuff necessary to use TargetData's.
27 namespace {
28   RegisterPass<MachineDebugInfo> X("machinedebuginfo", "Debug Information");
29 }
30
31 //===----------------------------------------------------------------------===//
32
33 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
34 /// specified value in their initializer somewhere.
35 static void
36 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
37   // Scan though value users.
38   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
39     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
40       // If the user is a GlobalVariable then add to result.
41       Result.push_back(GV);
42     } else if (Constant *C = dyn_cast<Constant>(*I)) {
43       // If the user is a constant variable then scan its users
44       getGlobalVariablesUsing(C, Result);
45     }
46   }
47 }
48
49 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
50 /// named GlobalVariable.
51 static std::vector<GlobalVariable*>
52 getGlobalVariablesUsing(Module &M, const std::string &RootName) {
53   std::vector<GlobalVariable*> Result;  // GlobalVariables matching criteria.
54   
55   std::vector<const Type*> FieldTypes;
56   FieldTypes.push_back(Type::UIntTy);
57   FieldTypes.push_back(Type::UIntTy);
58
59   // Get the GlobalVariable root.
60   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
61                                                 StructType::get(FieldTypes));
62
63   // If present and linkonce then scan for users.
64   if (UseRoot && UseRoot->hasLinkOnceLinkage()) {
65     getGlobalVariablesUsing(UseRoot, Result);
66   }
67   
68   return Result;
69 }
70   
71 /// isStringValue - Return true if the given value can be coerced to a string.
72 ///
73 static bool isStringValue(Value *V) {
74   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
75     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
76       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
77       return Init->isString();
78     }
79   } else if (Constant *C = dyn_cast<Constant>(V)) {
80     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
81       return isStringValue(GV);
82     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
83       if (CE->getOpcode() == Instruction::GetElementPtr) {
84         if (CE->getNumOperands() == 3 &&
85             cast<Constant>(CE->getOperand(1))->isNullValue() &&
86             isa<ConstantInt>(CE->getOperand(2))) {
87           return isStringValue(CE->getOperand(0));
88         }
89       }
90     }
91   }
92   return false;
93 }
94
95 /// getGlobalVariable - Return either a direct or cast Global value.
96 ///
97 static GlobalVariable *getGlobalVariable(Value *V) {
98   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
99     return GV;
100   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
101     if (CE->getOpcode() == Instruction::Cast) {
102       return dyn_cast<GlobalVariable>(CE->getOperand(0));
103     }
104   }
105   return NULL;
106 }
107
108 /// isGlobalVariable - Return true if the given value can be coerced to a
109 /// GlobalVariable.
110 static bool isGlobalVariable(Value *V) {
111   if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
112     return true;
113   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
114     if (CE->getOpcode() == Instruction::Cast) {
115       return isa<GlobalVariable>(CE->getOperand(0));
116     }
117   }
118   return false;
119 }
120
121 /// getUIntOperand - Return ith operand if it is an unsigned integer.
122 ///
123 static ConstantUInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
124   // Make sure the GlobalVariable has an initializer.
125   if (!GV->hasInitializer()) return NULL;
126   
127   // Get the initializer constant.
128   ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
129   if (!CI) return NULL;
130   
131   // Check if there is at least i + 1 operands.
132   unsigned N = CI->getNumOperands();
133   if (i >= N) return NULL;
134
135   // Check constant.
136   return dyn_cast<ConstantUInt>(CI->getOperand(i));
137 }
138 //===----------------------------------------------------------------------===//
139
140 /// ApplyToFields - Target the visitor to each field of the debug information
141 /// descriptor.
142 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
143   DD->ApplyToFields(this);
144 }
145
146 //===----------------------------------------------------------------------===//
147 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
148 /// the supplied DebugInfoDesc.
149 class DICountVisitor : public DIVisitor {
150 private:
151   unsigned Count;                       // Running count of fields.
152   
153 public:
154   DICountVisitor() : DIVisitor(), Count(0) {}
155   
156   // Accessors.
157   unsigned getCount() const { return Count; }
158   
159   /// Apply - Count each of the fields.
160   ///
161   virtual void Apply(int &Field)             { ++Count; }
162   virtual void Apply(unsigned &Field)        { ++Count; }
163   virtual void Apply(int64_t &Field)         { ++Count; }
164   virtual void Apply(uint64_t &Field)        { ++Count; }
165   virtual void Apply(bool &Field)            { ++Count; }
166   virtual void Apply(std::string &Field)     { ++Count; }
167   virtual void Apply(DebugInfoDesc *&Field)  { ++Count; }
168   virtual void Apply(GlobalVariable *&Field) { ++Count; }
169   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
170     ++Count;
171   }
172 };
173
174 //===----------------------------------------------------------------------===//
175 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
176 /// supplied DebugInfoDesc.
177 class DIDeserializeVisitor : public DIVisitor {
178 private:
179   DIDeserializer &DR;                   // Active deserializer.
180   unsigned I;                           // Current operand index.
181   ConstantStruct *CI;                   // GlobalVariable constant initializer.
182
183 public:
184   DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
185   : DIVisitor()
186   , DR(D)
187   , I(0)
188   , CI(cast<ConstantStruct>(GV->getInitializer()))
189   {}
190   
191   /// Apply - Set the value of each of the fields.
192   ///
193   virtual void Apply(int &Field) {
194     Constant *C = CI->getOperand(I++);
195     Field = cast<ConstantSInt>(C)->getValue();
196   }
197   virtual void Apply(unsigned &Field) {
198     Constant *C = CI->getOperand(I++);
199     Field = cast<ConstantUInt>(C)->getValue();
200   }
201   virtual void Apply(int64_t &Field) {
202     Constant *C = CI->getOperand(I++);
203     Field = cast<ConstantSInt>(C)->getValue();
204   }
205   virtual void Apply(uint64_t &Field) {
206     Constant *C = CI->getOperand(I++);
207     Field = cast<ConstantUInt>(C)->getValue();
208   }
209   virtual void Apply(bool &Field) {
210     Constant *C = CI->getOperand(I++);
211     Field = cast<ConstantBool>(C)->getValue();
212   }
213   virtual void Apply(std::string &Field) {
214     Constant *C = CI->getOperand(I++);
215     Field = C->getStringValue();
216   }
217   virtual void Apply(DebugInfoDesc *&Field) {
218     Constant *C = CI->getOperand(I++);
219     Field = DR.Deserialize(C);
220   }
221   virtual void Apply(GlobalVariable *&Field) {
222     Constant *C = CI->getOperand(I++);
223     Field = getGlobalVariable(C);
224   }
225   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
226     Constant *C = CI->getOperand(I++);
227     GlobalVariable *GV = getGlobalVariable(C);
228     Field.resize(0);
229     // Have to be able to deal with the empty array case (zero initializer)
230     if (!GV->hasInitializer()) return;
231     if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
232       for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
233         GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
234         DebugInfoDesc *DE = DR.Deserialize(GVE);
235         Field.push_back(DE);
236       }
237     }
238   }
239 };
240
241 //===----------------------------------------------------------------------===//
242 /// DISerializeVisitor - This DIVisitor serializes all the fields in
243 /// the supplied DebugInfoDesc.
244 class DISerializeVisitor : public DIVisitor {
245 private:
246   DISerializer &SR;                     // Active serializer.
247   std::vector<Constant*> &Elements;     // Element accumulator.
248   
249 public:
250   DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
251   : DIVisitor()
252   , SR(S)
253   , Elements(E)
254   {}
255   
256   /// Apply - Set the value of each of the fields.
257   ///
258   virtual void Apply(int &Field) {
259     Elements.push_back(ConstantSInt::get(Type::IntTy, Field));
260   }
261   virtual void Apply(unsigned &Field) {
262     Elements.push_back(ConstantUInt::get(Type::UIntTy, Field));
263   }
264   virtual void Apply(int64_t &Field) {
265     Elements.push_back(ConstantSInt::get(Type::LongTy, Field));
266   }
267   virtual void Apply(uint64_t &Field) {
268     Elements.push_back(ConstantUInt::get(Type::ULongTy, Field));
269   }
270   virtual void Apply(bool &Field) {
271     Elements.push_back(ConstantBool::get(Field));
272   }
273   virtual void Apply(std::string &Field) {
274       Elements.push_back(SR.getString(Field));
275   }
276   virtual void Apply(DebugInfoDesc *&Field) {
277     GlobalVariable *GV = NULL;
278     
279     // If non-NULL then convert to global.
280     if (Field) GV = SR.Serialize(Field);
281     
282     // FIXME - At some point should use specific type.
283     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
284     
285     if (GV) {
286       // Set to pointer to global.
287       Elements.push_back(ConstantExpr::getCast(GV, EmptyTy));
288     } else {
289       // Use NULL.
290       Elements.push_back(ConstantPointerNull::get(EmptyTy));
291     }
292   }
293   virtual void Apply(GlobalVariable *&Field) {
294     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
295     if (Field) {
296       Elements.push_back(ConstantExpr::getCast(Field, EmptyTy));
297     } else {
298       Elements.push_back(ConstantPointerNull::get(EmptyTy));
299     }
300   }
301   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
302     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
303     unsigned N = Field.size();
304     ArrayType *AT = ArrayType::get(EmptyTy, N);
305     std::vector<Constant *> ArrayElements;
306
307     for (unsigned i = 0, N = Field.size(); i < N; ++i) {
308       GlobalVariable *GVE = SR.Serialize(Field[i]);
309       Constant *CE = ConstantExpr::getCast(GVE, EmptyTy);
310       ArrayElements.push_back(cast<Constant>(CE));
311     }
312     
313     Constant *CA = ConstantArray::get(AT, ArrayElements);
314     GlobalVariable *CAGV = new GlobalVariable(AT, true,
315                                               GlobalValue::InternalLinkage,
316                                               CA, "llvm.dbg.array",
317                                               SR.getModule());
318     CAGV->setSection("llvm.metadata");
319     Constant *CAE = ConstantExpr::getCast(CAGV, EmptyTy);
320     Elements.push_back(CAE);
321   }
322 };
323
324 //===----------------------------------------------------------------------===//
325 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
326 /// the supplied DebugInfoDesc.
327 class DIGetTypesVisitor : public DIVisitor {
328 private:
329   DISerializer &SR;                     // Active serializer.
330   std::vector<const Type*> &Fields;     // Type accumulator.
331   
332 public:
333   DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
334   : DIVisitor()
335   , SR(S)
336   , Fields(F)
337   {}
338   
339   /// Apply - Set the value of each of the fields.
340   ///
341   virtual void Apply(int &Field) {
342     Fields.push_back(Type::IntTy);
343   }
344   virtual void Apply(unsigned &Field) {
345     Fields.push_back(Type::UIntTy);
346   }
347   virtual void Apply(int64_t &Field) {
348     Fields.push_back(Type::LongTy);
349   }
350   virtual void Apply(uint64_t &Field) {
351     Fields.push_back(Type::ULongTy);
352   }
353   virtual void Apply(bool &Field) {
354     Fields.push_back(Type::BoolTy);
355   }
356   virtual void Apply(std::string &Field) {
357     Fields.push_back(SR.getStrPtrType());
358   }
359   virtual void Apply(DebugInfoDesc *&Field) {
360     // FIXME - At some point should use specific type.
361     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
362     Fields.push_back(EmptyTy);
363   }
364   virtual void Apply(GlobalVariable *&Field) {
365     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
366     Fields.push_back(EmptyTy);
367   }
368   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
369     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
370     Fields.push_back(EmptyTy);
371   }
372 };
373
374 //===----------------------------------------------------------------------===//
375 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
376 /// a constant initializer.
377 class DIVerifyVisitor : public DIVisitor {
378 private:
379   DIVerifier &VR;                       // Active verifier.
380   bool IsValid;                         // Validity status.
381   unsigned I;                           // Current operand index.
382   ConstantStruct *CI;                   // GlobalVariable constant initializer.
383   
384 public:
385   DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
386   : DIVisitor()
387   , VR(V)
388   , IsValid(true)
389   , I(0)
390   , CI(cast<ConstantStruct>(GV->getInitializer()))
391   {
392   }
393   
394   // Accessors.
395   bool isValid() const { return IsValid; }
396   
397   /// Apply - Set the value of each of the fields.
398   ///
399   virtual void Apply(int &Field) {
400     Constant *C = CI->getOperand(I++);
401     IsValid = IsValid && isa<ConstantInt>(C);
402   }
403   virtual void Apply(unsigned &Field) {
404     Constant *C = CI->getOperand(I++);
405     IsValid = IsValid && isa<ConstantInt>(C);
406   }
407   virtual void Apply(int64_t &Field) {
408     Constant *C = CI->getOperand(I++);
409     IsValid = IsValid && isa<ConstantInt>(C);
410   }
411   virtual void Apply(uint64_t &Field) {
412     Constant *C = CI->getOperand(I++);
413     IsValid = IsValid && isa<ConstantInt>(C);
414   }
415   virtual void Apply(bool &Field) {
416     Constant *C = CI->getOperand(I++);
417     IsValid = IsValid && isa<ConstantBool>(C);
418   }
419   virtual void Apply(std::string &Field) {
420     Constant *C = CI->getOperand(I++);
421     IsValid = IsValid && (!C || isStringValue(C));
422   }
423   virtual void Apply(DebugInfoDesc *&Field) {
424     // FIXME - Prepare the correct descriptor.
425     Constant *C = CI->getOperand(I++);
426     IsValid = IsValid && isGlobalVariable(C);
427   }
428   virtual void Apply(GlobalVariable *&Field) {
429     Constant *C = CI->getOperand(I++);
430     IsValid = IsValid && isGlobalVariable(C);
431   }
432   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
433     Constant *C = CI->getOperand(I++);
434     IsValid = IsValid && isGlobalVariable(C);
435     if (!IsValid) return;
436
437     GlobalVariable *GV = getGlobalVariable(C);
438     IsValid = IsValid && GV && GV->hasInitializer();
439     if (!IsValid) return;
440     
441     ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
442     IsValid = IsValid && CA;
443     if (!IsValid) return;
444
445     for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
446       IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
447       if (!IsValid) return;
448     
449       GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
450       VR.Verify(GVE);
451     }
452   }
453 };
454
455
456 //===----------------------------------------------------------------------===//
457
458 /// TagFromGlobal - Returns the tag number from a debug info descriptor
459 /// GlobalVariable.   Return DIIValid if operand is not an unsigned int. 
460 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
461   ConstantUInt *C = getUIntOperand(GV, 0);
462   return C ? ((unsigned)C->getValue() & ~LLVMDebugVersionMask) :
463              (unsigned)DW_TAG_invalid;
464 }
465
466 /// VersionFromGlobal - Returns the version number from a debug info
467 /// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
468 /// int.
469 unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
470   ConstantUInt *C = getUIntOperand(GV, 0);
471   return C ? ((unsigned)C->getValue() & LLVMDebugVersionMask) :
472              (unsigned)DW_TAG_invalid;
473 }
474
475 /// DescFactory - Create an instance of debug info descriptor based on Tag.
476 /// Return NULL if not a recognized Tag.
477 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
478   switch (Tag) {
479   case DW_TAG_anchor:           return new AnchorDesc();
480   case DW_TAG_compile_unit:     return new CompileUnitDesc();
481   case DW_TAG_variable:         return new GlobalVariableDesc();
482   case DW_TAG_subprogram:       return new SubprogramDesc();
483   case DW_TAG_lexical_block:    return new BlockDesc();
484   case DW_TAG_base_type:        return new BasicTypeDesc();
485   case DW_TAG_typedef:
486   case DW_TAG_pointer_type:        
487   case DW_TAG_reference_type:
488   case DW_TAG_const_type:
489   case DW_TAG_volatile_type:        
490   case DW_TAG_restrict_type:
491   case DW_TAG_member:           return new DerivedTypeDesc(Tag);
492   case DW_TAG_array_type:
493   case DW_TAG_structure_type:
494   case DW_TAG_union_type:
495   case DW_TAG_enumeration_type:
496   case DW_TAG_vector_type:
497   case DW_TAG_subroutine_type:  return new CompositeTypeDesc(Tag);
498   case DW_TAG_subrange_type:    return new SubrangeDesc();
499   case DW_TAG_enumerator:       return new EnumeratorDesc();
500   case DW_TAG_return_variable:
501   case DW_TAG_arg_variable:
502   case DW_TAG_auto_variable:    return new VariableDesc(Tag);
503   default: break;
504   }
505   return NULL;
506 }
507
508 /// getLinkage - get linkage appropriate for this type of descriptor.
509 ///
510 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
511   return GlobalValue::InternalLinkage;
512 }
513
514 /// ApplyToFields - Target the vistor to the fields of the descriptor.
515 ///
516 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
517   Visitor->Apply(Tag);
518 }
519
520 //===----------------------------------------------------------------------===//
521
522 AnchorDesc::AnchorDesc()
523 : DebugInfoDesc(DW_TAG_anchor)
524 , AnchorTag(0)
525 {}
526 AnchorDesc::AnchorDesc(AnchoredDesc *D)
527 : DebugInfoDesc(DW_TAG_anchor)
528 , AnchorTag(D->getTag())
529 {}
530
531 // Implement isa/cast/dyncast.
532 bool AnchorDesc::classof(const DebugInfoDesc *D) {
533   return D->getTag() == DW_TAG_anchor;
534 }
535   
536 /// getLinkage - get linkage appropriate for this type of descriptor.
537 ///
538 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
539   return GlobalValue::LinkOnceLinkage;
540 }
541
542 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
543 ///
544 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
545   DebugInfoDesc::ApplyToFields(Visitor);
546   
547   Visitor->Apply(AnchorTag);
548 }
549
550 /// getDescString - Return a string used to compose global names and labels. A
551 /// A global variable name needs to be defined for each debug descriptor that is
552 /// anchored. NOTE: that each global variable named here also needs to be added
553 /// to the list of names left external in the internalizer.
554 ///   ExternalNames.insert("llvm.dbg.compile_units");
555 ///   ExternalNames.insert("llvm.dbg.global_variables");
556 ///   ExternalNames.insert("llvm.dbg.subprograms");
557 const char *AnchorDesc::getDescString() const {
558   switch (AnchorTag) {
559   case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
560   case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
561   case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
562   default: break;
563   }
564
565   assert(0 && "Tag does not have a case for anchor string");
566   return "";
567 }
568
569 /// getTypeString - Return a string used to label this descriptors type.
570 ///
571 const char *AnchorDesc::getTypeString() const {
572   return "llvm.dbg.anchor.type";
573 }
574
575 #ifndef NDEBUG
576 void AnchorDesc::dump() {
577   std::cerr << getDescString() << " "
578             << "Version(" << getVersion() << "), "
579             << "Tag(" << getTag() << "), "
580             << "AnchorTag(" << AnchorTag << ")\n";
581 }
582 #endif
583
584 //===----------------------------------------------------------------------===//
585
586 AnchoredDesc::AnchoredDesc(unsigned T)
587 : DebugInfoDesc(T)
588 , Anchor(NULL)
589 {}
590
591 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
592 ///
593 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
594   DebugInfoDesc::ApplyToFields(Visitor);
595
596   Visitor->Apply(Anchor);
597 }
598
599 //===----------------------------------------------------------------------===//
600
601 CompileUnitDesc::CompileUnitDesc()
602 : AnchoredDesc(DW_TAG_compile_unit)
603 , Language(0)
604 , FileName("")
605 , Directory("")
606 , Producer("")
607 {}
608
609 // Implement isa/cast/dyncast.
610 bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
611   return D->getTag() == DW_TAG_compile_unit;
612 }
613
614 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
615 ///
616 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
617   AnchoredDesc::ApplyToFields(Visitor);
618   
619   // Handle cases out of sync with compiler.
620   if (getVersion() == 0) {
621     unsigned DebugVersion;
622     Visitor->Apply(DebugVersion);
623   }
624
625   Visitor->Apply(Language);
626   Visitor->Apply(FileName);
627   Visitor->Apply(Directory);
628   Visitor->Apply(Producer);
629 }
630
631 /// getDescString - Return a string used to compose global names and labels.
632 ///
633 const char *CompileUnitDesc::getDescString() const {
634   return "llvm.dbg.compile_unit";
635 }
636
637 /// getTypeString - Return a string used to label this descriptors type.
638 ///
639 const char *CompileUnitDesc::getTypeString() const {
640   return "llvm.dbg.compile_unit.type";
641 }
642
643 /// getAnchorString - Return a string used to label this descriptor's anchor.
644 ///
645 const char *CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
646 const char *CompileUnitDesc::getAnchorString() const {
647   return AnchorString;
648 }
649
650 #ifndef NDEBUG
651 void CompileUnitDesc::dump() {
652   std::cerr << getDescString() << " "
653             << "Version(" << getVersion() << "), "
654             << "Tag(" << getTag() << "), "
655             << "Anchor(" << getAnchor() << "), "
656             << "Language(" << Language << "), "
657             << "FileName(\"" << FileName << "\"), "
658             << "Directory(\"" << Directory << "\"), "
659             << "Producer(\"" << Producer << "\")\n";
660 }
661 #endif
662
663 //===----------------------------------------------------------------------===//
664
665 TypeDesc::TypeDesc(unsigned T)
666 : DebugInfoDesc(T)
667 , Context(NULL)
668 , Name("")
669 , File(NULL)
670 , Line(0)
671 , Size(0)
672 , Align(0)
673 , Offset(0)
674 {}
675
676 /// ApplyToFields - Target the visitor to the fields of the TypeDesc.
677 ///
678 void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
679   DebugInfoDesc::ApplyToFields(Visitor);
680   
681   Visitor->Apply(Context);
682   Visitor->Apply(Name);
683   Visitor->Apply(File);
684   Visitor->Apply(Line);
685   Visitor->Apply(Size);
686   Visitor->Apply(Align);
687   Visitor->Apply(Offset);
688 }
689
690 /// getDescString - Return a string used to compose global names and labels.
691 ///
692 const char *TypeDesc::getDescString() const {
693   return "llvm.dbg.type";
694 }
695
696 /// getTypeString - Return a string used to label this descriptor's type.
697 ///
698 const char *TypeDesc::getTypeString() const {
699   return "llvm.dbg.type.type";
700 }
701
702 #ifndef NDEBUG
703 void TypeDesc::dump() {
704   std::cerr << getDescString() << " "
705             << "Version(" << getVersion() << "), "
706             << "Tag(" << getTag() << "), "
707             << "Context(" << Context << "), "
708             << "Name(\"" << Name << "\"), "
709             << "File(" << File << "), "
710             << "Line(" << Line << "), "
711             << "Size(" << Size << "), "
712             << "Align(" << Align << "), "
713             << "Offset(" << Offset << ")\n";
714 }
715 #endif
716
717 //===----------------------------------------------------------------------===//
718
719 BasicTypeDesc::BasicTypeDesc()
720 : TypeDesc(DW_TAG_base_type)
721 , Encoding(0)
722 {}
723
724 // Implement isa/cast/dyncast.
725 bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
726   return D->getTag() == DW_TAG_base_type;
727 }
728
729 /// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
730 ///
731 void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
732   TypeDesc::ApplyToFields(Visitor);
733   
734   Visitor->Apply(Encoding);
735 }
736
737 /// getDescString - Return a string used to compose global names and labels.
738 ///
739 const char *BasicTypeDesc::getDescString() const {
740   return "llvm.dbg.basictype";
741 }
742
743 /// getTypeString - Return a string used to label this descriptor's type.
744 ///
745 const char *BasicTypeDesc::getTypeString() const {
746   return "llvm.dbg.basictype.type";
747 }
748
749 #ifndef NDEBUG
750 void BasicTypeDesc::dump() {
751   std::cerr << getDescString() << " "
752             << "Version(" << getVersion() << "), "
753             << "Tag(" << getTag() << "), "
754             << "Context(" << getContext() << "), "
755             << "Name(\"" << getName() << "\"), "
756             << "Size(" << getSize() << "), "
757             << "Encoding(" << Encoding << ")\n";
758 }
759 #endif
760
761 //===----------------------------------------------------------------------===//
762
763 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
764 : TypeDesc(T)
765 , FromType(NULL)
766 {}
767
768 // Implement isa/cast/dyncast.
769 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
770   unsigned T =  D->getTag();
771   switch (T) {
772   case DW_TAG_typedef:
773   case DW_TAG_pointer_type:
774   case DW_TAG_reference_type:
775   case DW_TAG_const_type:
776   case DW_TAG_volatile_type:
777   case DW_TAG_restrict_type:
778   case DW_TAG_member:
779     return true;
780   default: break;
781   }
782   return false;
783 }
784
785 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
786 ///
787 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
788   TypeDesc::ApplyToFields(Visitor);
789   
790   Visitor->Apply(FromType);
791 }
792
793 /// getDescString - Return a string used to compose global names and labels.
794 ///
795 const char *DerivedTypeDesc::getDescString() const {
796   return "llvm.dbg.derivedtype";
797 }
798
799 /// getTypeString - Return a string used to label this descriptor's type.
800 ///
801 const char *DerivedTypeDesc::getTypeString() const {
802   return "llvm.dbg.derivedtype.type";
803 }
804
805 #ifndef NDEBUG
806 void DerivedTypeDesc::dump() {
807   std::cerr << getDescString() << " "
808             << "Version(" << getVersion() << "), "
809             << "Tag(" << getTag() << "), "
810             << "Context(" << getContext() << "), "
811             << "Name(\"" << getName() << "\"), "
812             << "Size(" << getSize() << "), "
813             << "File(" << getFile() << "), "
814             << "Line(" << getLine() << "), "
815             << "FromType(" << FromType << ")\n";
816 }
817 #endif
818
819 //===----------------------------------------------------------------------===//
820
821 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
822 : DerivedTypeDesc(T)
823 , Elements()
824 {}
825   
826 // Implement isa/cast/dyncast.
827 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
828   unsigned T =  D->getTag();
829   switch (T) {
830   case DW_TAG_array_type:
831   case DW_TAG_structure_type:
832   case DW_TAG_union_type:
833   case DW_TAG_enumeration_type:
834   case DW_TAG_vector_type:
835   case DW_TAG_subroutine_type:
836     return true;
837   default: break;
838   }
839   return false;
840 }
841
842 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
843 ///
844 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
845   DerivedTypeDesc::ApplyToFields(Visitor);  
846
847   Visitor->Apply(Elements);
848 }
849
850 /// getDescString - Return a string used to compose global names and labels.
851 ///
852 const char *CompositeTypeDesc::getDescString() const {
853   return "llvm.dbg.compositetype";
854 }
855
856 /// getTypeString - Return a string used to label this descriptor's type.
857 ///
858 const char *CompositeTypeDesc::getTypeString() const {
859   return "llvm.dbg.compositetype.type";
860 }
861
862 #ifndef NDEBUG
863 void CompositeTypeDesc::dump() {
864   std::cerr << getDescString() << " "
865             << "Version(" << getVersion() << "), "
866             << "Tag(" << getTag() << "), "
867             << "Context(" << getContext() << "), "
868             << "Name(\"" << getName() << "\"), "
869             << "Size(" << getSize() << "), "
870             << "File(" << getFile() << "), "
871             << "Line(" << getLine() << "), "
872             << "FromType(" << getFromType() << "), "
873             << "Elements.size(" << Elements.size() << ")\n";
874 }
875 #endif
876
877 //===----------------------------------------------------------------------===//
878
879 SubrangeDesc::SubrangeDesc()
880 : DebugInfoDesc(DW_TAG_subrange_type)
881 , Lo(0)
882 , Hi(0)
883 {}
884
885 // Implement isa/cast/dyncast.
886 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
887   return D->getTag() == DW_TAG_subrange_type;
888 }
889
890 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
891 ///
892 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
893   DebugInfoDesc::ApplyToFields(Visitor);
894
895   Visitor->Apply(Lo);
896   Visitor->Apply(Hi);
897 }
898
899 /// getDescString - Return a string used to compose global names and labels.
900 ///
901 const char *SubrangeDesc::getDescString() const {
902   return "llvm.dbg.subrange";
903 }
904   
905 /// getTypeString - Return a string used to label this descriptor's type.
906 ///
907 const char *SubrangeDesc::getTypeString() const {
908   return "llvm.dbg.subrange.type";
909 }
910
911 #ifndef NDEBUG
912 void SubrangeDesc::dump() {
913   std::cerr << getDescString() << " "
914             << "Version(" << getVersion() << "), "
915             << "Tag(" << getTag() << "), "
916             << "Lo(" << Lo << "), "
917             << "Hi(" << Hi << ")\n";
918 }
919 #endif
920
921 //===----------------------------------------------------------------------===//
922
923 EnumeratorDesc::EnumeratorDesc()
924 : DebugInfoDesc(DW_TAG_enumerator)
925 , Name("")
926 , Value(0)
927 {}
928
929 // Implement isa/cast/dyncast.
930 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
931   return D->getTag() == DW_TAG_enumerator;
932 }
933
934 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
935 ///
936 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
937   DebugInfoDesc::ApplyToFields(Visitor);
938
939   Visitor->Apply(Name);
940   Visitor->Apply(Value);
941 }
942
943 /// getDescString - Return a string used to compose global names and labels.
944 ///
945 const char *EnumeratorDesc::getDescString() const {
946   return "llvm.dbg.enumerator";
947 }
948   
949 /// getTypeString - Return a string used to label this descriptor's type.
950 ///
951 const char *EnumeratorDesc::getTypeString() const {
952   return "llvm.dbg.enumerator.type";
953 }
954
955 #ifndef NDEBUG
956 void EnumeratorDesc::dump() {
957   std::cerr << getDescString() << " "
958             << "Version(" << getVersion() << "), "
959             << "Tag(" << getTag() << "), "
960             << "Name(" << Name << "), "
961             << "Value(" << Value << ")\n";
962 }
963 #endif
964
965 //===----------------------------------------------------------------------===//
966
967 VariableDesc::VariableDesc(unsigned T)
968 : DebugInfoDesc(T)
969 , Context(NULL)
970 , Name("")
971 , File(NULL)
972 , Line(0)
973 , TyDesc(0)
974 {}
975
976 // Implement isa/cast/dyncast.
977 bool VariableDesc::classof(const DebugInfoDesc *D) {
978   unsigned T =  D->getTag();
979   switch (T) {
980   case DW_TAG_auto_variable:
981   case DW_TAG_arg_variable:
982   case DW_TAG_return_variable:
983     return true;
984   default: break;
985   }
986   return false;
987 }
988
989 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
990 ///
991 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
992   DebugInfoDesc::ApplyToFields(Visitor);
993   
994   Visitor->Apply(Context);
995   Visitor->Apply(Name);
996   Visitor->Apply(File);
997   Visitor->Apply(Line);
998   Visitor->Apply(TyDesc);
999 }
1000
1001 /// getDescString - Return a string used to compose global names and labels.
1002 ///
1003 const char *VariableDesc::getDescString() const {
1004   return "llvm.dbg.variable";
1005 }
1006
1007 /// getTypeString - Return a string used to label this descriptor's type.
1008 ///
1009 const char *VariableDesc::getTypeString() const {
1010   return "llvm.dbg.variable.type";
1011 }
1012
1013 #ifndef NDEBUG
1014 void VariableDesc::dump() {
1015   std::cerr << getDescString() << " "
1016             << "Version(" << getVersion() << "), "
1017             << "Tag(" << getTag() << "), "
1018             << "Context(" << Context << "), "
1019             << "Name(\"" << Name << "\"), "
1020             << "File(" << File << "), "
1021             << "Line(" << Line << "), "
1022             << "TyDesc(" << TyDesc << ")\n";
1023 }
1024 #endif
1025
1026 //===----------------------------------------------------------------------===//
1027
1028 GlobalDesc::GlobalDesc(unsigned T)
1029 : AnchoredDesc(T)
1030 , Context(0)
1031 , Name("")
1032 , File(NULL)
1033 , Line(0)
1034 , TyDesc(NULL)
1035 , IsStatic(false)
1036 , IsDefinition(false)
1037 {}
1038
1039 /// ApplyToFields - Target the visitor to the fields of the global.
1040 ///
1041 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1042   AnchoredDesc::ApplyToFields(Visitor);
1043
1044   Visitor->Apply(Context);
1045   Visitor->Apply(Name);
1046   Visitor->Apply(File);
1047   Visitor->Apply(Line);
1048   Visitor->Apply(TyDesc);
1049   Visitor->Apply(IsStatic);
1050   Visitor->Apply(IsDefinition);
1051 }
1052
1053 //===----------------------------------------------------------------------===//
1054
1055 GlobalVariableDesc::GlobalVariableDesc()
1056 : GlobalDesc(DW_TAG_variable)
1057 , Global(NULL)
1058 {}
1059
1060 // Implement isa/cast/dyncast.
1061 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1062   return D->getTag() == DW_TAG_variable; 
1063 }
1064
1065 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1066 ///
1067 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1068   GlobalDesc::ApplyToFields(Visitor);
1069
1070   Visitor->Apply(Global);
1071 }
1072
1073 /// getDescString - Return a string used to compose global names and labels.
1074 ///
1075 const char *GlobalVariableDesc::getDescString() const {
1076   return "llvm.dbg.global_variable";
1077 }
1078
1079 /// getTypeString - Return a string used to label this descriptors type.
1080 ///
1081 const char *GlobalVariableDesc::getTypeString() const {
1082   return "llvm.dbg.global_variable.type";
1083 }
1084
1085 /// getAnchorString - Return a string used to label this descriptor's anchor.
1086 ///
1087 const char *GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1088 const char *GlobalVariableDesc::getAnchorString() const {
1089   return AnchorString;
1090 }
1091
1092 #ifndef NDEBUG
1093 void GlobalVariableDesc::dump() {
1094   std::cerr << getDescString() << " "
1095             << "Version(" << getVersion() << "), "
1096             << "Tag(" << getTag() << "), "
1097             << "Anchor(" << getAnchor() << "), "
1098             << "Name(\"" << getName() << "\"), "
1099             << "File(" << getFile() << "),"
1100             << "Line(" << getLine() << "),"
1101             << "Type(\"" << getType() << "\"), "
1102             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1103             << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1104             << "Global(" << Global << ")\n";
1105 }
1106 #endif
1107
1108 //===----------------------------------------------------------------------===//
1109
1110 SubprogramDesc::SubprogramDesc()
1111 : GlobalDesc(DW_TAG_subprogram)
1112 {}
1113
1114 // Implement isa/cast/dyncast.
1115 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1116   return D->getTag() == DW_TAG_subprogram;
1117 }
1118
1119 /// ApplyToFields - Target the visitor to the fields of the
1120 /// SubprogramDesc.
1121 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1122   GlobalDesc::ApplyToFields(Visitor);
1123 }
1124
1125 /// getDescString - Return a string used to compose global names and labels.
1126 ///
1127 const char *SubprogramDesc::getDescString() const {
1128   return "llvm.dbg.subprogram";
1129 }
1130
1131 /// getTypeString - Return a string used to label this descriptors type.
1132 ///
1133 const char *SubprogramDesc::getTypeString() const {
1134   return "llvm.dbg.subprogram.type";
1135 }
1136
1137 /// getAnchorString - Return a string used to label this descriptor's anchor.
1138 ///
1139 const char *SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1140 const char *SubprogramDesc::getAnchorString() const {
1141   return AnchorString;
1142 }
1143
1144 #ifndef NDEBUG
1145 void SubprogramDesc::dump() {
1146   std::cerr << getDescString() << " "
1147             << "Version(" << getVersion() << "), "
1148             << "Tag(" << getTag() << "), "
1149             << "Anchor(" << getAnchor() << "), "
1150             << "Name(\"" << getName() << "\"), "
1151             << "File(" << getFile() << "),"
1152             << "Line(" << getLine() << "),"
1153             << "Type(\"" << getType() << "\"), "
1154             << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1155             << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1156 }
1157 #endif
1158
1159 //===----------------------------------------------------------------------===//
1160
1161 BlockDesc::BlockDesc()
1162 : DebugInfoDesc(DW_TAG_lexical_block)
1163 , Context(NULL)
1164 {}
1165
1166 // Implement isa/cast/dyncast.
1167 bool BlockDesc::classof(const DebugInfoDesc *D) {
1168   return D->getTag() == DW_TAG_lexical_block;
1169 }
1170
1171 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1172 ///
1173 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1174   DebugInfoDesc::ApplyToFields(Visitor);
1175
1176   Visitor->Apply(Context);
1177 }
1178
1179 /// getDescString - Return a string used to compose global names and labels.
1180 ///
1181 const char *BlockDesc::getDescString() const {
1182   return "llvm.dbg.block";
1183 }
1184
1185 /// getTypeString - Return a string used to label this descriptors type.
1186 ///
1187 const char *BlockDesc::getTypeString() const {
1188   return "llvm.dbg.block.type";
1189 }
1190
1191 #ifndef NDEBUG
1192 void BlockDesc::dump() {
1193   std::cerr << getDescString() << " "
1194             << "Version(" << getVersion() << "), "
1195             << "Tag(" << getTag() << "),"
1196             << "Context(" << Context << ")\n";
1197 }
1198 #endif
1199
1200 //===----------------------------------------------------------------------===//
1201
1202 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1203   return Deserialize(getGlobalVariable(V));
1204 }
1205 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1206   // Handle NULL.
1207   if (!GV) return NULL;
1208
1209   // Check to see if it has been already deserialized.
1210   DebugInfoDesc *&Slot = GlobalDescs[GV];
1211   if (Slot) return Slot;
1212
1213   // Get the Tag from the global.
1214   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1215   
1216   // Create an empty instance of the correct sort.
1217   Slot = DebugInfoDesc::DescFactory(Tag);
1218   
1219   // If not a user defined descriptor.
1220   if (Slot) {
1221     // Deserialize the fields.
1222     DIDeserializeVisitor DRAM(*this, GV);
1223     DRAM.ApplyToFields(Slot);
1224   }
1225   
1226   return Slot;
1227 }
1228
1229 //===----------------------------------------------------------------------===//
1230
1231 /// getStrPtrType - Return a "sbyte *" type.
1232 ///
1233 const PointerType *DISerializer::getStrPtrType() {
1234   // If not already defined.
1235   if (!StrPtrTy) {
1236     // Construct the pointer to signed bytes.
1237     StrPtrTy = PointerType::get(Type::SByteTy);
1238   }
1239   
1240   return StrPtrTy;
1241 }
1242
1243 /// getEmptyStructPtrType - Return a "{ }*" type.
1244 ///
1245 const PointerType *DISerializer::getEmptyStructPtrType() {
1246   // If not already defined.
1247   if (!EmptyStructPtrTy) {
1248     // Construct the empty structure type.
1249     const StructType *EmptyStructTy =
1250                                     StructType::get(std::vector<const Type*>());
1251     // Construct the pointer to empty structure type.
1252     EmptyStructPtrTy = PointerType::get(EmptyStructTy);
1253   }
1254   
1255   return EmptyStructPtrTy;
1256 }
1257
1258 /// getTagType - Return the type describing the specified descriptor (via tag.)
1259 ///
1260 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1261   // Attempt to get the previously defined type.
1262   StructType *&Ty = TagTypes[DD->getTag()];
1263   
1264   // If not already defined.
1265   if (!Ty) {
1266     // Set up fields vector.
1267     std::vector<const Type*> Fields;
1268     // Get types of fields.
1269     DIGetTypesVisitor GTAM(*this, Fields);
1270     GTAM.ApplyToFields(DD);
1271
1272     // Construct structured type.
1273     Ty = StructType::get(Fields);
1274     
1275     // Register type name with module.
1276     M->addTypeName(DD->getTypeString(), Ty);
1277   }
1278   
1279   return Ty;
1280 }
1281
1282 /// getString - Construct the string as constant string global.
1283 ///
1284 Constant *DISerializer::getString(const std::string &String) {
1285   // Check string cache for previous edition.
1286   Constant *&Slot = StringCache[String];
1287   // Return Constant if previously defined.
1288   if (Slot) return Slot;
1289   // If empty string then use a sbyte* null instead.
1290   if (String.empty()) {
1291     Slot = ConstantPointerNull::get(getStrPtrType());
1292   } else {
1293     // Construct string as an llvm constant.
1294     Constant *ConstStr = ConstantArray::get(String);
1295     // Otherwise create and return a new string global.
1296     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1297                                                GlobalVariable::InternalLinkage,
1298                                                ConstStr, "str", M);
1299     StrGV->setSection("llvm.metadata");
1300     // Convert to generic string pointer.
1301     Slot = ConstantExpr::getCast(StrGV, getStrPtrType());
1302   }
1303   return Slot;
1304   
1305 }
1306
1307 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1308 /// so that it can be serialized to a .bc or .ll file.
1309 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1310   // Check if the DebugInfoDesc is already in the map.
1311   GlobalVariable *&Slot = DescGlobals[DD];
1312   
1313   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1314   if (Slot) return Slot;
1315   
1316   // Get the type associated with the Tag.
1317   const StructType *Ty = getTagType(DD);
1318
1319   // Create the GlobalVariable early to prevent infinite recursion.
1320   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1321                                           NULL, DD->getDescString(), M);
1322   GV->setSection("llvm.metadata");
1323
1324   // Insert new GlobalVariable in DescGlobals map.
1325   Slot = GV;
1326  
1327   // Set up elements vector
1328   std::vector<Constant*> Elements;
1329   // Add fields.
1330   DISerializeVisitor SRAM(*this, Elements);
1331   SRAM.ApplyToFields(DD);
1332   
1333   // Set the globals initializer.
1334   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1335   
1336   return GV;
1337 }
1338
1339 //===----------------------------------------------------------------------===//
1340
1341 /// Verify - Return true if the GlobalVariable appears to be a valid
1342 /// serialization of a DebugInfoDesc.
1343 bool DIVerifier::Verify(Value *V) {
1344   return !V || Verify(getGlobalVariable(V));
1345 }
1346 bool DIVerifier::Verify(GlobalVariable *GV) {
1347   // NULLs are valid.
1348   if (!GV) return true;
1349   
1350   // Check prior validity.
1351   unsigned &ValiditySlot = Validity[GV];
1352   
1353   // If visited before then use old state.
1354   if (ValiditySlot) return ValiditySlot == Valid;
1355   
1356   // Assume validity for the time being (recursion.)
1357   ValiditySlot = Valid;
1358   
1359   // Make sure the global is internal or link once (anchor.)
1360   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1361       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1362     ValiditySlot = Invalid;
1363     return false;
1364   }
1365
1366   // Get the Tag
1367   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1368   
1369   // Check for user defined descriptors.
1370   if (Tag == DW_TAG_invalid) return true;
1371
1372   // Construct an empty DebugInfoDesc.
1373   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1374   
1375   // Allow for user defined descriptors.
1376   if (!DD) return true;
1377   
1378   // Get the initializer constant.
1379   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1380   
1381   // Get the operand count.
1382   unsigned N = CI->getNumOperands();
1383   
1384   // Get the field count.
1385   unsigned &CountSlot = Counts[Tag];
1386   if (!CountSlot) {
1387     // Check the operand count to the field count
1388     DICountVisitor CTAM;
1389     CTAM.ApplyToFields(DD);
1390     CountSlot = CTAM.getCount();
1391   }
1392   
1393   // Field count must be at most equal operand count.
1394   if (CountSlot >  N) {
1395     delete DD;
1396     ValiditySlot = Invalid;
1397     return false;
1398   }
1399   
1400   // Check each field for valid type.
1401   DIVerifyVisitor VRAM(*this, GV);
1402   VRAM.ApplyToFields(DD);
1403   
1404   // Release empty DebugInfoDesc.
1405   delete DD;
1406   
1407   // If fields are not valid.
1408   if (!VRAM.isValid()) {
1409     ValiditySlot = Invalid;
1410     return false;
1411   }
1412   
1413   return true;
1414 }
1415
1416 //===----------------------------------------------------------------------===//
1417
1418 DebugScope::~DebugScope() {
1419   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1420   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1421 }
1422
1423 //===----------------------------------------------------------------------===//
1424
1425 MachineDebugInfo::MachineDebugInfo()
1426 : DR()
1427 , VR()
1428 , CompileUnits()
1429 , Directories()
1430 , SourceFiles()
1431 , Lines()
1432 , LabelID(0)
1433 , ScopeMap()
1434 , RootScope(NULL)
1435 , FrameMoves()
1436 {}
1437 MachineDebugInfo::~MachineDebugInfo() {
1438
1439 }
1440
1441 /// doInitialization - Initialize the debug state for a new module.
1442 ///
1443 bool MachineDebugInfo::doInitialization() {
1444   return false;
1445 }
1446
1447 /// doFinalization - Tear down the debug state after completion of a module.
1448 ///
1449 bool MachineDebugInfo::doFinalization() {
1450   return false;
1451 }
1452
1453 /// BeginFunction - Begin gathering function debug information.
1454 ///
1455 void MachineDebugInfo::BeginFunction(MachineFunction *MF) {
1456   // Coming soon.
1457 }
1458
1459 /// MachineDebugInfo::EndFunction - Discard function debug information.
1460 ///
1461 void MachineDebugInfo::EndFunction() {
1462   // Clean up scope information.
1463   if (RootScope) {
1464     delete RootScope;
1465     ScopeMap.clear();
1466     RootScope = NULL;
1467   }
1468   
1469   // Clean up frame info.
1470   for (unsigned i = 0, N = FrameMoves.size(); i < N; ++i) delete FrameMoves[i];
1471   FrameMoves.clear();
1472 }
1473
1474 /// getDescFor - Convert a Value to a debug information descriptor.
1475 ///
1476 // FIXME - use new Value type when available.
1477 DebugInfoDesc *MachineDebugInfo::getDescFor(Value *V) {
1478   return DR.Deserialize(V);
1479 }
1480
1481 /// Verify - Verify that a Value is debug information descriptor.
1482 ///
1483 bool MachineDebugInfo::Verify(Value *V) {
1484   return VR.Verify(V);
1485 }
1486
1487 /// AnalyzeModule - Scan the module for global debug information.
1488 ///
1489 void MachineDebugInfo::AnalyzeModule(Module &M) {
1490   SetupCompileUnits(M);
1491 }
1492
1493 /// SetupCompileUnits - Set up the unique vector of compile units.
1494 ///
1495 void MachineDebugInfo::SetupCompileUnits(Module &M) {
1496   std::vector<CompileUnitDesc *>CU = getAnchoredDescriptors<CompileUnitDesc>(M);
1497   
1498   for (unsigned i = 0, N = CU.size(); i < N; i++) {
1499     CompileUnits.insert(CU[i]);
1500   }
1501 }
1502
1503 /// getCompileUnits - Return a vector of debug compile units.
1504 ///
1505 const UniqueVector<CompileUnitDesc *> MachineDebugInfo::getCompileUnits()const{
1506   return CompileUnits;
1507 }
1508
1509 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1510 /// named GlobalVariable.
1511 std::vector<GlobalVariable*>
1512 MachineDebugInfo::getGlobalVariablesUsing(Module &M,
1513                                           const std::string &RootName) {
1514   return ::getGlobalVariablesUsing(M, RootName);
1515 }
1516
1517 /// RecordLabel - Records location information and associates it with a
1518 /// debug label.  Returns a unique label ID used to generate a label and 
1519 /// provide correspondence to the source line list.
1520 unsigned MachineDebugInfo::RecordLabel(unsigned Line, unsigned Column,
1521                                        unsigned Source) {
1522   unsigned ID = NextLabelID();
1523   Lines.push_back(new SourceLineInfo(Line, Column, Source, ID));
1524   return ID;
1525 }
1526
1527 /// RecordSource - Register a source file with debug info. Returns an source
1528 /// ID.
1529 unsigned MachineDebugInfo::RecordSource(const std::string &Directory,
1530                                         const std::string &Source) {
1531   unsigned DirectoryID = Directories.insert(Directory);
1532   return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1533 }
1534 unsigned MachineDebugInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1535   return RecordSource(CompileUnit->getDirectory(),
1536                       CompileUnit->getFileName());
1537 }
1538
1539 /// RecordRegionStart - Indicate the start of a region.
1540 ///
1541 unsigned MachineDebugInfo::RecordRegionStart(Value *V) {
1542   // FIXME - need to be able to handle split scopes because of bb cloning.
1543   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1544   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1545   unsigned ID = NextLabelID();
1546   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1547   return ID;
1548 }
1549
1550 /// RecordRegionEnd - Indicate the end of a region.
1551 ///
1552 unsigned MachineDebugInfo::RecordRegionEnd(Value *V) {
1553   // FIXME - need to be able to handle split scopes because of bb cloning.
1554   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1555   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1556   unsigned ID = NextLabelID();
1557   Scope->setEndLabelID(ID);
1558   return ID;
1559 }
1560
1561 /// RecordVariable - Indicate the declaration of  a local variable.
1562 ///
1563 void MachineDebugInfo::RecordVariable(Value *V, unsigned FrameIndex) {
1564   VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(V));
1565   DebugScope *Scope = getOrCreateScope(VD->getContext());
1566   DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1567   Scope->AddVariable(DV);
1568 }
1569
1570 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1571 ///
1572 DebugScope *MachineDebugInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1573   DebugScope *&Slot = ScopeMap[ScopeDesc];
1574   if (!Slot) {
1575     // FIXME - breaks down when the context is an inlined function.
1576     DebugInfoDesc *ParentDesc = NULL;
1577     if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1578       ParentDesc = Block->getContext();
1579     }
1580     DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1581     Slot = new DebugScope(Parent, ScopeDesc);
1582     if (Parent) {
1583       Parent->AddScope(Slot);
1584     } else if (RootScope) {
1585       // FIXME - Add inlined function scopes to the root so we can delete
1586       // them later.  Long term, handle inlined functions properly.
1587       RootScope->AddScope(Slot);
1588     } else {
1589       // First function is top level function.
1590       RootScope = Slot;
1591     }
1592   }
1593   return Slot;
1594 }
1595
1596