LLVM API Documentation

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/Analysis/ValueTracking.h"
00021 #include "llvm/IR/Constants.h"
00022 #include "llvm/IR/DIBuilder.h"
00023 #include "llvm/IR/DerivedTypes.h"
00024 #include "llvm/IR/Instructions.h"
00025 #include "llvm/IR/IntrinsicInst.h"
00026 #include "llvm/IR/Intrinsics.h"
00027 #include "llvm/IR/Module.h"
00028 #include "llvm/IR/ValueHandle.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/Dwarf.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 using namespace llvm;
00033 using namespace llvm::dwarf;
00034 
00035 //===----------------------------------------------------------------------===//
00036 // DIDescriptor
00037 //===----------------------------------------------------------------------===//
00038 
00039 bool DIDescriptor::Verify() const {
00040   return DbgNode &&
00041          (DIDerivedType(DbgNode).Verify() ||
00042           DICompositeType(DbgNode).Verify() || DIBasicType(DbgNode).Verify() ||
00043           DIVariable(DbgNode).Verify() || DISubprogram(DbgNode).Verify() ||
00044           DIGlobalVariable(DbgNode).Verify() || DIFile(DbgNode).Verify() ||
00045           DICompileUnit(DbgNode).Verify() || DINameSpace(DbgNode).Verify() ||
00046           DILexicalBlock(DbgNode).Verify() ||
00047           DILexicalBlockFile(DbgNode).Verify() ||
00048           DISubrange(DbgNode).Verify() || DIEnumerator(DbgNode).Verify() ||
00049           DIObjCProperty(DbgNode).Verify() ||
00050           DITemplateTypeParameter(DbgNode).Verify() ||
00051           DITemplateValueParameter(DbgNode).Verify() ||
00052           DIImportedEntity(DbgNode).Verify() || DIExpression(DbgNode).Verify());
00053 }
00054 
00055 static Metadata *getField(const MDNode *DbgNode, unsigned Elt) {
00056   if (!DbgNode || Elt >= DbgNode->getNumOperands())
00057     return nullptr;
00058   return DbgNode->getOperand(Elt);
00059 }
00060 
00061 static MDNode *getNodeField(const MDNode *DbgNode, unsigned Elt) {
00062   return dyn_cast_or_null<MDNode>(getField(DbgNode, Elt));
00063 }
00064 
00065 static StringRef getStringField(const MDNode *DbgNode, unsigned Elt) {
00066   if (MDString *MDS = dyn_cast_or_null<MDString>(getField(DbgNode, Elt)))
00067     return MDS->getString();
00068   return StringRef();
00069 }
00070 
00071 StringRef DIDescriptor::getStringField(unsigned Elt) const {
00072   return ::getStringField(DbgNode, Elt);
00073 }
00074 
00075 uint64_t DIDescriptor::getUInt64Field(unsigned Elt) const {
00076   if (auto *C = getConstantField(Elt))
00077     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00078       return CI->getZExtValue();
00079 
00080   return 0;
00081 }
00082 
00083 int64_t DIDescriptor::getInt64Field(unsigned Elt) const {
00084   if (auto *C = getConstantField(Elt))
00085     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
00086       return CI->getZExtValue();
00087 
00088   return 0;
00089 }
00090 
00091 DIDescriptor DIDescriptor::getDescriptorField(unsigned Elt) const {
00092   MDNode *Field = getNodeField(DbgNode, Elt);
00093   return DIDescriptor(Field);
00094 }
00095 
00096 GlobalVariable *DIDescriptor::getGlobalVariableField(unsigned Elt) const {
00097   return dyn_cast_or_null<GlobalVariable>(getConstantField(Elt));
00098 }
00099 
00100 Constant *DIDescriptor::getConstantField(unsigned Elt) const {
00101   if (!DbgNode)
00102     return nullptr;
00103 
00104   if (Elt < DbgNode->getNumOperands())
00105     if (auto *C =
00106             dyn_cast_or_null<ConstantAsMetadata>(DbgNode->getOperand(Elt)))
00107       return C->getValue();
00108   return nullptr;
00109 }
00110 
00111 Function *DIDescriptor::getFunctionField(unsigned Elt) const {
00112   return dyn_cast_or_null<Function>(getConstantField(Elt));
00113 }
00114 
00115 void DIDescriptor::replaceFunctionField(unsigned Elt, Function *F) {
00116   if (!DbgNode)
00117     return;
00118 
00119   if (Elt < DbgNode->getNumOperands()) {
00120     MDNode *Node = const_cast<MDNode *>(DbgNode);
00121     Node->replaceOperandWith(Elt, F ? ConstantAsMetadata::get(F) : nullptr);
00122   }
00123 }
00124 
00125 static unsigned DIVariableInlinedAtIndex = 4;
00126 MDNode *DIVariable::getInlinedAt() const {
00127   return getNodeField(DbgNode, DIVariableInlinedAtIndex);
00128 }
00129 
00130 /// \brief Return the size reported by the variable's type.
00131 unsigned DIVariable::getSizeInBits(const DITypeIdentifierMap &Map) {
00132   DIType Ty = getType().resolve(Map);
00133   // Follow derived types until we reach a type that
00134   // reports back a size.
00135   while (Ty.isDerivedType() && !Ty.getSizeInBits()) {
00136     DIDerivedType DT(&*Ty);
00137     Ty = DT.getTypeDerivedFrom().resolve(Map);
00138   }
00139   assert(Ty.getSizeInBits() && "type with size 0");
00140   return Ty.getSizeInBits();
00141 }
00142 
00143 uint64_t DIExpression::getElement(unsigned Idx) const {
00144   unsigned I = Idx + 1;
00145   assert(I < getNumHeaderFields() &&
00146          "non-existing complex address element requested");
00147   return getHeaderFieldAs<int64_t>(I);
00148 }
00149 
00150 bool DIExpression::isVariablePiece() const {
00151   return getNumElements() && getElement(0) == dwarf::DW_OP_piece;
00152 }
00153 
00154 uint64_t DIExpression::getPieceOffset() const {
00155   assert(isVariablePiece());
00156   return getElement(1);
00157 }
00158 
00159 uint64_t DIExpression::getPieceSize() const {
00160   assert(isVariablePiece());
00161   return getElement(2);
00162 }
00163 
00164 //===----------------------------------------------------------------------===//
00165 // Predicates
00166 //===----------------------------------------------------------------------===//
00167 
00168 bool DIDescriptor::isSubroutineType() const {
00169   return isCompositeType() && getTag() == dwarf::DW_TAG_subroutine_type;
00170 }
00171 
00172 bool DIDescriptor::isBasicType() const {
00173   if (!DbgNode)
00174     return false;
00175   switch (getTag()) {
00176   case dwarf::DW_TAG_base_type:
00177   case dwarf::DW_TAG_unspecified_type:
00178     return true;
00179   default:
00180     return false;
00181   }
00182 }
00183 
00184 bool DIDescriptor::isDerivedType() const {
00185   if (!DbgNode)
00186     return false;
00187   switch (getTag()) {
00188   case dwarf::DW_TAG_typedef:
00189   case dwarf::DW_TAG_pointer_type:
00190   case dwarf::DW_TAG_ptr_to_member_type:
00191   case dwarf::DW_TAG_reference_type:
00192   case dwarf::DW_TAG_rvalue_reference_type:
00193   case dwarf::DW_TAG_const_type:
00194   case dwarf::DW_TAG_volatile_type:
00195   case dwarf::DW_TAG_restrict_type:
00196   case dwarf::DW_TAG_member:
00197   case dwarf::DW_TAG_inheritance:
00198   case dwarf::DW_TAG_friend:
00199     return true;
00200   default:
00201     // CompositeTypes are currently modelled as DerivedTypes.
00202     return isCompositeType();
00203   }
00204 }
00205 
00206 bool DIDescriptor::isCompositeType() const {
00207   if (!DbgNode)
00208     return false;
00209   switch (getTag()) {
00210   case dwarf::DW_TAG_array_type:
00211   case dwarf::DW_TAG_structure_type:
00212   case dwarf::DW_TAG_union_type:
00213   case dwarf::DW_TAG_enumeration_type:
00214   case dwarf::DW_TAG_subroutine_type:
00215   case dwarf::DW_TAG_class_type:
00216     return true;
00217   default:
00218     return false;
00219   }
00220 }
00221 
00222 bool DIDescriptor::isVariable() const {
00223   if (!DbgNode)
00224     return false;
00225   switch (getTag()) {
00226   case dwarf::DW_TAG_auto_variable:
00227   case dwarf::DW_TAG_arg_variable:
00228     return true;
00229   default:
00230     return false;
00231   }
00232 }
00233 
00234 bool DIDescriptor::isType() const {
00235   return isBasicType() || isCompositeType() || isDerivedType();
00236 }
00237 
00238 bool DIDescriptor::isSubprogram() const {
00239   return DbgNode && getTag() == dwarf::DW_TAG_subprogram;
00240 }
00241 
00242 bool DIDescriptor::isGlobalVariable() const {
00243   return DbgNode && (getTag() == dwarf::DW_TAG_variable ||
00244                      getTag() == dwarf::DW_TAG_constant);
00245 }
00246 
00247 bool DIDescriptor::isScope() const {
00248   if (!DbgNode)
00249     return false;
00250   switch (getTag()) {
00251   case dwarf::DW_TAG_compile_unit:
00252   case dwarf::DW_TAG_lexical_block:
00253   case dwarf::DW_TAG_subprogram:
00254   case dwarf::DW_TAG_namespace:
00255   case dwarf::DW_TAG_file_type:
00256     return true;
00257   default:
00258     break;
00259   }
00260   return isType();
00261 }
00262 
00263 bool DIDescriptor::isTemplateTypeParameter() const {
00264   return DbgNode && getTag() == dwarf::DW_TAG_template_type_parameter;
00265 }
00266 
00267 bool DIDescriptor::isTemplateValueParameter() const {
00268   return DbgNode && (getTag() == dwarf::DW_TAG_template_value_parameter ||
00269                      getTag() == dwarf::DW_TAG_GNU_template_template_param ||
00270                      getTag() == dwarf::DW_TAG_GNU_template_parameter_pack);
00271 }
00272 
00273 bool DIDescriptor::isCompileUnit() const {
00274   return DbgNode && getTag() == dwarf::DW_TAG_compile_unit;
00275 }
00276 
00277 bool DIDescriptor::isFile() const {
00278   return DbgNode && getTag() == dwarf::DW_TAG_file_type;
00279 }
00280 
00281 bool DIDescriptor::isNameSpace() const {
00282   return DbgNode && getTag() == dwarf::DW_TAG_namespace;
00283 }
00284 
00285 bool DIDescriptor::isLexicalBlockFile() const {
00286   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
00287          DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 2;
00288 }
00289 
00290 bool DIDescriptor::isLexicalBlock() const {
00291   // FIXME: There are always exactly 4 header fields in DILexicalBlock, but
00292   // something relies on this returning true for DILexicalBlockFile.
00293   return DbgNode && getTag() == dwarf::DW_TAG_lexical_block &&
00294          DbgNode->getNumOperands() == 3 &&
00295          (getNumHeaderFields() == 2 || getNumHeaderFields() == 4);
00296 }
00297 
00298 bool DIDescriptor::isSubrange() const {
00299   return DbgNode && getTag() == dwarf::DW_TAG_subrange_type;
00300 }
00301 
00302 bool DIDescriptor::isEnumerator() const {
00303   return DbgNode && getTag() == dwarf::DW_TAG_enumerator;
00304 }
00305 
00306 bool DIDescriptor::isObjCProperty() const {
00307   return DbgNode && getTag() == dwarf::DW_TAG_APPLE_property;
00308 }
00309 
00310 bool DIDescriptor::isImportedEntity() const {
00311   return DbgNode && (getTag() == dwarf::DW_TAG_imported_module ||
00312                      getTag() == dwarf::DW_TAG_imported_declaration);
00313 }
00314 
00315 bool DIDescriptor::isExpression() const {
00316   return DbgNode && (getTag() == dwarf::DW_TAG_expression);
00317 }
00318 
00319 //===----------------------------------------------------------------------===//
00320 // Simple Descriptor Constructors and other Methods
00321 //===----------------------------------------------------------------------===//
00322 
00323 void DIDescriptor::replaceAllUsesWith(LLVMContext &VMContext, DIDescriptor D) {
00324 
00325   assert(DbgNode && "Trying to replace an unverified type!");
00326 
00327   // Since we use a TrackingVH for the node, its easy for clients to manufacture
00328   // legitimate situations where they want to replaceAllUsesWith() on something
00329   // which, due to uniquing, has merged with the source. We shield clients from
00330   // this detail by allowing a value to be replaced with replaceAllUsesWith()
00331   // itself.
00332   const MDNode *DN = D;
00333   if (DbgNode == DN) {
00334     SmallVector<Metadata *, 10> Ops(DbgNode->getNumOperands());
00335     for (size_t i = 0; i != Ops.size(); ++i)
00336       Ops[i] = DbgNode->getOperand(i);
00337     DN = MDNode::get(VMContext, Ops);
00338   }
00339 
00340   auto *Node = cast<MDNodeFwdDecl>(const_cast<MDNode *>(DbgNode));
00341   Node->replaceAllUsesWith(const_cast<MDNode *>(DN));
00342   MDNode::deleteTemporary(Node);
00343   DbgNode = DN;
00344 }
00345 
00346 void DIDescriptor::replaceAllUsesWith(MDNode *D) {
00347   assert(DbgNode && "Trying to replace an unverified type!");
00348   assert(DbgNode != D && "This replacement should always happen");
00349   auto *Node = cast<MDNodeFwdDecl>(const_cast<MDNode *>(DbgNode));
00350   Node->replaceAllUsesWith(D);
00351   MDNode::deleteTemporary(Node);
00352 }
00353 
00354 bool DICompileUnit::Verify() const {
00355   if (!isCompileUnit())
00356     return false;
00357 
00358   // Don't bother verifying the compilation directory or producer string
00359   // as those could be empty.
00360   if (getFilename().empty())
00361     return false;
00362 
00363   return DbgNode->getNumOperands() == 7 && getNumHeaderFields() == 8;
00364 }
00365 
00366 bool DIObjCProperty::Verify() const {
00367   if (!isObjCProperty())
00368     return false;
00369 
00370   // Don't worry about the rest of the strings for now.
00371   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 6;
00372 }
00373 
00374 /// \brief Check if a field at position Elt of a MDNode is a MDNode.
00375 ///
00376 /// We currently allow an empty string and an integer.
00377 /// But we don't allow a non-empty string in a MDNode field.
00378 static bool fieldIsMDNode(const MDNode *DbgNode, unsigned Elt) {
00379   // FIXME: This function should return true, if the field is null or the field
00380   // is indeed a MDNode: return !Fld || isa<MDNode>(Fld).
00381   Metadata *Fld = getField(DbgNode, Elt);
00382   if (Fld && isa<MDString>(Fld) && !cast<MDString>(Fld)->getString().empty())
00383     return false;
00384   return true;
00385 }
00386 
00387 /// \brief Check if a field at position Elt of a MDNode is a MDString.
00388 static bool fieldIsMDString(const MDNode *DbgNode, unsigned Elt) {
00389   Metadata *Fld = getField(DbgNode, Elt);
00390   return !Fld || isa<MDString>(Fld);
00391 }
00392 
00393 /// \brief Check if a value can be a reference to a type.
00394 static bool isTypeRef(const Metadata *MD) {
00395   if (!MD)
00396     return true;
00397   if (auto *S = dyn_cast<MDString>(MD))
00398     return !S->getString().empty();
00399   if (auto *N = dyn_cast<MDNode>(MD))
00400     return DIType(N).isType();
00401   return false;
00402 }
00403 
00404 /// \brief Check if referenced field might be a type.
00405 static bool fieldIsTypeRef(const MDNode *DbgNode, unsigned Elt) {
00406   return isTypeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
00407 }
00408 
00409 /// \brief Check if a value can be a ScopeRef.
00410 static bool isScopeRef(const Metadata *MD) {
00411   if (!MD)
00412     return true;
00413   if (auto *S = dyn_cast<MDString>(MD))
00414     return !S->getString().empty();
00415   return isa<MDNode>(MD);
00416 }
00417 
00418 /// \brief Check if a field at position Elt of a MDNode can be a ScopeRef.
00419 static bool fieldIsScopeRef(const MDNode *DbgNode, unsigned Elt) {
00420   return isScopeRef(dyn_cast_or_null<Metadata>(getField(DbgNode, Elt)));
00421 }
00422 
00423 bool DIType::Verify() const {
00424   if (!isType())
00425     return false;
00426   // Make sure Context @ field 2 is MDNode.
00427   if (!fieldIsScopeRef(DbgNode, 2))
00428     return false;
00429 
00430   // FIXME: Sink this into the various subclass verifies.
00431   uint16_t Tag = getTag();
00432   if (!isBasicType() && Tag != dwarf::DW_TAG_const_type &&
00433       Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_pointer_type &&
00434       Tag != dwarf::DW_TAG_ptr_to_member_type &&
00435       Tag != dwarf::DW_TAG_reference_type &&
00436       Tag != dwarf::DW_TAG_rvalue_reference_type &&
00437       Tag != dwarf::DW_TAG_restrict_type && Tag != dwarf::DW_TAG_array_type &&
00438       Tag != dwarf::DW_TAG_enumeration_type &&
00439       Tag != dwarf::DW_TAG_subroutine_type &&
00440       Tag != dwarf::DW_TAG_inheritance && Tag != dwarf::DW_TAG_friend &&
00441       getFilename().empty())
00442     return false;
00443 
00444   // DIType is abstract, it should be a BasicType, a DerivedType or
00445   // a CompositeType.
00446   if (isBasicType())
00447     return DIBasicType(DbgNode).Verify();
00448   else if (isCompositeType())
00449     return DICompositeType(DbgNode).Verify();
00450   else if (isDerivedType())
00451     return DIDerivedType(DbgNode).Verify();
00452   else
00453     return false;
00454 }
00455 
00456 bool DIBasicType::Verify() const {
00457   return isBasicType() && DbgNode->getNumOperands() == 3 &&
00458          getNumHeaderFields() == 8;
00459 }
00460 
00461 bool DIDerivedType::Verify() const {
00462   // Make sure DerivedFrom @ field 3 is TypeRef.
00463   if (!fieldIsTypeRef(DbgNode, 3))
00464     return false;
00465   if (getTag() == dwarf::DW_TAG_ptr_to_member_type)
00466     // Make sure ClassType @ field 4 is a TypeRef.
00467     if (!fieldIsTypeRef(DbgNode, 4))
00468       return false;
00469 
00470   return isDerivedType() && DbgNode->getNumOperands() >= 4 &&
00471          DbgNode->getNumOperands() <= 8 && getNumHeaderFields() >= 7 &&
00472          getNumHeaderFields() <= 8;
00473 }
00474 
00475 bool DICompositeType::Verify() const {
00476   if (!isCompositeType())
00477     return false;
00478 
00479   // Make sure DerivedFrom @ field 3 and ContainingType @ field 5 are TypeRef.
00480   if (!fieldIsTypeRef(DbgNode, 3))
00481     return false;
00482   if (!fieldIsTypeRef(DbgNode, 5))
00483     return false;
00484 
00485   // Make sure the type identifier at field 7 is MDString, it can be null.
00486   if (!fieldIsMDString(DbgNode, 7))
00487     return false;
00488 
00489   // A subroutine type can't be both & and &&.
00490   if (isLValueReference() && isRValueReference())
00491     return false;
00492 
00493   return DbgNode->getNumOperands() == 8 && getNumHeaderFields() == 8;
00494 }
00495 
00496 bool DISubprogram::Verify() const {
00497   if (!isSubprogram())
00498     return false;
00499 
00500   // Make sure context @ field 2 is a ScopeRef and type @ field 3 is a MDNode.
00501   if (!fieldIsScopeRef(DbgNode, 2))
00502     return false;
00503   if (!fieldIsMDNode(DbgNode, 3))
00504     return false;
00505   // Containing type @ field 4.
00506   if (!fieldIsTypeRef(DbgNode, 4))
00507     return false;
00508 
00509   // A subprogram can't be both & and &&.
00510   if (isLValueReference() && isRValueReference())
00511     return false;
00512 
00513   // If a DISubprogram has an llvm::Function*, then scope chains from all
00514   // instructions within the function should lead to this DISubprogram.
00515   if (auto *F = getFunction()) {
00516     for (auto &BB : *F) {
00517       for (auto &I : BB) {
00518         DebugLoc DL = I.getDebugLoc();
00519         if (DL.isUnknown())
00520           continue;
00521 
00522         MDNode *Scope = nullptr;
00523         MDNode *IA = nullptr;
00524         // walk the inlined-at scopes
00525         while ((IA = DL.getInlinedAt()))
00526           DL = DebugLoc::getFromDILocation(IA);
00527         DL.getScopeAndInlinedAt(Scope, IA);
00528         assert(!IA);
00529         while (!DIDescriptor(Scope).isSubprogram()) {
00530           DILexicalBlockFile D(Scope);
00531           Scope = D.isLexicalBlockFile()
00532                       ? D.getScope()
00533                       : DebugLoc::getFromDILexicalBlock(Scope).getScope();
00534         }
00535         if (!DISubprogram(Scope).describes(F))
00536           return false;
00537       }
00538     }
00539   }
00540   return DbgNode->getNumOperands() == 9 && getNumHeaderFields() == 12;
00541 }
00542 
00543 bool DIGlobalVariable::Verify() const {
00544   if (!isGlobalVariable())
00545     return false;
00546 
00547   if (getDisplayName().empty())
00548     return false;
00549   // Make sure context @ field 1 is an MDNode.
00550   if (!fieldIsMDNode(DbgNode, 1))
00551     return false;
00552   // Make sure that type @ field 3 is a DITypeRef.
00553   if (!fieldIsTypeRef(DbgNode, 3))
00554     return false;
00555   // Make sure StaticDataMemberDeclaration @ field 5 is MDNode.
00556   if (!fieldIsMDNode(DbgNode, 5))
00557     return false;
00558 
00559   return DbgNode->getNumOperands() == 6 && getNumHeaderFields() == 7;
00560 }
00561 
00562 bool DIVariable::Verify() const {
00563   if (!isVariable())
00564     return false;
00565 
00566   // Make sure context @ field 1 is an MDNode.
00567   if (!fieldIsMDNode(DbgNode, 1))
00568     return false;
00569   // Make sure that type @ field 3 is a DITypeRef.
00570   if (!fieldIsTypeRef(DbgNode, 3))
00571     return false;
00572 
00573   // Check the number of header fields, which is common between complex and
00574   // simple variables.
00575   if (getNumHeaderFields() != 4)
00576     return false;
00577 
00578   // Variable without an inline location.
00579   if (DbgNode->getNumOperands() == 4)
00580     return true;
00581 
00582   // Variable with an inline location.
00583   return getInlinedAt() != nullptr && DbgNode->getNumOperands() == 5;
00584 }
00585 
00586 bool DIExpression::Verify() const {
00587   // Empty DIExpressions may be represented as a nullptr.
00588   if (!DbgNode)
00589     return true;
00590 
00591   return isExpression() && DbgNode->getNumOperands() == 1;
00592 }
00593 
00594 bool DILocation::Verify() const {
00595   if (!DbgNode)
00596     return false;
00597 
00598   return DbgNode->getNumOperands() == 4;
00599 }
00600 
00601 bool DINameSpace::Verify() const {
00602   if (!isNameSpace())
00603     return false;
00604   return DbgNode->getNumOperands() == 3 && getNumHeaderFields() == 3;
00605 }
00606 
00607 MDNode *DIFile::getFileNode() const { return getNodeField(DbgNode, 1); }
00608 
00609 bool DIFile::Verify() const {
00610   return isFile() && DbgNode->getNumOperands() == 2;
00611 }
00612 
00613 bool DIEnumerator::Verify() const {
00614   return isEnumerator() && DbgNode->getNumOperands() == 1 &&
00615          getNumHeaderFields() == 3;
00616 }
00617 
00618 bool DISubrange::Verify() const {
00619   return isSubrange() && DbgNode->getNumOperands() == 1 &&
00620          getNumHeaderFields() == 3;
00621 }
00622 
00623 bool DILexicalBlock::Verify() const {
00624   return isLexicalBlock() && DbgNode->getNumOperands() == 3 &&
00625          getNumHeaderFields() == 4;
00626 }
00627 
00628 bool DILexicalBlockFile::Verify() const {
00629   return isLexicalBlockFile() && DbgNode->getNumOperands() == 3 &&
00630          getNumHeaderFields() == 2;
00631 }
00632 
00633 bool DITemplateTypeParameter::Verify() const {
00634   return isTemplateTypeParameter() && DbgNode->getNumOperands() == 4 &&
00635          getNumHeaderFields() == 4;
00636 }
00637 
00638 bool DITemplateValueParameter::Verify() const {
00639   return isTemplateValueParameter() && DbgNode->getNumOperands() == 5 &&
00640          getNumHeaderFields() == 4;
00641 }
00642 
00643 bool DIImportedEntity::Verify() const {
00644   return isImportedEntity() && DbgNode->getNumOperands() == 3 &&
00645          getNumHeaderFields() == 3;
00646 }
00647 
00648 MDNode *DIDerivedType::getObjCProperty() const {
00649   return getNodeField(DbgNode, 4);
00650 }
00651 
00652 MDString *DICompositeType::getIdentifier() const {
00653   return cast_or_null<MDString>(getField(DbgNode, 7));
00654 }
00655 
00656 #ifndef NDEBUG
00657 static void VerifySubsetOf(const MDNode *LHS, const MDNode *RHS) {
00658   for (unsigned i = 0; i != LHS->getNumOperands(); ++i) {
00659     // Skip the 'empty' list (that's a single i32 0, rather than truly empty).
00660     if (i == 0 && mdconst::hasa<ConstantInt>(LHS->getOperand(i)))
00661       continue;
00662     const MDNode *E = cast<MDNode>(LHS->getOperand(i));
00663     bool found = false;
00664     for (unsigned j = 0; !found && j != RHS->getNumOperands(); ++j)
00665       found = (E == cast<MDNode>(RHS->getOperand(j)));
00666     assert(found && "Losing a member during member list replacement");
00667   }
00668 }
00669 #endif
00670 
00671 void DICompositeType::setArraysHelper(MDNode *Elements, MDNode *TParams) {
00672   TrackingMDNodeRef N(*this);
00673   if (Elements) {
00674 #ifndef NDEBUG
00675     // Check that the new list of members contains all the old members as well.
00676     if (const MDNode *El = cast_or_null<MDNode>(N->getOperand(4)))
00677       VerifySubsetOf(El, Elements);
00678 #endif
00679     N->replaceOperandWith(4, Elements);
00680   }
00681   if (TParams)
00682     N->replaceOperandWith(6, TParams);
00683   DbgNode = N;
00684 }
00685 
00686 DIScopeRef DIScope::getRef() const {
00687   if (!isCompositeType())
00688     return DIScopeRef(*this);
00689   DICompositeType DTy(DbgNode);
00690   if (!DTy.getIdentifier())
00691     return DIScopeRef(*this);
00692   return DIScopeRef(DTy.getIdentifier());
00693 }
00694 
00695 void DICompositeType::setContainingType(DICompositeType ContainingType) {
00696   TrackingMDNodeRef N(*this);
00697   N->replaceOperandWith(5, ContainingType.getRef());
00698   DbgNode = N;
00699 }
00700 
00701 bool DIVariable::isInlinedFnArgument(const Function *CurFn) {
00702   assert(CurFn && "Invalid function");
00703   if (!getContext().isSubprogram())
00704     return false;
00705   // This variable is not inlined function argument if its scope
00706   // does not describe current function.
00707   return !DISubprogram(getContext()).describes(CurFn);
00708 }
00709 
00710 bool DISubprogram::describes(const Function *F) {
00711   assert(F && "Invalid function");
00712   if (F == getFunction())
00713     return true;
00714   StringRef Name = getLinkageName();
00715   if (Name.empty())
00716     Name = getName();
00717   if (F->getName() == Name)
00718     return true;
00719   return false;
00720 }
00721 
00722 MDNode *DISubprogram::getVariablesNodes() const {
00723   return getNodeField(DbgNode, 8);
00724 }
00725 
00726 DIArray DISubprogram::getVariables() const {
00727   return DIArray(getNodeField(DbgNode, 8));
00728 }
00729 
00730 Metadata *DITemplateValueParameter::getValue() const {
00731   return DbgNode->getOperand(3);
00732 }
00733 
00734 DIScopeRef DIScope::getContext() const {
00735 
00736   if (isType())
00737     return DIType(DbgNode).getContext();
00738 
00739   if (isSubprogram())
00740     return DIScopeRef(DISubprogram(DbgNode).getContext());
00741 
00742   if (isLexicalBlock())
00743     return DIScopeRef(DILexicalBlock(DbgNode).getContext());
00744 
00745   if (isLexicalBlockFile())
00746     return DIScopeRef(DILexicalBlockFile(DbgNode).getContext());
00747 
00748   if (isNameSpace())
00749     return DIScopeRef(DINameSpace(DbgNode).getContext());
00750 
00751   assert((isFile() || isCompileUnit()) && "Unhandled type of scope.");
00752   return DIScopeRef(nullptr);
00753 }
00754 
00755 StringRef DIScope::getName() const {
00756   if (isType())
00757     return DIType(DbgNode).getName();
00758   if (isSubprogram())
00759     return DISubprogram(DbgNode).getName();
00760   if (isNameSpace())
00761     return DINameSpace(DbgNode).getName();
00762   assert((isLexicalBlock() || isLexicalBlockFile() || isFile() ||
00763           isCompileUnit()) &&
00764          "Unhandled type of scope.");
00765   return StringRef();
00766 }
00767 
00768 StringRef DIScope::getFilename() const {
00769   if (!DbgNode)
00770     return StringRef();
00771   return ::getStringField(getNodeField(DbgNode, 1), 0);
00772 }
00773 
00774 StringRef DIScope::getDirectory() const {
00775   if (!DbgNode)
00776     return StringRef();
00777   return ::getStringField(getNodeField(DbgNode, 1), 1);
00778 }
00779 
00780 DIArray DICompileUnit::getEnumTypes() const {
00781   if (!DbgNode || DbgNode->getNumOperands() < 7)
00782     return DIArray();
00783 
00784   return DIArray(getNodeField(DbgNode, 2));
00785 }
00786 
00787 DIArray DICompileUnit::getRetainedTypes() const {
00788   if (!DbgNode || DbgNode->getNumOperands() < 7)
00789     return DIArray();
00790 
00791   return DIArray(getNodeField(DbgNode, 3));
00792 }
00793 
00794 DIArray DICompileUnit::getSubprograms() const {
00795   if (!DbgNode || DbgNode->getNumOperands() < 7)
00796     return DIArray();
00797 
00798   return DIArray(getNodeField(DbgNode, 4));
00799 }
00800 
00801 DIArray DICompileUnit::getGlobalVariables() const {
00802   if (!DbgNode || DbgNode->getNumOperands() < 7)
00803     return DIArray();
00804 
00805   return DIArray(getNodeField(DbgNode, 5));
00806 }
00807 
00808 DIArray DICompileUnit::getImportedEntities() const {
00809   if (!DbgNode || DbgNode->getNumOperands() < 7)
00810     return DIArray();
00811 
00812   return DIArray(getNodeField(DbgNode, 6));
00813 }
00814 
00815 void DICompileUnit::replaceSubprograms(DIArray Subprograms) {
00816   assert(Verify() && "Expected compile unit");
00817   if (Subprograms == getSubprograms())
00818     return;
00819 
00820   const_cast<MDNode *>(DbgNode)->replaceOperandWith(4, Subprograms);
00821 }
00822 
00823 void DICompileUnit::replaceGlobalVariables(DIArray GlobalVariables) {
00824   assert(Verify() && "Expected compile unit");
00825   if (GlobalVariables == getGlobalVariables())
00826     return;
00827 
00828   const_cast<MDNode *>(DbgNode)->replaceOperandWith(5, GlobalVariables);
00829 }
00830 
00831 DILocation DILocation::copyWithNewScope(LLVMContext &Ctx,
00832                                         DILexicalBlockFile NewScope) {
00833   SmallVector<Metadata *, 10> Elts;
00834   assert(Verify());
00835   for (unsigned I = 0; I < DbgNode->getNumOperands(); ++I) {
00836     if (I != 2)
00837       Elts.push_back(DbgNode->getOperand(I));
00838     else
00839       Elts.push_back(NewScope);
00840   }
00841   MDNode *NewDIL = MDNode::get(Ctx, Elts);
00842   return DILocation(NewDIL);
00843 }
00844 
00845 unsigned DILocation::computeNewDiscriminator(LLVMContext &Ctx) {
00846   std::pair<const char *, unsigned> Key(getFilename().data(), getLineNumber());
00847   return ++Ctx.pImpl->DiscriminatorTable[Key];
00848 }
00849 
00850 DIVariable llvm::createInlinedVariable(MDNode *DV, MDNode *InlinedScope,
00851                                        LLVMContext &VMContext) {
00852   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
00853   if (!InlinedScope)
00854     return cleanseInlinedVariable(DV, VMContext);
00855 
00856   // Insert inlined scope.
00857   SmallVector<Metadata *, 8> Elts;
00858   for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
00859     Elts.push_back(DV->getOperand(I));
00860   Elts.push_back(InlinedScope);
00861 
00862   DIVariable Inlined(MDNode::get(VMContext, Elts));
00863   assert(Inlined.Verify() && "Expected to create a DIVariable");
00864   return Inlined;
00865 }
00866 
00867 DIVariable llvm::cleanseInlinedVariable(MDNode *DV, LLVMContext &VMContext) {
00868   assert(DIVariable(DV).Verify() && "Expected a DIVariable");
00869   if (!DIVariable(DV).getInlinedAt())
00870     return DIVariable(DV);
00871 
00872   // Remove inlined scope.
00873   SmallVector<Metadata *, 8> Elts;
00874   for (unsigned I = 0, E = DIVariableInlinedAtIndex; I != E; ++I)
00875     Elts.push_back(DV->getOperand(I));
00876 
00877   DIVariable Cleansed(MDNode::get(VMContext, Elts));
00878   assert(Cleansed.Verify() && "Expected to create a DIVariable");
00879   return Cleansed;
00880 }
00881 
00882 DISubprogram llvm::getDISubprogram(const MDNode *Scope) {
00883   DIDescriptor D(Scope);
00884   if (D.isSubprogram())
00885     return DISubprogram(Scope);
00886 
00887   if (D.isLexicalBlockFile())
00888     return getDISubprogram(DILexicalBlockFile(Scope).getContext());
00889 
00890   if (D.isLexicalBlock())
00891     return getDISubprogram(DILexicalBlock(Scope).getContext());
00892 
00893   return DISubprogram();
00894 }
00895 
00896 DISubprogram llvm::getDISubprogram(const Function *F) {
00897   // We look for the first instr that has a debug annotation leading back to F.
00898   for (auto &BB : *F) {
00899     auto Inst = std::find_if(BB.begin(), BB.end(), [](const Instruction &Inst) {
00900       return !Inst.getDebugLoc().isUnknown();
00901     });
00902     if (Inst == BB.end())
00903       continue;
00904     DebugLoc DLoc = Inst->getDebugLoc();
00905     const MDNode *Scope = DLoc.getScopeNode();
00906     DISubprogram Subprogram = getDISubprogram(Scope);
00907     return Subprogram.describes(F) ? Subprogram : DISubprogram();
00908   }
00909 
00910   return DISubprogram();
00911 }
00912 
00913 DICompositeType llvm::getDICompositeType(DIType T) {
00914   if (T.isCompositeType())
00915     return DICompositeType(T);
00916 
00917   if (T.isDerivedType()) {
00918     // This function is currently used by dragonegg and dragonegg does
00919     // not generate identifier for types, so using an empty map to resolve
00920     // DerivedFrom should be fine.
00921     DITypeIdentifierMap EmptyMap;
00922     return getDICompositeType(
00923         DIDerivedType(T).getTypeDerivedFrom().resolve(EmptyMap));
00924   }
00925 
00926   return DICompositeType();
00927 }
00928 
00929 DITypeIdentifierMap
00930 llvm::generateDITypeIdentifierMap(const NamedMDNode *CU_Nodes) {
00931   DITypeIdentifierMap Map;
00932   for (unsigned CUi = 0, CUe = CU_Nodes->getNumOperands(); CUi != CUe; ++CUi) {
00933     DICompileUnit CU(CU_Nodes->getOperand(CUi));
00934     DIArray Retain = CU.getRetainedTypes();
00935     for (unsigned Ti = 0, Te = Retain.getNumElements(); Ti != Te; ++Ti) {
00936       if (!Retain.getElement(Ti).isCompositeType())
00937         continue;
00938       DICompositeType Ty(Retain.getElement(Ti));
00939       if (MDString *TypeId = Ty.getIdentifier()) {
00940         // Definition has priority over declaration.
00941         // Try to insert (TypeId, Ty) to Map.
00942         std::pair<DITypeIdentifierMap::iterator, bool> P =
00943             Map.insert(std::make_pair(TypeId, Ty));
00944         // If TypeId already exists in Map and this is a definition, replace
00945         // whatever we had (declaration or definition) with the definition.
00946         if (!P.second && !Ty.isForwardDecl())
00947           P.first->second = Ty;
00948       }
00949     }
00950   }
00951   return Map;
00952 }
00953 
00954 //===----------------------------------------------------------------------===//
00955 // DebugInfoFinder implementations.
00956 //===----------------------------------------------------------------------===//
00957 
00958 void DebugInfoFinder::reset() {
00959   CUs.clear();
00960   SPs.clear();
00961   GVs.clear();
00962   TYs.clear();
00963   Scopes.clear();
00964   NodesSeen.clear();
00965   TypeIdentifierMap.clear();
00966   TypeMapInitialized = false;
00967 }
00968 
00969 void DebugInfoFinder::InitializeTypeMap(const Module &M) {
00970   if (!TypeMapInitialized)
00971     if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00972       TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
00973       TypeMapInitialized = true;
00974     }
00975 }
00976 
00977 void DebugInfoFinder::processModule(const Module &M) {
00978   InitializeTypeMap(M);
00979   if (NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu")) {
00980     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
00981       DICompileUnit CU(CU_Nodes->getOperand(i));
00982       addCompileUnit(CU);
00983       DIArray GVs = CU.getGlobalVariables();
00984       for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i) {
00985         DIGlobalVariable DIG(GVs.getElement(i));
00986         if (addGlobalVariable(DIG)) {
00987           processScope(DIG.getContext());
00988           processType(DIG.getType().resolve(TypeIdentifierMap));
00989         }
00990       }
00991       DIArray SPs = CU.getSubprograms();
00992       for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
00993         processSubprogram(DISubprogram(SPs.getElement(i)));
00994       DIArray EnumTypes = CU.getEnumTypes();
00995       for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
00996         processType(DIType(EnumTypes.getElement(i)));
00997       DIArray RetainedTypes = CU.getRetainedTypes();
00998       for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
00999         processType(DIType(RetainedTypes.getElement(i)));
01000       DIArray Imports = CU.getImportedEntities();
01001       for (unsigned i = 0, e = Imports.getNumElements(); i != e; ++i) {
01002         DIImportedEntity Import = DIImportedEntity(Imports.getElement(i));
01003         DIDescriptor Entity = Import.getEntity().resolve(TypeIdentifierMap);
01004         if (Entity.isType())
01005           processType(DIType(Entity));
01006         else if (Entity.isSubprogram())
01007           processSubprogram(DISubprogram(Entity));
01008         else if (Entity.isNameSpace())
01009           processScope(DINameSpace(Entity).getContext());
01010       }
01011     }
01012   }
01013 }
01014 
01015 void DebugInfoFinder::processLocation(const Module &M, DILocation Loc) {
01016   if (!Loc)
01017     return;
01018   InitializeTypeMap(M);
01019   processScope(Loc.getScope());
01020   processLocation(M, Loc.getOrigLocation());
01021 }
01022 
01023 void DebugInfoFinder::processType(DIType DT) {
01024   if (!addType(DT))
01025     return;
01026   processScope(DT.getContext().resolve(TypeIdentifierMap));
01027   if (DT.isCompositeType()) {
01028     DICompositeType DCT(DT);
01029     processType(DCT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01030     if (DT.isSubroutineType()) {
01031       DITypeArray DTA = DISubroutineType(DT).getTypeArray();
01032       for (unsigned i = 0, e = DTA.getNumElements(); i != e; ++i)
01033         processType(DTA.getElement(i).resolve(TypeIdentifierMap));
01034       return;
01035     }
01036     DIArray DA = DCT.getElements();
01037     for (unsigned i = 0, e = DA.getNumElements(); i != e; ++i) {
01038       DIDescriptor D = DA.getElement(i);
01039       if (D.isType())
01040         processType(DIType(D));
01041       else if (D.isSubprogram())
01042         processSubprogram(DISubprogram(D));
01043     }
01044   } else if (DT.isDerivedType()) {
01045     DIDerivedType DDT(DT);
01046     processType(DDT.getTypeDerivedFrom().resolve(TypeIdentifierMap));
01047   }
01048 }
01049 
01050 void DebugInfoFinder::processScope(DIScope Scope) {
01051   if (Scope.isType()) {
01052     DIType Ty(Scope);
01053     processType(Ty);
01054     return;
01055   }
01056   if (Scope.isCompileUnit()) {
01057     addCompileUnit(DICompileUnit(Scope));
01058     return;
01059   }
01060   if (Scope.isSubprogram()) {
01061     processSubprogram(DISubprogram(Scope));
01062     return;
01063   }
01064   if (!addScope(Scope))
01065     return;
01066   if (Scope.isLexicalBlock()) {
01067     DILexicalBlock LB(Scope);
01068     processScope(LB.getContext());
01069   } else if (Scope.isLexicalBlockFile()) {
01070     DILexicalBlockFile LBF = DILexicalBlockFile(Scope);
01071     processScope(LBF.getScope());
01072   } else if (Scope.isNameSpace()) {
01073     DINameSpace NS(Scope);
01074     processScope(NS.getContext());
01075   }
01076 }
01077 
01078 void DebugInfoFinder::processSubprogram(DISubprogram SP) {
01079   if (!addSubprogram(SP))
01080     return;
01081   processScope(SP.getContext().resolve(TypeIdentifierMap));
01082   processType(SP.getType());
01083   DIArray TParams = SP.getTemplateParams();
01084   for (unsigned I = 0, E = TParams.getNumElements(); I != E; ++I) {
01085     DIDescriptor Element = TParams.getElement(I);
01086     if (Element.isTemplateTypeParameter()) {
01087       DITemplateTypeParameter TType(Element);
01088       processScope(TType.getContext().resolve(TypeIdentifierMap));
01089       processType(TType.getType().resolve(TypeIdentifierMap));
01090     } else if (Element.isTemplateValueParameter()) {
01091       DITemplateValueParameter TVal(Element);
01092       processScope(TVal.getContext().resolve(TypeIdentifierMap));
01093       processType(TVal.getType().resolve(TypeIdentifierMap));
01094     }
01095   }
01096 }
01097 
01098 void DebugInfoFinder::processDeclare(const Module &M,
01099                                      const DbgDeclareInst *DDI) {
01100   MDNode *N = dyn_cast<MDNode>(DDI->getVariable());
01101   if (!N)
01102     return;
01103   InitializeTypeMap(M);
01104 
01105   DIDescriptor DV(N);
01106   if (!DV.isVariable())
01107     return;
01108 
01109   if (!NodesSeen.insert(DV).second)
01110     return;
01111   processScope(DIVariable(N).getContext());
01112   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01113 }
01114 
01115 void DebugInfoFinder::processValue(const Module &M, const DbgValueInst *DVI) {
01116   MDNode *N = dyn_cast<MDNode>(DVI->getVariable());
01117   if (!N)
01118     return;
01119   InitializeTypeMap(M);
01120 
01121   DIDescriptor DV(N);
01122   if (!DV.isVariable())
01123     return;
01124 
01125   if (!NodesSeen.insert(DV).second)
01126     return;
01127   processScope(DIVariable(N).getContext());
01128   processType(DIVariable(N).getType().resolve(TypeIdentifierMap));
01129 }
01130 
01131 bool DebugInfoFinder::addType(DIType DT) {
01132   if (!DT)
01133     return false;
01134 
01135   if (!NodesSeen.insert(DT).second)
01136     return false;
01137 
01138   TYs.push_back(DT);
01139   return true;
01140 }
01141 
01142 bool DebugInfoFinder::addCompileUnit(DICompileUnit CU) {
01143   if (!CU)
01144     return false;
01145   if (!NodesSeen.insert(CU).second)
01146     return false;
01147 
01148   CUs.push_back(CU);
01149   return true;
01150 }
01151 
01152 bool DebugInfoFinder::addGlobalVariable(DIGlobalVariable DIG) {
01153   if (!DIG)
01154     return false;
01155 
01156   if (!NodesSeen.insert(DIG).second)
01157     return false;
01158 
01159   GVs.push_back(DIG);
01160   return true;
01161 }
01162 
01163 bool DebugInfoFinder::addSubprogram(DISubprogram SP) {
01164   if (!SP)
01165     return false;
01166 
01167   if (!NodesSeen.insert(SP).second)
01168     return false;
01169 
01170   SPs.push_back(SP);
01171   return true;
01172 }
01173 
01174 bool DebugInfoFinder::addScope(DIScope Scope) {
01175   if (!Scope)
01176     return false;
01177   // FIXME: Ocaml binding generates a scope with no content, we treat it
01178   // as null for now.
01179   if (Scope->getNumOperands() == 0)
01180     return false;
01181   if (!NodesSeen.insert(Scope).second)
01182     return false;
01183   Scopes.push_back(Scope);
01184   return true;
01185 }
01186 
01187 //===----------------------------------------------------------------------===//
01188 // DIDescriptor: dump routines for all descriptors.
01189 //===----------------------------------------------------------------------===//
01190 
01191 void DIDescriptor::dump() const {
01192   print(dbgs());
01193   dbgs() << '\n';
01194 }
01195 
01196 void DIDescriptor::print(raw_ostream &OS) const {
01197   if (!DbgNode)
01198     return;
01199 
01200   if (const char *Tag = dwarf::TagString(getTag()))
01201     OS << "[ " << Tag << " ]";
01202 
01203   if (this->isSubrange()) {
01204     DISubrange(DbgNode).printInternal(OS);
01205   } else if (this->isCompileUnit()) {
01206     DICompileUnit(DbgNode).printInternal(OS);
01207   } else if (this->isFile()) {
01208     DIFile(DbgNode).printInternal(OS);
01209   } else if (this->isEnumerator()) {
01210     DIEnumerator(DbgNode).printInternal(OS);
01211   } else if (this->isBasicType()) {
01212     DIType(DbgNode).printInternal(OS);
01213   } else if (this->isDerivedType()) {
01214     DIDerivedType(DbgNode).printInternal(OS);
01215   } else if (this->isCompositeType()) {
01216     DICompositeType(DbgNode).printInternal(OS);
01217   } else if (this->isSubprogram()) {
01218     DISubprogram(DbgNode).printInternal(OS);
01219   } else if (this->isGlobalVariable()) {
01220     DIGlobalVariable(DbgNode).printInternal(OS);
01221   } else if (this->isVariable()) {
01222     DIVariable(DbgNode).printInternal(OS);
01223   } else if (this->isObjCProperty()) {
01224     DIObjCProperty(DbgNode).printInternal(OS);
01225   } else if (this->isNameSpace()) {
01226     DINameSpace(DbgNode).printInternal(OS);
01227   } else if (this->isScope()) {
01228     DIScope(DbgNode).printInternal(OS);
01229   } else if (this->isExpression()) {
01230     DIExpression(DbgNode).printInternal(OS);
01231   }
01232 }
01233 
01234 void DISubrange::printInternal(raw_ostream &OS) const {
01235   int64_t Count = getCount();
01236   if (Count != -1)
01237     OS << " [" << getLo() << ", " << Count - 1 << ']';
01238   else
01239     OS << " [unbounded]";
01240 }
01241 
01242 void DIScope::printInternal(raw_ostream &OS) const {
01243   OS << " [" << getDirectory() << "/" << getFilename() << ']';
01244 }
01245 
01246 void DICompileUnit::printInternal(raw_ostream &OS) const {
01247   DIScope::printInternal(OS);
01248   OS << " [";
01249   unsigned Lang = getLanguage();
01250   if (const char *LangStr = dwarf::LanguageString(Lang))
01251     OS << LangStr;
01252   else
01253     (OS << "lang 0x").write_hex(Lang);
01254   OS << ']';
01255 }
01256 
01257 void DIEnumerator::printInternal(raw_ostream &OS) const {
01258   OS << " [" << getName() << " :: " << getEnumValue() << ']';
01259 }
01260 
01261 void DIType::printInternal(raw_ostream &OS) const {
01262   if (!DbgNode)
01263     return;
01264 
01265   StringRef Res = getName();
01266   if (!Res.empty())
01267     OS << " [" << Res << "]";
01268 
01269   // TODO: Print context?
01270 
01271   OS << " [line " << getLineNumber() << ", size " << getSizeInBits()
01272      << ", align " << getAlignInBits() << ", offset " << getOffsetInBits();
01273   if (isBasicType())
01274     if (const char *Enc =
01275             dwarf::AttributeEncodingString(DIBasicType(DbgNode).getEncoding()))
01276       OS << ", enc " << Enc;
01277   OS << "]";
01278 
01279   if (isPrivate())
01280     OS << " [private]";
01281   else if (isProtected())
01282     OS << " [protected]";
01283   else if (isPublic())
01284     OS << " [public]";
01285 
01286   if (isArtificial())
01287     OS << " [artificial]";
01288 
01289   if (isForwardDecl())
01290     OS << " [decl]";
01291   else if (getTag() == dwarf::DW_TAG_structure_type ||
01292            getTag() == dwarf::DW_TAG_union_type ||
01293            getTag() == dwarf::DW_TAG_enumeration_type ||
01294            getTag() == dwarf::DW_TAG_class_type)
01295     OS << " [def]";
01296   if (isVector())
01297     OS << " [vector]";
01298   if (isStaticMember())
01299     OS << " [static]";
01300 
01301   if (isLValueReference())
01302     OS << " [reference]";
01303 
01304   if (isRValueReference())
01305     OS << " [rvalue reference]";
01306 }
01307 
01308 void DIDerivedType::printInternal(raw_ostream &OS) const {
01309   DIType::printInternal(OS);
01310   OS << " [from " << getTypeDerivedFrom().getName() << ']';
01311 }
01312 
01313 void DICompositeType::printInternal(raw_ostream &OS) const {
01314   DIType::printInternal(OS);
01315   DIArray A = getElements();
01316   OS << " [" << A.getNumElements() << " elements]";
01317 }
01318 
01319 void DINameSpace::printInternal(raw_ostream &OS) const {
01320   StringRef Name = getName();
01321   if (!Name.empty())
01322     OS << " [" << Name << ']';
01323 
01324   OS << " [line " << getLineNumber() << ']';
01325 }
01326 
01327 void DISubprogram::printInternal(raw_ostream &OS) const {
01328   // TODO : Print context
01329   OS << " [line " << getLineNumber() << ']';
01330 
01331   if (isLocalToUnit())
01332     OS << " [local]";
01333 
01334   if (isDefinition())
01335     OS << " [def]";
01336 
01337   if (getScopeLineNumber() != getLineNumber())
01338     OS << " [scope " << getScopeLineNumber() << "]";
01339 
01340   if (isPrivate())
01341     OS << " [private]";
01342   else if (isProtected())
01343     OS << " [protected]";
01344   else if (isPublic())
01345     OS << " [public]";
01346 
01347   if (isLValueReference())
01348     OS << " [reference]";
01349 
01350   if (isRValueReference())
01351     OS << " [rvalue reference]";
01352 
01353   StringRef Res = getName();
01354   if (!Res.empty())
01355     OS << " [" << Res << ']';
01356 }
01357 
01358 void DIGlobalVariable::printInternal(raw_ostream &OS) const {
01359   StringRef Res = getName();
01360   if (!Res.empty())
01361     OS << " [" << Res << ']';
01362 
01363   OS << " [line " << getLineNumber() << ']';
01364 
01365   // TODO : Print context
01366 
01367   if (isLocalToUnit())
01368     OS << " [local]";
01369 
01370   if (isDefinition())
01371     OS << " [def]";
01372 }
01373 
01374 void DIVariable::printInternal(raw_ostream &OS) const {
01375   StringRef Res = getName();
01376   if (!Res.empty())
01377     OS << " [" << Res << ']';
01378 
01379   OS << " [line " << getLineNumber() << ']';
01380 }
01381 
01382 void DIExpression::printInternal(raw_ostream &OS) const {
01383   for (unsigned I = 0; I < getNumElements(); ++I) {
01384     uint64_t OpCode = getElement(I);
01385     OS << " [" << OperationEncodingString(OpCode);
01386     switch (OpCode) {
01387     case DW_OP_plus: {
01388       OS << " " << getElement(++I);
01389       break;
01390     }
01391     case DW_OP_piece: {
01392       unsigned Offset = getElement(++I);
01393       unsigned Size = getElement(++I);
01394       OS << " offset=" << Offset << ", size=" << Size;
01395       break;
01396     }
01397     case DW_OP_deref:
01398       // No arguments.
01399       break;
01400     default:
01401       // Else bail out early. This may be a line table entry.
01402       OS << "Unknown]";
01403       return;
01404     }
01405     OS << "]";
01406   }
01407 }
01408 
01409 void DIObjCProperty::printInternal(raw_ostream &OS) const {
01410   StringRef Name = getObjCPropertyName();
01411   if (!Name.empty())
01412     OS << " [" << Name << ']';
01413 
01414   OS << " [line " << getLineNumber() << ", properties " << getUnsignedField(6)
01415      << ']';
01416 }
01417 
01418 static void printDebugLoc(DebugLoc DL, raw_ostream &CommentOS,
01419                           const LLVMContext &Ctx) {
01420   if (!DL.isUnknown()) { // Print source line info.
01421     DIScope Scope(DL.getScope(Ctx));
01422     assert(Scope.isScope() && "Scope of a DebugLoc should be a DIScope.");
01423     // Omit the directory, because it's likely to be long and uninteresting.
01424     CommentOS << Scope.getFilename();
01425     CommentOS << ':' << DL.getLine();
01426     if (DL.getCol() != 0)
01427       CommentOS << ':' << DL.getCol();
01428     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
01429     if (!InlinedAtDL.isUnknown()) {
01430       CommentOS << " @[ ";
01431       printDebugLoc(InlinedAtDL, CommentOS, Ctx);
01432       CommentOS << " ]";
01433     }
01434   }
01435 }
01436 
01437 void DIVariable::printExtendedName(raw_ostream &OS) const {
01438   const LLVMContext &Ctx = DbgNode->getContext();
01439   StringRef Res = getName();
01440   if (!Res.empty())
01441     OS << Res << "," << getLineNumber();
01442   if (MDNode *InlinedAt = getInlinedAt()) {
01443     DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
01444     if (!InlinedAtDL.isUnknown()) {
01445       OS << " @[";
01446       printDebugLoc(InlinedAtDL, OS, Ctx);
01447       OS << "]";
01448     }
01449   }
01450 }
01451 
01452 template <> DIRef<DIScope>::DIRef(const Metadata *V) : Val(V) {
01453   assert(isScopeRef(V) && "DIScopeRef should be a MDString or MDNode");
01454 }
01455 template <> DIRef<DIType>::DIRef(const Metadata *V) : Val(V) {
01456   assert(isTypeRef(V) && "DITypeRef should be a MDString or MDNode");
01457 }
01458 
01459 template <>
01460 DIScopeRef DIDescriptor::getFieldAs<DIScopeRef>(unsigned Elt) const {
01461   return DIScopeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
01462 }
01463 template <> DITypeRef DIDescriptor::getFieldAs<DITypeRef>(unsigned Elt) const {
01464   return DITypeRef(cast_or_null<Metadata>(getField(DbgNode, Elt)));
01465 }
01466 
01467 bool llvm::StripDebugInfo(Module &M) {
01468   bool Changed = false;
01469 
01470   // Remove all of the calls to the debugger intrinsics, and remove them from
01471   // the module.
01472   if (Function *Declare = M.getFunction("llvm.dbg.declare")) {
01473     while (!Declare->use_empty()) {
01474       CallInst *CI = cast<CallInst>(Declare->user_back());
01475       CI->eraseFromParent();
01476     }
01477     Declare->eraseFromParent();
01478     Changed = true;
01479   }
01480 
01481   if (Function *DbgVal = M.getFunction("llvm.dbg.value")) {
01482     while (!DbgVal->use_empty()) {
01483       CallInst *CI = cast<CallInst>(DbgVal->user_back());
01484       CI->eraseFromParent();
01485     }
01486     DbgVal->eraseFromParent();
01487     Changed = true;
01488   }
01489 
01490   for (Module::named_metadata_iterator NMI = M.named_metadata_begin(),
01491          NME = M.named_metadata_end(); NMI != NME;) {
01492     NamedMDNode *NMD = NMI;
01493     ++NMI;
01494     if (NMD->getName().startswith("llvm.dbg.")) {
01495       NMD->eraseFromParent();
01496       Changed = true;
01497     }
01498   }
01499 
01500   for (Module::iterator MI = M.begin(), ME = M.end(); MI != ME; ++MI)
01501     for (Function::iterator FI = MI->begin(), FE = MI->end(); FI != FE;
01502          ++FI)
01503       for (BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE;
01504            ++BI) {
01505         if (!BI->getDebugLoc().isUnknown()) {
01506           Changed = true;
01507           BI->setDebugLoc(DebugLoc());
01508         }
01509       }
01510 
01511   return Changed;
01512 }
01513 
01514 unsigned llvm::getDebugMetadataVersionFromModule(const Module &M) {
01515   if (auto *Val = mdconst::extract_or_null<ConstantInt>(
01516           M.getModuleFlag("Debug Info Version")))
01517     return Val->getZExtValue();
01518   return 0;
01519 }
01520 
01521 llvm::DenseMap<const llvm::Function *, llvm::DISubprogram>
01522 llvm::makeSubprogramMap(const Module &M) {
01523   DenseMap<const Function *, DISubprogram> R;
01524 
01525   NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
01526   if (!CU_Nodes)
01527     return R;
01528 
01529   for (MDNode *N : CU_Nodes->operands()) {
01530     DICompileUnit CUNode(N);
01531     DIArray SPs = CUNode.getSubprograms();
01532     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
01533       DISubprogram SP(SPs.getElement(i));
01534       if (Function *F = SP.getFunction())
01535         R.insert(std::make_pair(F, SP));
01536     }
01537   }
01538   return R;
01539 }