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