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