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