DwarfCompileUnit.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. #include "DwarfCompileUnit.h"
  2. #include "DwarfExpression.h"
  3. #include "llvm/CodeGen/MachineFunction.h"
  4. #include "llvm/IR/DataLayout.h"
  5. #include "llvm/IR/GlobalValue.h"
  6. #include "llvm/IR/GlobalVariable.h"
  7. #include "llvm/IR/Instruction.h"
  8. #include "llvm/MC/MCAsmInfo.h"
  9. #include "llvm/MC/MCStreamer.h"
  10. #include "llvm/Target/TargetFrameLowering.h"
  11. #include "llvm/Target/TargetLoweringObjectFile.h"
  12. #include "llvm/Target/TargetMachine.h"
  13. #include "llvm/Target/TargetRegisterInfo.h"
  14. #include "llvm/Target/TargetSubtargetInfo.h"
  15. namespace llvm {
  16. DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
  17. AsmPrinter *A, DwarfDebug *DW,
  18. DwarfFile *DWU)
  19. : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU),
  20. Skeleton(nullptr), LabelBegin(nullptr), BaseAddress(nullptr) {
  21. insertDIE(Node, &getUnitDie());
  22. }
  23. /// addLabelAddress - Add a dwarf label attribute data and value using
  24. /// DW_FORM_addr or DW_FORM_GNU_addr_index.
  25. ///
  26. void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
  27. const MCSymbol *Label) {
  28. // Don't use the address pool in non-fission or in the skeleton unit itself.
  29. // FIXME: Once GDB supports this, it's probably worthwhile using the address
  30. // pool from the skeleton - maybe even in non-fission (possibly fewer
  31. // relocations by sharing them in the pool, but we have other ideas about how
  32. // to reduce the number of relocations as well/instead).
  33. if (!DD->useSplitDwarf() || !Skeleton)
  34. return addLocalLabelAddress(Die, Attribute, Label);
  35. if (Label)
  36. DD->addArangeLabel(SymbolCU(this, Label));
  37. unsigned idx = DD->getAddressPool().getIndex(Label);
  38. DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
  39. Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
  40. }
  41. void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
  42. dwarf::Attribute Attribute,
  43. const MCSymbol *Label) {
  44. if (Label)
  45. DD->addArangeLabel(SymbolCU(this, Label));
  46. Die.addValue(Attribute, dwarf::DW_FORM_addr,
  47. Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
  48. : new (DIEValueAllocator) DIEInteger(0));
  49. }
  50. unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
  51. StringRef DirName) {
  52. // If we print assembly, we can't separate .file entries according to
  53. // compile units. Thus all files will belong to the default compile unit.
  54. // FIXME: add a better feature test than hasRawTextSupport. Even better,
  55. // extend .file to support this.
  56. return Asm->OutStreamer.EmitDwarfFileDirective(
  57. 0, DirName, FileName,
  58. Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
  59. }
  60. // Return const expression if value is a GEP to access merged global
  61. // constant. e.g.
  62. // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
  63. static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
  64. const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
  65. if (!CE || CE->getNumOperands() != 3 ||
  66. CE->getOpcode() != Instruction::GetElementPtr)
  67. return nullptr;
  68. // First operand points to a global struct.
  69. Value *Ptr = CE->getOperand(0);
  70. if (!isa<GlobalValue>(Ptr) ||
  71. !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
  72. return nullptr;
  73. // Second operand is zero.
  74. const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
  75. if (!CI || !CI->isZero())
  76. return nullptr;
  77. // Third operand is offset.
  78. if (!isa<ConstantInt>(CE->getOperand(2)))
  79. return nullptr;
  80. return CE;
  81. }
  82. /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
  83. DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
  84. // Check for pre-existence.
  85. if (DIE *Die = getDIE(GV))
  86. return Die;
  87. assert(GV.isGlobalVariable());
  88. DIScope GVContext = GV.getContext();
  89. DIType GTy = DD->resolve(GV.getType());
  90. // Construct the context before querying for the existence of the DIE in
  91. // case such construction creates the DIE.
  92. DIE *ContextDIE = getOrCreateContextDIE(GVContext);
  93. // Add to map.
  94. DIE *VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
  95. DIScope DeclContext;
  96. if (DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration()) {
  97. DeclContext = resolve(SDMDecl.getContext());
  98. assert(SDMDecl.isStaticMember() && "Expected static member decl");
  99. assert(GV.isDefinition());
  100. // We need the declaration DIE that is in the static member's class.
  101. DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
  102. addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
  103. } else {
  104. DeclContext = GV.getContext();
  105. // Add name and type.
  106. addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
  107. addType(*VariableDIE, GTy);
  108. // Add scoping info.
  109. if (!GV.isLocalToUnit())
  110. addFlag(*VariableDIE, dwarf::DW_AT_external);
  111. // Add line number info.
  112. addSourceLine(*VariableDIE, GV);
  113. }
  114. if (!GV.isDefinition())
  115. addFlag(*VariableDIE, dwarf::DW_AT_declaration);
  116. // Add location.
  117. bool addToAccelTable = false;
  118. bool isGlobalVariable = GV.getGlobal() != nullptr;
  119. if (isGlobalVariable) {
  120. addToAccelTable = true;
  121. DIELoc *Loc = new (DIEValueAllocator) DIELoc();
  122. const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
  123. if (GV.getGlobal()->isThreadLocal()) {
  124. // FIXME: Make this work with -gsplit-dwarf.
  125. unsigned PointerSize = Asm->getDataLayout().getPointerSize();
  126. assert((PointerSize == 4 || PointerSize == 8) &&
  127. "Add support for other sizes if necessary");
  128. // Based on GCC's support for TLS:
  129. if (!DD->useSplitDwarf()) {
  130. // 1) Start with a constNu of the appropriate pointer size
  131. addUInt(*Loc, dwarf::DW_FORM_data1,
  132. PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
  133. // 2) containing the (relocated) offset of the TLS variable
  134. // within the module's TLS block.
  135. addExpr(*Loc, dwarf::DW_FORM_udata,
  136. Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
  137. } else {
  138. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
  139. addUInt(*Loc, dwarf::DW_FORM_udata,
  140. DD->getAddressPool().getIndex(Sym, /* TLS */ true));
  141. }
  142. // 3) followed by a custom OP to make the debugger do a TLS lookup.
  143. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
  144. } else {
  145. DD->addArangeLabel(SymbolCU(this, Sym));
  146. addOpAddress(*Loc, Sym);
  147. }
  148. addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
  149. // Add the linkage name.
  150. StringRef LinkageName = GV.getLinkageName();
  151. if (!LinkageName.empty())
  152. // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
  153. // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
  154. // TAG_variable.
  155. addString(*VariableDIE,
  156. DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
  157. : dwarf::DW_AT_MIPS_linkage_name,
  158. GlobalValue::getRealLinkageName(LinkageName));
  159. } else if (const ConstantInt *CI =
  160. dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
  161. addConstantValue(*VariableDIE, CI, GTy);
  162. } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
  163. addToAccelTable = true;
  164. // GV is a merged global.
  165. DIELoc *Loc = new (DIEValueAllocator) DIELoc();
  166. Value *Ptr = CE->getOperand(0);
  167. MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
  168. DD->addArangeLabel(SymbolCU(this, Sym));
  169. addOpAddress(*Loc, Sym);
  170. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
  171. SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
  172. addUInt(*Loc, dwarf::DW_FORM_udata,
  173. Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
  174. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
  175. addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
  176. }
  177. if (addToAccelTable) {
  178. DD->addAccelName(GV.getName(), *VariableDIE);
  179. // If the linkage name is different than the name, go ahead and output
  180. // that as well into the name table.
  181. if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
  182. DD->addAccelName(GV.getLinkageName(), *VariableDIE);
  183. }
  184. addGlobalName(GV.getName(), *VariableDIE, DeclContext);
  185. return VariableDIE;
  186. }
  187. void DwarfCompileUnit::addRange(RangeSpan Range) {
  188. bool SameAsPrevCU = this == DD->getPrevCU();
  189. DD->setPrevCU(this);
  190. // If we have no current ranges just add the range and return, otherwise,
  191. // check the current section and CU against the previous section and CU we
  192. // emitted into and the subprogram was contained within. If these are the
  193. // same then extend our current range, otherwise add this as a new range.
  194. if (CURanges.empty() || !SameAsPrevCU ||
  195. (&CURanges.back().getEnd()->getSection() !=
  196. &Range.getEnd()->getSection())) {
  197. CURanges.push_back(Range);
  198. return;
  199. }
  200. CURanges.back().setEnd(Range.getEnd());
  201. }
  202. void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
  203. const MCSymbol *Label,
  204. const MCSymbol *Sec) {
  205. if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
  206. addLabel(Die, Attribute,
  207. DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  208. : dwarf::DW_FORM_data4,
  209. Label);
  210. else
  211. addSectionDelta(Die, Attribute, Label, Sec);
  212. }
  213. void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
  214. // Define start line table label for each Compile Unit.
  215. MCSymbol *LineTableStartSym =
  216. Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
  217. stmtListIndex = UnitDie.getValues().size();
  218. // DW_AT_stmt_list is a offset of line number information for this
  219. // compile unit in debug_line section. For split dwarf this is
  220. // left in the skeleton CU and so not included.
  221. // The line table entries are not always emitted in assembly, so it
  222. // is not okay to use line_table_start here.
  223. addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
  224. DwarfLineSectionSym);
  225. }
  226. void DwarfCompileUnit::applyStmtList(DIE &D) {
  227. D.addValue(dwarf::DW_AT_stmt_list,
  228. UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
  229. UnitDie.getValues()[stmtListIndex]);
  230. }
  231. void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
  232. const MCSymbol *End) {
  233. assert(Begin && "Begin label should not be null!");
  234. assert(End && "End label should not be null!");
  235. assert(Begin->isDefined() && "Invalid starting label");
  236. assert(End->isDefined() && "Invalid end label");
  237. addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
  238. if (DD->getDwarfVersion() < 4)
  239. addLabelAddress(D, dwarf::DW_AT_high_pc, End);
  240. else
  241. addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
  242. }
  243. // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
  244. // and DW_AT_high_pc attributes. If there are global variables in this
  245. // scope then create and insert DIEs for these variables.
  246. DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
  247. DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
  248. attachLowHighPC(*SPDie, DD->getFunctionBeginSym(), DD->getFunctionEndSym());
  249. if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
  250. *DD->getCurrentFunction()))
  251. addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
  252. // Only include DW_AT_frame_base in full debug info
  253. if (!includeMinimalInlineScopes()) {
  254. const TargetRegisterInfo *RI =
  255. Asm->TM.getSubtargetImpl()->getRegisterInfo();
  256. MachineLocation Location(RI->getFrameRegister(*Asm->MF));
  257. if (RI->isPhysicalRegister(Location.getReg()))
  258. addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
  259. }
  260. // Add name to the name table, we do this here because we're guaranteed
  261. // to have concrete versions of our DW_TAG_subprogram nodes.
  262. DD->addSubprogramNames(SP, *SPDie);
  263. return *SPDie;
  264. }
  265. // Construct a DIE for this scope.
  266. void DwarfCompileUnit::constructScopeDIE(
  267. LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
  268. if (!Scope || !Scope->getScopeNode())
  269. return;
  270. DIScope DS(Scope->getScopeNode());
  271. assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
  272. "Only handle inlined subprograms here, use "
  273. "constructSubprogramScopeDIE for non-inlined "
  274. "subprograms");
  275. SmallVector<std::unique_ptr<DIE>, 8> Children;
  276. // We try to create the scope DIE first, then the children DIEs. This will
  277. // avoid creating un-used children then removing them later when we find out
  278. // the scope DIE is null.
  279. std::unique_ptr<DIE> ScopeDIE;
  280. if (Scope->getParent() && DS.isSubprogram()) {
  281. ScopeDIE = constructInlinedScopeDIE(Scope);
  282. if (!ScopeDIE)
  283. return;
  284. // We create children when the scope DIE is not null.
  285. createScopeChildrenDIE(Scope, Children);
  286. } else {
  287. // Early exit when we know the scope DIE is going to be null.
  288. if (DD->isLexicalScopeDIENull(Scope))
  289. return;
  290. unsigned ChildScopeCount;
  291. // We create children here when we know the scope DIE is not going to be
  292. // null and the children will be added to the scope DIE.
  293. createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
  294. // Skip imported directives in gmlt-like data.
  295. if (!includeMinimalInlineScopes()) {
  296. // There is no need to emit empty lexical block DIE.
  297. for (const auto &E : DD->findImportedEntitiesForScope(DS))
  298. Children.push_back(
  299. constructImportedEntityDIE(DIImportedEntity(E.second)));
  300. }
  301. // If there are only other scopes as children, put them directly in the
  302. // parent instead, as this scope would serve no purpose.
  303. if (Children.size() == ChildScopeCount) {
  304. FinalChildren.insert(FinalChildren.end(),
  305. std::make_move_iterator(Children.begin()),
  306. std::make_move_iterator(Children.end()));
  307. return;
  308. }
  309. ScopeDIE = constructLexicalScopeDIE(Scope);
  310. assert(ScopeDIE && "Scope DIE should not be null.");
  311. }
  312. // Add children
  313. for (auto &I : Children)
  314. ScopeDIE->addChild(std::move(I));
  315. FinalChildren.push_back(std::move(ScopeDIE));
  316. }
  317. void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
  318. const MCSymbol *Hi, const MCSymbol *Lo) {
  319. DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
  320. Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  321. : dwarf::DW_FORM_data4,
  322. Value);
  323. }
  324. void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
  325. SmallVector<RangeSpan, 2> Range) {
  326. // Emit offset in .debug_range as a relocatable label. emitDIE will handle
  327. // emitting it appropriately.
  328. auto *RangeSectionSym = DD->getRangeSectionSym();
  329. RangeSpanList List(
  330. Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber()),
  331. std::move(Range));
  332. // Under fission, ranges are specified by constant offsets relative to the
  333. // CU's DW_AT_GNU_ranges_base.
  334. if (isDwoUnit())
  335. addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  336. RangeSectionSym);
  337. else
  338. addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
  339. RangeSectionSym);
  340. // Add the range list to the set of ranges to be emitted.
  341. (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
  342. }
  343. void DwarfCompileUnit::attachRangesOrLowHighPC(
  344. DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
  345. if (Ranges.size() == 1) {
  346. const auto &single = Ranges.front();
  347. attachLowHighPC(Die, single.getStart(), single.getEnd());
  348. } else
  349. addScopeRangeList(Die, std::move(Ranges));
  350. }
  351. void DwarfCompileUnit::attachRangesOrLowHighPC(
  352. DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
  353. SmallVector<RangeSpan, 2> List;
  354. List.reserve(Ranges.size());
  355. for (const InsnRange &R : Ranges)
  356. List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
  357. DD->getLabelAfterInsn(R.second)));
  358. attachRangesOrLowHighPC(Die, std::move(List));
  359. }
  360. // This scope represents inlined body of a function. Construct DIE to
  361. // represent this concrete inlined copy of the function.
  362. std::unique_ptr<DIE>
  363. DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
  364. assert(Scope->getScopeNode());
  365. DIScope DS(Scope->getScopeNode());
  366. DISubprogram InlinedSP = getDISubprogram(DS);
  367. // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
  368. // was inlined from another compile unit.
  369. DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
  370. assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
  371. auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
  372. addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
  373. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  374. // Add the call site information to the DIE.
  375. DILocation DL(Scope->getInlinedAt());
  376. addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
  377. getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
  378. addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
  379. // Add name to the name table, we do this here because we're guaranteed
  380. // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
  381. DD->addSubprogramNames(InlinedSP, *ScopeDIE);
  382. return ScopeDIE;
  383. }
  384. // Construct new DW_TAG_lexical_block for this scope and attach
  385. // DW_AT_low_pc/DW_AT_high_pc labels.
  386. std::unique_ptr<DIE>
  387. DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
  388. if (DD->isLexicalScopeDIENull(Scope))
  389. return nullptr;
  390. auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
  391. if (Scope->isAbstractScope())
  392. return ScopeDIE;
  393. attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
  394. return ScopeDIE;
  395. }
  396. /// constructVariableDIE - Construct a DIE for the given DbgVariable.
  397. std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
  398. bool Abstract) {
  399. auto D = constructVariableDIEImpl(DV, Abstract);
  400. DV.setDIE(*D);
  401. return D;
  402. }
  403. std::unique_ptr<DIE>
  404. DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
  405. bool Abstract) {
  406. // Define variable debug information entry.
  407. auto VariableDie = make_unique<DIE>(DV.getTag());
  408. if (Abstract) {
  409. applyVariableAttributes(DV, *VariableDie);
  410. return VariableDie;
  411. }
  412. // Add variable address.
  413. unsigned Offset = DV.getDotDebugLocOffset();
  414. if (Offset != ~0U) {
  415. addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
  416. return VariableDie;
  417. }
  418. // Check if variable is described by a DBG_VALUE instruction.
  419. if (const MachineInstr *DVInsn = DV.getMInsn()) {
  420. assert(DVInsn->getNumOperands() == 4);
  421. if (DVInsn->getOperand(0).isReg()) {
  422. const MachineOperand RegOp = DVInsn->getOperand(0);
  423. // If the second operand is an immediate, this is an indirect value.
  424. if (DVInsn->getOperand(1).isImm()) {
  425. MachineLocation Location(RegOp.getReg(),
  426. DVInsn->getOperand(1).getImm());
  427. addVariableAddress(DV, *VariableDie, Location);
  428. } else if (RegOp.getReg())
  429. addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
  430. } else if (DVInsn->getOperand(0).isImm())
  431. addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
  432. else if (DVInsn->getOperand(0).isFPImm())
  433. addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
  434. else if (DVInsn->getOperand(0).isCImm())
  435. addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
  436. DV.getType());
  437. return VariableDie;
  438. }
  439. // .. else use frame index.
  440. int FI = DV.getFrameIndex();
  441. if (FI != ~0) {
  442. unsigned FrameReg = 0;
  443. const TargetFrameLowering *TFI =
  444. Asm->TM.getSubtargetImpl()->getFrameLowering();
  445. int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
  446. MachineLocation Location(FrameReg, Offset);
  447. addVariableAddress(DV, *VariableDie, Location);
  448. }
  449. return VariableDie;
  450. }
  451. std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
  452. DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
  453. auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
  454. if (DV.isObjectPointer())
  455. ObjectPointer = Var.get();
  456. return Var;
  457. }
  458. DIE *DwarfCompileUnit::createScopeChildrenDIE(
  459. LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
  460. unsigned *ChildScopeCount) {
  461. DIE *ObjectPointer = nullptr;
  462. for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
  463. Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
  464. unsigned ChildCountWithoutScopes = Children.size();
  465. for (LexicalScope *LS : Scope->getChildren())
  466. constructScopeDIE(LS, Children);
  467. if (ChildScopeCount)
  468. *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
  469. return ObjectPointer;
  470. }
  471. void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
  472. assert(Scope && Scope->getScopeNode());
  473. assert(!Scope->getInlinedAt());
  474. assert(!Scope->isAbstractScope());
  475. DISubprogram Sub(Scope->getScopeNode());
  476. assert(Sub.isSubprogram());
  477. DD->getProcessedSPNodes().insert(Sub);
  478. DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
  479. // If this is a variadic function, add an unspecified parameter.
  480. DITypeArray FnArgs = Sub.getType().getTypeArray();
  481. // Collect lexical scope children first.
  482. // ObjectPointer might be a local (non-argument) local variable if it's a
  483. // block's synthetic this pointer.
  484. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
  485. addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
  486. // If we have a single element of null, it is a function that returns void.
  487. // If we have more than one elements and the last one is null, it is a
  488. // variadic function.
  489. if (FnArgs.getNumElements() > 1 &&
  490. !FnArgs.getElement(FnArgs.getNumElements() - 1) &&
  491. !includeMinimalInlineScopes())
  492. ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
  493. }
  494. DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
  495. DIE &ScopeDIE) {
  496. // We create children when the scope DIE is not null.
  497. SmallVector<std::unique_ptr<DIE>, 8> Children;
  498. DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
  499. // Add children
  500. for (auto &I : Children)
  501. ScopeDIE.addChild(std::move(I));
  502. return ObjectPointer;
  503. }
  504. void
  505. DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
  506. DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
  507. if (AbsDef)
  508. return;
  509. DISubprogram SP(Scope->getScopeNode());
  510. DIE *ContextDIE;
  511. if (includeMinimalInlineScopes())
  512. ContextDIE = &getUnitDie();
  513. // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
  514. // the important distinction that the DIDescriptor is not associated with the
  515. // DIE (since the DIDescriptor will be associated with the concrete DIE, if
  516. // any). It could be refactored to some common utility function.
  517. else if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
  518. ContextDIE = &getUnitDie();
  519. getOrCreateSubprogramDIE(SPDecl);
  520. } else
  521. ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
  522. // Passing null as the associated DIDescriptor because the abstract definition
  523. // shouldn't be found by lookup.
  524. AbsDef =
  525. &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
  526. applySubprogramAttributesToDefinition(SP, *AbsDef);
  527. if (!includeMinimalInlineScopes())
  528. addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
  529. if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
  530. addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
  531. }
  532. std::unique_ptr<DIE>
  533. DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
  534. assert(Module.Verify() &&
  535. "Use one of the MDNode * overloads to handle invalid metadata");
  536. std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
  537. insertDIE(Module, IMDie.get());
  538. DIE *EntityDie;
  539. DIDescriptor Entity = resolve(Module.getEntity());
  540. if (Entity.isNameSpace())
  541. EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
  542. else if (Entity.isSubprogram())
  543. EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
  544. else if (Entity.isType())
  545. EntityDie = getOrCreateTypeDIE(DIType(Entity));
  546. else if (Entity.isGlobalVariable())
  547. EntityDie = getOrCreateGlobalVariableDIE(DIGlobalVariable(Entity));
  548. else
  549. EntityDie = getDIE(Entity);
  550. assert(EntityDie);
  551. addSourceLine(*IMDie, Module.getLineNumber(),
  552. Module.getContext().getFilename(),
  553. Module.getContext().getDirectory());
  554. addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
  555. StringRef Name = Module.getName();
  556. if (!Name.empty())
  557. addString(*IMDie, dwarf::DW_AT_name, Name);
  558. return IMDie;
  559. }
  560. void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
  561. DIE *D = getDIE(SP);
  562. if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
  563. if (D)
  564. // If this subprogram has an abstract definition, reference that
  565. addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
  566. } else {
  567. if (!D && !includeMinimalInlineScopes())
  568. // Lazily construct the subprogram if we didn't see either concrete or
  569. // inlined versions during codegen. (except in -gmlt ^ where we want
  570. // to omit these entirely)
  571. D = getOrCreateSubprogramDIE(SP);
  572. if (D)
  573. // And attach the attributes
  574. applySubprogramAttributesToDefinition(SP, *D);
  575. }
  576. }
  577. void DwarfCompileUnit::collectDeadVariables(DISubprogram SP) {
  578. assert(SP.isSubprogram() && "CU's subprogram list contains a non-subprogram");
  579. assert(SP.isDefinition() &&
  580. "CU's subprogram list contains a subprogram declaration");
  581. DIArray Variables = SP.getVariables();
  582. if (Variables.getNumElements() == 0)
  583. return;
  584. DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
  585. if (!SPDIE)
  586. SPDIE = getDIE(SP);
  587. assert(SPDIE);
  588. for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
  589. DIVariable DV(Variables.getElement(vi));
  590. assert(DV.isVariable());
  591. DbgVariable NewVar(DV, DIExpression(nullptr), DD);
  592. auto VariableDie = constructVariableDIE(NewVar);
  593. applyVariableAttributes(NewVar, *VariableDie);
  594. SPDIE->addChild(std::move(VariableDie));
  595. }
  596. }
  597. void DwarfCompileUnit::emitHeader(const MCSymbol *ASectionSym) const {
  598. // Don't bother labeling the .dwo unit, as its offset isn't used.
  599. if (!Skeleton)
  600. Asm->OutStreamer.EmitLabel(LabelBegin);
  601. DwarfUnit::emitHeader(ASectionSym);
  602. }
  603. /// addGlobalName - Add a new global name to the compile unit.
  604. void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
  605. DIScope Context) {
  606. if (includeMinimalInlineScopes())
  607. return;
  608. std::string FullName = getParentContextString(Context) + Name.str();
  609. GlobalNames[FullName] = &Die;
  610. }
  611. /// Add a new global type to the unit.
  612. void DwarfCompileUnit::addGlobalType(DIType Ty, const DIE &Die,
  613. DIScope Context) {
  614. if (includeMinimalInlineScopes())
  615. return;
  616. std::string FullName = getParentContextString(Context) + Ty.getName().str();
  617. GlobalTypes[FullName] = &Die;
  618. }
  619. /// addVariableAddress - Add DW_AT_location attribute for a
  620. /// DbgVariable based on provided MachineLocation.
  621. void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
  622. MachineLocation Location) {
  623. if (DV.variableHasComplexAddress())
  624. addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
  625. else if (DV.isBlockByrefVariable())
  626. addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
  627. else
  628. addAddress(Die, dwarf::DW_AT_location, Location,
  629. DV.getVariable().isIndirect());
  630. }
  631. /// Add an address attribute to a die based on the location provided.
  632. void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
  633. const MachineLocation &Location,
  634. bool Indirect) {
  635. DIELoc *Loc = new (DIEValueAllocator) DIELoc();
  636. bool validReg;
  637. if (Location.isReg() && !Indirect)
  638. validReg = addRegisterOpPiece(*Loc, Location.getReg());
  639. else
  640. validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
  641. if (!validReg)
  642. return;
  643. if (!Location.isReg() && Indirect)
  644. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
  645. // Now attach the location information to the DIE.
  646. addBlock(Die, Attribute, Loc);
  647. }
  648. /// Start with the address based on the location provided, and generate the
  649. /// DWARF information necessary to find the actual variable given the extra
  650. /// address information encoded in the DbgVariable, starting from the starting
  651. /// location. Add the DWARF information to the die.
  652. void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
  653. dwarf::Attribute Attribute,
  654. const MachineLocation &Location) {
  655. DIELoc *Loc = new (DIEValueAllocator) DIELoc();
  656. DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
  657. DIExpression Expr = DV.getExpression();
  658. if (Location.getOffset()) {
  659. if (DwarfExpr.AddMachineRegIndirect(Location.getReg(),
  660. Location.getOffset())) {
  661. DwarfExpr.AddExpression(Expr);
  662. assert(!DV.getVariable().isIndirect()
  663. && "double indirection not handled");
  664. }
  665. } else {
  666. if (DwarfExpr.AddMachineRegExpression(Expr, Location.getReg()))
  667. if (DV.getVariable().isIndirect())
  668. DwarfExpr.EmitOp(dwarf::DW_OP_deref);
  669. }
  670. // Now attach the location information to the DIE.
  671. addBlock(Die, Attribute, Loc);
  672. }
  673. /// Add a Dwarf loclistptr attribute data and value.
  674. void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
  675. unsigned Index) {
  676. DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
  677. dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
  678. : dwarf::DW_FORM_data4;
  679. Die.addValue(Attribute, Form, Value);
  680. }
  681. void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
  682. DIE &VariableDie) {
  683. StringRef Name = Var.getName();
  684. if (!Name.empty())
  685. addString(VariableDie, dwarf::DW_AT_name, Name);
  686. addSourceLine(VariableDie, Var.getVariable());
  687. addType(VariableDie, Var.getType());
  688. if (Var.isArtificial())
  689. addFlag(VariableDie, dwarf::DW_AT_artificial);
  690. }
  691. /// Add a Dwarf expression attribute data and value.
  692. void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
  693. const MCExpr *Expr) {
  694. DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
  695. Die.addValue((dwarf::Attribute)0, Form, Value);
  696. }
  697. void DwarfCompileUnit::applySubprogramAttributesToDefinition(DISubprogram SP,
  698. DIE &SPDie) {
  699. DISubprogram SPDecl = SP.getFunctionDeclaration();
  700. DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
  701. applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
  702. addGlobalName(SP.getName(), SPDie, Context);
  703. }
  704. bool DwarfCompileUnit::isDwoUnit() const {
  705. return DD->useSplitDwarf() && Skeleton;
  706. }
  707. bool DwarfCompileUnit::includeMinimalInlineScopes() const {
  708. return getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly ||
  709. (DD->useSplitDwarf() && !Skeleton);
  710. }
  711. } // end llvm namespace