1 //===-- llvm/CodeGen/MachineModuleInfo.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/CodeGen/MachineModuleInfo.h"
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/CodeGen/MachineDebugInfoDesc.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"
28 using namespace llvm::dwarf;
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;
35 //===----------------------------------------------------------------------===//
37 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
38 /// specified value in their initializer somewhere.
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.
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);
53 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
54 /// named GlobalVariable.
56 getGlobalVariablesUsing(Module &M, const std::string &RootName,
57 std::vector<GlobalVariable*> &Result) {
58 std::vector<const Type*> FieldTypes;
59 FieldTypes.push_back(Type::Int32Ty);
60 FieldTypes.push_back(Type::Int32Ty);
62 // Get the GlobalVariable root.
63 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
64 StructType::get(FieldTypes));
66 // If present and linkonce then scan for users.
67 if (UseRoot && UseRoot->hasLinkOnceLinkage())
68 getGlobalVariablesUsing(UseRoot, Result);
71 /// isStringValue - Return true if the given value can be coerced to a string.
73 static bool isStringValue(Value *V) {
74 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
75 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
76 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
77 return Init->isString();
79 } else if (Constant *C = dyn_cast<Constant>(V)) {
80 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
81 return isStringValue(GV);
82 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
83 if (CE->getOpcode() == Instruction::GetElementPtr) {
84 if (CE->getNumOperands() == 3 &&
85 cast<Constant>(CE->getOperand(1))->isNullValue() &&
86 isa<ConstantInt>(CE->getOperand(2))) {
87 return isStringValue(CE->getOperand(0));
95 /// getGlobalVariable - Return either a direct or cast Global value.
97 static GlobalVariable *getGlobalVariable(Value *V) {
98 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
100 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
101 if (CE->getOpcode() == Instruction::BitCast) {
102 return dyn_cast<GlobalVariable>(CE->getOperand(0));
103 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
104 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
105 if (!CE->getOperand(i)->isNullValue())
108 return dyn_cast<GlobalVariable>(CE->getOperand(0));
114 /// isGlobalVariable - Return true if the given value can be coerced to a
116 static bool isGlobalVariable(Value *V) {
117 if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
119 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
120 if (CE->getOpcode() == Instruction::BitCast) {
121 return isa<GlobalVariable>(CE->getOperand(0));
122 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
123 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
124 if (!CE->getOperand(i)->isNullValue())
127 return isa<GlobalVariable>(CE->getOperand(0));
133 //===----------------------------------------------------------------------===//
135 /// ApplyToFields - Target the visitor to each field of the debug information
137 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
138 DD->ApplyToFields(this);
143 //===----------------------------------------------------------------------===//
144 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
145 /// the supplied DebugInfoDesc.
146 class DICountVisitor : public DIVisitor {
148 unsigned Count; // Running count of fields.
151 DICountVisitor() : DIVisitor(), Count(0) {}
154 unsigned getCount() const { return Count; }
156 /// Apply - Count each of the fields.
158 virtual void Apply(int &Field) { ++Count; }
159 virtual void Apply(unsigned &Field) { ++Count; }
160 virtual void Apply(int64_t &Field) { ++Count; }
161 virtual void Apply(uint64_t &Field) { ++Count; }
162 virtual void Apply(bool &Field) { ++Count; }
163 virtual void Apply(std::string &Field) { ++Count; }
164 virtual void Apply(DebugInfoDesc *&Field) { ++Count; }
165 virtual void Apply(GlobalVariable *&Field) { ++Count; }
166 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
171 //===----------------------------------------------------------------------===//
172 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
173 /// supplied DebugInfoDesc.
174 class DIDeserializeVisitor : public DIVisitor {
176 DIDeserializer &DR; // Active deserializer.
177 unsigned I; // Current operand index.
178 ConstantStruct *CI; // GlobalVariable constant initializer.
181 DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
182 : DIVisitor(), DR(D), I(0), CI(cast<ConstantStruct>(GV->getInitializer()))
185 /// Apply - Set the value of each of the fields.
187 virtual void Apply(int &Field) {
188 Constant *C = CI->getOperand(I++);
189 Field = cast<ConstantInt>(C)->getSExtValue();
191 virtual void Apply(unsigned &Field) {
192 Constant *C = CI->getOperand(I++);
193 Field = cast<ConstantInt>(C)->getZExtValue();
195 virtual void Apply(int64_t &Field) {
196 Constant *C = CI->getOperand(I++);
197 Field = cast<ConstantInt>(C)->getSExtValue();
199 virtual void Apply(uint64_t &Field) {
200 Constant *C = CI->getOperand(I++);
201 Field = cast<ConstantInt>(C)->getZExtValue();
203 virtual void Apply(bool &Field) {
204 Constant *C = CI->getOperand(I++);
205 Field = cast<ConstantInt>(C)->getZExtValue();
207 virtual void Apply(std::string &Field) {
208 Constant *C = CI->getOperand(I++);
209 Field = C->getStringValue();
211 virtual void Apply(DebugInfoDesc *&Field) {
212 Constant *C = CI->getOperand(I++);
213 Field = DR.Deserialize(C);
215 virtual void Apply(GlobalVariable *&Field) {
216 Constant *C = CI->getOperand(I++);
217 Field = getGlobalVariable(C);
219 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
221 Constant *C = CI->getOperand(I++);
222 GlobalVariable *GV = getGlobalVariable(C);
223 if (GV->hasInitializer()) {
224 if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
225 for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
226 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
227 DebugInfoDesc *DE = DR.Deserialize(GVE);
230 } else if (GV->getInitializer()->isNullValue()) {
231 if (const ArrayType *T =
232 dyn_cast<ArrayType>(GV->getType()->getElementType())) {
233 Field.resize(T->getNumElements());
240 //===----------------------------------------------------------------------===//
241 /// DISerializeVisitor - This DIVisitor serializes all the fields in
242 /// the supplied DebugInfoDesc.
243 class DISerializeVisitor : public DIVisitor {
245 DISerializer &SR; // Active serializer.
246 std::vector<Constant*> &Elements; // Element accumulator.
249 DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
255 /// Apply - Set the value of each of the fields.
257 virtual void Apply(int &Field) {
258 Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
260 virtual void Apply(unsigned &Field) {
261 Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
263 virtual void Apply(int64_t &Field) {
264 Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
266 virtual void Apply(uint64_t &Field) {
267 Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
269 virtual void Apply(bool &Field) {
270 Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
272 virtual void Apply(std::string &Field) {
273 Elements.push_back(SR.getString(Field));
275 virtual void Apply(DebugInfoDesc *&Field) {
276 GlobalVariable *GV = NULL;
278 // If non-NULL then convert to global.
279 if (Field) GV = SR.Serialize(Field);
281 // FIXME - At some point should use specific type.
282 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
285 // Set to pointer to global.
286 Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
289 Elements.push_back(ConstantPointerNull::get(EmptyTy));
292 virtual void Apply(GlobalVariable *&Field) {
293 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
295 Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
297 Elements.push_back(ConstantPointerNull::get(EmptyTy));
300 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
301 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
302 unsigned N = Field.size();
303 ArrayType *AT = ArrayType::get(EmptyTy, N);
304 std::vector<Constant *> ArrayElements;
306 for (unsigned i = 0; i < N; ++i) {
307 if (DebugInfoDesc *Element = Field[i]) {
308 GlobalVariable *GVE = SR.Serialize(Element);
309 Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
310 ArrayElements.push_back(cast<Constant>(CE));
312 ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
316 Constant *CA = ConstantArray::get(AT, ArrayElements);
317 GlobalVariable *CAGV = new GlobalVariable(AT, true,
318 GlobalValue::InternalLinkage,
319 CA, "llvm.dbg.array",
321 CAGV->setSection("llvm.metadata");
322 Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
323 Elements.push_back(CAE);
327 //===----------------------------------------------------------------------===//
328 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
329 /// the supplied DebugInfoDesc.
330 class DIGetTypesVisitor : public DIVisitor {
332 DISerializer &SR; // Active serializer.
333 std::vector<const Type*> &Fields; // Type accumulator.
336 DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
342 /// Apply - Set the value of each of the fields.
344 virtual void Apply(int &Field) {
345 Fields.push_back(Type::Int32Ty);
347 virtual void Apply(unsigned &Field) {
348 Fields.push_back(Type::Int32Ty);
350 virtual void Apply(int64_t &Field) {
351 Fields.push_back(Type::Int64Ty);
353 virtual void Apply(uint64_t &Field) {
354 Fields.push_back(Type::Int64Ty);
356 virtual void Apply(bool &Field) {
357 Fields.push_back(Type::Int1Ty);
359 virtual void Apply(std::string &Field) {
360 Fields.push_back(SR.getStrPtrType());
362 virtual void Apply(DebugInfoDesc *&Field) {
363 // FIXME - At some point should use specific type.
364 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
365 Fields.push_back(EmptyTy);
367 virtual void Apply(GlobalVariable *&Field) {
368 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
369 Fields.push_back(EmptyTy);
371 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
372 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
373 Fields.push_back(EmptyTy);
377 //===----------------------------------------------------------------------===//
378 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
379 /// a constant initializer.
380 class DIVerifyVisitor : public DIVisitor {
382 DIVerifier &VR; // Active verifier.
383 bool IsValid; // Validity status.
384 unsigned I; // Current operand index.
385 ConstantStruct *CI; // GlobalVariable constant initializer.
388 DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
393 , CI(cast<ConstantStruct>(GV->getInitializer()))
398 bool isValid() const { return IsValid; }
400 /// Apply - Set the value of each of the fields.
402 virtual void Apply(int &Field) {
403 Constant *C = CI->getOperand(I++);
404 IsValid = IsValid && isa<ConstantInt>(C);
406 virtual void Apply(unsigned &Field) {
407 Constant *C = CI->getOperand(I++);
408 IsValid = IsValid && isa<ConstantInt>(C);
410 virtual void Apply(int64_t &Field) {
411 Constant *C = CI->getOperand(I++);
412 IsValid = IsValid && isa<ConstantInt>(C);
414 virtual void Apply(uint64_t &Field) {
415 Constant *C = CI->getOperand(I++);
416 IsValid = IsValid && isa<ConstantInt>(C);
418 virtual void Apply(bool &Field) {
419 Constant *C = CI->getOperand(I++);
420 IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
422 virtual void Apply(std::string &Field) {
423 Constant *C = CI->getOperand(I++);
425 (!C || isStringValue(C) || C->isNullValue());
427 virtual void Apply(DebugInfoDesc *&Field) {
428 // FIXME - Prepare the correct descriptor.
429 Constant *C = CI->getOperand(I++);
430 IsValid = IsValid && isGlobalVariable(C);
432 virtual void Apply(GlobalVariable *&Field) {
433 Constant *C = CI->getOperand(I++);
434 IsValid = IsValid && isGlobalVariable(C);
436 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
437 Constant *C = CI->getOperand(I++);
438 IsValid = IsValid && isGlobalVariable(C);
439 if (!IsValid) return;
441 GlobalVariable *GV = getGlobalVariable(C);
442 IsValid = IsValid && GV && GV->hasInitializer();
443 if (!IsValid) return;
445 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
446 IsValid = IsValid && CA;
447 if (!IsValid) return;
449 for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
450 IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
451 if (!IsValid) return;
453 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
461 //===----------------------------------------------------------------------===//
463 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
464 return Deserialize(getGlobalVariable(V));
466 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
468 if (!GV) return NULL;
470 // Check to see if it has been already deserialized.
471 DebugInfoDesc *&Slot = GlobalDescs[GV];
472 if (Slot) return Slot;
474 // Get the Tag from the global.
475 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
477 // Create an empty instance of the correct sort.
478 Slot = DebugInfoDesc::DescFactory(Tag);
480 // If not a user defined descriptor.
482 // Deserialize the fields.
483 DIDeserializeVisitor DRAM(*this, GV);
484 DRAM.ApplyToFields(Slot);
490 //===----------------------------------------------------------------------===//
492 /// getStrPtrType - Return a "sbyte *" type.
494 const PointerType *DISerializer::getStrPtrType() {
495 // If not already defined.
497 // Construct the pointer to signed bytes.
498 StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
504 /// getEmptyStructPtrType - Return a "{ }*" type.
506 const PointerType *DISerializer::getEmptyStructPtrType() {
507 // If not already defined.
508 if (EmptyStructPtrTy) return EmptyStructPtrTy;
510 // Construct the pointer to empty structure type.
511 const StructType *EmptyStructTy =
512 StructType::get(std::vector<const Type*>());
514 // Construct the pointer to empty structure type.
515 EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
516 return EmptyStructPtrTy;
519 /// getTagType - Return the type describing the specified descriptor (via tag.)
521 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
522 // Attempt to get the previously defined type.
523 StructType *&Ty = TagTypes[DD->getTag()];
525 // If not already defined.
527 // Set up fields vector.
528 std::vector<const Type*> Fields;
529 // Get types of fields.
530 DIGetTypesVisitor GTAM(*this, Fields);
531 GTAM.ApplyToFields(DD);
533 // Construct structured type.
534 Ty = StructType::get(Fields);
536 // Register type name with module.
537 M->addTypeName(DD->getTypeString(), Ty);
543 /// getString - Construct the string as constant string global.
545 Constant *DISerializer::getString(const std::string &String) {
546 // Check string cache for previous edition.
547 Constant *&Slot = StringCache[String.c_str()];
549 // Return Constant if previously defined.
550 if (Slot) return Slot;
552 // If empty string then use a sbyte* null instead.
553 if (String.empty()) {
554 Slot = ConstantPointerNull::get(getStrPtrType());
556 // Construct string as an llvm constant.
557 Constant *ConstStr = ConstantArray::get(String);
559 // Otherwise create and return a new string global.
560 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
561 GlobalVariable::InternalLinkage,
562 ConstStr, ".str", M);
563 StrGV->setSection("llvm.metadata");
565 // Convert to generic string pointer.
566 Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
573 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
574 /// so that it can be serialized to a .bc or .ll file.
575 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
576 // Check if the DebugInfoDesc is already in the map.
577 GlobalVariable *&Slot = DescGlobals[DD];
579 // See if DebugInfoDesc exists, if so return prior GlobalVariable.
580 if (Slot) return Slot;
582 // Get the type associated with the Tag.
583 const StructType *Ty = getTagType(DD);
585 // Create the GlobalVariable early to prevent infinite recursion.
586 GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
587 NULL, DD->getDescString(), M);
588 GV->setSection("llvm.metadata");
590 // Insert new GlobalVariable in DescGlobals map.
593 // Set up elements vector
594 std::vector<Constant*> Elements;
596 DISerializeVisitor SRAM(*this, Elements);
597 SRAM.ApplyToFields(DD);
599 // Set the globals initializer.
600 GV->setInitializer(ConstantStruct::get(Ty, Elements));
605 /// addDescriptor - Directly connect DD with existing GV.
606 void DISerializer::addDescriptor(DebugInfoDesc *DD,
607 GlobalVariable *GV) {
608 DescGlobals[DD] = GV;
611 //===----------------------------------------------------------------------===//
613 /// Verify - Return true if the GlobalVariable appears to be a valid
614 /// serialization of a DebugInfoDesc.
615 bool DIVerifier::Verify(Value *V) {
616 return !V || Verify(getGlobalVariable(V));
618 bool DIVerifier::Verify(GlobalVariable *GV) {
620 if (!GV) return true;
622 // Check prior validity.
623 unsigned &ValiditySlot = Validity[GV];
625 // If visited before then use old state.
626 if (ValiditySlot) return ValiditySlot == Valid;
628 // Assume validity for the time being (recursion.)
629 ValiditySlot = Valid;
631 // Make sure the global is internal or link once (anchor.)
632 if (GV->getLinkage() != GlobalValue::InternalLinkage &&
633 GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
634 ValiditySlot = Invalid;
639 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
641 // Check for user defined descriptors.
642 if (Tag == DW_TAG_invalid) {
643 ValiditySlot = Valid;
648 unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
650 // Check for version mismatch.
651 if (Version != LLVMDebugVersion) {
652 ValiditySlot = Invalid;
656 // Construct an empty DebugInfoDesc.
657 DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
659 // Allow for user defined descriptors.
660 if (!DD) return true;
662 // Get the initializer constant.
663 ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
665 // Get the operand count.
666 unsigned N = CI->getNumOperands();
668 // Get the field count.
669 unsigned &CountSlot = Counts[Tag];
671 // Check the operand count to the field count
673 CTAM.ApplyToFields(DD);
674 CountSlot = CTAM.getCount();
677 // Field count must be at most equal operand count.
680 ValiditySlot = Invalid;
684 // Check each field for valid type.
685 DIVerifyVisitor VRAM(*this, GV);
686 VRAM.ApplyToFields(DD);
688 // Release empty DebugInfoDesc.
691 // If fields are not valid.
692 if (!VRAM.isValid()) {
693 ValiditySlot = Invalid;
700 /// isVerified - Return true if the specified GV has already been
701 /// verified as a debug information descriptor.
702 bool DIVerifier::isVerified(GlobalVariable *GV) {
703 unsigned &ValiditySlot = Validity[GV];
704 if (ValiditySlot) return ValiditySlot == Valid;
708 //===----------------------------------------------------------------------===//
710 DebugScope::~DebugScope() {
711 for (unsigned i = 0, e = Scopes.size(); i < e; ++i) delete Scopes[i];
712 for (unsigned i = 0, e = Variables.size(); i < e; ++i) delete Variables[i];
715 //===----------------------------------------------------------------------===//
717 MachineModuleInfo::MachineModuleInfo()
718 : ImmutablePass((intptr_t)&ID)
734 // Always emit "no personality" info
735 Personalities.push_back(NULL);
737 MachineModuleInfo::~MachineModuleInfo() {
741 /// doInitialization - Initialize the state for a new module.
743 bool MachineModuleInfo::doInitialization() {
747 /// doFinalization - Tear down the state after completion of a module.
749 bool MachineModuleInfo::doFinalization() {
753 /// BeginFunction - Begin gathering function meta information.
755 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
759 /// EndFunction - Discard function meta information.
761 void MachineModuleInfo::EndFunction() {
762 // Clean up scope information.
769 // Clean up line info.
772 // Clean up frame info.
775 // Clean up exception info.
784 /// getDescFor - Convert a Value to a debug information descriptor.
786 // FIXME - use new Value type when available.
787 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
788 return DR.Deserialize(V);
791 /// AnalyzeModule - Scan the module for global debug information.
793 void MachineModuleInfo::AnalyzeModule(Module &M) {
794 SetupCompileUnits(M);
796 // Insert functions in the llvm.used array into UsedFunctions.
797 GlobalVariable *GV = M.getGlobalVariable("llvm.used");
798 if (!GV || !GV->hasInitializer()) return;
800 // Should be an array of 'i8*'.
801 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
802 if (InitList == 0) return;
804 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
805 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
806 if (CE->getOpcode() == Instruction::BitCast)
807 if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
808 UsedFunctions.insert(F);
812 /// SetupCompileUnits - Set up the unique vector of compile units.
814 void MachineModuleInfo::SetupCompileUnits(Module &M) {
815 std::vector<void*> CUList;
817 getAnchoredDescriptors(M, &CUD, CUList);
819 for (unsigned i = 0, e = CUList.size(); i < e; i++)
820 CompileUnits.insert((CompileUnitDesc*)CUList[i]);
823 /// getCompileUnits - Return a vector of debug compile units.
825 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
829 /// getAnchoredDescriptors - Return a vector of anchored debug descriptors.
832 MachineModuleInfo::getAnchoredDescriptors(Module &M, const AnchoredDesc *Desc,
833 std::vector<void*> &AnchoredDescs) {
834 std::vector<GlobalVariable*> Globals;
835 getGlobalVariablesUsing(M, Desc->getAnchorString(), Globals);
837 for (unsigned i = 0, e = Globals.size(); i < e; ++i) {
838 GlobalVariable *GV = Globals[i];
840 // FIXME - In the short term, changes are too drastic to continue.
841 if (DebugInfoDesc::TagFromGlobal(GV) == Desc->getTag() &&
842 DebugInfoDesc::VersionFromGlobal(GV) == LLVMDebugVersion)
843 AnchoredDescs.push_back(DR.Deserialize(GV));
847 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
848 /// named GlobalVariable.
850 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
851 const std::string &RootName,
852 std::vector<GlobalVariable*> &Globals) {
853 return ::getGlobalVariablesUsing(M, RootName, Globals);
856 /// RecordSourceLine - Records location information and associates it with a
857 /// debug label. Returns a unique label ID used to generate a label and
858 /// provide correspondence to the source line list.
859 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
861 unsigned ID = NextLabelID();
862 Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
866 /// RecordSource - Register a source file with debug info. Returns an source
868 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
869 const std::string &Source) {
870 unsigned DirectoryID = Directories.insert(Directory);
871 return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
873 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
874 return RecordSource(CompileUnit->getDirectory(),
875 CompileUnit->getFileName());
878 /// RecordRegionStart - Indicate the start of a region.
880 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
881 // FIXME - need to be able to handle split scopes because of bb cloning.
882 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
883 DebugScope *Scope = getOrCreateScope(ScopeDesc);
884 unsigned ID = NextLabelID();
885 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
889 /// RecordRegionEnd - Indicate the end of a region.
891 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
892 // FIXME - need to be able to handle split scopes because of bb cloning.
893 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
894 DebugScope *Scope = getOrCreateScope(ScopeDesc);
895 unsigned ID = NextLabelID();
896 Scope->setEndLabelID(ID);
900 /// RecordVariable - Indicate the declaration of a local variable.
902 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
903 VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
904 DebugScope *Scope = getOrCreateScope(VD->getContext());
905 DebugVariable *DV = new DebugVariable(VD, FrameIndex);
906 Scope->AddVariable(DV);
909 /// getOrCreateScope - Returns the scope associated with the given descriptor.
911 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
912 DebugScope *&Slot = ScopeMap[ScopeDesc];
914 // FIXME - breaks down when the context is an inlined function.
915 DebugInfoDesc *ParentDesc = NULL;
916 if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
917 ParentDesc = Block->getContext();
919 DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
920 Slot = new DebugScope(Parent, ScopeDesc);
922 Parent->AddScope(Slot);
923 } else if (RootScope) {
924 // FIXME - Add inlined function scopes to the root so we can delete
925 // them later. Long term, handle inlined functions properly.
926 RootScope->AddScope(Slot);
928 // First function is top level function.
935 //===-EH-------------------------------------------------------------------===//
937 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
938 /// specified MachineBasicBlock.
940 MachineModuleInfo::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) {
941 unsigned N = LandingPads.size();
943 for (unsigned i = 0; i < N; ++i) {
944 LandingPadInfo &LP = LandingPads[i];
945 if (LP.LandingPadBlock == LandingPad)
949 LandingPads.push_back(LandingPadInfo(LandingPad));
950 return LandingPads[N];
953 /// addInvoke - Provide the begin and end labels of an invoke style call and
954 /// associate it with a try landing pad block.
955 void MachineModuleInfo::addInvoke(MachineBasicBlock *LandingPad,
956 unsigned BeginLabel, unsigned EndLabel) {
957 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
958 LP.BeginLabels.push_back(BeginLabel);
959 LP.EndLabels.push_back(EndLabel);
962 /// addLandingPad - Provide the label of a try LandingPad block.
964 unsigned MachineModuleInfo::addLandingPad(MachineBasicBlock *LandingPad) {
965 unsigned LandingPadLabel = NextLabelID();
966 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
967 LP.LandingPadLabel = LandingPadLabel;
968 return LandingPadLabel;
971 /// addPersonality - Provide the personality function for the exception
973 void MachineModuleInfo::addPersonality(MachineBasicBlock *LandingPad,
974 Function *Personality) {
975 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
976 LP.Personality = Personality;
978 for (unsigned i = 0, e = Personalities.size(); i < e; ++i)
979 if (Personalities[i] == Personality)
982 Personalities.push_back(Personality);
985 /// addCatchTypeInfo - Provide the catch typeinfo for a landing pad.
987 void MachineModuleInfo::addCatchTypeInfo(MachineBasicBlock *LandingPad,
988 std::vector<GlobalVariable *> &TyInfo) {
989 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
990 for (unsigned N = TyInfo.size(); N; --N)
991 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1]));
994 /// addFilterTypeInfo - Provide the filter typeinfo for a landing pad.
996 void MachineModuleInfo::addFilterTypeInfo(MachineBasicBlock *LandingPad,
997 std::vector<GlobalVariable *> &TyInfo) {
998 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
999 unsigned TyInfoSize = TyInfo.size();
1000 std::vector<unsigned> IdsInFilter(TyInfoSize);
1002 for (unsigned I = 0; I != TyInfoSize; ++I)
1003 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1005 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1008 /// addCleanup - Add a cleanup action for a landing pad.
1010 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1011 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1012 LP.TypeIds.push_back(0);
1015 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1017 void MachineModuleInfo::TidyLandingPads() {
1018 for (unsigned i = 0; i != LandingPads.size(); ) {
1019 LandingPadInfo &LandingPad = LandingPads[i];
1020 LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1022 // Special case: we *should* emit LPs with null LP MBB. This indicates
1024 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1025 LandingPads.erase(LandingPads.begin() + i);
1029 for (unsigned j = 0; j != LandingPads[i].BeginLabels.size(); ) {
1030 unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1031 unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1033 if (!BeginLabel || !EndLabel) {
1034 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1035 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1039 LandingPad.BeginLabels[j] = BeginLabel;
1040 LandingPad.EndLabels[j] = EndLabel;
1044 // Remove landing pads with no try-ranges.
1045 if (LandingPads[i].BeginLabels.empty()) {
1046 LandingPads.erase(LandingPads.begin() + i);
1050 // If there is no landing pad, ensure that the list of typeids is empty.
1051 // If the only typeid is a cleanup, this is the same as having no typeids.
1052 if (!LandingPad.LandingPadBlock ||
1053 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1054 LandingPad.TypeIds.clear();
1060 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
1062 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1063 for (unsigned i = 0, e = TypeInfos.size(); i != e; ++i)
1064 if (TypeInfos[i] == TI)
1067 TypeInfos.push_back(TI);
1068 return TypeInfos.size();
1071 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
1073 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1074 // If the new filter coincides with the tail of an existing filter, then
1075 // re-use the existing filter. Folding filters more than this requires
1076 // re-ordering filters and/or their elements - probably not worth it.
1077 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1078 E = FilterEnds.end(); I != E; ++I) {
1079 unsigned i = *I, j = TyIds.size();
1082 if (FilterIds[--i] != TyIds[--j])
1086 // The new filter coincides with range [i, end) of the existing filter.
1092 // Add the new filter.
1093 int FilterID = -(1 + FilterIds.size());
1094 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1096 for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1097 FilterIds.push_back(TyIds[I]);
1099 FilterEnds.push_back(FilterIds.size());
1100 FilterIds.push_back(0); // terminator
1104 /// getPersonality - Return the personality function for the current function.
1105 Function *MachineModuleInfo::getPersonality() const {
1106 // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1108 return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1111 /// getPersonalityIndex - Return unique index for current personality
1112 /// function. NULL personality function should always get zero index.
1113 unsigned MachineModuleInfo::getPersonalityIndex() const {
1114 const Function* Personality = NULL;
1116 // Scan landing pads. If there is at least one non-NULL personality - use it.
1117 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
1118 if (LandingPads[i].Personality) {
1119 Personality = LandingPads[i].Personality;
1123 for (unsigned i = 0, e = Personalities.size(); i < e; ++i)
1124 if (Personalities[i] == Personality)
1127 // This should never happen
1128 assert(0 && "Personality function should be set!");
1132 //===----------------------------------------------------------------------===//
1133 /// DebugLabelFolding pass - This pass prunes out redundant labels. This allows
1134 /// a info consumer to determine if the range of two labels is empty, by seeing
1135 /// if the labels map to the same reduced label.
1139 struct DebugLabelFolder : public MachineFunctionPass {
1141 DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {}
1143 virtual bool runOnMachineFunction(MachineFunction &MF);
1144 virtual const char *getPassName() const { return "Label Folder"; }
1147 char DebugLabelFolder::ID = 0;
1149 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1150 // Get machine module info.
1151 MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1152 if (!MMI) return false;
1154 // Track if change is made.
1155 bool MadeChange = false;
1156 // No prior label to begin.
1157 unsigned PriorLabel = 0;
1159 // Iterate through basic blocks.
1160 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1162 // Iterate through instructions.
1163 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1165 if (I->isDebugLabel()) {
1166 // The label ID # is always operand #0, an immediate.
1167 unsigned NextLabel = I->getOperand(0).getImm();
1169 // If there was an immediate prior label.
1171 // Remap the current label to prior label.
1172 MMI->RemapLabel(NextLabel, PriorLabel);
1173 // Delete the current label.
1175 // Indicate a change has been made.
1179 // Start a new round.
1180 PriorLabel = NextLabel;
1183 // No consecutive labels.
1194 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }