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/Analysis/ValueTracking.h"
14 #include "llvm/CodeGen/MachineFunctionPass.h"
15 #include "llvm/CodeGen/MachineFunction.h"
16 #include "llvm/CodeGen/MachineLocation.h"
17 #include "llvm/CodeGen/MachineDebugInfoDesc.h"
18 #include "llvm/Target/TargetInstrInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetOptions.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/Streams.h"
29 using namespace llvm::dwarf;
31 // Handle the Pass registration stuff necessary to use TargetData's.
32 static RegisterPass<MachineModuleInfo>
33 X("machinemoduleinfo", "Module Information");
34 char MachineModuleInfo::ID = 0;
36 //===----------------------------------------------------------------------===//
38 /// getGlobalVariablesUsing - Return all of the GlobalVariables which have the
39 /// specified value in their initializer somewhere.
41 getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
42 // Scan though value users.
43 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
44 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
45 // If the user is a GlobalVariable then add to result.
47 } else if (Constant *C = dyn_cast<Constant>(*I)) {
48 // If the user is a constant variable then scan its users
49 getGlobalVariablesUsing(C, Result);
54 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
55 /// named GlobalVariable.
57 getGlobalVariablesUsing(Module &M, const std::string &RootName,
58 std::vector<GlobalVariable*> &Result) {
59 std::vector<const Type*> FieldTypes;
60 FieldTypes.push_back(Type::Int32Ty);
61 FieldTypes.push_back(Type::Int32Ty);
63 // Get the GlobalVariable root.
64 GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
65 StructType::get(FieldTypes));
67 // If present and linkonce then scan for users.
68 if (UseRoot && UseRoot->hasLinkOnceLinkage())
69 getGlobalVariablesUsing(UseRoot, Result);
72 /// isStringValue - Return true if the given value can be coerced to a string.
74 static bool isStringValue(Value *V) {
75 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
76 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
77 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
78 return Init->isString();
80 } else if (Constant *C = dyn_cast<Constant>(V)) {
81 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
82 return isStringValue(GV);
83 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
84 if (CE->getOpcode() == Instruction::GetElementPtr) {
85 if (CE->getNumOperands() == 3 &&
86 cast<Constant>(CE->getOperand(1))->isNullValue() &&
87 isa<ConstantInt>(CE->getOperand(2))) {
88 return isStringValue(CE->getOperand(0));
96 /// getGlobalVariable - Return either a direct or cast Global value.
98 static GlobalVariable *getGlobalVariable(Value *V) {
99 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
101 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
102 if (CE->getOpcode() == Instruction::BitCast) {
103 return dyn_cast<GlobalVariable>(CE->getOperand(0));
104 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
105 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
106 if (!CE->getOperand(i)->isNullValue())
109 return dyn_cast<GlobalVariable>(CE->getOperand(0));
115 /// isGlobalVariable - Return true if the given value can be coerced to a
117 static bool isGlobalVariable(Value *V) {
118 if (isa<GlobalVariable>(V) || isa<ConstantPointerNull>(V)) {
120 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
121 if (CE->getOpcode() == Instruction::BitCast) {
122 return isa<GlobalVariable>(CE->getOperand(0));
123 } else if (CE->getOpcode() == Instruction::GetElementPtr) {
124 for (unsigned int i=1; i<CE->getNumOperands(); i++) {
125 if (!CE->getOperand(i)->isNullValue())
128 return isa<GlobalVariable>(CE->getOperand(0));
134 //===----------------------------------------------------------------------===//
136 /// ApplyToFields - Target the visitor to each field of the debug information
138 void DIVisitor::ApplyToFields(DebugInfoDesc *DD) {
139 DD->ApplyToFields(this);
144 //===----------------------------------------------------------------------===//
145 /// DICountVisitor - This DIVisitor counts all the fields in the supplied debug
146 /// the supplied DebugInfoDesc.
147 class DICountVisitor : public DIVisitor {
149 unsigned Count; // Running count of fields.
152 DICountVisitor() : DIVisitor(), Count(0) {}
155 unsigned getCount() const { return Count; }
157 /// Apply - Count each of the fields.
159 virtual void Apply(int &Field) { ++Count; }
160 virtual void Apply(unsigned &Field) { ++Count; }
161 virtual void Apply(int64_t &Field) { ++Count; }
162 virtual void Apply(uint64_t &Field) { ++Count; }
163 virtual void Apply(bool &Field) { ++Count; }
164 virtual void Apply(std::string &Field) { ++Count; }
165 virtual void Apply(DebugInfoDesc *&Field) { ++Count; }
166 virtual void Apply(GlobalVariable *&Field) { ++Count; }
167 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
172 //===----------------------------------------------------------------------===//
173 /// DIDeserializeVisitor - This DIVisitor deserializes all the fields in the
174 /// supplied DebugInfoDesc.
175 class DIDeserializeVisitor : public DIVisitor {
177 DIDeserializer &DR; // Active deserializer.
178 unsigned I; // Current operand index.
179 ConstantStruct *CI; // GlobalVariable constant initializer.
182 DIDeserializeVisitor(DIDeserializer &D, GlobalVariable *GV)
186 , CI(cast<ConstantStruct>(GV->getInitializer()))
189 /// Apply - Set the value of each of the fields.
191 virtual void Apply(int &Field) {
192 Constant *C = CI->getOperand(I++);
193 Field = cast<ConstantInt>(C)->getSExtValue();
195 virtual void Apply(unsigned &Field) {
196 Constant *C = CI->getOperand(I++);
197 Field = cast<ConstantInt>(C)->getZExtValue();
199 virtual void Apply(int64_t &Field) {
200 Constant *C = CI->getOperand(I++);
201 Field = cast<ConstantInt>(C)->getSExtValue();
203 virtual void Apply(uint64_t &Field) {
204 Constant *C = CI->getOperand(I++);
205 Field = cast<ConstantInt>(C)->getZExtValue();
207 virtual void Apply(bool &Field) {
208 Constant *C = CI->getOperand(I++);
209 Field = cast<ConstantInt>(C)->getZExtValue();
211 virtual void Apply(std::string &Field) {
212 Constant *C = CI->getOperand(I++);
213 // Fills in the string if it succeeds
214 if (!GetConstantStringInfo(C, Field))
217 virtual void Apply(DebugInfoDesc *&Field) {
218 Constant *C = CI->getOperand(I++);
219 Field = DR.Deserialize(C);
221 virtual void Apply(GlobalVariable *&Field) {
222 Constant *C = CI->getOperand(I++);
223 Field = getGlobalVariable(C);
225 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
227 Constant *C = CI->getOperand(I++);
228 GlobalVariable *GV = getGlobalVariable(C);
229 if (GV->hasInitializer()) {
230 if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
231 for (unsigned i = 0, N = CA->getNumOperands(); i < N; ++i) {
232 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
233 DebugInfoDesc *DE = DR.Deserialize(GVE);
236 } else if (GV->getInitializer()->isNullValue()) {
237 if (const ArrayType *T =
238 dyn_cast<ArrayType>(GV->getType()->getElementType())) {
239 Field.resize(T->getNumElements());
246 //===----------------------------------------------------------------------===//
247 /// DISerializeVisitor - This DIVisitor serializes all the fields in
248 /// the supplied DebugInfoDesc.
249 class DISerializeVisitor : public DIVisitor {
251 DISerializer &SR; // Active serializer.
252 std::vector<Constant*> &Elements; // Element accumulator.
255 DISerializeVisitor(DISerializer &S, std::vector<Constant*> &E)
261 /// Apply - Set the value of each of the fields.
263 virtual void Apply(int &Field) {
264 Elements.push_back(ConstantInt::get(Type::Int32Ty, int32_t(Field)));
266 virtual void Apply(unsigned &Field) {
267 Elements.push_back(ConstantInt::get(Type::Int32Ty, uint32_t(Field)));
269 virtual void Apply(int64_t &Field) {
270 Elements.push_back(ConstantInt::get(Type::Int64Ty, int64_t(Field)));
272 virtual void Apply(uint64_t &Field) {
273 Elements.push_back(ConstantInt::get(Type::Int64Ty, uint64_t(Field)));
275 virtual void Apply(bool &Field) {
276 Elements.push_back(ConstantInt::get(Type::Int1Ty, Field));
278 virtual void Apply(std::string &Field) {
279 Elements.push_back(SR.getString(Field));
281 virtual void Apply(DebugInfoDesc *&Field) {
282 GlobalVariable *GV = NULL;
284 // If non-NULL then convert to global.
285 if (Field) GV = SR.Serialize(Field);
287 // FIXME - At some point should use specific type.
288 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
291 // Set to pointer to global.
292 Elements.push_back(ConstantExpr::getBitCast(GV, EmptyTy));
295 Elements.push_back(ConstantPointerNull::get(EmptyTy));
298 virtual void Apply(GlobalVariable *&Field) {
299 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
301 Elements.push_back(ConstantExpr::getBitCast(Field, EmptyTy));
303 Elements.push_back(ConstantPointerNull::get(EmptyTy));
306 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
307 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
308 unsigned N = Field.size();
309 ArrayType *AT = ArrayType::get(EmptyTy, N);
310 std::vector<Constant *> ArrayElements;
312 for (unsigned i = 0, N = Field.size(); i < N; ++i) {
313 if (DebugInfoDesc *Element = Field[i]) {
314 GlobalVariable *GVE = SR.Serialize(Element);
315 Constant *CE = ConstantExpr::getBitCast(GVE, EmptyTy);
316 ArrayElements.push_back(cast<Constant>(CE));
318 ArrayElements.push_back(ConstantPointerNull::get(EmptyTy));
322 Constant *CA = ConstantArray::get(AT, ArrayElements);
323 GlobalVariable *CAGV = new GlobalVariable(AT, true,
324 GlobalValue::InternalLinkage,
325 CA, "llvm.dbg.array",
327 CAGV->setSection("llvm.metadata");
328 Constant *CAE = ConstantExpr::getBitCast(CAGV, EmptyTy);
329 Elements.push_back(CAE);
333 //===----------------------------------------------------------------------===//
334 /// DIGetTypesVisitor - This DIVisitor gathers all the field types in
335 /// the supplied DebugInfoDesc.
336 class DIGetTypesVisitor : public DIVisitor {
338 DISerializer &SR; // Active serializer.
339 std::vector<const Type*> &Fields; // Type accumulator.
342 DIGetTypesVisitor(DISerializer &S, std::vector<const Type*> &F)
348 /// Apply - Set the value of each of the fields.
350 virtual void Apply(int &Field) {
351 Fields.push_back(Type::Int32Ty);
353 virtual void Apply(unsigned &Field) {
354 Fields.push_back(Type::Int32Ty);
356 virtual void Apply(int64_t &Field) {
357 Fields.push_back(Type::Int64Ty);
359 virtual void Apply(uint64_t &Field) {
360 Fields.push_back(Type::Int64Ty);
362 virtual void Apply(bool &Field) {
363 Fields.push_back(Type::Int1Ty);
365 virtual void Apply(std::string &Field) {
366 Fields.push_back(SR.getStrPtrType());
368 virtual void Apply(DebugInfoDesc *&Field) {
369 // FIXME - At some point should use specific type.
370 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
371 Fields.push_back(EmptyTy);
373 virtual void Apply(GlobalVariable *&Field) {
374 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
375 Fields.push_back(EmptyTy);
377 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
378 const PointerType *EmptyTy = SR.getEmptyStructPtrType();
379 Fields.push_back(EmptyTy);
383 //===----------------------------------------------------------------------===//
384 /// DIVerifyVisitor - This DIVisitor verifies all the field types against
385 /// a constant initializer.
386 class DIVerifyVisitor : public DIVisitor {
388 DIVerifier &VR; // Active verifier.
389 bool IsValid; // Validity status.
390 unsigned I; // Current operand index.
391 ConstantStruct *CI; // GlobalVariable constant initializer.
394 DIVerifyVisitor(DIVerifier &V, GlobalVariable *GV)
399 , CI(cast<ConstantStruct>(GV->getInitializer()))
404 bool isValid() const { return IsValid; }
406 /// Apply - Set the value of each of the fields.
408 virtual void Apply(int &Field) {
409 Constant *C = CI->getOperand(I++);
410 IsValid = IsValid && isa<ConstantInt>(C);
412 virtual void Apply(unsigned &Field) {
413 Constant *C = CI->getOperand(I++);
414 IsValid = IsValid && isa<ConstantInt>(C);
416 virtual void Apply(int64_t &Field) {
417 Constant *C = CI->getOperand(I++);
418 IsValid = IsValid && isa<ConstantInt>(C);
420 virtual void Apply(uint64_t &Field) {
421 Constant *C = CI->getOperand(I++);
422 IsValid = IsValid && isa<ConstantInt>(C);
424 virtual void Apply(bool &Field) {
425 Constant *C = CI->getOperand(I++);
426 IsValid = IsValid && isa<ConstantInt>(C) && C->getType() == Type::Int1Ty;
428 virtual void Apply(std::string &Field) {
429 Constant *C = CI->getOperand(I++);
431 (!C || isStringValue(C) || C->isNullValue());
433 virtual void Apply(DebugInfoDesc *&Field) {
434 // FIXME - Prepare the correct descriptor.
435 Constant *C = CI->getOperand(I++);
436 IsValid = IsValid && isGlobalVariable(C);
438 virtual void Apply(GlobalVariable *&Field) {
439 Constant *C = CI->getOperand(I++);
440 IsValid = IsValid && isGlobalVariable(C);
442 virtual void Apply(std::vector<DebugInfoDesc *> &Field) {
443 Constant *C = CI->getOperand(I++);
444 IsValid = IsValid && isGlobalVariable(C);
445 if (!IsValid) return;
447 GlobalVariable *GV = getGlobalVariable(C);
448 IsValid = IsValid && GV && GV->hasInitializer();
449 if (!IsValid) return;
451 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
452 IsValid = IsValid && CA;
453 if (!IsValid) return;
455 for (unsigned i = 0, N = CA->getNumOperands(); IsValid && i < N; ++i) {
456 IsValid = IsValid && isGlobalVariable(CA->getOperand(i));
457 if (!IsValid) return;
459 GlobalVariable *GVE = getGlobalVariable(CA->getOperand(i));
467 //===----------------------------------------------------------------------===//
469 DebugInfoDesc *DIDeserializer::Deserialize(Value *V) {
470 return Deserialize(getGlobalVariable(V));
472 DebugInfoDesc *DIDeserializer::Deserialize(GlobalVariable *GV) {
474 if (!GV) return NULL;
476 // Check to see if it has been already deserialized.
477 DebugInfoDesc *&Slot = GlobalDescs[GV];
478 if (Slot) return Slot;
480 // Get the Tag from the global.
481 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
483 // Create an empty instance of the correct sort.
484 Slot = DebugInfoDesc::DescFactory(Tag);
486 // If not a user defined descriptor.
488 // Deserialize the fields.
489 DIDeserializeVisitor DRAM(*this, GV);
490 DRAM.ApplyToFields(Slot);
496 //===----------------------------------------------------------------------===//
498 /// getStrPtrType - Return a "sbyte *" type.
500 const PointerType *DISerializer::getStrPtrType() {
501 // If not already defined.
503 // Construct the pointer to signed bytes.
504 StrPtrTy = PointerType::getUnqual(Type::Int8Ty);
510 /// getEmptyStructPtrType - Return a "{ }*" type.
512 const PointerType *DISerializer::getEmptyStructPtrType() {
513 // If not already defined.
514 if (!EmptyStructPtrTy) {
515 // Construct the empty structure type.
516 const StructType *EmptyStructTy =
517 StructType::get(std::vector<const Type*>());
518 // Construct the pointer to empty structure type.
519 EmptyStructPtrTy = PointerType::getUnqual(EmptyStructTy);
522 return EmptyStructPtrTy;
525 /// getTagType - Return the type describing the specified descriptor (via tag.)
527 const StructType *DISerializer::getTagType(DebugInfoDesc *DD) {
528 // Attempt to get the previously defined type.
529 StructType *&Ty = TagTypes[DD->getTag()];
531 // If not already defined.
533 // Set up fields vector.
534 std::vector<const Type*> Fields;
535 // Get types of fields.
536 DIGetTypesVisitor GTAM(*this, Fields);
537 GTAM.ApplyToFields(DD);
539 // Construct structured type.
540 Ty = StructType::get(Fields);
542 // Register type name with module.
543 M->addTypeName(DD->getTypeString(), Ty);
549 /// getString - Construct the string as constant string global.
551 Constant *DISerializer::getString(const std::string &String) {
552 // Check string cache for previous edition.
553 Constant *&Slot = StringCache[String];
554 // Return Constant if previously defined.
555 if (Slot) return Slot;
556 // If empty string then use a sbyte* null instead.
557 if (String.empty()) {
558 Slot = ConstantPointerNull::get(getStrPtrType());
560 // Construct string as an llvm constant.
561 Constant *ConstStr = ConstantArray::get(String);
562 // Otherwise create and return a new string global.
563 GlobalVariable *StrGV = new GlobalVariable(ConstStr->getType(), true,
564 GlobalVariable::InternalLinkage,
565 ConstStr, ".str", M);
566 StrGV->setSection("llvm.metadata");
567 // Convert to generic string pointer.
568 Slot = ConstantExpr::getBitCast(StrGV, getStrPtrType());
574 /// Serialize - Recursively cast the specified descriptor into a GlobalVariable
575 /// so that it can be serialized to a .bc or .ll file.
576 GlobalVariable *DISerializer::Serialize(DebugInfoDesc *DD) {
577 // Check if the DebugInfoDesc is already in the map.
578 GlobalVariable *&Slot = DescGlobals[DD];
580 // See if DebugInfoDesc exists, if so return prior GlobalVariable.
581 if (Slot) return Slot;
583 // Get the type associated with the Tag.
584 const StructType *Ty = getTagType(DD);
586 // Create the GlobalVariable early to prevent infinite recursion.
587 GlobalVariable *GV = new GlobalVariable(Ty, true, DD->getLinkage(),
588 NULL, DD->getDescString(), M);
589 GV->setSection("llvm.metadata");
591 // Insert new GlobalVariable in DescGlobals map.
594 // Set up elements vector
595 std::vector<Constant*> Elements;
597 DISerializeVisitor SRAM(*this, Elements);
598 SRAM.ApplyToFields(DD);
600 // Set the globals initializer.
601 GV->setInitializer(ConstantStruct::get(Ty, Elements));
606 /// addDescriptor - Directly connect DD with existing GV.
607 void DISerializer::addDescriptor(DebugInfoDesc *DD,
608 GlobalVariable *GV) {
609 DescGlobals[DD] = GV;
612 //===----------------------------------------------------------------------===//
614 /// Verify - Return true if the GlobalVariable appears to be a valid
615 /// serialization of a DebugInfoDesc.
616 bool DIVerifier::Verify(Value *V) {
617 return !V || Verify(getGlobalVariable(V));
619 bool DIVerifier::Verify(GlobalVariable *GV) {
621 if (!GV) return true;
623 // Check prior validity.
624 unsigned &ValiditySlot = Validity[GV];
626 // If visited before then use old state.
627 if (ValiditySlot) return ValiditySlot == Valid;
629 // Assume validity for the time being (recursion.)
630 ValiditySlot = Valid;
632 // Make sure the global is internal or link once (anchor.)
633 if (GV->getLinkage() != GlobalValue::InternalLinkage &&
634 GV->getLinkage() != GlobalValue::LinkOnceLinkage) {
635 ValiditySlot = Invalid;
640 unsigned Tag = DebugInfoDesc::TagFromGlobal(GV);
642 // Check for user defined descriptors.
643 if (Tag == DW_TAG_invalid) {
644 ValiditySlot = Valid;
649 unsigned Version = DebugInfoDesc::VersionFromGlobal(GV);
651 // Check for version mismatch.
652 if (Version != LLVMDebugVersion) {
653 ValiditySlot = Invalid;
657 // Construct an empty DebugInfoDesc.
658 DebugInfoDesc *DD = DebugInfoDesc::DescFactory(Tag);
660 // Allow for user defined descriptors.
661 if (!DD) return true;
663 // Get the initializer constant.
664 ConstantStruct *CI = cast<ConstantStruct>(GV->getInitializer());
666 // Get the operand count.
667 unsigned N = CI->getNumOperands();
669 // Get the field count.
670 unsigned &CountSlot = Counts[Tag];
672 // Check the operand count to the field count
674 CTAM.ApplyToFields(DD);
675 CountSlot = CTAM.getCount();
678 // Field count must be at most equal operand count.
681 ValiditySlot = Invalid;
685 // Check each field for valid type.
686 DIVerifyVisitor VRAM(*this, GV);
687 VRAM.ApplyToFields(DD);
689 // Release empty DebugInfoDesc.
692 // If fields are not valid.
693 if (!VRAM.isValid()) {
694 ValiditySlot = Invalid;
701 /// isVerified - Return true if the specified GV has already been
702 /// verified as a debug information descriptor.
703 bool DIVerifier::isVerified(GlobalVariable *GV) {
704 unsigned &ValiditySlot = Validity[GV];
705 if (ValiditySlot) return ValiditySlot == Valid;
709 //===----------------------------------------------------------------------===//
711 DebugScope::~DebugScope() {
712 for (unsigned i = 0, N = Scopes.size(); i < N; ++i) delete Scopes[i];
713 for (unsigned j = 0, M = Variables.size(); j < M; ++j) delete Variables[j];
716 //===----------------------------------------------------------------------===//
718 MachineModuleInfo::MachineModuleInfo()
719 : ImmutablePass((intptr_t)&ID)
735 // Always emit "no personality" info
736 Personalities.push_back(NULL);
738 MachineModuleInfo::~MachineModuleInfo() {
742 /// doInitialization - Initialize the state for a new module.
744 bool MachineModuleInfo::doInitialization() {
748 /// doFinalization - Tear down the state after completion of a module.
750 bool MachineModuleInfo::doFinalization() {
754 /// BeginFunction - Begin gathering function meta information.
756 void MachineModuleInfo::BeginFunction(MachineFunction *MF) {
760 /// EndFunction - Discard function meta information.
762 void MachineModuleInfo::EndFunction() {
763 // Clean up scope information.
770 // Clean up line info.
773 // Clean up frame info.
776 // Clean up exception info.
785 /// getDescFor - Convert a Value to a debug information descriptor.
787 // FIXME - use new Value type when available.
788 DebugInfoDesc *MachineModuleInfo::getDescFor(Value *V) {
789 return DR.Deserialize(V);
792 /// AnalyzeModule - Scan the module for global debug information.
794 void MachineModuleInfo::AnalyzeModule(Module &M) {
795 SetupCompileUnits(M);
797 // Insert functions in the llvm.used array into UsedFunctions.
798 GlobalVariable *GV = M.getGlobalVariable("llvm.used");
799 if (!GV || !GV->hasInitializer()) return;
801 // Should be an array of 'i8*'.
802 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
803 if (InitList == 0) return;
805 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
806 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InitList->getOperand(i)))
807 if (CE->getOpcode() == Instruction::BitCast)
808 if (Function *F = dyn_cast<Function>(CE->getOperand(0)))
809 UsedFunctions.insert(F);
813 /// SetupCompileUnits - Set up the unique vector of compile units.
815 void MachineModuleInfo::SetupCompileUnits(Module &M) {
816 std::vector<void*> CUList;
818 getAnchoredDescriptors(M, &CUD, CUList);
820 for (unsigned i = 0, N = CUList.size(); i < N; i++)
821 CompileUnits.insert((CompileUnitDesc*)CUList[i]);
824 /// getCompileUnits - Return a vector of debug compile units.
826 const UniqueVector<CompileUnitDesc *> MachineModuleInfo::getCompileUnits()const{
830 /// getAnchoredDescriptors - Return a vector of anchored debug descriptors.
833 MachineModuleInfo::getAnchoredDescriptors(Module &M, const AnchoredDesc *Desc,
834 std::vector<void*> &AnchoredDescs) {
835 std::vector<GlobalVariable*> Globals;
836 getGlobalVariablesUsing(M, Desc->getAnchorString(), Globals);
838 for (unsigned i = 0, N = Globals.size(); i < N; ++i) {
839 GlobalVariable *GV = Globals[i];
841 // FIXME - In the short term, changes are too drastic to continue.
842 if (DebugInfoDesc::TagFromGlobal(GV) == Desc->getTag() &&
843 DebugInfoDesc::VersionFromGlobal(GV) == LLVMDebugVersion)
844 AnchoredDescs.push_back(DR.Deserialize(GV));
848 /// getGlobalVariablesUsing - Return all of the GlobalVariables that use the
849 /// named GlobalVariable.
851 MachineModuleInfo::getGlobalVariablesUsing(Module &M,
852 const std::string &RootName,
853 std::vector<GlobalVariable*> &Globals) {
854 return ::getGlobalVariablesUsing(M, RootName, Globals);
857 /// RecordSourceLine - Records location information and associates it with a
858 /// debug label. Returns a unique label ID used to generate a label and
859 /// provide correspondence to the source line list.
860 unsigned MachineModuleInfo::RecordSourceLine(unsigned Line, unsigned Column,
862 unsigned ID = NextLabelID();
863 Lines.push_back(SourceLineInfo(Line, Column, Source, ID));
867 /// RecordSource - Register a source file with debug info. Returns an source
869 unsigned MachineModuleInfo::RecordSource(const std::string &Directory,
870 const std::string &Source) {
871 unsigned DirectoryID = Directories.insert(Directory);
872 return SourceFiles.insert(SourceFileInfo(DirectoryID, Source));
874 unsigned MachineModuleInfo::RecordSource(const CompileUnitDesc *CompileUnit) {
875 return RecordSource(CompileUnit->getDirectory(),
876 CompileUnit->getFileName());
879 /// RecordRegionStart - Indicate the start of a region.
881 unsigned MachineModuleInfo::RecordRegionStart(Value *V) {
882 // FIXME - need to be able to handle split scopes because of bb cloning.
883 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
884 DebugScope *Scope = getOrCreateScope(ScopeDesc);
885 unsigned ID = NextLabelID();
886 if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
890 /// RecordRegionEnd - Indicate the end of a region.
892 unsigned MachineModuleInfo::RecordRegionEnd(Value *V) {
893 // FIXME - need to be able to handle split scopes because of bb cloning.
894 DebugInfoDesc *ScopeDesc = DR.Deserialize(V);
895 DebugScope *Scope = getOrCreateScope(ScopeDesc);
896 unsigned ID = NextLabelID();
897 Scope->setEndLabelID(ID);
901 /// RecordVariable - Indicate the declaration of a local variable.
903 void MachineModuleInfo::RecordVariable(GlobalValue *GV, unsigned FrameIndex) {
904 VariableDesc *VD = cast<VariableDesc>(DR.Deserialize(GV));
905 DebugScope *Scope = getOrCreateScope(VD->getContext());
906 DebugVariable *DV = new DebugVariable(VD, FrameIndex);
907 Scope->AddVariable(DV);
910 /// getOrCreateScope - Returns the scope associated with the given descriptor.
912 DebugScope *MachineModuleInfo::getOrCreateScope(DebugInfoDesc *ScopeDesc) {
913 DebugScope *&Slot = ScopeMap[ScopeDesc];
915 // FIXME - breaks down when the context is an inlined function.
916 DebugInfoDesc *ParentDesc = NULL;
917 if (BlockDesc *Block = dyn_cast<BlockDesc>(ScopeDesc)) {
918 ParentDesc = Block->getContext();
920 DebugScope *Parent = ParentDesc ? getOrCreateScope(ParentDesc) : NULL;
921 Slot = new DebugScope(Parent, ScopeDesc);
923 Parent->AddScope(Slot);
924 } else if (RootScope) {
925 // FIXME - Add inlined function scopes to the root so we can delete
926 // them later. Long term, handle inlined functions properly.
927 RootScope->AddScope(Slot);
929 // First function is top level function.
936 //===-EH-------------------------------------------------------------------===//
938 /// getOrCreateLandingPadInfo - Find or create an LandingPadInfo for the
939 /// specified MachineBasicBlock.
940 LandingPadInfo &MachineModuleInfo::getOrCreateLandingPadInfo
941 (MachineBasicBlock *LandingPad) {
942 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; i < Personalities.size(); ++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 std::vector<unsigned> IdsInFilter (TyInfo.size());
1000 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I)
1001 IdsInFilter[I] = getTypeIDFor(TyInfo[I]);
1002 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter));
1005 /// addCleanup - Add a cleanup action for a landing pad.
1007 void MachineModuleInfo::addCleanup(MachineBasicBlock *LandingPad) {
1008 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad);
1009 LP.TypeIds.push_back(0);
1012 /// TidyLandingPads - Remap landing pad labels and remove any deleted landing
1014 void MachineModuleInfo::TidyLandingPads() {
1015 for (unsigned i = 0; i != LandingPads.size(); ) {
1016 LandingPadInfo &LandingPad = LandingPads[i];
1017 LandingPad.LandingPadLabel = MappedLabel(LandingPad.LandingPadLabel);
1019 // Special case: we *should* emit LPs with null LP MBB. This indicates
1021 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) {
1022 LandingPads.erase(LandingPads.begin() + i);
1026 for (unsigned j=0; j != LandingPads[i].BeginLabels.size(); ) {
1027 unsigned BeginLabel = MappedLabel(LandingPad.BeginLabels[j]);
1028 unsigned EndLabel = MappedLabel(LandingPad.EndLabels[j]);
1030 if (!BeginLabel || !EndLabel) {
1031 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j);
1032 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j);
1036 LandingPad.BeginLabels[j] = BeginLabel;
1037 LandingPad.EndLabels[j] = EndLabel;
1041 // Remove landing pads with no try-ranges.
1042 if (LandingPads[i].BeginLabels.empty()) {
1043 LandingPads.erase(LandingPads.begin() + i);
1047 // If there is no landing pad, ensure that the list of typeids is empty.
1048 // If the only typeid is a cleanup, this is the same as having no typeids.
1049 if (!LandingPad.LandingPadBlock ||
1050 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0]))
1051 LandingPad.TypeIds.clear();
1057 /// getTypeIDFor - Return the type id for the specified typeinfo. This is
1059 unsigned MachineModuleInfo::getTypeIDFor(GlobalVariable *TI) {
1060 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i)
1061 if (TypeInfos[i] == TI) return i + 1;
1063 TypeInfos.push_back(TI);
1064 return TypeInfos.size();
1067 /// getFilterIDFor - Return the filter id for the specified typeinfos. This is
1069 int MachineModuleInfo::getFilterIDFor(std::vector<unsigned> &TyIds) {
1070 // If the new filter coincides with the tail of an existing filter, then
1071 // re-use the existing filter. Folding filters more than this requires
1072 // re-ordering filters and/or their elements - probably not worth it.
1073 for (std::vector<unsigned>::iterator I = FilterEnds.begin(),
1074 E = FilterEnds.end(); I != E; ++I) {
1075 unsigned i = *I, j = TyIds.size();
1078 if (FilterIds[--i] != TyIds[--j])
1082 // The new filter coincides with range [i, end) of the existing filter.
1088 // Add the new filter.
1089 int FilterID = -(1 + FilterIds.size());
1090 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1);
1091 for (unsigned I = 0, N = TyIds.size(); I != N; ++I)
1092 FilterIds.push_back(TyIds[I]);
1093 FilterEnds.push_back(FilterIds.size());
1094 FilterIds.push_back(0); // terminator
1098 /// getPersonality - Return the personality function for the current function.
1099 Function *MachineModuleInfo::getPersonality() const {
1100 // FIXME: Until PR1414 will be fixed, we're using 1 personality function per
1102 return !LandingPads.empty() ? LandingPads[0].Personality : NULL;
1105 /// getPersonalityIndex - Return unique index for current personality
1106 /// function. NULL personality function should always get zero index.
1107 unsigned MachineModuleInfo::getPersonalityIndex() const {
1108 const Function* Personality = NULL;
1110 // Scan landing pads. If there is at least one non-NULL personality - use it.
1111 for (unsigned i = 0; i != LandingPads.size(); ++i)
1112 if (LandingPads[i].Personality) {
1113 Personality = LandingPads[i].Personality;
1117 for (unsigned i = 0; i < Personalities.size(); ++i) {
1118 if (Personalities[i] == Personality)
1122 // This should never happen
1123 assert(0 && "Personality function should be set!");
1127 //===----------------------------------------------------------------------===//
1128 /// DebugLabelFolding pass - This pass prunes out redundant labels. This allows
1129 /// a info consumer to determine if the range of two labels is empty, by seeing
1130 /// if the labels map to the same reduced label.
1134 struct DebugLabelFolder : public MachineFunctionPass {
1136 DebugLabelFolder() : MachineFunctionPass((intptr_t)&ID) {}
1138 virtual bool runOnMachineFunction(MachineFunction &MF);
1139 virtual const char *getPassName() const { return "Label Folder"; }
1142 char DebugLabelFolder::ID = 0;
1144 bool DebugLabelFolder::runOnMachineFunction(MachineFunction &MF) {
1145 // Get machine module info.
1146 MachineModuleInfo *MMI = getAnalysisToUpdate<MachineModuleInfo>();
1147 if (!MMI) return false;
1149 // Track if change is made.
1150 bool MadeChange = false;
1151 // No prior label to begin.
1152 unsigned PriorLabel = 0;
1154 // Iterate through basic blocks.
1155 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
1157 // Iterate through instructions.
1158 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1160 if (I->isDebugLabel()) {
1161 // The label ID # is always operand #0, an immediate.
1162 unsigned NextLabel = I->getOperand(0).getImm();
1164 // If there was an immediate prior label.
1166 // Remap the current label to prior label.
1167 MMI->RemapLabel(NextLabel, PriorLabel);
1168 // Delete the current label.
1170 // Indicate a change has been made.
1174 // Start a new round.
1175 PriorLabel = NextLabel;
1178 // No consecutive labels.
1189 FunctionPass *createDebugLabelFoldingPass() { return new DebugLabelFolder(); }