LLVM API Documentation

DwarfCompileUnit.cpp
Go to the documentation of this file.
00001 #include "DwarfCompileUnit.h"
00002 
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/TargetSubtargetInfo.h"
00014 #include "llvm/Target/TargetRegisterInfo.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     addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
00299   }
00300 
00301   // Add name to the name table, we do this here because we're guaranteed
00302   // to have concrete versions of our DW_TAG_subprogram nodes.
00303   DD->addSubprogramNames(SP, *SPDie);
00304 
00305   return *SPDie;
00306 }
00307 
00308 // Construct a DIE for this scope.
00309 void DwarfCompileUnit::constructScopeDIE(
00310     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
00311   if (!Scope || !Scope->getScopeNode())
00312     return;
00313 
00314   DIScope DS(Scope->getScopeNode());
00315 
00316   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
00317          "Only handle inlined subprograms here, use "
00318          "constructSubprogramScopeDIE for non-inlined "
00319          "subprograms");
00320 
00321   SmallVector<std::unique_ptr<DIE>, 8> Children;
00322 
00323   // We try to create the scope DIE first, then the children DIEs. This will
00324   // avoid creating un-used children then removing them later when we find out
00325   // the scope DIE is null.
00326   std::unique_ptr<DIE> ScopeDIE;
00327   if (Scope->getParent() && DS.isSubprogram()) {
00328     ScopeDIE = constructInlinedScopeDIE(Scope);
00329     if (!ScopeDIE)
00330       return;
00331     // We create children when the scope DIE is not null.
00332     createScopeChildrenDIE(Scope, Children);
00333   } else {
00334     // Early exit when we know the scope DIE is going to be null.
00335     if (DD->isLexicalScopeDIENull(Scope))
00336       return;
00337 
00338     unsigned ChildScopeCount;
00339 
00340     // We create children here when we know the scope DIE is not going to be
00341     // null and the children will be added to the scope DIE.
00342     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
00343 
00344     // Skip imported directives in gmlt-like data.
00345     if (!includeMinimalInlineScopes()) {
00346       // There is no need to emit empty lexical block DIE.
00347       for (const auto &E : DD->findImportedEntitiesForScope(DS))
00348         Children.push_back(
00349             constructImportedEntityDIE(DIImportedEntity(E.second)));
00350     }
00351 
00352     // If there are only other scopes as children, put them directly in the
00353     // parent instead, as this scope would serve no purpose.
00354     if (Children.size() == ChildScopeCount) {
00355       FinalChildren.insert(FinalChildren.end(),
00356                            std::make_move_iterator(Children.begin()),
00357                            std::make_move_iterator(Children.end()));
00358       return;
00359     }
00360     ScopeDIE = constructLexicalScopeDIE(Scope);
00361     assert(ScopeDIE && "Scope DIE should not be null.");
00362   }
00363 
00364   // Add children
00365   for (auto &I : Children)
00366     ScopeDIE->addChild(std::move(I));
00367 
00368   FinalChildren.push_back(std::move(ScopeDIE));
00369 }
00370 
00371 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
00372                                        const MCSymbol *Hi, const MCSymbol *Lo) {
00373   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
00374   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00375                                                      : dwarf::DW_FORM_data4,
00376                Value);
00377 }
00378 
00379 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
00380                                          SmallVector<RangeSpan, 2> Range) {
00381   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
00382   // emitting it appropriately.
00383   auto *RangeSectionSym = DD->getRangeSectionSym();
00384 
00385   RangeSpanList List(
00386       Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber()),
00387       std::move(Range));
00388 
00389   // Under fission, ranges are specified by constant offsets relative to the
00390   // CU's DW_AT_GNU_ranges_base.
00391   if (isDwoUnit())
00392     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00393                     RangeSectionSym);
00394   else
00395     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00396                     RangeSectionSym);
00397 
00398   // Add the range list to the set of ranges to be emitted.
00399   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
00400 }
00401 
00402 void DwarfCompileUnit::attachRangesOrLowHighPC(
00403     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
00404   if (Ranges.size() == 1) {
00405     const auto &single = Ranges.front();
00406     attachLowHighPC(Die, single.getStart(), single.getEnd());
00407   } else
00408     addScopeRangeList(Die, std::move(Ranges));
00409 }
00410 
00411 void DwarfCompileUnit::attachRangesOrLowHighPC(
00412     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
00413   SmallVector<RangeSpan, 2> List;
00414   List.reserve(Ranges.size());
00415   for (const InsnRange &R : Ranges)
00416     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
00417                              DD->getLabelAfterInsn(R.second)));
00418   attachRangesOrLowHighPC(Die, std::move(List));
00419 }
00420 
00421 // This scope represents inlined body of a function. Construct DIE to
00422 // represent this concrete inlined copy of the function.
00423 std::unique_ptr<DIE>
00424 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
00425   assert(Scope->getScopeNode());
00426   DIScope DS(Scope->getScopeNode());
00427   DISubprogram InlinedSP = getDISubprogram(DS);
00428   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00429   // was inlined from another compile unit.
00430   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
00431   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
00432 
00433   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
00434   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
00435 
00436   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00437 
00438   // Add the call site information to the DIE.
00439   DILocation DL(Scope->getInlinedAt());
00440   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
00441           getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
00442   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
00443 
00444   // Add name to the name table, we do this here because we're guaranteed
00445   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
00446   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
00447 
00448   return ScopeDIE;
00449 }
00450 
00451 // Construct new DW_TAG_lexical_block for this scope and attach
00452 // DW_AT_low_pc/DW_AT_high_pc labels.
00453 std::unique_ptr<DIE>
00454 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
00455   if (DD->isLexicalScopeDIENull(Scope))
00456     return nullptr;
00457 
00458   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
00459   if (Scope->isAbstractScope())
00460     return ScopeDIE;
00461 
00462   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00463 
00464   return ScopeDIE;
00465 }
00466 
00467 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
00468 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
00469                                                             bool Abstract) {
00470   auto D = constructVariableDIEImpl(DV, Abstract);
00471   DV.setDIE(*D);
00472   return D;
00473 }
00474 
00475 std::unique_ptr<DIE>
00476 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
00477                                            bool Abstract) {
00478   // Define variable debug information entry.
00479   auto VariableDie = make_unique<DIE>(DV.getTag());
00480 
00481   if (Abstract) {
00482     applyVariableAttributes(DV, *VariableDie);
00483     return VariableDie;
00484   }
00485 
00486   // Add variable address.
00487 
00488   unsigned Offset = DV.getDotDebugLocOffset();
00489   if (Offset != ~0U) {
00490     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
00491     return VariableDie;
00492   }
00493 
00494   // Check if variable is described by a DBG_VALUE instruction.
00495   if (const MachineInstr *DVInsn = DV.getMInsn()) {
00496     assert(DVInsn->getNumOperands() == 4);
00497     if (DVInsn->getOperand(0).isReg()) {
00498       const MachineOperand RegOp = DVInsn->getOperand(0);
00499       // If the second operand is an immediate, this is an indirect value.
00500       if (DVInsn->getOperand(1).isImm()) {
00501         MachineLocation Location(RegOp.getReg(),
00502                                  DVInsn->getOperand(1).getImm());
00503         addVariableAddress(DV, *VariableDie, Location);
00504       } else if (RegOp.getReg())
00505         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
00506     } else if (DVInsn->getOperand(0).isImm())
00507       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
00508     else if (DVInsn->getOperand(0).isFPImm())
00509       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
00510     else if (DVInsn->getOperand(0).isCImm())
00511       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
00512                        DV.getType());
00513 
00514     return VariableDie;
00515   }
00516 
00517   // .. else use frame index.
00518   int FI = DV.getFrameIndex();
00519   if (FI != ~0) {
00520     unsigned FrameReg = 0;
00521     const TargetFrameLowering *TFI =
00522         Asm->TM.getSubtargetImpl()->getFrameLowering();
00523     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
00524     MachineLocation Location(FrameReg, Offset);
00525     addVariableAddress(DV, *VariableDie, Location);
00526   }
00527 
00528   return VariableDie;
00529 }
00530 
00531 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
00532     DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
00533   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
00534   if (DV.isObjectPointer())
00535     ObjectPointer = Var.get();
00536   return Var;
00537 }
00538 
00539 DIE *DwarfCompileUnit::createScopeChildrenDIE(
00540     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
00541     unsigned *ChildScopeCount) {
00542   DIE *ObjectPointer = nullptr;
00543 
00544   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
00545     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
00546 
00547   unsigned ChildCountWithoutScopes = Children.size();
00548 
00549   for (LexicalScope *LS : Scope->getChildren())
00550     constructScopeDIE(LS, Children);
00551 
00552   if (ChildScopeCount)
00553     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
00554 
00555   return ObjectPointer;
00556 }
00557 
00558 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
00559   assert(Scope && Scope->getScopeNode());
00560   assert(!Scope->getInlinedAt());
00561   assert(!Scope->isAbstractScope());
00562   DISubprogram Sub(Scope->getScopeNode());
00563 
00564   assert(Sub.isSubprogram());
00565 
00566   DD->getProcessedSPNodes().insert(Sub);
00567 
00568   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
00569 
00570   // If this is a variadic function, add an unspecified parameter.
00571   DITypeArray FnArgs = Sub.getType().getTypeArray();
00572 
00573   // Collect lexical scope children first.
00574   // ObjectPointer might be a local (non-argument) local variable if it's a
00575   // block's synthetic this pointer.
00576   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
00577     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
00578 
00579   // If we have a single element of null, it is a function that returns void.
00580   // If we have more than one elements and the last one is null, it is a
00581   // variadic function.
00582   if (FnArgs.getNumElements() > 1 &&
00583       !FnArgs.getElement(FnArgs.getNumElements() - 1) &&
00584       !includeMinimalInlineScopes())
00585     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
00586 }
00587 
00588 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
00589                                                  DIE &ScopeDIE) {
00590   // We create children when the scope DIE is not null.
00591   SmallVector<std::unique_ptr<DIE>, 8> Children;
00592   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
00593 
00594   // Add children
00595   for (auto &I : Children)
00596     ScopeDIE.addChild(std::move(I));
00597 
00598   return ObjectPointer;
00599 }
00600 
00601 void
00602 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
00603   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
00604   if (AbsDef)
00605     return;
00606 
00607   DISubprogram SP(Scope->getScopeNode());
00608 
00609   DIE *ContextDIE;
00610 
00611   if (includeMinimalInlineScopes())
00612     ContextDIE = &getUnitDie();
00613   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
00614   // the important distinction that the DIDescriptor is not associated with the
00615   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
00616   // any). It could be refactored to some common utility function.
00617   else if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
00618     ContextDIE = &getUnitDie();
00619     getOrCreateSubprogramDIE(SPDecl);
00620   } else
00621     ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
00622 
00623   // Passing null as the associated DIDescriptor because the abstract definition
00624   // shouldn't be found by lookup.
00625   AbsDef =
00626       &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
00627   applySubprogramAttributesToDefinition(SP, *AbsDef);
00628 
00629   if (!includeMinimalInlineScopes())
00630     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
00631   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
00632     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
00633 }
00634 
00635 std::unique_ptr<DIE>
00636 DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
00637   assert(Module.Verify() &&
00638          "Use one of the MDNode * overloads to handle invalid metadata");
00639   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
00640   insertDIE(Module, IMDie.get());
00641   DIE *EntityDie;
00642   DIDescriptor Entity = resolve(Module.getEntity());
00643   if (Entity.isNameSpace())
00644     EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
00645   else if (Entity.isSubprogram())
00646     EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
00647   else if (Entity.isType())
00648     EntityDie = getOrCreateTypeDIE(DIType(Entity));
00649   else if (Entity.isGlobalVariable())
00650     EntityDie = getOrCreateGlobalVariableDIE(DIGlobalVariable(Entity));
00651   else
00652     EntityDie = getDIE(Entity);
00653   assert(EntityDie);
00654   addSourceLine(*IMDie, Module.getLineNumber(),
00655                 Module.getContext().getFilename(),
00656                 Module.getContext().getDirectory());
00657   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
00658   StringRef Name = Module.getName();
00659   if (!Name.empty())
00660     addString(*IMDie, dwarf::DW_AT_name, Name);
00661 
00662   return IMDie;
00663 }
00664 
00665 void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
00666   DIE *D = getDIE(SP);
00667   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
00668     if (D)
00669       // If this subprogram has an abstract definition, reference that
00670       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
00671   } else {
00672     if (!D && !includeMinimalInlineScopes())
00673       // Lazily construct the subprogram if we didn't see either concrete or
00674       // inlined versions during codegen. (except in -gmlt ^ where we want
00675       // to omit these entirely)
00676       D = getOrCreateSubprogramDIE(SP);
00677     if (D)
00678       // And attach the attributes
00679       applySubprogramAttributesToDefinition(SP, *D);
00680   }
00681 }
00682 void DwarfCompileUnit::collectDeadVariables(DISubprogram SP) {
00683   assert(SP.isSubprogram() && "CU's subprogram list contains a non-subprogram");
00684   assert(SP.isDefinition() &&
00685          "CU's subprogram list contains a subprogram declaration");
00686   DIArray Variables = SP.getVariables();
00687   if (Variables.getNumElements() == 0)
00688     return;
00689 
00690   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
00691   if (!SPDIE)
00692     SPDIE = getDIE(SP);
00693   assert(SPDIE);
00694   for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
00695     DIVariable DV(Variables.getElement(vi));
00696     assert(DV.isVariable());
00697     DbgVariable NewVar(DV, DIExpression(nullptr), DD);
00698     auto VariableDie = constructVariableDIE(NewVar);
00699     applyVariableAttributes(NewVar, *VariableDie);
00700     SPDIE->addChild(std::move(VariableDie));
00701   }
00702 }
00703 
00704 void DwarfCompileUnit::emitHeader(const MCSymbol *ASectionSym) const {
00705   // Don't bother labeling the .dwo unit, as its offset isn't used.
00706   if (!Skeleton)
00707     Asm->OutStreamer.EmitLabel(LabelBegin);
00708 
00709   DwarfUnit::emitHeader(ASectionSym);
00710 }
00711 
00712 /// addGlobalName - Add a new global name to the compile unit.
00713 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
00714                                      DIScope Context) {
00715   if (includeMinimalInlineScopes())
00716     return;
00717   std::string FullName = getParentContextString(Context) + Name.str();
00718   GlobalNames[FullName] = &Die;
00719 }
00720 
00721 /// Add a new global type to the unit.
00722 void DwarfCompileUnit::addGlobalType(DIType Ty, const DIE &Die,
00723                                      DIScope Context) {
00724   if (includeMinimalInlineScopes())
00725     return;
00726   std::string FullName = getParentContextString(Context) + Ty.getName().str();
00727   GlobalTypes[FullName] = &Die;
00728 }
00729 
00730 /// addVariableAddress - Add DW_AT_location attribute for a
00731 /// DbgVariable based on provided MachineLocation.
00732 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
00733                                           MachineLocation Location) {
00734   if (DV.variableHasComplexAddress())
00735     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
00736   else if (DV.isBlockByrefVariable())
00737     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
00738   else
00739     addAddress(Die, dwarf::DW_AT_location, Location,
00740                DV.getVariable().isIndirect());
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                                   bool Indirect) {
00747   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00748 
00749   if (Location.isReg() && !Indirect)
00750     addRegisterOpPiece(*Loc, Location.getReg());
00751   else {
00752     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
00753     if (Indirect && !Location.isReg()) {
00754       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
00755     }
00756   }
00757 
00758   // Now attach the location information to the DIE.
00759   addBlock(Die, Attribute, Loc);
00760 }
00761 
00762 /// Start with the address based on the location provided, and generate the
00763 /// DWARF information necessary to find the actual variable given the extra
00764 /// address information encoded in the DbgVariable, starting from the starting
00765 /// location.  Add the DWARF information to the die.
00766 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
00767                                          dwarf::Attribute Attribute,
00768                                          const MachineLocation &Location) {
00769   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00770   unsigned N = DV.getNumAddrElements();
00771   unsigned i = 0;
00772   if (Location.isReg()) {
00773     if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_plus) {
00774       assert(!DV.getVariable().isIndirect() &&
00775              "double indirection not handled");
00776       // If first address element is OpPlus then emit
00777       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
00778       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
00779       i = 2;
00780     } else if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_deref) {
00781       assert(!DV.getVariable().isIndirect() &&
00782              "double indirection not handled");
00783       addRegisterOpPiece(*Loc, Location.getReg(),
00784                          DV.getExpression().getPieceSize(),
00785                          DV.getExpression().getPieceOffset());
00786       i = 3;
00787     } else
00788       addRegisterOpPiece(*Loc, Location.getReg());
00789   } else
00790     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
00791 
00792   for (; i < N; ++i) {
00793     uint64_t Element = DV.getAddrElement(i);
00794     if (Element == dwarf::DW_OP_plus) {
00795       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
00796       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
00797 
00798     } else if (Element == dwarf::DW_OP_deref) {
00799       if (!Location.isReg())
00800         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
00801 
00802     } else if (Element == dwarf::DW_OP_piece) {
00803       const unsigned SizeOfByte = 8;
00804       unsigned PieceOffsetInBits = DV.getAddrElement(++i) * SizeOfByte;
00805       unsigned PieceSizeInBits = DV.getAddrElement(++i) * SizeOfByte;
00806       // Emit DW_OP_bit_piece Size Offset.
00807       assert(PieceSizeInBits > 0 && "piece has zero size");
00808       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
00809       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
00810       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
00811     } else
00812       llvm_unreachable("unknown DIBuilder Opcode");
00813   }
00814 
00815   // Now attach the location information to the DIE.
00816   addBlock(Die, Attribute, Loc);
00817 }
00818 
00819 /// Add a Dwarf loclistptr attribute data and value.
00820 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
00821                                        unsigned Index) {
00822   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
00823   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00824                                                 : dwarf::DW_FORM_data4;
00825   Die.addValue(Attribute, Form, Value);
00826 }
00827 
00828 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
00829                                                DIE &VariableDie) {
00830   StringRef Name = Var.getName();
00831   if (!Name.empty())
00832     addString(VariableDie, dwarf::DW_AT_name, Name);
00833   addSourceLine(VariableDie, Var.getVariable());
00834   addType(VariableDie, Var.getType());
00835   if (Var.isArtificial())
00836     addFlag(VariableDie, dwarf::DW_AT_artificial);
00837 }
00838 
00839 /// Add a Dwarf expression attribute data and value.
00840 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
00841                                const MCExpr *Expr) {
00842   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
00843   Die.addValue((dwarf::Attribute)0, Form, Value);
00844 }
00845 
00846 void DwarfCompileUnit::applySubprogramAttributesToDefinition(DISubprogram SP,
00847                                                              DIE &SPDie) {
00848   DISubprogram SPDecl = SP.getFunctionDeclaration();
00849   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
00850   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
00851   addGlobalName(SP.getName(), SPDie, Context);
00852 }
00853 
00854 bool DwarfCompileUnit::isDwoUnit() const {
00855   return DD->useSplitDwarf() && Skeleton;
00856 }
00857 
00858 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
00859   return getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly ||
00860          (DD->useSplitDwarf() && !Skeleton);
00861 }
00862 } // end llvm namespace