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