rename files
[oota-llvm.git] / lib / CodeGen / MachineModuleInfo.cpp
1 //===-- llvm/CodeGen/MachineModuleInfo.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/MachineModuleInfo.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<MachineModuleInfo> X("machinemoduleinfo", "Module 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::Int32Ty);
59   FieldTypes.push_back(Type::Int32Ty);
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<ConstantInt>(C)->getZExtValue();
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::Int32Ty, int32_t(Field)));
268   }
269   virtual void Apply(unsigned &Field) {
270     Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
271   }
272   virtual void Apply(int64_t &Field) {
273     Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
274   }
275   virtual void Apply(uint64_t &Field) {
276     Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
277   }
278   virtual void Apply(bool &Field) {
279     Elements.push_back(ConstantInt::get(Type::Int1Ty, 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::Int32Ty);
355   }
356   virtual void Apply(unsigned &Field) {
357     Fields.push_back(Type::Int32Ty);
358   }
359   virtual void Apply(int64_t &Field) {
360     Fields.push_back(Type::Int64Ty);
361   }
362   virtual void Apply(uint64_t &Field) {
363     Fields.push_back(Type::Int64Ty);
364   }
365   virtual void Apply(bool &Field) {
366     Fields.push_back(Type::Int1Ty);
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<ConstantInt>(C) && C->getType() == Type::Int1Ty;
430   }
431   virtual void Apply(std::string &Field) {
432     Constant *C = CI->getOperand(I++);
433     IsValid = IsValid &&
434               (!C || isStringValue(C) || C->isNullValue());
435   }
436   virtual void Apply(DebugInfoDesc *&Field) {
437     // FIXME - Prepare the correct descriptor.
438     Constant *C = CI->getOperand(I++);
439     IsValid = IsValid && isGlobalVariable(C);
440   }
441   virtual void Apply(GlobalVariable *&Field) {
442     Constant *C = CI->getOperand(I++);
443     IsValid = IsValid && isGlobalVariable(C);
444   }
445   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
446     Constant *C = CI->getOperand(I++);
447     IsValid = IsValid && isGlobalVariable(C);
448     if (!IsValid) return;
449
450     GlobalVariable *GV = getGlobalVariable(C);
451     IsValid = IsValid && GV && GV->hasInitializer();
452     if (!IsValid) return;
453     
454     ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
455     IsValid = IsValid && CA;
456     if (!IsValid) return;
457
458     for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
459       IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
460       if (!IsValid) return;
461     
462       GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
463       VR.Verify(GVE);
464     }
465   }
466 };
467
468
469 //===----------------------------------------------------------------------===//
470
471 /// TagFromGlobal - Returns the tag number from a debug info descriptor
472 /// GlobalVariable.   Return DIIValid if operand is not an unsigned int. 
473 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
474   ConstantInt *C = getUIntOperand(GV, 0);
475   return C ? ((unsigned)C->getZExtValue() & ~LLVMDebugVersionMask) :
476              (unsigned)DW_TAG_invalid;
477 }
478
479 /// VersionFromGlobal - Returns the version number from a debug info
480 /// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
481 /// int.
482 unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
483   ConstantInt *C = getUIntOperand(GV, 0);
484   return C ? ((unsigned)C->getZExtValue() & LLVMDebugVersionMask) :
485              (unsigned)DW_TAG_invalid;
486 }
487
488 /// DescFactory - Create an instance of debug info descriptor based on Tag.
489 /// Return NULL if not a recognized Tag.
490 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
491   switch (Tag) {
492   case DW_TAG_anchor:           return new AnchorDesc();
493   case DW_TAG_compile_unit:     return new CompileUnitDesc();
494   case DW_TAG_variable:         return new GlobalVariableDesc();
495   case DW_TAG_subprogram:       return new SubprogramDesc();
496   case DW_TAG_lexical_block:    return new BlockDesc();
497   case DW_TAG_base_type:        return new BasicTypeDesc();
498   case DW_TAG_typedef:
499   case DW_TAG_pointer_type:        
500   case DW_TAG_reference_type:
501   case DW_TAG_const_type:
502   case DW_TAG_volatile_type:        
503   case DW_TAG_restrict_type:
504   case DW_TAG_member:
505   case DW_TAG_inheritance:      return new DerivedTypeDesc(Tag);
506   case DW_TAG_array_type:
507   case DW_TAG_structure_type:
508   case DW_TAG_union_type:
509   case DW_TAG_enumeration_type:
510   case DW_TAG_vector_type:
511   case DW_TAG_subroutine_type:  return new CompositeTypeDesc(Tag);
512   case DW_TAG_subrange_type:    return new SubrangeDesc();
513   case DW_TAG_enumerator:       return new EnumeratorDesc();
514   case DW_TAG_return_variable:
515   case DW_TAG_arg_variable:
516   case DW_TAG_auto_variable:    return new VariableDesc(Tag);
517   default: break;
518   }
519   return NULL;
520 }
521
522 /// getLinkage - get linkage appropriate for this type of descriptor.
523 ///
524 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
525   return GlobalValue::InternalLinkage;
526 }
527
528 /// ApplyToFields - Target the vistor to the fields of the descriptor.
529 ///
530 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
531   Visitor->Apply(Tag);
532 }
533
534 //===----------------------------------------------------------------------===//
535
536 AnchorDesc::AnchorDesc()
537 : DebugInfoDesc(DW_TAG_anchor)
538 , AnchorTag(0)
539 {}
540 AnchorDesc::AnchorDesc(AnchoredDesc *D)
541 : DebugInfoDesc(DW_TAG_anchor)
542 , AnchorTag(D->getTag())
543 {}
544
545 // Implement isa/cast/dyncast.
546 bool AnchorDesc::classof(const DebugInfoDesc *D) {
547   return D->getTag() == DW_TAG_anchor;
548 }
549   
550 /// getLinkage - get linkage appropriate for this type of descriptor.
551 ///
552 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
553   return GlobalValue::LinkOnceLinkage;
554 }
555
556 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
557 ///
558 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
559   DebugInfoDesc::ApplyToFields(Visitor);
560   
561   Visitor->Apply(AnchorTag);
562 }
563
564 /// getDescString - Return a string used to compose global names and labels. A
565 /// A global variable name needs to be defined for each debug descriptor that is
566 /// anchored. NOTE: that each global variable named here also needs to be added
567 /// to the list of names left external in the internalizer.
568 ///   ExternalNames.insert("llvm.dbg.compile_units");
569 ///   ExternalNames.insert("llvm.dbg.global_variables");
570 ///   ExternalNames.insert("llvm.dbg.subprograms");
571 const char *AnchorDesc::getDescString() const {
572   switch (AnchorTag) {
573   case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
574   case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
575   case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
576   default: break;
577   }
578
579   assert(0 && "Tag does not have a case for anchor string");
580   return "";
581 }
582
583 /// getTypeString - Return a string used to label this descriptors type.
584 ///
585 const char *AnchorDesc::getTypeString() const {
586   return "llvm.dbg.anchor.type";
587 }
588
589 #ifndef NDEBUG
590 void AnchorDesc::dump() {
591   cerr << getDescString() << " "
592        << "Version(" << getVersion() << "), "
593        << "Tag(" << getTag() << "), "
594        << "AnchorTag(" << AnchorTag << ")\n";
595 }
596 #endif
597
598 //===----------------------------------------------------------------------===//
599
600 AnchoredDesc::AnchoredDesc(unsigned T)
601 : DebugInfoDesc(T)
602 , Anchor(NULL)
603 {}
604
605 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
606 ///
607 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
608   DebugInfoDesc::ApplyToFields(Visitor);
609
610   Visitor->Apply(Anchor);
611 }
612
613 //===----------------------------------------------------------------------===//
614
615 CompileUnitDesc::CompileUnitDesc()
616 : AnchoredDesc(DW_TAG_compile_unit)
617 , Language(0)
618 , FileName("")
619 , Directory("")
620 , Producer("")
621 {}
622
623 // Implement isa/cast/dyncast.
624 bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
625   return D->getTag() == DW_TAG_compile_unit;
626 }
627
628 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
629 ///
630 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
631   AnchoredDesc::ApplyToFields(Visitor);
632   
633   // Handle cases out of sync with compiler.
634   if (getVersion() == 0) {
635     unsigned DebugVersion;
636     Visitor->Apply(DebugVersion);
637   }
638
639   Visitor->Apply(Language);
640   Visitor->Apply(FileName);
641   Visitor->Apply(Directory);
642   Visitor->Apply(Producer);
643 }
644
645 /// getDescString - Return a string used to compose global names and labels.
646 ///
647 const char *CompileUnitDesc::getDescString() const {
648   return "llvm.dbg.compile_unit";
649 }
650
651 /// getTypeString - Return a string used to label this descriptors type.
652 ///
653 const char *CompileUnitDesc::getTypeString() const {
654   return "llvm.dbg.compile_unit.type";
655 }
656
657 /// getAnchorString - Return a string used to label this descriptor's anchor.
658 ///
659 const char *CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
660 const char *CompileUnitDesc::getAnchorString() const {
661   return AnchorString;
662 }
663
664 #ifndef NDEBUG
665 void CompileUnitDesc::dump() {
666   cerr << getDescString() << " "
667        << "Version(" << getVersion() << "), "
668        << "Tag(" << getTag() << "), "
669        << "Anchor(" << getAnchor() << "), "
670        << "Language(" << Language << "), "
671        << "FileName(\"" << FileName << "\"), "
672        << "Directory(\"" << Directory << "\"), "
673        << "Producer(\"" << Producer << "\")\n";
674 }
675 #endif
676
677 //===----------------------------------------------------------------------===//
678
679 TypeDesc::TypeDesc(unsigned T)
680 : DebugInfoDesc(T)
681 , Context(NULL)
682 , Name("")
683 , File(NULL)
684 , Line(0)
685 , Size(0)
686 , Align(0)
687 , Offset(0)
688 , Flags(0)
689 {}
690
691 /// ApplyToFields - Target the visitor to the fields of the TypeDesc.
692 ///
693 void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
694   DebugInfoDesc::ApplyToFields(Visitor);
695   
696   Visitor->Apply(Context);
697   Visitor->Apply(Name);
698   Visitor->Apply(File);
699   Visitor->Apply(Line);
700   Visitor->Apply(Size);
701   Visitor->Apply(Align);
702   Visitor->Apply(Offset);
703   if (getVersion() > LLVMDebugVersion4) Visitor->Apply(Flags);
704 }
705
706 /// getDescString - Return a string used to compose global names and labels.
707 ///
708 const char *TypeDesc::getDescString() const {
709   return "llvm.dbg.type";
710 }
711
712 /// getTypeString - Return a string used to label this descriptor's type.
713 ///
714 const char *TypeDesc::getTypeString() const {
715   return "llvm.dbg.type.type";
716 }
717
718 #ifndef NDEBUG
719 void TypeDesc::dump() {
720   cerr << getDescString() << " "
721        << "Version(" << getVersion() << "), "
722        << "Tag(" << getTag() << "), "
723        << "Context(" << Context << "), "
724        << "Name(\"" << Name << "\"), "
725        << "File(" << File << "), "
726        << "Line(" << Line << "), "
727        << "Size(" << Size << "), "
728        << "Align(" << Align << "), "
729        << "Offset(" << Offset << "), "
730        << "Flags(" << Flags << ")\n";
731 }
732 #endif
733
734 //===----------------------------------------------------------------------===//
735
736 BasicTypeDesc::BasicTypeDesc()
737 : TypeDesc(DW_TAG_base_type)
738 , Encoding(0)
739 {}
740
741 // Implement isa/cast/dyncast.
742 bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
743   return D->getTag() == DW_TAG_base_type;
744 }
745
746 /// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
747 ///
748 void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
749   TypeDesc::ApplyToFields(Visitor);
750   
751   Visitor->Apply(Encoding);
752 }
753
754 /// getDescString - Return a string used to compose global names and labels.
755 ///
756 const char *BasicTypeDesc::getDescString() const {
757   return "llvm.dbg.basictype";
758 }
759
760 /// getTypeString - Return a string used to label this descriptor's type.
761 ///
762 const char *BasicTypeDesc::getTypeString() const {
763   return "llvm.dbg.basictype.type";
764 }
765
766 #ifndef NDEBUG
767 void BasicTypeDesc::dump() {
768   cerr << getDescString() << " "
769        << "Version(" << getVersion() << "), "
770        << "Tag(" << getTag() << "), "
771        << "Context(" << getContext() << "), "
772        << "Name(\"" << getName() << "\"), "
773        << "Size(" << getSize() << "), "
774        << "Encoding(" << Encoding << ")\n";
775 }
776 #endif
777
778 //===----------------------------------------------------------------------===//
779
780 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
781 : TypeDesc(T)
782 , FromType(NULL)
783 {}
784
785 // Implement isa/cast/dyncast.
786 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
787   unsigned T =  D->getTag();
788   switch (T) {
789   case DW_TAG_typedef:
790   case DW_TAG_pointer_type:
791   case DW_TAG_reference_type:
792   case DW_TAG_const_type:
793   case DW_TAG_volatile_type:
794   case DW_TAG_restrict_type:
795   case DW_TAG_member:
796   case DW_TAG_inheritance:
797     return true;
798   default: break;
799   }
800   return false;
801 }
802
803 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
804 ///
805 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
806   TypeDesc::ApplyToFields(Visitor);
807   
808   Visitor->Apply(FromType);
809 }
810
811 /// getDescString - Return a string used to compose global names and labels.
812 ///
813 const char *DerivedTypeDesc::getDescString() const {
814   return "llvm.dbg.derivedtype";
815 }
816
817 /// getTypeString - Return a string used to label this descriptor's type.
818 ///
819 const char *DerivedTypeDesc::getTypeString() const {
820   return "llvm.dbg.derivedtype.type";
821 }
822
823 #ifndef NDEBUG
824 void DerivedTypeDesc::dump() {
825   cerr << getDescString() << " "
826        << "Version(" << getVersion() << "), "
827        << "Tag(" << getTag() << "), "
828        << "Context(" << getContext() << "), "
829        << "Name(\"" << getName() << "\"), "
830        << "Size(" << getSize() << "), "
831        << "File(" << getFile() << "), "
832        << "Line(" << getLine() << "), "
833        << "FromType(" << FromType << ")\n";
834 }
835 #endif
836
837 //===----------------------------------------------------------------------===//
838
839 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
840 : DerivedTypeDesc(T)
841 , Elements()
842 {}
843   
844 // Implement isa/cast/dyncast.
845 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
846   unsigned T =  D->getTag();
847   switch (T) {
848   case DW_TAG_array_type:
849   case DW_TAG_structure_type:
850   case DW_TAG_union_type:
851   case DW_TAG_enumeration_type:
852   case DW_TAG_vector_type:
853   case DW_TAG_subroutine_type:
854     return true;
855   default: break;
856   }
857   return false;
858 }
859
860 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
861 ///
862 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
863   DerivedTypeDesc::ApplyToFields(Visitor);  
864
865   Visitor->Apply(Elements);
866 }
867
868 /// getDescString - Return a string used to compose global names and labels.
869 ///
870 const char *CompositeTypeDesc::getDescString() const {
871   return "llvm.dbg.compositetype";
872 }
873
874 /// getTypeString - Return a string used to label this descriptor's type.
875 ///
876 const char *CompositeTypeDesc::getTypeString() const {
877   return "llvm.dbg.compositetype.type";
878 }
879
880 #ifndef NDEBUG
881 void CompositeTypeDesc::dump() {
882   cerr << getDescString() << " "
883        << "Version(" << getVersion() << "), "
884        << "Tag(" << getTag() << "), "
885        << "Context(" << getContext() << "), "
886        << "Name(\"" << getName() << "\"), "
887        << "Size(" << getSize() << "), "
888        << "File(" << getFile() << "), "
889        << "Line(" << getLine() << "), "
890        << "FromType(" << getFromType() << "), "
891        << "Elements.size(" << Elements.size() << ")\n";
892 }
893 #endif
894
895 //===----------------------------------------------------------------------===//
896
897 SubrangeDesc::SubrangeDesc()
898 : DebugInfoDesc(DW_TAG_subrange_type)
899 , Lo(0)
900 , Hi(0)
901 {}
902
903 // Implement isa/cast/dyncast.
904 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
905   return D->getTag() == DW_TAG_subrange_type;
906 }
907
908 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
909 ///
910 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
911   DebugInfoDesc::ApplyToFields(Visitor);
912
913   Visitor->Apply(Lo);
914   Visitor->Apply(Hi);
915 }
916
917 /// getDescString - Return a string used to compose global names and labels.
918 ///
919 const char *SubrangeDesc::getDescString() const {
920   return "llvm.dbg.subrange";
921 }
922   
923 /// getTypeString - Return a string used to label this descriptor's type.
924 ///
925 const char *SubrangeDesc::getTypeString() const {
926   return "llvm.dbg.subrange.type";
927 }
928
929 #ifndef NDEBUG
930 void SubrangeDesc::dump() {
931   cerr << getDescString() << " "
932        << "Version(" << getVersion() << "), "
933        << "Tag(" << getTag() << "), "
934        << "Lo(" << Lo << "), "
935        << "Hi(" << Hi << ")\n";
936 }
937 #endif
938
939 //===----------------------------------------------------------------------===//
940
941 EnumeratorDesc::EnumeratorDesc()
942 : DebugInfoDesc(DW_TAG_enumerator)
943 , Name("")
944 , Value(0)
945 {}
946
947 // Implement isa/cast/dyncast.
948 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
949   return D->getTag() == DW_TAG_enumerator;
950 }
951
952 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
953 ///
954 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
955   DebugInfoDesc::ApplyToFields(Visitor);
956
957   Visitor->Apply(Name);
958   Visitor->Apply(Value);
959 }
960
961 /// getDescString - Return a string used to compose global names and labels.
962 ///
963 const char *EnumeratorDesc::getDescString() const {
964   return "llvm.dbg.enumerator";
965 }
966   
967 /// getTypeString - Return a string used to label this descriptor's type.
968 ///
969 const char *EnumeratorDesc::getTypeString() const {
970   return "llvm.dbg.enumerator.type";
971 }
972
973 #ifndef NDEBUG
974 void EnumeratorDesc::dump() {
975   cerr << getDescString() << " "
976        << "Version(" << getVersion() << "), "
977        << "Tag(" << getTag() << "), "
978        << "Name(" << Name << "), "
979        << "Value(" << Value << ")\n";
980 }
981 #endif
982
983 //===----------------------------------------------------------------------===//
984
985 VariableDesc::VariableDesc(unsigned T)
986 : DebugInfoDesc(T)
987 , Context(NULL)
988 , Name("")
989 , File(NULL)
990 , Line(0)
991 , TyDesc(0)
992 {}
993
994 // Implement isa/cast/dyncast.
995 bool VariableDesc::classof(const DebugInfoDesc *D) {
996   unsigned T =  D->getTag();
997   switch (T) {
998   case DW_TAG_auto_variable:
999   case DW_TAG_arg_variable:
1000   case DW_TAG_return_variable:
1001     return true;
1002   default: break;
1003   }
1004   return false;
1005 }
1006
1007 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
1008 ///
1009 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
1010   DebugInfoDesc::ApplyToFields(Visitor);
1011   
1012   Visitor->Apply(Context);
1013   Visitor->Apply(Name);
1014   Visitor->Apply(File);
1015   Visitor->Apply(Line);
1016   Visitor->Apply(TyDesc);
1017 }
1018
1019 /// getDescString - Return a string used to compose global names and labels.
1020 ///
1021 const char *VariableDesc::getDescString() const {
1022   return "llvm.dbg.variable";
1023 }
1024
1025 /// getTypeString - Return a string used to label this descriptor's type.
1026 ///
1027 const char *VariableDesc::getTypeString() const {
1028   return "llvm.dbg.variable.type";
1029 }
1030
1031 #ifndef NDEBUG
1032 void VariableDesc::dump() {
1033   cerr << getDescString() << " "
1034        << "Version(" << getVersion() << "), "
1035        << "Tag(" << getTag() << "), "
1036        << "Context(" << Context << "), "
1037        << "Name(\"" << Name << "\"), "
1038        << "File(" << File << "), "
1039        << "Line(" << Line << "), "
1040        << "TyDesc(" << TyDesc << ")\n";
1041 }
1042 #endif
1043
1044 //===----------------------------------------------------------------------===//
1045
1046 GlobalDesc::GlobalDesc(unsigned T)
1047 : AnchoredDesc(T)
1048 , Context(0)
1049 , Name("")
1050 , FullName("")
1051 , LinkageName("")
1052 , File(NULL)
1053 , Line(0)
1054 , TyDesc(NULL)
1055 , IsStatic(false)
1056 , IsDefinition(false)
1057 {}
1058
1059 /// ApplyToFields - Target the visitor to the fields of the global.
1060 ///
1061 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1062   AnchoredDesc::ApplyToFields(Visitor);
1063
1064   Visitor->Apply(Context);
1065   Visitor->Apply(Name);
1066   Visitor->Apply(FullName);
1067   Visitor->Apply(LinkageName);
1068   Visitor->Apply(File);
1069   Visitor->Apply(Line);
1070   Visitor->Apply(TyDesc);
1071   Visitor->Apply(IsStatic);
1072   Visitor->Apply(IsDefinition);
1073 }
1074
1075 //===----------------------------------------------------------------------===//
1076
1077 GlobalVariableDesc::GlobalVariableDesc()
1078 : GlobalDesc(DW_TAG_variable)
1079 , Global(NULL)
1080 {}
1081
1082 // Implement isa/cast/dyncast.
1083 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1084   return D->getTag() == DW_TAG_variable; 
1085 }
1086
1087 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1088 ///
1089 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1090   GlobalDesc::ApplyToFields(Visitor);
1091
1092   Visitor->Apply(Global);
1093 }
1094
1095 /// getDescString - Return a string used to compose global names and labels.
1096 ///
1097 const char *GlobalVariableDesc::getDescString() const {
1098   return "llvm.dbg.global_variable";
1099 }
1100
1101 /// getTypeString - Return a string used to label this descriptors type.
1102 ///
1103 const char *GlobalVariableDesc::getTypeString() const {
1104   return "llvm.dbg.global_variable.type";
1105 }
1106
1107 /// getAnchorString - Return a string used to label this descriptor's anchor.
1108 ///
1109 const char *GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1110 const char *GlobalVariableDesc::getAnchorString() const {
1111   return AnchorString;
1112 }
1113
1114 #ifndef NDEBUG
1115 void GlobalVariableDesc::dump() {
1116   cerr << getDescString() << " "
1117        << "Version(" << getVersion() << "), "
1118        << "Tag(" << getTag() << "), "
1119        << "Anchor(" << getAnchor() << "), "
1120        << "Name(\"" << getName() << "\"), "
1121        << "FullName(\"" << getFullName() << "\"), "
1122        << "LinkageName(\"" << getLinkageName() << "\"), "
1123        << "File(" << getFile() << "),"
1124        << "Line(" << getLine() << "),"
1125        << "Type(" << getType() << "), "
1126        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1127        << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1128        << "Global(" << Global << ")\n";
1129 }
1130 #endif
1131
1132 //===----------------------------------------------------------------------===//
1133
1134 SubprogramDesc::SubprogramDesc()
1135 : GlobalDesc(DW_TAG_subprogram)
1136 {}
1137
1138 // Implement isa/cast/dyncast.
1139 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1140   return D->getTag() == DW_TAG_subprogram;
1141 }
1142
1143 /// ApplyToFields - Target the visitor to the fields of the
1144 /// SubprogramDesc.
1145 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1146   GlobalDesc::ApplyToFields(Visitor);
1147 }
1148
1149 /// getDescString - Return a string used to compose global names and labels.
1150 ///
1151 const char *SubprogramDesc::getDescString() const {
1152   return "llvm.dbg.subprogram";
1153 }
1154
1155 /// getTypeString - Return a string used to label this descriptors type.
1156 ///
1157 const char *SubprogramDesc::getTypeString() const {
1158   return "llvm.dbg.subprogram.type";
1159 }
1160
1161 /// getAnchorString - Return a string used to label this descriptor's anchor.
1162 ///
1163 const char *SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1164 const char *SubprogramDesc::getAnchorString() const {
1165   return AnchorString;
1166 }
1167
1168 #ifndef NDEBUG
1169 void SubprogramDesc::dump() {
1170   cerr << getDescString() << " "
1171        << "Version(" << getVersion() << "), "
1172        << "Tag(" << getTag() << "), "
1173        << "Anchor(" << getAnchor() << "), "
1174        << "Name(\"" << getName() << "\"), "
1175        << "FullName(\"" << getFullName() << "\"), "
1176        << "LinkageName(\"" << getLinkageName() << "\"), "
1177        << "File(" << getFile() << "),"
1178        << "Line(" << getLine() << "),"
1179        << "Type(" << getType() << "), "
1180        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1181        << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1182 }
1183 #endif
1184
1185 //===----------------------------------------------------------------------===//
1186
1187 BlockDesc::BlockDesc()
1188 : DebugInfoDesc(DW_TAG_lexical_block)
1189 , Context(NULL)
1190 {}
1191
1192 // Implement isa/cast/dyncast.
1193 bool BlockDesc::classof(const DebugInfoDesc *D) {
1194   return D->getTag() == DW_TAG_lexical_block;
1195 }
1196
1197 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1198 ///
1199 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1200   DebugInfoDesc::ApplyToFields(Visitor);
1201
1202   Visitor->Apply(Context);
1203 }
1204
1205 /// getDescString - Return a string used to compose global names and labels.
1206 ///
1207 const char *BlockDesc::getDescString() const {
1208   return "llvm.dbg.block";
1209 }
1210
1211 /// getTypeString - Return a string used to label this descriptors type.
1212 ///
1213 const char *BlockDesc::getTypeString() const {
1214   return "llvm.dbg.block.type";
1215 }
1216
1217 #ifndef NDEBUG
1218 void BlockDesc::dump() {
1219   cerr << getDescString() << " "
1220        << "Version(" << getVersion() << "), "
1221        << "Tag(" << getTag() << "),"
1222        << "Context(" << Context << ")\n";
1223 }
1224 #endif
1225
1226 //===----------------------------------------------------------------------===//
1227
1228 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1229   return Deserialize(getGlobalVariable(V));
1230 }
1231 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1232   // Handle NULL.
1233   if (!GV) return NULL;
1234
1235   // Check to see if it has been already deserialized.
1236   DebugInfoDesc *&Slot = GlobalDescs[GV];
1237   if (Slot) return Slot;
1238
1239   // Get the Tag from the global.
1240   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1241   
1242   // Create an empty instance of the correct sort.
1243   Slot = DebugInfoDesc::DescFactory(Tag);
1244   
1245   // If not a user defined descriptor.
1246   if (Slot) {
1247     // Deserialize the fields.
1248     DIDeserializeVisitor DRAM(*this, GV);
1249     DRAM.ApplyToFields(Slot);
1250   }
1251   
1252   return Slot;
1253 }
1254
1255 //===----------------------------------------------------------------------===//
1256
1257 /// getStrPtrType - Return a "sbyte *" type.
1258 ///
1259 const PointerType *DISerializer::getStrPtrType() {
1260   // If not already defined.
1261   if (!StrPtrTy) {
1262     // Construct the pointer to signed bytes.
1263     StrPtrTy = PointerType::get(Type::Int8Ty);
1264   }
1265   
1266   return StrPtrTy;
1267 }
1268
1269 /// getEmptyStructPtrType - Return a "{ }*" type.
1270 ///
1271 const PointerType *DISerializer::getEmptyStructPtrType() {
1272   // If not already defined.
1273   if (!EmptyStructPtrTy) {
1274     // Construct the empty structure type.
1275     const StructType *EmptyStructTy =
1276                                     StructType::get(std::vector<const Type*>());
1277     // Construct the pointer to empty structure type.
1278     EmptyStructPtrTy = PointerType::get(EmptyStructTy);
1279   }
1280   
1281   return EmptyStructPtrTy;
1282 }
1283
1284 /// getTagType - Return the type describing the specified descriptor (via tag.)
1285 ///
1286 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1287   // Attempt to get the previously defined type.
1288   StructType *&Ty = TagTypes[DD->getTag()];
1289   
1290   // If not already defined.
1291   if (!Ty) {
1292     // Set up fields vector.
1293     std::vector<const Type*> Fields;
1294     // Get types of fields.
1295     DIGetTypesVisitor GTAM(*this, Fields);
1296     GTAM.ApplyToFields(DD);
1297
1298     // Construct structured type.
1299     Ty = StructType::get(Fields);
1300     
1301     // Register type name with module.
1302     M->addTypeName(DD->getTypeString(), Ty);
1303   }
1304   
1305   return Ty;
1306 }
1307
1308 /// getString - Construct the string as constant string global.
1309 ///
1310 Constant *DISerializer::getString(const std::string &String) {
1311   // Check string cache for previous edition.
1312   Constant *&Slot = StringCache[String];
1313   // Return Constant if previously defined.
1314   if (Slot) return Slot;
1315   // If empty string then use a sbyte* null instead.
1316   if (String.empty()) {
1317     Slot = ConstantPointerNull::get(getStrPtrType());
1318   } else {
1319     // Construct string as an llvm constant.
1320     Constant *ConstStr = ConstantArray::get(String);
1321     // Otherwise create and return a new string global.
1322     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1323                                                GlobalVariable::InternalLinkage,
1324                                                ConstStr, "str", M);
1325     StrGV->setSection("llvm.metadata");
1326     // Convert to generic string pointer.
1327     Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
1328   }
1329   return Slot;
1330   
1331 }
1332
1333 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1334 /// so that it can be serialized to a .bc or .ll file.
1335 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1336   // Check if the DebugInfoDesc is already in the map.
1337   GlobalVariable *&Slot = DescGlobals[DD];
1338   
1339   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1340   if (Slot) return Slot;
1341   
1342   // Get the type associated with the Tag.
1343   const StructType *Ty = getTagType(DD);
1344
1345   // Create the GlobalVariable early to prevent infinite recursion.
1346   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1347                                           NULL, DD->getDescString(), M);
1348   GV->setSection("llvm.metadata");
1349
1350   // Insert new GlobalVariable in DescGlobals map.
1351   Slot = GV;
1352  
1353   // Set up elements vector
1354   std::vector<Constant*> Elements;
1355   // Add fields.
1356   DISerializeVisitor SRAM(*this, Elements);
1357   SRAM.ApplyToFields(DD);
1358   
1359   // Set the globals initializer.
1360   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1361   
1362   return GV;
1363 }
1364
1365 //===----------------------------------------------------------------------===//
1366
1367 /// Verify - Return true if the GlobalVariable appears to be a valid
1368 /// serialization of a DebugInfoDesc.
1369 bool DIVerifier::Verify(Value *V) {
1370   return !V || Verify(getGlobalVariable(V));
1371 }
1372 bool DIVerifier::Verify(GlobalVariable *GV) {
1373   // NULLs are valid.
1374   if (!GV) return true;
1375   
1376   // Check prior validity.
1377   unsigned &ValiditySlot = Validity[GV];
1378   
1379   // If visited before then use old state.
1380   if (ValiditySlot) return ValiditySlot == Valid;
1381   
1382   // Assume validity for the time being (recursion.)
1383   ValiditySlot = Valid;
1384   
1385   // Make sure the global is internal or link once (anchor.)
1386   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1387       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1388     ValiditySlot = Invalid;
1389     return false;
1390   }
1391
1392   // Get the Tag.
1393   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1394   
1395   // Check for user defined descriptors.
1396   if (Tag == DW_TAG_invalid) {
1397     ValiditySlot = Valid;
1398     return true;
1399   }
1400   
1401   // Get the Version.
1402   unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
1403   
1404   // Check for version mismatch.
1405   if (Version != LLVMDebugVersion) {
1406     ValiditySlot = Invalid;
1407     return false;
1408   }
1409
1410   // Construct an empty DebugInfoDesc.
1411   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1412   
1413   // Allow for user defined descriptors.
1414   if (!DD) return true;
1415   
1416   // Get the initializer constant.
1417   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1418   
1419   // Get the operand count.
1420   unsigned N = CI->getNumOperands();
1421   
1422   // Get the field count.
1423   unsigned &CountSlot = Counts[Tag];
1424   if (!CountSlot) {
1425     // Check the operand count to the field count
1426     DICountVisitor CTAM;
1427     CTAM.ApplyToFields(DD);
1428     CountSlot = CTAM.getCount();
1429   }
1430   
1431   // Field count must be at most equal operand count.
1432   if (CountSlot >  N) {
1433     delete DD;
1434     ValiditySlot = Invalid;
1435     return false;
1436   }
1437   
1438   // Check each field for valid type.
1439   DIVerifyVisitor VRAM(*this, GV);
1440   VRAM.ApplyToFields(DD);
1441   
1442   // Release empty DebugInfoDesc.
1443   delete DD;
1444   
1445   // If fields are not valid.
1446   if (!VRAM.isValid()) {
1447     ValiditySlot = Invalid;
1448     return false;
1449   }
1450   
1451   return true;
1452 }
1453
1454 //===----------------------------------------------------------------------===//
1455
1456 DebugScope::~DebugScope() {
1457   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1458   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1459 }
1460
1461 //===----------------------------------------------------------------------===//
1462
1463 MachineModuleInfo::MachineModuleInfo()
1464 : DR()
1465 , VR()
1466 , CompileUnits()
1467 , Directories()
1468 , SourceFiles()
1469 , Lines()
1470 , LabelIDList()
1471 , ScopeMap()
1472 , RootScope(NULL)
1473 , FrameMoves()
1474 {}
1475 MachineModuleInfo::~MachineModuleInfo() {
1476
1477 }
1478
1479 /// doInitialization - Initialize the state for a new module.
1480 ///
1481 bool MachineModuleInfo::doInitialization() {
1482   return false;
1483 }
1484
1485 /// doFinalization - Tear down the state after completion of a module.
1486 ///
1487 bool MachineModuleInfo::doFinalization() {
1488   return false;
1489 }
1490
1491 /// BeginFunction - Begin gathering function meta information.
1492 ///
1493 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
1494   // Coming soon.
1495 }
1496
1497 /// EndFunction - Discard function meta information.
1498 ///
1499 void MachineModuleInfo::EndFunction() {
1500   // Clean up scope information.
1501   if (RootScope) {
1502     delete RootScope;
1503     ScopeMap.clear();
1504     RootScope = NULL;
1505   }
1506   
1507   // Clean up frame info.
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 *MachineModuleInfo::getDescFor(Value *V) {
1515   return DR.Deserialize(V);
1516 }
1517
1518 /// Verify - Verify that a Value is debug information descriptor.
1519 ///
1520 bool MachineModuleInfo::Verify(Value *V) {
1521   return VR.Verify(V);
1522 }
1523
1524 /// AnalyzeModule - Scan the module for global debug information.
1525 ///
1526 void MachineModuleInfo::AnalyzeModule(Module &M) {
1527   SetupCompileUnits(M);
1528 }
1529
1530 /// SetupCompileUnits - Set up the unique vector of compile units.
1531 ///
1532 void MachineModuleInfo::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 *> MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 MachineModuleInfo::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 *MachineModuleInfo::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 labels.  This allows
1635 /// a info consumer to determine if the range of two labels is empty, by seeing
1636 /// 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 "Label Folder"; }
1643 };
1644
1645 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1646   // Get machine module info.
1647   MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1648   if (!MMI) return false;
1649   // Get target instruction info.
1650   const TargetInstrInfo *TII = MF.getTarget().getInstrInfo();
1651   if (!TII) return false;
1652   
1653   // Track if change is made.
1654   bool MadeChange = false;
1655   // No prior label to begin.
1656   unsigned PriorLabel = 0;
1657   
1658   // Iterate through basic blocks.
1659   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1660        BB != E; ++BB) {
1661     // Iterate through instructions.
1662     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1663       // Is it a label.
1664       if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
1665         // The label ID # is always operand #0, an immediate.
1666         unsigned NextLabel = I->getOperand(0).getImm();
1667         
1668         // If there was an immediate prior label.
1669         if (PriorLabel) {
1670           // Remap the current label to prior label.
1671           MMI->RemapLabel(NextLabel, PriorLabel);
1672           // Delete the current label.
1673           I = BB->erase(I);
1674           // Indicate a change has been made.
1675           MadeChange = true;
1676           continue;
1677         } else {
1678           // Start a new round.
1679           PriorLabel = NextLabel;
1680         }
1681        } else {
1682         // No consecutive labels.
1683         PriorLabel = 0;
1684       }
1685       
1686       ++I;
1687     }
1688   }
1689   
1690   return MadeChange;
1691 }
1692
1693 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
1694
1695 }
1696