LLVM  mainline
DebugInfo.cpp
Go to the documentation of this file.
00001 //===--- DebugInfo.cpp - Debug Information Helper Classes -----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the helper classes used to build and interpret debug
00011 // information in LLVM IR form.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/IR/DebugInfo.h"
00016 #include "LLVMContextImpl.h"
00017 #include "llvm/ADT/STLExtras.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/StringSwitch.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/IR/Constants.h"
00023 #include "llvm/IR/DIBuilder.h"
00024 #include "llvm/IR/DerivedTypes.h"
00025 #include "llvm/IR/Instructions.h"
00026 #include "llvm/IR/IntrinsicInst.h"
00027 #include "llvm/IR/Intrinsics.h"
00028 #include "llvm/IR/Module.h"
00029 #include "llvm/IR/ValueHandle.h"
00030 #include "llvm/Support/Debug.h"
00031 #include "llvm/Support/Dwarf.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 using namespace llvm;
00034 using namespace llvm::dwarf;
00035 
00036 //===----------------------------------------------------------------------===//
00037 // DIDescriptor
00038 //===----------------------------------------------------------------------===//
00039 
00040 unsigned DIDescriptor::getFlag(StringRef Flag) {
00041   return StringSwitch<unsigned>(Flag)
00042 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
00043 #include "llvm/IR/DebugInfoFlags.def"
00044       .Default(0);
00045 }
00046 
00047 const char *DIDescriptor::getFlagString(unsigned Flag) {
00048   switch (Flag) {
00049   default:
00050     return "";
00051 #define HANDLE_DI_FLAG(ID, NAME)                                               \
00052   case Flag##NAME:                                                             \
00053     return "DIFlag" #NAME;
00054 #include "llvm/IR/DebugInfoFlags.def"
00055   }
00056 }
00057 
00058 unsigned DIDescriptor::splitFlags(unsigned Flags,
00059                                   SmallVectorImpl<unsigned> &SplitFlags) {
00060   // Accessibility flags need to be specially handled, since they're packed
00061   // together.
00062   if (unsigned A = Flags & FlagAccessibility) {
00063     if (A == FlagPrivate)
00064       SplitFlags.push_back(FlagPrivate);
00065     else if (A == FlagProtected)
00066       SplitFlags.push_back(FlagProtected);
00067     else
00068       SplitFlags.push_back(FlagPublic);
00069     Flags &= ~A;
00070   }
00071 
00072 #define HANDLE_DI_FLAG(ID, NAME)                                               \
00073   if (unsigned Bit = Flags & ID) {                                             \
00074     SplitFlags.push_back(Bit);                                                 \
00075     Flags &= ~Bit;                                                             \
00076   }
00077 #include "llvm/IR/DebugInfoFlags.def"
00078 
00079   return Flags;
00080 }
00081 
00082 bool DIDescriptor::Verify() const {
00083   return DbgNode &&
00084          (DIDerivedType(DbgNode).Verify() ||
00085           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
00086           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
00087           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
00088           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
00089           DILexicalBlock(DbgNode).Verify() ||
00090           DILexicalBlockFile(DbgNode).Verify() ||
00091           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
00092           DIObjCProperty(DbgNode).Verify() ||
00093           DITemplateTypeParameter(DbgNode).Verify() ||
00094           DITemplateValueParameter(DbgNode).Verify() ||
00095           DIImportedEntity(DbgNode).Verify());
00096 }
00097 
00098 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
00099   if (!DbgNode || Elt >= DbgNode->getNumOperands())
00100     return nullptr;
00101   return DbgNode->getOperand(Elt);
00102 }
00103 
00104 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
00105   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
00106 }
00107 
00108 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
00109   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
00110     return MDS->getString();
00111   return StringRef();
00112 }
00113 
00114 StringRef DIDescriptor::getStringField(unsigned Elt) const {
00115   return ::getStringField(DbgNode, Elt);
00116 }
00117 
00118 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
00119   if (auto *C = getConstantField(Elt))
00120     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00121       return CI->getZExtValue();
00122 
00123   return 0;
00124 }
00125 
00126 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
00127   if (auto *C = getConstantField(Elt))
00128     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00129       return CI->getZExtValue();
00130 
00131   return 0;
00132 }
00133 
00134 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
00135   MDNode *Field = getNodeField(DbgNode, Elt);
00136   return DIDescriptor(Field);
00137 }
00138 
00139 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
00140   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
00141 }
00142 
00143 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
00144   if (!DbgNode)
00145     return nullptr;
00146 
00147   if (Elt < DbgNode->getNumOperands())
00148     if (auto *C =
00149             dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
00150       return C->getValue();
00151   return nullptr;
00152 }
00153 
00154 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
00155   return dyn_cast_or_null<Function>(getConstantField(Elt));
00156 }
00157 
00158 /// \brief Return the size reported by the variable's type.
00159 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
00160   DIType Ty = getType().resolve(Map);
00161   // Follow derived types until we reach a type that
00162   // reports back a size.
00163   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
00164     DIDerivedType DT(&*Ty);
00165     Ty = DT.getTypeDerivedFrom().resolve(Map);
00166   }
00167   assert(Ty.getSizeInBits() && "type with size 0");
00168   return Ty.getSizeInBits();
00169 }
00170 
00171 bool DIExpression::isBitPiece() const {
00172   unsigned N = getNumElements();
00173   return N >=3 && getElement(N-3) == dwarf::DW_OP_bit_piece;
00174 }
00175 
00176 uint64_t DIExpression::getBitPieceOffset() const {
00177   assert(isBitPiece() && "not a piece");
00178   return getElement(getNumElements()-2);
00179 }
00180 
00181 uint64_t DIExpression::getBitPieceSize() const {
00182   assert(isBitPiece() && "not a piece");
00183   return getElement(getNumElements()-1);
00184 }
00185 
00186 DIExpression::iterator DIExpression::Operand::getNext() const {
00187   iterator it(I);
00188   return ++it;
00189 }
00190 
00191 //===----------------------------------------------------------------------===//
00192 // Simple Descriptor Constructors and other Methods
00193 //===----------------------------------------------------------------------===//
00194 
00195 void DIDescriptor::replaceAllUsesWith(LLVMContext &, DIDescriptor D) {
00196   assert(DbgNode && "Trying to replace an unverified type!");
00197   assert(DbgNode->isTemporary() && "Expected temporary node");
00198   TempMDNode Temp(get());
00199 
00200   // Since we use a TrackingVH for the node, its easy for clients to manufacture
00201   // legitimate situations where they want to replaceAllUsesWith() on something
00202   // which, due to uniquing, has merged with the source. We shield clients from
00203   // this detail by allowing a value to be replaced with replaceAllUsesWith()
00204   // itself.
00205   if (Temp.get() == D.get()) {
00206     DbgNode = MDNode::replaceWithUniqued(std::move(Temp));
00207     return;
00208   }
00209 
00210   Temp->replaceAllUsesWith(D.get());
00211   DbgNode = D.get();
00212 }
00213 
00214 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
00215   assert(DbgNode && "Trying to replace an unverified type!");
00216   assert(DbgNode != D && "This replacement should always happen");
00217   assert(DbgNode->isTemporary() && "Expected temporary node");
00218   TempMDNode Node(get());
00219   Node->replaceAllUsesWith(D);
00220 }
00221 
00222 bool DICompileUnit::Verify() const {
00223   if (!isCompileUnit())
00224     return false;
00225 
00226   // Don't bother verifying the compilation directory or producer string
00227   // as those could be empty.
00228   return !getFilename().empty();
00229 }
00230 
00231 bool DIObjCProperty::Verify() const { return isObjCProperty(); }
00232 
00233 /// \brief Check if a value can be a reference to a type.
00234 static bool isTypeRef(const Metadata *MD) {
00235   if (!MD)
00236     return true;
00237   if (auto *S = dyn_cast<MDString>(MD))
00238     return !S->getString().empty();
00239   return isa<MDType>(MD);
00240 }
00241 
00242 /// \brief Check if a value can be a ScopeRef.
00243 static bool isScopeRef(const Metadata *MD) {
00244   if (!MD)
00245     return true;
00246   if (auto *S = dyn_cast<MDString>(MD))
00247     return !S->getString().empty();
00248   return isa<MDScope>(MD);
00249 }
00250 
00251 #ifndef NDEBUG
00252 /// \brief Check if a value can be a DescriptorRef.
00253 static bool isDescriptorRef(const Metadata *MD) {
00254   if (!MD)
00255     return true;
00256   if (auto *S = dyn_cast<MDString>(MD))
00257     return !S->getString().empty();
00258   return isa<MDNode>(MD);
00259 }
00260 #endif
00261 
00262 bool DIType::Verify() const {
00263   auto *N = dyn_cast_or_null<MDType>(DbgNode);
00264   if (!N)
00265     return false;
00266   if (!isScopeRef(N->getScope()))
00267     return false;
00268 
00269   // DIType is abstract, it should be a BasicType, a DerivedType or
00270   // a CompositeType.
00271   if (isBasicType())
00272     return DIBasicType(DbgNode).Verify();
00273 
00274   // FIXME: Sink this into the various subclass verifies.
00275   if (getFilename().empty()) {
00276     // Check whether the filename is allowed to be empty.
00277     uint16_t Tag = getTag();
00278     if (Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type &&
00279         Tag != dwarf::DW_TAG_pointer_type &&
00280         Tag != dwarf::DW_TAG_ptr_to_member_type &&
00281         Tag != dwarf::DW_TAG_reference_type &&
00282         Tag != dwarf::DW_TAG_rvalue_reference_type &&
00283         Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
00284         Tag != dwarf::DW_TAG_enumeration_type &&
00285         Tag != dwarf::DW_TAG_subroutine_type &&
00286         Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
00287         Tag != dwarf::DW_TAG_structure_type && Tag != dwarf::DW_TAG_member &&
00288         Tag != dwarf::DW_TAG_typedef)
00289       return false;
00290   }
00291 
00292   if (isCompositeType())
00293     return DICompositeType(DbgNode).Verify();
00294   if (isDerivedType())
00295     return DIDerivedType(DbgNode).Verify();
00296   return false;
00297 }
00298 
00299 bool DIBasicType::Verify() const {
00300   return dyn_cast_or_null<MDBasicType>(DbgNode);
00301 }
00302 
00303 bool DIDerivedType::Verify() const {
00304   auto *N = dyn_cast_or_null<MDDerivedTypeBase>(DbgNode);
00305   if (!N)
00306     return false;
00307   if (getTag() == dwarf::DW_TAG_ptr_to_member_type) {
00308     auto *D = dyn_cast<MDDerivedType>(N);
00309     if (!D)
00310       return false;
00311     if (!isTypeRef(D->getExtraData()))
00312       return false;
00313   }
00314   return isTypeRef(N->getBaseType());
00315 }
00316 
00317 bool DICompositeType::Verify() const {
00318   auto *N = dyn_cast_or_null<MDCompositeTypeBase>(DbgNode);
00319   return N && isTypeRef(N->getBaseType()) && isTypeRef(N->getVTableHolder()) &&
00320          !(isLValueReference() && isRValueReference());
00321 }
00322 
00323 bool DISubprogram::Verify() const {
00324   auto *N = dyn_cast_or_null<MDSubprogram>(DbgNode);
00325   if (!N)
00326     return false;
00327 
00328   if (!isScopeRef(N->getScope()))
00329     return false;
00330 
00331   if (auto *Op = N->getType())
00332     if (!isa<MDNode>(Op))
00333       return false;
00334 
00335   if (!isTypeRef(getContainingType()))
00336     return false;
00337 
00338   if (isLValueReference() && isRValueReference())
00339     return false;
00340 
00341   // If a DISubprogram has an llvm::Function*, then scope chains from all
00342   // instructions within the function should lead to this DISubprogram.
00343   if (auto *F = getFunction()) {
00344     for (auto &BB : *F) {
00345       for (auto &I : BB) {
00346         DebugLoc DL = I.getDebugLoc();
00347         if (DL.isUnknown())
00348           continue;
00349 
00350         MDNode *Scope = nullptr;
00351         MDNode *IA = nullptr;
00352         // walk the inlined-at scopes
00353         while ((IA = DL.getInlinedAt()))
00354           DL = DebugLoc::getFromDILocation(IA);
00355         DL.getScopeAndInlinedAt(Scope, IA);
00356         if (!Scope)
00357           return false;
00358         assert(!IA);
00359         while (!DIDescriptor(Scope).isSubprogram()) {
00360           DILexicalBlockFile D(Scope);
00361           Scope = D.isLexicalBlockFile()
00362                       ? D.getScope()
00363                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
00364           if (!Scope)
00365             return false;
00366         }
00367         if (!DISubprogram(Scope).describes(F))
00368           return false;
00369       }
00370     }
00371   }
00372 
00373   return true;
00374 }
00375 
00376 bool DIGlobalVariable::Verify() const {
00377   auto *N = dyn_cast_or_null<MDGlobalVariable>(DbgNode);
00378 
00379   if (!N)
00380     return false;
00381 
00382   if (N->getDisplayName().empty())
00383     return false;
00384 
00385   if (auto *Op = N->getScope())
00386     if (!isa<MDNode>(Op))
00387       return false;
00388 
00389   if (auto *Op = N->getStaticDataMemberDeclaration())
00390     if (!isa<MDNode>(Op))
00391       return false;
00392 
00393   return isTypeRef(N->getType());
00394 }
00395 
00396 bool DIVariable::Verify() const {
00397   auto *N = dyn_cast_or_null<MDLocalVariable>(DbgNode);
00398 
00399   if (!N)
00400     return false;
00401 
00402   if (auto *Op = N->getScope())
00403     if (!isa<MDNode>(Op))
00404       return false;
00405 
00406   return isTypeRef(N->getType());
00407 }
00408 
00409 bool DILocation::Verify() const {
00410   return dyn_cast_or_null<MDLocation>(DbgNode);
00411 }
00412 bool DINameSpace::Verify() const {
00413   return dyn_cast_or_null<MDNamespace>(DbgNode);
00414 }
00415 bool DIFile::Verify() const { return dyn_cast_or_null<MDFile>(DbgNode); }
00416 bool DIEnumerator::Verify() const {
00417   return dyn_cast_or_null<MDEnumerator>(DbgNode);
00418 }
00419 bool DISubrange::Verify() const {
00420   return dyn_cast_or_null<MDSubrange>(DbgNode);
00421 }
00422 bool DILexicalBlock::Verify() const {
00423   return dyn_cast_or_null<MDLexicalBlock>(DbgNode);
00424 }
00425 bool DILexicalBlockFile::Verify() const {
00426   return dyn_cast_or_null<MDLexicalBlockFile>(DbgNode);
00427 }
00428 bool DITemplateTypeParameter::Verify() const {
00429   return dyn_cast_or_null<MDTemplateTypeParameter>(DbgNode);
00430 }
00431 bool DITemplateValueParameter::Verify() const {
00432   return dyn_cast_or_null<MDTemplateValueParameter>(DbgNode);
00433 }
00434 bool DIImportedEntity::Verify() const {
00435   return dyn_cast_or_null<MDImportedEntity>(DbgNode);
00436 }
00437 
00438 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
00439   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
00440   if (Elements)
00441     N->replaceElements(cast<MDTuple>(Elements));
00442   if (TParams)
00443     N->replaceTemplateParams(cast<MDTuple>(TParams));
00444   DbgNode = N;
00445 }
00446 
00447 DIScopeRef DIScope::getRef() const {
00448   if (!isCompositeType())
00449     return DIScopeRef(*this);
00450   DICompositeType DTy(DbgNode);
00451   if (!DTy.getIdentifier())
00452     return DIScopeRef(*this);
00453   return DIScopeRef(DTy.getIdentifier());
00454 }
00455 
00456 void DICompositeType::setContainingType(DICompositeType ContainingType) {
00457   TypedTrackingMDRef<MDCompositeTypeBase> N(get());
00458   N->replaceVTableHolder(ContainingType.getRef());
00459   DbgNode = N;
00460 }
00461 
00462 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
00463   assert(CurFn && "Invalid function");
00464   if (!getContext().isSubprogram())
00465     return false;
00466   // This variable is not inlined function argument if its scope
00467   // does not describe current function.
00468   return !DISubprogram(getContext()).describes(CurFn);
00469 }
00470 
00471 Function *DISubprogram::getFunction() const {
00472   if (auto *N = get())
00473     if (auto *C = dyn_cast_or_null<ConstantAsMetadata>(N->getFunction()))
00474       return dyn_cast<Function>(C->getValue());
00475   return nullptr;
00476 }
00477 
00478 bool DISubprogram::describes(const Function *F) {
00479   assert(F && "Invalid function");
00480   if (F == getFunction())
00481     return true;
00482   StringRef Name = getLinkageName();
00483   if (Name.empty())
00484     Name = getName();
00485   if (F->getName() == Name)
00486     return true;
00487   return false;
00488 }
00489 
00490 GlobalVariable *DIGlobalVariable::getGlobal() const {
00491   return dyn_cast_or_null<GlobalVariable>(getConstant());
00492 }
00493 
00494 DIScopeRef DIScope::getContext() const {
00495 
00496   if (isType())
00497     return DIType(DbgNode).getContext();
00498 
00499   if (isSubprogram())
00500     return DIScopeRef(DISubprogram(DbgNode).getContext());
00501 
00502   if (isLexicalBlock())
00503     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
00504 
00505   if (isLexicalBlockFile())
00506     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
00507 
00508   if (isNameSpace())
00509     return DIScopeRef(DINameSpace(DbgNode).getContext());
00510 
00511   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
00512   return DIScopeRef(nullptr);
00513 }
00514 
00515 StringRef DIScope::getName() const {
00516   if (isType())
00517     return DIType(DbgNode).getName();
00518   if (isSubprogram())
00519     return DISubprogram(DbgNode).getName();
00520   if (isNameSpace())
00521     return DINameSpace(DbgNode).getName();
00522   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
00523           isCompileUnit()) &&
00524          "Unhandled type of scope.");
00525   return StringRef();
00526 }
00527 
00528 StringRef DIScope::getFilename() const {
00529   if (auto *N = get())
00530     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 0);
00531   return "";
00532 }
00533 
00534 StringRef DIScope::getDirectory() const {
00535   if (auto *N = get())
00536     return ::getStringField(dyn_cast_or_null<MDNode>(N->getFile()), 1);
00537   return "";
00538 }
00539 
00540 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
00541   assert(Verify() && "Expected compile unit");
00542   get()->replaceSubprograms(cast_or_null<MDTuple>(Subprograms.get()));
00543 }
00544 
00545 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
00546   assert(Verify() && "Expected compile unit");
00547   get()->replaceGlobalVariables(cast_or_null<MDTuple>(GlobalVariables.get()));
00548 }
00549 
00550 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
00551                                         DILexicalBlockFile NewScope) {
00552   assert(Verify());
00553   assert(NewScope && "Expected valid scope");
00554 
00555   const auto *Old = cast<MDLocation>(DbgNode);
00556   return DILocation(MDLocation::get(Ctx, Old->getLine(), Old->getColumn(),
00557                                     NewScope, Old->getInlinedAt()));
00558 }
00559 
00560 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
00561   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
00562   return ++Ctx.pImpl->DiscriminatorTable[Key];
00563 }
00564 
00565 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
00566                                        LLVMContext &VMContext) {
00567   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
00568   return cast<MDLocalVariable>(DV)
00569       ->withInline(cast_or_null<MDLocation>(InlinedScope));
00570 }
00571 
00572 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
00573   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
00574   return cast<MDLocalVariable>(DV)->withoutInline();
00575 }
00576 
00577 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
00578   DIDescriptor D(Scope);
00579   if (D.isSubprogram())
00580     return DISubprogram(Scope);
00581 
00582   if (D.isLexicalBlockFile())
00583     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
00584 
00585   if (D.isLexicalBlock())
00586     return getDISubprogram(DILexicalBlock(Scope).getContext());
00587 
00588   return DISubprogram();
00589 }
00590 
00591 DISubprogram llvm::getDISubprogram(const Function *F) {
00592   // We look for the first instr that has a debug annotation leading back to F.
00593   for (auto &BB : *F) {
00594     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
00595       return !Inst.getDebugLoc().isUnknown();
00596     });
00597     if (Inst == BB.end())
00598       continue;
00599     DebugLoc DLoc = Inst->getDebugLoc();
00600     const MDNode *Scope = DLoc.getScopeNode();
00601     DISubprogram Subprogram = getDISubprogram(Scope);
00602     return Subprogram.describes(F) ? Subprogram : DISubprogram();
00603   }
00604 
00605   return DISubprogram();
00606 }
00607 
00608 DICompositeType llvm::getDICompositeType(DIType T) {
00609   if (T.isCompositeType())
00610     return DICompositeType(T);
00611 
00612   if (T.isDerivedType()) {
00613     // This function is currently used by dragonegg and dragonegg does
00614     // not generate identifier for types, so using an empty map to resolve
00615     // DerivedFrom should be fine.
00616     DITypeIdentifierMap EmptyMap;
00617     return getDICompositeType(
00618         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
00619   }
00620 
00621   return DICompositeType();
00622 }
00623 
00624 DITypeIdentifierMap
00625 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
00626   DITypeIdentifierMap Map;
00627   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
00628     DICompileUnit CU(CU_Nodes->getOperand(CUi));
00629     DIArray Retain = CU.getRetainedTypes();
00630     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
00631       if (!Retain.getElement(Ti).isCompositeType())
00632         continue;
00633       DICompositeType Ty(Retain.getElement(Ti));
00634       if (MDString *TypeId = Ty.getIdentifier()) {
00635         // Definition has priority over declaration.
00636         // Try to insert (TypeId, Ty) to Map.
00637         std::pair<DITypeIdentifierMap::iterator, bool> P =
00638             Map.insert(std::make_pair(TypeId, Ty));
00639         // If TypeId already exists in Map and this is a definition, replace
00640         // whatever we had (declaration or definition) with the definition.
00641         if (!P.second && !Ty.isForwardDecl())
00642           P.first->second = Ty;
00643       }
00644     }
00645   }
00646   return Map;
00647 }
00648 
00649 //===----------------------------------------------------------------------===//
00650 // DebugInfoFinder implementations.
00651 //===----------------------------------------------------------------------===//
00652 
00653 void DebugInfoFinder::reset() {
00654   CUs.clear();
00655   SPs.clear();
00656   GVs.clear();
00657   TYs.clear();
00658   Scopes.clear();
00659   NodesSeen.clear();
00660   TypeIdentifierMap.clear();
00661   TypeMapInitialized = false;
00662 }
00663 
00664 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
00665   if (!TypeMapInitialized)
00666     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00667       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
00668       TypeMapInitialized = true;
00669     }
00670 }
00671 
00672 void DebugInfoFinder::processModule(const Module &M) {
00673   InitializeTypeMap(M);
00674   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00675     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
00676       DICompileUnit CU(CU_Nodes->getOperand(i));
00677       addCompileUnit(CU);
00678       DIArray GVs = CU.getGlobalVariables();
00679       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
00680         DIGlobalVariable DIG(GVs.getElement(i));
00681         if (addGlobalVariable(DIG)) {
00682           processScope(DIG.getContext());
00683           processType(DIG.getType().resolve(TypeIdentifierMap));
00684         }
00685       }
00686       DIArray SPs = CU.getSubprograms();
00687       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
00688         processSubprogram(DISubprogram(SPs.getElement(i)));
00689       DIArray EnumTypes = CU.getEnumTypes();
00690       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
00691         processType(DIType(EnumTypes.getElement(i)));
00692       DIArray RetainedTypes = CU.getRetainedTypes();
00693       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
00694         processType(DIType(RetainedTypes.getElement(i)));
00695       DIArray Imports = CU.getImportedEntities();
00696       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
00697         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
00698         if (!Import)
00699           continue;
00700         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
00701         if (Entity.isType())
00702           processType(DIType(Entity));
00703         else if (Entity.isSubprogram())
00704           processSubprogram(DISubprogram(Entity));
00705         else if (Entity.isNameSpace())
00706           processScope(DINameSpace(Entity).getContext());
00707       }
00708     }
00709   }
00710 }
00711 
00712 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
00713   if (!Loc)
00714     return;
00715   InitializeTypeMap(M);
00716   processScope(Loc.getScope());
00717   processLocation(M, Loc.getOrigLocation());
00718 }
00719 
00720 void DebugInfoFinder::processType(DIType DT) {
00721   if (!addType(DT))
00722     return;
00723   processScope(DT.getContext().resolve(TypeIdentifierMap));
00724   if (DT.isCompositeType()) {
00725     DICompositeType DCT(DT);
00726     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
00727     if (DT.isSubroutineType()) {
00728       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
00729       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
00730         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
00731       return;
00732     }
00733     DIArray DA = DCT.getElements();
00734     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
00735       DIDescriptor D = DA.getElement(i);
00736       if (D.isType())
00737         processType(DIType(D));
00738       else if (D.isSubprogram())
00739         processSubprogram(DISubprogram(D));
00740     }
00741   } else if (DT.isDerivedType()) {
00742     DIDerivedType DDT(DT);
00743     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
00744   }
00745 }
00746 
00747 void DebugInfoFinder::processScope(DIScope Scope) {
00748   if (Scope.isType()) {
00749     DIType Ty(Scope);
00750     processType(Ty);
00751     return;
00752   }
00753   if (Scope.isCompileUnit()) {
00754     addCompileUnit(DICompileUnit(Scope));
00755     return;
00756   }
00757   if (Scope.isSubprogram()) {
00758     processSubprogram(DISubprogram(Scope));
00759     return;
00760   }
00761   if (!addScope(Scope))
00762     return;
00763   if (Scope.isLexicalBlock()) {
00764     DILexicalBlock LB(Scope);
00765     processScope(LB.getContext());
00766   } else if (Scope.isLexicalBlockFile()) {
00767     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
00768     processScope(LBF.getScope());
00769   } else if (Scope.isNameSpace()) {
00770     DINameSpace NS(Scope);
00771     processScope(NS.getContext());
00772   }
00773 }
00774 
00775 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
00776   if (!addSubprogram(SP))
00777     return;
00778   processScope(SP.getContext().resolve(TypeIdentifierMap));
00779   processType(SP.getType());
00780   DIArray TParams = SP.getTemplateParams();
00781   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
00782     DIDescriptor Element = TParams.getElement(I);
00783     if (Element.isTemplateTypeParameter()) {
00784       DITemplateTypeParameter TType(Element);
00785       processType(TType.getType().resolve(TypeIdentifierMap));
00786     } else if (Element.isTemplateValueParameter()) {
00787       DITemplateValueParameter TVal(Element);
00788       processType(TVal.getType().resolve(TypeIdentifierMap));
00789     }
00790   }
00791 }
00792 
00793 void DebugInfoFinder::processDeclare(const Module &M,
00794                                      const DbgDeclareInst *DDI) {
00795   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
00796   if (!N)
00797     return;
00798   InitializeTypeMap(M);
00799 
00800   DIDescriptor DV(N);
00801   if (!DV.isVariable())
00802     return;
00803 
00804   if (!NodesSeen.insert(DV).second)
00805     return;
00806   processScope(DIVariable(N).getContext());
00807   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
00808 }
00809 
00810 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
00811   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
00812   if (!N)
00813     return;
00814   InitializeTypeMap(M);
00815 
00816   DIDescriptor DV(N);
00817   if (!DV.isVariable())
00818     return;
00819 
00820   if (!NodesSeen.insert(DV).second)
00821     return;
00822   processScope(DIVariable(N).getContext());
00823   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
00824 }
00825 
00826 bool DebugInfoFinder::addType(DIType DT) {
00827   if (!DT)
00828     return false;
00829 
00830   if (!NodesSeen.insert(DT).second)
00831     return false;
00832 
00833   TYs.push_back(DT);
00834   return true;
00835 }
00836 
00837 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
00838   if (!CU)
00839     return false;
00840   if (!NodesSeen.insert(CU).second)
00841     return false;
00842 
00843   CUs.push_back(CU);
00844   return true;
00845 }
00846 
00847 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
00848   if (!DIG)
00849     return false;
00850 
00851   if (!NodesSeen.insert(DIG).second)
00852     return false;
00853 
00854   GVs.push_back(DIG);
00855   return true;
00856 }
00857 
00858 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
00859   if (!SP)
00860     return false;
00861 
00862   if (!NodesSeen.insert(SP).second)
00863     return false;
00864 
00865   SPs.push_back(SP);
00866   return true;
00867 }
00868 
00869 bool DebugInfoFinder::addScope(DIScope Scope) {
00870   if (!Scope)
00871     return false;
00872   // FIXME: Ocaml binding generates a scope with no content, we treat it
00873   // as null for now.
00874   if (Scope->getNumOperands() == 0)
00875     return false;
00876   if (!NodesSeen.insert(Scope).second)
00877     return false;
00878   Scopes.push_back(Scope);
00879   return true;
00880 }
00881 
00882 //===----------------------------------------------------------------------===//
00883 // DIDescriptor: dump routines for all descriptors.
00884 //===----------------------------------------------------------------------===//
00885 
00886 void DIDescriptor::dump() const {
00887   print(dbgs());
00888   dbgs() << '\n';
00889 }
00890 
00891 void DIDescriptor::print(raw_ostream &OS) const {
00892   if (!get())
00893     return;
00894   get()->print(OS);
00895 }
00896 
00897 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
00898                           const LLVMContext &Ctx) {
00899   if (!DL.isUnknown()) { // Print source line info.
00900     DIScope Scope(DL.getScope(Ctx));
00901     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
00902     // Omit the directory, because it's likely to be long and uninteresting.
00903     CommentOS << Scope.getFilename();
00904     CommentOS << ':' << DL.getLine();
00905     if (DL.getCol() != 0)
00906       CommentOS << ':' << DL.getCol();
00907     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
00908     if (!InlinedAtDL.isUnknown()) {
00909       CommentOS << " @[ ";
00910       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
00911       CommentOS << " ]";
00912     }
00913   }
00914 }
00915 
00916 void DIVariable::printExtendedName(raw_ostream &OS) const {
00917   const LLVMContext &Ctx = DbgNode->getContext();
00918   StringRef Res = getName();
00919   if (!Res.empty())
00920     OS << Res << "," << getLineNumber();
00921   if (MDNode *InlinedAt = getInlinedAt()) {
00922     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
00923     if (!InlinedAtDL.isUnknown()) {
00924       OS << " @[";
00925       printDebugLoc(InlinedAtDL, OS, Ctx);
00926       OS << "]";
00927     }
00928   }
00929 }
00930 
00931 template <> DIRef<DIDescriptor>::DIRef(const Metadata *V) : Val(V) {
00932   assert(isDescriptorRef(V) &&
00933          "DIDescriptorRef should be a MDString or MDNode");
00934 }
00935 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
00936   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
00937 }
00938 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
00939   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
00940 }
00941 
00942 template <>
00943 DIDescriptorRef DIDescriptor::getFieldAs<DIDescriptorRef>(unsigned Elt) const {
00944   return DIDescriptorRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
00945 }
00946 template <>
00947 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
00948   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
00949 }
00950 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
00951   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
00952 }
00953 
00954 bool llvm::StripDebugInfo(Module &M) {
00955   bool Changed = false;
00956 
00957   // Remove all of the calls to the debugger intrinsics, and remove them from
00958   // the module.
00959   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
00960     while (!Declare->use_empty()) {
00961       CallInst *CI = cast<CallInst>(Declare->user_back());
00962       CI->eraseFromParent();
00963     }
00964     Declare->eraseFromParent();
00965     Changed = true;
00966   }
00967 
00968   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
00969     while (!DbgVal->use_empty()) {
00970       CallInst *CI = cast<CallInst>(DbgVal->user_back());
00971       CI->eraseFromParent();
00972     }
00973     DbgVal->eraseFromParent();
00974     Changed = true;
00975   }
00976 
00977   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
00978          NME = M.named_metadata_end(); NMI != NME;) {
00979     NamedMDNode *NMD = NMI;
00980     ++NMI;
00981     if (NMD->getName().startswith("llvm.dbg.")) {
00982       NMD->eraseFromParent();
00983       Changed = true;
00984     }
00985   }
00986 
00987   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
00988     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
00989          ++FI)
00990       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
00991            ++BI) {
00992         if (!BI->getDebugLoc().isUnknown()) {
00993           Changed = true;
00994           BI->setDebugLoc(DebugLoc());
00995         }
00996       }
00997 
00998   return Changed;
00999 }
01000 
01001 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
01002   if (auto *Val = mdconst::dyn_extract_or_null<ConstantInt>(
01003           M.getModuleFlag("Debug Info Version")))
01004     return Val->getZExtValue();
01005   return 0;
01006 }
01007 
01008 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
01009 llvm::makeSubprogramMap(const Module &M) {
01010   DenseMap<const Function *, DISubprogram> R;
01011 
01012   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
01013   if (!CU_Nodes)
01014     return R;
01015 
01016   for (MDNode *N : CU_Nodes->operands()) {
01017     DICompileUnit CUNode(N);
01018     DIArray SPs = CUNode.getSubprograms();
01019     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
01020       DISubprogram SP(SPs.getElement(i));
01021       if (Function *F = SP.getFunction())
01022         R.insert(std::make_pair(F, SP));
01023     }
01024   }
01025   return R;
01026 }