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