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 an OP to make the debugger do a TLS lookup.
00168       addUInt(*Loc, dwarf::DW_FORM_data1,
00169               DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
00170                                     : dwarf::DW_OP_form_tls_address);
00171     } else {
00172       DD->addArangeLabel(SymbolCU(this, Sym));
00173       addOpAddress(*Loc, Sym);
00174     }
00175 
00176     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00177     // Add the linkage name.
00178     StringRef LinkageName = GV.getLinkageName();
00179     if (!LinkageName.empty())
00180       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
00181       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
00182       // TAG_variable.
00183       addString(*VariableDIE,
00184                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
00185                                            : dwarf::DW_AT_MIPS_linkage_name,
00186                 GlobalValue::getRealLinkageName(LinkageName));
00187   } else if (const ConstantInt *CI =
00188                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
00189     addConstantValue(*VariableDIE, CI, GTy);
00190   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
00191     addToAccelTable = true;
00192     // GV is a merged global.
00193     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00194     Value *Ptr = CE->getOperand(0);
00195     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
00196     DD->addArangeLabel(SymbolCU(this, Sym));
00197     addOpAddress(*Loc, Sym);
00198     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
00199     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
00200     addUInt(*Loc, dwarf::DW_FORM_udata,
00201             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
00202     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
00203     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
00204   }
00205 
00206   if (addToAccelTable) {
00207     DD->addAccelName(GV.getName(), *VariableDIE);
00208 
00209     // If the linkage name is different than the name, go ahead and output
00210     // that as well into the name table.
00211     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
00212       DD->addAccelName(GV.getLinkageName(), *VariableDIE);
00213   }
00214 
00215   addGlobalName(GV.getName(), *VariableDIE, DeclContext);
00216   return VariableDIE;
00217 }
00218 
00219 void DwarfCompileUnit::addRange(RangeSpan Range) {
00220   bool SameAsPrevCU = this == DD->getPrevCU();
00221   DD->setPrevCU(this);
00222   // If we have no current ranges just add the range and return, otherwise,
00223   // check the current section and CU against the previous section and CU we
00224   // emitted into and the subprogram was contained within. If these are the
00225   // same then extend our current range, otherwise add this as a new range.
00226   if (CURanges.empty() || !SameAsPrevCU ||
00227       (&CURanges.back().getEnd()->getSection() !=
00228        &Range.getEnd()->getSection())) {
00229     CURanges.push_back(Range);
00230     return;
00231   }
00232 
00233   CURanges.back().setEnd(Range.getEnd());
00234 }
00235 
00236 void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
00237                                        const MCSymbol *Label,
00238                                        const MCSymbol *Sec) {
00239   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
00240     addLabel(Die, Attribute,
00241              DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00242                                         : dwarf::DW_FORM_data4,
00243              Label);
00244   else
00245     addSectionDelta(Die, Attribute, Label, Sec);
00246 }
00247 
00248 void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
00249   // Define start line table label for each Compile Unit.
00250   MCSymbol *LineTableStartSym =
00251       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
00252 
00253   stmtListIndex = UnitDie.getValues().size();
00254 
00255   // DW_AT_stmt_list is a offset of line number information for this
00256   // compile unit in debug_line section. For split dwarf this is
00257   // left in the skeleton CU and so not included.
00258   // The line table entries are not always emitted in assembly, so it
00259   // is not okay to use line_table_start here.
00260   addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
00261                   DwarfLineSectionSym);
00262 }
00263 
00264 void DwarfCompileUnit::applyStmtList(DIE &D) {
00265   D.addValue(dwarf::DW_AT_stmt_list,
00266              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
00267              UnitDie.getValues()[stmtListIndex]);
00268 }
00269 
00270 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
00271                                        const MCSymbol *End) {
00272   assert(Begin && "Begin label should not be null!");
00273   assert(End && "End label should not be null!");
00274   assert(Begin->isDefined() && "Invalid starting label");
00275   assert(End->isDefined() && "Invalid end label");
00276 
00277   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
00278   if (DD->getDwarfVersion() < 4)
00279     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
00280   else
00281     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
00282 }
00283 
00284 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
00285 // and DW_AT_high_pc attributes. If there are global variables in this
00286 // scope then create and insert DIEs for these variables.
00287 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
00288   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
00289 
00290   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
00291   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
00292           *DD->getCurrentFunction()))
00293     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
00294 
00295   // Only include DW_AT_frame_base in full debug info
00296   if (!includeMinimalInlineScopes()) {
00297     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
00298     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
00299     if (RI->isPhysicalRegister(Location.getReg()))
00300       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
00301   }
00302 
00303   // Add name to the name table, we do this here because we're guaranteed
00304   // to have concrete versions of our DW_TAG_subprogram nodes.
00305   DD->addSubprogramNames(SP, *SPDie);
00306 
00307   return *SPDie;
00308 }
00309 
00310 // Construct a DIE for this scope.
00311 void DwarfCompileUnit::constructScopeDIE(
00312     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
00313   if (!Scope || !Scope->getScopeNode())
00314     return;
00315 
00316   DIScope DS(Scope->getScopeNode());
00317 
00318   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
00319          "Only handle inlined subprograms here, use "
00320          "constructSubprogramScopeDIE for non-inlined "
00321          "subprograms");
00322 
00323   SmallVector<std::unique_ptr<DIE>, 8> Children;
00324 
00325   // We try to create the scope DIE first, then the children DIEs. This will
00326   // avoid creating un-used children then removing them later when we find out
00327   // the scope DIE is null.
00328   std::unique_ptr<DIE> ScopeDIE;
00329   if (Scope->getParent() && DS.isSubprogram()) {
00330     ScopeDIE = constructInlinedScopeDIE(Scope);
00331     if (!ScopeDIE)
00332       return;
00333     // We create children when the scope DIE is not null.
00334     createScopeChildrenDIE(Scope, Children);
00335   } else {
00336     // Early exit when we know the scope DIE is going to be null.
00337     if (DD->isLexicalScopeDIENull(Scope))
00338       return;
00339 
00340     unsigned ChildScopeCount;
00341 
00342     // We create children here when we know the scope DIE is not going to be
00343     // null and the children will be added to the scope DIE.
00344     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
00345 
00346     // Skip imported directives in gmlt-like data.
00347     if (!includeMinimalInlineScopes()) {
00348       // There is no need to emit empty lexical block DIE.
00349       for (const auto &E : DD->findImportedEntitiesForScope(DS))
00350         Children.push_back(
00351             constructImportedEntityDIE(DIImportedEntity(E.second)));
00352     }
00353 
00354     // If there are only other scopes as children, put them directly in the
00355     // parent instead, as this scope would serve no purpose.
00356     if (Children.size() == ChildScopeCount) {
00357       FinalChildren.insert(FinalChildren.end(),
00358                            std::make_move_iterator(Children.begin()),
00359                            std::make_move_iterator(Children.end()));
00360       return;
00361     }
00362     ScopeDIE = constructLexicalScopeDIE(Scope);
00363     assert(ScopeDIE && "Scope DIE should not be null.");
00364   }
00365 
00366   // Add children
00367   for (auto &I : Children)
00368     ScopeDIE->addChild(std::move(I));
00369 
00370   FinalChildren.push_back(std::move(ScopeDIE));
00371 }
00372 
00373 void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
00374                                        const MCSymbol *Hi, const MCSymbol *Lo) {
00375   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
00376   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00377                                                      : dwarf::DW_FORM_data4,
00378                Value);
00379 }
00380 
00381 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
00382                                          SmallVector<RangeSpan, 2> Range) {
00383   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
00384   // emitting it appropriately.
00385   auto *RangeSectionSym = DD->getRangeSectionSym();
00386 
00387   RangeSpanList List(
00388       Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber()),
00389       std::move(Range));
00390 
00391   // Under fission, ranges are specified by constant offsets relative to the
00392   // CU's DW_AT_GNU_ranges_base.
00393   if (isDwoUnit())
00394     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00395                     RangeSectionSym);
00396   else
00397     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
00398                     RangeSectionSym);
00399 
00400   // Add the range list to the set of ranges to be emitted.
00401   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
00402 }
00403 
00404 void DwarfCompileUnit::attachRangesOrLowHighPC(
00405     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
00406   if (Ranges.size() == 1) {
00407     const auto &single = Ranges.front();
00408     attachLowHighPC(Die, single.getStart(), single.getEnd());
00409   } else
00410     addScopeRangeList(Die, std::move(Ranges));
00411 }
00412 
00413 void DwarfCompileUnit::attachRangesOrLowHighPC(
00414     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
00415   SmallVector<RangeSpan, 2> List;
00416   List.reserve(Ranges.size());
00417   for (const InsnRange &R : Ranges)
00418     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
00419                              DD->getLabelAfterInsn(R.second)));
00420   attachRangesOrLowHighPC(Die, std::move(List));
00421 }
00422 
00423 // This scope represents inlined body of a function. Construct DIE to
00424 // represent this concrete inlined copy of the function.
00425 std::unique_ptr<DIE>
00426 DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
00427   assert(Scope->getScopeNode());
00428   DIScope DS(Scope->getScopeNode());
00429   DISubprogram InlinedSP = getDISubprogram(DS);
00430   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
00431   // was inlined from another compile unit.
00432   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
00433   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
00434 
00435   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
00436   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
00437 
00438   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00439 
00440   // Add the call site information to the DIE.
00441   DILocation DL(Scope->getInlinedAt());
00442   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
00443           getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
00444   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
00445 
00446   // Add name to the name table, we do this here because we're guaranteed
00447   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
00448   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
00449 
00450   return ScopeDIE;
00451 }
00452 
00453 // Construct new DW_TAG_lexical_block for this scope and attach
00454 // DW_AT_low_pc/DW_AT_high_pc labels.
00455 std::unique_ptr<DIE>
00456 DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
00457   if (DD->isLexicalScopeDIENull(Scope))
00458     return nullptr;
00459 
00460   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
00461   if (Scope->isAbstractScope())
00462     return ScopeDIE;
00463 
00464   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
00465 
00466   return ScopeDIE;
00467 }
00468 
00469 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
00470 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
00471                                                             bool Abstract) {
00472   auto D = constructVariableDIEImpl(DV, Abstract);
00473   DV.setDIE(*D);
00474   return D;
00475 }
00476 
00477 std::unique_ptr<DIE>
00478 DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
00479                                            bool Abstract) {
00480   // Define variable debug information entry.
00481   auto VariableDie = make_unique<DIE>(DV.getTag());
00482 
00483   if (Abstract) {
00484     applyVariableAttributes(DV, *VariableDie);
00485     return VariableDie;
00486   }
00487 
00488   // Add variable address.
00489 
00490   unsigned Offset = DV.getDotDebugLocOffset();
00491   if (Offset != ~0U) {
00492     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
00493     return VariableDie;
00494   }
00495 
00496   // Check if variable is described by a DBG_VALUE instruction.
00497   if (const MachineInstr *DVInsn = DV.getMInsn()) {
00498     assert(DVInsn->getNumOperands() == 4);
00499     if (DVInsn->getOperand(0).isReg()) {
00500       const MachineOperand RegOp = DVInsn->getOperand(0);
00501       // If the second operand is an immediate, this is an indirect value.
00502       if (DVInsn->getOperand(1).isImm()) {
00503         MachineLocation Location(RegOp.getReg(),
00504                                  DVInsn->getOperand(1).getImm());
00505         addVariableAddress(DV, *VariableDie, Location);
00506       } else if (RegOp.getReg())
00507         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
00508     } else if (DVInsn->getOperand(0).isImm())
00509       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
00510     else if (DVInsn->getOperand(0).isFPImm())
00511       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
00512     else if (DVInsn->getOperand(0).isCImm())
00513       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
00514                        DV.getType());
00515 
00516     return VariableDie;
00517   }
00518 
00519   // .. else use frame index.
00520   if (DV.getFrameIndex().back() == ~0)
00521     return VariableDie;
00522 
00523   auto Expr = DV.getExpression().begin();
00524   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00525   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
00526   for (auto FI : DV.getFrameIndex()) {
00527     unsigned FrameReg = 0;
00528     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
00529     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
00530     assert(Expr != DV.getExpression().end() &&
00531            "Wrong number of expressions");
00532     DwarfExpr.AddMachineRegIndirect(FrameReg, Offset);
00533     DwarfExpr.AddExpression(Expr->begin(), Expr->end());
00534     ++Expr;
00535   }
00536   addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
00537 
00538   return VariableDie;
00539 }
00540 
00541 std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
00542     DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
00543   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
00544   if (DV.isObjectPointer())
00545     ObjectPointer = Var.get();
00546   return Var;
00547 }
00548 
00549 DIE *DwarfCompileUnit::createScopeChildrenDIE(
00550     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
00551     unsigned *ChildScopeCount) {
00552   DIE *ObjectPointer = nullptr;
00553 
00554   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
00555     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
00556 
00557   unsigned ChildCountWithoutScopes = Children.size();
00558 
00559   for (LexicalScope *LS : Scope->getChildren())
00560     constructScopeDIE(LS, Children);
00561 
00562   if (ChildScopeCount)
00563     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
00564 
00565   return ObjectPointer;
00566 }
00567 
00568 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
00569   assert(Scope && Scope->getScopeNode());
00570   assert(!Scope->getInlinedAt());
00571   assert(!Scope->isAbstractScope());
00572   DISubprogram Sub(Scope->getScopeNode());
00573 
00574   assert(Sub.isSubprogram());
00575 
00576   DD->getProcessedSPNodes().insert(Sub);
00577 
00578   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
00579 
00580   // If this is a variadic function, add an unspecified parameter.
00581   DITypeArray FnArgs = Sub.getType().getTypeArray();
00582 
00583   // Collect lexical scope children first.
00584   // ObjectPointer might be a local (non-argument) local variable if it's a
00585   // block's synthetic this pointer.
00586   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
00587     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
00588 
00589   // If we have a single element of null, it is a function that returns void.
00590   // If we have more than one elements and the last one is null, it is a
00591   // variadic function.
00592   if (FnArgs.getNumElements() > 1 &&
00593       !FnArgs.getElement(FnArgs.getNumElements() - 1) &&
00594       !includeMinimalInlineScopes())
00595     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
00596 }
00597 
00598 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
00599                                                  DIE &ScopeDIE) {
00600   // We create children when the scope DIE is not null.
00601   SmallVector<std::unique_ptr<DIE>, 8> Children;
00602   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
00603 
00604   // Add children
00605   for (auto &I : Children)
00606     ScopeDIE.addChild(std::move(I));
00607 
00608   return ObjectPointer;
00609 }
00610 
00611 void
00612 DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
00613   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
00614   if (AbsDef)
00615     return;
00616 
00617   DISubprogram SP(Scope->getScopeNode());
00618 
00619   DIE *ContextDIE;
00620 
00621   if (includeMinimalInlineScopes())
00622     ContextDIE = &getUnitDie();
00623   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
00624   // the important distinction that the DIDescriptor is not associated with the
00625   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
00626   // any). It could be refactored to some common utility function.
00627   else if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
00628     ContextDIE = &getUnitDie();
00629     getOrCreateSubprogramDIE(SPDecl);
00630   } else
00631     ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
00632 
00633   // Passing null as the associated DIDescriptor because the abstract definition
00634   // shouldn't be found by lookup.
00635   AbsDef =
00636       &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
00637   applySubprogramAttributesToDefinition(SP, *AbsDef);
00638 
00639   if (!includeMinimalInlineScopes())
00640     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
00641   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
00642     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
00643 }
00644 
00645 std::unique_ptr<DIE>
00646 DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
00647   assert(Module.Verify() &&
00648          "Use one of the MDNode * overloads to handle invalid metadata");
00649   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
00650   insertDIE(Module, IMDie.get());
00651   DIE *EntityDie;
00652   DIDescriptor Entity = resolve(Module.getEntity());
00653   if (Entity.isNameSpace())
00654     EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
00655   else if (Entity.isSubprogram())
00656     EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
00657   else if (Entity.isType())
00658     EntityDie = getOrCreateTypeDIE(DIType(Entity));
00659   else if (Entity.isGlobalVariable())
00660     EntityDie = getOrCreateGlobalVariableDIE(DIGlobalVariable(Entity));
00661   else
00662     EntityDie = getDIE(Entity);
00663   assert(EntityDie);
00664   addSourceLine(*IMDie, Module.getLineNumber(),
00665                 Module.getContext().getFilename(),
00666                 Module.getContext().getDirectory());
00667   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
00668   StringRef Name = Module.getName();
00669   if (!Name.empty())
00670     addString(*IMDie, dwarf::DW_AT_name, Name);
00671 
00672   return IMDie;
00673 }
00674 
00675 void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
00676   DIE *D = getDIE(SP);
00677   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
00678     if (D)
00679       // If this subprogram has an abstract definition, reference that
00680       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
00681   } else {
00682     if (!D && !includeMinimalInlineScopes())
00683       // Lazily construct the subprogram if we didn't see either concrete or
00684       // inlined versions during codegen. (except in -gmlt ^ where we want
00685       // to omit these entirely)
00686       D = getOrCreateSubprogramDIE(SP);
00687     if (D)
00688       // And attach the attributes
00689       applySubprogramAttributesToDefinition(SP, *D);
00690   }
00691 }
00692 void DwarfCompileUnit::collectDeadVariables(DISubprogram SP) {
00693   assert(SP.isSubprogram() && "CU's subprogram list contains a non-subprogram");
00694   assert(SP.isDefinition() &&
00695          "CU's subprogram list contains a subprogram declaration");
00696   DIArray Variables = SP.getVariables();
00697   if (Variables.getNumElements() == 0)
00698     return;
00699 
00700   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
00701   if (!SPDIE)
00702     SPDIE = getDIE(SP);
00703   assert(SPDIE);
00704   for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
00705     DIVariable DV(Variables.getElement(vi));
00706     assert(DV.isVariable());
00707     DbgVariable NewVar(DV, DIExpression(), DD);
00708     auto VariableDie = constructVariableDIE(NewVar);
00709     applyVariableAttributes(NewVar, *VariableDie);
00710     SPDIE->addChild(std::move(VariableDie));
00711   }
00712 }
00713 
00714 void DwarfCompileUnit::emitHeader(const MCSymbol *ASectionSym) const {
00715   // Don't bother labeling the .dwo unit, as its offset isn't used.
00716   if (!Skeleton)
00717     Asm->OutStreamer.EmitLabel(LabelBegin);
00718 
00719   DwarfUnit::emitHeader(ASectionSym);
00720 }
00721 
00722 /// addGlobalName - Add a new global name to the compile unit.
00723 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
00724                                      DIScope Context) {
00725   if (includeMinimalInlineScopes())
00726     return;
00727   std::string FullName = getParentContextString(Context) + Name.str();
00728   GlobalNames[FullName] = &Die;
00729 }
00730 
00731 /// Add a new global type to the unit.
00732 void DwarfCompileUnit::addGlobalType(DIType Ty, const DIE &Die,
00733                                      DIScope Context) {
00734   if (includeMinimalInlineScopes())
00735     return;
00736   std::string FullName = getParentContextString(Context) + Ty.getName().str();
00737   GlobalTypes[FullName] = &Die;
00738 }
00739 
00740 /// addVariableAddress - Add DW_AT_location attribute for a
00741 /// DbgVariable based on provided MachineLocation.
00742 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
00743                                           MachineLocation Location) {
00744   if (DV.variableHasComplexAddress())
00745     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
00746   else if (DV.isBlockByrefVariable())
00747     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
00748   else
00749     addAddress(Die, dwarf::DW_AT_location, Location);
00750 }
00751 
00752 /// Add an address attribute to a die based on the location provided.
00753 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
00754                                   const MachineLocation &Location) {
00755   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00756 
00757   bool validReg;
00758   if (Location.isReg())
00759     validReg = addRegisterOpPiece(*Loc, Location.getReg());
00760   else
00761     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
00762 
00763   if (!validReg)
00764     return;
00765 
00766   // Now attach the location information to the DIE.
00767   addBlock(Die, Attribute, Loc);
00768 }
00769 
00770 /// Start with the address based on the location provided, and generate the
00771 /// DWARF information necessary to find the actual variable given the extra
00772 /// address information encoded in the DbgVariable, starting from the starting
00773 /// location.  Add the DWARF information to the die.
00774 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
00775                                          dwarf::Attribute Attribute,
00776                                          const MachineLocation &Location) {
00777   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
00778   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
00779   assert(DV.getExpression().size() == 1);
00780   DIExpression Expr = DV.getExpression().back();
00781   bool ValidReg;
00782   if (Location.getOffset()) {
00783     ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
00784                                                Location.getOffset());
00785     if (ValidReg)
00786       DwarfExpr.AddExpression(Expr.begin(), Expr.end());
00787   } else
00788     ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
00789 
00790   // Now attach the location information to the DIE.
00791   if (ValidReg)
00792     addBlock(Die, Attribute, Loc);
00793 }
00794 
00795 /// Add a Dwarf loclistptr attribute data and value.
00796 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
00797                                        unsigned Index) {
00798   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
00799   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
00800                                                 : dwarf::DW_FORM_data4;
00801   Die.addValue(Attribute, Form, Value);
00802 }
00803 
00804 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
00805                                                DIE &VariableDie) {
00806   StringRef Name = Var.getName();
00807   if (!Name.empty())
00808     addString(VariableDie, dwarf::DW_AT_name, Name);
00809   addSourceLine(VariableDie, Var.getVariable());
00810   addType(VariableDie, Var.getType());
00811   if (Var.isArtificial())
00812     addFlag(VariableDie, dwarf::DW_AT_artificial);
00813 }
00814 
00815 /// Add a Dwarf expression attribute data and value.
00816 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
00817                                const MCExpr *Expr) {
00818   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
00819   Die.addValue((dwarf::Attribute)0, Form, Value);
00820 }
00821 
00822 void DwarfCompileUnit::applySubprogramAttributesToDefinition(DISubprogram SP,
00823                                                              DIE &SPDie) {
00824   DISubprogram SPDecl = SP.getFunctionDeclaration();
00825   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
00826   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
00827   addGlobalName(SP.getName(), SPDie, Context);
00828 }
00829 
00830 bool DwarfCompileUnit::isDwoUnit() const {
00831   return DD->useSplitDwarf() && Skeleton;
00832 }
00833 
00834 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
00835   return getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly ||
00836          (DD->useSplitDwarf() && !Skeleton);
00837 }
00838 } // end llvm namespace