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