Keep "has debug info" big in MachineModuleInfo to avoid circular dependency between...
[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 << "),"
910        << "Flags(" << Flags << ")\n";
911 }
912 #endif
913
914 //===----------------------------------------------------------------------===//
915
916 DerivedTypeDesc::DerivedTypeDesc(unsigned T)
917 : TypeDesc(T)
918 , FromType(NULL)
919 {}
920
921 // Implement isa/cast/dyncast.
922 bool DerivedTypeDesc::classof(const DebugInfoDesc *D) {
923   unsigned T =  D->getTag();
924   switch (T) {
925   case DW_TAG_typedef:
926   case DW_TAG_pointer_type:
927   case DW_TAG_reference_type:
928   case DW_TAG_const_type:
929   case DW_TAG_volatile_type:
930   case DW_TAG_restrict_type:
931   case DW_TAG_member:
932   case DW_TAG_inheritance:
933     return true;
934   default: break;
935   }
936   return false;
937 }
938
939 /// ApplyToFields - Target the visitor to the fields of the DerivedTypeDesc.
940 ///
941 void DerivedTypeDesc::ApplyToFields(DIVisitor *Visitor) {
942   TypeDesc::ApplyToFields(Visitor);
943   
944   Visitor->Apply(FromType);
945 }
946
947 /// getDescString - Return a string used to compose global names and labels.
948 ///
949 const char *DerivedTypeDesc::getDescString() const {
950   return "llvm.dbg.derivedtype";
951 }
952
953 /// getTypeString - Return a string used to label this descriptor's type.
954 ///
955 const char *DerivedTypeDesc::getTypeString() const {
956   return "llvm.dbg.derivedtype.type";
957 }
958
959 #ifndef NDEBUG
960 void DerivedTypeDesc::dump() {
961   cerr << getDescString() << " "
962        << "Version(" << getVersion() << "), "
963        << "Tag(" << getTag() << "), "
964        << "Context(" << getContext() << "), "
965        << "Name(\"" << getName() << "\"), "
966        << "Size(" << getSize() << "), "
967        << "File(" << getFile() << "), "
968        << "Line(" << getLine() << "), "
969        << "FromType(" << FromType << "),"
970        << "Flags(" << Flags << ")\n";
971 }
972 #endif
973
974 //===----------------------------------------------------------------------===//
975
976 CompositeTypeDesc::CompositeTypeDesc(unsigned T)
977 : DerivedTypeDesc(T)
978 , Elements()
979 {}
980   
981 // Implement isa/cast/dyncast.
982 bool CompositeTypeDesc::classof(const DebugInfoDesc *D) {
983   unsigned T =  D->getTag();
984   switch (T) {
985   case DW_TAG_array_type:
986   case DW_TAG_structure_type:
987   case DW_TAG_union_type:
988   case DW_TAG_enumeration_type:
989   case DW_TAG_vector_type:
990   case DW_TAG_subroutine_type:
991     return true;
992   default: break;
993   }
994   return false;
995 }
996
997 /// ApplyToFields - Target the visitor to the fields of the CompositeTypeDesc.
998 ///
999 void CompositeTypeDesc::ApplyToFields(DIVisitor *Visitor) {
1000   DerivedTypeDesc::ApplyToFields(Visitor);  
1001
1002   Visitor->Apply(Elements);
1003 }
1004
1005 /// getDescString - Return a string used to compose global names and labels.
1006 ///
1007 const char *CompositeTypeDesc::getDescString() const {
1008   return "llvm.dbg.compositetype";
1009 }
1010
1011 /// getTypeString - Return a string used to label this descriptor's type.
1012 ///
1013 const char *CompositeTypeDesc::getTypeString() const {
1014   return "llvm.dbg.compositetype.type";
1015 }
1016
1017 #ifndef NDEBUG
1018 void CompositeTypeDesc::dump() {
1019   cerr << getDescString() << " "
1020        << "Version(" << getVersion() << "), "
1021        << "Tag(" << getTag() << "), "
1022        << "Context(" << getContext() << "), "
1023        << "Name(\"" << getName() << "\"), "
1024        << "Size(" << getSize() << "), "
1025        << "File(" << getFile() << "), "
1026        << "Line(" << getLine() << "), "
1027        << "FromType(" << getFromType() << "), "
1028        << "Elements.size(" << Elements.size() << "),"
1029        << "Flags(" << Flags << ")\n";
1030 }
1031 #endif
1032
1033 //===----------------------------------------------------------------------===//
1034
1035 SubrangeDesc::SubrangeDesc()
1036 : DebugInfoDesc(DW_TAG_subrange_type)
1037 , Lo(0)
1038 , Hi(0)
1039 {}
1040
1041 // Implement isa/cast/dyncast.
1042 bool SubrangeDesc::classof(const DebugInfoDesc *D) {
1043   return D->getTag() == DW_TAG_subrange_type;
1044 }
1045
1046 /// ApplyToFields - Target the visitor to the fields of the SubrangeDesc.
1047 ///
1048 void SubrangeDesc::ApplyToFields(DIVisitor *Visitor) {
1049   DebugInfoDesc::ApplyToFields(Visitor);
1050
1051   Visitor->Apply(Lo);
1052   Visitor->Apply(Hi);
1053 }
1054
1055 /// getDescString - Return a string used to compose global names and labels.
1056 ///
1057 const char *SubrangeDesc::getDescString() const {
1058   return "llvm.dbg.subrange";
1059 }
1060   
1061 /// getTypeString - Return a string used to label this descriptor's type.
1062 ///
1063 const char *SubrangeDesc::getTypeString() const {
1064   return "llvm.dbg.subrange.type";
1065 }
1066
1067 #ifndef NDEBUG
1068 void SubrangeDesc::dump() {
1069   cerr << getDescString() << " "
1070        << "Version(" << getVersion() << "), "
1071        << "Tag(" << getTag() << "), "
1072        << "Lo(" << Lo << "), "
1073        << "Hi(" << Hi << ")\n";
1074 }
1075 #endif
1076
1077 //===----------------------------------------------------------------------===//
1078
1079 EnumeratorDesc::EnumeratorDesc()
1080 : DebugInfoDesc(DW_TAG_enumerator)
1081 , Name("")
1082 , Value(0)
1083 {}
1084
1085 // Implement isa/cast/dyncast.
1086 bool EnumeratorDesc::classof(const DebugInfoDesc *D) {
1087   return D->getTag() == DW_TAG_enumerator;
1088 }
1089
1090 /// ApplyToFields - Target the visitor to the fields of the EnumeratorDesc.
1091 ///
1092 void EnumeratorDesc::ApplyToFields(DIVisitor *Visitor) {
1093   DebugInfoDesc::ApplyToFields(Visitor);
1094
1095   Visitor->Apply(Name);
1096   Visitor->Apply(Value);
1097 }
1098
1099 /// getDescString - Return a string used to compose global names and labels.
1100 ///
1101 const char *EnumeratorDesc::getDescString() const {
1102   return "llvm.dbg.enumerator";
1103 }
1104   
1105 /// getTypeString - Return a string used to label this descriptor's type.
1106 ///
1107 const char *EnumeratorDesc::getTypeString() const {
1108   return "llvm.dbg.enumerator.type";
1109 }
1110
1111 #ifndef NDEBUG
1112 void EnumeratorDesc::dump() {
1113   cerr << getDescString() << " "
1114        << "Version(" << getVersion() << "), "
1115        << "Tag(" << getTag() << "), "
1116        << "Name(" << Name << "), "
1117        << "Value(" << Value << ")\n";
1118 }
1119 #endif
1120
1121 //===----------------------------------------------------------------------===//
1122
1123 VariableDesc::VariableDesc(unsigned T)
1124 : DebugInfoDesc(T)
1125 , Context(NULL)
1126 , Name("")
1127 , File(NULL)
1128 , Line(0)
1129 , TyDesc(0)
1130 {}
1131
1132 // Implement isa/cast/dyncast.
1133 bool VariableDesc::classof(const DebugInfoDesc *D) {
1134   unsigned T =  D->getTag();
1135   switch (T) {
1136   case DW_TAG_auto_variable:
1137   case DW_TAG_arg_variable:
1138   case DW_TAG_return_variable:
1139     return true;
1140   default: break;
1141   }
1142   return false;
1143 }
1144
1145 /// ApplyToFields - Target the visitor to the fields of the VariableDesc.
1146 ///
1147 void VariableDesc::ApplyToFields(DIVisitor *Visitor) {
1148   DebugInfoDesc::ApplyToFields(Visitor);
1149   
1150   Visitor->Apply(Context);
1151   Visitor->Apply(Name);
1152   Visitor->Apply(File);
1153   Visitor->Apply(Line);
1154   Visitor->Apply(TyDesc);
1155 }
1156
1157 /// getDescString - Return a string used to compose global names and labels.
1158 ///
1159 const char *VariableDesc::getDescString() const {
1160   return "llvm.dbg.variable";
1161 }
1162
1163 /// getTypeString - Return a string used to label this descriptor's type.
1164 ///
1165 const char *VariableDesc::getTypeString() const {
1166   return "llvm.dbg.variable.type";
1167 }
1168
1169 #ifndef NDEBUG
1170 void VariableDesc::dump() {
1171   cerr << getDescString() << " "
1172        << "Version(" << getVersion() << "), "
1173        << "Tag(" << getTag() << "), "
1174        << "Context(" << Context << "), "
1175        << "Name(\"" << Name << "\"), "
1176        << "File(" << File << "), "
1177        << "Line(" << Line << "), "
1178        << "TyDesc(" << TyDesc << ")\n";
1179 }
1180 #endif
1181
1182 //===----------------------------------------------------------------------===//
1183
1184 GlobalDesc::GlobalDesc(unsigned T)
1185 : AnchoredDesc(T)
1186 , Context(0)
1187 , Name("")
1188 , FullName("")
1189 , LinkageName("")
1190 , File(NULL)
1191 , Line(0)
1192 , TyDesc(NULL)
1193 , IsStatic(false)
1194 , IsDefinition(false)
1195 {}
1196
1197 /// ApplyToFields - Target the visitor to the fields of the global.
1198 ///
1199 void GlobalDesc::ApplyToFields(DIVisitor *Visitor) {
1200   AnchoredDesc::ApplyToFields(Visitor);
1201
1202   Visitor->Apply(Context);
1203   Visitor->Apply(Name);
1204   Visitor->Apply(FullName);
1205   Visitor->Apply(LinkageName);
1206   Visitor->Apply(File);
1207   Visitor->Apply(Line);
1208   Visitor->Apply(TyDesc);
1209   Visitor->Apply(IsStatic);
1210   Visitor->Apply(IsDefinition);
1211 }
1212
1213 //===----------------------------------------------------------------------===//
1214
1215 GlobalVariableDesc::GlobalVariableDesc()
1216 : GlobalDesc(DW_TAG_variable)
1217 , Global(NULL)
1218 {}
1219
1220 // Implement isa/cast/dyncast.
1221 bool GlobalVariableDesc::classof(const DebugInfoDesc *D) {
1222   return D->getTag() == DW_TAG_variable; 
1223 }
1224
1225 /// ApplyToFields - Target the visitor to the fields of the GlobalVariableDesc.
1226 ///
1227 void GlobalVariableDesc::ApplyToFields(DIVisitor *Visitor) {
1228   GlobalDesc::ApplyToFields(Visitor);
1229
1230   Visitor->Apply(Global);
1231 }
1232
1233 /// getDescString - Return a string used to compose global names and labels.
1234 ///
1235 const char *GlobalVariableDesc::getDescString() const {
1236   return "llvm.dbg.global_variable";
1237 }
1238
1239 /// getTypeString - Return a string used to label this descriptors type.
1240 ///
1241 const char *GlobalVariableDesc::getTypeString() const {
1242   return "llvm.dbg.global_variable.type";
1243 }
1244
1245 /// getAnchorString - Return a string used to label this descriptor's anchor.
1246 ///
1247 const char *const GlobalVariableDesc::AnchorString = "llvm.dbg.global_variables";
1248 const char *GlobalVariableDesc::getAnchorString() const {
1249   return AnchorString;
1250 }
1251
1252 #ifndef NDEBUG
1253 void GlobalVariableDesc::dump() {
1254   cerr << getDescString() << " "
1255        << "Version(" << getVersion() << "), "
1256        << "Tag(" << getTag() << "), "
1257        << "Anchor(" << getAnchor() << "), "
1258        << "Name(\"" << getName() << "\"), "
1259        << "FullName(\"" << getFullName() << "\"), "
1260        << "LinkageName(\"" << getLinkageName() << "\"), "
1261        << "File(" << getFile() << "),"
1262        << "Line(" << getLine() << "),"
1263        << "Type(" << getType() << "), "
1264        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1265        << "IsDefinition(" << (isDefinition() ? "true" : "false") << "), "
1266        << "Global(" << Global << ")\n";
1267 }
1268 #endif
1269
1270 //===----------------------------------------------------------------------===//
1271
1272 SubprogramDesc::SubprogramDesc()
1273 : GlobalDesc(DW_TAG_subprogram)
1274 {}
1275
1276 // Implement isa/cast/dyncast.
1277 bool SubprogramDesc::classof(const DebugInfoDesc *D) {
1278   return D->getTag() == DW_TAG_subprogram;
1279 }
1280
1281 /// ApplyToFields - Target the visitor to the fields of the
1282 /// SubprogramDesc.
1283 void SubprogramDesc::ApplyToFields(DIVisitor *Visitor) {
1284   GlobalDesc::ApplyToFields(Visitor);
1285 }
1286
1287 /// getDescString - Return a string used to compose global names and labels.
1288 ///
1289 const char *SubprogramDesc::getDescString() const {
1290   return "llvm.dbg.subprogram";
1291 }
1292
1293 /// getTypeString - Return a string used to label this descriptors type.
1294 ///
1295 const char *SubprogramDesc::getTypeString() const {
1296   return "llvm.dbg.subprogram.type";
1297 }
1298
1299 /// getAnchorString - Return a string used to label this descriptor's anchor.
1300 ///
1301 const char *const SubprogramDesc::AnchorString = "llvm.dbg.subprograms";
1302 const char *SubprogramDesc::getAnchorString() const {
1303   return AnchorString;
1304 }
1305
1306 #ifndef NDEBUG
1307 void SubprogramDesc::dump() {
1308   cerr << getDescString() << " "
1309        << "Version(" << getVersion() << "), "
1310        << "Tag(" << getTag() << "), "
1311        << "Anchor(" << getAnchor() << "), "
1312        << "Name(\"" << getName() << "\"), "
1313        << "FullName(\"" << getFullName() << "\"), "
1314        << "LinkageName(\"" << getLinkageName() << "\"), "
1315        << "File(" << getFile() << "),"
1316        << "Line(" << getLine() << "),"
1317        << "Type(" << getType() << "), "
1318        << "IsStatic(" << (isStatic() ? "true" : "false") << "), "
1319        << "IsDefinition(" << (isDefinition() ? "true" : "false") << ")\n";
1320 }
1321 #endif
1322
1323 //===----------------------------------------------------------------------===//
1324
1325 BlockDesc::BlockDesc()
1326 : DebugInfoDesc(DW_TAG_lexical_block)
1327 , Context(NULL)
1328 {}
1329
1330 // Implement isa/cast/dyncast.
1331 bool BlockDesc::classof(const DebugInfoDesc *D) {
1332   return D->getTag() == DW_TAG_lexical_block;
1333 }
1334
1335 /// ApplyToFields - Target the visitor to the fields of the BlockDesc.
1336 ///
1337 void BlockDesc::ApplyToFields(DIVisitor *Visitor) {
1338   DebugInfoDesc::ApplyToFields(Visitor);
1339
1340   Visitor->Apply(Context);
1341 }
1342
1343 /// getDescString - Return a string used to compose global names and labels.
1344 ///
1345 const char *BlockDesc::getDescString() const {
1346   return "llvm.dbg.block";
1347 }
1348
1349 /// getTypeString - Return a string used to label this descriptors type.
1350 ///
1351 const char *BlockDesc::getTypeString() const {
1352   return "llvm.dbg.block.type";
1353 }
1354
1355 #ifndef NDEBUG
1356 void BlockDesc::dump() {
1357   cerr << getDescString() << " "
1358        << "Version(" << getVersion() << "), "
1359        << "Tag(" << getTag() << "),"
1360        << "Context(" << Context << ")\n";
1361 }
1362 #endif
1363
1364 //===----------------------------------------------------------------------===//
1365
1366 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
1367   return Deserialize(getGlobalVariable(V));
1368 }
1369 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
1370   // Handle NULL.
1371   if (!GV) return NULL;
1372
1373   // Check to see if it has been already deserialized.
1374   DebugInfoDesc *&Slot = GlobalDescs[GV];
1375   if (Slot) return Slot;
1376
1377   // Get the Tag from the global.
1378   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1379   
1380   // Create an empty instance of the correct sort.
1381   Slot = DebugInfoDesc::DescFactory(Tag);
1382   
1383   // If not a user defined descriptor.
1384   if (Slot) {
1385     // Deserialize the fields.
1386     DIDeserializeVisitor DRAM(*this, GV);
1387     DRAM.ApplyToFields(Slot);
1388   }
1389   
1390   return Slot;
1391 }
1392
1393 //===----------------------------------------------------------------------===//
1394
1395 /// getStrPtrType - Return a "sbyte *" type.
1396 ///
1397 const PointerType *DISerializer::getStrPtrType() {
1398   // If not already defined.
1399   if (!StrPtrTy) {
1400     // Construct the pointer to signed bytes.
1401     StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
1402   }
1403   
1404   return StrPtrTy;
1405 }
1406
1407 /// getEmptyStructPtrType - Return a "{ }*" type.
1408 ///
1409 const PointerType *DISerializer::getEmptyStructPtrType() {
1410   // If not already defined.
1411   if (EmptyStructPtrTy) return EmptyStructPtrTy;
1412
1413   // Construct the pointer to empty structure type.
1414   const StructType *EmptyStructTy = StructType::get(NULL, NULL);
1415
1416   // Construct the pointer to empty structure type.
1417   EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
1418   return EmptyStructPtrTy;
1419 }
1420
1421 /// getTagType - Return the type describing the specified descriptor (via tag.)
1422 ///
1423 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
1424   // Attempt to get the previously defined type.
1425   StructType *&Ty = TagTypes[DD->getTag()];
1426   
1427   // If not already defined.
1428   if (!Ty) {
1429     // Set up fields vector.
1430     std::vector<const Type*> Fields;
1431     // Get types of fields.
1432     DIGetTypesVisitor GTAM(*this, Fields);
1433     GTAM.ApplyToFields(DD);
1434
1435     // Construct structured type.
1436     Ty = StructType::get(Fields);
1437     
1438     // Register type name with module.
1439     M->addTypeName(DD->getTypeString(), Ty);
1440   }
1441   
1442   return Ty;
1443 }
1444
1445 /// getString - Construct the string as constant string global.
1446 ///
1447 Constant *DISerializer::getString(const std::string &String) {
1448   // Check string cache for previous edition.
1449   Constant *&Slot = StringCache[String];
1450
1451   // Return Constant if previously defined.
1452   if (Slot) return Slot;
1453
1454   // If empty string then use a sbyte* null instead.
1455   if (String.empty()) {
1456     Slot = ConstantPointerNull::get(getStrPtrType());
1457   } else {
1458     // Construct string as an llvm constant.
1459     Constant *ConstStr = ConstantArray::get(String);
1460
1461     // Otherwise create and return a new string global.
1462     GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
1463                                                GlobalVariable::InternalLinkage,
1464                                                ConstStr, ".str", M);
1465     StrGV->setSection("llvm.metadata");
1466
1467     // Convert to generic string pointer.
1468     Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
1469   }
1470
1471   return Slot;
1472   
1473 }
1474
1475 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
1476 /// so that it can be serialized to a .bc or .ll file.
1477 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
1478   // Check if the DebugInfoDesc is already in the map.
1479   GlobalVariable *&Slot = DescGlobals[DD];
1480   
1481   // See if DebugInfoDesc exists, if so return prior GlobalVariable.
1482   if (Slot) return Slot;
1483   
1484   // Get the type associated with the Tag.
1485   const StructType *Ty = getTagType(DD);
1486
1487   // Create the GlobalVariable early to prevent infinite recursion.
1488   GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
1489                                           NULL, DD->getDescString(), M);
1490   GV->setSection("llvm.metadata");
1491
1492   // Insert new GlobalVariable in DescGlobals map.
1493   Slot = GV;
1494  
1495   // Set up elements vector
1496   std::vector<Constant*> Elements;
1497   // Add fields.
1498   DISerializeVisitor SRAM(*this, Elements);
1499   SRAM.ApplyToFields(DD);
1500
1501   // Set the globals initializer.
1502   GV->setInitializer(ConstantStruct::get(Ty, Elements));
1503   
1504   return GV;
1505 }
1506
1507 /// addDescriptor - Directly connect DD with existing GV.
1508 void DISerializer::addDescriptor(DebugInfoDesc *DD,
1509                                  GlobalVariable *GV) {
1510   DescGlobals[DD] = GV;
1511 }
1512
1513 //===----------------------------------------------------------------------===//
1514
1515 /// Verify - Return true if the GlobalVariable appears to be a valid
1516 /// serialization of a DebugInfoDesc.
1517 bool DIVerifier::Verify(Value *V) {
1518   return !V || Verify(getGlobalVariable(V));
1519 }
1520 bool DIVerifier::Verify(GlobalVariable *GV) {
1521   // NULLs are valid.
1522   if (!GV) return true;
1523   
1524   // Check prior validity.
1525   unsigned &ValiditySlot = Validity[GV];
1526   
1527   // If visited before then use old state.
1528   if (ValiditySlot) return ValiditySlot == Valid;
1529   
1530   // Assume validity for the time being (recursion.)
1531   ValiditySlot = Valid;
1532   
1533   // Make sure the global is internal or link once (anchor.)
1534   if (GV->getLinkage() != GlobalValue::InternalLinkage &&
1535       GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
1536     ValiditySlot = Invalid;
1537     return false;
1538   }
1539
1540   // Get the Tag.
1541   unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
1542   
1543   // Check for user defined descriptors.
1544   if (Tag == DW_TAG_invalid) {
1545     ValiditySlot = Valid;
1546     return true;
1547   }
1548   
1549   // Get the Version.
1550   unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
1551   
1552   // Check for version mismatch.
1553   if (Version != LLVMDebugVersion) {
1554     ValiditySlot = Invalid;
1555     return false;
1556   }
1557
1558   // Construct an empty DebugInfoDesc.
1559   DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
1560   
1561   // Allow for user defined descriptors.
1562   if (!DD) return true;
1563   
1564   // Get the initializer constant.
1565   ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
1566   
1567   // Get the operand count.
1568   unsigned N = CI->getNumOperands();
1569   
1570   // Get the field count.
1571   unsigned &CountSlot = Counts[Tag];
1572
1573   if (!CountSlot)
1574     // Check the operand count to the field count
1575     CountSlot = CountFields(DD);
1576   
1577   // Field count must be at most equal operand count.
1578   if (CountSlot >  N) {
1579     delete DD;
1580     ValiditySlot = Invalid;
1581     return false;
1582   }
1583   
1584   // Check each field for valid type.
1585   DIVerifyVisitor VRAM(*this, GV);
1586   VRAM.ApplyToFields(DD);
1587   
1588   // Release empty DebugInfoDesc.
1589   delete DD;
1590   
1591   // If fields are not valid.
1592   if (!VRAM.isValid()) {
1593     ValiditySlot = Invalid;
1594     return false;
1595   }
1596   
1597   return true;
1598 }
1599
1600 /// isVerified - Return true if the specified GV has already been
1601 /// verified as a debug information descriptor.
1602 bool DIVerifier::isVerified(GlobalVariable *GV) {
1603   unsigned &ValiditySlot = Validity[GV];
1604   if (ValiditySlot) return ValiditySlot == Valid;
1605   return false;
1606 }
1607
1608 //===----------------------------------------------------------------------===//
1609
1610 DebugScope::~DebugScope() {
1611   for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
1612   for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
1613 }
1614
1615 //===----------------------------------------------------------------------===//
1616
1617 MachineModuleInfo::MachineModuleInfo()
1618 : ImmutablePass(&ID)
1619 , DR()
1620 , VR()
1621 , CompileUnits()
1622 , Directories()
1623 , SourceFiles()
1624 , Lines()
1625 , LabelIDList()
1626 , ScopeMap()
1627 , RootScope(NULL)
1628 , FrameMoves()
1629 , LandingPads()
1630 , Personalities()
1631 , CallsEHReturn(0)
1632 , CallsUnwindInit(0)
1633 , DbgInfoAvailable(false)
1634 {
1635   // Always emit "no personality" info
1636   Personalities.push_back(NULL);
1637 }
1638 MachineModuleInfo::~MachineModuleInfo() {
1639
1640 }
1641
1642 /// doInitialization - Initialize the state for a new module.
1643 ///
1644 bool MachineModuleInfo::doInitialization() {
1645   return false;
1646 }
1647
1648 /// doFinalization - Tear down the state after completion of a module.
1649 ///
1650 bool MachineModuleInfo::doFinalization() {
1651   return false;
1652 }
1653
1654 /// BeginFunction - Begin gathering function meta information.
1655 ///
1656 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
1657   // Coming soon.
1658 }
1659
1660 /// EndFunction - Discard function meta information.
1661 ///
1662 void MachineModuleInfo::EndFunction() {
1663   // Clean up scope information.
1664   if (RootScope) {
1665     delete RootScope;
1666     ScopeMap.clear();
1667     RootScope = NULL;
1668   }
1669   
1670   // Clean up line info.
1671   Lines.clear();
1672
1673   // Clean up frame info.
1674   FrameMoves.clear();
1675   
1676   // Clean up exception info.
1677   LandingPads.clear();
1678   TypeInfos.clear();
1679   FilterIds.clear();
1680   FilterEnds.clear();
1681   CallsEHReturn = 0;
1682   CallsUnwindInit = 0;
1683 }
1684
1685 /// getDescFor - Convert a Value to a debug information descriptor.
1686 ///
1687 // FIXME - use new Value type when available.
1688 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
1689   return DR.Deserialize(V);
1690 }
1691
1692 /// AnalyzeModule - Scan the module for global debug information.
1693 ///
1694 void MachineModuleInfo::AnalyzeModule(Module &M) {
1695   SetupCompileUnits(M);
1696
1697   // Insert functions in the llvm.used array into UsedFunctions.
1698   GlobalVariable *GV = M.getGlobalVariable("llvm.used");
1699   if (!GV || !GV->hasInitializer()) return;
1700
1701   // Should be an array of 'i8*'.
1702   ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
1703   if (InitList == 0) return;
1704
1705   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1706     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
1707       if (CE->getOpcode() == Instruction::BitCast)
1708         if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
1709           UsedFunctions.insert(F);
1710   }
1711 }
1712
1713 /// SetupCompileUnits - Set up the unique vector of compile units.
1714 ///
1715 void MachineModuleInfo::SetupCompileUnits(Module &M) {
1716   std::vector<CompileUnitDesc *> CU;
1717   getAnchoredDescriptors<CompileUnitDesc>(M, CU);
1718   
1719   for (unsigned i = 0, N = CU.size(); i < N; i++) {
1720     CompileUnits.insert(CU[i]);
1721   }
1722 }
1723
1724 /// getCompileUnits - Return a vector of debug compile units.
1725 ///
1726 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
1727   return CompileUnits;
1728 }
1729
1730 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
1731 /// named GlobalVariable.
1732 void
1733 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
1734                                            const std::string &RootName,
1735                                            std::vector<GlobalVariable*>&Result){
1736   return ::getGlobalVariablesUsing(M, RootName, Result);
1737 }
1738
1739 /// RecordSourceLine - Records location information and associates it with a
1740 /// debug label.  Returns a unique label ID used to generate a label and 
1741 /// provide correspondence to the source line list.
1742 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
1743                                              unsigned Source) {
1744   unsigned ID = NextLabelID();
1745   Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
1746   return ID;
1747 }
1748
1749 /// RecordSource - Register a source file with debug info. Returns an source
1750 /// ID.
1751 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
1752                                          const std::string &Source) {
1753   unsigned DirectoryID = Directories.insert(Directory);
1754   return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
1755 }
1756 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
1757   return RecordSource(CompileUnit->getDirectory(),
1758                       CompileUnit->getFileName());
1759 }
1760
1761 /// RecordRegionStart - Indicate the start of a region.
1762 ///
1763 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
1764   // FIXME - need to be able to handle split scopes because of bb cloning.
1765   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1766   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1767   unsigned ID = NextLabelID();
1768   if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
1769   return ID;
1770 }
1771
1772 /// RecordRegionEnd - Indicate the end of a region.
1773 ///
1774 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
1775   // FIXME - need to be able to handle split scopes because of bb cloning.
1776   DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
1777   DebugScope *Scope = getOrCreateScope(ScopeDesc);
1778   unsigned ID = NextLabelID();
1779   Scope->setEndLabelID(ID);
1780   return ID;
1781 }
1782
1783 /// RecordVariable - Indicate the declaration of  a local variable.
1784 ///
1785 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
1786   VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
1787   DebugScope *Scope = getOrCreateScope(VD->getContext());
1788   DebugVariable *DV = new DebugVariable(VD, FrameIndex);
1789   Scope->AddVariable(DV);
1790 }
1791
1792 /// getOrCreateScope - Returns the scope associated with the given descriptor.
1793 ///
1794 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
1795   DebugScope *&Slot = ScopeMap[ScopeDesc];
1796   if (!Slot) {
1797     // FIXME - breaks down when the context is an inlined function.
1798     DebugInfoDesc *ParentDesc = NULL;
1799     if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
1800       ParentDesc = Block->getContext();
1801     }
1802     DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
1803     Slot = new DebugScope(Parent, ScopeDesc);
1804     if (Parent) {
1805       Parent->AddScope(Slot);
1806     } else if (RootScope) {
1807       // FIXME - Add inlined function scopes to the root so we can delete
1808       // them later.  Long term, handle inlined functions properly.
1809       RootScope->AddScope(Slot);
1810     } else {
1811       // First function is top level function.
1812       RootScope = Slot;
1813     }
1814   }
1815   return Slot;
1816 }
1817
1818 //===-EH-------------------------------------------------------------------===//
1819
1820 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
1821 /// specified MachineBasicBlock.
1822 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
1823     (MachineBasicBlock *LandingPad) {
1824   unsigned N = LandingPads.size();
1825   for (unsigned i = 0; i < N; ++i) {
1826     LandingPadInfo &LP = LandingPads[i];
1827     if (LP.LandingPadBlock == LandingPad)
1828       return LP;
1829   }
1830   
1831   LandingPads.push_back(LandingPadInfo(LandingPad));
1832   return LandingPads[N];
1833 }
1834
1835 /// addInvoke - Provide the begin and end labels of an invoke style call and
1836 /// associate it with a try landing pad block.
1837 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
1838                                   unsigned BeginLabel, unsigned EndLabel) {
1839   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1840   LP.BeginLabels.push_back(BeginLabel);
1841   LP.EndLabels.push_back(EndLabel);
1842 }
1843
1844 /// addLandingPad - Provide the label of a try LandingPad block.
1845 ///
1846 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
1847   unsigned LandingPadLabel = NextLabelID();
1848   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1849   LP.LandingPadLabel = LandingPadLabel;  
1850   return LandingPadLabel;
1851 }
1852
1853 /// addPersonality - Provide the personality function for the exception
1854 /// information.
1855 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
1856                                        Function *Personality) {
1857   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1858   LP.Personality = Personality;
1859
1860   for (unsigned i = 0; i < Personalities.size(); ++i)
1861     if (Personalities[i] == Personality)
1862       return;
1863   
1864   Personalities.push_back(Personality);
1865 }
1866
1867 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
1868 ///
1869 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
1870                                         std::vector<GlobalVariable *> &TyInfo) {
1871   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1872   for (unsigned N = TyInfo.size(); N; --N)
1873     LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
1874 }
1875
1876 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
1877 ///
1878 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
1879                                         std::vector<GlobalVariable *> &TyInfo) {
1880   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1881   std::vector<unsigned> IdsInFilter(TyInfo.size());
1882   for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1883     IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1884   LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1885 }
1886
1887 /// addCleanup - Add a cleanup action for a landing pad.
1888 ///
1889 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1890   LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1891   LP.TypeIds.push_back(0);
1892 }
1893
1894 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1895 /// pads.
1896 void MachineModuleInfo::TidyLandingPads() {
1897   for (unsigned i = 0; i != LandingPads.size(); ) {
1898     LandingPadInfo &LandingPad = LandingPads[i];
1899     LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1900
1901     // Special case: we *should* emit LPs with null LP MBB. This indicates
1902     // "nounwind" case.
1903     if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1904       LandingPads.erase(LandingPads.begin() + i);
1905       continue;
1906     }
1907
1908     for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1909       unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1910       unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1911
1912       if (!BeginLabel || !EndLabel) {
1913         LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1914         LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1915         continue;
1916       }
1917
1918       LandingPad.BeginLabels[j] = BeginLabel;
1919       LandingPad.EndLabels[j] = EndLabel;
1920       ++j;
1921     }
1922
1923     // Remove landing pads with no try-ranges.
1924     if (LandingPads[i].BeginLabels.empty()) {
1925       LandingPads.erase(LandingPads.begin() + i);
1926       continue;
1927     }
1928
1929     // If there is no landing pad, ensure that the list of typeids is empty.
1930     // If the only typeid is a cleanup, this is the same as having no typeids.
1931     if (!LandingPad.LandingPadBlock ||
1932         (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1933       LandingPad.TypeIds.clear();
1934
1935     ++i;
1936   }
1937 }
1938
1939 /// getTypeIDFor - Return the type id for the specified typeinfo.  This is 
1940 /// function wide.
1941 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1942   for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1943     if (TypeInfos[i] == TI) return i + 1;
1944
1945   TypeInfos.push_back(TI);
1946   return TypeInfos.size();
1947 }
1948
1949 /// getFilterIDFor - Return the filter id for the specified typeinfos.  This is
1950 /// function wide.
1951 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1952   // If the new filter coincides with the tail of an existing filter, then
1953   // re-use the existing filter.  Folding filters more than this requires
1954   // re-ordering filters and/or their elements - probably not worth it.
1955   for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1956        E = FilterEnds.end(); I != E; ++I) {
1957     unsigned i = *I, j = TyIds.size();
1958
1959     while (i && j)
1960       if (FilterIds[--i] != TyIds[--j])
1961         goto try_next;
1962
1963     if (!j)
1964       // The new filter coincides with range [i, end) of the existing filter.
1965       return -(1 + i);
1966
1967 try_next:;
1968   }
1969
1970   // Add the new filter.
1971   int FilterID = -(1 + FilterIds.size());
1972   FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1973   for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1974     FilterIds.push_back(TyIds[I]);
1975   FilterEnds.push_back(FilterIds.size());
1976   FilterIds.push_back(0); // terminator
1977   return FilterID;
1978 }
1979
1980 /// getPersonality - Return the personality function for the current function.
1981 Function *MachineModuleInfo::getPersonality() const {
1982   // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1983   // function
1984   return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1985 }
1986
1987 /// getPersonalityIndex - Return unique index for current personality
1988 /// function. NULL personality function should always get zero index.
1989 unsigned MachineModuleInfo::getPersonalityIndex() const {
1990   const Function* Personality = NULL;
1991   
1992   // Scan landing pads. If there is at least one non-NULL personality - use it.
1993   for (unsigned i = 0; i != LandingPads.size(); ++i)
1994     if (LandingPads[i].Personality) {
1995       Personality = LandingPads[i].Personality;
1996       break;
1997     }
1998   
1999   for (unsigned i = 0; i < Personalities.size(); ++i) {
2000     if (Personalities[i] == Personality)
2001       return i;
2002   }
2003
2004   // This should never happen
2005   assert(0 && "Personality function should be set!");
2006   return 0;
2007 }
2008
2009 //===----------------------------------------------------------------------===//
2010 /// DebugLabelFolding pass - This pass prunes out redundant labels.  This allows
2011 /// a info consumer to determine if the range of two labels is empty, by seeing
2012 /// if the labels map to the same reduced label.
2013
2014 namespace llvm {
2015
2016 struct DebugLabelFolder : public MachineFunctionPass {
2017   static char ID;
2018   DebugLabelFolder() : MachineFunctionPass(&ID) {}
2019
2020   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2021     AU.addPreservedID(MachineLoopInfoID);
2022     AU.addPreservedID(MachineDominatorsID);
2023     MachineFunctionPass::getAnalysisUsage(AU);
2024   }
2025
2026   virtual bool runOnMachineFunction(MachineFunction &MF);
2027   virtual const char *getPassName() const { return "Label Folder"; }
2028 };
2029
2030 char DebugLabelFolder::ID = 0;
2031
2032 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
2033   // Get machine module info.
2034   MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
2035   if (!MMI) return false;
2036   
2037   // Track if change is made.
2038   bool MadeChange = false;
2039   // No prior label to begin.
2040   unsigned PriorLabel = 0;
2041   
2042   // Iterate through basic blocks.
2043   for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
2044        BB != E; ++BB) {
2045     // Iterate through instructions.
2046     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
2047       // Is it a label.
2048       if (I->isDebugLabel()) {
2049         // The label ID # is always operand #0, an immediate.
2050         unsigned NextLabel = I->getOperand(0).getImm();
2051         
2052         // If there was an immediate prior label.
2053         if (PriorLabel) {
2054           // Remap the current label to prior label.
2055           MMI->RemapLabel(NextLabel, PriorLabel);
2056           // Delete the current label.
2057           I = BB->erase(I);
2058           // Indicate a change has been made.
2059           MadeChange = true;
2060           continue;
2061         } else {
2062           // Start a new round.
2063           PriorLabel = NextLabel;
2064         }
2065        } else {
2066         // No consecutive labels.
2067         PriorLabel = 0;
2068       }
2069       
2070       ++I;
2071     }
2072   }
2073   
2074   return MadeChange;
2075 }
2076
2077 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }
2078
2079 }
2080