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