blob: 1de2ffb6cfa11fb8b5f0f338d44c2e4531928325 [file] [log] [blame]
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00001//===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
Bill Wendling2f921f82009-05-15 09:23:25 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains support for writing dwarf debug info into asm files.
11//
12//===----------------------------------------------------------------------===//
Chris Lattnerb14490d2010-03-09 00:39:24 +000013
Bill Wendling2f921f82009-05-15 09:23:25 +000014#include "DwarfDebug.h"
David Blaikie37c52312014-10-04 15:49:50 +000015#include "ByteStreamer.h"
Eric Christopher45731982013-08-08 23:45:55 +000016#include "DIEHash.h"
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +000017#include "DebugLocEntry.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000018#include "DebugLocStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000019#include "DwarfCompileUnit.h"
20#include "DwarfExpression.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000021#include "DwarfFile.h"
David Blaikie2c86a722013-12-02 19:33:15 +000022#include "DwarfUnit.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000023#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/DenseMap.h"
25#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/MapVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/ADT/STLExtras.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000028#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/ADT/Triple.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000031#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/BinaryFormat/Dwarf.h"
Jonas Devlieghere855fc3b2018-01-29 14:52:41 +000033#include "llvm/CodeGen/AccelTable.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000034#include "llvm/CodeGen/AsmPrinter.h"
Frederic Risse541e0b2015-01-05 21:29:41 +000035#include "llvm/CodeGen/DIE.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000036#include "llvm/CodeGen/LexicalScopes.h"
37#include "llvm/CodeGen/MachineBasicBlock.h"
David Greene829b3e82009-08-19 21:52:55 +000038#include "llvm/CodeGen/MachineFunction.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000039#include "llvm/CodeGen/MachineInstr.h"
Bill Wendling2f921f82009-05-15 09:23:25 +000040#include "llvm/CodeGen/MachineModuleInfo.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000041#include "llvm/CodeGen/MachineOperand.h"
Vedant Kumar5931b4e2018-10-05 20:37:17 +000042#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000043#include "llvm/CodeGen/TargetRegisterInfo.h"
44#include "llvm/CodeGen/TargetSubtargetInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000045#include "llvm/IR/Constants.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000046#include "llvm/IR/DebugInfoMetadata.h"
47#include "llvm/IR/DebugLoc.h"
48#include "llvm/IR/Function.h"
49#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Module.h"
Chris Lattnere13c3722010-03-09 01:58:53 +000051#include "llvm/MC/MCAsmInfo.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000052#include "llvm/MC/MCContext.h"
Frederic Rissa5ab8442015-08-07 15:14:08 +000053#include "llvm/MC/MCDwarf.h"
Chris Lattner4d2c0f92009-07-31 18:48:30 +000054#include "llvm/MC/MCSection.h"
Chris Lattner4b7dadb2009-08-19 05:49:37 +000055#include "llvm/MC/MCStreamer.h"
Chris Lattnere13c3722010-03-09 01:58:53 +000056#include "llvm/MC/MCSymbol.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000057#include "llvm/MC/MCTargetOptions.h"
58#include "llvm/MC/MachineLocation.h"
59#include "llvm/MC/SectionKind.h"
60#include "llvm/Pass.h"
61#include "llvm/Support/Casting.h"
Devang Patel6c74a872010-04-27 19:46:33 +000062#include "llvm/Support/CommandLine.h"
Daniel Dunbarcdf01b52009-10-13 06:47:08 +000063#include "llvm/Support/Debug.h"
64#include "llvm/Support/ErrorHandling.h"
Eric Christopher67646432013-07-26 17:02:41 +000065#include "llvm/Support/MD5.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000066#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000067#include "llvm/Support/Timer.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000068#include "llvm/Support/raw_ostream.h"
David Blaikie6054e652018-03-23 23:58:19 +000069#include "llvm/Target/TargetLoweringObjectFile.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Target/TargetMachine.h"
71#include "llvm/Target/TargetOptions.h"
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +000072#include <algorithm>
73#include <cassert>
74#include <cstddef>
75#include <cstdint>
76#include <iterator>
77#include <string>
78#include <utility>
79#include <vector>
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000080
Bill Wendling2f921f82009-05-15 09:23:25 +000081using namespace llvm;
82
Chandler Carruth1b9dde02014-04-22 02:02:50 +000083#define DEBUG_TYPE "dwarfdebug"
84
Eric Christopher7f2b5512013-07-23 22:16:41 +000085static cl::opt<bool>
86DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
87 cl::desc("Disable debug info printing"));
Devang Patel6c74a872010-04-27 19:46:33 +000088
David Blaikie038e28a2017-07-31 21:48:42 +000089static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
90 "use-dwarf-ranges-base-address-specifier", cl::Hidden,
David Blaikiec2be8632017-08-01 14:50:50 +000091 cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
David Blaikie038e28a2017-07-31 21:48:42 +000092
Eric Christopher02dbadb2014-02-14 01:26:55 +000093static cl::opt<bool> GenerateARangeSection("generate-arange-section",
94 cl::Hidden,
95 cl::desc("Generate dwarf aranges"),
96 cl::init(false));
97
Pavel Labathf9adc202018-07-20 12:59:05 +000098static cl::opt<bool>
99 GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
100 cl::desc("Generate DWARF4 type units."),
101 cl::init(false));
102
David Blaikie488393f2017-05-12 01:13:45 +0000103static cl::opt<bool> SplitDwarfCrossCuReferences(
104 "split-dwarf-cross-cu-references", cl::Hidden,
105 cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
106
Eric Christopherf07ee3a2014-01-27 23:50:03 +0000107enum DefaultOnOff { Default, Enable, Disable };
Eric Christopher4996c702011-11-07 09:24:32 +0000108
Paul Robinsonac7fe5e2016-12-12 20:49:11 +0000109static cl::opt<DefaultOnOff> UnknownLocations(
110 "use-unknown-locations", cl::Hidden,
111 cl::desc("Make an absence of debug location information explicit."),
112 cl::values(clEnumVal(Default, "At top of block or after label"),
113 clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
114 cl::init(Default));
115
Pavel Labath6088c232018-04-04 14:42:14 +0000116static cl::opt<AccelTableKind> AccelTables(
117 "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
118 cl::values(clEnumValN(AccelTableKind::Default, "Default",
119 "Default for platform"),
120 clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
121 clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
122 clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
123 cl::init(AccelTableKind::Default));
Eric Christopher20b76a72012-08-23 22:36:40 +0000124
Alexey Bataev0d6aead2018-02-20 15:28:08 +0000125static cl::opt<DefaultOnOff>
126DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
127 cl::desc("Use inlined strings rather than string section."),
128 cl::values(clEnumVal(Default, "Default for platform"),
129 clEnumVal(Enable, "Enabled"),
130 clEnumVal(Disable, "Disabled")),
131 cl::init(Default));
132
Alexey Bataev648ed2d2018-03-20 16:04:40 +0000133static cl::opt<bool>
Alexey Bataev858a7dd2018-03-20 20:21:38 +0000134 NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
135 cl::desc("Disable emission .debug_ranges section."),
136 cl::init(false));
137
Alexey Bataevbff36082018-03-23 13:35:54 +0000138static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
139 "dwarf-sections-as-references", cl::Hidden,
140 cl::desc("Use sections+offset as references rather than labels."),
141 cl::values(clEnumVal(Default, "Default for platform"),
142 clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
143 cl::init(Default));
144
Paul Robinson43d1e452016-04-18 22:41:41 +0000145enum LinkageNameOption {
146 DefaultLinkageNames,
147 AllLinkageNames,
148 AbstractLinkageNames
149};
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000150
Paul Robinson43d1e452016-04-18 22:41:41 +0000151static cl::opt<LinkageNameOption>
152 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
153 cl::desc("Which DWARF linkage-name attributes to emit."),
154 cl::values(clEnumValN(DefaultLinkageNames, "Default",
155 "Default for platform"),
156 clEnumValN(AllLinkageNames, "All", "All"),
157 clEnumValN(AbstractLinkageNames, "Abstract",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000158 "Abstract subprograms")),
Paul Robinson43d1e452016-04-18 22:41:41 +0000159 cl::init(DefaultLinkageNames));
Paul Robinson78046b42015-08-11 21:36:45 +0000160
Matthias Braun9f15a792016-11-18 19:43:18 +0000161static const char *const DWARFGroupName = "dwarf";
162static const char *const DWARFGroupDescription = "DWARF Emission";
163static const char *const DbgTimerName = "writer";
164static const char *const DbgTimerDescription = "DWARF Debug Writer";
Bill Wendlingfcc14142010-04-07 09:28:04 +0000165
Adrian Prantla63b8e82017-03-16 17:42:45 +0000166void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000167 BS.EmitInt8(
168 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
169 : dwarf::OperationEncodingString(Op));
170}
171
Adrian Prantla63b8e82017-03-16 17:42:45 +0000172void DebugLocDwarfExpression::emitSigned(int64_t Value) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000173 BS.EmitSLEB128(Value, Twine(Value));
174}
175
Adrian Prantla63b8e82017-03-16 17:42:45 +0000176void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000177 BS.EmitULEB128(Value, Twine(Value));
178}
179
Peter Collingbourne96c9ae62016-05-20 19:35:17 +0000180bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
181 unsigned MachineReg) {
Adrian Prantl92da14b2015-03-02 22:02:33 +0000182 // This information is not available while emitting .debug_loc entries.
183 return false;
184}
185
Adrian Prantl1a1647c2014-03-18 02:34:58 +0000186bool DbgVariable::isBlockByrefVariable() const {
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000187 assert(getVariable() && "Invalid complex DbgVariable!");
188 return getVariable()->getType().resolve()->isBlockByrefStruct();
Adrian Prantl1a1647c2014-03-18 02:34:58 +0000189}
190
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000191const DIType *DbgVariable::getType() const {
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000192 DIType *Ty = getVariable()->getType().resolve();
Devang Patelf20c4f72011-04-12 22:53:02 +0000193 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
194 // addresses instead.
Duncan P. N. Exon Smith571baeb2015-04-14 01:59:58 +0000195 if (Ty->isBlockByrefStruct()) {
Devang Patelf20c4f72011-04-12 22:53:02 +0000196 /* Byref variables, in Blocks, are declared by the programmer as
197 "SomeType VarName;", but the compiler creates a
198 __Block_byref_x_VarName struct, and gives the variable VarName
199 either the struct, or a pointer to the struct, as its type. This
200 is necessary for various behind-the-scenes things the compiler
201 needs to do with by-reference variables in blocks.
Eric Christopher6a841382012-11-19 22:42:10 +0000202
Devang Patelf20c4f72011-04-12 22:53:02 +0000203 However, as far as the original *programmer* is concerned, the
204 variable should still have type 'SomeType', as originally declared.
Eric Christopher6a841382012-11-19 22:42:10 +0000205
Devang Patelf20c4f72011-04-12 22:53:02 +0000206 The following function dives into the __Block_byref_x_VarName
207 struct to find the original type of the variable. This will be
208 passed back to the code generating the type for the Debug
209 Information Entry for the variable 'VarName'. 'VarName' will then
210 have the original type 'SomeType' in its debug information.
Eric Christopher6a841382012-11-19 22:42:10 +0000211
Devang Patelf20c4f72011-04-12 22:53:02 +0000212 The original type 'SomeType' will be the type of the field named
213 'VarName' inside the __Block_byref_x_VarName struct.
Eric Christopher6a841382012-11-19 22:42:10 +0000214
Devang Patelf20c4f72011-04-12 22:53:02 +0000215 NOTE: In order for this to not completely fail on the debugger
216 side, the Debug Information Entry for the variable VarName needs to
217 have a DW_AT_location that tells the debugger how to unwind through
218 the pointers and __Block_byref_x_VarName struct to find the actual
219 value of the variable. The function addBlockByrefType does this. */
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000220 DIType *subType = Ty;
Duncan P. N. Exon Smithb1055642015-04-16 01:01:28 +0000221 uint16_t tag = Ty->getTag();
Eric Christopher6a841382012-11-19 22:42:10 +0000222
Eric Christopher9adc55f2013-09-04 19:53:21 +0000223 if (tag == dwarf::DW_TAG_pointer_type)
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000224 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
Eric Christopher6a841382012-11-19 22:42:10 +0000225
Duncan P. N. Exon Smith6ac940d2015-07-24 18:17:17 +0000226 auto Elements = cast<DICompositeType>(subType)->getElements();
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +0000227 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
Duncan P. N. Exon Smith099ea1c2015-07-24 18:58:32 +0000228 auto *DT = cast<DIDerivedType>(Elements[i]);
Duncan P. N. Exon Smithb1055642015-04-16 01:01:28 +0000229 if (getName() == DT->getName())
Duncan P. N. Exon Smith848af382015-04-20 18:20:03 +0000230 return resolve(DT->getBaseType());
Devang Patel6d9f9fe2010-08-09 21:01:39 +0000231 }
Devang Patel6d9f9fe2010-08-09 21:01:39 +0000232 }
Devang Patelf20c4f72011-04-12 22:53:02 +0000233 return Ty;
234}
Bill Wendling2f921f82009-05-15 09:23:25 +0000235
Adrian Prantl67c24422017-02-17 19:42:32 +0000236ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
Adrian Prantl55030772017-03-22 16:50:16 +0000237 if (FrameIndexExprs.size() == 1)
238 return FrameIndexExprs;
239
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000240 assert(llvm::all_of(FrameIndexExprs,
241 [](const FrameIndexExpr &A) {
242 return A.Expr->isFragment();
243 }) &&
Adrian Prantl55030772017-03-22 16:50:16 +0000244 "multiple FI expressions without DW_OP_LLVM_fragment");
Fangrui Song0cac7262018-09-27 02:13:45 +0000245 llvm::sort(FrameIndexExprs,
Mandeep Singh Grange92f0cf2018-04-06 18:08:42 +0000246 [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
247 return A.Expr->getFragmentInfo()->OffsetInBits <
248 B.Expr->getFragmentInfo()->OffsetInBits;
249 });
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000250
Adrian Prantl67c24422017-02-17 19:42:32 +0000251 return FrameIndexExprs;
252}
253
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000254void DbgVariable::addMMIEntry(const DbgVariable &V) {
255 assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
256 assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000257 assert(V.getVariable() == getVariable() && "conflicting variable");
258 assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000259
260 assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
261 assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
262
Daniel Jasper4d931202017-10-12 13:25:05 +0000263 // FIXME: This logic should not be necessary anymore, as we now have proper
264 // deduplication. However, without it, we currently run into the assertion
265 // below, which means that we are likely dealing with broken input, i.e. two
266 // non-fragment entries for the same variable at different frame indices.
267 if (FrameIndexExprs.size()) {
268 auto *Expr = FrameIndexExprs.back().Expr;
269 if (!Expr || !Expr->isFragment())
270 return;
271 }
272
Bjorn Steinbrinkd36bbe92017-10-10 07:46:17 +0000273 for (const auto &FIE : V.FrameIndexExprs)
274 // Ignore duplicate entries.
275 if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
276 return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
277 }))
278 FrameIndexExprs.push_back(FIE);
279
280 assert((FrameIndexExprs.size() == 1 ||
281 llvm::all_of(FrameIndexExprs,
282 [](FrameIndexExpr &FIE) {
283 return FIE.Expr && FIE.Expr->isFragment();
284 })) &&
285 "conflicting locations for variable");
286}
287
Pavel Labathf9adc202018-07-20 12:59:05 +0000288static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
289 bool GenerateTypeUnits,
290 DebuggerKind Tuning,
291 const Triple &TT) {
292 // Honor an explicit request.
293 if (AccelTables != AccelTableKind::Default)
294 return AccelTables;
295
296 // Accelerator tables with type units are currently not supported.
297 if (GenerateTypeUnits)
298 return AccelTableKind::None;
299
300 // Accelerator tables get emitted if targetting DWARF v5 or LLDB. DWARF v5
301 // always implies debug_names. For lower standard versions we use apple
302 // accelerator tables on apple platforms and debug_names elsewhere.
303 if (DwarfVersion >= 5)
304 return AccelTableKind::Dwarf;
305 if (Tuning == DebuggerKind::LLDB)
306 return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
307 : AccelTableKind::Dwarf;
308 return AccelTableKind::None;
309}
310
Chris Lattnerf0d6bd32010-04-05 05:11:15 +0000311DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
Reid Klecknerf9c275f2016-02-10 20:55:49 +0000312 : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
313 InfoHolder(A, "info_string", DIEValueAllocator),
Frederic Riss9412d632015-03-04 02:30:17 +0000314 SkeletonHolder(A, "skel_string", DIEValueAllocator),
Pavel Labatha7c457d2018-02-19 16:12:20 +0000315 IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
Eric Christopher364dbe02016-10-01 01:50:29 +0000316 const Triple &TT = Asm->TM.getTargetTriple();
Eric Christopherad9fe892012-04-02 17:58:52 +0000317
Paul Robinson6c27a2c2015-12-16 19:58:30 +0000318 // Make sure we know our "debugger tuning." The target option takes
Paul Robinsonb9de1062015-07-15 22:04:54 +0000319 // precedence; fall back to triple-based defaults.
Paul Robinson6c27a2c2015-12-16 19:58:30 +0000320 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
321 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
Dimitry Andric2c364212016-01-07 22:09:12 +0000322 else if (IsDarwin)
Paul Robinsonb9de1062015-07-15 22:04:54 +0000323 DebuggerTuning = DebuggerKind::LLDB;
324 else if (TT.isPS4CPU())
325 DebuggerTuning = DebuggerKind::SCE;
326 else
327 DebuggerTuning = DebuggerKind::GDB;
328
Eric Christopher68f22182018-05-18 03:13:08 +0000329 if (DwarfInlinedStrings == Default)
330 UseInlineStrings = TT.isNVPTX();
331 else
332 UseInlineStrings = DwarfInlinedStrings == Enable;
333
Alexey Bataev2a03d422018-06-29 14:23:28 +0000334 UseLocSection = !TT.isNVPTX();
335
David Blaikiec53e18d2016-05-24 21:19:28 +0000336 HasAppleExtensionAttributes = tuneForLLDB();
337
David Blaikie96b1ed52017-04-21 23:35:26 +0000338 // Handle split DWARF.
339 HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
Eric Christopher29424312012-11-12 22:22:20 +0000340
Paul Robinson43d1e452016-04-18 22:41:41 +0000341 // SCE defaults to linkage names only for abstract subprograms.
342 if (DwarfLinkageNames == DefaultLinkageNames)
343 UseAllLinkageNames = !tuneForSCE();
Paul Robinson78046b42015-08-11 21:36:45 +0000344 else
Paul Robinson43d1e452016-04-18 22:41:41 +0000345 UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
Paul Robinson78046b42015-08-11 21:36:45 +0000346
Eric Christopher4c5bff32014-06-19 06:22:08 +0000347 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
Greg Claytone6543972016-11-23 23:30:37 +0000348 unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
Eric Christopher793c7472014-04-28 20:42:22 +0000349 : MMI->getModule()->getDwarfVersion();
Eric Christopher68f22182018-05-18 03:13:08 +0000350 // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
351 DwarfVersion =
352 TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
Manman Renac8062b2013-07-02 23:40:10 +0000353
Eric Christopher68f22182018-05-18 03:13:08 +0000354 UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
Alexey Bataev648ed2d2018-03-20 16:04:40 +0000355
Eric Christopher68f22182018-05-18 03:13:08 +0000356 // Use sections as references. Force for NVPTX.
357 if (DwarfSectionsAsReferences == Default)
358 UseSectionsAsReferences = TT.isNVPTX();
359 else
360 UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
Alexey Bataevbff36082018-03-23 13:35:54 +0000361
Jonas Devlieghere8acb74e2018-08-01 12:53:06 +0000362 // Don't generate type units for unsupported object file formats.
363 GenerateTypeUnits =
364 A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
Pavel Labathf9adc202018-07-20 12:59:05 +0000365
366 TheAccelTableKind = computeAccelTableKind(
367 DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
368
Paul Robinsonb9de1062015-07-15 22:04:54 +0000369 // Work around a GDB bug. GDB doesn't support the standard opcode;
370 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
371 // is defined as of DWARF 3.
372 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
373 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
374 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
Paul Robinson78cc0822015-03-04 20:55:11 +0000375
Adrian Prantl6323ddf2016-05-17 21:07:16 +0000376 // GDB does not fully support the DWARF 4 representation for bitfields.
377 UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
378
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000379 // The DWARF v5 string offsets table has - possibly shared - contributions
380 // from each compile and type unit each preceded by a header. The string
381 // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
382 // a monolithic string offsets table without any header.
383 UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
384
Lang Hames9ff69c82015-04-24 19:11:51 +0000385 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
Bill Wendling2f921f82009-05-15 09:23:25 +0000386}
Bill Wendling2f921f82009-05-15 09:23:25 +0000387
Reid Klecknerdd2647e2014-04-30 20:34:31 +0000388// Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +0000389DwarfDebug::~DwarfDebug() = default;
Reid Klecknerdd2647e2014-04-30 20:34:31 +0000390
Eric Christopherd9843b32011-11-10 19:25:34 +0000391static bool isObjCClass(StringRef Name) {
392 return Name.startswith("+") || Name.startswith("-");
393}
394
395static bool hasObjCCategory(StringRef Name) {
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000396 if (!isObjCClass(Name))
397 return false;
Eric Christopherd9843b32011-11-10 19:25:34 +0000398
Benjamin Kramer260de742013-08-24 12:15:54 +0000399 return Name.find(") ") != StringRef::npos;
Eric Christopherd9843b32011-11-10 19:25:34 +0000400}
401
402static void getObjCClassCategory(StringRef In, StringRef &Class,
403 StringRef &Category) {
404 if (!hasObjCCategory(In)) {
405 Class = In.slice(In.find('[') + 1, In.find(' '));
406 Category = "";
407 return;
408 }
409
410 Class = In.slice(In.find('[') + 1, In.find('('));
411 Category = In.slice(In.find('[') + 1, In.find(' '));
Eric Christopherd9843b32011-11-10 19:25:34 +0000412}
413
414static StringRef getObjCMethodName(StringRef In) {
415 return In.slice(In.find(' ') + 1, In.find(']'));
416}
417
418// Add the various names to the Dwarf accelerator table names.
David Blaikie66cf14d2018-08-16 21:29:55 +0000419void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
420 const DISubprogram *SP, DIE &Die) {
421 if (getAccelTableKind() != AccelTableKind::Apple &&
422 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
423 return;
424
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000425 if (!SP->isDefinition())
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000426 return;
Pavel Labath889bf9f2018-04-09 08:41:57 +0000427
428 if (SP->getName() != "")
David Blaikie66cf14d2018-08-16 21:29:55 +0000429 addAccelName(CU, SP->getName(), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000430
Pavel Labath2a6afe52018-05-14 14:13:20 +0000431 // If the linkage name is different than the name, go ahead and output that as
432 // well into the name table. Only do that if we are going to actually emit
433 // that name.
434 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
435 (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
David Blaikie66cf14d2018-08-16 21:29:55 +0000436 addAccelName(CU, SP->getLinkageName(), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000437
438 // If this is an Objective-C selector name add it to the ObjC accelerator
439 // too.
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000440 if (isObjCClass(SP->getName())) {
Eric Christopherd9843b32011-11-10 19:25:34 +0000441 StringRef Class, Category;
Duncan P. N. Exon Smith537b4a82015-04-14 03:40:37 +0000442 getObjCClassCategory(SP->getName(), Class, Category);
David Blaikie66cf14d2018-08-16 21:29:55 +0000443 addAccelObjC(CU, Class, Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000444 if (Category != "")
David Blaikie66cf14d2018-08-16 21:29:55 +0000445 addAccelObjC(CU, Category, Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000446 // Also add the base method name to the name table.
David Blaikie66cf14d2018-08-16 21:29:55 +0000447 addAccelName(CU, getObjCMethodName(SP->getName()), Die);
Eric Christopherd9843b32011-11-10 19:25:34 +0000448 }
449}
450
Manman Ren5b2f4b02013-09-11 19:40:28 +0000451/// Check whether we should create a DIE for the given Scope, return true
452/// if we don't create a DIE (the corresponding DIE is null).
Manman Ren2312ed32013-09-10 18:40:41 +0000453bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
454 if (Scope->isAbstractScope())
455 return false;
456
Manman Ren5b2f4b02013-09-11 19:40:28 +0000457 // We don't create a DIE if there is no Range.
Manman Ren2312ed32013-09-10 18:40:41 +0000458 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
459 if (Ranges.empty())
460 return true;
461
462 if (Ranges.size() > 1)
463 return false;
464
Manman Ren5b2f4b02013-09-11 19:40:28 +0000465 // We don't create a DIE if we have a single Range and the end label
466 // is null.
David Blaikiecd4b8a22014-08-31 02:14:26 +0000467 return !getLabelAfterInsn(Ranges.front().second);
Manman Ren2312ed32013-09-10 18:40:41 +0000468}
469
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000470template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
David Blaikie3a443c22014-11-04 22:12:25 +0000471 F(CU);
472 if (auto *SkelCU = CU.getSkeleton())
David Blaikiea01f2952016-08-24 18:29:49 +0000473 if (CU.getCUNode()->getSplitDebugInlining())
474 F(*SkelCU);
David Blaikie3a443c22014-11-04 22:12:25 +0000475}
476
David Blaikie488393f2017-05-12 01:13:45 +0000477bool DwarfDebug::shareAcrossDWOCUs() const {
478 return SplitDwarfCrossCuReferences;
479}
480
481void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
482 LexicalScope *Scope) {
David Blaikiee872a6e2014-04-29 15:58:35 +0000483 assert(Scope && Scope->getScopeNode());
484 assert(Scope->isAbstractScope());
485 assert(!Scope->getInlinedAt());
486
David Blaikieb4614682016-12-14 19:38:39 +0000487 auto *SP = cast<DISubprogram>(Scope->getScopeNode());
David Blaikiee872a6e2014-04-29 15:58:35 +0000488
David Blaikie1ea9db22014-05-21 23:14:12 +0000489 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
490 // was inlined from another compile unit.
Mehdi Amini41812052017-05-29 06:25:30 +0000491 if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
492 // Avoid building the original CU if it won't be used
493 SrcCU.constructAbstractSubprogramScopeDIE(Scope);
494 else {
495 auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
496 if (auto *SkelCU = CU.getSkeleton()) {
497 (shareAcrossDWOCUs() ? CU : SrcCU)
498 .constructAbstractSubprogramScopeDIE(Scope);
499 if (CU.getCUNode()->getSplitDebugInlining())
500 SkelCU->constructAbstractSubprogramScopeDIE(Scope);
501 } else
502 CU.constructAbstractSubprogramScopeDIE(Scope);
David Blaikie488393f2017-05-12 01:13:45 +0000503 }
David Blaikiee872a6e2014-04-29 15:58:35 +0000504}
505
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000506void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
507 DwarfCompileUnit &CU, DIE &ScopeDIE,
508 const MachineFunction &MF) {
509 // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
510 // the subprogram is required to have one.
511 if (!SP.areAllCallsDescribed() || !SP.isDefinition())
512 return;
513
514 // Use DW_AT_call_all_calls to express that call site entries are present
515 // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
516 // because one of its requirements is not met: call site entries for
517 // optimized-out calls are elided.
518 CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
519
520 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
521 assert(TII && "TargetInstrInfo not found: cannot label tail calls");
522
523 // Emit call site entries for each call or tail call in the function.
524 for (const MachineBasicBlock &MBB : MF) {
525 for (const MachineInstr &MI : MBB.instrs()) {
526 // Skip instructions which aren't calls. Both calls and tail-calling jump
527 // instructions (e.g TAILJMPd64) are classified correctly here.
528 if (!MI.isCall())
529 continue;
530
531 // TODO: Add support for targets with delay slots (see: beginInstruction).
532 if (MI.hasDelaySlot())
533 return;
534
535 // If this is a direct call, find the callee's subprogram.
536 const MachineOperand &CalleeOp = MI.getOperand(0);
537 if (!CalleeOp.isGlobal())
538 continue;
539 const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
540 if (!CalleeDecl || !CalleeDecl->getSubprogram())
541 continue;
542
543 // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
544 // TODO: Add support for indirect calls.
545
546 bool IsTail = TII->isTailCall(MI);
547
548 // For tail calls, no return PC information is needed. For regular calls,
549 // the return PC is needed to disambiguate paths in the call graph which
550 // could lead to some target function.
Vedant Kumar74533bd2018-10-22 21:44:21 +0000551 const MCExpr *PCOffset =
552 IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI);
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000553
Vedant Kumar74533bd2018-10-22 21:44:21 +0000554 assert((IsTail || PCOffset) && "Call without return PC information");
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000555 LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
556 << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
557 << "\n");
558 CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
Vedant Kumar74533bd2018-10-22 21:44:21 +0000559 IsTail, PCOffset);
Vedant Kumar5931b4e2018-10-05 20:37:17 +0000560 }
561 }
562}
563
David Blaikieb3cee2f2017-05-25 18:50:28 +0000564void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
Peter Collingbourneb52e2362017-09-12 21:50:41 +0000565 if (!U.hasDwarfPubSections())
David Blaikie3c842622013-12-04 21:31:26 +0000566 return;
567
David Blaikief9b6a552014-04-22 22:39:41 +0000568 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
David Blaikie3c842622013-12-04 21:31:26 +0000569}
570
David Blaikie560ff352018-12-14 22:44:46 +0000571void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
572 DwarfCompileUnit &NewCU) {
David Blaikie92a2f8a2014-04-28 21:04:29 +0000573 DIE &Die = NewCU.getUnitDie();
David Blaikie560ff352018-12-14 22:44:46 +0000574 StringRef FN = DIUnit->getFilename();
David Blaikief9b6a552014-04-22 22:39:41 +0000575
Eric Christopher9ea300f2017-03-29 23:34:27 +0000576 StringRef Producer = DIUnit->getProducer();
577 StringRef Flags = DIUnit->getFlags();
Jonas Devliegherecaacedb2018-08-08 16:33:22 +0000578 if (!Flags.empty() && !useAppleExtensionAttributes()) {
Eric Christopher9ea300f2017-03-29 23:34:27 +0000579 std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
580 NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
581 } else
582 NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
583
David Blaikie92a2f8a2014-04-28 21:04:29 +0000584 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
Duncan P. N. Exon Smith35ef22c2015-04-15 23:19:27 +0000585 DIUnit->getSourceLanguage());
David Blaikie92a2f8a2014-04-28 21:04:29 +0000586 NewCU.addString(Die, dwarf::DW_AT_name, FN);
Eric Christopher52ce7182013-04-09 19:23:15 +0000587
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000588 // Add DW_str_offsets_base to the unit DIE, except for split units.
589 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
590 NewCU.addStringOffsetsStart();
591
Eric Christopher52ce7182013-04-09 19:23:15 +0000592 if (!useSplitDwarf()) {
Rafael Espindola063d7252015-03-10 16:58:10 +0000593 NewCU.initStmtList();
Eric Christophera51d3fc2013-09-27 22:50:48 +0000594
595 // If we're using split dwarf the compilation dir is going to be in the
596 // skeleton CU and so we don't need to duplicate it here.
597 if (!CompilationDir.empty())
David Blaikie92a2f8a2014-04-28 21:04:29 +0000598 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
Eric Christophera51d3fc2013-09-27 22:50:48 +0000599
David Blaikie92a2f8a2014-04-28 21:04:29 +0000600 addGnuPubAttributes(NewCU, Die);
Eric Christopher52ce7182013-04-09 19:23:15 +0000601 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000602
David Blaikiec53e18d2016-05-24 21:19:28 +0000603 if (useAppleExtensionAttributes()) {
604 if (DIUnit->isOptimized())
605 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
Bill Wendling2b128d72009-05-20 23:19:06 +0000606
David Blaikiec53e18d2016-05-24 21:19:28 +0000607 StringRef Flags = DIUnit->getFlags();
608 if (!Flags.empty())
609 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
Eric Christopher6a841382012-11-19 22:42:10 +0000610
David Blaikiec53e18d2016-05-24 21:19:28 +0000611 if (unsigned RVer = DIUnit->getRuntimeVersion())
612 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
613 dwarf::DW_FORM_data1, RVer);
614 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000615
Adrian Prantldeef90d2015-09-14 22:10:22 +0000616 if (DIUnit->getDWOId()) {
Adrian Prantl77fefeb2015-09-22 23:21:00 +0000617 // This CU is either a clang module DWO or a skeleton CU.
Adrian Prantldeef90d2015-09-14 22:10:22 +0000618 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
619 DIUnit->getDWOId());
Adrian Prantl77fefeb2015-09-22 23:21:00 +0000620 if (!DIUnit->getSplitDebugFilename().empty())
621 // This is a prefabricated skeleton CU.
622 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
623 DIUnit->getSplitDebugFilename());
Adrian Prantldeef90d2015-09-14 22:10:22 +0000624 }
David Blaikie560ff352018-12-14 22:44:46 +0000625}
626// Create new DwarfCompileUnit for the given metadata node with tag
627// DW_TAG_compile_unit.
628DwarfCompileUnit &
629DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
630 if (auto *CU = CUMap.lookup(DIUnit))
631 return *CU;
632
633 CompilationDir = DIUnit->getDirectory();
634
635 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
636 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
637 DwarfCompileUnit &NewCU = *OwnedUnit;
638 InfoHolder.addUnit(std::move(OwnedUnit));
639
David Blaikie693f6172018-12-18 19:40:22 +0000640 for (auto *IE : DIUnit->getImportedEntities())
641 NewCU.addImportedEntity(IE);
642
David Blaikieb3c56af2018-12-20 20:46:55 +0000643 // LTO with assembly output shares a single line table amongst multiple CUs.
644 // To avoid the compilation directory being ambiguous, let the line table
645 // explicitly describe the directory of all files, never relying on the
646 // compilation directory.
647 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
648 Asm->OutStreamer->emitDwarfFile0Directive(
649 CompilationDir, DIUnit->getFilename(),
650 NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
651 NewCU.getUniqueID());
652
David Blaikie560ff352018-12-14 22:44:46 +0000653 if (useSplitDwarf()) {
654 NewCU.setSkeleton(constructSkeletonCU(NewCU));
655 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
656 } else {
657 finishUnitAttributes(DIUnit, NewCU);
658 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
659 }
Adrian Prantldeef90d2015-09-14 22:10:22 +0000660
David Majnemer0a16c222016-08-11 21:15:00 +0000661 CUMap.insert({DIUnit, &NewCU});
David Blaikie560ff352018-12-14 22:44:46 +0000662 CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
Devang Pateleb1bb4e2011-08-16 22:09:43 +0000663 return NewCU;
Devang Patel1a0df9a2010-05-10 22:49:55 +0000664}
665
David Blaikie8912df12014-08-31 05:41:15 +0000666void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +0000667 const DIImportedEntity *N) {
David Blaikie2195e132017-07-27 00:06:53 +0000668 if (isa<DILocalScope>(N->getScope()))
669 return;
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +0000670 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
671 D->addChild(TheCU.constructImportedEntityDIE(N));
David Blaikief55abea2013-04-22 06:12:31 +0000672}
673
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000674/// Sort and unique GVEs by comparing their fragment offset.
675static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
676sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
Fangrui Song0cac7262018-09-27 02:13:45 +0000677 llvm::sort(
678 GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
679 // Sort order: first null exprs, then exprs without fragment
680 // info, then sort by fragment offset in bits.
681 // FIXME: Come up with a more comprehensive comparator so
682 // the sorting isn't non-deterministic, and so the following
683 // std::unique call works correctly.
684 if (!A.Expr || !B.Expr)
685 return !!B.Expr;
686 auto FragmentA = A.Expr->getFragmentInfo();
687 auto FragmentB = B.Expr->getFragmentInfo();
688 if (!FragmentA || !FragmentB)
689 return !!FragmentB;
690 return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
691 });
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000692 GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
693 [](DwarfCompileUnit::GlobalExpr A,
694 DwarfCompileUnit::GlobalExpr B) {
695 return A.Expr == B.Expr;
696 }),
697 GVEs.end());
698 return GVEs;
699}
700
Eric Christopheracdcbdb2012-11-27 22:43:45 +0000701// Emit all Dwarf sections that should come prior to the content. Create
702// global DIEs and emit initial debug info sections. This is invoked by
703// the target AsmPrinter.
Eric Christopher58f41952012-11-19 22:42:15 +0000704void DwarfDebug::beginModule() {
Matthias Braun9f15a792016-11-18 19:43:18 +0000705 NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
706 DWARFGroupDescription, TimePassesIsEnabled);
Matthias Braun8763c0c2018-10-31 17:18:41 +0000707 if (DisableDebugInfoPrinting) {
708 MMI->setDebugInfoAvailability(false);
Devang Patel6c74a872010-04-27 19:46:33 +0000709 return;
Matthias Braun8763c0c2018-10-31 17:18:41 +0000710 }
Devang Patel6c74a872010-04-27 19:46:33 +0000711
Eric Christopher58f41952012-11-19 22:42:15 +0000712 const Module *M = MMI->getModule();
713
Peter Collingbourneb3269862016-06-01 02:58:40 +0000714 unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
715 M->debug_compile_units_end());
Adrian Prantl5992a722016-04-08 22:43:03 +0000716 // Tell MMI whether we have debug info.
Matthias Braun8763c0c2018-10-31 17:18:41 +0000717 assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
718 "DebugInfoAvailabilty initialized unexpectedly");
Adrian Prantl5992a722016-04-08 22:43:03 +0000719 SingleCU = NumDebugCUs == 1;
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000720 DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
721 GVMap;
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000722 for (const GlobalVariable &Global : M->globals()) {
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000723 SmallVector<DIGlobalVariableExpression *, 1> GVs;
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000724 Global.getDebugInfo(GVs);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000725 for (auto *GVE : GVs)
726 GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
Peter Collingbourned4135bb2016-09-13 01:12:59 +0000727 }
728
Wolfgang Pieb456b5552018-01-26 18:52:58 +0000729 // Create the symbol that designates the start of the unit's contribution
730 // to the string offsets table. In a split DWARF scenario, only the skeleton
731 // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
732 if (useSegmentedStringOffsetsTable())
733 (useSplitDwarf() ? SkeletonHolder : InfoHolder)
734 .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
735
George Rimar088d96b2018-10-26 11:25:12 +0000736
737 // Create the symbols that designates the start of the DWARF v5 range list
738 // and locations list tables. They are located past the table headers.
David Blaikiec4af8bf2018-10-20 07:36:39 +0000739 if (getDwarfVersion() >= 5) {
George Rimar088d96b2018-10-26 11:25:12 +0000740 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
741 Holder.setRnglistsTableBaseSym(
742 Asm->createTempSymbol("rnglists_table_base"));
743 Holder.setLoclistsTableBaseSym(
744 Asm->createTempSymbol("loclists_table_base"));
745
David Blaikiec4af8bf2018-10-20 07:36:39 +0000746 if (useSplitDwarf())
747 InfoHolder.setRnglistsTableBaseSym(
748 Asm->createTempSymbol("rnglists_dwo_table_base"));
749 }
Wolfgang Piebfcf38102018-07-12 18:18:21 +0000750
George Rimar425f7512018-09-20 09:17:36 +0000751 // Create the symbol that points to the first entry following the debug
752 // address table (.debug_addr) header.
753 AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
754
Adrian Prantl5992a722016-04-08 22:43:03 +0000755 for (DICompileUnit *CUNode : M->debug_compile_units()) {
David Blaikie89daf772017-07-28 03:06:25 +0000756 // FIXME: Move local imported entities into a list attached to the
757 // subprogram, then this search won't be needed and a
758 // getImportedEntities().empty() test should go below with the rest.
759 bool HasNonLocalImportedEntities = llvm::any_of(
760 CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
761 return !isa<DILocalScope>(IE->getScope());
762 });
763
764 if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
765 CUNode->getRetainedTypes().empty() &&
766 CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
David Blaikie07963bd2017-05-26 18:52:56 +0000767 continue;
768
769 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000770
771 // Global Variables.
Adrian Prantl2116dd32017-08-19 01:15:06 +0000772 for (auto *GVE : CUNode->getGlobalVariables()) {
773 // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
774 // already know about the variable and it isn't adding a constant
775 // expression.
776 auto &GVMapEntry = GVMap[GVE->getVariable()];
777 auto *Expr = GVE->getExpression();
778 if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
779 GVMapEntry.push_back({nullptr, Expr});
780 }
Adrian Prantlbceaaa92016-12-20 02:09:43 +0000781 DenseSet<DIGlobalVariable *> Processed;
782 for (auto *GVE : CUNode->getGlobalVariables()) {
783 DIGlobalVariable *GV = GVE->getVariable();
784 if (Processed.insert(GV).second)
785 CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
786 }
787
Duncan P. N. Exon Smith9928a902015-04-20 18:52:06 +0000788 for (auto *Ty : CUNode->getEnumTypes()) {
Manman Renbd1628a2014-07-28 23:04:20 +0000789 // The enum types array by design contains pointers to
790 // MDNodes rather than DIRefs. Unique them here.
Duncan P. N. Exon Smitha59d3e52016-04-23 21:08:00 +0000791 CU.getOrCreateTypeDIE(cast<DIType>(Ty));
Manman Renbd1628a2014-07-28 23:04:20 +0000792 }
Duncan P. N. Exon Smith9928a902015-04-20 18:52:06 +0000793 for (auto *Ty : CUNode->getRetainedTypes()) {
Adrian Prantl0aa1aa22014-03-18 02:35:03 +0000794 // The retained types array by design contains pointers to
795 // MDNodes rather than DIRefs. Unique them here.
Amjad Aboud72da9392016-04-30 01:44:07 +0000796 if (DIType *RT = dyn_cast<DIType>(Ty))
Adrian Prantl75819ae2016-04-15 15:57:41 +0000797 // There is no point in force-emitting a forward declaration.
798 CU.getOrCreateTypeDIE(RT);
Adrian Prantl0aa1aa22014-03-18 02:35:03 +0000799 }
David Blaikief55abea2013-04-22 06:12:31 +0000800 // Emit imported_modules last so that the relevant context is already
801 // available.
Duncan P. N. Exon Smith000fa2c2015-04-07 04:14:33 +0000802 for (auto *IE : CUNode->getImportedEntities())
Amjad Aboud72da9392016-04-30 01:44:07 +0000803 constructAndAddImportedEntityDIE(CU, IE);
David Blaikiedc69ebb2013-03-11 23:39:23 +0000804 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000805}
806
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000807void DwarfDebug::finishEntityDefinitions() {
808 for (const auto &Entity : ConcreteEntities) {
809 DIE *Die = Entity->getDIE();
810 assert(Die);
David Blaikieeb1a2722014-06-13 22:18:23 +0000811 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000812 // in the ConcreteEntities list, rather than looking it up again here.
David Blaikieeb1a2722014-06-13 22:18:23 +0000813 // DIE::getUnit isn't simple - it walks parent pointers, etc.
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000814 DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
David Blaikieeb1a2722014-06-13 22:18:23 +0000815 assert(Unit);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000816 Unit->finishEntityDefinition(Entity.get());
David Blaikieeb1a2722014-06-13 22:18:23 +0000817 }
818}
819
David Blaikief7221ad2014-05-27 18:37:43 +0000820void DwarfDebug::finishSubprogramDefinitions() {
David Blaikie07963bd2017-05-26 18:52:56 +0000821 for (const DISubprogram *SP : ProcessedSPNodes) {
822 assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
823 forBothCUs(
824 getOrCreateDwarfCompileUnit(SP->getUnit()),
825 [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
826 }
Eric Christopher960ac372012-11-22 00:59:49 +0000827}
828
829void DwarfDebug::finalizeModuleInfo() {
Rafael Espindola063d7252015-03-10 16:58:10 +0000830 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
831
David Blaikie3c2fff32014-05-27 18:37:48 +0000832 finishSubprogramDefinitions();
833
Hsiangkai Wang2532ac82018-08-17 15:22:04 +0000834 finishEntityDefinitions();
David Blaikieeb1a2722014-06-13 22:18:23 +0000835
Mehdi Amini96ab48f2017-05-29 06:32:34 +0000836 // Include the DWO file name in the hash if there's more than one CU.
837 // This handles ThinLTO's situation where imported CUs may very easily be
838 // duplicate with the same CU partially imported into another ThinLTO unit.
839 StringRef DWOName;
840 if (CUMap.size() > 1)
841 DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
842
Eric Christopherad10cb52013-12-04 23:24:38 +0000843 // Handle anything that needs to be done on a per-unit basis after
844 // all other generation.
David Blaikie1998a2e2014-11-01 01:11:19 +0000845 for (const auto &P : CUMap) {
846 auto &TheCU = *P.second;
Alexey Bataevd4dd7212018-08-01 19:38:20 +0000847 if (TheCU.getCUNode()->isDebugDirectivesOnly())
848 continue;
Eric Christopher60eb7692013-08-12 20:27:48 +0000849 // Emit DW_AT_containing_type attribute to connect types with their
850 // vtable holding type.
David Blaikie1998a2e2014-11-01 01:11:19 +0000851 TheCU.constructContainingTypeDIEs();
Eric Christopher60eb7692013-08-12 20:27:48 +0000852
Eric Christopher46e23432013-12-20 04:16:18 +0000853 // Add CU specific attributes if we need to add any.
David Blaikie1998a2e2014-11-01 01:11:19 +0000854 // If we're splitting the dwarf out now that we've got the entire
855 // CU then add the dwo id to it.
856 auto *SkCU = TheCU.getSkeleton();
David Blaikie560ff352018-12-14 22:44:46 +0000857 if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) {
858 finishUnitAttributes(TheCU.getCUNode(), TheCU);
859 TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
860 Asm->TM.Options.MCOptions.SplitDwarfFile);
861 SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
862 Asm->TM.Options.MCOptions.SplitDwarfFile);
David Blaikie1998a2e2014-11-01 01:11:19 +0000863 // Emit a unique identifier for this CU.
Mehdi Amini96ab48f2017-05-29 06:32:34 +0000864 uint64_t ID =
865 DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
Paul Robinson543c0e12018-05-22 17:27:31 +0000866 if (getDwarfVersion() >= 5) {
867 TheCU.setDWOId(ID);
868 SkCU->setDWOId(ID);
869 } else {
870 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
871 dwarf::DW_FORM_data8, ID);
872 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
873 dwarf::DW_FORM_data8, ID);
874 }
George Rimar425f7512018-09-20 09:17:36 +0000875
David Blaikiec4af8bf2018-10-20 07:36:39 +0000876 if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
Rafael Espindola063d7252015-03-10 16:58:10 +0000877 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
David Blaikie1998a2e2014-11-01 01:11:19 +0000878 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
Rafael Espindola063d7252015-03-10 16:58:10 +0000879 Sym, Sym);
880 }
David Blaikie560ff352018-12-14 22:44:46 +0000881 } else if (SkCU) {
882 finishUnitAttributes(SkCU->getCUNode(), *SkCU);
David Blaikie1998a2e2014-11-01 01:11:19 +0000883 }
Eric Christopherd8667202013-12-30 17:22:27 +0000884
David Blaikie1998a2e2014-11-01 01:11:19 +0000885 // If we have code split among multiple sections or non-contiguous
886 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
887 // remain in the .o file, otherwise add a DW_AT_low_pc.
888 // FIXME: We should use ranges allow reordering of code ala
889 // .subsections_via_symbols in mach-o. This would mean turning on
890 // ranges for all subprogram DIEs for mach-o.
David Blaikiea8be0a72014-11-01 01:15:24 +0000891 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
David Blaikie161dd3c2018-10-20 06:02:15 +0000892
893 // We don't keep track of which addresses are used in which CU so this
894 // is a bit pessimistic under LTO.
David Blaikie560ff352018-12-14 22:44:46 +0000895 if (!AddrPool.isEmpty() &&
896 (getDwarfVersion() >= 5 ||
897 (SkCU && !empty(TheCU.getUnitDie().children()))))
David Blaikie161dd3c2018-10-20 06:02:15 +0000898 U.addAddrTableBase();
899
David Blaikie5b02a192014-11-03 23:10:59 +0000900 if (unsigned NumRanges = TheCU.getRanges().size()) {
Alexey Bataev858a7dd2018-03-20 20:21:38 +0000901 if (NumRanges > 1 && useRangesSection())
David Blaikie1998a2e2014-11-01 01:11:19 +0000902 // A DW_AT_low_pc attribute may also be specified in combination with
903 // DW_AT_ranges to specify the default base address for use in
904 // location lists (see Section 2.6.2) and range lists (see Section
905 // 2.17.3).
906 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
David Blaikie5b02a192014-11-03 23:10:59 +0000907 else
David Blaikie72d03ef2015-05-02 02:31:49 +0000908 U.setBaseAddress(TheCU.getRanges().front().getStart());
David Blaikie5b02a192014-11-03 23:10:59 +0000909 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
Eric Christopher60eb7692013-08-12 20:27:48 +0000910 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000911
George Rimar088d96b2018-10-26 11:25:12 +0000912 if (getDwarfVersion() >= 5) {
913 if (U.hasRangeLists())
914 U.addRnglistsBase();
915
916 if (!DebugLocs.getLists().empty() && !useSplitDwarf())
917 U.addLoclistsBase();
918 }
Wolfgang Pieb9ea65082018-07-26 22:48:52 +0000919
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000920 auto *CUNode = cast<DICompileUnit>(P.first);
Amjad Aboud8bbce8a2016-02-01 14:09:41 +0000921 // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
922 if (CUNode->getMacros())
923 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
924 U.getMacroLabelBegin(),
925 TLOF.getDwarfMacinfoSection()->getBeginSymbol());
Eric Christopher60eb7692013-08-12 20:27:48 +0000926 }
927
Adrian Prantl833ad372017-07-26 18:48:32 +0000928 // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
929 for (auto *CUNode : MMI->getModule()->debug_compile_units())
Adrian Prantl960e7662017-07-27 15:24:20 +0000930 if (CUNode->getDWOId())
Adrian Prantl833ad372017-07-26 18:48:32 +0000931 getOrCreateDwarfCompileUnit(CUNode);
932
Eric Christopher60eb7692013-08-12 20:27:48 +0000933 // Compute DIE offsets and sizes.
Eric Christopherc8a310e2012-12-10 23:34:43 +0000934 InfoHolder.computeSizeAndOffsets();
935 if (useSplitDwarf())
936 SkeletonHolder.computeSizeAndOffsets();
Eric Christopher960ac372012-11-22 00:59:49 +0000937}
938
Eric Christopheracdcbdb2012-11-27 22:43:45 +0000939// Emit all Dwarf sections that should come after the content.
Eric Christopher960ac372012-11-22 00:59:49 +0000940void DwarfDebug::endModule() {
Craig Toppere73658d2014-04-28 04:05:08 +0000941 assert(CurFn == nullptr);
942 assert(CurMI == nullptr);
Eric Christopher960ac372012-11-22 00:59:49 +0000943
David Blaikie0dc623c2014-10-24 17:53:38 +0000944 // If we aren't actually generating debug info (check beginModule -
945 // conditionalized on !DisableDebugInfoPrinting and the presence of the
946 // llvm.dbg.cu metadata node)
Rafael Espindolaf1a13f52015-03-11 00:51:37 +0000947 if (!MMI->hasDebugInfo())
Eric Christopherb4bef6d2013-11-19 09:04:36 +0000948 return;
Eric Christopher960ac372012-11-22 00:59:49 +0000949
Eric Christopher960ac372012-11-22 00:59:49 +0000950 // Finalize the debug info for the module.
951 finalizeModuleInfo();
Bill Wendling2b128d72009-05-20 23:19:06 +0000952
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000953 emitDebugStr();
Eric Christopher9cd26af2013-09-20 23:22:52 +0000954
Rafael Espindola063d7252015-03-10 16:58:10 +0000955 if (useSplitDwarf())
956 emitDebugLocDWO();
957 else
958 // Emit info into a debug loc section.
959 emitDebugLoc();
960
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000961 // Corresponding abbreviations into a abbrev section.
962 emitAbbreviations();
Eric Christopher95198f502012-11-27 22:43:42 +0000963
Rafael Espindolaf1a13f52015-03-11 00:51:37 +0000964 // Emit all the DIEs into a debug info section.
965 emitDebugInfo();
966
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000967 // Emit info into a debug aranges section.
Eric Christopher02dbadb2014-02-14 01:26:55 +0000968 if (GenerateARangeSection)
969 emitDebugARanges();
Eric Christopher95198f502012-11-27 22:43:42 +0000970
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000971 // Emit info into a debug ranges section.
972 emitDebugRanges();
Eric Christopher95198f502012-11-27 22:43:42 +0000973
Amjad Aboudd7cfb482016-01-07 14:28:20 +0000974 // Emit info into a debug macinfo section.
975 emitDebugMacinfo();
976
Eric Christopher9a8f5ed2013-11-19 09:04:50 +0000977 if (useSplitDwarf()) {
978 emitDebugStrDWO();
Eric Christopher9c2ecd92012-11-30 23:59:06 +0000979 emitDebugInfoDWO();
Eric Christopher3c5a1912012-12-19 22:02:53 +0000980 emitDebugAbbrevDWO();
David Blaikie4a2f95f2014-03-18 01:17:26 +0000981 emitDebugLineDWO();
David Blaikie32e09de2018-10-20 08:12:36 +0000982 emitDebugRangesDWO();
Rafael Espindola063d7252015-03-10 16:58:10 +0000983 }
Bill Wendling2b128d72009-05-20 23:19:06 +0000984
David Blaikie161dd3c2018-10-20 06:02:15 +0000985 emitDebugAddr();
986
Eric Christophera876b822012-08-23 07:32:06 +0000987 // Emit info into the dwarf accelerator table sections.
Pavel Labath6088c232018-04-04 14:42:14 +0000988 switch (getAccelTableKind()) {
989 case AccelTableKind::Apple:
Eric Christopher4996c702011-11-07 09:24:32 +0000990 emitAccelNames();
991 emitAccelObjC();
992 emitAccelNamespaces();
993 emitAccelTypes();
Pavel Labath6088c232018-04-04 14:42:14 +0000994 break;
995 case AccelTableKind::Dwarf:
996 emitAccelDebugNames();
997 break;
998 case AccelTableKind::None:
999 break;
1000 case AccelTableKind::Default:
1001 llvm_unreachable("Default should have already been resolved.");
Eric Christopher4996c702011-11-07 09:24:32 +00001002 }
Eric Christopher6a841382012-11-19 22:42:10 +00001003
Eric Christopher4b358182013-08-30 00:40:17 +00001004 // Emit the pubnames and pubtypes sections if requested.
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001005 emitDebugPubSections();
Devang Patel04d2f2d2009-11-24 01:14:22 +00001006
Devang Pateld0701282010-08-02 17:32:15 +00001007 // clean up.
David Blaikie488393f2017-05-12 01:13:45 +00001008 // FIXME: AbstractVariables.clear();
Bill Wendling2b128d72009-05-20 23:19:06 +00001009}
1010
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001011void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1012 const DINode *Node,
1013 const MDNode *ScopeNode) {
1014 if (CU.getExistingAbstractEntity(Node))
David Blaikie6f9e8672014-06-13 23:52:55 +00001015 return;
David Blaikie36408e72014-06-04 23:50:52 +00001016
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001017 CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001018 cast<DILocalScope>(ScopeNode)));
David Blaikie36408e72014-06-04 23:50:52 +00001019}
1020
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001021void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1022 const DINode *Node, const MDNode *ScopeNode) {
1023 if (CU.getExistingAbstractEntity(Node))
David Blaikie6f9e8672014-06-13 23:52:55 +00001024 return;
David Blaikie36408e72014-06-04 23:50:52 +00001025
Duncan P. N. Exon Smith33af7a82015-03-30 23:21:21 +00001026 if (LexicalScope *Scope =
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001027 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001028 CU.createAbstractEntity(Node, Scope);
David Blaikie36408e72014-06-04 23:50:52 +00001029}
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00001030
Matthias Braunef331ef2016-11-30 23:48:50 +00001031// Collect variable information from side table maintained by MF.
1032void DwarfDebug::collectVariableInfoFromMFTable(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001033 DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1034 SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
Matthias Braunef331ef2016-11-30 23:48:50 +00001035 for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
Benjamin Kramer2abfd6c72014-03-09 15:44:39 +00001036 if (!VI.Var)
Eric Christopherb4bef6d2013-11-19 09:04:36 +00001037 continue;
Duncan P. N. Exon Smith78a95272015-04-16 22:12:59 +00001038 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1039 "Expected inlined-at fields to agree");
1040
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001041 InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001042 Processed.insert(Var);
Benjamin Kramer2abfd6c72014-03-09 15:44:39 +00001043 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
Jim Grosbacha8683bb2010-07-21 21:21:52 +00001044
Devang Patelcdb7d442009-11-10 23:20:04 +00001045 // If variable scope is not found then skip this variable.
Craig Topper353eda42014-04-24 06:44:33 +00001046 if (!Scope)
Devang Patelcdb7d442009-11-10 23:20:04 +00001047 continue;
Devang Patelf6eeaeb2009-11-10 23:06:00 +00001048
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001049 ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001050 auto RegVar = llvm::make_unique<DbgVariable>(
1051 cast<DILocalVariable>(Var.first), Var.second);
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +00001052 RegVar->initializeMMI(VI.Expr, VI.Slot);
Adrian Prantlbe662712017-07-25 23:32:59 +00001053 if (DbgVariable *DbgVar = MFVars.lookup(Var))
1054 DbgVar->addMMIEntry(*RegVar);
1055 else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1056 MFVars.insert({Var, RegVar.get()});
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001057 ConcreteEntities.push_back(std::move(RegVar));
Adrian Prantlbe662712017-07-25 23:32:59 +00001058 }
Devang Patel475d32a2009-10-06 01:26:37 +00001059 }
Devang Patel490c8ab2010-05-20 19:57:06 +00001060}
Devang Patela3e9c9c2010-03-15 18:33:46 +00001061
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001062// Get .debug_loc entry for the instruction range starting at MI.
Adrian Prantle19e5ef2014-04-27 18:25:40 +00001063static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001064 const DIExpression *Expr = MI->getDebugExpression();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001065 assert(MI->getNumOperands() == 4);
Adrian Prantl418d1d12013-07-09 20:28:37 +00001066 if (MI->getOperand(0).isReg()) {
Adrian Prantlbd6d2912017-08-02 17:19:13 +00001067 auto RegOp = MI->getOperand(0);
1068 auto Op1 = MI->getOperand(1);
Adrian Prantl418d1d12013-07-09 20:28:37 +00001069 // If the second operand is an immediate, this is a
1070 // register-indirect address.
Adrian Prantlbd6d2912017-08-02 17:19:13 +00001071 assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
1072 MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +00001073 return DebugLocEntry::Value(Expr, MLoc);
Devang Patel2442a892011-07-08 17:09:57 +00001074 }
1075 if (MI->getOperand(0).isImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +00001076 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
Devang Patel2442a892011-07-08 17:09:57 +00001077 if (MI->getOperand(0).isFPImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +00001078 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
Devang Patel2442a892011-07-08 17:09:57 +00001079 if (MI->getOperand(0).isCImm())
Duncan P. N. Exon Smith546c8be2015-04-17 16:33:37 +00001080 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
Devang Patel2442a892011-07-08 17:09:57 +00001081
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001082 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
Devang Patel2442a892011-07-08 17:09:57 +00001083}
1084
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001085/// If this and Next are describing different fragments of the same
Keno Fischerf8eb6a12016-01-16 01:11:33 +00001086/// variable, merge them by appending Next's values to the current
1087/// list of values.
1088/// Return true if the merge was successful.
1089bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
1090 if (Begin == Next.Begin) {
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001091 auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
1092 auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
Adrian Prantl941fa752016-12-05 18:04:47 +00001093 if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001094 return false;
1095
Adrian Prantl941fa752016-12-05 18:04:47 +00001096 // We can only merge entries if none of the fragments overlap any others.
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001097 // In doing so, we can take advantage of the fact that both lists are
1098 // sorted.
1099 for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
1100 for (; j < Next.Values.size(); ++j) {
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001101 int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001102 cast<DIExpression>(Next.Values[j].Expression));
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001103 if (res == 0) // The two expressions overlap, we can't merge.
1104 return false;
1105 // Values[i] is entirely before Next.Values[j],
1106 // so go back to the next entry of Values.
1107 else if (res == -1)
1108 break;
1109 // Next.Values[j] is entirely before Values[i], so go on to the
1110 // next entry of Next.Values.
1111 }
Keno Fischerf8eb6a12016-01-16 01:11:33 +00001112 }
Keno Fischer6c1e47a2016-02-03 21:13:33 +00001113
1114 addValues(Next.Values);
1115 End = Next.End;
1116 return true;
Keno Fischerf8eb6a12016-01-16 01:11:33 +00001117 }
1118 return false;
1119}
1120
Adrian Prantlb1416832014-08-01 22:11:58 +00001121/// Build the location list for all DBG_VALUEs in the function that
1122/// describe the same variable. If the ranges of several independent
Adrian Prantl941fa752016-12-05 18:04:47 +00001123/// fragments of the same variable overlap partially, split them up and
Adrian Prantlb1416832014-08-01 22:11:58 +00001124/// combine the ranges. The resulting DebugLocEntries are will have
1125/// strict monotonically increasing begin addresses and will never
1126/// overlap.
1127//
1128// Input:
1129//
Adrian Prantl941fa752016-12-05 18:04:47 +00001130// Ranges History [var, loc, fragment ofs size]
1131// 0 | [x, (reg0, fragment 0, 32)]
1132// 1 | | [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
Adrian Prantlb1416832014-08-01 22:11:58 +00001133// 2 | | ...
1134// 3 | [clobber reg0]
Adrian Prantl941fa752016-12-05 18:04:47 +00001135// 4 [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
Eric Christopherffc5ff32015-02-17 20:02:28 +00001136// x.
Adrian Prantlb1416832014-08-01 22:11:58 +00001137//
1138// Output:
1139//
Adrian Prantl941fa752016-12-05 18:04:47 +00001140// [0-1] [x, (reg0, fragment 0, 32)]
1141// [1-3] [x, (reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1142// [3-4] [x, (reg1, fragment 32, 32)]
1143// [4- ] [x, (mem, fragment 0, 64)]
David Blaikiee1a26a62014-08-05 23:14:16 +00001144void
1145DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1146 const DbgValueHistoryMap::InstrRanges &Ranges) {
Adrian Prantlcaaf0532014-08-11 21:05:57 +00001147 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
Adrian Prantlb1416832014-08-01 22:11:58 +00001148
1149 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1150 const MachineInstr *Begin = I->first;
1151 const MachineInstr *End = I->second;
1152 assert(Begin->isDebugValue() && "Invalid History entry");
1153
1154 // Check if a variable is inaccessible in this range.
Adrian Prantl5e1fa852014-08-12 21:55:58 +00001155 if (Begin->getNumOperands() > 1 &&
1156 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
Adrian Prantlb1416832014-08-01 22:11:58 +00001157 OpenRanges.clear();
1158 continue;
1159 }
1160
Adrian Prantl941fa752016-12-05 18:04:47 +00001161 // If this fragment overlaps with any open ranges, truncate them.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001162 const DIExpression *DIExpr = Begin->getDebugExpression();
David Majnemer0a16c222016-08-11 21:15:00 +00001163 auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
Bjorn Petterssona223f8152018-03-12 18:02:39 +00001164 return DIExpr->fragmentsOverlap(R.getExpression());
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001165 });
Adrian Prantlb1416832014-08-01 22:11:58 +00001166 OpenRanges.erase(Last, OpenRanges.end());
1167
1168 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1169 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1170
1171 const MCSymbol *EndLabel;
1172 if (End != nullptr)
1173 EndLabel = getLabelAfterInsn(End);
1174 else if (std::next(I) == Ranges.end())
Rafael Espindola07c03d32015-03-05 02:05:42 +00001175 EndLabel = Asm->getFunctionEnd();
Adrian Prantlb1416832014-08-01 22:11:58 +00001176 else
1177 EndLabel = getLabelBeforeInsn(std::next(I)->first);
1178 assert(EndLabel && "Forgot label after instruction ending a range!");
1179
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001180 LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
Adrian Prantlb1416832014-08-01 22:11:58 +00001181
1182 auto Value = getDebugLocValue(Begin);
David Stenberg33b192d2019-01-09 09:58:59 +00001183
1184 // Omit entries with empty ranges as they do not have any effect in DWARF.
1185 if (StartLabel == EndLabel) {
1186 // If this is a fragment, we must still add the value to the list of
1187 // open ranges, since it may describe non-overlapping parts of the
1188 // variable.
1189 if (DIExpr->isFragment())
1190 OpenRanges.push_back(Value);
1191 LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1192 continue;
1193 }
1194
David Blaikiee1a26a62014-08-05 23:14:16 +00001195 DebugLocEntry Loc(StartLabel, EndLabel, Value);
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001196 bool couldMerge = false;
1197
Adrian Prantl941fa752016-12-05 18:04:47 +00001198 // If this is a fragment, it may belong to the current DebugLocEntry.
1199 if (DIExpr->isFragment()) {
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001200 // Add this value to the list of open ranges.
Adrian Prantlcaaf0532014-08-11 21:05:57 +00001201 OpenRanges.push_back(Value);
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001202
Adrian Prantl941fa752016-12-05 18:04:47 +00001203 // Attempt to add the fragment to the last entry.
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001204 if (!DebugLoc.empty())
1205 if (DebugLoc.back().MergeValues(Loc))
1206 couldMerge = true;
1207 }
1208
1209 if (!couldMerge) {
1210 // Need to add a new DebugLocEntry. Add all values from still
Adrian Prantl941fa752016-12-05 18:04:47 +00001211 // valid non-overlapping fragments.
Adrian Prantl1c6f2ec2014-08-11 21:06:00 +00001212 if (OpenRanges.size())
1213 Loc.addValues(OpenRanges);
1214
Adrian Prantlb1416832014-08-01 22:11:58 +00001215 DebugLoc.push_back(std::move(Loc));
1216 }
Adrian Prantle09ee3f2014-08-11 20:59:28 +00001217
1218 // Attempt to coalesce the ranges of two otherwise identical
1219 // DebugLocEntries.
1220 auto CurEntry = DebugLoc.rbegin();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001221 LLVM_DEBUG({
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001222 dbgs() << CurEntry->getValues().size() << " Values:\n";
Adrian Prantl6f8c1b62015-05-26 20:06:51 +00001223 for (auto &Value : CurEntry->getValues())
Adrian Prantldba58fb2016-02-29 22:28:22 +00001224 Value.dump();
Adrian Prantl87b7eb92014-10-01 18:55:02 +00001225 dbgs() << "-----\n";
1226 });
Adrian Prantl75707312015-05-26 20:06:48 +00001227
1228 auto PrevEntry = std::next(CurEntry);
1229 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1230 DebugLoc.pop_back();
Adrian Prantlb1416832014-08-01 22:11:58 +00001231 }
1232}
1233
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001234DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1235 LexicalScope &Scope,
1236 const DINode *Node,
1237 const DILocation *Location,
1238 const MCSymbol *Sym) {
1239 ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1240 if (isa<const DILocalVariable>(Node)) {
1241 ConcreteEntities.push_back(
1242 llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1243 Location));
1244 InfoHolder.addScopeVariable(&Scope,
1245 cast<DbgVariable>(ConcreteEntities.back().get()));
1246 } else if (isa<const DILabel>(Node)) {
1247 ConcreteEntities.push_back(
1248 llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1249 Location, Sym));
1250 InfoHolder.addScopeLabel(&Scope,
1251 cast<DbgLabel>(ConcreteEntities.back().get()));
1252 }
1253 return ConcreteEntities.back().get();
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +00001254}
Adrian Prantlb1416832014-08-01 22:11:58 +00001255
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001256/// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1257/// enclosing lexical scope. The check ensures there are no other instructions
1258/// in the same lexical scope preceding the DBG_VALUE and that its range is
1259/// either open or otherwise rolls off the end of the scope.
1260static bool validThroughout(LexicalScopes &LScopes,
1261 const MachineInstr *DbgValue,
1262 const MachineInstr *RangeEnd) {
1263 assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1264 auto MBB = DbgValue->getParent();
1265 auto DL = DbgValue->getDebugLoc();
1266 auto *LScope = LScopes.findLexicalScope(DL);
1267 // Scope doesn't exist; this is a dead DBG_VALUE.
1268 if (!LScope)
Adrian Prantlfb2add22016-02-29 19:49:46 +00001269 return false;
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001270 auto &LSRange = LScope->getRanges();
1271 if (LSRange.size() == 0)
1272 return false;
1273
1274 // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1275 const MachineInstr *LScopeBegin = LSRange.front().first;
1276 // Early exit if the lexical scope begins outside of the current block.
1277 if (LScopeBegin->getParent() != MBB)
1278 return false;
1279 MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1280 for (++Pred; Pred != MBB->rend(); ++Pred) {
1281 if (Pred->getFlag(MachineInstr::FrameSetup))
1282 break;
1283 auto PredDL = Pred->getDebugLoc();
Adrian Prantl25422dc2017-06-20 21:08:52 +00001284 if (!PredDL || Pred->isMetaInstruction())
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001285 continue;
1286 // Check whether the instruction preceding the DBG_VALUE is in the same
1287 // (sub)scope as the DBG_VALUE.
Adrian Prantl25422dc2017-06-20 21:08:52 +00001288 if (DL->getScope() == PredDL->getScope())
1289 return false;
1290 auto *PredScope = LScopes.findLexicalScope(PredDL);
1291 if (!PredScope || LScope->dominates(PredScope))
Adrian Prantlfb2add22016-02-29 19:49:46 +00001292 return false;
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001293 }
1294
1295 // If the range of the DBG_VALUE is open-ended, report success.
1296 if (!RangeEnd)
1297 return true;
1298
1299 // Fail if there are instructions belonging to our scope in another block.
1300 const MachineInstr *LScopeEnd = LSRange.back().second;
1301 if (LScopeEnd->getParent() != MBB)
1302 return false;
1303
1304 // Single, constant DBG_VALUEs in the prologue are promoted to be live
1305 // throughout the function. This is a hack, presumably for DWARF v2 and not
1306 // necessarily correct. It would be much better to use a dbg.declare instead
1307 // if we know the constant is live throughout the scope.
1308 if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1309 return true;
1310
1311 return false;
Adrian Prantlfb2add22016-02-29 19:49:46 +00001312}
1313
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001314// Find variables for each lexical scope.
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001315void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1316 const DISubprogram *SP,
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001317 DenseSet<InlinedEntity> &Processed) {
Eric Christopher270a12c2013-07-03 21:37:03 +00001318 // Grab the variable info that was squirreled away in the MMI side-table.
David Blaikie488393f2017-05-12 01:13:45 +00001319 collectVariableInfoFromMFTable(TheCU, Processed);
Devang Patel490c8ab2010-05-20 19:57:06 +00001320
Alexey Samsonov0436caa2014-04-30 23:02:40 +00001321 for (const auto &I : DbgValues) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001322 InlinedEntity IV = I.first;
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001323 if (Processed.count(IV))
Devang Patel490c8ab2010-05-20 19:57:06 +00001324 continue;
1325
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001326 // Instruction ranges, specifying where IV is accessible.
Alexey Samsonovbb2990d2014-05-27 23:09:50 +00001327 const auto &Ranges = I.second;
1328 if (Ranges.empty())
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001329 continue;
Devang Patel9fc11702010-05-25 23:40:22 +00001330
Craig Topper353eda42014-04-24 06:44:33 +00001331 LexicalScope *Scope = nullptr;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001332 const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001333 if (const DILocation *IA = IV.second)
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001334 Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
Duncan P. N. Exon Smithb4749372015-02-17 00:02:27 +00001335 else
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001336 Scope = LScopes.findLexicalScope(LocalVar->getScope());
Devang Patel490c8ab2010-05-20 19:57:06 +00001337 // If variable scope is not found then skip this variable.
Devang Patelfbd6c452010-05-21 00:10:20 +00001338 if (!Scope)
Devang Patel490c8ab2010-05-20 19:57:06 +00001339 continue;
1340
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00001341 Processed.insert(IV);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001342 DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001343 *Scope, LocalVar, IV.second));
Duncan P. N. Exon Smithe6cc5312015-06-21 16:50:43 +00001344
Alexey Samsonovbb2990d2014-05-27 23:09:50 +00001345 const MachineInstr *MInsn = Ranges.front().first;
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001346 assert(MInsn->isDebugValue() && "History must begin with debug value");
Jakob Stoklund Olesen9a624fa2011-03-26 02:19:36 +00001347
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001348 // Check if there is a single DBG_VALUE, valid throughout the var's scope.
Adrian Prantlfb2add22016-02-29 19:49:46 +00001349 if (Ranges.size() == 1 &&
Adrian Prantl274bcbc2017-06-16 22:40:04 +00001350 validThroughout(LScopes, MInsn, Ranges.front().second)) {
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001351 RegVar->initializeDbgValue(MInsn);
Devang Patel9fc11702010-05-25 23:40:22 +00001352 continue;
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001353 }
Alexey Bataev2a03d422018-06-29 14:23:28 +00001354 // Do not emit location lists if .debug_loc secton is disabled.
1355 if (!useLocSection())
1356 continue;
Devang Patel9fc11702010-05-25 23:40:22 +00001357
Eric Christopher59cc0712013-01-28 17:33:26 +00001358 // Handle multiple DBG_VALUE instructions describing one variable.
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001359 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
Jakob Stoklund Olesen9c057ee2011-03-22 00:21:41 +00001360
Adrian Prantlb1416832014-08-01 22:11:58 +00001361 // Build the location list for this variable.
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001362 SmallVector<DebugLocEntry, 8> Entries;
1363 buildLocationList(Entries, Ranges);
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001364
Adrian Prantl693e8de2016-02-29 17:06:46 +00001365 // If the variable has a DIBasicType, extract it. Basic types cannot have
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001366 // unique identifiers, so don't bother resolving the type with the
1367 // identifier map.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001368 const DIBasicType *BT = dyn_cast<DIBasicType>(
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001369 static_cast<const Metadata *>(LocalVar->getType()));
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001370
Adrian Prantl92da14b2015-03-02 22:02:33 +00001371 // Finalize the entry by lowering it into a DWARF bytestream.
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001372 for (auto &Entry : Entries)
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001373 Entry.finalize(*Asm, List, BT);
Devang Patela3e9c9c2010-03-15 18:33:46 +00001374 }
Devang Patele0a94bf2010-05-14 21:01:35 +00001375
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001376 // For each InlinedEntity collected from DBG_LABEL instructions, convert to
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001377 // DWARF-related DbgLabel.
1378 for (const auto &I : DbgLabels) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001379 InlinedEntity IL = I.first;
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001380 const MachineInstr *MI = I.second;
1381 if (MI == nullptr)
1382 continue;
1383
1384 LexicalScope *Scope = nullptr;
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001385 const DILabel *Label = cast<DILabel>(IL.first);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001386 // Get inlined DILocation if it is inlined label.
1387 if (const DILocation *IA = IL.second)
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001388 Scope = LScopes.findInlinedScope(Label->getScope(), IA);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001389 else
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001390 Scope = LScopes.findLexicalScope(Label->getScope());
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001391 // If label scope is not found then skip this label.
1392 if (!Scope)
1393 continue;
1394
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001395 Processed.insert(IL);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001396 /// At this point, the temporary label is created.
1397 /// Save the temporary label to DbgLabel entity to get the
1398 /// actually address when generating Dwarf DIE.
1399 MCSymbol *Sym = getLabelBeforeInsn(MI);
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001400 createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001401 }
1402
1403 // Collect info for variables/labels that were optimized out.
Shiva Chen2c864552018-05-09 02:40:45 +00001404 for (const DINode *DN : SP->getRetainedNodes()) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001405 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1406 continue;
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001407 LexicalScope *Scope = nullptr;
Shiva Chen2c864552018-05-09 02:40:45 +00001408 if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001409 Scope = LScopes.findLexicalScope(DV->getScope());
1410 } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1411 Scope = LScopes.findLexicalScope(DL->getScope());
Shiva Chen2c864552018-05-09 02:40:45 +00001412 }
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001413
1414 if (Scope)
1415 createConcreteEntity(TheCU, *Scope, DN, nullptr);
Devang Patele0a94bf2010-05-14 21:01:35 +00001416 }
Devang Patel9fc11702010-05-25 23:40:22 +00001417}
Devang Patele0a94bf2010-05-14 21:01:35 +00001418
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001419// Process beginning of an instruction.
Devang Patelb5694e72010-10-26 17:49:02 +00001420void DwarfDebug::beginInstruction(const MachineInstr *MI) {
Reid Klecknerf9c275f2016-02-10 20:55:49 +00001421 DebugHandlerBase::beginInstruction(MI);
1422 assert(CurMI);
1423
Matthias Braunf1caa282017-12-15 22:22:58 +00001424 const auto *SP = MI->getMF()->getFunction().getSubprogram();
David Blaikie7f2b7172017-05-26 17:05:15 +00001425 if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1426 return;
1427
Paul Robinson4fa7b57a2016-12-09 19:15:32 +00001428 // Check if source location changes, but ignore DBG_VALUE and CFI locations.
Paul Robinsonee88ed62018-02-14 17:35:52 +00001429 // If the instruction is part of the function frame setup code, do not emit
1430 // any line record, as there is no correspondence with any user code.
1431 if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
Paul Robinsonf428c9b2016-11-22 19:46:51 +00001432 return;
1433 const DebugLoc &DL = MI->getDebugLoc();
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001434 // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1435 // the last line number actually emitted, to see if it was line 0.
1436 unsigned LastAsmLine =
1437 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
Paul Robinson96de8c72016-11-29 22:41:16 +00001438
Vedant Kumar5931b4e2018-10-05 20:37:17 +00001439 // Request a label after the call in order to emit AT_return_pc information
1440 // in call site entries. TODO: Add support for targets with delay slots.
1441 if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1442 requestLabelAfterInsn(MI);
1443
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001444 if (DL == PrevInstLoc) {
1445 // If we have an ongoing unspecified location, nothing to do here.
1446 if (!DL)
1447 return;
1448 // We have an explicit location, same as the previous location.
1449 // But we might be coming back to it after a line 0 record.
1450 if (LastAsmLine == 0 && DL.getLine() != 0) {
1451 // Reinstate the source location but not marked as a statement.
1452 const MDNode *Scope = DL.getScope();
1453 recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
Paul Robinson37a13dd2016-11-30 22:49:55 +00001454 }
1455 return;
1456 }
1457
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001458 if (!DL) {
1459 // We have an unspecified location, which might want to be line 0.
1460 // If we have already emitted a line-0 record, don't repeat it.
1461 if (LastAsmLine == 0)
1462 return;
1463 // If user said Don't Do That, don't do that.
1464 if (UnknownLocations == Disable)
1465 return;
Matthias Braunc7efb6f2018-10-11 23:37:58 +00001466 // See if we have a reason to emit a line-0 record now.
1467 // Reasons to emit a line-0 record include:
1468 // - User asked for it (UnknownLocations).
1469 // - Instruction has a label, so it's referenced from somewhere else,
1470 // possibly debug information; we want it to have a source location.
1471 // - Instruction is at the top of a block; we don't want to inherit the
1472 // location from the physically previous (maybe unrelated) block.
1473 if (UnknownLocations == Enable || PrevLabel ||
1474 (PrevInstBB && PrevInstBB != MI->getParent())) {
1475 // Preserve the file and column numbers, if we can, to save space in
1476 // the encoded line table.
1477 // Do not update PrevInstLoc, it remembers the last non-0 line.
1478 const MDNode *Scope = nullptr;
1479 unsigned Column = 0;
1480 if (PrevInstLoc) {
1481 Scope = PrevInstLoc.getScope();
1482 Column = PrevInstLoc.getCol();
1483 }
1484 recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
Paul Robinsonac7fe5e2016-12-12 20:49:11 +00001485 }
1486 return;
1487 }
1488
Matthias Braunc7efb6f2018-10-11 23:37:58 +00001489 // We have an explicit location, different from the previous location.
1490 // Don't repeat a line-0 record, but otherwise emit the new location.
1491 // (The new location might be an explicit line 0, which we do emit.)
1492 if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1493 return;
1494 unsigned Flags = 0;
1495 if (DL == PrologEndLoc) {
1496 Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1497 PrologEndLoc = DebugLoc();
1498 }
1499 // If the line changed, we call that a new statement; unless we went to
1500 // line 0 and came back, in which case it is not a new statement.
1501 unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1502 if (DL.getLine() && DL.getLine() != OldLine)
1503 Flags |= DWARF2_FLAG_IS_STMT;
1504
1505 const MDNode *Scope = DL.getScope();
1506 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1507
1508 // If we're not at line 0, remember this location.
1509 if (DL.getLine())
1510 PrevInstLoc = DL;
Devang Patel75cc16c2009-10-01 20:31:14 +00001511}
1512
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001513static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1514 // First known non-DBG_VALUE and non-frame setup location marks
1515 // the beginning of the function body.
1516 for (const auto &MBB : *MF)
1517 for (const auto &MI : MBB)
Adrian Prantlfb31da12017-05-22 20:47:09 +00001518 if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
Michael Kuperstein2b3c16c2015-10-08 07:48:49 +00001519 MI.getDebugLoc())
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001520 return MI.getDebugLoc();
1521 return DebugLoc();
1522}
1523
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001524// Gather pre-function debug information. Assumes being called immediately
1525// after the function entry point has been emitted.
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001526void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
Timur Iskhodzhanov1cd14442013-12-03 15:10:23 +00001527 CurFn = MF;
Eric Christopherfedfa442013-11-01 23:14:17 +00001528
Matthias Braunf1caa282017-12-15 22:22:58 +00001529 auto *SP = MF->getFunction().getSubprogram();
David Blaikie2c78f182017-05-25 23:11:28 +00001530 assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
David Blaikie07963bd2017-05-26 18:52:56 +00001531 if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
Adrian Prantl5992a722016-04-08 22:43:03 +00001532 return;
David Blaikie07963bd2017-05-26 18:52:56 +00001533
1534 DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
David Blaikie2c78f182017-05-25 23:11:28 +00001535
1536 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1537 // belongs to so that we add to the correct per-cu line table in the
1538 // non-asm case.
Lang Hames9ff69c82015-04-24 19:11:51 +00001539 if (Asm->OutStreamer->hasRawTextSupport())
Rafael Espindolab4eec1d2014-02-05 18:00:21 +00001540 // Use a single line table if we are generating assembly.
Lang Hames9ff69c82015-04-24 19:11:51 +00001541 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
Manman Ren9d4c7352013-05-21 00:57:22 +00001542 else
David Blaikie07963bd2017-05-26 18:52:56 +00001543 Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
Manman Ren4e042a62013-02-05 21:52:47 +00001544
Devang Patel34a66202011-05-11 19:22:19 +00001545 // Record beginning of function.
Alexey Samsonov8a86d6d2014-05-27 22:47:41 +00001546 PrologEndLoc = findPrologueEndLoc(MF);
David Blaikie2c78f182017-05-25 23:11:28 +00001547 if (PrologEndLoc) {
Saleem Abdulrasoolfc07c722015-01-24 20:19:45 +00001548 // We'd like to list the prologue as "not statements" but GDB behaves
1549 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
David Blaikie2c78f182017-05-25 23:11:28 +00001550 auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
Duncan P. N. Exon Smithfd07a2a2015-03-30 21:32:28 +00001551 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
Devang Patel34a66202011-05-11 19:22:19 +00001552 }
Bill Wendling2b128d72009-05-20 23:19:06 +00001553}
1554
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001555void DwarfDebug::skippedNonDebugFunction() {
1556 // If we don't have a subprogram for this function then there will be a hole
1557 // in the range information. Keep note of this by setting the previously used
1558 // section to nullptr.
1559 PrevCU = nullptr;
1560 CurFn = nullptr;
1561}
1562
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001563// Gather and emit post-function debug information.
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001564void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
Matthias Braunf1caa282017-12-15 22:22:58 +00001565 const DISubprogram *SP = MF->getFunction().getSubprogram();
David Blaikieb2fbb4b2017-02-16 18:48:33 +00001566
David Blaikiee75f9632014-10-14 17:12:02 +00001567 assert(CurFn == MF &&
1568 "endFunction should be called with the same function as beginFunction");
Timur Iskhodzhanov1cd14442013-12-03 15:10:23 +00001569
Eric Christopher4287a492013-12-09 23:57:44 +00001570 // Set DwarfDwarfCompileUnitID in MCContext to default value.
Lang Hames9ff69c82015-04-24 19:11:51 +00001571 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
Eric Christopher6a841382012-11-19 22:42:10 +00001572
Devang Patel3acc70e2011-08-15 22:04:40 +00001573 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
David Blaikie3e3eb332016-12-15 23:17:52 +00001574 assert(!FnScope || SP == FnScope->getScopeNode());
Adrian Prantl75819ae2016-04-15 15:57:41 +00001575 DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
Alexey Bataevd4dd7212018-08-01 19:38:20 +00001576 if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1577 PrevLabel = nullptr;
1578 CurFn = nullptr;
1579 return;
1580 }
David Blaikie263a0082014-10-23 00:06:27 +00001581
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001582 DenseSet<InlinedEntity> Processed;
1583 collectEntityInfo(TheCU, SP, Processed);
Devang Patel3acc70e2011-08-15 22:04:40 +00001584
David Blaikie3a7ce252014-09-19 17:03:16 +00001585 // Add the range of this function to the list of ranges for the CU.
Rafael Espindola07c03d32015-03-05 02:05:42 +00001586 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
David Blaikie3a7ce252014-09-19 17:03:16 +00001587
1588 // Under -gmlt, skip building the subprogram if there are no inlined
Dehao Chen1ce8d6c2017-01-19 00:44:11 +00001589 // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1590 // is still needed as we need its source location.
Dehao Chen0944a8c2017-02-01 22:45:09 +00001591 if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
Dehao Chen1ce8d6c2017-01-19 00:44:11 +00001592 TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
David Blaikiee1c79742014-09-30 21:28:32 +00001593 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
David Blaikie80e5b1e2014-10-24 17:57:34 +00001594 assert(InfoHolder.getScopeVariables().empty());
David Blaikie3a7ce252014-09-19 17:03:16 +00001595 PrevLabel = nullptr;
1596 CurFn = nullptr;
1597 return;
1598 }
1599
Adrian Prantl049d21c2014-10-13 20:44:58 +00001600#ifndef NDEBUG
1601 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1602#endif
Devang Patel7e623022011-08-10 20:55:27 +00001603 // Construct abstract scopes.
Benjamin Kramer15596c72014-03-07 19:09:39 +00001604 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001605 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
Shiva Chen2c864552018-05-09 02:40:45 +00001606 for (const DINode *DN : SP->getRetainedNodes()) {
Hsiangkai Wang760c1ab2018-09-06 02:22:06 +00001607 if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1608 continue;
1609
1610 const MDNode *Scope = nullptr;
1611 if (auto *DV = dyn_cast<DILocalVariable>(DN))
1612 Scope = DV->getScope();
1613 else if (auto *DL = dyn_cast<DILabel>(DN))
1614 Scope = DL->getScope();
1615 else
1616 llvm_unreachable("Unexpected DI type!");
1617
1618 // Collect info for variables/labels that were optimized out.
1619 ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1620 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1621 && "ensureAbstractEntityIsCreated inserted abstract scopes");
Devang Patel5c0f85c2010-06-25 22:07:34 +00001622 }
David Blaikie488393f2017-05-12 01:13:45 +00001623 constructAbstractSubprogramScopeDIE(TheCU, AScope);
Bill Wendling2b128d72009-05-20 23:19:06 +00001624 }
Eric Christopher6a841382012-11-19 22:42:10 +00001625
David Blaikie38b74bf2016-12-15 23:37:38 +00001626 ProcessedSPNodes.insert(SP);
Vedant Kumar5931b4e2018-10-05 20:37:17 +00001627 DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
David Blaikie3a443c22014-11-04 22:12:25 +00001628 if (auto *SkelCU = TheCU.getSkeleton())
David Blaikiea01f2952016-08-24 18:29:49 +00001629 if (!LScopes.getAbstractScopesList().empty() &&
1630 TheCU.getCUNode()->getSplitDebugInlining())
David Blaikie3e3eb332016-12-15 23:17:52 +00001631 SkelCU->constructSubprogramScopeDIE(SP, FnScope);
Devang Patel3acc70e2011-08-15 22:04:40 +00001632
Vedant Kumar5931b4e2018-10-05 20:37:17 +00001633 // Construct call site entries.
1634 constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1635
Bill Wendling2b128d72009-05-20 23:19:06 +00001636 // Clear debug info
David Blaikie825bdd22014-05-21 22:41:17 +00001637 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1638 // DbgVariables except those that are also in AbstractVariables (since they
1639 // can be used cross-function)
David Blaikie80e5b1e2014-10-24 17:57:34 +00001640 InfoHolder.getScopeVariables().clear();
Hsiangkai Wang2532ac82018-08-17 15:22:04 +00001641 InfoHolder.getScopeLabels().clear();
Craig Topper353eda42014-04-24 06:44:33 +00001642 PrevLabel = nullptr;
1643 CurFn = nullptr;
Bill Wendling2b128d72009-05-20 23:19:06 +00001644}
1645
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001646// Register a source line with debug info. Returns the unique label that was
1647// emitted and which provides correspondence to the source line list.
Devang Patel34a66202011-05-11 19:22:19 +00001648void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1649 unsigned Flags) {
Devang Patel2d9caf92009-11-25 17:36:49 +00001650 StringRef Fn;
Scott Linder16c7bda2018-02-23 23:01:06 +00001651 unsigned FileNo = 1;
Diego Novillo282450d2014-03-03 18:53:17 +00001652 unsigned Discriminator = 0;
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001653 if (auto *Scope = cast_or_null<DIScope>(S)) {
Duncan P. N. Exon Smithb273d062015-04-16 01:37:00 +00001654 Fn = Scope->getFilename();
Paul Robinsonbb921372017-09-07 22:15:44 +00001655 if (Line != 0 && getDwarfVersion() >= 4)
1656 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
Dehao Chen6e0c8442016-10-07 15:21:31 +00001657 Discriminator = LBF->getDiscriminator();
Dan Gohman50849c62010-05-05 23:41:32 +00001658
Lang Hames9ff69c82015-04-24 19:11:51 +00001659 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
Scott Linder16c7bda2018-02-23 23:01:06 +00001660 FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
Paul Robinson612e89d2018-01-12 19:17:50 +00001661 .getOrCreateSourceID(Scope->getFile());
Dan Gohman50849c62010-05-05 23:41:32 +00001662 }
Scott Linder16c7bda2018-02-23 23:01:06 +00001663 Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
Lang Hames9ff69c82015-04-24 19:11:51 +00001664 Discriminator, Fn);
Bill Wendling2b128d72009-05-20 23:19:06 +00001665}
1666
Bill Wendling806535f2009-05-20 23:22:40 +00001667//===----------------------------------------------------------------------===//
1668// Emit Methods
1669//===----------------------------------------------------------------------===//
1670
Eric Christopher9c2ecd92012-11-30 23:59:06 +00001671// Emit the debug info section.
1672void DwarfDebug::emitDebugInfo() {
Eric Christopherf8194852013-12-05 18:06:10 +00001673 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Rafael Espindola063d7252015-03-10 16:58:10 +00001674 Holder.emitUnits(/* UseOffsets */ false);
Eric Christopher9c2ecd92012-11-30 23:59:06 +00001675}
1676
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001677// Emit the abbreviation section.
Eric Christopher38371952012-11-20 23:30:11 +00001678void DwarfDebug::emitAbbreviations() {
Eric Christopherf8194852013-12-05 18:06:10 +00001679 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
David Blaikie0504cda2013-12-05 07:43:55 +00001680
1681 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
Eric Christopher3c5a1912012-12-19 22:02:53 +00001682}
Bill Wendling480ff322009-05-20 23:21:38 +00001683
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001684void DwarfDebug::emitStringOffsetsTableHeader() {
1685 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Pavel Labath7bfa5d62018-07-26 14:36:07 +00001686 Holder.getStringPool().emitStringOffsetsTableHeader(
1687 *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1688 Holder.getStringOffsetsStartSym());
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001689}
1690
Jonas Devliegheree699dfa2018-01-29 14:52:34 +00001691template <typename AccelTableT>
1692void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001693 StringRef TableName) {
Lang Hames9ff69c82015-04-24 19:11:51 +00001694 Asm->OutStreamer->SwitchSection(Section);
Eric Christopher4996c702011-11-07 09:24:32 +00001695
1696 // Emit the full data.
Pavel Labatha7c457d2018-02-19 16:12:20 +00001697 emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
David Blaikie6741bb02014-09-11 21:12:48 +00001698}
1699
Pavel Labath6088c232018-04-04 14:42:14 +00001700void DwarfDebug::emitAccelDebugNames() {
Pavel Labatheadfac82018-04-09 14:38:53 +00001701 // Don't emit anything if we have no compilation units to index.
1702 if (getUnits().empty())
1703 return;
1704
Pavel Labath6088c232018-04-04 14:42:14 +00001705 emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1706}
1707
David Blaikie6741bb02014-09-11 21:12:48 +00001708// Emit visible names into a hashed accelerator table section.
1709void DwarfDebug::emitAccelNames() {
1710 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001711 "Names");
Eric Christopher4996c702011-11-07 09:24:32 +00001712}
1713
Eric Christopher48fef592012-12-20 21:58:40 +00001714// Emit objective C classes and categories into a hashed accelerator table
1715// section.
Eric Christopher4996c702011-11-07 09:24:32 +00001716void DwarfDebug::emitAccelObjC() {
David Blaikie6741bb02014-09-11 21:12:48 +00001717 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001718 "ObjC");
Eric Christopher4996c702011-11-07 09:24:32 +00001719}
1720
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001721// Emit namespace dies into a hashed accelerator table.
Eric Christopher4996c702011-11-07 09:24:32 +00001722void DwarfDebug::emitAccelNamespaces() {
David Blaikie6741bb02014-09-11 21:12:48 +00001723 emitAccel(AccelNamespace,
1724 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001725 "namespac");
Eric Christopher4996c702011-11-07 09:24:32 +00001726}
1727
Eric Christopheracdcbdb2012-11-27 22:43:45 +00001728// Emit type dies into a hashed accelerator table.
Eric Christopher4996c702011-11-07 09:24:32 +00001729void DwarfDebug::emitAccelTypes() {
David Blaikie6741bb02014-09-11 21:12:48 +00001730 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
Rafael Espindola6b9998b2015-03-10 22:00:25 +00001731 "types");
Eric Christopher4996c702011-11-07 09:24:32 +00001732}
1733
Eric Christopherdd1a0122013-09-13 00:35:05 +00001734// Public name handling.
1735// The format for the various pubnames:
1736//
1737// dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1738// for the DIE that is named.
1739//
1740// gnu pubnames - offset/index value/name tuples where the offset is the offset
1741// into the CU and the index value is computed according to the type of value
1742// for the DIE that is named.
1743//
1744// For type units the offset is the offset of the skeleton DIE. For split dwarf
1745// it's the offset within the debug_info/debug_types dwo section, however, the
1746// reference in the pubname header doesn't change.
1747
1748/// computeIndexValue - Compute the gdb index value for the DIE and CU.
Eric Christophera5a79422013-12-09 23:32:48 +00001749static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
Eric Christopher0fe676a2013-11-21 00:48:22 +00001750 const DIE *Die) {
David Blaikiea0e3c752017-02-03 00:44:18 +00001751 // Entities that ended up only in a Type Unit reference the CU instead (since
1752 // the pub entry has offsets within the CU there's no real offset that can be
1753 // provided anyway). As it happens all such entities (namespaces and types,
1754 // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1755 // not to be true it would be necessary to persist this information from the
1756 // point at which the entry is added to the index data structure - since by
1757 // the time the index is built from that, the original type/namespace DIE in a
1758 // type unit has already been destroyed so it can't be queried for properties
1759 // like tag, etc.
1760 if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1761 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1762 dwarf::GIEL_EXTERNAL);
Eric Christopherd2b497b2013-10-16 01:37:49 +00001763 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1764
1765 // We could have a specification DIE that has our most of our knowledge,
1766 // look for that now.
Duncan P. N. Exon Smithe7e1d0c2015-05-27 22:14:58 +00001767 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1768 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
David Blaikie8dbcc3f2014-04-25 19:33:43 +00001769 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
Eric Christopherd2b497b2013-10-16 01:37:49 +00001770 Linkage = dwarf::GIEL_EXTERNAL;
1771 } else if (Die->findAttribute(dwarf::DW_AT_external))
1772 Linkage = dwarf::GIEL_EXTERNAL;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001773
1774 switch (Die->getTag()) {
1775 case dwarf::DW_TAG_class_type:
1776 case dwarf::DW_TAG_structure_type:
1777 case dwarf::DW_TAG_union_type:
1778 case dwarf::DW_TAG_enumeration_type:
Eric Christopher261d2342013-09-23 20:55:35 +00001779 return dwarf::PubIndexEntryDescriptor(
1780 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1781 ? dwarf::GIEL_STATIC
1782 : dwarf::GIEL_EXTERNAL);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001783 case dwarf::DW_TAG_typedef:
1784 case dwarf::DW_TAG_base_type:
1785 case dwarf::DW_TAG_subrange_type:
David Blaikie8dec4072013-09-19 20:40:26 +00001786 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001787 case dwarf::DW_TAG_namespace:
David Blaikie8dec4072013-09-19 20:40:26 +00001788 return dwarf::GIEK_TYPE;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001789 case dwarf::DW_TAG_subprogram:
Eric Christopherccac5c42013-09-23 22:59:14 +00001790 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001791 case dwarf::DW_TAG_variable:
Eric Christopherccac5c42013-09-23 22:59:14 +00001792 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001793 case dwarf::DW_TAG_enumerator:
David Blaikie8dec4072013-09-19 20:40:26 +00001794 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1795 dwarf::GIEL_STATIC);
Eric Christopherdd1a0122013-09-13 00:35:05 +00001796 default:
David Blaikie8dec4072013-09-19 20:40:26 +00001797 return dwarf::GIEK_NONE;
Eric Christopherdd1a0122013-09-13 00:35:05 +00001798 }
Eric Christopherdd1a0122013-09-13 00:35:05 +00001799}
1800
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001801/// emitDebugPubSections - Emit visible names and types into debug pubnames and
1802/// pubtypes sections.
1803void DwarfDebug::emitDebugPubSections() {
David Blaikiec3d9e9e2014-03-06 01:42:00 +00001804 for (const auto &NU : CUMap) {
1805 DwarfCompileUnit *TheU = NU.second;
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001806 if (!TheU->hasDwarfPubSections())
David Blaikiece2f1cb2014-03-11 23:35:06 +00001807 continue;
1808
David Blaikie66cf14d2018-08-16 21:29:55 +00001809 bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
1810 DICompileUnit::DebugNameTableKind::GNU;
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001811
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001812 Asm->OutStreamer->SwitchSection(
1813 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1814 : Asm->getObjFileLowering().getDwarfPubNamesSection());
1815 emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001816
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001817 Asm->OutStreamer->SwitchSection(
1818 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1819 : Asm->getObjFileLowering().getDwarfPubTypesSection());
1820 emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
Krzysztof Parzyszek228daa62013-02-12 18:00:14 +00001821 }
1822}
1823
Alexey Bataevbff36082018-03-23 13:35:54 +00001824void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1825 if (useSectionsAsReferences())
1826 Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1827 CU.getDebugSectionOffset());
1828 else
1829 Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1830}
1831
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001832void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1833 DwarfCompileUnit *TheU,
1834 const StringMap<const DIE *> &Globals) {
1835 if (auto *Skeleton = TheU->getSkeleton())
1836 TheU = Skeleton;
Eric Christopher8b3737f2013-09-13 00:34:58 +00001837
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001838 // Emit the header.
1839 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1840 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1841 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1842 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1843
1844 Asm->OutStreamer->EmitLabel(BeginLabel);
1845
1846 Asm->OutStreamer->AddComment("DWARF Version");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001847 Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001848
1849 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
Alexey Bataevbff36082018-03-23 13:35:54 +00001850 emitSectionReference(*TheU);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001851
1852 Asm->OutStreamer->AddComment("Compilation Unit Length");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001853 Asm->emitInt32(TheU->getLength());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001854
1855 // Emit the pubnames for this compilation unit.
1856 for (const auto &GI : Globals) {
1857 const char *Name = GI.getKeyData();
1858 const DIE *Entity = GI.second;
1859
1860 Asm->OutStreamer->AddComment("DIE offset");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001861 Asm->emitInt32(Entity->getOffset());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001862
1863 if (GnuStyle) {
1864 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1865 Asm->OutStreamer->AddComment(
Fangrui Songd8fd0ec2018-11-13 20:18:08 +00001866 Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
1867 ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001868 Asm->emitInt8(Desc.toBits());
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001869 }
1870
1871 Asm->OutStreamer->AddComment("External Name");
1872 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1873 }
1874
1875 Asm->OutStreamer->AddComment("End Mark");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001876 Asm->emitInt32(0);
Peter Collingbourneb52e2362017-09-12 21:50:41 +00001877 Asm->OutStreamer->EmitLabel(EndLabel);
Devang Patel04d2f2d2009-11-24 01:14:22 +00001878}
1879
Amjad Aboudc0778412016-01-24 08:18:55 +00001880/// Emit null-terminated strings into a debug str section.
Eric Christopher3bf29fd2012-12-27 02:14:01 +00001881void DwarfDebug::emitDebugStr() {
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001882 MCSection *StringOffsetsSection = nullptr;
1883 if (useSegmentedStringOffsetsTable()) {
1884 emitStringOffsetsTableHeader();
1885 StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1886 }
Eric Christopherf8194852013-12-05 18:06:10 +00001887 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Wolfgang Pieb456b5552018-01-26 18:52:58 +00001888 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1889 StringOffsetsSection, /* UseRelativeOffsets = */ true);
Eric Christopher3bf29fd2012-12-27 02:14:01 +00001890}
1891
Eric Christopher29e874d2014-03-07 22:40:37 +00001892void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001893 const DebugLocStream::Entry &Entry) {
1894 auto &&Comments = DebugLocs.getComments(Entry);
1895 auto Comment = Comments.begin();
1896 auto End = Comments.end();
1897 for (uint8_t Byte : DebugLocs.getBytes(Entry))
Adrian Prantl92da14b2015-03-02 22:02:33 +00001898 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
Adrian Prantlb1416832014-08-01 22:11:58 +00001899}
1900
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001901static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
Adrian Prantl92da14b2015-03-02 22:02:33 +00001902 const DebugLocEntry::Value &Value,
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001903 DwarfExpression &DwarfExpr) {
Adrian Prantl956484b2017-03-20 21:35:09 +00001904 auto *DIExpr = Value.getExpression();
1905 DIExpressionCursor ExprCursor(DIExpr);
1906 DwarfExpr.addFragmentOffset(DIExpr);
Adrian Prantlb1416832014-08-01 22:11:58 +00001907 // Regular entry.
Adrian Prantle19e5ef2014-04-27 18:25:40 +00001908 if (Value.isInt()) {
Duncan P. N. Exon Smithfba25d62015-04-17 16:28:58 +00001909 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1910 BT->getEncoding() == dwarf::DW_ATE_signed_char))
Adrian Prantla63b8e82017-03-16 17:42:45 +00001911 DwarfExpr.addSignedConstant(Value.getInt());
Adrian Prantl66f25952015-01-13 00:04:06 +00001912 else
Adrian Prantla63b8e82017-03-16 17:42:45 +00001913 DwarfExpr.addUnsignedConstant(Value.getInt());
Adrian Prantle19e5ef2014-04-27 18:25:40 +00001914 } else if (Value.isLocation()) {
Adrian Prantl956484b2017-03-20 21:35:09 +00001915 MachineLocation Location = Value.getLoc();
Adrian Prantlc12cee32017-04-19 23:42:25 +00001916 if (Location.isIndirect())
1917 DwarfExpr.setMemoryLocationKind();
Adrian Prantl2049c0d2017-08-02 15:22:17 +00001918 DIExpressionCursor Cursor(DIExpr);
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001919 const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
Adrian Prantlc12cee32017-04-19 23:42:25 +00001920 if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
Adrian Prantl956484b2017-03-20 21:35:09 +00001921 return;
1922 return DwarfExpr.addExpression(std::move(Cursor));
Adrian Prantl3e9c8872016-04-08 00:38:37 +00001923 } else if (Value.isConstantFP()) {
1924 APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
Adrian Prantla63b8e82017-03-16 17:42:45 +00001925 DwarfExpr.addUnsignedConstant(RawBytes);
Eric Christopher29e874d2014-03-07 22:40:37 +00001926 }
Adrian Prantla63b8e82017-03-16 17:42:45 +00001927 DwarfExpr.addExpression(std::move(ExprCursor));
Eric Christopher29e874d2014-03-07 22:40:37 +00001928}
1929
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001930void DebugLocEntry::finalize(const AsmPrinter &AP,
1931 DebugLocStream::ListBuilder &List,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001932 const DIBasicType *BT) {
David Stenberg33b192d2019-01-09 09:58:59 +00001933 assert(Begin != End && "unexpected location list entry with empty range");
Duncan P. N. Exon Smith3a73d9e2015-06-21 16:54:56 +00001934 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1935 BufferByteStreamer Streamer = Entry.getStreamer();
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001936 DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001937 const DebugLocEntry::Value &Value = Values[0];
Adrian Prantl941fa752016-12-05 18:04:47 +00001938 if (Value.isFragment()) {
1939 // Emit all fragments that belong to the same variable and range.
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00001940 assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
Adrian Prantl941fa752016-12-05 18:04:47 +00001941 return P.isFragment();
1942 }) && "all values are expected to be fragments");
Adrian Prantl92da14b2015-03-02 22:02:33 +00001943 assert(std::is_sorted(Values.begin(), Values.end()) &&
Adrian Prantl941fa752016-12-05 18:04:47 +00001944 "fragments are expected to be sorted");
Duncan P. N. Exon Smithc82570b2015-04-13 18:53:11 +00001945
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001946 for (auto Fragment : Values)
Petar Jovanovicd175aeb2018-06-28 04:50:40 +00001947 emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001948
Adrian Prantl92da14b2015-03-02 22:02:33 +00001949 } else {
Adrian Prantl941fa752016-12-05 18:04:47 +00001950 assert(Values.size() == 1 && "only fragments may have >1 value");
Petar Jovanovicd175aeb2018-06-28 04:50:40 +00001951 emitDebugLocValue(AP, BT, Value, DwarfExpr);
Adrian Prantl92da14b2015-03-02 22:02:33 +00001952 }
Adrian Prantl8fafb8d2016-12-09 20:43:40 +00001953 DwarfExpr.finalize();
Adrian Prantl92da14b2015-03-02 22:02:33 +00001954}
1955
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00001956void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
Duncan P. N. Exon Smith653c1092015-05-06 19:11:20 +00001957 // Emit the size.
Lang Hames9ff69c82015-04-24 19:11:51 +00001958 Asm->OutStreamer->AddComment("Loc expr size");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00001959 Asm->emitInt16(DebugLocs.getBytes(Entry).size());
Duncan P. N. Exon Smith653c1092015-05-06 19:11:20 +00001960
David Blaikie0e84adc2014-04-01 16:17:41 +00001961 // Emit the entry.
1962 APByteStreamer Streamer(*Asm);
1963 emitDebugLocEntry(Streamer, Entry);
David Blaikie0e84adc2014-04-01 16:17:41 +00001964}
1965
George Rimar088d96b2018-10-26 11:25:12 +00001966// Emit the common part of the DWARF 5 range/locations list tables header.
1967static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder,
1968 MCSymbol *TableStart,
1969 MCSymbol *TableEnd) {
1970 // Build the table header, which starts with the length field.
1971 Asm->OutStreamer->AddComment("Length");
1972 Asm->EmitLabelDifference(TableEnd, TableStart, 4);
1973 Asm->OutStreamer->EmitLabel(TableStart);
1974 // Version number (DWARF v5 and later).
1975 Asm->OutStreamer->AddComment("Version");
1976 Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
1977 // Address size.
1978 Asm->OutStreamer->AddComment("Address size");
1979 Asm->emitInt8(Asm->MAI->getCodePointerSize());
1980 // Segment selector size.
1981 Asm->OutStreamer->AddComment("Segment selector size");
1982 Asm->emitInt8(0);
1983}
1984
1985// Emit the header of a DWARF 5 range list table list table. Returns the symbol
1986// that designates the end of the table for the caller to emit when the table is
1987// complete.
1988static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
1989 const DwarfFile &Holder) {
1990 MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
1991 MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
1992 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
1993
1994 Asm->OutStreamer->AddComment("Offset entry count");
1995 Asm->emitInt32(Holder.getRangeLists().size());
1996 Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
1997
1998 for (const RangeSpanList &List : Holder.getRangeLists())
1999 Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2000 4);
2001
2002 return TableEnd;
2003}
2004
2005// Emit the header of a DWARF 5 locations list table. Returns the symbol that
2006// designates the end of the table for the caller to emit when the table is
2007// complete.
2008static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2009 const DwarfFile &Holder) {
2010 MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2011 MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2012 emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2013
2014 // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2015 // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2016 Asm->OutStreamer->AddComment("Offset entry count");
2017 Asm->emitInt32(0);
2018 Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym());
2019
2020 return TableEnd;
2021}
2022
2023// Emit locations into the .debug_loc/.debug_rnglists section.
Devang Patel930143b2009-11-21 02:48:08 +00002024void DwarfDebug::emitDebugLoc() {
David Blaikie07963bd2017-05-26 18:52:56 +00002025 if (DebugLocs.getLists().empty())
2026 return;
2027
George Rimar088d96b2018-10-26 11:25:12 +00002028 bool IsLocLists = getDwarfVersion() >= 5;
2029 MCSymbol *TableEnd = nullptr;
2030 if (IsLocLists) {
2031 Asm->OutStreamer->SwitchSection(
2032 Asm->getObjFileLowering().getDwarfLoclistsSection());
2033 TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder
2034 : InfoHolder);
2035 } else {
2036 Asm->OutStreamer->SwitchSection(
2037 Asm->getObjFileLowering().getDwarfLocSection());
2038 }
2039
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00002040 unsigned char Size = Asm->MAI->getCodePointerSize();
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002041 for (const auto &List : DebugLocs.getLists()) {
Lang Hames9ff69c82015-04-24 19:11:51 +00002042 Asm->OutStreamer->EmitLabel(List.Label);
George Rimar088d96b2018-10-26 11:25:12 +00002043
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002044 const DwarfCompileUnit *CU = List.CU;
George Rimar088d96b2018-10-26 11:25:12 +00002045 const MCSymbol *Base = CU->getBaseAddress();
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002046 for (const auto &Entry : DebugLocs.getEntries(List)) {
George Rimar088d96b2018-10-26 11:25:12 +00002047 if (Base) {
2048 // Set up the range. This range is relative to the entry point of the
2049 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2050 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2051 if (IsLocLists) {
2052 Asm->OutStreamer->AddComment("DW_LLE_offset_pair");
2053 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1);
2054 Asm->OutStreamer->AddComment(" starting offset");
2055 Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base);
2056 Asm->OutStreamer->AddComment(" ending offset");
2057 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base);
2058 } else {
2059 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
2060 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
2061 }
2062
2063 emitDebugLocEntryLocation(Entry);
2064 continue;
2065 }
2066
2067 // We have no base address.
2068 if (IsLocLists) {
2069 // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2070 // DW_LLE_startx_length in case if there is only a single range.
2071 // That should reduce the size of the debug data emited.
2072 // For now just use the DW_LLE_startx_length for all cases.
2073 Asm->OutStreamer->AddComment("DW_LLE_startx_length");
2074 Asm->emitInt8(dwarf::DW_LLE_startx_length);
2075 Asm->OutStreamer->AddComment(" start idx");
2076 Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym));
2077 Asm->OutStreamer->AddComment(" length");
2078 Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym);
Eric Christopher384f3fe2014-03-20 19:16:16 +00002079 } else {
Lang Hames9ff69c82015-04-24 19:11:51 +00002080 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
2081 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
Eric Christopher384f3fe2014-03-20 19:16:16 +00002082 }
David Blaikie94c1d7f2014-04-02 01:50:20 +00002083
David Blaikie0e84adc2014-04-01 16:17:41 +00002084 emitDebugLocEntryLocation(Entry);
Devang Patel9fc11702010-05-25 23:40:22 +00002085 }
George Rimar088d96b2018-10-26 11:25:12 +00002086
2087 if (IsLocLists) {
2088 // .debug_loclists section ends with DW_LLE_end_of_list.
2089 Asm->OutStreamer->AddComment("DW_LLE_end_of_list");
2090 Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1);
2091 } else {
2092 // Terminate the .debug_loc list with two 0 values.
2093 Asm->OutStreamer->EmitIntValue(0, Size);
2094 Asm->OutStreamer->EmitIntValue(0, Size);
2095 }
David Blaikie94c1d7f2014-04-02 01:50:20 +00002096 }
George Rimar088d96b2018-10-26 11:25:12 +00002097
2098 if (TableEnd)
2099 Asm->OutStreamer->EmitLabel(TableEnd);
David Blaikie94c1d7f2014-04-02 01:50:20 +00002100}
2101
2102void DwarfDebug::emitDebugLocDWO() {
Lang Hames9ff69c82015-04-24 19:11:51 +00002103 Asm->OutStreamer->SwitchSection(
David Blaikie94c1d7f2014-04-02 01:50:20 +00002104 Asm->getObjFileLowering().getDwarfLocDWOSection());
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002105 for (const auto &List : DebugLocs.getLists()) {
Lang Hames9ff69c82015-04-24 19:11:51 +00002106 Asm->OutStreamer->EmitLabel(List.Label);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002107 for (const auto &Entry : DebugLocs.getEntries(List)) {
David Blaikie73c2f192018-10-25 22:26:25 +00002108 // GDB only supports startx_length in pre-standard split-DWARF.
2109 // (in v5 standard loclists, it currently* /only/ supports base_address +
2110 // offset_pair, so the implementations can't really share much since they
2111 // need to use different representations)
2112 // * as of October 2018, at least
2113 // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2114 // in the address pool to minimize object size/relocations.
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002115 Asm->emitInt8(dwarf::DW_LLE_startx_length);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002116 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
David Blaikie94c1d7f2014-04-02 01:50:20 +00002117 Asm->EmitULEB128(idx);
Duncan P. N. Exon Smith364a3002015-04-17 21:34:47 +00002118 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
David Blaikie94c1d7f2014-04-02 01:50:20 +00002119
2120 emitDebugLocEntryLocation(Entry);
David Blaikie9c550ac2014-03-25 01:44:02 +00002121 }
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002122 Asm->emitInt8(dwarf::DW_LLE_end_of_list);
Devang Patel9fc11702010-05-25 23:40:22 +00002123 }
Bill Wendling480ff322009-05-20 23:21:38 +00002124}
2125
Richard Mitton21101b32013-09-19 23:21:01 +00002126struct ArangeSpan {
2127 const MCSymbol *Start, *End;
2128};
2129
2130// Emit a debug aranges section, containing a CU lookup for any
2131// address we can tie back to a CU.
Eric Christopher7b30f2e42012-11-21 00:34:35 +00002132void DwarfDebug::emitDebugARanges() {
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002133 // Provides a unique id per text section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00002134 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
Richard Mitton21101b32013-09-19 23:21:01 +00002135
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002136 // Filter labels by section.
2137 for (const SymbolCU &SCU : ArangeLabels) {
2138 if (SCU.Sym->isInSection()) {
2139 // Make a note of this symbol and it's section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00002140 MCSection *Section = &SCU.Sym->getSection();
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002141 if (!Section->getKind().isMetadata())
2142 SectionMap[Section].push_back(SCU);
2143 } else {
2144 // Some symbols (e.g. common/bss on mach-o) can have no section but still
2145 // appear in the output. This sucks as we rely on sections to build
2146 // arange spans. We can do it without, but it's icky.
2147 SectionMap[nullptr].push_back(SCU);
2148 }
2149 }
Richard Mitton21101b32013-09-19 23:21:01 +00002150
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002151 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2152
Rafael Espindola4f4ef152015-03-09 22:08:37 +00002153 for (auto &I : SectionMap) {
Rafael Espindola78d947b2016-05-20 00:38:28 +00002154 MCSection *Section = I.first;
Rafael Espindola4f4ef152015-03-09 22:08:37 +00002155 SmallVector<SymbolCU, 8> &List = I.second;
Rafael Espindola78d947b2016-05-20 00:38:28 +00002156 if (List.size() < 1)
Richard Mitton21101b32013-09-19 23:21:01 +00002157 continue;
2158
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00002159 // If we have no section (e.g. common), just write out
2160 // individual spans for each symbol.
2161 if (!Section) {
2162 for (const SymbolCU &Cur : List) {
2163 ArangeSpan Span;
2164 Span.Start = Cur.Sym;
2165 Span.End = nullptr;
Rafael Espindola78d947b2016-05-20 00:38:28 +00002166 assert(Cur.CU);
2167 Spans[Cur.CU].push_back(Span);
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00002168 }
2169 continue;
2170 }
2171
Richard Mitton21101b32013-09-19 23:21:01 +00002172 // Sort the symbols by offset within the section.
Mandeep Singh Grang46d02de2018-02-25 19:52:34 +00002173 std::stable_sort(
Rafael Espindola0a78f8c2016-05-19 23:17:37 +00002174 List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
2175 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2176 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
Benjamin Kramer571e2fe2014-03-07 19:41:22 +00002177
Rafael Espindola0a78f8c2016-05-19 23:17:37 +00002178 // Symbols with no order assigned should be placed at the end.
2179 // (e.g. section end labels)
2180 if (IA == 0)
2181 return false;
2182 if (IB == 0)
2183 return true;
2184 return IA < IB;
2185 });
Richard Mitton21101b32013-09-19 23:21:01 +00002186
Rafael Espindola78d947b2016-05-20 00:38:28 +00002187 // Insert a final terminator.
2188 List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2189
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00002190 // Build spans between each label.
2191 const MCSymbol *StartSym = List[0].Sym;
2192 for (size_t n = 1, e = List.size(); n < e; n++) {
2193 const SymbolCU &Prev = List[n - 1];
2194 const SymbolCU &Cur = List[n];
Richard Mitton21101b32013-09-19 23:21:01 +00002195
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00002196 // Try and build the longest span we can within the same CU.
2197 if (Cur.CU != Prev.CU) {
2198 ArangeSpan Span;
2199 Span.Start = StartSym;
2200 Span.End = Cur.Sym;
Rafael Espindola78d947b2016-05-20 00:38:28 +00002201 assert(Prev.CU);
Rafael Espindola6ffb1d72015-02-02 19:22:51 +00002202 Spans[Prev.CU].push_back(Span);
2203 StartSym = Cur.Sym;
Richard Mitton21101b32013-09-19 23:21:01 +00002204 }
2205 }
2206 }
2207
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002208 // Start the dwarf aranges section.
Lang Hames9ff69c82015-04-24 19:11:51 +00002209 Asm->OutStreamer->SwitchSection(
Rafael Espindolae8fd00d2015-02-26 22:02:02 +00002210 Asm->getObjFileLowering().getDwarfARangesSection());
2211
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00002212 unsigned PtrSize = Asm->MAI->getCodePointerSize();
Richard Mitton21101b32013-09-19 23:21:01 +00002213
2214 // Build a list of CUs used.
Eric Christopher4287a492013-12-09 23:57:44 +00002215 std::vector<DwarfCompileUnit *> CUs;
Benjamin Kramer15596c72014-03-07 19:09:39 +00002216 for (const auto &it : Spans) {
2217 DwarfCompileUnit *CU = it.first;
Richard Mitton21101b32013-09-19 23:21:01 +00002218 CUs.push_back(CU);
2219 }
2220
2221 // Sort the CU list (again, to ensure consistent output order).
Fangrui Song0cac7262018-09-27 02:13:45 +00002222 llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2223 return A->getUniqueID() < B->getUniqueID();
2224 });
Richard Mitton21101b32013-09-19 23:21:01 +00002225
2226 // Emit an arange table for each CU we used.
Benjamin Kramer15596c72014-03-07 19:09:39 +00002227 for (DwarfCompileUnit *CU : CUs) {
Richard Mitton21101b32013-09-19 23:21:01 +00002228 std::vector<ArangeSpan> &List = Spans[CU];
2229
David Blaikie27e35f22014-11-02 01:21:43 +00002230 // Describe the skeleton CU's offset and length, not the dwo file's.
2231 if (auto *Skel = CU->getSkeleton())
2232 CU = Skel;
2233
Richard Mitton21101b32013-09-19 23:21:01 +00002234 // Emit size of content not including length itself.
Eric Christopherb4bef6d2013-11-19 09:04:36 +00002235 unsigned ContentSize =
2236 sizeof(int16_t) + // DWARF ARange version number
2237 sizeof(int32_t) + // Offset of CU in the .debug_info section
2238 sizeof(int8_t) + // Pointer Size (in bytes)
2239 sizeof(int8_t); // Segment Size (in bytes)
Richard Mitton21101b32013-09-19 23:21:01 +00002240
2241 unsigned TupleSize = PtrSize * 2;
2242
2243 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
Benjamin Kramer8a68ab32014-01-07 19:28:14 +00002244 unsigned Padding =
2245 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
Richard Mitton21101b32013-09-19 23:21:01 +00002246
2247 ContentSize += Padding;
2248 ContentSize += (List.size() + 1) * TupleSize;
2249
2250 // For each compile unit, write the list of spans it covers.
Lang Hames9ff69c82015-04-24 19:11:51 +00002251 Asm->OutStreamer->AddComment("Length of ARange Set");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002252 Asm->emitInt32(ContentSize);
Lang Hames9ff69c82015-04-24 19:11:51 +00002253 Asm->OutStreamer->AddComment("DWARF Arange version number");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002254 Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
Lang Hames9ff69c82015-04-24 19:11:51 +00002255 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
Alexey Bataevbff36082018-03-23 13:35:54 +00002256 emitSectionReference(*CU);
Lang Hames9ff69c82015-04-24 19:11:51 +00002257 Asm->OutStreamer->AddComment("Address Size (in bytes)");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002258 Asm->emitInt8(PtrSize);
Lang Hames9ff69c82015-04-24 19:11:51 +00002259 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002260 Asm->emitInt8(0);
Richard Mitton21101b32013-09-19 23:21:01 +00002261
Petr Hosekfaef3202016-06-01 01:59:58 +00002262 Asm->OutStreamer->emitFill(Padding, 0xff);
Richard Mitton21101b32013-09-19 23:21:01 +00002263
Benjamin Kramer15596c72014-03-07 19:09:39 +00002264 for (const ArangeSpan &Span : List) {
Richard Mitton21101b32013-09-19 23:21:01 +00002265 Asm->EmitLabelReference(Span.Start, PtrSize);
2266
2267 // Calculate the size as being from the span start to it's end.
Richard Mitton089ed892013-09-23 17:56:20 +00002268 if (Span.End) {
Richard Mitton21101b32013-09-19 23:21:01 +00002269 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
Richard Mitton089ed892013-09-23 17:56:20 +00002270 } else {
2271 // For symbols without an end marker (e.g. common), we
2272 // write a single arange entry containing just that one symbol.
2273 uint64_t Size = SymSize[Span.Start];
2274 if (Size == 0)
2275 Size = 1;
2276
Lang Hames9ff69c82015-04-24 19:11:51 +00002277 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
Richard Mitton089ed892013-09-23 17:56:20 +00002278 }
Richard Mitton21101b32013-09-19 23:21:01 +00002279 }
2280
Lang Hames9ff69c82015-04-24 19:11:51 +00002281 Asm->OutStreamer->AddComment("ARange terminator");
2282 Asm->OutStreamer->EmitIntValue(0, PtrSize);
2283 Asm->OutStreamer->EmitIntValue(0, PtrSize);
Richard Mitton21101b32013-09-19 23:21:01 +00002284 }
Bill Wendling480ff322009-05-20 23:21:38 +00002285}
2286
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002287/// Emit a single range list. We handle both DWARF v5 and earlier.
David Blaikiec4af8bf2018-10-20 07:36:39 +00002288static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
Wolfgang Piebe194f732018-07-10 00:10:11 +00002289 const RangeSpanList &List) {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002290
David Blaikiec4af8bf2018-10-20 07:36:39 +00002291 auto DwarfVersion = DD.getDwarfVersion();
Wolfgang Piebe194f732018-07-10 00:10:11 +00002292 // Emit our symbol so we can find the beginning of the range.
2293 Asm->OutStreamer->EmitLabel(List.getSym());
2294 // Gather all the ranges that apply to the same section so they can share
2295 // a base address entry.
2296 MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
2297 // Size for our labels.
2298 auto Size = Asm->MAI->getCodePointerSize();
2299
2300 for (const RangeSpan &Range : List.getRanges())
2301 SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2302
David Blaikiec8f7e6c2018-11-08 00:35:54 +00002303 const DwarfCompileUnit &CU = List.getCU();
2304 const MCSymbol *CUBase = CU.getBaseAddress();
Wolfgang Piebe194f732018-07-10 00:10:11 +00002305 bool BaseIsSet = false;
2306 for (const auto &P : SectionRanges) {
2307 // Don't bother with a base address entry if there's only one range in
2308 // this section in this range list - for example ranges for a CU will
2309 // usually consist of single regions from each of many sections
2310 // (-ffunction-sections, or just C++ inline functions) except under LTO
2311 // or optnone where there may be holes in a single CU's section
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002312 // contributions.
Wolfgang Piebe194f732018-07-10 00:10:11 +00002313 auto *Base = CUBase;
David Blaikie14cfa0d2018-10-20 09:16:49 +00002314 if (!Base && (P.second.size() > 1 || DwarfVersion < 5) &&
David Blaikiebb279112018-11-13 20:08:10 +00002315 (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) {
Wolfgang Piebe194f732018-07-10 00:10:11 +00002316 BaseIsSet = true;
2317 // FIXME/use care: This may not be a useful base address if it's not
2318 // the lowest address/range in this object.
2319 Base = P.second.front()->getStart();
David Blaikied6614052018-07-18 18:04:42 +00002320 if (DwarfVersion >= 5) {
David Blaikie60fddac2018-10-24 23:36:29 +00002321 Base = DD.getSectionLabel(&Base->getSection());
David Blaikiec4af8bf2018-10-20 07:36:39 +00002322 Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
2323 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
2324 Asm->OutStreamer->AddComment(" base address index");
2325 Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2326 } else {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002327 Asm->OutStreamer->EmitIntValue(-1, Size);
David Blaikiec4af8bf2018-10-20 07:36:39 +00002328 Asm->OutStreamer->AddComment(" base address");
2329 Asm->OutStreamer->EmitSymbolValue(Base, Size);
2330 }
David Blaikied6614052018-07-18 18:04:42 +00002331 } else if (BaseIsSet && DwarfVersion < 5) {
Wolfgang Piebe194f732018-07-10 00:10:11 +00002332 BaseIsSet = false;
David Blaikied6614052018-07-18 18:04:42 +00002333 assert(!Base);
2334 Asm->OutStreamer->EmitIntValue(-1, Size);
Wolfgang Piebe194f732018-07-10 00:10:11 +00002335 Asm->OutStreamer->EmitIntValue(0, Size);
2336 }
2337
2338 for (const auto *RS : P.second) {
2339 const MCSymbol *Begin = RS->getStart();
2340 const MCSymbol *End = RS->getEnd();
2341 assert(Begin && "Range without a begin symbol?");
2342 assert(End && "Range without an end symbol?");
2343 if (Base) {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002344 if (DwarfVersion >= 5) {
2345 // Emit DW_RLE_offset_pair when we have a base.
David Blaikied6614052018-07-18 18:04:42 +00002346 Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002347 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
David Blaikied6614052018-07-18 18:04:42 +00002348 Asm->OutStreamer->AddComment(" starting offset");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002349 Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
David Blaikied6614052018-07-18 18:04:42 +00002350 Asm->OutStreamer->AddComment(" ending offset");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002351 Asm->EmitLabelDifferenceAsULEB128(End, Base);
2352 } else {
2353 Asm->EmitLabelDifference(Begin, Base, Size);
2354 Asm->EmitLabelDifference(End, Base, Size);
2355 }
2356 } else if (DwarfVersion >= 5) {
David Blaikiec4af8bf2018-10-20 07:36:39 +00002357 Asm->OutStreamer->AddComment("DW_RLE_startx_length");
2358 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
2359 Asm->OutStreamer->AddComment(" start index");
2360 Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
David Blaikied6614052018-07-18 18:04:42 +00002361 Asm->OutStreamer->AddComment(" length");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002362 Asm->EmitLabelDifferenceAsULEB128(End, Begin);
Wolfgang Piebe194f732018-07-10 00:10:11 +00002363 } else {
2364 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2365 Asm->OutStreamer->EmitSymbolValue(End, Size);
2366 }
2367 }
2368 }
David Blaikied6614052018-07-18 18:04:42 +00002369 if (DwarfVersion >= 5) {
2370 Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002371 Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
David Blaikied6614052018-07-18 18:04:42 +00002372 } else {
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002373 // Terminate the list with two 0 values.
2374 Asm->OutStreamer->EmitIntValue(0, Size);
2375 Asm->OutStreamer->EmitIntValue(0, Size);
2376 }
Wolfgang Piebe194f732018-07-10 00:10:11 +00002377}
2378
Benjamin Kramerb17d2132019-01-12 18:36:22 +00002379static void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm,
2380 const DwarfFile &Holder, MCSymbol *TableEnd) {
David Blaikiec4af8bf2018-10-20 07:36:39 +00002381 for (const RangeSpanList &List : Holder.getRangeLists())
2382 emitRangeList(DD, Asm, List);
2383
2384 if (TableEnd)
2385 Asm->OutStreamer->EmitLabel(TableEnd);
2386}
2387
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002388/// Emit address ranges into the .debug_ranges section or into the DWARF v5
2389/// .debug_rnglists section.
Devang Patel930143b2009-11-21 02:48:08 +00002390void DwarfDebug::emitDebugRanges() {
David Blaikie07963bd2017-05-26 18:52:56 +00002391 if (CUMap.empty())
2392 return;
2393
David Blaikiec4af8bf2018-10-20 07:36:39 +00002394 const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002395
David Blaikiec4af8bf2018-10-20 07:36:39 +00002396 if (Holder.getRangeLists().empty())
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002397 return;
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002398
David Blaikiec4af8bf2018-10-20 07:36:39 +00002399 assert(useRangesSection());
2400 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2401 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2402 }));
Wolfgang Piebfcf38102018-07-12 18:18:21 +00002403
Bill Wendling480ff322009-05-20 23:21:38 +00002404 // Start the dwarf ranges section.
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002405 MCSymbol *TableEnd = nullptr;
2406 if (getDwarfVersion() >= 5) {
2407 Asm->OutStreamer->SwitchSection(
2408 Asm->getObjFileLowering().getDwarfRnglistsSection());
David Blaikiec4af8bf2018-10-20 07:36:39 +00002409 TableEnd = emitRnglistsTableHeader(Asm, Holder);
Wolfgang Pieb9ea65082018-07-26 22:48:52 +00002410 } else
2411 Asm->OutStreamer->SwitchSection(
2412 Asm->getObjFileLowering().getDwarfRangesSection());
Eric Christopher4751d702013-11-23 00:05:29 +00002413
David Blaikiec4af8bf2018-10-20 07:36:39 +00002414 emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
Bill Wendling480ff322009-05-20 23:21:38 +00002415}
2416
David Blaikie32e09de2018-10-20 08:12:36 +00002417void DwarfDebug::emitDebugRangesDWO() {
2418 assert(useSplitDwarf());
2419
2420 if (CUMap.empty())
2421 return;
2422
2423 const auto &Holder = InfoHolder;
2424
2425 if (Holder.getRangeLists().empty())
2426 return;
2427
2428 assert(getDwarfVersion() >= 5);
2429 assert(useRangesSection());
2430 assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2431 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2432 }));
2433
2434 // Start the dwarf ranges section.
2435 Asm->OutStreamer->SwitchSection(
2436 Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2437 MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder);
2438
2439 emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2440}
2441
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002442void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002443 for (auto *MN : Nodes) {
2444 if (auto *M = dyn_cast<DIMacro>(MN))
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002445 emitMacro(*M);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002446 else if (auto *F = dyn_cast<DIMacroFile>(MN))
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002447 emitMacroFile(*F, U);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002448 else
2449 llvm_unreachable("Unexpected DI type!");
2450 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002451}
2452
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002453void DwarfDebug::emitMacro(DIMacro &M) {
2454 Asm->EmitULEB128(M.getMacinfoType());
2455 Asm->EmitULEB128(M.getLine());
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002456 StringRef Name = M.getName();
2457 StringRef Value = M.getValue();
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002458 Asm->OutStreamer->EmitBytes(Name);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002459 if (!Value.empty()) {
2460 // There should be one space between macro name and macro value.
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002461 Asm->emitInt8(' ');
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002462 Asm->OutStreamer->EmitBytes(Value);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002463 }
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002464 Asm->emitInt8('\0');
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002465}
2466
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002467void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002468 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002469 Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2470 Asm->EmitULEB128(F.getLine());
Paul Robinson612e89d2018-01-12 19:17:50 +00002471 Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002472 handleMacroNodes(F.getElements(), U);
2473 Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002474}
2475
Amjad Aboudc0778412016-01-24 08:18:55 +00002476/// Emit macros into a debug macinfo section.
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002477void DwarfDebug::emitDebugMacinfo() {
David Blaikie07963bd2017-05-26 18:52:56 +00002478 if (CUMap.empty())
2479 return;
2480
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002481 if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2482 return Pair.second->getCUNode()->isDebugDirectivesOnly();
2483 }))
2484 return;
2485
Amjad Aboud8bbce8a2016-02-01 14:09:41 +00002486 // Start the dwarf macinfo section.
2487 Asm->OutStreamer->SwitchSection(
2488 Asm->getObjFileLowering().getDwarfMacinfoSection());
2489
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002490 for (const auto &P : CUMap) {
2491 auto &TheCU = *P.second;
Alexey Bataevd4dd7212018-08-01 19:38:20 +00002492 if (TheCU.getCUNode()->isDebugDirectivesOnly())
2493 continue;
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002494 auto *SkCU = TheCU.getSkeleton();
2495 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2496 auto *CUNode = cast<DICompileUnit>(P.first);
Alexey Bataevbd7869442018-02-22 16:20:30 +00002497 DIMacroNodeArray Macros = CUNode->getMacros();
2498 if (!Macros.empty()) {
2499 Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2500 handleMacroNodes(Macros, U);
2501 }
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002502 }
2503 Asm->OutStreamer->AddComment("End Of Macro List Mark");
Rafael Espindola4b4d85f2018-03-29 23:32:54 +00002504 Asm->emitInt8(0);
Amjad Aboudd7cfb482016-01-07 14:28:20 +00002505}
2506
Eric Christopherd692c1d2012-12-11 19:42:09 +00002507// DWARF5 Experimental Separate Dwarf emitters.
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002508
David Blaikie65a74662014-04-25 18:26:14 +00002509void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002510 std::unique_ptr<DwarfCompileUnit> NewU) {
David Blaikie38fe6342014-01-09 04:28:46 +00002511
David Blaikie38fe6342014-01-09 04:28:46 +00002512 if (!CompilationDir.empty())
David Blaikiecafd9622014-11-02 08:51:37 +00002513 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
David Blaikie38fe6342014-01-09 04:28:46 +00002514
David Blaikief9b6a552014-04-22 22:39:41 +00002515 addGnuPubAttributes(*NewU, Die);
David Blaikie38fe6342014-01-09 04:28:46 +00002516
David Blaikief9b6a552014-04-22 22:39:41 +00002517 SkeletonHolder.addUnit(std::move(NewU));
David Blaikie38fe6342014-01-09 04:28:46 +00002518}
2519
David Blaikief9b6a552014-04-22 22:39:41 +00002520DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002521
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00002522 auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
David Blaikiebd579052014-04-28 21:14:27 +00002523 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
David Blaikief9b6a552014-04-22 22:39:41 +00002524 DwarfCompileUnit &NewCU = *OwnedUnit;
Greg Clayton35630c32016-12-01 18:56:29 +00002525 NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
Eric Christopher4c7765f2013-01-17 03:00:04 +00002526
Rafael Espindola063d7252015-03-10 16:58:10 +00002527 NewCU.initStmtList();
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002528
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002529 if (useSegmentedStringOffsetsTable())
2530 NewCU.addStringOffsetsStart();
2531
David Blaikie92a2f8a2014-04-28 21:04:29 +00002532 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
Eric Christopherc8a310e2012-12-10 23:34:43 +00002533
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002534 return NewCU;
2535}
2536
Eric Christopherd692c1d2012-12-11 19:42:09 +00002537// Emit the .debug_info.dwo section for separated dwarf. This contains the
2538// compile units that would normally be in debug_info.
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002539void DwarfDebug::emitDebugInfoDWO() {
Eric Christophercdf218d2012-12-10 19:51:21 +00002540 assert(useSplitDwarf() && "No split dwarf debug info?");
Rafael Espindola063d7252015-03-10 16:58:10 +00002541 // Don't emit relocations into the dwo file.
2542 InfoHolder.emitUnits(/* UseOffsets */ true);
Eric Christopher3c5a1912012-12-19 22:02:53 +00002543}
2544
2545// Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2546// abbreviations for the .debug_info.dwo section.
2547void DwarfDebug::emitDebugAbbrevDWO() {
2548 assert(useSplitDwarf() && "No split dwarf?");
David Blaikie0504cda2013-12-05 07:43:55 +00002549 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
Eric Christopher9c2ecd92012-11-30 23:59:06 +00002550}
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002551
David Blaikie4a2f95f2014-03-18 01:17:26 +00002552void DwarfDebug::emitDebugLineDWO() {
2553 assert(useSplitDwarf() && "No split dwarf?");
Paul Robinson7cb26ad2018-03-27 21:28:59 +00002554 SplitTypeUnitFileTable.Emit(
2555 *Asm->OutStreamer, MCDwarfLineTableParams(),
David Blaikie4a2f95f2014-03-18 01:17:26 +00002556 Asm->getObjFileLowering().getDwarfLineDWOSection());
David Blaikie4a2f95f2014-03-18 01:17:26 +00002557}
2558
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002559void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2560 assert(useSplitDwarf() && "No split dwarf?");
Pavel Labath7bfa5d62018-07-26 14:36:07 +00002561 InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2562 *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2563 InfoHolder.getStringOffsetsStartSym());
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002564}
2565
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002566// Emit the .debug_str.dwo section for separated dwarf. This contains the
2567// string section and is identical in format to traditional .debug_str
2568// sections.
2569void DwarfDebug::emitDebugStrDWO() {
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002570 if (useSegmentedStringOffsetsTable())
2571 emitStringOffsetsTableHeaderDWO();
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002572 assert(useSplitDwarf() && "No split dwarf?");
Rafael Espindola0709a7b2015-05-21 19:20:38 +00002573 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
Eric Christopher2cbd5762013-01-07 19:32:41 +00002574 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002575 OffSec, /* UseRelativeOffsets = */ false);
Eric Christopher3bf29fd2012-12-27 02:14:01 +00002576}
David Blaikie409dd9c2013-11-19 23:08:21 +00002577
David Blaikie161dd3c2018-10-20 06:02:15 +00002578// Emit address pool.
Victor Leschuk64e0c562018-08-01 05:48:06 +00002579void DwarfDebug::emitDebugAddr() {
Victor Leschuk64e0c562018-08-01 05:48:06 +00002580 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2581}
2582
David Blaikie47f4b822014-03-19 00:11:28 +00002583MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2584 if (!useSplitDwarf())
2585 return nullptr;
Paul Robinsonb271f312018-03-29 17:16:41 +00002586 const DICompileUnit *DIUnit = CU.getCUNode();
2587 SplitTypeUnitFileTable.maybeSetRootFile(
2588 DIUnit->getDirectory(), DIUnit->getFilename(),
2589 CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
David Blaikie47f4b822014-03-19 00:11:28 +00002590 return &SplitTypeUnitFileTable;
2591}
2592
Adrian Prantlee5feaf2015-07-15 17:01:41 +00002593uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
David Blaikief3de2ab2014-04-26 16:26:41 +00002594 MD5 Hash;
2595 Hash.update(Identifier);
2596 // ... take the least significant 8 bytes and return those. Our MD5
Zachary Turner82a0c972017-03-20 23:33:18 +00002597 // implementation always returns its results in little endian, so we actually
2598 // need the "high" word.
David Blaikief3de2ab2014-04-26 16:26:41 +00002599 MD5::MD5Result Result;
2600 Hash.final(Result);
Zachary Turner82a0c972017-03-20 23:33:18 +00002601 return Result.high();
David Blaikief3de2ab2014-04-26 16:26:41 +00002602}
2603
David Blaikie15632ae2014-02-12 00:31:30 +00002604void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
David Blaikie65a74662014-04-25 18:26:14 +00002605 StringRef Identifier, DIE &RefDie,
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002606 const DICompositeType *CTy) {
David Blaikiee12b49a2014-04-26 17:27:38 +00002607 // Fast path if we're building some type units and one has already used the
2608 // address pool we know we're going to throw away all this work anyway, so
2609 // don't bother building dependent types.
2610 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2611 return;
2612
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002613 auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2614 if (!Ins.second) {
2615 CU.addDIETypeSignature(RefDie, Ins.first->second);
Chandler Carruthb587ab62014-01-20 08:07:07 +00002616 return;
David Blaikie409dd9c2013-11-19 23:08:21 +00002617 }
2618
David Blaikiee12b49a2014-04-26 17:27:38 +00002619 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2620 AddrPool.resetUsedFlag();
2621
Eugene Zelenko6e07bfd2017-08-17 21:26:39 +00002622 auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2623 getDwoLineTable(CU));
David Blaikief9b6a552014-04-22 22:39:41 +00002624 DwarfTypeUnit &NewTU = *OwnedUnit;
David Blaikie92a2f8a2014-04-28 21:04:29 +00002625 DIE &UnitDie = NewTU.getUnitDie();
David Majnemer0a16c222016-08-11 21:15:00 +00002626 TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
Chandler Carruthb587ab62014-01-20 08:07:07 +00002627
David Blaikie92a2f8a2014-04-28 21:04:29 +00002628 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
David Blaikie637cac42014-04-22 23:09:36 +00002629 CU.getLanguage());
Chandler Carruthb587ab62014-01-20 08:07:07 +00002630
David Blaikief3de2ab2014-04-26 16:26:41 +00002631 uint64_t Signature = makeTypeSignature(Identifier);
David Blaikief9b6a552014-04-22 22:39:41 +00002632 NewTU.setTypeSignature(Signature);
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002633 Ins.first->second = Signature;
David Blaikief3de2ab2014-04-26 16:26:41 +00002634
Paul Robinson5b302bf2018-11-12 16:55:11 +00002635 if (useSplitDwarf()) {
2636 MCSection *Section =
2637 getDwarfVersion() <= 4
2638 ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2639 : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2640 NewTU.setSection(Section);
2641 } else {
Paul Robinsonddbde9a2018-11-09 19:06:09 +00002642 MCSection *Section =
2643 getDwarfVersion() <= 4
2644 ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2645 : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2646 NewTU.setSection(Section);
Paul Robinson7cb26ad2018-03-27 21:28:59 +00002647 // Non-split type units reuse the compile unit's line table.
2648 CU.applyStmtList(UnitDie);
David Blaikie29459ae2014-07-25 17:11:58 +00002649 }
Chandler Carruthb587ab62014-01-20 08:07:07 +00002650
Wolfgang Pieb456b5552018-01-26 18:52:58 +00002651 // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2652 // units.
2653 if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2654 NewTU.addStringOffsetsStart();
2655
David Blaikief3de2ab2014-04-26 16:26:41 +00002656 NewTU.setType(NewTU.createTypeDIE(CTy));
2657
David Blaikiee12b49a2014-04-26 17:27:38 +00002658 if (TopLevelType) {
2659 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2660 TypeUnitsUnderConstruction.clear();
2661
2662 // Types referencing entries in the address table cannot be placed in type
2663 // units.
2664 if (AddrPool.hasBeenUsed()) {
2665
2666 // Remove all the types built while building this type.
2667 // This is pessimistic as some of these types might not be dependent on
2668 // the type that used an address.
2669 for (const auto &TU : TypeUnitsToAdd)
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002670 TypeSignatures.erase(TU.second);
David Blaikiee12b49a2014-04-26 17:27:38 +00002671
2672 // Construct this type in the CU directly.
2673 // This is inefficient because all the dependent types will be rebuilt
2674 // from scratch, including building them in type units, discovering that
2675 // they depend on addresses, throwing them out and rebuilding them.
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002676 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
David Blaikiee12b49a2014-04-26 17:27:38 +00002677 return;
2678 }
2679
2680 // If the type wasn't dependent on fission addresses, finish adding the type
2681 // and all its dependent types.
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002682 for (auto &TU : TypeUnitsToAdd) {
2683 InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2684 InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2685 }
David Blaikiee12b49a2014-04-26 17:27:38 +00002686 }
Peter Collingbourne7c384cc2016-02-11 19:57:46 +00002687 CU.addDIETypeSignature(RefDie, Signature);
David Blaikie409dd9c2013-11-19 23:08:21 +00002688}
David Blaikie4bd13b72014-03-07 18:49:45 +00002689
Pavel Labath7f7e6062018-07-20 15:24:13 +00002690// Add the Name along with its companion DIE to the appropriate accelerator
2691// table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2692// AccelTableKind::Apple, we use the table we got as an argument). If
2693// accelerator tables are disabled, this function does nothing.
2694template <typename DataT>
David Blaikie66cf14d2018-08-16 21:29:55 +00002695void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
2696 AccelTable<DataT> &AppleAccel, StringRef Name,
Pavel Labath7f7e6062018-07-20 15:24:13 +00002697 const DIE &Die) {
2698 if (getAccelTableKind() == AccelTableKind::None)
2699 return;
Pavel Labath3fb39c72018-04-18 12:11:59 +00002700
David Blaikie66cf14d2018-08-16 21:29:55 +00002701 if (getAccelTableKind() != AccelTableKind::Apple &&
2702 CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
2703 return;
2704
Pavel Labath3fb39c72018-04-18 12:11:59 +00002705 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
Pavel Labath2f088112018-08-07 09:54:52 +00002706 DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
Pavel Labath3fb39c72018-04-18 12:11:59 +00002707
Pavel Labath6088c232018-04-04 14:42:14 +00002708 switch (getAccelTableKind()) {
2709 case AccelTableKind::Apple:
Pavel Labath7f7e6062018-07-20 15:24:13 +00002710 AppleAccel.addName(Ref, Die);
Pavel Labath6088c232018-04-04 14:42:14 +00002711 break;
2712 case AccelTableKind::Dwarf:
Pavel Labath7f7e6062018-07-20 15:24:13 +00002713 AccelDebugNames.addName(Ref, Die);
Pavel Labath6088c232018-04-04 14:42:14 +00002714 break;
Pavel Labath6088c232018-04-04 14:42:14 +00002715 case AccelTableKind::Default:
2716 llvm_unreachable("Default should have already been resolved.");
Pavel Labath7f7e6062018-07-20 15:24:13 +00002717 case AccelTableKind::None:
2718 llvm_unreachable("None handled above");
Pavel Labath6088c232018-04-04 14:42:14 +00002719 }
David Blaikie2406a0622014-04-23 23:37:35 +00002720}
David Blaikie0ee82b92014-04-24 00:53:32 +00002721
David Blaikie66cf14d2018-08-16 21:29:55 +00002722void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
2723 const DIE &Die) {
2724 addAccelNameImpl(CU, AccelNames, Name, Die);
Pavel Labath7f7e6062018-07-20 15:24:13 +00002725}
2726
David Blaikie66cf14d2018-08-16 21:29:55 +00002727void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
2728 const DIE &Die) {
Pavel Labath7f7e6062018-07-20 15:24:13 +00002729 // ObjC names go only into the Apple accelerator tables.
2730 if (getAccelTableKind() == AccelTableKind::Apple)
David Blaikie66cf14d2018-08-16 21:29:55 +00002731 addAccelNameImpl(CU, AccelObjC, Name, Die);
David Blaikie0ee82b92014-04-24 00:53:32 +00002732}
David Blaikieecf04152014-04-24 01:02:42 +00002733
David Blaikie66cf14d2018-08-16 21:29:55 +00002734void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
2735 const DIE &Die) {
2736 addAccelNameImpl(CU, AccelNamespace, Name, Die);
David Blaikieecf04152014-04-24 01:02:42 +00002737}
David Blaikie18d33752014-04-24 01:23:49 +00002738
David Blaikie66cf14d2018-08-16 21:29:55 +00002739void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
2740 const DIE &Die, char Flags) {
2741 addAccelNameImpl(CU, AccelTypes, Name, Die);
David Blaikie18d33752014-04-24 01:23:49 +00002742}
Greg Claytone6543972016-11-23 23:30:37 +00002743
2744uint16_t DwarfDebug::getDwarfVersion() const {
2745 return Asm->OutStreamer->getContext().getDwarfVersion();
2746}
David Blaikie60fddac2018-10-24 23:36:29 +00002747
2748void DwarfDebug::addSectionLabel(const MCSymbol *Sym) {
2749 SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym));
2750}
2751
2752const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
2753 return SectionLabels.find(S)->second;
2754}