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