Fix an over aggressive assumption that struct decls will have a pointer to
[oota-llvm.git] / lib / CodeGen / MachineModuleInfo.cpp
1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/MachineModuleInfo.h"
11
12 #include "llvm/Constants.h"
13 #include "llvm/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/Passes.h"
17 #include "llvm/Target/TargetInstrInfo.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/TargetOptions.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Support/Dwarf.h"
26 #include "llvm/Support/Streams.h"
27 using namespace llvm;
28 using namespace llvm::dwarf;
29
30 // Handle the Pass registration stuff necessary to use TargetData's.
31 static RegisterPass<MachineModuleInfo>
32 X("machinemoduleinfo", "Module Information");
33 char MachineModuleInfo::ID = 0;
34
35 //===----------------------------------------------------------------------===//
36
37 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
38 /// specified value in their initializer somewhere.
39 static void
40 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
41   // Scan though value users.
42   for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
43     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
44       // If the user is a GlobalVariable then add to result.
45       Result.push_back(GV);
46     } else if (Constant *C = dyn_cast<Constant>(*I)) {
47       // If the user is a constant variable then scan its users
48       getGlobalVariablesUsing(C, Result);
49     }
50   }
51 }
52
53 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
54 /// named GlobalVariable.
55 static void
56 getGlobalVariablesUsing(Module &M, const std::string &RootName,
57                         std::vector<GlobalVariable*> &Result) {
58   std::vector<const Type*> FieldTypes;
59   FieldTypes.push_back(Type::Int32Ty);
60   FieldTypes.push_back(Type::Int32Ty);
61
62   // Get the GlobalVariable root.
63   GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
64                                                 StructType::get(FieldTypes));
65
66   // If present and linkonce then scan for users.
67   if (UseRoot && UseRoot->hasLinkOnceLinkage())
68     getGlobalVariablesUsing(UseRoot, 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::BitCast) {
102       return dyn_cast<GlobalVariable>(CE->getOperand(0));
103     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
104       for (unsigned int i=1; i<CE->getNumOperands(); i++) {
105         if (!CE->getOperand(i)->isNullValue())
106           return NULL;
107       }
108       return dyn_cast<GlobalVariable>(CE->getOperand(0));
109     }
110   }
111   return NULL;
112 }
113
114 /// isGlobalVariable - Return true if the given value can be coerced to a
115 /// GlobalVariable.
116 static bool isGlobalVariable(Value *V) {
117   if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
118     return true;
119   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
120     if (CE->getOpcode() == Instruction::BitCast) {
121       return isa<GlobalVariable>(CE->getOperand(0));
122     } else if (CE->getOpcode() == Instruction::GetElementPtr) {
123       for (unsigned int i=1; i<CE->getNumOperands(); i++) {
124         if (!CE->getOperand(i)->isNullValue())
125           return false;
126       }
127       return isa<GlobalVariable>(CE->getOperand(0));
128     }
129   }
130   return false;
131 }
132
133 /// getUIntOperand - Return ith operand if it is an unsigned integer.
134 ///
135 static ConstantInt *getUIntOperand(GlobalVariable *GV, unsigned i) {
136   // Make sure the GlobalVariable has an initializer.
137   if (!GV->hasInitializer()) return NULL;
138   
139   // Get the initializer constant.
140   ConstantStruct *CI = dyn_cast<ConstantStruct>(GV->getInitializer());
141   if (!CI) return NULL;
142   
143   // Check if there is at least i + 1 operands.
144   unsigned N = CI->getNumOperands();
145   if (i >= N) return NULL;
146
147   // Check constant.
148   return dyn_cast<ConstantInt>(CI->getOperand(i));
149 }
150
151 //===----------------------------------------------------------------------===//
152
153 static unsigned CountFields(DebugInfoDesc *DD) {
154   unsigned Count = 0;
155
156   switch (DD->getTag()) {
157   case DW_TAG_anchor:           // AnchorDesc
158     // Tag
159     // AnchorTag
160     Count = 2;
161     break;
162   case DW_TAG_compile_unit:     // CompileUnitDesc
163     // [DW_TAG_anchor]
164     // if (Version == 0) DebugVersion
165     // Language
166     // FileName
167     // Directory
168     // Producer
169     Count = 6;
170   
171     // Handle cases out of sync with compiler.
172     if (DD->getVersion() == 0)
173       ++Count;
174
175     break;
176   case DW_TAG_variable:         // GlobalVariableDesc
177     // [DW_TAG_anchor]
178     // Context
179     // Name
180     // FullName
181     // LinkageName
182     // File
183     // Line
184     // TyDesc
185     // IsStatic
186     // IsDefinition
187     // Global
188     Count = 12;
189     break;
190   case DW_TAG_subprogram:       // SubprogramDesc
191     // [DW_TAG_anchor]
192     // Context
193     // Name
194     // FullName
195     // LinkageName
196     // File
197     // Line
198     // TyDesc
199     // IsStatic
200     // IsDefinition
201     Count = 11;
202     break;
203   case DW_TAG_lexical_block:    // BlockDesc
204     // Tag
205     // Context
206     Count = 2;
207     break;
208   case DW_TAG_base_type:        // BasicTypeDesc
209     // Tag
210     // Context
211     // Name
212     // File
213     // Line
214     // Size
215     // Align
216     // Offset
217     // if (Version > LLVMDebugVersion4) Flags
218     // Encoding
219     Count = 9;
220
221     if (DD->getVersion() > LLVMDebugVersion4)
222       ++Count;
223
224     break;
225   case DW_TAG_typedef:
226   case DW_TAG_pointer_type:        
227   case DW_TAG_reference_type:
228   case DW_TAG_const_type:
229   case DW_TAG_volatile_type:        
230   case DW_TAG_restrict_type:
231   case DW_TAG_member:
232   case DW_TAG_inheritance:      // DerivedTypeDesc
233     // Tag
234     // Context
235     // Name
236     // File
237     // Line
238     // Size
239     // Align
240     // Offset
241     // if (Version > LLVMDebugVersion4) Flags
242     // FromType
243     Count = 9;
244
245     if (DD->getVersion() > LLVMDebugVersion4)
246       ++Count;
247
248     break;
249   case DW_TAG_array_type:
250   case DW_TAG_structure_type:
251   case DW_TAG_union_type:
252   case DW_TAG_enumeration_type:
253   case DW_TAG_vector_type:
254   case DW_TAG_subroutine_type:  // CompositeTypeDesc
255     // Tag
256     // Context
257     // Name
258     // File
259     // Line
260     // Size
261     // Align
262     // Offset
263     // if (Version > LLVMDebugVersion4) Flags
264     // FromType
265     // Elements
266     Count = 10;
267
268     if (DD->getVersion() > LLVMDebugVersion4)
269       ++Count;
270
271     break;
272   case DW_TAG_subrange_type:    // SubrangeDesc
273     // Tag
274     // Lo
275     // Hi
276     Count = 3;
277     break;
278   case DW_TAG_enumerator:       // EnumeratorDesc
279     // Tag
280     // Name
281     // Value
282     Count = 3;
283     break;
284   case DW_TAG_return_variable:
285   case DW_TAG_arg_variable:
286   case DW_TAG_auto_variable:    // VariableDesc
287     // Tag
288     // Context
289     // Name
290     // File
291     // Line
292     // TyDesc
293     Count = 6;
294     break;
295   default:
296     break;
297   }
298
299   return Count;
300 }
301
302 //===----------------------------------------------------------------------===//
303
304 /// ApplyToFields - Target the visitor to each field of the debug information
305 /// descriptor.
306 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
307   DD->ApplyToFields(this);
308 }
309
310 namespace {
311
312 //===----------------------------------------------------------------------===//
313 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
314 /// supplied DebugInfoDesc.
315 class DIDeserializeVisitor : public DIVisitor {
316 private:
317   DIDeserializer &DR;                   // Active deserializer.
318   unsigned I;                           // Current operand index.
319   ConstantStruct *CI;                   // GlobalVariable constant initializer.
320
321 public:
322   DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
323     : DIVisitor(), DR(D), I(0), CI(cast<ConstantStruct>(GV->getInitializer()))
324   {}
325   
326   /// Apply - Set the value of each of the fields.
327   ///
328   virtual void Apply(int &Field) {
329     Constant *C = CI->getOperand(I++);
330     Field = cast<ConstantInt>(C)->getSExtValue();
331   }
332   virtual void Apply(unsigned &Field) {
333     Constant *C = CI->getOperand(I++);
334     Field = cast<ConstantInt>(C)->getZExtValue();
335   }
336   virtual void Apply(int64_t &Field) {
337     Constant *C = CI->getOperand(I++);
338     Field = cast<ConstantInt>(C)->getSExtValue();
339   }
340   virtual void Apply(uint64_t &Field) {
341     Constant *C = CI->getOperand(I++);
342     Field = cast<ConstantInt>(C)->getZExtValue();
343   }
344   virtual void Apply(bool &Field) {
345     Constant *C = CI->getOperand(I++);
346     Field = cast<ConstantInt>(C)->getZExtValue();
347   }
348   virtual void Apply(std::string &Field) {
349     Constant *C = CI->getOperand(I++);
350     // Fills in the string if it succeeds
351     if (!GetConstantStringInfo(C, Field))
352       Field.clear();
353   }
354   virtual void Apply(DebugInfoDesc *&Field) {
355     Constant *C = CI->getOperand(I++);
356     Field = DR.Deserialize(C);
357   }
358   virtual void Apply(GlobalVariable *&Field) {
359     Constant *C = CI->getOperand(I++);
360     Field = getGlobalVariable(C);
361   }
362   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
363     Field.resize(0);
364     Constant *C = CI->getOperand(I++);
365     GlobalVariable *GV = getGlobalVariable(C);
366     if (GV && GV->hasInitializer()) {
367       if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
368         for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
369           GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
370           DebugInfoDesc *DE = DR.Deserialize(GVE);
371           Field.push_back(DE);
372         }
373       } else if (GV->getInitializer()->isNullValue()) {
374         if (const ArrayType *T =
375             dyn_cast<ArrayType>(GV->getType()->getElementType())) {
376           Field.resize(T->getNumElements());
377         }
378       }
379     }
380   }
381 };
382
383 //===----------------------------------------------------------------------===//
384 /// DISerializeVisitor - This DIVisitor serializes all the fields in
385 /// the supplied DebugInfoDesc.
386 class DISerializeVisitor : public DIVisitor {
387 private:
388   DISerializer &SR;                     // Active serializer.
389   std::vector<Constant*> &Elements;     // Element accumulator.
390   
391 public:
392   DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
393   : DIVisitor()
394   , SR(S)
395   , Elements(E)
396   {}
397   
398   /// Apply - Set the value of each of the fields.
399   ///
400   virtual void Apply(int &Field) {
401     Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
402   }
403   virtual void Apply(unsigned &Field) {
404     Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
405   }
406   virtual void Apply(int64_t &Field) {
407     Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
408   }
409   virtual void Apply(uint64_t &Field) {
410     Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
411   }
412   virtual void Apply(bool &Field) {
413     Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
414   }
415   virtual void Apply(std::string &Field) {
416     Elements.push_back(SR.getString(Field));
417   }
418   virtual void Apply(DebugInfoDesc *&Field) {
419     GlobalVariable *GV = NULL;
420     
421     // If non-NULL then convert to global.
422     if (Field) GV = SR.Serialize(Field);
423     
424     // FIXME - At some point should use specific type.
425     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
426     
427     if (GV) {
428       // Set to pointer to global.
429       Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
430     } else {
431       // Use NULL.
432       Elements.push_back(ConstantPointerNull::get(EmptyTy));
433     }
434   }
435   virtual void Apply(GlobalVariable *&Field) {
436     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
437     if (Field) {
438       Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
439     } else {
440       Elements.push_back(ConstantPointerNull::get(EmptyTy));
441     }
442   }
443   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
444     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
445     unsigned N = Field.size();
446     ArrayType *AT = ArrayType::get(EmptyTy, N);
447     std::vector<Constant *> ArrayElements;
448
449     for (unsigned i = 0, N = Field.size(); i < N; ++i) {
450       if (DebugInfoDesc *Element = Field[i]) {
451         GlobalVariable *GVE = SR.Serialize(Element);
452         Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
453         ArrayElements.push_back(cast<Constant>(CE));
454       } else {
455         ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
456       }
457     }
458     
459     Constant *CA = ConstantArray::get(AT, ArrayElements);
460     GlobalVariable *CAGV = new GlobalVariable(AT, true,
461                                               GlobalValue::InternalLinkage,
462                                               CA, "llvm.dbg.array",
463                                               SR.getModule());
464     CAGV->setSection("llvm.metadata");
465     Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
466     Elements.push_back(CAE);
467   }
468 };
469
470 //===----------------------------------------------------------------------===//
471 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
472 /// the supplied DebugInfoDesc.
473 class DIGetTypesVisitor : public DIVisitor {
474 private:
475   DISerializer &SR;                     // Active serializer.
476   std::vector<const Type*> &Fields;     // Type accumulator.
477   
478 public:
479   DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
480   : DIVisitor()
481   , SR(S)
482   , Fields(F)
483   {}
484   
485   /// Apply - Set the value of each of the fields.
486   ///
487   virtual void Apply(int &Field) {
488     Fields.push_back(Type::Int32Ty);
489   }
490   virtual void Apply(unsigned &Field) {
491     Fields.push_back(Type::Int32Ty);
492   }
493   virtual void Apply(int64_t &Field) {
494     Fields.push_back(Type::Int64Ty);
495   }
496   virtual void Apply(uint64_t &Field) {
497     Fields.push_back(Type::Int64Ty);
498   }
499   virtual void Apply(bool &Field) {
500     Fields.push_back(Type::Int1Ty);
501   }
502   virtual void Apply(std::string &Field) {
503     Fields.push_back(SR.getStrPtrType());
504   }
505   virtual void Apply(DebugInfoDesc *&Field) {
506     // FIXME - At some point should use specific type.
507     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
508     Fields.push_back(EmptyTy);
509   }
510   virtual void Apply(GlobalVariable *&Field) {
511     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
512     Fields.push_back(EmptyTy);
513   }
514   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
515     const PointerType *EmptyTy = SR.getEmptyStructPtrType();
516     Fields.push_back(EmptyTy);
517   }
518 };
519
520 //===----------------------------------------------------------------------===//
521 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
522 /// a constant initializer.
523 class DIVerifyVisitor : public DIVisitor {
524 private:
525   DIVerifier &VR;                       // Active verifier.
526   bool IsValid;                         // Validity status.
527   unsigned I;                           // Current operand index.
528   ConstantStruct *CI;                   // GlobalVariable constant initializer.
529   
530 public:
531   DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
532   : DIVisitor()
533   , VR(V)
534   , IsValid(true)
535   , I(0)
536   , CI(cast<ConstantStruct>(GV->getInitializer()))
537   {
538   }
539   
540   // Accessors.
541   bool isValid() const { return IsValid; }
542   
543   /// Apply - Set the value of each of the fields.
544   ///
545   virtual void Apply(int &Field) {
546     Constant *C = CI->getOperand(I++);
547     IsValid = IsValid && isa<ConstantInt>(C);
548   }
549   virtual void Apply(unsigned &Field) {
550     Constant *C = CI->getOperand(I++);
551     IsValid = IsValid && isa<ConstantInt>(C);
552   }
553   virtual void Apply(int64_t &Field) {
554     Constant *C = CI->getOperand(I++);
555     IsValid = IsValid && isa<ConstantInt>(C);
556   }
557   virtual void Apply(uint64_t &Field) {
558     Constant *C = CI->getOperand(I++);
559     IsValid = IsValid && isa<ConstantInt>(C);
560   }
561   virtual void Apply(bool &Field) {
562     Constant *C = CI->getOperand(I++);
563     IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
564   }
565   virtual void Apply(std::string &Field) {
566     Constant *C = CI->getOperand(I++);
567     IsValid = IsValid &&
568               (!C || isStringValue(C) || C->isNullValue());
569   }
570   virtual void Apply(DebugInfoDesc *&Field) {
571     // FIXME - Prepare the correct descriptor.
572     Constant *C = CI->getOperand(I++);
573     IsValid = IsValid && isGlobalVariable(C);
574   }
575   virtual void Apply(GlobalVariable *&Field) {
576     Constant *C = CI->getOperand(I++);
577     IsValid = IsValid && isGlobalVariable(C);
578   }
579   virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
580     Constant *C = CI->getOperand(I++);
581     IsValid = IsValid && isGlobalVariable(C);
582     if (!IsValid) return;
583
584     GlobalVariable *GV = getGlobalVariable(C);
585     IsValid = IsValid && GV && GV->hasInitializer();
586     if (!IsValid) return;
587     
588     ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
589     IsValid = IsValid && CA;
590     if (!IsValid) return;
591
592     for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
593       IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
594       if (!IsValid) return;
595     
596       GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
597       VR.Verify(GVE);
598     }
599   }
600 };
601
602 }
603
604 //===----------------------------------------------------------------------===//
605
606 /// TagFromGlobal - Returns the tag number from a debug info descriptor
607 /// GlobalVariable.   Return DIIValid if operand is not an unsigned int. 
608 unsigned DebugInfoDesc::TagFromGlobal(GlobalVariable *GV) {
609   ConstantInt *C = getUIntOperand(GV, 0);
610   return C ? ((unsigned)C->getZExtValue() & ~LLVMDebugVersionMask) :
611              (unsigned)DW_TAG_invalid;
612 }
613
614 /// VersionFromGlobal - Returns the version number from a debug info
615 /// descriptor GlobalVariable.  Return DIIValid if operand is not an unsigned
616 /// int.
617 unsigned  DebugInfoDesc::VersionFromGlobal(GlobalVariable *GV) {
618   ConstantInt *C = getUIntOperand(GV, 0);
619   return C ? ((unsigned)C->getZExtValue() & LLVMDebugVersionMask) :
620              (unsigned)DW_TAG_invalid;
621 }
622
623 /// DescFactory - Create an instance of debug info descriptor based on Tag.
624 /// Return NULL if not a recognized Tag.
625 DebugInfoDesc *DebugInfoDesc::DescFactory(unsigned Tag) {
626   switch (Tag) {
627   case DW_TAG_anchor:           return new AnchorDesc();
628   case DW_TAG_compile_unit:     return new CompileUnitDesc();
629   case DW_TAG_variable:         return new GlobalVariableDesc();
630   case DW_TAG_subprogram:       return new SubprogramDesc();
631   case DW_TAG_lexical_block:    return new BlockDesc();
632   case DW_TAG_base_type:        return new BasicTypeDesc();
633   case DW_TAG_typedef:
634   case DW_TAG_pointer_type:        
635   case DW_TAG_reference_type:
636   case DW_TAG_const_type:
637   case DW_TAG_volatile_type:        
638   case DW_TAG_restrict_type:
639   case DW_TAG_member:
640   case DW_TAG_inheritance:      return new DerivedTypeDesc(Tag);
641   case DW_TAG_array_type:
642   case DW_TAG_structure_type:
643   case DW_TAG_union_type:
644   case DW_TAG_enumeration_type:
645   case DW_TAG_vector_type:
646   case DW_TAG_subroutine_type:  return new CompositeTypeDesc(Tag);
647   case DW_TAG_subrange_type:    return new SubrangeDesc();
648   case DW_TAG_enumerator:       return new EnumeratorDesc();
649   case DW_TAG_return_variable:
650   case DW_TAG_arg_variable:
651   case DW_TAG_auto_variable:    return new VariableDesc(Tag);
652   default: break;
653   }
654   return NULL;
655 }
656
657 /// getLinkage - get linkage appropriate for this type of descriptor.
658 ///
659 GlobalValue::LinkageTypes DebugInfoDesc::getLinkage() const {
660   return GlobalValue::InternalLinkage;
661 }
662
663 /// ApplyToFields - Target the vistor to the fields of the descriptor.
664 ///
665 void DebugInfoDesc::ApplyToFields(DIVisitor *Visitor) {
666   Visitor->Apply(Tag);
667 }
668
669 //===----------------------------------------------------------------------===//
670
671 AnchorDesc::AnchorDesc()
672 : DebugInfoDesc(DW_TAG_anchor)
673 , AnchorTag(0)
674 {}
675 AnchorDesc::AnchorDesc(AnchoredDesc *D)
676 : DebugInfoDesc(DW_TAG_anchor)
677 , AnchorTag(D->getTag())
678 {}
679
680 // Implement isa/cast/dyncast.
681 bool AnchorDesc::classof(const DebugInfoDesc *D) {
682   return D->getTag() == DW_TAG_anchor;
683 }
684   
685 /// getLinkage - get linkage appropriate for this type of descriptor.
686 ///
687 GlobalValue::LinkageTypes AnchorDesc::getLinkage() const {
688   return GlobalValue::LinkOnceLinkage;
689 }
690
691 /// ApplyToFields - Target the visitor to the fields of the TransUnitDesc.
692 ///
693 void AnchorDesc::ApplyToFields(DIVisitor *Visitor) {
694   DebugInfoDesc::ApplyToFields(Visitor);
695   
696   Visitor->Apply(AnchorTag);
697 }
698
699 /// getDescString - Return a string used to compose global names and labels. A
700 /// A global variable name needs to be defined for each debug descriptor that is
701 /// anchored. NOTE: that each global variable named here also needs to be added
702 /// to the list of names left external in the internalizer.
703 ///   ExternalNames.insert("llvm.dbg.compile_units");
704 ///   ExternalNames.insert("llvm.dbg.global_variables");
705 ///   ExternalNames.insert("llvm.dbg.subprograms");
706 const char *AnchorDesc::getDescString() const {
707   switch (AnchorTag) {
708   case DW_TAG_compile_unit: return CompileUnitDesc::AnchorString;
709   case DW_TAG_variable:     return GlobalVariableDesc::AnchorString;
710   case DW_TAG_subprogram:   return SubprogramDesc::AnchorString;
711   default: break;
712   }
713
714   assert(0 && "Tag does not have a case for anchor string");
715   return "";
716 }
717
718 /// getTypeString - Return a string used to label this descriptors type.
719 ///
720 const char *AnchorDesc::getTypeString() const {
721   return "llvm.dbg.anchor.type";
722 }
723
724 #ifndef NDEBUG
725 void AnchorDesc::dump() {
726   cerr << getDescString() << " "
727        << "Version(" << getVersion() << "), "
728        << "Tag(" << getTag() << "), "
729        << "AnchorTag(" << AnchorTag << ")\n";
730 }
731 #endif
732
733 //===----------------------------------------------------------------------===//
734
735 AnchoredDesc::AnchoredDesc(unsigned T)
736 : DebugInfoDesc(T)
737 , Anchor(NULL)
738 {}
739
740 /// ApplyToFields - Target the visitor to the fields of the AnchoredDesc.
741 ///
742 void AnchoredDesc::ApplyToFields(DIVisitor *Visitor) {
743   DebugInfoDesc::ApplyToFields(Visitor);
744
745   Visitor->Apply(Anchor);
746 }
747
748 //===----------------------------------------------------------------------===//
749
750 CompileUnitDesc::CompileUnitDesc()
751 : AnchoredDesc(DW_TAG_compile_unit)
752 , Language(0)
753 , FileName("")
754 , Directory("")
755 , Producer("")
756 {}
757
758 // Implement isa/cast/dyncast.
759 bool CompileUnitDesc::classof(const DebugInfoDesc *D) {
760   return D->getTag() == DW_TAG_compile_unit;
761 }
762
763 /// ApplyToFields - Target the visitor to the fields of the CompileUnitDesc.
764 ///
765 void CompileUnitDesc::ApplyToFields(DIVisitor *Visitor) {
766   AnchoredDesc::ApplyToFields(Visitor);
767   
768   // Handle cases out of sync with compiler.
769   if (getVersion() == 0) {
770     unsigned DebugVersion;
771     Visitor->Apply(DebugVersion);
772   }
773
774   Visitor->Apply(Language);
775   Visitor->Apply(FileName);
776   Visitor->Apply(Directory);
777   Visitor->Apply(Producer);
778 }
779
780 /// getDescString - Return a string used to compose global names and labels.
781 ///
782 const char *CompileUnitDesc::getDescString() const {
783   return "llvm.dbg.compile_unit";
784 }
785
786 /// getTypeString - Return a string used to label this descriptors type.
787 ///
788 const char *CompileUnitDesc::getTypeString() const {
789   return "llvm.dbg.compile_unit.type";
790 }
791
792 /// getAnchorString - Return a string used to label this descriptor's anchor.
793 ///
794 const char *const CompileUnitDesc::AnchorString = "llvm.dbg.compile_units";
795 const char *CompileUnitDesc::getAnchorString() const {
796   return AnchorString;
797 }
798
799 #ifndef NDEBUG
800 void CompileUnitDesc::dump() {
801   cerr << getDescString() << " "
802        << "Version(" << getVersion() << "), "
803        << "Tag(" << getTag() << "), "
804        << "Anchor(" << getAnchor() << "), "
805        << "Language(" << Language << "), "
806        << "FileName(\"" << FileName << "\"), "
807        << "Directory(\"" << Directory << "\"), "
808        << "Producer(\"" << Producer << "\")\n";
809 }
810 #endif
811
812 //===----------------------------------------------------------------------===//
813
814 TypeDesc::TypeDesc(unsigned T)
815 : DebugInfoDesc(T)
816 , Context(NULL)
817 , Name("")
818 , File(NULL)
819 , Line(0)
820 , Size(0)
821 , Align(0)
822 , Offset(0)
823 , Flags(0)
824 {}
825
826 /// ApplyToFields - Target the visitor to the fields of the TypeDesc.
827 ///
828 void TypeDesc::ApplyToFields(DIVisitor *Visitor) {
829   DebugInfoDesc::ApplyToFields(Visitor);
830   
831   Visitor->Apply(Context);
832   Visitor->Apply(Name);
833   Visitor->Apply(File);
834   Visitor->Apply(Line);
835   Visitor->Apply(Size);
836   Visitor->Apply(Align);
837   Visitor->Apply(Offset);
838   if (getVersion() > LLVMDebugVersion4) Visitor->Apply(Flags);
839 }
840
841 /// getDescString - Return a string used to compose global names and labels.
842 ///
843 const char *TypeDesc::getDescString() const {
844   return "llvm.dbg.type";
845 }
846
847 /// getTypeString - Return a string used to label this descriptor's type.
848 ///
849 const char *TypeDesc::getTypeString() const {
850   return "llvm.dbg.type.type";
851 }
852
853 #ifndef NDEBUG
854 void TypeDesc::dump() {
855   cerr << getDescString() << " "
856        << "Version(" << getVersion() << "), "
857        << "Tag(" << getTag() << "), "
858        << "Context(" << Context << "), "
859        << "Name(\"" << Name << "\"), "
860        << "File(" << File << "), "
861        << "Line(" << Line << "), "
862        << "Size(" << Size << "), "
863        << "Align(" << Align << "), "
864        << "Offset(" << Offset << "), "
865        << "Flags(" << Flags << ")\n";
866 }
867 #endif
868
869 //===----------------------------------------------------------------------===//
870
871 BasicTypeDesc::BasicTypeDesc()
872 : TypeDesc(DW_TAG_base_type)
873 , Encoding(0)
874 {}
875
876 // Implement isa/cast/dyncast.
877 bool BasicTypeDesc::classof(const DebugInfoDesc *D) {
878   return D->getTag() == DW_TAG_base_type;
879 }
880
881 /// ApplyToFields - Target the visitor to the fields of the BasicTypeDesc.
882 ///
883 void BasicTypeDesc::ApplyToFields(DIVisitor *Visitor) {
884   TypeDesc::ApplyToFields(Visitor);
885   
886   Visitor->Apply(Encoding);
887 }
888
889 /// getDescString - Return a string used to compose global names and labels.
890 ///
891 const char *BasicTypeDesc::getDescString() const {
892   return "llvm.dbg.basictype";
893 }
894
895 /// getTypeString - Return a string used to label this descriptor's type.
896 ///
897 const char *BasicTypeDesc::getTypeString() const {
898   return "llvm.dbg.basictype.type";
899 }
900
901 #ifndef NDEBUG
902 void BasicTypeDesc::dump() {
903   cerr << getDescString() << " "
904        << "Version(" << getVersion() << "), "
905        << "Tag(" << getTag() << "), "
906        << "Context(" << getContext() << "), "
907        << "Name(\"" << getName() << "\"), "
908        << "Size(" << getSize() << "), "
909        << "Encoding(" << Encoding << ")\n";
910 }
911 #endif
912
913 //===----------------------------------------------------------------------===//
914
915 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
916 : TypeDesc(T)
917 , FromType(NULL)
918 {}
919
920 // Implement isa/cast/dyncast.
921 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
922   unsigned T =  D->getTag();
923   switch (T) {
924   case DW_TAG_typedef:
925   case DW_TAG_pointer_type:
926   case DW_TAG_reference_type:
927   case DW_TAG_const_type:
928   case DW_TAG_volatile_type:
929   case DW_TAG_restrict_type:
930   case DW_TAG_member:
931   case DW_TAG_inheritance:
932     return true;
933   default: break;
934   }
935   return false;
936 }
937
938 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
939 ///
940 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
941   TypeDesc::ApplyToFields(Visitor);
942   
943   Visitor->Apply(FromType);
944 }
945
946 /// getDescString - Return a string used to compose global names and labels.
947 ///
948 const char *DerivedTypeDesc::getDescString() const {
949   return "llvm.dbg.derivedtype";
950 }
951
952 /// getTypeString - Return a string used to label this descriptor's type.
953 ///
954 const char *DerivedTypeDesc::getTypeString() const {
955   return "llvm.dbg.derivedtype.type";
956 }
957
958 #ifndef NDEBUG
959 void DerivedTypeDesc::dump() {
960   cerr << getDescString() << " "
961        << "Version(" << getVersion() << "), "
962        << "Tag(" << getTag() << "), "
963        << "Context(" << getContext() << "), "
964        << "Name(\"" << getName() << "\"), "
965        << "Size(" << getSize() << "), "
966        << "File(" << getFile() << "), "
967        << "Line(" << getLine() << "), "
968        << "FromType(" << FromType << ")\n";
969 }
970 #endif
971
972 //===----------------------------------------------------------------------===//
973
974 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
975 : DerivedTypeDesc(T)
976 , Elements()
977 {}
978   
979 // Implement isa/cast/dyncast.
980 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
981   unsigned T =  D->getTag();
982   switch (T) {
983   case DW_TAG_array_type:
984   case DW_TAG_structure_type:
985   case DW_TAG_union_type:
986   case DW_TAG_enumeration_type:
987   case DW_TAG_vector_type:
988   case DW_TAG_subroutine_type:
989     return true;
990   default: break;
991   }
992   return false;
993 }
994
995 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
996 ///
997 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
998   DerivedTypeDesc::ApplyToFields(Visitor);  
999
1000   Visitor->Apply(Elements);
1001 }
1002
1003 /// getDescString - Return a string used to compose global names and labels.
1004 ///
1005 const char *CompositeTypeDesc::getDescString() const {
1006   return "llvm.dbg.compositetype";
1007 }
1008
1009 /// getTypeString - Return a string used to label this descriptor's type.
1010 ///
1011 const char *CompositeTypeDesc::getTypeString() const {
1012   return "llvm.dbg.compositetype.type";
1013 }
1014
1015 #ifndef NDEBUG
1016 void CompositeTypeDesc::dump() {
1017   cerr << getDescString() << " "
1018        << "Version(" << getVersion() << "), "
1019        << "Tag(" << getTag() << "), "
1020        << "Context(" << getContext() << "), "
1021        << "Name(\"" << getName() << "\"), "
1022        << "Size(" << getSize() << "), "
1023        << "File(" << getFile() << "), "
1024        << "Line(" << getLine() << "), "
1025        << "FromType(" << getFromType() << "), "
1026        << "Elements.size(" << Elements.size() << ")\n";
1027 }
1028 #endif
1029
1030 //===----------------------------------------------------------------------===//
1031
1032 SubrangeDesc::SubrangeDesc()
1033 : DebugInfoDesc(DW_TAG_subrange_type)
1034 , Lo(0)
1035 , Hi(0)
1036 {}
1037
1038 // Implement isa/cast/dyncast.
1039 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
1040   return D->getTag() == DW_TAG_subrange_type;
1041 }
1042
1043 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
1044 ///
1045 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
1046   DebugInfoDesc::ApplyToFields(Visitor);
1047
1048   Visitor->Apply(Lo);
1049   Visitor->Apply(Hi);
1050 }
1051
1052 /// getDescString - Return a string used to compose global names and labels.
1053 ///
1054 const char *SubrangeDesc::getDescString() const {
1055   return "llvm.dbg.subrange";
1056 }
1057   
1058 /// getTypeString - Return a string used to label this descriptor's type.
1059 ///
1060 const char *SubrangeDesc::getTypeString() const {
1061   return "llvm.dbg.subrange.type";
1062 }
1063
1064 #ifndef NDEBUG
1065 void SubrangeDesc::dump() {
1066   cerr << getDescString() << " "
1067        << "Version(" << getVersion() << "), "
1068        << "Tag(" << getTag() << "), "
1069        << "Lo(" << Lo << "), "
1070        << "Hi(" << Hi << ")\n";
1071 }
1072 #endif
1073
1074 //===----------------------------------------------------------------------===//
1075
1076 EnumeratorDesc::EnumeratorDesc()
1077 : DebugInfoDesc(DW_TAG_enumerator)
1078 , Name("")
1079 , Value(0)
1080 {}
1081
1082 // Implement isa/cast/dyncast.
1083 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
1084   return D->getTag() == DW_TAG_enumerator;
1085 }
1086
1087 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
1088 ///
1089 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
1090   DebugInfoDesc::ApplyToFields(Visitor);
1091
1092   Visitor->Apply(Name);
1093   Visitor->Apply(Value);
1094 }
1095
1096 /// getDescString - Return a string used to compose global names and labels.
1097 ///
1098 const char *EnumeratorDesc::getDescString() const {
1099   return "llvm.dbg.enumerator";
1100 }
1101   
1102 /// getTypeString - Return a string used to label this descriptor's type.
1103 ///
1104 const char *EnumeratorDesc::getTypeString() const {
1105   return "llvm.dbg.enumerator.type";
1106 }
1107
1108 #ifndef NDEBUG
1109 void EnumeratorDesc::dump() {
1110   cerr << getDescString() << " "
1111        << "Version(" << getVersion() << "), "
1112        << "Tag(" << getTag() << "), "
1113        << "Name(" << Name << "), "
1114        << "Value(" << Value << ")\n";
1115 }
1116 #endif
1117
1118 //===----------------------------------------------------------------------===//
1119
1120 VariableDesc::VariableDesc(unsigned T)
1121 : DebugInfoDesc(T)
1122 , Context(NULL)
1123 , Name("")
1124 , File(NULL)
1125 , Line(0)
1126 , TyDesc(0)
1127 {}
1128
1129 // Implement isa/cast/dyncast.
1130 bool VariableDesc::classof(const DebugInfoDesc *D) {
1131   unsigned T =  D->getTag();
1132   switch (T) {
1133   case DW_TAG_auto_variable:
1134   case DW_TAG_arg_variable:
1135   case DW_TAG_return_variable:
1136     return true;
1137   default: break;
1138   }
1139   return false;
1140 }
1141
1142 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
1143 ///
1144 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
1145   DebugInfoDesc::ApplyToFields(Visitor);
1146   
1147   Visitor->Apply(Context);
1148   Visitor->Apply(Name);
1149   Visitor->Apply(File);
1150   Visitor->Apply(Line);
1151   Visitor->Apply(TyDesc);
1152 }
1153
1154 /// getDescString - Return a string used to compose global names and labels.
1155 ///
1156 const char *VariableDesc::getDescString() const {
1157   return "llvm.dbg.variable";
1158 }
1159
1160 /// getTypeString - Return a string used to label this descriptor's type.
1161 ///
1162 const char *VariableDesc::getTypeString() const {
1163   return "llvm.dbg.variable.type";
1164 }
1165
1166 #ifndef NDEBUG
1167 void VariableDesc::dump() {
1168   cerr << getDescString() << " "
1169        << "Version(" << getVersion() << "), "
1170        << "Tag(" << getTag() << "), "
1171        << "Context(" << Context << "), "
1172        << "Name(\"" << Name << "\"), "
1173        << "File(" << File << "), "
1174        << "Line(" << Line << "), "
1175        << "TyDesc(" << TyDesc << ")\n";
1176 }
1177 #endif
1178
1179 //===----------------------------------------------------------------------===//
1180
1181 GlobalDesc::GlobalDesc(unsigned T)
1182 : AnchoredDesc(T)
1183 , Context(0)
1184 , Name("")
1185 , FullName("")
1186 , LinkageName("")
1187 , File(NULL)
1188 , Line(0)
1189 , TyDesc(NULL)
1190 , IsStatic(false)
1191 , IsDefinition(false)
1192 {}
1193
1194 /// ApplyToFields - Target the visitor to the fields of the global.
1195 ///
1196 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1197   AnchoredDesc::ApplyToFields(Visitor);
1198
1199   Visitor->Apply(Context);
1200   Visitor->Apply(Name);
1201   Visitor->Apply(FullName);
1202   Visitor->Apply(LinkageName);
1203   Visitor->Apply(File);
1204   Visitor->Apply(Line);
1205   Visitor->Apply(TyDesc);
1206   Visitor->Apply(IsStatic);
1207   Visitor->Apply(IsDefinition);
1208 }
1209
1210 //===----------------------------------------------------------------------===//
1211
1212 GlobalVariableDesc::GlobalVariableDesc()
1213 : GlobalDesc(DW_TAG_variable)
1214 , Global(NULL)
1215 {}
1216
1217 // Implement isa/cast/dyncast.
1218 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1219   return D->getTag() == DW_TAG_variable; 
1220 }
1221
1222 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1223 ///
1224 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1225   GlobalDesc::ApplyToFields(Visitor);
1226
1227   Visitor->Apply(Global);
1228 }
1229
1230 /// getDescString - Return a string used to compose global names and labels.
1231 ///
1232 const char *GlobalVariableDesc::getDescString() const {
1233   return "llvm.dbg.global_variable";
1234 }
1235
1236 /// getTypeString - Return a string used to label this descriptors type.
1237 ///
1238 const char *GlobalVariableDesc::getTypeString() const {
1239   return "llvm.dbg.global_variable.type";
1240 }
1241
1242 /// getAnchorString - Return a string used to label this descriptor's anchor.
1243 ///
1244 const char *const GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1245 const char *GlobalVariableDesc::getAnchorString() const {
1246   return AnchorString;
1247 }
1248
1249 #ifndef NDEBUG
1250 void GlobalVariableDesc::dump() {
1251   cerr << getDescString() << " "
1252        << "Version(" << getVersion() << "), "
1253        << "Tag(" << getTag() << "), "
1254        << "Anchor(" << getAnchor() << "), "
1255        << "Name(\"" << getName() << "\"), "
1256        << "FullName(\"" << getFullName() << "\"), "
1257        << "LinkageName(\"" << getLinkageName() << "\"), "
1258        << "File(" << getFile() << "),"
1259        << "Line(" << getLine() << "),"
1260        << "Type(" << getType() << "), "
1261        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1262        << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1263        << "Global(" << Global << ")\n";
1264 }
1265 #endif
1266
1267 //===----------------------------------------------------------------------===//
1268
1269 SubprogramDesc::SubprogramDesc()
1270 : GlobalDesc(DW_TAG_subprogram)
1271 {}
1272
1273 // Implement isa/cast/dyncast.
1274 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1275   return D->getTag() == DW_TAG_subprogram;
1276 }
1277
1278 /// ApplyToFields - Target the visitor to the fields of the
1279 /// SubprogramDesc.
1280 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1281   GlobalDesc::ApplyToFields(Visitor);
1282 }
1283
1284 /// getDescString - Return a string used to compose global names and labels.
1285 ///
1286 const char *SubprogramDesc::getDescString() const {
1287   return "llvm.dbg.subprogram";
1288 }
1289
1290 /// getTypeString - Return a string used to label this descriptors type.
1291 ///
1292 const char *SubprogramDesc::getTypeString() const {
1293   return "llvm.dbg.subprogram.type";
1294 }
1295
1296 /// getAnchorString - Return a string used to label this descriptor's anchor.
1297 ///
1298 const char *const SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1299 const char *SubprogramDesc::getAnchorString() const {
1300   return AnchorString;
1301 }
1302
1303 #ifndef NDEBUG
1304 void SubprogramDesc::dump() {
1305   cerr << getDescString() << " "
1306        << "Version(" << getVersion() << "), "
1307        << "Tag(" << getTag() << "), "
1308        << "Anchor(" << getAnchor() << "), "
1309        << "Name(\"" << getName() << "\"), "
1310        << "FullName(\"" << getFullName() << "\"), "
1311        << "LinkageName(\"" << getLinkageName() << "\"), "
1312        << "File(" << getFile() << "),"
1313        << "Line(" << getLine() << "),"
1314        << "Type(" << getType() << "), "
1315        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1316        << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1317 }
1318 #endif
1319
1320 //===----------------------------------------------------------------------===//
1321
1322 BlockDesc::BlockDesc()
1323 : DebugInfoDesc(DW_TAG_lexical_block)
1324 , Context(NULL)
1325 {}
1326
1327 // Implement isa/cast/dyncast.
1328 bool BlockDesc::classof(const DebugInfoDesc *D) {
1329   return D->getTag() == DW_TAG_lexical_block;
1330 }
1331
1332 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1333 ///
1334 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1335   DebugInfoDesc::ApplyToFields(Visitor);
1336
1337   Visitor->Apply(Context);
1338 }
1339
1340 /// getDescString - Return a string used to compose global names and labels.
1341 ///
1342 const char *BlockDesc::getDescString() const {
1343   return "llvm.dbg.block";
1344 }
1345
1346 /// getTypeString - Return a string used to label this descriptors type.
1347 ///
1348 const char *BlockDesc::getTypeString() const {
1349   return "llvm.dbg.block.type";
1350 }
1351
1352 #ifndef NDEBUG
1353 void BlockDesc::dump() {
1354   cerr << getDescString() << " "
1355        << "Version(" << getVersion() << "), "
1356        << "Tag(" << getTag() << "),"
1357        << "Context(" << Context << ")\n";
1358 }
1359 #endif
1360
1361 //===----------------------------------------------------------------------===//
1362
1363 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1364   return Deserialize(getGlobalVariable(V));
1365 }
1366 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1367   // Handle NULL.
1368   if (!GV) return NULL;
1369
1370   // Check to see if it has been already deserialized.
1371   DebugInfoDesc *&Slot = GlobalDescs[GV];
1372   if (Slot) return Slot;
1373
1374   // Get the Tag from the global.
1375   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1376   
1377   // Create an empty instance of the correct sort.
1378   Slot = DebugInfoDesc::DescFactory(Tag);
1379   
1380   // If not a user defined descriptor.
1381   if (Slot) {
1382     // Deserialize the fields.
1383     DIDeserializeVisitor DRAM(*this, GV);
1384     DRAM.ApplyToFields(Slot);
1385   }
1386   
1387   return Slot;
1388 }
1389
1390 //===----------------------------------------------------------------------===//
1391
1392 /// getStrPtrType - Return a "sbyte *" type.
1393 ///
1394 const PointerType *DISerializer::getStrPtrType() {
1395   // If not already defined.
1396   if (!StrPtrTy) {
1397     // Construct the pointer to signed bytes.
1398     StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
1399   }
1400   
1401   return StrPtrTy;
1402 }
1403
1404 /// getEmptyStructPtrType - Return a "{ }*" type.
1405 ///
1406 const PointerType *DISerializer::getEmptyStructPtrType() {
1407   // If not already defined.
1408   if (EmptyStructPtrTy) return EmptyStructPtrTy;
1409
1410   // Construct the pointer to empty structure type.
1411   const StructType *EmptyStructTy = StructType::get(NULL, NULL);
1412
1413   // Construct the pointer to empty structure type.
1414   EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
1415   return EmptyStructPtrTy;
1416 }
1417
1418 /// getTagType - Return the type describing the specified descriptor (via tag.)
1419 ///
1420 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1421   // Attempt to get the previously defined type.
1422   StructType *&Ty = TagTypes[DD->getTag()];
1423   
1424   // If not already defined.
1425   if (!Ty) {
1426     // Set up fields vector.
1427     std::vector<const Type*> Fields;
1428     // Get types of fields.
1429     DIGetTypesVisitor GTAM(*this, Fields);
1430     GTAM.ApplyToFields(DD);
1431
1432     // Construct structured type.
1433     Ty = StructType::get(Fields);
1434     
1435     // Register type name with module.
1436     M->addTypeName(DD->getTypeString(), Ty);
1437   }
1438   
1439   return Ty;
1440 }
1441
1442 /// getString - Construct the string as constant string global.
1443 ///
1444 Constant *DISerializer::getString(const std::string &String) {
1445   // Check string cache for previous edition.
1446   Constant *&Slot = StringCache[String];
1447
1448   // Return Constant if previously defined.
1449   if (Slot) return Slot;
1450
1451   // If empty string then use a sbyte* null instead.
1452   if (String.empty()) {
1453     Slot = ConstantPointerNull::get(getStrPtrType());
1454   } else {
1455     // Construct string as an llvm constant.
1456     Constant *ConstStr = ConstantArray::get(String);
1457
1458     // Otherwise create and return a new string global.
1459     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1460                                                GlobalVariable::InternalLinkage,
1461                                                ConstStr, ".str", M);
1462     StrGV->setSection("llvm.metadata");
1463
1464     // Convert to generic string pointer.
1465     Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
1466   }
1467
1468   return Slot;
1469   
1470 }
1471
1472 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1473 /// so that it can be serialized to a .bc or .ll file.
1474 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1475   // Check if the DebugInfoDesc is already in the map.
1476   GlobalVariable *&Slot = DescGlobals[DD];
1477   
1478   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1479   if (Slot) return Slot;
1480   
1481   // Get the type associated with the Tag.
1482   const StructType *Ty = getTagType(DD);
1483
1484   // Create the GlobalVariable early to prevent infinite recursion.
1485   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1486                                           NULL, DD->getDescString(), M);
1487   GV->setSection("llvm.metadata");
1488
1489   // Insert new GlobalVariable in DescGlobals map.
1490   Slot = GV;
1491  
1492   // Set up elements vector
1493   std::vector<Constant*> Elements;
1494   // Add fields.
1495   DISerializeVisitor SRAM(*this, Elements);
1496   SRAM.ApplyToFields(DD);
1497
1498   // Set the globals initializer.
1499   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1500   
1501   return GV;
1502 }
1503
1504 /// addDescriptor - Directly connect DD with existing GV.
1505 void DISerializer::addDescriptor(DebugInfoDesc *DD,
1506                                  GlobalVariable *GV) {
1507   DescGlobals[DD] = GV;
1508 }
1509
1510 //===----------------------------------------------------------------------===//
1511
1512 /// Verify - Return true if the GlobalVariable appears to be a valid
1513 /// serialization of a DebugInfoDesc.
1514 bool DIVerifier::Verify(Value *V) {
1515   return !V || Verify(getGlobalVariable(V));
1516 }
1517 bool DIVerifier::Verify(GlobalVariable *GV) {
1518   // NULLs are valid.
1519   if (!GV) return true;
1520   
1521   // Check prior validity.
1522   unsigned &ValiditySlot = Validity[GV];
1523   
1524   // If visited before then use old state.
1525   if (ValiditySlot) return ValiditySlot == Valid;
1526   
1527   // Assume validity for the time being (recursion.)
1528   ValiditySlot = Valid;
1529   
1530   // Make sure the global is internal or link once (anchor.)
1531   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1532       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1533     ValiditySlot = Invalid;
1534     return false;
1535   }
1536
1537   // Get the Tag.
1538   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1539   
1540   // Check for user defined descriptors.
1541   if (Tag == DW_TAG_invalid) {
1542     ValiditySlot = Valid;
1543     return true;
1544   }
1545   
1546   // Get the Version.
1547   unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
1548   
1549   // Check for version mismatch.
1550   if (Version != LLVMDebugVersion) {
1551     ValiditySlot = Invalid;
1552     return false;
1553   }
1554
1555   // Construct an empty DebugInfoDesc.
1556   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1557   
1558   // Allow for user defined descriptors.
1559   if (!DD) return true;
1560   
1561   // Get the initializer constant.
1562   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1563   
1564   // Get the operand count.
1565   unsigned N = CI->getNumOperands();
1566   
1567   // Get the field count.
1568   unsigned &CountSlot = Counts[Tag];
1569
1570   if (!CountSlot)
1571     // Check the operand count to the field count
1572     CountSlot = CountFields(DD);
1573   
1574   // Field count must be at most equal operand count.
1575   if (CountSlot >  N) {
1576     delete DD;
1577     ValiditySlot = Invalid;
1578     return false;
1579   }
1580   
1581   // Check each field for valid type.
1582   DIVerifyVisitor VRAM(*this, GV);
1583   VRAM.ApplyToFields(DD);
1584   
1585   // Release empty DebugInfoDesc.
1586   delete DD;
1587   
1588   // If fields are not valid.
1589   if (!VRAM.isValid()) {
1590     ValiditySlot = Invalid;
1591     return false;
1592   }
1593   
1594   return true;
1595 }
1596
1597 /// isVerified - Return true if the specified GV has already been
1598 /// verified as a debug information descriptor.
1599 bool DIVerifier::isVerified(GlobalVariable *GV) {
1600   unsigned &ValiditySlot = Validity[GV];
1601   if (ValiditySlot) return ValiditySlot == Valid;
1602   return false;
1603 }
1604
1605 //===----------------------------------------------------------------------===//
1606
1607 DebugScope::~DebugScope() {
1608   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1609   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1610 }
1611
1612 //===----------------------------------------------------------------------===//
1613
1614 MachineModuleInfo::MachineModuleInfo()
1615 : ImmutablePass(&ID)
1616 , DR()
1617 , VR()
1618 , CompileUnits()
1619 , Directories()
1620 , SourceFiles()
1621 , Lines()
1622 , LabelIDList()
1623 , ScopeMap()
1624 , RootScope(NULL)
1625 , FrameMoves()
1626 , LandingPads()
1627 , Personalities()
1628 , CallsEHReturn(0)
1629 , CallsUnwindInit(0)
1630 {
1631   // Always emit "no personality" info
1632   Personalities.push_back(NULL);
1633 }
1634 MachineModuleInfo::~MachineModuleInfo() {
1635
1636 }
1637
1638 /// doInitialization - Initialize the state for a new module.
1639 ///
1640 bool MachineModuleInfo::doInitialization() {
1641   return false;
1642 }
1643
1644 /// doFinalization - Tear down the state after completion of a module.
1645 ///
1646 bool MachineModuleInfo::doFinalization() {
1647   return false;
1648 }
1649
1650 /// BeginFunction - Begin gathering function meta information.
1651 ///
1652 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
1653   // Coming soon.
1654 }
1655
1656 /// EndFunction - Discard function meta information.
1657 ///
1658 void MachineModuleInfo::EndFunction() {
1659   // Clean up scope information.
1660   if (RootScope) {
1661     delete RootScope;
1662     ScopeMap.clear();
1663     RootScope = NULL;
1664   }
1665   
1666   // Clean up line info.
1667   Lines.clear();
1668
1669   // Clean up frame info.
1670   FrameMoves.clear();
1671   
1672   // Clean up exception info.
1673   LandingPads.clear();
1674   TypeInfos.clear();
1675   FilterIds.clear();
1676   FilterEnds.clear();
1677   CallsEHReturn = 0;
1678   CallsUnwindInit = 0;
1679 }
1680
1681 /// getDescFor - Convert a Value to a debug information descriptor.
1682 ///
1683 // FIXME - use new Value type when available.
1684 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
1685   return DR.Deserialize(V);
1686 }
1687
1688 /// AnalyzeModule - Scan the module for global debug information.
1689 ///
1690 void MachineModuleInfo::AnalyzeModule(Module &M) {
1691   SetupCompileUnits(M);
1692
1693   // Insert functions in the llvm.used array into UsedFunctions.
1694   GlobalVariable *GV = M.getGlobalVariable("llvm.used");
1695   if (!GV || !GV->hasInitializer()) return;
1696
1697   // Should be an array of 'i8*'.
1698   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1699   if (InitList == 0) return;
1700
1701   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1702     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
1703       if (CE->getOpcode() == Instruction::BitCast)
1704         if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
1705           UsedFunctions.insert(F);
1706   }
1707 }
1708
1709 /// SetupCompileUnits - Set up the unique vector of compile units.
1710 ///
1711 void MachineModuleInfo::SetupCompileUnits(Module &M) {
1712   std::vector<CompileUnitDesc *> CU;
1713   getAnchoredDescriptors<CompileUnitDesc>(M, CU);
1714   
1715   for (unsigned i = 0, N = CU.size(); i < N; i++) {
1716     CompileUnits.insert(CU[i]);
1717   }
1718 }
1719
1720 /// getCompileUnits - Return a vector of debug compile units.
1721 ///
1722 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
1723   return CompileUnits;
1724 }
1725
1726 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1727 /// named GlobalVariable.
1728 void
1729 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
1730                                            const std::string &RootName,
1731                                            std::vector<GlobalVariable*>&Result){
1732   return ::getGlobalVariablesUsing(M, RootName, Result);
1733 }
1734
1735 /// RecordSourceLine - Records location information and associates it with a
1736 /// debug label.  Returns a unique label ID used to generate a label and 
1737 /// provide correspondence to the source line list.
1738 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
1739                                              unsigned Source) {
1740   unsigned ID = NextLabelID();
1741   Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
1742   return ID;
1743 }
1744
1745 /// RecordSource - Register a source file with debug info. Returns an source
1746 /// ID.
1747 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
1748                                          const std::string &Source) {
1749   unsigned DirectoryID = Directories.insert(Directory);
1750   return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1751 }
1752 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1753   return RecordSource(CompileUnit->getDirectory(),
1754                       CompileUnit->getFileName());
1755 }
1756
1757 /// RecordRegionStart - Indicate the start of a region.
1758 ///
1759 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
1760   // FIXME - need to be able to handle split scopes because of bb cloning.
1761   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1762   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1763   unsigned ID = NextLabelID();
1764   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1765   return ID;
1766 }
1767
1768 /// RecordRegionEnd - Indicate the end of a region.
1769 ///
1770 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
1771   // FIXME - need to be able to handle split scopes because of bb cloning.
1772   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1773   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1774   unsigned ID = NextLabelID();
1775   Scope->setEndLabelID(ID);
1776   return ID;
1777 }
1778
1779 /// RecordVariable - Indicate the declaration of  a local variable.
1780 ///
1781 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
1782   VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
1783   DebugScope *Scope = getOrCreateScope(VD->getContext());
1784   DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1785   Scope->AddVariable(DV);
1786 }
1787
1788 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1789 ///
1790 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1791   DebugScope *&Slot = ScopeMap[ScopeDesc];
1792   if (!Slot) {
1793     // FIXME - breaks down when the context is an inlined function.
1794     DebugInfoDesc *ParentDesc = NULL;
1795     if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1796       ParentDesc = Block->getContext();
1797     }
1798     DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1799     Slot = new DebugScope(Parent, ScopeDesc);
1800     if (Parent) {
1801       Parent->AddScope(Slot);
1802     } else if (RootScope) {
1803       // FIXME - Add inlined function scopes to the root so we can delete
1804       // them later.  Long term, handle inlined functions properly.
1805       RootScope->AddScope(Slot);
1806     } else {
1807       // First function is top level function.
1808       RootScope = Slot;
1809     }
1810   }
1811   return Slot;
1812 }
1813
1814 //===-EH-------------------------------------------------------------------===//
1815
1816 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
1817 /// specified MachineBasicBlock.
1818 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
1819     (MachineBasicBlock *LandingPad) {
1820   unsigned N = LandingPads.size();
1821   for (unsigned i = 0; i < N; ++i) {
1822     LandingPadInfo &LP = LandingPads[i];
1823     if (LP.LandingPadBlock == LandingPad)
1824       return LP;
1825   }
1826   
1827   LandingPads.push_back(LandingPadInfo(LandingPad));
1828   return LandingPads[N];
1829 }
1830
1831 /// addInvoke - Provide the begin and end labels of an invoke style call and
1832 /// associate it with a try landing pad block.
1833 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
1834                                   unsigned BeginLabel, unsigned EndLabel) {
1835   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1836   LP.BeginLabels.push_back(BeginLabel);
1837   LP.EndLabels.push_back(EndLabel);
1838 }
1839
1840 /// addLandingPad - Provide the label of a try LandingPad block.
1841 ///
1842 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
1843   unsigned LandingPadLabel = NextLabelID();
1844   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1845   LP.LandingPadLabel = LandingPadLabel;  
1846   return LandingPadLabel;
1847 }
1848
1849 /// addPersonality - Provide the personality function for the exception
1850 /// information.
1851 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
1852                                        Function *Personality) {
1853   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1854   LP.Personality = Personality;
1855
1856   for (unsigned i = 0; i < Personalities.size(); ++i)
1857     if (Personalities[i] == Personality)
1858       return;
1859   
1860   Personalities.push_back(Personality);
1861 }
1862
1863 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
1864 ///
1865 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
1866                                         std::vector<GlobalVariable *> &TyInfo) {
1867   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1868   for (unsigned N = TyInfo.size(); N; --N)
1869     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
1870 }
1871
1872 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
1873 ///
1874 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
1875                                         std::vector<GlobalVariable *> &TyInfo) {
1876   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1877   std::vector<unsigned> IdsInFilter(TyInfo.size());
1878   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1879     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1880   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1881 }
1882
1883 /// addCleanup - Add a cleanup action for a landing pad.
1884 ///
1885 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1886   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1887   LP.TypeIds.push_back(0);
1888 }
1889
1890 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1891 /// pads.
1892 void MachineModuleInfo::TidyLandingPads() {
1893   for (unsigned i = 0; i != LandingPads.size(); ) {
1894     LandingPadInfo &LandingPad = LandingPads[i];
1895     LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1896
1897     // Special case: we *should* emit LPs with null LP MBB. This indicates
1898     // "nounwind" case.
1899     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1900       LandingPads.erase(LandingPads.begin() + i);
1901       continue;
1902     }
1903
1904     for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1905       unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1906       unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1907
1908       if (!BeginLabel || !EndLabel) {
1909         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1910         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1911         continue;
1912       }
1913
1914       LandingPad.BeginLabels[j] = BeginLabel;
1915       LandingPad.EndLabels[j] = EndLabel;
1916       ++j;
1917     }
1918
1919     // Remove landing pads with no try-ranges.
1920     if (LandingPads[i].BeginLabels.empty()) {
1921       LandingPads.erase(LandingPads.begin() + i);
1922       continue;
1923     }
1924
1925     // If there is no landing pad, ensure that the list of typeids is empty.
1926     // If the only typeid is a cleanup, this is the same as having no typeids.
1927     if (!LandingPad.LandingPadBlock ||
1928         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1929       LandingPad.TypeIds.clear();
1930
1931     ++i;
1932   }
1933 }
1934
1935 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is 
1936 /// function wide.
1937 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1938   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1939     if (TypeInfos[i] == TI) return i + 1;
1940
1941   TypeInfos.push_back(TI);
1942   return TypeInfos.size();
1943 }
1944
1945 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
1946 /// function wide.
1947 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1948   // If the new filter coincides with the tail of an existing filter, then
1949   // re-use the existing filter.  Folding filters more than this requires
1950   // re-ordering filters and/or their elements - probably not worth it.
1951   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1952        E = FilterEnds.end(); I != E; ++I) {
1953     unsigned i = *I, j = TyIds.size();
1954
1955     while (i && j)
1956       if (FilterIds[--i] != TyIds[--j])
1957         goto try_next;
1958
1959     if (!j)
1960       // The new filter coincides with range [i, end) of the existing filter.
1961       return -(1 + i);
1962
1963 try_next:;
1964   }
1965
1966   // Add the new filter.
1967   int FilterID = -(1 + FilterIds.size());
1968   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1969   for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1970     FilterIds.push_back(TyIds[I]);
1971   FilterEnds.push_back(FilterIds.size());
1972   FilterIds.push_back(0); // terminator
1973   return FilterID;
1974 }
1975
1976 /// getPersonality - Return the personality function for the current function.
1977 Function *MachineModuleInfo::getPersonality() const {
1978   // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1979   // function
1980   return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1981 }
1982
1983 /// getPersonalityIndex - Return unique index for current personality
1984 /// function. NULL personality function should always get zero index.
1985 unsigned MachineModuleInfo::getPersonalityIndex() const {
1986   const Function* Personality = NULL;
1987   
1988   // Scan landing pads. If there is at least one non-NULL personality - use it.
1989   for (unsigned i = 0; i != LandingPads.size(); ++i)
1990     if (LandingPads[i].Personality) {
1991       Personality = LandingPads[i].Personality;
1992       break;
1993     }
1994   
1995   for (unsigned i = 0; i < Personalities.size(); ++i) {
1996     if (Personalities[i] == Personality)
1997       return i;
1998   }
1999
2000   // This should never happen
2001   assert(0 && "Personality function should be set!");
2002   return 0;
2003 }
2004
2005 //===----------------------------------------------------------------------===//
2006 /// DebugLabelFolding pass - This pass prunes out redundant labels.  This allows
2007 /// a info consumer to determine if the range of two labels is empty, by seeing
2008 /// if the labels map to the same reduced label.
2009
2010 namespace llvm {
2011
2012 struct DebugLabelFolder : public MachineFunctionPass {
2013   static char ID;
2014   DebugLabelFolder() : MachineFunctionPass(&ID) {}
2015
2016   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2017     AU.addPreservedID(MachineLoopInfoID);
2018     AU.addPreservedID(MachineDominatorsID);
2019     MachineFunctionPass::getAnalysisUsage(AU);
2020   }
2021
2022   virtual bool runOnMachineFunction(MachineFunction &MF);
2023   virtual const char *getPassName() const { return "Label Folder"; }
2024 };
2025
2026 char DebugLabelFolder::ID = 0;
2027
2028 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
2029   // Get machine module info.
2030   MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
2031   if (!MMI) return false;
2032   
2033   // Track if change is made.
2034   bool MadeChange = false;
2035   // No prior label to begin.
2036   unsigned PriorLabel = 0;
2037   
2038   // Iterate through basic blocks.
2039   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
2040        BB != E; ++BB) {
2041     // Iterate through instructions.
2042     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
2043       // Is it a label.
2044       if (I->isDebugLabel()) {
2045         // The label ID # is always operand #0, an immediate.
2046         unsigned NextLabel = I->getOperand(0).getImm();
2047         
2048         // If there was an immediate prior label.
2049         if (PriorLabel) {
2050           // Remap the current label to prior label.
2051           MMI->RemapLabel(NextLabel, PriorLabel);
2052           // Delete the current label.
2053           I = BB->erase(I);
2054           // Indicate a change has been made.
2055           MadeChange = true;
2056           continue;
2057         } else {
2058           // Start a new round.
2059           PriorLabel = NextLabel;
2060         }
2061        } else {
2062         // No consecutive labels.
2063         PriorLabel = 0;
2064       }
2065       
2066       ++I;
2067     }
2068   }
2069   
2070   return MadeChange;
2071 }
2072
2073 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
2074
2075 }
2076