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