LLVM API Documentation

DwarfCompileUnit.cpp
Go to the documentation of this file.
00001 #include "DwarfCompileUnit.h"
00002 #include "DwarfExpression.h"
00003 #include "llvm/CodeGen/MachineFunction.h"
00004 #include "llvm/IR/DataLayout.h"
00005 #include "llvm/IR/GlobalValue.h"
00006 #include "llvm/IR/GlobalVariable.h"
00007 #include "llvm/IR/Instruction.h"
00008 #include "llvm/MC/MCAsmInfo.h"
00009 #include "llvm/MC/MCStreamer.h"
00010 #include "llvm/Target/TargetFrameLowering.h"
00011 #include "llvm/Target/TargetLoweringObjectFile.h"
00012 #include "llvm/Target/TargetMachine.h"
00013 #include "llvm/Target/TargetRegisterInfo.h"
00014 #include "llvm/Target/TargetSubtargetInfo.h"
00015 
00016 namespace llvm {
00017 
00018 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
00019                                    AsmPrinter *A, DwarfDebug *DW,
00020                                    DwarfFile *DWU)
00021     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU),
00022       Skeleton(nullptr), LabelBegin(nullptr), BaseAddress(nullptr) {
00023   insertDIE(Node, &getUnitDie());
00024 }
00025 
00026 /// addLabelAddress - Add a dwarf label attribute data and value using
00027 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
00028 ///
00029 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
00030                                        const MCSymbol *Label) {
00031 
00032   // Don't use the address pool in non-fission or in the skeleton unit itself.
00033   // FIXME: Once GDB supports this, it's probably worthwhile using the address
00034   // pool from the skeleton - maybe even in non-fission (possibly fewer
00035   // relocations by sharing them in the pool, but we have other ideas about how
00036   // to reduce the number of relocations as well/instead).
00037   if (!DD->useSplitDwarf() || !Skeleton)
00038     return addLocalLabelAddress(Die, Attribute, Label);
00039 
00040   if (Label)
00041     DD->addArangeLabel(SymbolCU(this, Label));
00042 
00043   unsigned idx = DD->getAddressPool().getIndex(Label);
00044   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
00045   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
00046 }
00047 
00048 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
00049                                             dwarf::Attribute Attribute,
00050                                             const MCSymbol *Label) {
00051   if (Label)
00052     DD->addArangeLabel(SymbolCU(this, Label));
00053 
00054   Die.addValue(Attribute, dwarf::DW_FORM_addr,
00055                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
00056                      : new (DIEValueAllocator) DIEInteger(0));
00057 }
00058 
00059 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
00060                                                StringRef DirName) {
00061   // If we print assembly, we can't separate .file entries according to
00062   // compile units. Thus all files will belong to the default compile unit.
00063 
00064   // FIXME: add a better feature test than hasRawTextSupport. Even better,
00065   // extend .file to support this.
00066   return Asm->OutStreamer.EmitDwarfFileDirective(
00067       0, DirName, FileName,
00068       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
00069 }
00070 
00071 // Return const expression if value is a GEP to access merged global
00072 // constant. e.g.
00073 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
00074 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
00075   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
00076   if (!CE || CE->getNumOperands() != 3 ||
00077       CE->getOpcode() != Instruction::GetElementPtr)
00078     return nullptr;
00079 
00080   // First operand points to a global struct.
00081   Value *Ptr = CE->getOperand(0);
00082   if (!isa<GlobalValue>(Ptr) ||
00083       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
00084     return nullptr;
00085 
00086   // Second operand is zero.
00087   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
00088   if (!CI || !CI->isZero())
00089     return nullptr;
00090 
00091   // Third operand is offset.
00092   if (!isa<ConstantInt>(CE->getOperand(2)))
00093     return nullptr;
00094 
00095   return CE;
00096 }
00097 
00098 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
00099 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
00100   // Check for pre-existence.
00101   if (DIE *Die = getDIE(GV))
00102     return Die;
00103 
00104   assert(GV.isGlobalVariable());
00105 
00106   DIScope GVContext = GV.getContext();
00107   DIType GTy = DD->resolve(GV.getType());
00108 
00109   // Construct the context before querying for the existence of the DIE in
00110   // case such construction creates the DIE.
00111   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
00112 
00113   // Add to map.
00114   DIE *VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
00115   DIScope DeclContext;
00116 
00117   if (DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration()) {
00118     DeclContext = resolve(SDMDecl.getContext());
00119     assert(SDMDecl.isStaticMember() && "Expected static member decl");
00120     assert(GV.isDefinition());
00121     // We need the declaration DIE that is in the static member's class.
00122     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
00123     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
00124   } else {
00125     DeclContext = GV.getContext();
00126     // Add name and type.
00127     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
00128     addType(*VariableDIE, GTy);
00129 
00130     // Add scoping info.
00131     if (!GV.isLocalToUnit())
00132       addFlag(*VariableDIE, dwarf::DW_AT_external);
00133 
00134     // Add line number info.
00135     addSourceLine(*VariableDIE, GV);
00136   }
00137 
00138   if (!GV.isDefinition())
00139     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
00140 
00141   // Add location.
00142   bool addToAccelTable = false;
00143   bool isGlobalVariable = GV.getGlobal() != nullptr;
00144   if (isGlobalVariable) {
00145     addToAccelTable = true;
00146     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00147     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
00148     if (GV.getGlobal()->isThreadLocal()) {
00149       // FIXME: Make this work with -gsplit-dwarf.
00150       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
00151       assert((PointerSize == 4 || PointerSize == 8) &&
00152              "Add support for other sizes if necessary");
00153       // Based on GCC's support for TLS:
00154       if (!DD->useSplitDwarf()) {
00155         // 1) Start with a constNu of the appropriate pointer size
00156         addUInt(*Loc, dwarf::DW_FORM_data1,
00157                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
00158         // 2) containing the (relocated) offset of the TLS variable
00159         //    within the module's TLS block.
00160         addExpr(*Loc, dwarf::DW_FORM_udata,
00161                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
00162       } else {
00163         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
00164         addUInt(*Loc, dwarf::DW_FORM_udata,
00165                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
00166       }
00167       // 3) followed by a custom OP to make the debugger do a TLS lookup.
00168       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
00169     } else {
00170       DD->addArangeLabel(SymbolCU(this, Sym));
00171       addOpAddress(*Loc, Sym);
00172     }
00173 
00174     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00175     // Add the linkage name.
00176     StringRef LinkageName = GV.getLinkageName();
00177     if (!LinkageName.empty())
00178       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
00179       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
00180       // TAG_variable.
00181       addString(*VariableDIE,
00182                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
00183                                            : dwarf::DW_AT_MIPS_linkage_name,
00184                 GlobalValue::getRealLinkageName(LinkageName));
00185   } else if (const ConstantInt *CI =
00186                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
00187     addConstantValue(*VariableDIE, CI, GTy);
00188   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
00189     addToAccelTable = true;
00190     // GV is a merged global.
00191     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00192     Value *Ptr = CE->getOperand(0);
00193     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
00194     DD->addArangeLabel(SymbolCU(this, Sym));
00195     addOpAddress(*Loc, Sym);
00196     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
00197     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
00198     addUInt(*Loc, dwarf::DW_FORM_udata,
00199             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
00200     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
00201     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00202   }
00203 
00204   if (addToAccelTable) {
00205     DD->addAccelName(GV.getName(), *VariableDIE);
00206 
00207     // If the linkage name is different than the name, go ahead and output
00208     // that as well into the name table.
00209     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
00210       DD->addAccelName(GV.getLinkageName(), *VariableDIE);
00211   }
00212 
00213   addGlobalName(GV.getName(), *VariableDIE, DeclContext);
00214   return VariableDIE;
00215 }
00216 
00217 void DwarfCompileUnit::addRange(RangeSpan Range) {
00218   bool SameAsPrevCU = this == DD->getPrevCU();
00219   DD->setPrevCU(this);
00220   // If we have no current ranges just add the range and return, otherwise,
00221   // check the current section and CU against the previous section and CU we
00222   // emitted into and the subprogram was contained within. If these are the
00223   // same then extend our current range, otherwise add this as a new range.
00224   if (CURanges.empty() || !SameAsPrevCU ||
00225       (&CURanges.back().getEnd()->getSection() !=
00226        &Range.getEnd()->getSection())) {
00227     CURanges.push_back(Range);
00228     return;
00229   }
00230 
00231   CURanges.back().setEnd(Range.getEnd());
00232 }
00233 
00234 void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
00235                                        const MCSymbol *Label,
00236                                        const MCSymbol *Sec) {
00237   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
00238     addLabel(Die, Attribute,
00239              DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00240                                         : dwarf::DW_FORM_data4,
00241              Label);
00242   else
00243     addSectionDelta(Die, Attribute, Label, Sec);
00244 }
00245 
00246 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
00247   // Define start line table label for each Compile Unit.
00248   MCSymbol *LineTableStartSym =
00249       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
00250 
00251   stmtListIndex = UnitDie.getValues().size();
00252 
00253   // DW_AT_stmt_list is a offset of line number information for this
00254   // compile unit in debug_line section. For split dwarf this is
00255   // left in the skeleton CU and so not included.
00256   // The line table entries are not always emitted in assembly, so it
00257   // is not okay to use line_table_start here.
00258   addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
00259                   DwarfLineSectionSym);
00260 }
00261 
00262 void DwarfCompileUnit::applyStmtList(DIE &D) {
00263   D.addValue(dwarf::DW_AT_stmt_list,
00264              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
00265              UnitDie.getValues()[stmtListIndex]);
00266 }
00267 
00268 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
00269                                        const MCSymbol *End) {
00270   assert(Begin && "Begin label should not be null!");
00271   assert(End && "End label should not be null!");
00272   assert(Begin->isDefined() && "Invalid starting label");
00273   assert(End->isDefined() && "Invalid end label");
00274 
00275   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
00276   if (DD->getDwarfVersion() < 4)
00277     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
00278   else
00279     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
00280 }
00281 
00282 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
00283 // and DW_AT_high_pc attributes. If there are global variables in this
00284 // scope then create and insert DIEs for these variables.
00285 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
00286   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
00287 
00288   attachLowHighPC(*SPDie, DD->getFunctionBeginSym(), DD->getFunctionEndSym());
00289   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
00290           *DD->getCurrentFunction()))
00291     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
00292 
00293   // Only include DW_AT_frame_base in full debug info
00294   if (!includeMinimalInlineScopes()) {
00295     const TargetRegisterInfo *RI =
00296         Asm->TM.getSubtargetImpl()->getRegisterInfo();
00297     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
00298     if (RI->isPhysicalRegister(Location.getReg()))
00299       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
00300   }
00301 
00302   // Add name to the name table, we do this here because we're guaranteed
00303   // to have concrete versions of our DW_TAG_subprogram nodes.
00304   DD->addSubprogramNames(SP, *SPDie);
00305 
00306   return *SPDie;
00307 }
00308 
00309 // Construct a DIE for this scope.
00310 void DwarfCompileUnit::constructScopeDIE(
00311     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
00312   if (!Scope || !Scope->getScopeNode())
00313     return;
00314 
00315   DIScope DS(Scope->getScopeNode());
00316 
00317   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
00318          "Only handle inlined subprograms here, use "
00319          "constructSubprogramScopeDIE for non-inlined "
00320          "subprograms");
00321 
00322   SmallVector<std::unique_ptr<DIE>, 8> Children;
00323 
00324   // We try to create the scope DIE first, then the children DIEs. This will
00325   // avoid creating un-used children then removing them later when we find out
00326   // the scope DIE is null.
00327   std::unique_ptr<DIE> ScopeDIE;
00328   if (Scope->getParent() && DS.isSubprogram()) {
00329     ScopeDIE = constructInlinedScopeDIE(Scope);
00330     if (!ScopeDIE)
00331       return;
00332     // We create children when the scope DIE is not null.
00333     createScopeChildrenDIE(Scope, Children);
00334   } else {
00335     // Early exit when we know the scope DIE is going to be null.
00336     if (DD->isLexicalScopeDIENull(Scope))
00337       return;
00338 
00339     unsigned ChildScopeCount;
00340 
00341     // We create children here when we know the scope DIE is not going to be
00342     // null and the children will be added to the scope DIE.
00343     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
00344 
00345     // Skip imported directives in gmlt-like data.
00346     if (!includeMinimalInlineScopes()) {
00347       // There is no need to emit empty lexical block DIE.
00348       for (const auto &E : DD->findImportedEntitiesForScope(DS))
00349         Children.push_back(
00350             constructImportedEntityDIE(DIImportedEntity(E.second)));
00351     }
00352 
00353     // If there are only other scopes as children, put them directly in the
00354     // parent instead, as this scope would serve no purpose.
00355     if (Children.size() == ChildScopeCount) {
00356       FinalChildren.insert(FinalChildren.end(),
00357                            std::make_move_iterator(Children.begin()),
00358                            std::make_move_iterator(Children.end()));
00359       return;
00360     }
00361     ScopeDIE = constructLexicalScopeDIE(Scope);
00362     assert(ScopeDIE && "Scope DIE should not be null.");
00363   }
00364 
00365   // Add children
00366   for (auto &I : Children)
00367     ScopeDIE->addChild(std::move(I));
00368 
00369   FinalChildren.push_back(std::move(ScopeDIE));
00370 }
00371 
00372 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
00373                                        const MCSymbol *Hi, const MCSymbol *Lo) {
00374   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
00375   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00376                                                      : dwarf::DW_FORM_data4,
00377                Value);
00378 }
00379 
00380 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
00381                                          SmallVector<RangeSpan, 2> Range) {
00382   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
00383   // emitting it appropriately.
00384   auto *RangeSectionSym = DD->getRangeSectionSym();
00385 
00386   RangeSpanList List(
00387       Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber()),
00388       std::move(Range));
00389 
00390   // Under fission, ranges are specified by constant offsets relative to the
00391   // CU's DW_AT_GNU_ranges_base.
00392   if (isDwoUnit())
00393     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00394                     RangeSectionSym);
00395   else
00396     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00397                     RangeSectionSym);
00398 
00399   // Add the range list to the set of ranges to be emitted.
00400   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
00401 }
00402 
00403 void DwarfCompileUnit::attachRangesOrLowHighPC(
00404     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
00405   if (Ranges.size() == 1) {
00406     const auto &single = Ranges.front();
00407     attachLowHighPC(Die, single.getStart(), single.getEnd());
00408   } else
00409     addScopeRangeList(Die, std::move(Ranges));
00410 }
00411 
00412 void DwarfCompileUnit::attachRangesOrLowHighPC(
00413     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
00414   SmallVector<RangeSpan, 2> List;
00415   List.reserve(Ranges.size());
00416   for (const InsnRange &R : Ranges)
00417     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
00418                              DD->getLabelAfterInsn(R.second)));
00419   attachRangesOrLowHighPC(Die, std::move(List));
00420 }
00421 
00422 // This scope represents inlined body of a function. Construct DIE to
00423 // represent this concrete inlined copy of the function.
00424 std::unique_ptr<DIE>
00425 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
00426   assert(Scope->getScopeNode());
00427   DIScope DS(Scope->getScopeNode());
00428   DISubprogram InlinedSP = getDISubprogram(DS);
00429   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00430   // was inlined from another compile unit.
00431   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
00432   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
00433 
00434   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
00435   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
00436 
00437   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00438 
00439   // Add the call site information to the DIE.
00440   DILocation DL(Scope->getInlinedAt());
00441   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
00442           getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
00443   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
00444 
00445   // Add name to the name table, we do this here because we're guaranteed
00446   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
00447   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
00448 
00449   return ScopeDIE;
00450 }
00451 
00452 // Construct new DW_TAG_lexical_block for this scope and attach
00453 // DW_AT_low_pc/DW_AT_high_pc labels.
00454 std::unique_ptr<DIE>
00455 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
00456   if (DD->isLexicalScopeDIENull(Scope))
00457     return nullptr;
00458 
00459   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
00460   if (Scope->isAbstractScope())
00461     return ScopeDIE;
00462 
00463   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00464 
00465   return ScopeDIE;
00466 }
00467 
00468 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
00469 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
00470                                                             bool Abstract) {
00471   auto D = constructVariableDIEImpl(DV, Abstract);
00472   DV.setDIE(*D);
00473   return D;
00474 }
00475 
00476 std::unique_ptr<DIE>
00477 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
00478                                            bool Abstract) {
00479   // Define variable debug information entry.
00480   auto VariableDie = make_unique<DIE>(DV.getTag());
00481 
00482   if (Abstract) {
00483     applyVariableAttributes(DV, *VariableDie);
00484     return VariableDie;
00485   }
00486 
00487   // Add variable address.
00488 
00489   unsigned Offset = DV.getDotDebugLocOffset();
00490   if (Offset != ~0U) {
00491     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
00492     return VariableDie;
00493   }
00494 
00495   // Check if variable is described by a DBG_VALUE instruction.
00496   if (const MachineInstr *DVInsn = DV.getMInsn()) {
00497     assert(DVInsn->getNumOperands() == 4);
00498     if (DVInsn->getOperand(0).isReg()) {
00499       const MachineOperand RegOp = DVInsn->getOperand(0);
00500       // If the second operand is an immediate, this is an indirect value.
00501       if (DVInsn->getOperand(1).isImm()) {
00502         MachineLocation Location(RegOp.getReg(),
00503                                  DVInsn->getOperand(1).getImm());
00504         addVariableAddress(DV, *VariableDie, Location);
00505       } else if (RegOp.getReg())
00506         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
00507     } else if (DVInsn->getOperand(0).isImm())
00508       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
00509     else if (DVInsn->getOperand(0).isFPImm())
00510       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
00511     else if (DVInsn->getOperand(0).isCImm())
00512       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
00513                        DV.getType());
00514 
00515     return VariableDie;
00516   }
00517 
00518   // .. else use frame index.
00519   int FI = DV.getFrameIndex();
00520   if (FI != ~0) {
00521     unsigned FrameReg = 0;
00522     const TargetFrameLowering *TFI =
00523         Asm->TM.getSubtargetImpl()->getFrameLowering();
00524     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
00525     MachineLocation Location(FrameReg, Offset);
00526     addVariableAddress(DV, *VariableDie, Location);
00527   }
00528 
00529   return VariableDie;
00530 }
00531 
00532 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
00533     DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
00534   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
00535   if (DV.isObjectPointer())
00536     ObjectPointer = Var.get();
00537   return Var;
00538 }
00539 
00540 DIE *DwarfCompileUnit::createScopeChildrenDIE(
00541     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
00542     unsigned *ChildScopeCount) {
00543   DIE *ObjectPointer = nullptr;
00544 
00545   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
00546     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
00547 
00548   unsigned ChildCountWithoutScopes = Children.size();
00549 
00550   for (LexicalScope *LS : Scope->getChildren())
00551     constructScopeDIE(LS, Children);
00552 
00553   if (ChildScopeCount)
00554     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
00555 
00556   return ObjectPointer;
00557 }
00558 
00559 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
00560   assert(Scope && Scope->getScopeNode());
00561   assert(!Scope->getInlinedAt());
00562   assert(!Scope->isAbstractScope());
00563   DISubprogram Sub(Scope->getScopeNode());
00564 
00565   assert(Sub.isSubprogram());
00566 
00567   DD->getProcessedSPNodes().insert(Sub);
00568 
00569   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
00570 
00571   // If this is a variadic function, add an unspecified parameter.
00572   DITypeArray FnArgs = Sub.getType().getTypeArray();
00573 
00574   // Collect lexical scope children first.
00575   // ObjectPointer might be a local (non-argument) local variable if it's a
00576   // block's synthetic this pointer.
00577   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
00578     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
00579 
00580   // If we have a single element of null, it is a function that returns void.
00581   // If we have more than one elements and the last one is null, it is a
00582   // variadic function.
00583   if (FnArgs.getNumElements() > 1 &&
00584       !FnArgs.getElement(FnArgs.getNumElements() - 1) &&
00585       !includeMinimalInlineScopes())
00586     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
00587 }
00588 
00589 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
00590                                                  DIE &ScopeDIE) {
00591   // We create children when the scope DIE is not null.
00592   SmallVector<std::unique_ptr<DIE>, 8> Children;
00593   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
00594 
00595   // Add children
00596   for (auto &I : Children)
00597     ScopeDIE.addChild(std::move(I));
00598 
00599   return ObjectPointer;
00600 }
00601 
00602 void
00603 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
00604   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
00605   if (AbsDef)
00606     return;
00607 
00608   DISubprogram SP(Scope->getScopeNode());
00609 
00610   DIE *ContextDIE;
00611 
00612   if (includeMinimalInlineScopes())
00613     ContextDIE = &getUnitDie();
00614   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
00615   // the important distinction that the DIDescriptor is not associated with the
00616   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
00617   // any). It could be refactored to some common utility function.
00618   else if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
00619     ContextDIE = &getUnitDie();
00620     getOrCreateSubprogramDIE(SPDecl);
00621   } else
00622     ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
00623 
00624   // Passing null as the associated DIDescriptor because the abstract definition
00625   // shouldn't be found by lookup.
00626   AbsDef =
00627       &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
00628   applySubprogramAttributesToDefinition(SP, *AbsDef);
00629 
00630   if (!includeMinimalInlineScopes())
00631     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
00632   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
00633     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
00634 }
00635 
00636 std::unique_ptr<DIE>
00637 DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
00638   assert(Module.Verify() &&
00639          "Use one of the MDNode * overloads to handle invalid metadata");
00640   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
00641   insertDIE(Module, IMDie.get());
00642   DIE *EntityDie;
00643   DIDescriptor Entity = resolve(Module.getEntity());
00644   if (Entity.isNameSpace())
00645     EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
00646   else if (Entity.isSubprogram())
00647     EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
00648   else if (Entity.isType())
00649     EntityDie = getOrCreateTypeDIE(DIType(Entity));
00650   else if (Entity.isGlobalVariable())
00651     EntityDie = getOrCreateGlobalVariableDIE(DIGlobalVariable(Entity));
00652   else
00653     EntityDie = getDIE(Entity);
00654   assert(EntityDie);
00655   addSourceLine(*IMDie, Module.getLineNumber(),
00656                 Module.getContext().getFilename(),
00657                 Module.getContext().getDirectory());
00658   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
00659   StringRef Name = Module.getName();
00660   if (!Name.empty())
00661     addString(*IMDie, dwarf::DW_AT_name, Name);
00662 
00663   return IMDie;
00664 }
00665 
00666 void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
00667   DIE *D = getDIE(SP);
00668   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
00669     if (D)
00670       // If this subprogram has an abstract definition, reference that
00671       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
00672   } else {
00673     if (!D && !includeMinimalInlineScopes())
00674       // Lazily construct the subprogram if we didn't see either concrete or
00675       // inlined versions during codegen. (except in -gmlt ^ where we want
00676       // to omit these entirely)
00677       D = getOrCreateSubprogramDIE(SP);
00678     if (D)
00679       // And attach the attributes
00680       applySubprogramAttributesToDefinition(SP, *D);
00681   }
00682 }
00683 void DwarfCompileUnit::collectDeadVariables(DISubprogram SP) {
00684   assert(SP.isSubprogram() && "CU's subprogram list contains a non-subprogram");
00685   assert(SP.isDefinition() &&
00686          "CU's subprogram list contains a subprogram declaration");
00687   DIArray Variables = SP.getVariables();
00688   if (Variables.getNumElements() == 0)
00689     return;
00690 
00691   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
00692   if (!SPDIE)
00693     SPDIE = getDIE(SP);
00694   assert(SPDIE);
00695   for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
00696     DIVariable DV(Variables.getElement(vi));
00697     assert(DV.isVariable());
00698     DbgVariable NewVar(DV, DIExpression(nullptr), DD);
00699     auto VariableDie = constructVariableDIE(NewVar);
00700     applyVariableAttributes(NewVar, *VariableDie);
00701     SPDIE->addChild(std::move(VariableDie));
00702   }
00703 }
00704 
00705 void DwarfCompileUnit::emitHeader(const MCSymbol *ASectionSym) const {
00706   // Don't bother labeling the .dwo unit, as its offset isn't used.
00707   if (!Skeleton)
00708     Asm->OutStreamer.EmitLabel(LabelBegin);
00709 
00710   DwarfUnit::emitHeader(ASectionSym);
00711 }
00712 
00713 /// addGlobalName - Add a new global name to the compile unit.
00714 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
00715                                      DIScope Context) {
00716   if (includeMinimalInlineScopes())
00717     return;
00718   std::string FullName = getParentContextString(Context) + Name.str();
00719   GlobalNames[FullName] = &Die;
00720 }
00721 
00722 /// Add a new global type to the unit.
00723 void DwarfCompileUnit::addGlobalType(DIType Ty, const DIE &Die,
00724                                      DIScope Context) {
00725   if (includeMinimalInlineScopes())
00726     return;
00727   std::string FullName = getParentContextString(Context) + Ty.getName().str();
00728   GlobalTypes[FullName] = &Die;
00729 }
00730 
00731 /// addVariableAddress - Add DW_AT_location attribute for a
00732 /// DbgVariable based on provided MachineLocation.
00733 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
00734                                           MachineLocation Location) {
00735   if (DV.variableHasComplexAddress())
00736     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
00737   else if (DV.isBlockByrefVariable())
00738     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
00739   else
00740     addAddress(Die, dwarf::DW_AT_location, Location);
00741 }
00742 
00743 /// Add an address attribute to a die based on the location provided.
00744 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
00745                                   const MachineLocation &Location) {
00746   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00747 
00748   bool validReg;
00749   if (Location.isReg())
00750     validReg = addRegisterOpPiece(*Loc, Location.getReg());
00751   else
00752     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
00753 
00754   if (!validReg)
00755     return;
00756 
00757   // Now attach the location information to the DIE.
00758   addBlock(Die, Attribute, Loc);
00759 }
00760 
00761 /// Start with the address based on the location provided, and generate the
00762 /// DWARF information necessary to find the actual variable given the extra
00763 /// address information encoded in the DbgVariable, starting from the starting
00764 /// location.  Add the DWARF information to the die.
00765 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
00766                                          dwarf::Attribute Attribute,
00767                                          const MachineLocation &Location) {
00768   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00769   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
00770   DIExpression Expr = DV.getExpression();
00771   bool ValidReg;
00772   if (Location.getOffset()) {
00773     ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
00774                                                Location.getOffset());
00775     if (ValidReg)
00776       DwarfExpr.AddExpression(Expr);
00777   } else
00778     ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
00779 
00780   // Now attach the location information to the DIE.
00781   if (ValidReg)
00782     addBlock(Die, Attribute, Loc);
00783 }
00784 
00785 /// Add a Dwarf loclistptr attribute data and value.
00786 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
00787                                        unsigned Index) {
00788   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
00789   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00790                                                 : dwarf::DW_FORM_data4;
00791   Die.addValue(Attribute, Form, Value);
00792 }
00793 
00794 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
00795                                                DIE &VariableDie) {
00796   StringRef Name = Var.getName();
00797   if (!Name.empty())
00798     addString(VariableDie, dwarf::DW_AT_name, Name);
00799   addSourceLine(VariableDie, Var.getVariable());
00800   addType(VariableDie, Var.getType());
00801   if (Var.isArtificial())
00802     addFlag(VariableDie, dwarf::DW_AT_artificial);
00803 }
00804 
00805 /// Add a Dwarf expression attribute data and value.
00806 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
00807                                const MCExpr *Expr) {
00808   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
00809   Die.addValue((dwarf::Attribute)0, Form, Value);
00810 }
00811 
00812 void DwarfCompileUnit::applySubprogramAttributesToDefinition(DISubprogram SP,
00813                                                              DIE &SPDie) {
00814   DISubprogram SPDecl = SP.getFunctionDeclaration();
00815   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
00816   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
00817   addGlobalName(SP.getName(), SPDie, Context);
00818 }
00819 
00820 bool DwarfCompileUnit::isDwoUnit() const {
00821   return DD->useSplitDwarf() && Skeleton;
00822 }
00823 
00824 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
00825   return getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly ||
00826          (DD->useSplitDwarf() && !Skeleton);
00827 }
00828 } // end llvm namespace