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