1*0b57cec5SDimitry Andric //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file contains support for writing dwarf debug info into asm files.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13*0b57cec5SDimitry Andric #include "DwarfDebug.h"
14*0b57cec5SDimitry Andric #include "ByteStreamer.h"
15*0b57cec5SDimitry Andric #include "DIEHash.h"
16*0b57cec5SDimitry Andric #include "DwarfCompileUnit.h"
17*0b57cec5SDimitry Andric #include "DwarfExpression.h"
18*0b57cec5SDimitry Andric #include "DwarfUnit.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
208bcb0991SDimitry Andric #include "llvm/ADT/Statistic.h"
21*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
22*0b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
23*0b57cec5SDimitry Andric #include "llvm/CodeGen/AsmPrinter.h"
24*0b57cec5SDimitry Andric #include "llvm/CodeGen/DIE.h"
25*0b57cec5SDimitry Andric #include "llvm/CodeGen/LexicalScopes.h"
26*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
27*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
30*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
318bcb0991SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
32*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
33*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
34*0b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
35*0b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
40*0b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
41*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
42*0b57cec5SDimitry Andric #include "llvm/MC/MCSection.h"
43*0b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
44*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
45*0b57cec5SDimitry Andric #include "llvm/MC/MCTargetOptions.h"
46*0b57cec5SDimitry Andric #include "llvm/MC/MachineLocation.h"
47*0b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
48*0b57cec5SDimitry Andric #include "llvm/Pass.h"
49*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
50*0b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
51*0b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
52*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
53*0b57cec5SDimitry Andric #include "llvm/Support/MD5.h"
54*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
55*0b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
56*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
57*0b57cec5SDimitry Andric #include "llvm/Target/TargetLoweringObjectFile.h"
58*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
59*0b57cec5SDimitry Andric #include <algorithm>
60*0b57cec5SDimitry Andric #include <cstddef>
61*0b57cec5SDimitry Andric #include <iterator>
62*0b57cec5SDimitry Andric #include <string>
63*0b57cec5SDimitry Andric 
64*0b57cec5SDimitry Andric using namespace llvm;
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric #define DEBUG_TYPE "dwarfdebug"
67*0b57cec5SDimitry Andric 
688bcb0991SDimitry Andric STATISTIC(NumCSParams, "Number of dbg call site params created");
698bcb0991SDimitry Andric 
70*0b57cec5SDimitry Andric static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
71*0b57cec5SDimitry Andric     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
72*0b57cec5SDimitry Andric     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric static cl::opt<bool> GenerateARangeSection("generate-arange-section",
75*0b57cec5SDimitry Andric                                            cl::Hidden,
76*0b57cec5SDimitry Andric                                            cl::desc("Generate dwarf aranges"),
77*0b57cec5SDimitry Andric                                            cl::init(false));
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric static cl::opt<bool>
80*0b57cec5SDimitry Andric     GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
81*0b57cec5SDimitry Andric                            cl::desc("Generate DWARF4 type units."),
82*0b57cec5SDimitry Andric                            cl::init(false));
83*0b57cec5SDimitry Andric 
84*0b57cec5SDimitry Andric static cl::opt<bool> SplitDwarfCrossCuReferences(
85*0b57cec5SDimitry Andric     "split-dwarf-cross-cu-references", cl::Hidden,
86*0b57cec5SDimitry Andric     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
87*0b57cec5SDimitry Andric 
88*0b57cec5SDimitry Andric enum DefaultOnOff { Default, Enable, Disable };
89*0b57cec5SDimitry Andric 
90*0b57cec5SDimitry Andric static cl::opt<DefaultOnOff> UnknownLocations(
91*0b57cec5SDimitry Andric     "use-unknown-locations", cl::Hidden,
92*0b57cec5SDimitry Andric     cl::desc("Make an absence of debug location information explicit."),
93*0b57cec5SDimitry Andric     cl::values(clEnumVal(Default, "At top of block or after label"),
94*0b57cec5SDimitry Andric                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
95*0b57cec5SDimitry Andric     cl::init(Default));
96*0b57cec5SDimitry Andric 
97*0b57cec5SDimitry Andric static cl::opt<AccelTableKind> AccelTables(
98*0b57cec5SDimitry Andric     "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
99*0b57cec5SDimitry Andric     cl::values(clEnumValN(AccelTableKind::Default, "Default",
100*0b57cec5SDimitry Andric                           "Default for platform"),
101*0b57cec5SDimitry Andric                clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
102*0b57cec5SDimitry Andric                clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
103*0b57cec5SDimitry Andric                clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
104*0b57cec5SDimitry Andric     cl::init(AccelTableKind::Default));
105*0b57cec5SDimitry Andric 
106*0b57cec5SDimitry Andric static cl::opt<DefaultOnOff>
107*0b57cec5SDimitry Andric DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
108*0b57cec5SDimitry Andric                  cl::desc("Use inlined strings rather than string section."),
109*0b57cec5SDimitry Andric                  cl::values(clEnumVal(Default, "Default for platform"),
110*0b57cec5SDimitry Andric                             clEnumVal(Enable, "Enabled"),
111*0b57cec5SDimitry Andric                             clEnumVal(Disable, "Disabled")),
112*0b57cec5SDimitry Andric                  cl::init(Default));
113*0b57cec5SDimitry Andric 
114*0b57cec5SDimitry Andric static cl::opt<bool>
115*0b57cec5SDimitry Andric     NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
116*0b57cec5SDimitry Andric                          cl::desc("Disable emission .debug_ranges section."),
117*0b57cec5SDimitry Andric                          cl::init(false));
118*0b57cec5SDimitry Andric 
119*0b57cec5SDimitry Andric static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
120*0b57cec5SDimitry Andric     "dwarf-sections-as-references", cl::Hidden,
121*0b57cec5SDimitry Andric     cl::desc("Use sections+offset as references rather than labels."),
122*0b57cec5SDimitry Andric     cl::values(clEnumVal(Default, "Default for platform"),
123*0b57cec5SDimitry Andric                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
124*0b57cec5SDimitry Andric     cl::init(Default));
125*0b57cec5SDimitry Andric 
126e8d8bef9SDimitry Andric static cl::opt<bool>
127e8d8bef9SDimitry Andric     UseGNUDebugMacro("use-gnu-debug-macro", cl::Hidden,
128e8d8bef9SDimitry Andric                      cl::desc("Emit the GNU .debug_macro format with DWARF <5"),
129e8d8bef9SDimitry Andric                      cl::init(false));
130e8d8bef9SDimitry Andric 
131e8d8bef9SDimitry Andric static cl::opt<DefaultOnOff> DwarfOpConvert(
132e8d8bef9SDimitry Andric     "dwarf-op-convert", cl::Hidden,
133e8d8bef9SDimitry Andric     cl::desc("Enable use of the DWARFv5 DW_OP_convert operator"),
134e8d8bef9SDimitry Andric     cl::values(clEnumVal(Default, "Default for platform"),
135e8d8bef9SDimitry Andric                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
136e8d8bef9SDimitry Andric     cl::init(Default));
137e8d8bef9SDimitry Andric 
138*0b57cec5SDimitry Andric enum LinkageNameOption {
139*0b57cec5SDimitry Andric   DefaultLinkageNames,
140*0b57cec5SDimitry Andric   AllLinkageNames,
141*0b57cec5SDimitry Andric   AbstractLinkageNames
142*0b57cec5SDimitry Andric };
143*0b57cec5SDimitry Andric 
144*0b57cec5SDimitry Andric static cl::opt<LinkageNameOption>
145*0b57cec5SDimitry Andric     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
146*0b57cec5SDimitry Andric                       cl::desc("Which DWARF linkage-name attributes to emit."),
147*0b57cec5SDimitry Andric                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
148*0b57cec5SDimitry Andric                                             "Default for platform"),
149*0b57cec5SDimitry Andric                                  clEnumValN(AllLinkageNames, "All", "All"),
150*0b57cec5SDimitry Andric                                  clEnumValN(AbstractLinkageNames, "Abstract",
151*0b57cec5SDimitry Andric                                             "Abstract subprograms")),
152*0b57cec5SDimitry Andric                       cl::init(DefaultLinkageNames));
153*0b57cec5SDimitry Andric 
154e8d8bef9SDimitry Andric static cl::opt<DwarfDebug::MinimizeAddrInV5> MinimizeAddrInV5Option(
155e8d8bef9SDimitry Andric     "minimize-addr-in-v5", cl::Hidden,
156e8d8bef9SDimitry Andric     cl::desc("Always use DW_AT_ranges in DWARFv5 whenever it could allow more "
157e8d8bef9SDimitry Andric              "address pool entry sharing to reduce relocations/object size"),
158e8d8bef9SDimitry Andric     cl::values(clEnumValN(DwarfDebug::MinimizeAddrInV5::Default, "Default",
159e8d8bef9SDimitry Andric                           "Default address minimization strategy"),
160e8d8bef9SDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Ranges, "Ranges",
161e8d8bef9SDimitry Andric                           "Use rnglists for contiguous ranges if that allows "
162e8d8bef9SDimitry Andric                           "using a pre-existing base address"),
163e8d8bef9SDimitry Andric                clEnumValN(DwarfDebug::MinimizeAddrInV5::Disabled, "Disabled",
164e8d8bef9SDimitry Andric                           "Stuff")),
165e8d8bef9SDimitry Andric     cl::init(DwarfDebug::MinimizeAddrInV5::Default));
1665ffd83dbSDimitry Andric 
167*0b57cec5SDimitry Andric static constexpr unsigned ULEB128PadSize = 4;
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
170e8d8bef9SDimitry Andric   getActiveStreamer().emitInt8(
171*0b57cec5SDimitry Andric       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
172*0b57cec5SDimitry Andric                   : dwarf::OperationEncodingString(Op));
173*0b57cec5SDimitry Andric }
174*0b57cec5SDimitry Andric 
175*0b57cec5SDimitry Andric void DebugLocDwarfExpression::emitSigned(int64_t Value) {
1765ffd83dbSDimitry Andric   getActiveStreamer().emitSLEB128(Value, Twine(Value));
177*0b57cec5SDimitry Andric }
178*0b57cec5SDimitry Andric 
179*0b57cec5SDimitry Andric void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
1805ffd83dbSDimitry Andric   getActiveStreamer().emitULEB128(Value, Twine(Value));
181*0b57cec5SDimitry Andric }
182*0b57cec5SDimitry Andric 
183*0b57cec5SDimitry Andric void DebugLocDwarfExpression::emitData1(uint8_t Value) {
184e8d8bef9SDimitry Andric   getActiveStreamer().emitInt8(Value, Twine(Value));
185*0b57cec5SDimitry Andric }
186*0b57cec5SDimitry Andric 
187*0b57cec5SDimitry Andric void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
188*0b57cec5SDimitry Andric   assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
1895ffd83dbSDimitry Andric   getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
190*0b57cec5SDimitry Andric }
191*0b57cec5SDimitry Andric 
192*0b57cec5SDimitry Andric bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
193e8d8bef9SDimitry Andric                                               llvm::Register MachineReg) {
194*0b57cec5SDimitry Andric   // This information is not available while emitting .debug_loc entries.
195*0b57cec5SDimitry Andric   return false;
196*0b57cec5SDimitry Andric }
197*0b57cec5SDimitry Andric 
1988bcb0991SDimitry Andric void DebugLocDwarfExpression::enableTemporaryBuffer() {
1998bcb0991SDimitry Andric   assert(!IsBuffering && "Already buffering?");
2008bcb0991SDimitry Andric   if (!TmpBuf)
2018bcb0991SDimitry Andric     TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
2028bcb0991SDimitry Andric   IsBuffering = true;
2038bcb0991SDimitry Andric }
2048bcb0991SDimitry Andric 
2058bcb0991SDimitry Andric void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
2068bcb0991SDimitry Andric 
2078bcb0991SDimitry Andric unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
2088bcb0991SDimitry Andric   return TmpBuf ? TmpBuf->Bytes.size() : 0;
2098bcb0991SDimitry Andric }
2108bcb0991SDimitry Andric 
2118bcb0991SDimitry Andric void DebugLocDwarfExpression::commitTemporaryBuffer() {
2128bcb0991SDimitry Andric   if (!TmpBuf)
2138bcb0991SDimitry Andric     return;
2148bcb0991SDimitry Andric   for (auto Byte : enumerate(TmpBuf->Bytes)) {
2158bcb0991SDimitry Andric     const char *Comment = (Byte.index() < TmpBuf->Comments.size())
2168bcb0991SDimitry Andric                               ? TmpBuf->Comments[Byte.index()].c_str()
2178bcb0991SDimitry Andric                               : "";
218e8d8bef9SDimitry Andric     OutBS.emitInt8(Byte.value(), Comment);
2198bcb0991SDimitry Andric   }
2208bcb0991SDimitry Andric   TmpBuf->Bytes.clear();
2218bcb0991SDimitry Andric   TmpBuf->Comments.clear();
222*0b57cec5SDimitry Andric }
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric const DIType *DbgVariable::getType() const {
2258bcb0991SDimitry Andric   return getVariable()->getType();
226*0b57cec5SDimitry Andric }
227*0b57cec5SDimitry Andric 
228*0b57cec5SDimitry Andric /// Get .debug_loc entry for the instruction range starting at MI.
229*0b57cec5SDimitry Andric static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
230*0b57cec5SDimitry Andric   const DIExpression *Expr = MI->getDebugExpression();
231*0b57cec5SDimitry Andric   assert(MI->getNumOperands() == 4);
2325ffd83dbSDimitry Andric   if (MI->getDebugOperand(0).isReg()) {
233e8d8bef9SDimitry Andric     const auto &RegOp = MI->getDebugOperand(0);
234e8d8bef9SDimitry Andric     const auto &Op1 = MI->getDebugOffset();
235*0b57cec5SDimitry Andric     // If the second operand is an immediate, this is a
236*0b57cec5SDimitry Andric     // register-indirect address.
237*0b57cec5SDimitry Andric     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
238*0b57cec5SDimitry Andric     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
239*0b57cec5SDimitry Andric     return DbgValueLoc(Expr, MLoc);
240*0b57cec5SDimitry Andric   }
2415ffd83dbSDimitry Andric   if (MI->getDebugOperand(0).isTargetIndex()) {
242e8d8bef9SDimitry Andric     const auto &Op = MI->getDebugOperand(0);
243480093f4SDimitry Andric     return DbgValueLoc(Expr,
244480093f4SDimitry Andric                        TargetIndexLocation(Op.getIndex(), Op.getOffset()));
245480093f4SDimitry Andric   }
2465ffd83dbSDimitry Andric   if (MI->getDebugOperand(0).isImm())
2475ffd83dbSDimitry Andric     return DbgValueLoc(Expr, MI->getDebugOperand(0).getImm());
2485ffd83dbSDimitry Andric   if (MI->getDebugOperand(0).isFPImm())
2495ffd83dbSDimitry Andric     return DbgValueLoc(Expr, MI->getDebugOperand(0).getFPImm());
2505ffd83dbSDimitry Andric   if (MI->getDebugOperand(0).isCImm())
2515ffd83dbSDimitry Andric     return DbgValueLoc(Expr, MI->getDebugOperand(0).getCImm());
252*0b57cec5SDimitry Andric 
253*0b57cec5SDimitry Andric   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
254*0b57cec5SDimitry Andric }
255*0b57cec5SDimitry Andric 
256*0b57cec5SDimitry Andric void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
257*0b57cec5SDimitry Andric   assert(FrameIndexExprs.empty() && "Already initialized?");
258*0b57cec5SDimitry Andric   assert(!ValueLoc.get() && "Already initialized?");
259*0b57cec5SDimitry Andric 
260*0b57cec5SDimitry Andric   assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
261*0b57cec5SDimitry Andric   assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
262*0b57cec5SDimitry Andric          "Wrong inlined-at");
263*0b57cec5SDimitry Andric 
2648bcb0991SDimitry Andric   ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
265*0b57cec5SDimitry Andric   if (auto *E = DbgValue->getDebugExpression())
266*0b57cec5SDimitry Andric     if (E->getNumElements())
267*0b57cec5SDimitry Andric       FrameIndexExprs.push_back({0, E});
268*0b57cec5SDimitry Andric }
269*0b57cec5SDimitry Andric 
270*0b57cec5SDimitry Andric ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
271*0b57cec5SDimitry Andric   if (FrameIndexExprs.size() == 1)
272*0b57cec5SDimitry Andric     return FrameIndexExprs;
273*0b57cec5SDimitry Andric 
274*0b57cec5SDimitry Andric   assert(llvm::all_of(FrameIndexExprs,
275*0b57cec5SDimitry Andric                       [](const FrameIndexExpr &A) {
276*0b57cec5SDimitry Andric                         return A.Expr->isFragment();
277*0b57cec5SDimitry Andric                       }) &&
278*0b57cec5SDimitry Andric          "multiple FI expressions without DW_OP_LLVM_fragment");
279*0b57cec5SDimitry Andric   llvm::sort(FrameIndexExprs,
280*0b57cec5SDimitry Andric              [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
281*0b57cec5SDimitry Andric                return A.Expr->getFragmentInfo()->OffsetInBits <
282*0b57cec5SDimitry Andric                       B.Expr->getFragmentInfo()->OffsetInBits;
283*0b57cec5SDimitry Andric              });
284*0b57cec5SDimitry Andric 
285*0b57cec5SDimitry Andric   return FrameIndexExprs;
286*0b57cec5SDimitry Andric }
287*0b57cec5SDimitry Andric 
288*0b57cec5SDimitry Andric void DbgVariable::addMMIEntry(const DbgVariable &V) {
289*0b57cec5SDimitry Andric   assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
290*0b57cec5SDimitry Andric   assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
291*0b57cec5SDimitry Andric   assert(V.getVariable() == getVariable() && "conflicting variable");
292*0b57cec5SDimitry Andric   assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
293*0b57cec5SDimitry Andric 
294*0b57cec5SDimitry Andric   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
295*0b57cec5SDimitry Andric   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
296*0b57cec5SDimitry Andric 
297*0b57cec5SDimitry Andric   // FIXME: This logic should not be necessary anymore, as we now have proper
298*0b57cec5SDimitry Andric   // deduplication. However, without it, we currently run into the assertion
299*0b57cec5SDimitry Andric   // below, which means that we are likely dealing with broken input, i.e. two
300*0b57cec5SDimitry Andric   // non-fragment entries for the same variable at different frame indices.
301*0b57cec5SDimitry Andric   if (FrameIndexExprs.size()) {
302*0b57cec5SDimitry Andric     auto *Expr = FrameIndexExprs.back().Expr;
303*0b57cec5SDimitry Andric     if (!Expr || !Expr->isFragment())
304*0b57cec5SDimitry Andric       return;
305*0b57cec5SDimitry Andric   }
306*0b57cec5SDimitry Andric 
307*0b57cec5SDimitry Andric   for (const auto &FIE : V.FrameIndexExprs)
308*0b57cec5SDimitry Andric     // Ignore duplicate entries.
309*0b57cec5SDimitry Andric     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
310*0b57cec5SDimitry Andric           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
311*0b57cec5SDimitry Andric         }))
312*0b57cec5SDimitry Andric       FrameIndexExprs.push_back(FIE);
313*0b57cec5SDimitry Andric 
314*0b57cec5SDimitry Andric   assert((FrameIndexExprs.size() == 1 ||
315*0b57cec5SDimitry Andric           llvm::all_of(FrameIndexExprs,
316*0b57cec5SDimitry Andric                        [](FrameIndexExpr &FIE) {
317*0b57cec5SDimitry Andric                          return FIE.Expr && FIE.Expr->isFragment();
318*0b57cec5SDimitry Andric                        })) &&
319*0b57cec5SDimitry Andric          "conflicting locations for variable");
320*0b57cec5SDimitry Andric }
321*0b57cec5SDimitry Andric 
322*0b57cec5SDimitry Andric static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
323*0b57cec5SDimitry Andric                                             bool GenerateTypeUnits,
324*0b57cec5SDimitry Andric                                             DebuggerKind Tuning,
325*0b57cec5SDimitry Andric                                             const Triple &TT) {
326*0b57cec5SDimitry Andric   // Honor an explicit request.
327*0b57cec5SDimitry Andric   if (AccelTables != AccelTableKind::Default)
328*0b57cec5SDimitry Andric     return AccelTables;
329*0b57cec5SDimitry Andric 
330*0b57cec5SDimitry Andric   // Accelerator tables with type units are currently not supported.
331*0b57cec5SDimitry Andric   if (GenerateTypeUnits)
332*0b57cec5SDimitry Andric     return AccelTableKind::None;
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
335*0b57cec5SDimitry Andric   // always implies debug_names. For lower standard versions we use apple
336*0b57cec5SDimitry Andric   // accelerator tables on apple platforms and debug_names elsewhere.
337*0b57cec5SDimitry Andric   if (DwarfVersion >= 5)
338*0b57cec5SDimitry Andric     return AccelTableKind::Dwarf;
339*0b57cec5SDimitry Andric   if (Tuning == DebuggerKind::LLDB)
340*0b57cec5SDimitry Andric     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
341*0b57cec5SDimitry Andric                                    : AccelTableKind::Dwarf;
342*0b57cec5SDimitry Andric   return AccelTableKind::None;
343*0b57cec5SDimitry Andric }
344*0b57cec5SDimitry Andric 
345e8d8bef9SDimitry Andric DwarfDebug::DwarfDebug(AsmPrinter *A)
346*0b57cec5SDimitry Andric     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
347*0b57cec5SDimitry Andric       InfoHolder(A, "info_string", DIEValueAllocator),
348*0b57cec5SDimitry Andric       SkeletonHolder(A, "skel_string", DIEValueAllocator),
349*0b57cec5SDimitry Andric       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
350*0b57cec5SDimitry Andric   const Triple &TT = Asm->TM.getTargetTriple();
351*0b57cec5SDimitry Andric 
352*0b57cec5SDimitry Andric   // Make sure we know our "debugger tuning".  The target option takes
353*0b57cec5SDimitry Andric   // precedence; fall back to triple-based defaults.
354*0b57cec5SDimitry Andric   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
355*0b57cec5SDimitry Andric     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
356*0b57cec5SDimitry Andric   else if (IsDarwin)
357*0b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::LLDB;
358*0b57cec5SDimitry Andric   else if (TT.isPS4CPU())
359*0b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::SCE;
360*0b57cec5SDimitry Andric   else
361*0b57cec5SDimitry Andric     DebuggerTuning = DebuggerKind::GDB;
362*0b57cec5SDimitry Andric 
363*0b57cec5SDimitry Andric   if (DwarfInlinedStrings == Default)
364*0b57cec5SDimitry Andric     UseInlineStrings = TT.isNVPTX();
365*0b57cec5SDimitry Andric   else
366*0b57cec5SDimitry Andric     UseInlineStrings = DwarfInlinedStrings == Enable;
367*0b57cec5SDimitry Andric 
368*0b57cec5SDimitry Andric   UseLocSection = !TT.isNVPTX();
369*0b57cec5SDimitry Andric 
370*0b57cec5SDimitry Andric   HasAppleExtensionAttributes = tuneForLLDB();
371*0b57cec5SDimitry Andric 
372*0b57cec5SDimitry Andric   // Handle split DWARF.
373*0b57cec5SDimitry Andric   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
374*0b57cec5SDimitry Andric 
375*0b57cec5SDimitry Andric   // SCE defaults to linkage names only for abstract subprograms.
376*0b57cec5SDimitry Andric   if (DwarfLinkageNames == DefaultLinkageNames)
377*0b57cec5SDimitry Andric     UseAllLinkageNames = !tuneForSCE();
378*0b57cec5SDimitry Andric   else
379*0b57cec5SDimitry Andric     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
380*0b57cec5SDimitry Andric 
381*0b57cec5SDimitry Andric   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
382*0b57cec5SDimitry Andric   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
383*0b57cec5SDimitry Andric                                     : MMI->getModule()->getDwarfVersion();
384*0b57cec5SDimitry Andric   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
385*0b57cec5SDimitry Andric   DwarfVersion =
386*0b57cec5SDimitry Andric       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
387*0b57cec5SDimitry Andric 
388e8d8bef9SDimitry Andric   bool Dwarf64 = Asm->TM.Options.MCOptions.Dwarf64 &&
389e8d8bef9SDimitry Andric                  DwarfVersion >= 3 &&   // DWARF64 was introduced in DWARFv3.
390e8d8bef9SDimitry Andric                  TT.isArch64Bit() &&    // DWARF64 requires 64-bit relocations.
391e8d8bef9SDimitry Andric                  TT.isOSBinFormatELF(); // Support only ELF for now.
392e8d8bef9SDimitry Andric 
393*0b57cec5SDimitry Andric   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
394*0b57cec5SDimitry Andric 
395*0b57cec5SDimitry Andric   // Use sections as references. Force for NVPTX.
396*0b57cec5SDimitry Andric   if (DwarfSectionsAsReferences == Default)
397*0b57cec5SDimitry Andric     UseSectionsAsReferences = TT.isNVPTX();
398*0b57cec5SDimitry Andric   else
399*0b57cec5SDimitry Andric     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
400*0b57cec5SDimitry Andric 
401*0b57cec5SDimitry Andric   // Don't generate type units for unsupported object file formats.
402e8d8bef9SDimitry Andric   GenerateTypeUnits = (A->TM.getTargetTriple().isOSBinFormatELF() ||
403e8d8bef9SDimitry Andric                        A->TM.getTargetTriple().isOSBinFormatWasm()) &&
404e8d8bef9SDimitry Andric                       GenerateDwarfTypeUnits;
405*0b57cec5SDimitry Andric 
406*0b57cec5SDimitry Andric   TheAccelTableKind = computeAccelTableKind(
407*0b57cec5SDimitry Andric       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
408*0b57cec5SDimitry Andric 
409*0b57cec5SDimitry Andric   // Work around a GDB bug. GDB doesn't support the standard opcode;
410*0b57cec5SDimitry Andric   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
411*0b57cec5SDimitry Andric   // is defined as of DWARF 3.
412*0b57cec5SDimitry Andric   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
413*0b57cec5SDimitry Andric   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
414*0b57cec5SDimitry Andric   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
415*0b57cec5SDimitry Andric 
416*0b57cec5SDimitry Andric   // GDB does not fully support the DWARF 4 representation for bitfields.
417*0b57cec5SDimitry Andric   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
418*0b57cec5SDimitry Andric 
419*0b57cec5SDimitry Andric   // The DWARF v5 string offsets table has - possibly shared - contributions
420*0b57cec5SDimitry Andric   // from each compile and type unit each preceded by a header. The string
421*0b57cec5SDimitry Andric   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
422*0b57cec5SDimitry Andric   // a monolithic string offsets table without any header.
423*0b57cec5SDimitry Andric   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
424*0b57cec5SDimitry Andric 
4255ffd83dbSDimitry Andric   // Emit call-site-param debug info for GDB and LLDB, if the target supports
4265ffd83dbSDimitry Andric   // the debug entry values feature. It can also be enabled explicitly.
427e8d8bef9SDimitry Andric   EmitDebugEntryValues = Asm->TM.Options.ShouldEmitDebugEntryValues();
428e8d8bef9SDimitry Andric 
429e8d8bef9SDimitry Andric   // It is unclear if the GCC .debug_macro extension is well-specified
430e8d8bef9SDimitry Andric   // for split DWARF. For now, do not allow LLVM to emit it.
431e8d8bef9SDimitry Andric   UseDebugMacroSection =
432e8d8bef9SDimitry Andric       DwarfVersion >= 5 || (UseGNUDebugMacro && !useSplitDwarf());
433e8d8bef9SDimitry Andric   if (DwarfOpConvert == Default)
434e8d8bef9SDimitry Andric     EnableOpConvert = !((tuneForGDB() && useSplitDwarf()) || (tuneForLLDB() && !TT.isOSBinFormatMachO()));
435e8d8bef9SDimitry Andric   else
436e8d8bef9SDimitry Andric     EnableOpConvert = (DwarfOpConvert == Enable);
437e8d8bef9SDimitry Andric 
438e8d8bef9SDimitry Andric   // Split DWARF would benefit object size significantly by trading reductions
439e8d8bef9SDimitry Andric   // in address pool usage for slightly increased range list encodings.
440e8d8bef9SDimitry Andric   if (DwarfVersion >= 5) {
441e8d8bef9SDimitry Andric     MinimizeAddr = MinimizeAddrInV5Option;
442e8d8bef9SDimitry Andric     // FIXME: In the future, enable this by default for Split DWARF where the
443e8d8bef9SDimitry Andric     // tradeoff is more pronounced due to being able to offload the range
444e8d8bef9SDimitry Andric     // lists to the dwo file and shrink object files/reduce relocations there.
445e8d8bef9SDimitry Andric     if (MinimizeAddr == MinimizeAddrInV5::Default)
446e8d8bef9SDimitry Andric       MinimizeAddr = MinimizeAddrInV5::Disabled;
447e8d8bef9SDimitry Andric   }
4485ffd83dbSDimitry Andric 
449*0b57cec5SDimitry Andric   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
450e8d8bef9SDimitry Andric   Asm->OutStreamer->getContext().setDwarfFormat(Dwarf64 ? dwarf::DWARF64
451e8d8bef9SDimitry Andric                                                         : dwarf::DWARF32);
452*0b57cec5SDimitry Andric }
453*0b57cec5SDimitry Andric 
454*0b57cec5SDimitry Andric // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
455*0b57cec5SDimitry Andric DwarfDebug::~DwarfDebug() = default;
456*0b57cec5SDimitry Andric 
457*0b57cec5SDimitry Andric static bool isObjCClass(StringRef Name) {
458*0b57cec5SDimitry Andric   return Name.startswith("+") || Name.startswith("-");
459*0b57cec5SDimitry Andric }
460*0b57cec5SDimitry Andric 
461*0b57cec5SDimitry Andric static bool hasObjCCategory(StringRef Name) {
462*0b57cec5SDimitry Andric   if (!isObjCClass(Name))
463*0b57cec5SDimitry Andric     return false;
464*0b57cec5SDimitry Andric 
465*0b57cec5SDimitry Andric   return Name.find(") ") != StringRef::npos;
466*0b57cec5SDimitry Andric }
467*0b57cec5SDimitry Andric 
468*0b57cec5SDimitry Andric static void getObjCClassCategory(StringRef In, StringRef &Class,
469*0b57cec5SDimitry Andric                                  StringRef &Category) {
470*0b57cec5SDimitry Andric   if (!hasObjCCategory(In)) {
471*0b57cec5SDimitry Andric     Class = In.slice(In.find('[') + 1, In.find(' '));
472*0b57cec5SDimitry Andric     Category = "";
473*0b57cec5SDimitry Andric     return;
474*0b57cec5SDimitry Andric   }
475*0b57cec5SDimitry Andric 
476*0b57cec5SDimitry Andric   Class = In.slice(In.find('[') + 1, In.find('('));
477*0b57cec5SDimitry Andric   Category = In.slice(In.find('[') + 1, In.find(' '));
478*0b57cec5SDimitry Andric }
479*0b57cec5SDimitry Andric 
480*0b57cec5SDimitry Andric static StringRef getObjCMethodName(StringRef In) {
481*0b57cec5SDimitry Andric   return In.slice(In.find(' ') + 1, In.find(']'));
482*0b57cec5SDimitry Andric }
483*0b57cec5SDimitry Andric 
484*0b57cec5SDimitry Andric // Add the various names to the Dwarf accelerator table names.
485*0b57cec5SDimitry Andric void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
486*0b57cec5SDimitry Andric                                     const DISubprogram *SP, DIE &Die) {
487*0b57cec5SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
488*0b57cec5SDimitry Andric       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
489*0b57cec5SDimitry Andric     return;
490*0b57cec5SDimitry Andric 
491*0b57cec5SDimitry Andric   if (!SP->isDefinition())
492*0b57cec5SDimitry Andric     return;
493*0b57cec5SDimitry Andric 
494*0b57cec5SDimitry Andric   if (SP->getName() != "")
495*0b57cec5SDimitry Andric     addAccelName(CU, SP->getName(), Die);
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric   // If the linkage name is different than the name, go ahead and output that as
498*0b57cec5SDimitry Andric   // well into the name table. Only do that if we are going to actually emit
499*0b57cec5SDimitry Andric   // that name.
500*0b57cec5SDimitry Andric   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
501*0b57cec5SDimitry Andric       (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
502*0b57cec5SDimitry Andric     addAccelName(CU, SP->getLinkageName(), Die);
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric   // If this is an Objective-C selector name add it to the ObjC accelerator
505*0b57cec5SDimitry Andric   // too.
506*0b57cec5SDimitry Andric   if (isObjCClass(SP->getName())) {
507*0b57cec5SDimitry Andric     StringRef Class, Category;
508*0b57cec5SDimitry Andric     getObjCClassCategory(SP->getName(), Class, Category);
509*0b57cec5SDimitry Andric     addAccelObjC(CU, Class, Die);
510*0b57cec5SDimitry Andric     if (Category != "")
511*0b57cec5SDimitry Andric       addAccelObjC(CU, Category, Die);
512*0b57cec5SDimitry Andric     // Also add the base method name to the name table.
513*0b57cec5SDimitry Andric     addAccelName(CU, getObjCMethodName(SP->getName()), Die);
514*0b57cec5SDimitry Andric   }
515*0b57cec5SDimitry Andric }
516*0b57cec5SDimitry Andric 
517*0b57cec5SDimitry Andric /// Check whether we should create a DIE for the given Scope, return true
518*0b57cec5SDimitry Andric /// if we don't create a DIE (the corresponding DIE is null).
519*0b57cec5SDimitry Andric bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
520*0b57cec5SDimitry Andric   if (Scope->isAbstractScope())
521*0b57cec5SDimitry Andric     return false;
522*0b57cec5SDimitry Andric 
523*0b57cec5SDimitry Andric   // We don't create a DIE if there is no Range.
524*0b57cec5SDimitry Andric   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
525*0b57cec5SDimitry Andric   if (Ranges.empty())
526*0b57cec5SDimitry Andric     return true;
527*0b57cec5SDimitry Andric 
528*0b57cec5SDimitry Andric   if (Ranges.size() > 1)
529*0b57cec5SDimitry Andric     return false;
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric   // We don't create a DIE if we have a single Range and the end label
532*0b57cec5SDimitry Andric   // is null.
533*0b57cec5SDimitry Andric   return !getLabelAfterInsn(Ranges.front().second);
534*0b57cec5SDimitry Andric }
535*0b57cec5SDimitry Andric 
536*0b57cec5SDimitry Andric template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
537*0b57cec5SDimitry Andric   F(CU);
538*0b57cec5SDimitry Andric   if (auto *SkelCU = CU.getSkeleton())
539*0b57cec5SDimitry Andric     if (CU.getCUNode()->getSplitDebugInlining())
540*0b57cec5SDimitry Andric       F(*SkelCU);
541*0b57cec5SDimitry Andric }
542*0b57cec5SDimitry Andric 
543*0b57cec5SDimitry Andric bool DwarfDebug::shareAcrossDWOCUs() const {
544*0b57cec5SDimitry Andric   return SplitDwarfCrossCuReferences;
545*0b57cec5SDimitry Andric }
546*0b57cec5SDimitry Andric 
547*0b57cec5SDimitry Andric void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
548*0b57cec5SDimitry Andric                                                      LexicalScope *Scope) {
549*0b57cec5SDimitry Andric   assert(Scope && Scope->getScopeNode());
550*0b57cec5SDimitry Andric   assert(Scope->isAbstractScope());
551*0b57cec5SDimitry Andric   assert(!Scope->getInlinedAt());
552*0b57cec5SDimitry Andric 
553*0b57cec5SDimitry Andric   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
554*0b57cec5SDimitry Andric 
555*0b57cec5SDimitry Andric   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
556*0b57cec5SDimitry Andric   // was inlined from another compile unit.
557*0b57cec5SDimitry Andric   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
558*0b57cec5SDimitry Andric     // Avoid building the original CU if it won't be used
559*0b57cec5SDimitry Andric     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
560*0b57cec5SDimitry Andric   else {
561*0b57cec5SDimitry Andric     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
562*0b57cec5SDimitry Andric     if (auto *SkelCU = CU.getSkeleton()) {
563*0b57cec5SDimitry Andric       (shareAcrossDWOCUs() ? CU : SrcCU)
564*0b57cec5SDimitry Andric           .constructAbstractSubprogramScopeDIE(Scope);
565*0b57cec5SDimitry Andric       if (CU.getCUNode()->getSplitDebugInlining())
566*0b57cec5SDimitry Andric         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
567*0b57cec5SDimitry Andric     } else
568*0b57cec5SDimitry Andric       CU.constructAbstractSubprogramScopeDIE(Scope);
569*0b57cec5SDimitry Andric   }
570*0b57cec5SDimitry Andric }
571*0b57cec5SDimitry Andric 
5725ffd83dbSDimitry Andric DIE &DwarfDebug::constructSubprogramDefinitionDIE(const DISubprogram *SP) {
5735ffd83dbSDimitry Andric   DICompileUnit *Unit = SP->getUnit();
5745ffd83dbSDimitry Andric   assert(SP->isDefinition() && "Subprogram not a definition");
5755ffd83dbSDimitry Andric   assert(Unit && "Subprogram definition without parent unit");
5765ffd83dbSDimitry Andric   auto &CU = getOrCreateDwarfCompileUnit(Unit);
5775ffd83dbSDimitry Andric   return *CU.getOrCreateSubprogramDIE(SP);
5785ffd83dbSDimitry Andric }
5795ffd83dbSDimitry Andric 
5805ffd83dbSDimitry Andric /// Represents a parameter whose call site value can be described by applying a
5815ffd83dbSDimitry Andric /// debug expression to a register in the forwarded register worklist.
5825ffd83dbSDimitry Andric struct FwdRegParamInfo {
5835ffd83dbSDimitry Andric   /// The described parameter register.
5845ffd83dbSDimitry Andric   unsigned ParamReg;
5855ffd83dbSDimitry Andric 
5865ffd83dbSDimitry Andric   /// Debug expression that has been built up when walking through the
5875ffd83dbSDimitry Andric   /// instruction chain that produces the parameter's value.
5885ffd83dbSDimitry Andric   const DIExpression *Expr;
5895ffd83dbSDimitry Andric };
5905ffd83dbSDimitry Andric 
5915ffd83dbSDimitry Andric /// Register worklist for finding call site values.
5925ffd83dbSDimitry Andric using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
5935ffd83dbSDimitry Andric 
5945ffd83dbSDimitry Andric /// Append the expression \p Addition to \p Original and return the result.
5955ffd83dbSDimitry Andric static const DIExpression *combineDIExpressions(const DIExpression *Original,
5965ffd83dbSDimitry Andric                                                 const DIExpression *Addition) {
5975ffd83dbSDimitry Andric   std::vector<uint64_t> Elts = Addition->getElements().vec();
5985ffd83dbSDimitry Andric   // Avoid multiple DW_OP_stack_values.
5995ffd83dbSDimitry Andric   if (Original->isImplicit() && Addition->isImplicit())
600e8d8bef9SDimitry Andric     erase_value(Elts, dwarf::DW_OP_stack_value);
6015ffd83dbSDimitry Andric   const DIExpression *CombinedExpr =
6025ffd83dbSDimitry Andric       (Elts.size() > 0) ? DIExpression::append(Original, Elts) : Original;
6035ffd83dbSDimitry Andric   return CombinedExpr;
6045ffd83dbSDimitry Andric }
6055ffd83dbSDimitry Andric 
6065ffd83dbSDimitry Andric /// Emit call site parameter entries that are described by the given value and
6075ffd83dbSDimitry Andric /// debug expression.
6085ffd83dbSDimitry Andric template <typename ValT>
6095ffd83dbSDimitry Andric static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
6105ffd83dbSDimitry Andric                                  ArrayRef<FwdRegParamInfo> DescribedParams,
6115ffd83dbSDimitry Andric                                  ParamSet &Params) {
6125ffd83dbSDimitry Andric   for (auto Param : DescribedParams) {
6135ffd83dbSDimitry Andric     bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
6145ffd83dbSDimitry Andric 
6155ffd83dbSDimitry Andric     // TODO: Entry value operations can currently not be combined with any
6165ffd83dbSDimitry Andric     // other expressions, so we can't emit call site entries in those cases.
6175ffd83dbSDimitry Andric     if (ShouldCombineExpressions && Expr->isEntryValue())
6185ffd83dbSDimitry Andric       continue;
6195ffd83dbSDimitry Andric 
6205ffd83dbSDimitry Andric     // If a parameter's call site value is produced by a chain of
6215ffd83dbSDimitry Andric     // instructions we may have already created an expression for the
6225ffd83dbSDimitry Andric     // parameter when walking through the instructions. Append that to the
6235ffd83dbSDimitry Andric     // base expression.
6245ffd83dbSDimitry Andric     const DIExpression *CombinedExpr =
6255ffd83dbSDimitry Andric         ShouldCombineExpressions ? combineDIExpressions(Expr, Param.Expr)
6265ffd83dbSDimitry Andric                                  : Expr;
6275ffd83dbSDimitry Andric     assert((!CombinedExpr || CombinedExpr->isValid()) &&
6285ffd83dbSDimitry Andric            "Combined debug expression is invalid");
6295ffd83dbSDimitry Andric 
6305ffd83dbSDimitry Andric     DbgValueLoc DbgLocVal(CombinedExpr, Val);
6315ffd83dbSDimitry Andric     DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
6325ffd83dbSDimitry Andric     Params.push_back(CSParm);
6335ffd83dbSDimitry Andric     ++NumCSParams;
6345ffd83dbSDimitry Andric   }
6355ffd83dbSDimitry Andric }
6365ffd83dbSDimitry Andric 
6375ffd83dbSDimitry Andric /// Add \p Reg to the worklist, if it's not already present, and mark that the
6385ffd83dbSDimitry Andric /// given parameter registers' values can (potentially) be described using
6395ffd83dbSDimitry Andric /// that register and an debug expression.
6405ffd83dbSDimitry Andric static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
6415ffd83dbSDimitry Andric                                 const DIExpression *Expr,
6425ffd83dbSDimitry Andric                                 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
6435ffd83dbSDimitry Andric   auto I = Worklist.insert({Reg, {}});
6445ffd83dbSDimitry Andric   auto &ParamsForFwdReg = I.first->second;
6455ffd83dbSDimitry Andric   for (auto Param : ParamsToAdd) {
6465ffd83dbSDimitry Andric     assert(none_of(ParamsForFwdReg,
6475ffd83dbSDimitry Andric                    [Param](const FwdRegParamInfo &D) {
6485ffd83dbSDimitry Andric                      return D.ParamReg == Param.ParamReg;
6495ffd83dbSDimitry Andric                    }) &&
6505ffd83dbSDimitry Andric            "Same parameter described twice by forwarding reg");
6515ffd83dbSDimitry Andric 
6525ffd83dbSDimitry Andric     // If a parameter's call site value is produced by a chain of
6535ffd83dbSDimitry Andric     // instructions we may have already created an expression for the
6545ffd83dbSDimitry Andric     // parameter when walking through the instructions. Append that to the
6555ffd83dbSDimitry Andric     // new expression.
6565ffd83dbSDimitry Andric     const DIExpression *CombinedExpr = combineDIExpressions(Expr, Param.Expr);
6575ffd83dbSDimitry Andric     ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
6585ffd83dbSDimitry Andric   }
6595ffd83dbSDimitry Andric }
6605ffd83dbSDimitry Andric 
6615ffd83dbSDimitry Andric /// Interpret values loaded into registers by \p CurMI.
6625ffd83dbSDimitry Andric static void interpretValues(const MachineInstr *CurMI,
6635ffd83dbSDimitry Andric                             FwdRegWorklist &ForwardedRegWorklist,
6645ffd83dbSDimitry Andric                             ParamSet &Params) {
6655ffd83dbSDimitry Andric 
6665ffd83dbSDimitry Andric   const MachineFunction *MF = CurMI->getMF();
6675ffd83dbSDimitry Andric   const DIExpression *EmptyExpr =
6685ffd83dbSDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
6695ffd83dbSDimitry Andric   const auto &TRI = *MF->getSubtarget().getRegisterInfo();
6705ffd83dbSDimitry Andric   const auto &TII = *MF->getSubtarget().getInstrInfo();
6715ffd83dbSDimitry Andric   const auto &TLI = *MF->getSubtarget().getTargetLowering();
6725ffd83dbSDimitry Andric 
6735ffd83dbSDimitry Andric   // If an instruction defines more than one item in the worklist, we may run
6745ffd83dbSDimitry Andric   // into situations where a worklist register's value is (potentially)
6755ffd83dbSDimitry Andric   // described by the previous value of another register that is also defined
6765ffd83dbSDimitry Andric   // by that instruction.
6775ffd83dbSDimitry Andric   //
6785ffd83dbSDimitry Andric   // This can for example occur in cases like this:
6795ffd83dbSDimitry Andric   //
6805ffd83dbSDimitry Andric   //   $r1 = mov 123
6815ffd83dbSDimitry Andric   //   $r0, $r1 = mvrr $r1, 456
6825ffd83dbSDimitry Andric   //   call @foo, $r0, $r1
6835ffd83dbSDimitry Andric   //
6845ffd83dbSDimitry Andric   // When describing $r1's value for the mvrr instruction, we need to make sure
6855ffd83dbSDimitry Andric   // that we don't finalize an entry value for $r0, as that is dependent on the
6865ffd83dbSDimitry Andric   // previous value of $r1 (123 rather than 456).
6875ffd83dbSDimitry Andric   //
6885ffd83dbSDimitry Andric   // In order to not have to distinguish between those cases when finalizing
6895ffd83dbSDimitry Andric   // entry values, we simply postpone adding new parameter registers to the
6905ffd83dbSDimitry Andric   // worklist, by first keeping them in this temporary container until the
6915ffd83dbSDimitry Andric   // instruction has been handled.
6925ffd83dbSDimitry Andric   FwdRegWorklist TmpWorklistItems;
6935ffd83dbSDimitry Andric 
6945ffd83dbSDimitry Andric   // If the MI is an instruction defining one or more parameters' forwarding
6955ffd83dbSDimitry Andric   // registers, add those defines.
6965ffd83dbSDimitry Andric   auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
6975ffd83dbSDimitry Andric                                           SmallSetVector<unsigned, 4> &Defs) {
6985ffd83dbSDimitry Andric     if (MI.isDebugInstr())
6995ffd83dbSDimitry Andric       return;
7005ffd83dbSDimitry Andric 
7015ffd83dbSDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
7025ffd83dbSDimitry Andric       if (MO.isReg() && MO.isDef() &&
7035ffd83dbSDimitry Andric           Register::isPhysicalRegister(MO.getReg())) {
7045ffd83dbSDimitry Andric         for (auto FwdReg : ForwardedRegWorklist)
7055ffd83dbSDimitry Andric           if (TRI.regsOverlap(FwdReg.first, MO.getReg()))
7065ffd83dbSDimitry Andric             Defs.insert(FwdReg.first);
7075ffd83dbSDimitry Andric       }
7085ffd83dbSDimitry Andric     }
7095ffd83dbSDimitry Andric   };
7105ffd83dbSDimitry Andric 
7115ffd83dbSDimitry Andric   // Set of worklist registers that are defined by this instruction.
7125ffd83dbSDimitry Andric   SmallSetVector<unsigned, 4> FwdRegDefs;
7135ffd83dbSDimitry Andric 
7145ffd83dbSDimitry Andric   getForwardingRegsDefinedByMI(*CurMI, FwdRegDefs);
7155ffd83dbSDimitry Andric   if (FwdRegDefs.empty())
7165ffd83dbSDimitry Andric     return;
7175ffd83dbSDimitry Andric 
7185ffd83dbSDimitry Andric   for (auto ParamFwdReg : FwdRegDefs) {
7195ffd83dbSDimitry Andric     if (auto ParamValue = TII.describeLoadedValue(*CurMI, ParamFwdReg)) {
7205ffd83dbSDimitry Andric       if (ParamValue->first.isImm()) {
7215ffd83dbSDimitry Andric         int64_t Val = ParamValue->first.getImm();
7225ffd83dbSDimitry Andric         finishCallSiteParams(Val, ParamValue->second,
7235ffd83dbSDimitry Andric                              ForwardedRegWorklist[ParamFwdReg], Params);
7245ffd83dbSDimitry Andric       } else if (ParamValue->first.isReg()) {
7255ffd83dbSDimitry Andric         Register RegLoc = ParamValue->first.getReg();
726e8d8bef9SDimitry Andric         Register SP = TLI.getStackPointerRegisterToSaveRestore();
7275ffd83dbSDimitry Andric         Register FP = TRI.getFrameRegister(*MF);
7285ffd83dbSDimitry Andric         bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
7295ffd83dbSDimitry Andric         if (TRI.isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
730e8d8bef9SDimitry Andric           MachineLocation MLoc(RegLoc, /*Indirect=*/IsSPorFP);
7315ffd83dbSDimitry Andric           finishCallSiteParams(MLoc, ParamValue->second,
7325ffd83dbSDimitry Andric                                ForwardedRegWorklist[ParamFwdReg], Params);
7335ffd83dbSDimitry Andric         } else {
7345ffd83dbSDimitry Andric           // ParamFwdReg was described by the non-callee saved register
7355ffd83dbSDimitry Andric           // RegLoc. Mark that the call site values for the parameters are
7365ffd83dbSDimitry Andric           // dependent on that register instead of ParamFwdReg. Since RegLoc
7375ffd83dbSDimitry Andric           // may be a register that will be handled in this iteration, we
7385ffd83dbSDimitry Andric           // postpone adding the items to the worklist, and instead keep them
7395ffd83dbSDimitry Andric           // in a temporary container.
7405ffd83dbSDimitry Andric           addToFwdRegWorklist(TmpWorklistItems, RegLoc, ParamValue->second,
7415ffd83dbSDimitry Andric                               ForwardedRegWorklist[ParamFwdReg]);
7425ffd83dbSDimitry Andric         }
7435ffd83dbSDimitry Andric       }
7445ffd83dbSDimitry Andric     }
7455ffd83dbSDimitry Andric   }
7465ffd83dbSDimitry Andric 
7475ffd83dbSDimitry Andric   // Remove all registers that this instruction defines from the worklist.
7485ffd83dbSDimitry Andric   for (auto ParamFwdReg : FwdRegDefs)
7495ffd83dbSDimitry Andric     ForwardedRegWorklist.erase(ParamFwdReg);
7505ffd83dbSDimitry Andric 
7515ffd83dbSDimitry Andric   // Now that we are done handling this instruction, add items from the
7525ffd83dbSDimitry Andric   // temporary worklist to the real one.
7535ffd83dbSDimitry Andric   for (auto New : TmpWorklistItems)
7545ffd83dbSDimitry Andric     addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr, New.second);
7555ffd83dbSDimitry Andric   TmpWorklistItems.clear();
7565ffd83dbSDimitry Andric }
7575ffd83dbSDimitry Andric 
7585ffd83dbSDimitry Andric static bool interpretNextInstr(const MachineInstr *CurMI,
7595ffd83dbSDimitry Andric                                FwdRegWorklist &ForwardedRegWorklist,
7605ffd83dbSDimitry Andric                                ParamSet &Params) {
7615ffd83dbSDimitry Andric   // Skip bundle headers.
7625ffd83dbSDimitry Andric   if (CurMI->isBundle())
7635ffd83dbSDimitry Andric     return true;
7645ffd83dbSDimitry Andric 
7655ffd83dbSDimitry Andric   // If the next instruction is a call we can not interpret parameter's
7665ffd83dbSDimitry Andric   // forwarding registers or we finished the interpretation of all
7675ffd83dbSDimitry Andric   // parameters.
7685ffd83dbSDimitry Andric   if (CurMI->isCall())
7695ffd83dbSDimitry Andric     return false;
7705ffd83dbSDimitry Andric 
7715ffd83dbSDimitry Andric   if (ForwardedRegWorklist.empty())
7725ffd83dbSDimitry Andric     return false;
7735ffd83dbSDimitry Andric 
7745ffd83dbSDimitry Andric   // Avoid NOP description.
7755ffd83dbSDimitry Andric   if (CurMI->getNumOperands() == 0)
7765ffd83dbSDimitry Andric     return true;
7775ffd83dbSDimitry Andric 
7785ffd83dbSDimitry Andric   interpretValues(CurMI, ForwardedRegWorklist, Params);
7795ffd83dbSDimitry Andric 
7805ffd83dbSDimitry Andric   return true;
7815ffd83dbSDimitry Andric }
7825ffd83dbSDimitry Andric 
7838bcb0991SDimitry Andric /// Try to interpret values loaded into registers that forward parameters
7848bcb0991SDimitry Andric /// for \p CallMI. Store parameters with interpreted value into \p Params.
7858bcb0991SDimitry Andric static void collectCallSiteParameters(const MachineInstr *CallMI,
7868bcb0991SDimitry Andric                                       ParamSet &Params) {
7875ffd83dbSDimitry Andric   const MachineFunction *MF = CallMI->getMF();
7888bcb0991SDimitry Andric   auto CalleesMap = MF->getCallSitesInfo();
7898bcb0991SDimitry Andric   auto CallFwdRegsInfo = CalleesMap.find(CallMI);
7908bcb0991SDimitry Andric 
7918bcb0991SDimitry Andric   // There is no information for the call instruction.
7928bcb0991SDimitry Andric   if (CallFwdRegsInfo == CalleesMap.end())
7938bcb0991SDimitry Andric     return;
7948bcb0991SDimitry Andric 
7955ffd83dbSDimitry Andric   const MachineBasicBlock *MBB = CallMI->getParent();
7968bcb0991SDimitry Andric 
7978bcb0991SDimitry Andric   // Skip the call instruction.
7988bcb0991SDimitry Andric   auto I = std::next(CallMI->getReverseIterator());
7998bcb0991SDimitry Andric 
8005ffd83dbSDimitry Andric   FwdRegWorklist ForwardedRegWorklist;
8015ffd83dbSDimitry Andric 
8025ffd83dbSDimitry Andric   const DIExpression *EmptyExpr =
8035ffd83dbSDimitry Andric       DIExpression::get(MF->getFunction().getContext(), {});
8045ffd83dbSDimitry Andric 
8058bcb0991SDimitry Andric   // Add all the forwarding registers into the ForwardedRegWorklist.
8068bcb0991SDimitry Andric   for (auto ArgReg : CallFwdRegsInfo->second) {
8075ffd83dbSDimitry Andric     bool InsertedReg =
8085ffd83dbSDimitry Andric         ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
8095ffd83dbSDimitry Andric             .second;
8108bcb0991SDimitry Andric     assert(InsertedReg && "Single register used to forward two arguments?");
8118bcb0991SDimitry Andric     (void)InsertedReg;
8128bcb0991SDimitry Andric   }
8138bcb0991SDimitry Andric 
814e8d8bef9SDimitry Andric   // Do not emit CSInfo for undef forwarding registers.
815e8d8bef9SDimitry Andric   for (auto &MO : CallMI->uses())
816e8d8bef9SDimitry Andric     if (MO.isReg() && MO.isUndef())
817e8d8bef9SDimitry Andric       ForwardedRegWorklist.erase(MO.getReg());
818e8d8bef9SDimitry Andric 
8198bcb0991SDimitry Andric   // We erase, from the ForwardedRegWorklist, those forwarding registers for
8208bcb0991SDimitry Andric   // which we successfully describe a loaded value (by using
8218bcb0991SDimitry Andric   // the describeLoadedValue()). For those remaining arguments in the working
8228bcb0991SDimitry Andric   // list, for which we do not describe a loaded value by
8238bcb0991SDimitry Andric   // the describeLoadedValue(), we try to generate an entry value expression
8245ffd83dbSDimitry Andric   // for their call site value description, if the call is within the entry MBB.
8258bcb0991SDimitry Andric   // TODO: Handle situations when call site parameter value can be described
8265ffd83dbSDimitry Andric   // as the entry value within basic blocks other than the first one.
8278bcb0991SDimitry Andric   bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
8288bcb0991SDimitry Andric 
8295ffd83dbSDimitry Andric   // Search for a loading value in forwarding registers inside call delay slot.
8305ffd83dbSDimitry Andric   if (CallMI->hasDelaySlot()) {
8315ffd83dbSDimitry Andric     auto Suc = std::next(CallMI->getIterator());
8325ffd83dbSDimitry Andric     // Only one-instruction delay slot is supported.
8335ffd83dbSDimitry Andric     auto BundleEnd = llvm::getBundleEnd(CallMI->getIterator());
8345ffd83dbSDimitry Andric     (void)BundleEnd;
8355ffd83dbSDimitry Andric     assert(std::next(Suc) == BundleEnd &&
8365ffd83dbSDimitry Andric            "More than one instruction in call delay slot");
8375ffd83dbSDimitry Andric     // Try to interpret value loaded by instruction.
8385ffd83dbSDimitry Andric     if (!interpretNextInstr(&*Suc, ForwardedRegWorklist, Params))
8398bcb0991SDimitry Andric       return;
8408bcb0991SDimitry Andric   }
8418bcb0991SDimitry Andric 
842480093f4SDimitry Andric   // Search for a loading value in forwarding registers.
8438bcb0991SDimitry Andric   for (; I != MBB->rend(); ++I) {
8445ffd83dbSDimitry Andric     // Try to interpret values loaded by instruction.
8455ffd83dbSDimitry Andric     if (!interpretNextInstr(&*I, ForwardedRegWorklist, Params))
8468bcb0991SDimitry Andric       return;
8478bcb0991SDimitry Andric   }
8488bcb0991SDimitry Andric 
8498bcb0991SDimitry Andric   // Emit the call site parameter's value as an entry value.
8508bcb0991SDimitry Andric   if (ShouldTryEmitEntryVals) {
8518bcb0991SDimitry Andric     // Create an expression where the register's entry value is used.
8528bcb0991SDimitry Andric     DIExpression *EntryExpr = DIExpression::get(
8538bcb0991SDimitry Andric         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
8548bcb0991SDimitry Andric     for (auto RegEntry : ForwardedRegWorklist) {
8555ffd83dbSDimitry Andric       MachineLocation MLoc(RegEntry.first);
8565ffd83dbSDimitry Andric       finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
8578bcb0991SDimitry Andric     }
8588bcb0991SDimitry Andric   }
8598bcb0991SDimitry Andric }
8608bcb0991SDimitry Andric 
861*0b57cec5SDimitry Andric void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
862*0b57cec5SDimitry Andric                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
863*0b57cec5SDimitry Andric                                             const MachineFunction &MF) {
864*0b57cec5SDimitry Andric   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
865*0b57cec5SDimitry Andric   // the subprogram is required to have one.
866*0b57cec5SDimitry Andric   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
867*0b57cec5SDimitry Andric     return;
868*0b57cec5SDimitry Andric 
869*0b57cec5SDimitry Andric   // Use DW_AT_call_all_calls to express that call site entries are present
870*0b57cec5SDimitry Andric   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
871*0b57cec5SDimitry Andric   // because one of its requirements is not met: call site entries for
872*0b57cec5SDimitry Andric   // optimized-out calls are elided.
8738bcb0991SDimitry Andric   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
874*0b57cec5SDimitry Andric 
875*0b57cec5SDimitry Andric   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
876*0b57cec5SDimitry Andric   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
8775ffd83dbSDimitry Andric 
8785ffd83dbSDimitry Andric   // Delay slot support check.
8795ffd83dbSDimitry Andric   auto delaySlotSupported = [&](const MachineInstr &MI) {
8805ffd83dbSDimitry Andric     if (!MI.isBundledWithSucc())
8815ffd83dbSDimitry Andric       return false;
8825ffd83dbSDimitry Andric     auto Suc = std::next(MI.getIterator());
8835ffd83dbSDimitry Andric     auto CallInstrBundle = getBundleStart(MI.getIterator());
8845ffd83dbSDimitry Andric     (void)CallInstrBundle;
8855ffd83dbSDimitry Andric     auto DelaySlotBundle = getBundleStart(Suc);
8865ffd83dbSDimitry Andric     (void)DelaySlotBundle;
8875ffd83dbSDimitry Andric     // Ensure that label after call is following delay slot instruction.
8885ffd83dbSDimitry Andric     // Ex. CALL_INSTRUCTION {
8895ffd83dbSDimitry Andric     //       DELAY_SLOT_INSTRUCTION }
8905ffd83dbSDimitry Andric     //      LABEL_AFTER_CALL
8915ffd83dbSDimitry Andric     assert(getLabelAfterInsn(&*CallInstrBundle) ==
8925ffd83dbSDimitry Andric                getLabelAfterInsn(&*DelaySlotBundle) &&
8935ffd83dbSDimitry Andric            "Call and its successor instruction don't have same label after.");
8945ffd83dbSDimitry Andric     return true;
8955ffd83dbSDimitry Andric   };
896*0b57cec5SDimitry Andric 
897*0b57cec5SDimitry Andric   // Emit call site entries for each call or tail call in the function.
898*0b57cec5SDimitry Andric   for (const MachineBasicBlock &MBB : MF) {
899*0b57cec5SDimitry Andric     for (const MachineInstr &MI : MBB.instrs()) {
900480093f4SDimitry Andric       // Bundles with call in them will pass the isCall() test below but do not
901480093f4SDimitry Andric       // have callee operand information so skip them here. Iterator will
902480093f4SDimitry Andric       // eventually reach the call MI.
903480093f4SDimitry Andric       if (MI.isBundle())
904480093f4SDimitry Andric         continue;
905480093f4SDimitry Andric 
906*0b57cec5SDimitry Andric       // Skip instructions which aren't calls. Both calls and tail-calling jump
907*0b57cec5SDimitry Andric       // instructions (e.g TAILJMPd64) are classified correctly here.
9085ffd83dbSDimitry Andric       if (!MI.isCandidateForCallSiteEntry())
909*0b57cec5SDimitry Andric         continue;
910*0b57cec5SDimitry Andric 
9115ffd83dbSDimitry Andric       // Skip instructions marked as frame setup, as they are not interesting to
9125ffd83dbSDimitry Andric       // the user.
9135ffd83dbSDimitry Andric       if (MI.getFlag(MachineInstr::FrameSetup))
9145ffd83dbSDimitry Andric         continue;
9155ffd83dbSDimitry Andric 
9165ffd83dbSDimitry Andric       // Check if delay slot support is enabled.
9175ffd83dbSDimitry Andric       if (MI.hasDelaySlot() && !delaySlotSupported(*&MI))
918*0b57cec5SDimitry Andric         return;
919*0b57cec5SDimitry Andric 
920*0b57cec5SDimitry Andric       // If this is a direct call, find the callee's subprogram.
9218bcb0991SDimitry Andric       // In the case of an indirect call find the register that holds
9228bcb0991SDimitry Andric       // the callee.
923*0b57cec5SDimitry Andric       const MachineOperand &CalleeOp = MI.getOperand(0);
9248bcb0991SDimitry Andric       if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
925*0b57cec5SDimitry Andric         continue;
926*0b57cec5SDimitry Andric 
9278bcb0991SDimitry Andric       unsigned CallReg = 0;
9285ffd83dbSDimitry Andric       DIE *CalleeDIE = nullptr;
9298bcb0991SDimitry Andric       const Function *CalleeDecl = nullptr;
9308bcb0991SDimitry Andric       if (CalleeOp.isReg()) {
9318bcb0991SDimitry Andric         CallReg = CalleeOp.getReg();
9328bcb0991SDimitry Andric         if (!CallReg)
9338bcb0991SDimitry Andric           continue;
9348bcb0991SDimitry Andric       } else {
9358bcb0991SDimitry Andric         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
9368bcb0991SDimitry Andric         if (!CalleeDecl || !CalleeDecl->getSubprogram())
9378bcb0991SDimitry Andric           continue;
9385ffd83dbSDimitry Andric         const DISubprogram *CalleeSP = CalleeDecl->getSubprogram();
9395ffd83dbSDimitry Andric 
9405ffd83dbSDimitry Andric         if (CalleeSP->isDefinition()) {
9415ffd83dbSDimitry Andric           // Ensure that a subprogram DIE for the callee is available in the
9425ffd83dbSDimitry Andric           // appropriate CU.
9435ffd83dbSDimitry Andric           CalleeDIE = &constructSubprogramDefinitionDIE(CalleeSP);
9445ffd83dbSDimitry Andric         } else {
9455ffd83dbSDimitry Andric           // Create the declaration DIE if it is missing. This is required to
9465ffd83dbSDimitry Andric           // support compilation of old bitcode with an incomplete list of
9475ffd83dbSDimitry Andric           // retained metadata.
9485ffd83dbSDimitry Andric           CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP);
9495ffd83dbSDimitry Andric         }
9505ffd83dbSDimitry Andric         assert(CalleeDIE && "Must have a DIE for the callee");
9518bcb0991SDimitry Andric       }
9528bcb0991SDimitry Andric 
953*0b57cec5SDimitry Andric       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric       bool IsTail = TII->isTailCall(MI);
956*0b57cec5SDimitry Andric 
957480093f4SDimitry Andric       // If MI is in a bundle, the label was created after the bundle since
958480093f4SDimitry Andric       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
959480093f4SDimitry Andric       // to search for that label below.
960480093f4SDimitry Andric       const MachineInstr *TopLevelCallMI =
961480093f4SDimitry Andric           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
962480093f4SDimitry Andric 
9635ffd83dbSDimitry Andric       // For non-tail calls, the return PC is needed to disambiguate paths in
9645ffd83dbSDimitry Andric       // the call graph which could lead to some target function. For tail
9655ffd83dbSDimitry Andric       // calls, no return PC information is needed, unless tuning for GDB in
9665ffd83dbSDimitry Andric       // DWARF4 mode in which case we fake a return PC for compatibility.
9678bcb0991SDimitry Andric       const MCSymbol *PCAddr =
9685ffd83dbSDimitry Andric           (!IsTail || CU.useGNUAnalogForDwarf5Feature())
969480093f4SDimitry Andric               ? const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI))
9708bcb0991SDimitry Andric               : nullptr;
9718bcb0991SDimitry Andric 
9725ffd83dbSDimitry Andric       // For tail calls, it's necessary to record the address of the branch
9735ffd83dbSDimitry Andric       // instruction so that the debugger can show where the tail call occurred.
9745ffd83dbSDimitry Andric       const MCSymbol *CallAddr =
9755ffd83dbSDimitry Andric           IsTail ? getLabelBeforeInsn(TopLevelCallMI) : nullptr;
9765ffd83dbSDimitry Andric 
9775ffd83dbSDimitry Andric       assert((IsTail || PCAddr) && "Non-tail call without return PC");
9788bcb0991SDimitry Andric 
979*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
9808bcb0991SDimitry Andric                         << (CalleeDecl ? CalleeDecl->getName()
9818bcb0991SDimitry Andric                                        : StringRef(MF.getSubtarget()
9828bcb0991SDimitry Andric                                                        .getRegisterInfo()
9838bcb0991SDimitry Andric                                                        ->getName(CallReg)))
9848bcb0991SDimitry Andric                         << (IsTail ? " [IsTail]" : "") << "\n");
9858bcb0991SDimitry Andric 
9865ffd83dbSDimitry Andric       DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(
9875ffd83dbSDimitry Andric           ScopeDIE, CalleeDIE, IsTail, PCAddr, CallAddr, CallReg);
9888bcb0991SDimitry Andric 
9895ffd83dbSDimitry Andric       // Optionally emit call-site-param debug info.
9905ffd83dbSDimitry Andric       if (emitDebugEntryValues()) {
9918bcb0991SDimitry Andric         ParamSet Params;
9928bcb0991SDimitry Andric         // Try to interpret values of call site parameters.
9938bcb0991SDimitry Andric         collectCallSiteParameters(&MI, Params);
9948bcb0991SDimitry Andric         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
9958bcb0991SDimitry Andric       }
996*0b57cec5SDimitry Andric     }
997*0b57cec5SDimitry Andric   }
998*0b57cec5SDimitry Andric }
999*0b57cec5SDimitry Andric 
1000*0b57cec5SDimitry Andric void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
1001*0b57cec5SDimitry Andric   if (!U.hasDwarfPubSections())
1002*0b57cec5SDimitry Andric     return;
1003*0b57cec5SDimitry Andric 
1004*0b57cec5SDimitry Andric   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
1005*0b57cec5SDimitry Andric }
1006*0b57cec5SDimitry Andric 
1007*0b57cec5SDimitry Andric void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
1008*0b57cec5SDimitry Andric                                       DwarfCompileUnit &NewCU) {
1009*0b57cec5SDimitry Andric   DIE &Die = NewCU.getUnitDie();
1010*0b57cec5SDimitry Andric   StringRef FN = DIUnit->getFilename();
1011*0b57cec5SDimitry Andric 
1012*0b57cec5SDimitry Andric   StringRef Producer = DIUnit->getProducer();
1013*0b57cec5SDimitry Andric   StringRef Flags = DIUnit->getFlags();
1014*0b57cec5SDimitry Andric   if (!Flags.empty() && !useAppleExtensionAttributes()) {
1015*0b57cec5SDimitry Andric     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
1016*0b57cec5SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
1017*0b57cec5SDimitry Andric   } else
1018*0b57cec5SDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
1019*0b57cec5SDimitry Andric 
1020*0b57cec5SDimitry Andric   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1021*0b57cec5SDimitry Andric                 DIUnit->getSourceLanguage());
1022*0b57cec5SDimitry Andric   NewCU.addString(Die, dwarf::DW_AT_name, FN);
10235ffd83dbSDimitry Andric   StringRef SysRoot = DIUnit->getSysRoot();
10245ffd83dbSDimitry Andric   if (!SysRoot.empty())
10255ffd83dbSDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
10265ffd83dbSDimitry Andric   StringRef SDK = DIUnit->getSDK();
10275ffd83dbSDimitry Andric   if (!SDK.empty())
10285ffd83dbSDimitry Andric     NewCU.addString(Die, dwarf::DW_AT_APPLE_sdk, SDK);
1029*0b57cec5SDimitry Andric 
1030*0b57cec5SDimitry Andric   // Add DW_str_offsets_base to the unit DIE, except for split units.
1031*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
1032*0b57cec5SDimitry Andric     NewCU.addStringOffsetsStart();
1033*0b57cec5SDimitry Andric 
1034*0b57cec5SDimitry Andric   if (!useSplitDwarf()) {
1035*0b57cec5SDimitry Andric     NewCU.initStmtList();
1036*0b57cec5SDimitry Andric 
1037*0b57cec5SDimitry Andric     // If we're using split dwarf the compilation dir is going to be in the
1038*0b57cec5SDimitry Andric     // skeleton CU and so we don't need to duplicate it here.
1039*0b57cec5SDimitry Andric     if (!CompilationDir.empty())
1040*0b57cec5SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1041*0b57cec5SDimitry Andric     addGnuPubAttributes(NewCU, Die);
1042*0b57cec5SDimitry Andric   }
1043*0b57cec5SDimitry Andric 
1044*0b57cec5SDimitry Andric   if (useAppleExtensionAttributes()) {
1045*0b57cec5SDimitry Andric     if (DIUnit->isOptimized())
1046*0b57cec5SDimitry Andric       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
1047*0b57cec5SDimitry Andric 
1048*0b57cec5SDimitry Andric     StringRef Flags = DIUnit->getFlags();
1049*0b57cec5SDimitry Andric     if (!Flags.empty())
1050*0b57cec5SDimitry Andric       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
1051*0b57cec5SDimitry Andric 
1052*0b57cec5SDimitry Andric     if (unsigned RVer = DIUnit->getRuntimeVersion())
1053*0b57cec5SDimitry Andric       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1054*0b57cec5SDimitry Andric                     dwarf::DW_FORM_data1, RVer);
1055*0b57cec5SDimitry Andric   }
1056*0b57cec5SDimitry Andric 
1057*0b57cec5SDimitry Andric   if (DIUnit->getDWOId()) {
1058*0b57cec5SDimitry Andric     // This CU is either a clang module DWO or a skeleton CU.
1059*0b57cec5SDimitry Andric     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
1060*0b57cec5SDimitry Andric                   DIUnit->getDWOId());
1061480093f4SDimitry Andric     if (!DIUnit->getSplitDebugFilename().empty()) {
1062*0b57cec5SDimitry Andric       // This is a prefabricated skeleton CU.
1063480093f4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1064480093f4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1065480093f4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
1066480093f4SDimitry Andric       NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
1067480093f4SDimitry Andric     }
1068*0b57cec5SDimitry Andric   }
1069*0b57cec5SDimitry Andric }
1070*0b57cec5SDimitry Andric // Create new DwarfCompileUnit for the given metadata node with tag
1071*0b57cec5SDimitry Andric // DW_TAG_compile_unit.
1072*0b57cec5SDimitry Andric DwarfCompileUnit &
1073*0b57cec5SDimitry Andric DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
1074*0b57cec5SDimitry Andric   if (auto *CU = CUMap.lookup(DIUnit))
1075*0b57cec5SDimitry Andric     return *CU;
1076*0b57cec5SDimitry Andric 
1077*0b57cec5SDimitry Andric   CompilationDir = DIUnit->getDirectory();
1078*0b57cec5SDimitry Andric 
10798bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
1080*0b57cec5SDimitry Andric       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
1081*0b57cec5SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
1082*0b57cec5SDimitry Andric   InfoHolder.addUnit(std::move(OwnedUnit));
1083*0b57cec5SDimitry Andric 
1084*0b57cec5SDimitry Andric   for (auto *IE : DIUnit->getImportedEntities())
1085*0b57cec5SDimitry Andric     NewCU.addImportedEntity(IE);
1086*0b57cec5SDimitry Andric 
1087*0b57cec5SDimitry Andric   // LTO with assembly output shares a single line table amongst multiple CUs.
1088*0b57cec5SDimitry Andric   // To avoid the compilation directory being ambiguous, let the line table
1089*0b57cec5SDimitry Andric   // explicitly describe the directory of all files, never relying on the
1090*0b57cec5SDimitry Andric   // compilation directory.
1091*0b57cec5SDimitry Andric   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
1092*0b57cec5SDimitry Andric     Asm->OutStreamer->emitDwarfFile0Directive(
1093e8d8bef9SDimitry Andric         CompilationDir, DIUnit->getFilename(), getMD5AsBytes(DIUnit->getFile()),
1094e8d8bef9SDimitry Andric         DIUnit->getSource(), NewCU.getUniqueID());
1095*0b57cec5SDimitry Andric 
1096*0b57cec5SDimitry Andric   if (useSplitDwarf()) {
1097*0b57cec5SDimitry Andric     NewCU.setSkeleton(constructSkeletonCU(NewCU));
1098*0b57cec5SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1099*0b57cec5SDimitry Andric   } else {
1100*0b57cec5SDimitry Andric     finishUnitAttributes(DIUnit, NewCU);
1101*0b57cec5SDimitry Andric     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1102*0b57cec5SDimitry Andric   }
1103*0b57cec5SDimitry Andric 
1104*0b57cec5SDimitry Andric   CUMap.insert({DIUnit, &NewCU});
1105*0b57cec5SDimitry Andric   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1106*0b57cec5SDimitry Andric   return NewCU;
1107*0b57cec5SDimitry Andric }
1108*0b57cec5SDimitry Andric 
1109*0b57cec5SDimitry Andric void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
1110*0b57cec5SDimitry Andric                                                   const DIImportedEntity *N) {
1111*0b57cec5SDimitry Andric   if (isa<DILocalScope>(N->getScope()))
1112*0b57cec5SDimitry Andric     return;
1113*0b57cec5SDimitry Andric   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
1114*0b57cec5SDimitry Andric     D->addChild(TheCU.constructImportedEntityDIE(N));
1115*0b57cec5SDimitry Andric }
1116*0b57cec5SDimitry Andric 
1117*0b57cec5SDimitry Andric /// Sort and unique GVEs by comparing their fragment offset.
1118*0b57cec5SDimitry Andric static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1119*0b57cec5SDimitry Andric sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1120*0b57cec5SDimitry Andric   llvm::sort(
1121*0b57cec5SDimitry Andric       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1122*0b57cec5SDimitry Andric         // Sort order: first null exprs, then exprs without fragment
1123*0b57cec5SDimitry Andric         // info, then sort by fragment offset in bits.
1124*0b57cec5SDimitry Andric         // FIXME: Come up with a more comprehensive comparator so
1125*0b57cec5SDimitry Andric         // the sorting isn't non-deterministic, and so the following
1126*0b57cec5SDimitry Andric         // std::unique call works correctly.
1127*0b57cec5SDimitry Andric         if (!A.Expr || !B.Expr)
1128*0b57cec5SDimitry Andric           return !!B.Expr;
1129*0b57cec5SDimitry Andric         auto FragmentA = A.Expr->getFragmentInfo();
1130*0b57cec5SDimitry Andric         auto FragmentB = B.Expr->getFragmentInfo();
1131*0b57cec5SDimitry Andric         if (!FragmentA || !FragmentB)
1132*0b57cec5SDimitry Andric           return !!FragmentB;
1133*0b57cec5SDimitry Andric         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1134*0b57cec5SDimitry Andric       });
1135*0b57cec5SDimitry Andric   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1136*0b57cec5SDimitry Andric                          [](DwarfCompileUnit::GlobalExpr A,
1137*0b57cec5SDimitry Andric                             DwarfCompileUnit::GlobalExpr B) {
1138*0b57cec5SDimitry Andric                            return A.Expr == B.Expr;
1139*0b57cec5SDimitry Andric                          }),
1140*0b57cec5SDimitry Andric              GVEs.end());
1141*0b57cec5SDimitry Andric   return GVEs;
1142*0b57cec5SDimitry Andric }
1143*0b57cec5SDimitry Andric 
1144*0b57cec5SDimitry Andric // Emit all Dwarf sections that should come prior to the content. Create
1145*0b57cec5SDimitry Andric // global DIEs and emit initial debug info sections. This is invoked by
1146*0b57cec5SDimitry Andric // the target AsmPrinter.
1147e8d8bef9SDimitry Andric void DwarfDebug::beginModule(Module *M) {
1148e8d8bef9SDimitry Andric   DebugHandlerBase::beginModule(M);
1149*0b57cec5SDimitry Andric 
1150e8d8bef9SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
1151e8d8bef9SDimitry Andric     return;
1152*0b57cec5SDimitry Andric 
1153*0b57cec5SDimitry Andric   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1154*0b57cec5SDimitry Andric                                        M->debug_compile_units_end());
1155e8d8bef9SDimitry Andric   assert(NumDebugCUs > 0 && "Asm unexpectedly initialized");
1156e8d8bef9SDimitry Andric   assert(MMI->hasDebugInfo() &&
1157e8d8bef9SDimitry Andric          "DebugInfoAvailabilty unexpectedly not initialized");
1158*0b57cec5SDimitry Andric   SingleCU = NumDebugCUs == 1;
1159*0b57cec5SDimitry Andric   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1160*0b57cec5SDimitry Andric       GVMap;
1161*0b57cec5SDimitry Andric   for (const GlobalVariable &Global : M->globals()) {
1162*0b57cec5SDimitry Andric     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1163*0b57cec5SDimitry Andric     Global.getDebugInfo(GVs);
1164*0b57cec5SDimitry Andric     for (auto *GVE : GVs)
1165*0b57cec5SDimitry Andric       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1166*0b57cec5SDimitry Andric   }
1167*0b57cec5SDimitry Andric 
1168*0b57cec5SDimitry Andric   // Create the symbol that designates the start of the unit's contribution
1169*0b57cec5SDimitry Andric   // to the string offsets table. In a split DWARF scenario, only the skeleton
1170*0b57cec5SDimitry Andric   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1171*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
1172*0b57cec5SDimitry Andric     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1173*0b57cec5SDimitry Andric         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1174*0b57cec5SDimitry Andric 
1175*0b57cec5SDimitry Andric 
1176*0b57cec5SDimitry Andric   // Create the symbols that designates the start of the DWARF v5 range list
1177*0b57cec5SDimitry Andric   // and locations list tables. They are located past the table headers.
1178*0b57cec5SDimitry Andric   if (getDwarfVersion() >= 5) {
1179*0b57cec5SDimitry Andric     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1180*0b57cec5SDimitry Andric     Holder.setRnglistsTableBaseSym(
1181*0b57cec5SDimitry Andric         Asm->createTempSymbol("rnglists_table_base"));
1182*0b57cec5SDimitry Andric 
1183*0b57cec5SDimitry Andric     if (useSplitDwarf())
1184*0b57cec5SDimitry Andric       InfoHolder.setRnglistsTableBaseSym(
1185*0b57cec5SDimitry Andric           Asm->createTempSymbol("rnglists_dwo_table_base"));
1186*0b57cec5SDimitry Andric   }
1187*0b57cec5SDimitry Andric 
1188*0b57cec5SDimitry Andric   // Create the symbol that points to the first entry following the debug
1189*0b57cec5SDimitry Andric   // address table (.debug_addr) header.
1190*0b57cec5SDimitry Andric   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1191480093f4SDimitry Andric   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1194*0b57cec5SDimitry Andric     // FIXME: Move local imported entities into a list attached to the
1195*0b57cec5SDimitry Andric     // subprogram, then this search won't be needed and a
1196*0b57cec5SDimitry Andric     // getImportedEntities().empty() test should go below with the rest.
1197*0b57cec5SDimitry Andric     bool HasNonLocalImportedEntities = llvm::any_of(
1198*0b57cec5SDimitry Andric         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1199*0b57cec5SDimitry Andric           return !isa<DILocalScope>(IE->getScope());
1200*0b57cec5SDimitry Andric         });
1201*0b57cec5SDimitry Andric 
1202*0b57cec5SDimitry Andric     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1203*0b57cec5SDimitry Andric         CUNode->getRetainedTypes().empty() &&
1204*0b57cec5SDimitry Andric         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1205*0b57cec5SDimitry Andric       continue;
1206*0b57cec5SDimitry Andric 
1207*0b57cec5SDimitry Andric     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1208*0b57cec5SDimitry Andric 
1209*0b57cec5SDimitry Andric     // Global Variables.
1210*0b57cec5SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
1211*0b57cec5SDimitry Andric       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1212*0b57cec5SDimitry Andric       // already know about the variable and it isn't adding a constant
1213*0b57cec5SDimitry Andric       // expression.
1214*0b57cec5SDimitry Andric       auto &GVMapEntry = GVMap[GVE->getVariable()];
1215*0b57cec5SDimitry Andric       auto *Expr = GVE->getExpression();
1216*0b57cec5SDimitry Andric       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1217*0b57cec5SDimitry Andric         GVMapEntry.push_back({nullptr, Expr});
1218*0b57cec5SDimitry Andric     }
1219*0b57cec5SDimitry Andric     DenseSet<DIGlobalVariable *> Processed;
1220*0b57cec5SDimitry Andric     for (auto *GVE : CUNode->getGlobalVariables()) {
1221*0b57cec5SDimitry Andric       DIGlobalVariable *GV = GVE->getVariable();
1222*0b57cec5SDimitry Andric       if (Processed.insert(GV).second)
1223*0b57cec5SDimitry Andric         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1224*0b57cec5SDimitry Andric     }
1225*0b57cec5SDimitry Andric 
1226*0b57cec5SDimitry Andric     for (auto *Ty : CUNode->getEnumTypes()) {
1227*0b57cec5SDimitry Andric       // The enum types array by design contains pointers to
1228*0b57cec5SDimitry Andric       // MDNodes rather than DIRefs. Unique them here.
1229*0b57cec5SDimitry Andric       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1230*0b57cec5SDimitry Andric     }
1231*0b57cec5SDimitry Andric     for (auto *Ty : CUNode->getRetainedTypes()) {
1232*0b57cec5SDimitry Andric       // The retained types array by design contains pointers to
1233*0b57cec5SDimitry Andric       // MDNodes rather than DIRefs. Unique them here.
1234*0b57cec5SDimitry Andric       if (DIType *RT = dyn_cast<DIType>(Ty))
1235*0b57cec5SDimitry Andric           // There is no point in force-emitting a forward declaration.
1236*0b57cec5SDimitry Andric           CU.getOrCreateTypeDIE(RT);
1237*0b57cec5SDimitry Andric     }
1238*0b57cec5SDimitry Andric     // Emit imported_modules last so that the relevant context is already
1239*0b57cec5SDimitry Andric     // available.
1240*0b57cec5SDimitry Andric     for (auto *IE : CUNode->getImportedEntities())
1241*0b57cec5SDimitry Andric       constructAndAddImportedEntityDIE(CU, IE);
1242*0b57cec5SDimitry Andric   }
1243*0b57cec5SDimitry Andric }
1244*0b57cec5SDimitry Andric 
1245*0b57cec5SDimitry Andric void DwarfDebug::finishEntityDefinitions() {
1246*0b57cec5SDimitry Andric   for (const auto &Entity : ConcreteEntities) {
1247*0b57cec5SDimitry Andric     DIE *Die = Entity->getDIE();
1248*0b57cec5SDimitry Andric     assert(Die);
1249*0b57cec5SDimitry Andric     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1250*0b57cec5SDimitry Andric     // in the ConcreteEntities list, rather than looking it up again here.
1251*0b57cec5SDimitry Andric     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1252*0b57cec5SDimitry Andric     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1253*0b57cec5SDimitry Andric     assert(Unit);
1254*0b57cec5SDimitry Andric     Unit->finishEntityDefinition(Entity.get());
1255*0b57cec5SDimitry Andric   }
1256*0b57cec5SDimitry Andric }
1257*0b57cec5SDimitry Andric 
1258*0b57cec5SDimitry Andric void DwarfDebug::finishSubprogramDefinitions() {
1259*0b57cec5SDimitry Andric   for (const DISubprogram *SP : ProcessedSPNodes) {
1260*0b57cec5SDimitry Andric     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1261*0b57cec5SDimitry Andric     forBothCUs(
1262*0b57cec5SDimitry Andric         getOrCreateDwarfCompileUnit(SP->getUnit()),
1263*0b57cec5SDimitry Andric         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1264*0b57cec5SDimitry Andric   }
1265*0b57cec5SDimitry Andric }
1266*0b57cec5SDimitry Andric 
1267*0b57cec5SDimitry Andric void DwarfDebug::finalizeModuleInfo() {
1268*0b57cec5SDimitry Andric   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1269*0b57cec5SDimitry Andric 
1270*0b57cec5SDimitry Andric   finishSubprogramDefinitions();
1271*0b57cec5SDimitry Andric 
1272*0b57cec5SDimitry Andric   finishEntityDefinitions();
1273*0b57cec5SDimitry Andric 
1274*0b57cec5SDimitry Andric   // Include the DWO file name in the hash if there's more than one CU.
1275*0b57cec5SDimitry Andric   // This handles ThinLTO's situation where imported CUs may very easily be
1276*0b57cec5SDimitry Andric   // duplicate with the same CU partially imported into another ThinLTO unit.
1277*0b57cec5SDimitry Andric   StringRef DWOName;
1278*0b57cec5SDimitry Andric   if (CUMap.size() > 1)
1279*0b57cec5SDimitry Andric     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1280*0b57cec5SDimitry Andric 
1281*0b57cec5SDimitry Andric   // Handle anything that needs to be done on a per-unit basis after
1282*0b57cec5SDimitry Andric   // all other generation.
1283*0b57cec5SDimitry Andric   for (const auto &P : CUMap) {
1284*0b57cec5SDimitry Andric     auto &TheCU = *P.second;
1285*0b57cec5SDimitry Andric     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1286*0b57cec5SDimitry Andric       continue;
1287*0b57cec5SDimitry Andric     // Emit DW_AT_containing_type attribute to connect types with their
1288*0b57cec5SDimitry Andric     // vtable holding type.
1289*0b57cec5SDimitry Andric     TheCU.constructContainingTypeDIEs();
1290*0b57cec5SDimitry Andric 
1291*0b57cec5SDimitry Andric     // Add CU specific attributes if we need to add any.
1292*0b57cec5SDimitry Andric     // If we're splitting the dwarf out now that we've got the entire
1293*0b57cec5SDimitry Andric     // CU then add the dwo id to it.
1294*0b57cec5SDimitry Andric     auto *SkCU = TheCU.getSkeleton();
1295480093f4SDimitry Andric 
1296480093f4SDimitry Andric     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1297480093f4SDimitry Andric 
1298480093f4SDimitry Andric     if (HasSplitUnit) {
1299480093f4SDimitry Andric       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1300480093f4SDimitry Andric                                          ? dwarf::DW_AT_dwo_name
1301480093f4SDimitry Andric                                          : dwarf::DW_AT_GNU_dwo_name;
1302*0b57cec5SDimitry Andric       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1303480093f4SDimitry Andric       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1304*0b57cec5SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1305480093f4SDimitry Andric       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1306*0b57cec5SDimitry Andric                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1307*0b57cec5SDimitry Andric       // Emit a unique identifier for this CU.
1308*0b57cec5SDimitry Andric       uint64_t ID =
1309e8d8bef9SDimitry Andric           DIEHash(Asm, &TheCU).computeCUSignature(DWOName, TheCU.getUnitDie());
1310*0b57cec5SDimitry Andric       if (getDwarfVersion() >= 5) {
1311*0b57cec5SDimitry Andric         TheCU.setDWOId(ID);
1312*0b57cec5SDimitry Andric         SkCU->setDWOId(ID);
1313*0b57cec5SDimitry Andric       } else {
1314*0b57cec5SDimitry Andric         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1315*0b57cec5SDimitry Andric                       dwarf::DW_FORM_data8, ID);
1316*0b57cec5SDimitry Andric         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1317*0b57cec5SDimitry Andric                       dwarf::DW_FORM_data8, ID);
1318*0b57cec5SDimitry Andric       }
1319*0b57cec5SDimitry Andric 
1320*0b57cec5SDimitry Andric       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1321*0b57cec5SDimitry Andric         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1322*0b57cec5SDimitry Andric         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1323*0b57cec5SDimitry Andric                               Sym, Sym);
1324*0b57cec5SDimitry Andric       }
1325*0b57cec5SDimitry Andric     } else if (SkCU) {
1326*0b57cec5SDimitry Andric       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1327*0b57cec5SDimitry Andric     }
1328*0b57cec5SDimitry Andric 
1329*0b57cec5SDimitry Andric     // If we have code split among multiple sections or non-contiguous
1330*0b57cec5SDimitry Andric     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1331*0b57cec5SDimitry Andric     // remain in the .o file, otherwise add a DW_AT_low_pc.
1332*0b57cec5SDimitry Andric     // FIXME: We should use ranges allow reordering of code ala
1333*0b57cec5SDimitry Andric     // .subsections_via_symbols in mach-o. This would mean turning on
1334*0b57cec5SDimitry Andric     // ranges for all subprogram DIEs for mach-o.
1335*0b57cec5SDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1336*0b57cec5SDimitry Andric 
1337*0b57cec5SDimitry Andric     if (unsigned NumRanges = TheCU.getRanges().size()) {
1338*0b57cec5SDimitry Andric       if (NumRanges > 1 && useRangesSection())
1339*0b57cec5SDimitry Andric         // A DW_AT_low_pc attribute may also be specified in combination with
1340*0b57cec5SDimitry Andric         // DW_AT_ranges to specify the default base address for use in
1341*0b57cec5SDimitry Andric         // location lists (see Section 2.6.2) and range lists (see Section
1342*0b57cec5SDimitry Andric         // 2.17.3).
1343*0b57cec5SDimitry Andric         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1344*0b57cec5SDimitry Andric       else
13458bcb0991SDimitry Andric         U.setBaseAddress(TheCU.getRanges().front().Begin);
1346*0b57cec5SDimitry Andric       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1347*0b57cec5SDimitry Andric     }
1348*0b57cec5SDimitry Andric 
1349*0b57cec5SDimitry Andric     // We don't keep track of which addresses are used in which CU so this
1350*0b57cec5SDimitry Andric     // is a bit pessimistic under LTO.
13515ffd83dbSDimitry Andric     if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1352*0b57cec5SDimitry Andric       U.addAddrTableBase();
1353*0b57cec5SDimitry Andric 
1354*0b57cec5SDimitry Andric     if (getDwarfVersion() >= 5) {
1355*0b57cec5SDimitry Andric       if (U.hasRangeLists())
1356*0b57cec5SDimitry Andric         U.addRnglistsBase();
1357*0b57cec5SDimitry Andric 
1358480093f4SDimitry Andric       if (!DebugLocs.getLists().empty()) {
1359480093f4SDimitry Andric         if (!useSplitDwarf())
13608bcb0991SDimitry Andric           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
13618bcb0991SDimitry Andric                             DebugLocs.getSym(),
13628bcb0991SDimitry Andric                             TLOF.getDwarfLoclistsSection()->getBeginSymbol());
13638bcb0991SDimitry Andric       }
1364*0b57cec5SDimitry Andric     }
1365*0b57cec5SDimitry Andric 
1366*0b57cec5SDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
13675ffd83dbSDimitry Andric     // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
13685ffd83dbSDimitry Andric     // attribute.
1369480093f4SDimitry Andric     if (CUNode->getMacros()) {
1370e8d8bef9SDimitry Andric       if (UseDebugMacroSection) {
1371480093f4SDimitry Andric         if (useSplitDwarf())
13725ffd83dbSDimitry Andric           TheCU.addSectionDelta(
13735ffd83dbSDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
13745ffd83dbSDimitry Andric               TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1375e8d8bef9SDimitry Andric         else {
1376e8d8bef9SDimitry Andric           dwarf::Attribute MacrosAttr = getDwarfVersion() >= 5
1377e8d8bef9SDimitry Andric                                             ? dwarf::DW_AT_macros
1378e8d8bef9SDimitry Andric                                             : dwarf::DW_AT_GNU_macros;
1379e8d8bef9SDimitry Andric           U.addSectionLabel(U.getUnitDie(), MacrosAttr, U.getMacroLabelBegin(),
13805ffd83dbSDimitry Andric                             TLOF.getDwarfMacroSection()->getBeginSymbol());
1381e8d8bef9SDimitry Andric         }
13825ffd83dbSDimitry Andric       } else {
13835ffd83dbSDimitry Andric         if (useSplitDwarf())
13845ffd83dbSDimitry Andric           TheCU.addSectionDelta(
13855ffd83dbSDimitry Andric               TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1386480093f4SDimitry Andric               U.getMacroLabelBegin(),
1387480093f4SDimitry Andric               TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1388480093f4SDimitry Andric         else
1389*0b57cec5SDimitry Andric           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1390*0b57cec5SDimitry Andric                             U.getMacroLabelBegin(),
1391*0b57cec5SDimitry Andric                             TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1392*0b57cec5SDimitry Andric       }
1393480093f4SDimitry Andric     }
13945ffd83dbSDimitry Andric     }
1395*0b57cec5SDimitry Andric 
1396*0b57cec5SDimitry Andric   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1397*0b57cec5SDimitry Andric   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1398*0b57cec5SDimitry Andric     if (CUNode->getDWOId())
1399*0b57cec5SDimitry Andric       getOrCreateDwarfCompileUnit(CUNode);
1400*0b57cec5SDimitry Andric 
1401*0b57cec5SDimitry Andric   // Compute DIE offsets and sizes.
1402*0b57cec5SDimitry Andric   InfoHolder.computeSizeAndOffsets();
1403*0b57cec5SDimitry Andric   if (useSplitDwarf())
1404*0b57cec5SDimitry Andric     SkeletonHolder.computeSizeAndOffsets();
1405*0b57cec5SDimitry Andric }
1406*0b57cec5SDimitry Andric 
1407*0b57cec5SDimitry Andric // Emit all Dwarf sections that should come after the content.
1408*0b57cec5SDimitry Andric void DwarfDebug::endModule() {
1409*0b57cec5SDimitry Andric   assert(CurFn == nullptr);
1410*0b57cec5SDimitry Andric   assert(CurMI == nullptr);
1411*0b57cec5SDimitry Andric 
1412*0b57cec5SDimitry Andric   for (const auto &P : CUMap) {
1413*0b57cec5SDimitry Andric     auto &CU = *P.second;
1414*0b57cec5SDimitry Andric     CU.createBaseTypeDIEs();
1415*0b57cec5SDimitry Andric   }
1416*0b57cec5SDimitry Andric 
1417*0b57cec5SDimitry Andric   // If we aren't actually generating debug info (check beginModule -
1418e8d8bef9SDimitry Andric   // conditionalized on the presence of the llvm.dbg.cu metadata node)
1419e8d8bef9SDimitry Andric   if (!Asm || !MMI->hasDebugInfo())
1420*0b57cec5SDimitry Andric     return;
1421*0b57cec5SDimitry Andric 
1422*0b57cec5SDimitry Andric   // Finalize the debug info for the module.
1423*0b57cec5SDimitry Andric   finalizeModuleInfo();
1424*0b57cec5SDimitry Andric 
1425*0b57cec5SDimitry Andric   if (useSplitDwarf())
1426480093f4SDimitry Andric     // Emit debug_loc.dwo/debug_loclists.dwo section.
1427*0b57cec5SDimitry Andric     emitDebugLocDWO();
1428*0b57cec5SDimitry Andric   else
1429480093f4SDimitry Andric     // Emit debug_loc/debug_loclists section.
1430*0b57cec5SDimitry Andric     emitDebugLoc();
1431*0b57cec5SDimitry Andric 
1432*0b57cec5SDimitry Andric   // Corresponding abbreviations into a abbrev section.
1433*0b57cec5SDimitry Andric   emitAbbreviations();
1434*0b57cec5SDimitry Andric 
1435*0b57cec5SDimitry Andric   // Emit all the DIEs into a debug info section.
1436*0b57cec5SDimitry Andric   emitDebugInfo();
1437*0b57cec5SDimitry Andric 
1438*0b57cec5SDimitry Andric   // Emit info into a debug aranges section.
1439*0b57cec5SDimitry Andric   if (GenerateARangeSection)
1440*0b57cec5SDimitry Andric     emitDebugARanges();
1441*0b57cec5SDimitry Andric 
1442*0b57cec5SDimitry Andric   // Emit info into a debug ranges section.
1443*0b57cec5SDimitry Andric   emitDebugRanges();
1444*0b57cec5SDimitry Andric 
1445480093f4SDimitry Andric   if (useSplitDwarf())
1446480093f4SDimitry Andric   // Emit info into a debug macinfo.dwo section.
1447480093f4SDimitry Andric     emitDebugMacinfoDWO();
1448480093f4SDimitry Andric   else
14495ffd83dbSDimitry Andric     // Emit info into a debug macinfo/macro section.
1450*0b57cec5SDimitry Andric     emitDebugMacinfo();
1451*0b57cec5SDimitry Andric 
14525ffd83dbSDimitry Andric   emitDebugStr();
14535ffd83dbSDimitry Andric 
1454*0b57cec5SDimitry Andric   if (useSplitDwarf()) {
1455*0b57cec5SDimitry Andric     emitDebugStrDWO();
1456*0b57cec5SDimitry Andric     emitDebugInfoDWO();
1457*0b57cec5SDimitry Andric     emitDebugAbbrevDWO();
1458*0b57cec5SDimitry Andric     emitDebugLineDWO();
1459*0b57cec5SDimitry Andric     emitDebugRangesDWO();
1460*0b57cec5SDimitry Andric   }
1461*0b57cec5SDimitry Andric 
1462*0b57cec5SDimitry Andric   emitDebugAddr();
1463*0b57cec5SDimitry Andric 
1464*0b57cec5SDimitry Andric   // Emit info into the dwarf accelerator table sections.
1465*0b57cec5SDimitry Andric   switch (getAccelTableKind()) {
1466*0b57cec5SDimitry Andric   case AccelTableKind::Apple:
1467*0b57cec5SDimitry Andric     emitAccelNames();
1468*0b57cec5SDimitry Andric     emitAccelObjC();
1469*0b57cec5SDimitry Andric     emitAccelNamespaces();
1470*0b57cec5SDimitry Andric     emitAccelTypes();
1471*0b57cec5SDimitry Andric     break;
1472*0b57cec5SDimitry Andric   case AccelTableKind::Dwarf:
1473*0b57cec5SDimitry Andric     emitAccelDebugNames();
1474*0b57cec5SDimitry Andric     break;
1475*0b57cec5SDimitry Andric   case AccelTableKind::None:
1476*0b57cec5SDimitry Andric     break;
1477*0b57cec5SDimitry Andric   case AccelTableKind::Default:
1478*0b57cec5SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
1479*0b57cec5SDimitry Andric   }
1480*0b57cec5SDimitry Andric 
1481*0b57cec5SDimitry Andric   // Emit the pubnames and pubtypes sections if requested.
1482*0b57cec5SDimitry Andric   emitDebugPubSections();
1483*0b57cec5SDimitry Andric 
1484*0b57cec5SDimitry Andric   // clean up.
1485*0b57cec5SDimitry Andric   // FIXME: AbstractVariables.clear();
1486*0b57cec5SDimitry Andric }
1487*0b57cec5SDimitry Andric 
1488*0b57cec5SDimitry Andric void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1489*0b57cec5SDimitry Andric                                                const DINode *Node,
1490*0b57cec5SDimitry Andric                                                const MDNode *ScopeNode) {
1491*0b57cec5SDimitry Andric   if (CU.getExistingAbstractEntity(Node))
1492*0b57cec5SDimitry Andric     return;
1493*0b57cec5SDimitry Andric 
1494*0b57cec5SDimitry Andric   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1495*0b57cec5SDimitry Andric                                        cast<DILocalScope>(ScopeNode)));
1496*0b57cec5SDimitry Andric }
1497*0b57cec5SDimitry Andric 
1498*0b57cec5SDimitry Andric void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1499*0b57cec5SDimitry Andric     const DINode *Node, const MDNode *ScopeNode) {
1500*0b57cec5SDimitry Andric   if (CU.getExistingAbstractEntity(Node))
1501*0b57cec5SDimitry Andric     return;
1502*0b57cec5SDimitry Andric 
1503*0b57cec5SDimitry Andric   if (LexicalScope *Scope =
1504*0b57cec5SDimitry Andric           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1505*0b57cec5SDimitry Andric     CU.createAbstractEntity(Node, Scope);
1506*0b57cec5SDimitry Andric }
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric // Collect variable information from side table maintained by MF.
1509*0b57cec5SDimitry Andric void DwarfDebug::collectVariableInfoFromMFTable(
1510*0b57cec5SDimitry Andric     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1511*0b57cec5SDimitry Andric   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
15125ffd83dbSDimitry Andric   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1513*0b57cec5SDimitry Andric   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1514*0b57cec5SDimitry Andric     if (!VI.Var)
1515*0b57cec5SDimitry Andric       continue;
1516*0b57cec5SDimitry Andric     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1517*0b57cec5SDimitry Andric            "Expected inlined-at fields to agree");
1518*0b57cec5SDimitry Andric 
1519*0b57cec5SDimitry Andric     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1520*0b57cec5SDimitry Andric     Processed.insert(Var);
1521*0b57cec5SDimitry Andric     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1522*0b57cec5SDimitry Andric 
1523*0b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
15245ffd83dbSDimitry Andric     if (!Scope) {
15255ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
15265ffd83dbSDimitry Andric                         << ", no variable scope found\n");
1527*0b57cec5SDimitry Andric       continue;
15285ffd83dbSDimitry Andric     }
1529*0b57cec5SDimitry Andric 
1530*0b57cec5SDimitry Andric     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
15318bcb0991SDimitry Andric     auto RegVar = std::make_unique<DbgVariable>(
1532*0b57cec5SDimitry Andric                     cast<DILocalVariable>(Var.first), Var.second);
1533*0b57cec5SDimitry Andric     RegVar->initializeMMI(VI.Expr, VI.Slot);
15345ffd83dbSDimitry Andric     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
15355ffd83dbSDimitry Andric                       << "\n");
1536*0b57cec5SDimitry Andric     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1537*0b57cec5SDimitry Andric       DbgVar->addMMIEntry(*RegVar);
1538*0b57cec5SDimitry Andric     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1539*0b57cec5SDimitry Andric       MFVars.insert({Var, RegVar.get()});
1540*0b57cec5SDimitry Andric       ConcreteEntities.push_back(std::move(RegVar));
1541*0b57cec5SDimitry Andric     }
1542*0b57cec5SDimitry Andric   }
1543*0b57cec5SDimitry Andric }
1544*0b57cec5SDimitry Andric 
1545*0b57cec5SDimitry Andric /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1546*0b57cec5SDimitry Andric /// enclosing lexical scope. The check ensures there are no other instructions
1547*0b57cec5SDimitry Andric /// in the same lexical scope preceding the DBG_VALUE and that its range is
1548*0b57cec5SDimitry Andric /// either open or otherwise rolls off the end of the scope.
1549*0b57cec5SDimitry Andric static bool validThroughout(LexicalScopes &LScopes,
1550*0b57cec5SDimitry Andric                             const MachineInstr *DbgValue,
1551e8d8bef9SDimitry Andric                             const MachineInstr *RangeEnd,
1552e8d8bef9SDimitry Andric                             const InstructionOrdering &Ordering) {
1553*0b57cec5SDimitry Andric   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1554*0b57cec5SDimitry Andric   auto MBB = DbgValue->getParent();
1555*0b57cec5SDimitry Andric   auto DL = DbgValue->getDebugLoc();
1556*0b57cec5SDimitry Andric   auto *LScope = LScopes.findLexicalScope(DL);
1557*0b57cec5SDimitry Andric   // Scope doesn't exist; this is a dead DBG_VALUE.
1558*0b57cec5SDimitry Andric   if (!LScope)
1559*0b57cec5SDimitry Andric     return false;
1560*0b57cec5SDimitry Andric   auto &LSRange = LScope->getRanges();
1561*0b57cec5SDimitry Andric   if (LSRange.size() == 0)
1562*0b57cec5SDimitry Andric     return false;
1563*0b57cec5SDimitry Andric 
1564*0b57cec5SDimitry Andric   const MachineInstr *LScopeBegin = LSRange.front().first;
1565e8d8bef9SDimitry Andric   // If the scope starts before the DBG_VALUE then we may have a negative
1566e8d8bef9SDimitry Andric   // result. Otherwise the location is live coming into the scope and we
1567e8d8bef9SDimitry Andric   // can skip the following checks.
1568e8d8bef9SDimitry Andric   if (!Ordering.isBefore(DbgValue, LScopeBegin)) {
1569e8d8bef9SDimitry Andric     // Exit if the lexical scope begins outside of the current block.
1570*0b57cec5SDimitry Andric     if (LScopeBegin->getParent() != MBB)
1571*0b57cec5SDimitry Andric       return false;
15725ffd83dbSDimitry Andric 
1573*0b57cec5SDimitry Andric     MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1574*0b57cec5SDimitry Andric     for (++Pred; Pred != MBB->rend(); ++Pred) {
1575*0b57cec5SDimitry Andric       if (Pred->getFlag(MachineInstr::FrameSetup))
1576*0b57cec5SDimitry Andric         break;
1577*0b57cec5SDimitry Andric       auto PredDL = Pred->getDebugLoc();
1578*0b57cec5SDimitry Andric       if (!PredDL || Pred->isMetaInstruction())
1579*0b57cec5SDimitry Andric         continue;
1580*0b57cec5SDimitry Andric       // Check whether the instruction preceding the DBG_VALUE is in the same
1581*0b57cec5SDimitry Andric       // (sub)scope as the DBG_VALUE.
1582*0b57cec5SDimitry Andric       if (DL->getScope() == PredDL->getScope())
1583*0b57cec5SDimitry Andric         return false;
1584*0b57cec5SDimitry Andric       auto *PredScope = LScopes.findLexicalScope(PredDL);
1585*0b57cec5SDimitry Andric       if (!PredScope || LScope->dominates(PredScope))
1586*0b57cec5SDimitry Andric         return false;
1587*0b57cec5SDimitry Andric     }
1588e8d8bef9SDimitry Andric   }
1589*0b57cec5SDimitry Andric 
1590*0b57cec5SDimitry Andric   // If the range of the DBG_VALUE is open-ended, report success.
1591*0b57cec5SDimitry Andric   if (!RangeEnd)
1592*0b57cec5SDimitry Andric     return true;
1593*0b57cec5SDimitry Andric 
1594*0b57cec5SDimitry Andric   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1595*0b57cec5SDimitry Andric   // throughout the function. This is a hack, presumably for DWARF v2 and not
1596*0b57cec5SDimitry Andric   // necessarily correct. It would be much better to use a dbg.declare instead
1597*0b57cec5SDimitry Andric   // if we know the constant is live throughout the scope.
15985ffd83dbSDimitry Andric   if (DbgValue->getDebugOperand(0).isImm() && MBB->pred_empty())
1599*0b57cec5SDimitry Andric     return true;
1600*0b57cec5SDimitry Andric 
1601e8d8bef9SDimitry Andric   // Test if the location terminates before the end of the scope.
1602e8d8bef9SDimitry Andric   const MachineInstr *LScopeEnd = LSRange.back().second;
1603e8d8bef9SDimitry Andric   if (Ordering.isBefore(RangeEnd, LScopeEnd))
1604*0b57cec5SDimitry Andric     return false;
16055ffd83dbSDimitry Andric 
16065ffd83dbSDimitry Andric   // There's a single location which starts at the scope start, and ends at or
16075ffd83dbSDimitry Andric   // after the scope end.
16085ffd83dbSDimitry Andric   return true;
1609*0b57cec5SDimitry Andric }
1610*0b57cec5SDimitry Andric 
1611*0b57cec5SDimitry Andric /// Build the location list for all DBG_VALUEs in the function that
1612*0b57cec5SDimitry Andric /// describe the same variable. The resulting DebugLocEntries will have
1613*0b57cec5SDimitry Andric /// strict monotonically increasing begin addresses and will never
1614*0b57cec5SDimitry Andric /// overlap. If the resulting list has only one entry that is valid
1615*0b57cec5SDimitry Andric /// throughout variable's scope return true.
1616*0b57cec5SDimitry Andric //
1617*0b57cec5SDimitry Andric // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1618*0b57cec5SDimitry Andric // different kinds of history map entries. One thing to be aware of is that if
1619*0b57cec5SDimitry Andric // a debug value is ended by another entry (rather than being valid until the
1620*0b57cec5SDimitry Andric // end of the function), that entry's instruction may or may not be included in
1621*0b57cec5SDimitry Andric // the range, depending on if the entry is a clobbering entry (it has an
1622*0b57cec5SDimitry Andric // instruction that clobbers one or more preceding locations), or if it is an
1623*0b57cec5SDimitry Andric // (overlapping) debug value entry. This distinction can be seen in the example
1624*0b57cec5SDimitry Andric // below. The first debug value is ended by the clobbering entry 2, and the
1625*0b57cec5SDimitry Andric // second and third debug values are ended by the overlapping debug value entry
1626*0b57cec5SDimitry Andric // 4.
1627*0b57cec5SDimitry Andric //
1628*0b57cec5SDimitry Andric // Input:
1629*0b57cec5SDimitry Andric //
1630*0b57cec5SDimitry Andric //   History map entries [type, end index, mi]
1631*0b57cec5SDimitry Andric //
1632*0b57cec5SDimitry Andric // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1633*0b57cec5SDimitry Andric // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1634*0b57cec5SDimitry Andric // 2 | |    [Clobber, $reg0 = [...], -, -]
1635*0b57cec5SDimitry Andric // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1636*0b57cec5SDimitry Andric // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1637*0b57cec5SDimitry Andric //
1638*0b57cec5SDimitry Andric // Output [start, end) [Value...]:
1639*0b57cec5SDimitry Andric //
1640*0b57cec5SDimitry Andric // [0-1)    [(reg0, fragment 0, 32)]
1641*0b57cec5SDimitry Andric // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1642*0b57cec5SDimitry Andric // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1643*0b57cec5SDimitry Andric // [4-)     [(@g, fragment 0, 96)]
1644e8d8bef9SDimitry Andric bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1645e8d8bef9SDimitry Andric                                    const DbgValueHistoryMap::Entries &Entries) {
1646*0b57cec5SDimitry Andric   using OpenRange =
1647*0b57cec5SDimitry Andric       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1648*0b57cec5SDimitry Andric   SmallVector<OpenRange, 4> OpenRanges;
1649*0b57cec5SDimitry Andric   bool isSafeForSingleLocation = true;
1650*0b57cec5SDimitry Andric   const MachineInstr *StartDebugMI = nullptr;
1651*0b57cec5SDimitry Andric   const MachineInstr *EndMI = nullptr;
1652*0b57cec5SDimitry Andric 
1653*0b57cec5SDimitry Andric   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1654*0b57cec5SDimitry Andric     const MachineInstr *Instr = EI->getInstr();
1655*0b57cec5SDimitry Andric 
1656*0b57cec5SDimitry Andric     // Remove all values that are no longer live.
1657*0b57cec5SDimitry Andric     size_t Index = std::distance(EB, EI);
1658e8d8bef9SDimitry Andric     erase_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1659*0b57cec5SDimitry Andric 
1660*0b57cec5SDimitry Andric     // If we are dealing with a clobbering entry, this iteration will result in
1661*0b57cec5SDimitry Andric     // a location list entry starting after the clobbering instruction.
1662*0b57cec5SDimitry Andric     const MCSymbol *StartLabel =
1663*0b57cec5SDimitry Andric         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1664*0b57cec5SDimitry Andric     assert(StartLabel &&
1665*0b57cec5SDimitry Andric            "Forgot label before/after instruction starting a range!");
1666*0b57cec5SDimitry Andric 
1667*0b57cec5SDimitry Andric     const MCSymbol *EndLabel;
1668*0b57cec5SDimitry Andric     if (std::next(EI) == Entries.end()) {
16695ffd83dbSDimitry Andric       const MachineBasicBlock &EndMBB = Asm->MF->back();
16705ffd83dbSDimitry Andric       EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
1671*0b57cec5SDimitry Andric       if (EI->isClobber())
1672*0b57cec5SDimitry Andric         EndMI = EI->getInstr();
1673*0b57cec5SDimitry Andric     }
1674*0b57cec5SDimitry Andric     else if (std::next(EI)->isClobber())
1675*0b57cec5SDimitry Andric       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1676*0b57cec5SDimitry Andric     else
1677*0b57cec5SDimitry Andric       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1678*0b57cec5SDimitry Andric     assert(EndLabel && "Forgot label after instruction ending a range!");
1679*0b57cec5SDimitry Andric 
1680*0b57cec5SDimitry Andric     if (EI->isDbgValue())
1681*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1682*0b57cec5SDimitry Andric 
1683*0b57cec5SDimitry Andric     // If this history map entry has a debug value, add that to the list of
1684*0b57cec5SDimitry Andric     // open ranges and check if its location is valid for a single value
1685*0b57cec5SDimitry Andric     // location.
1686*0b57cec5SDimitry Andric     if (EI->isDbgValue()) {
1687*0b57cec5SDimitry Andric       // Do not add undef debug values, as they are redundant information in
1688*0b57cec5SDimitry Andric       // the location list entries. An undef debug results in an empty location
1689*0b57cec5SDimitry Andric       // description. If there are any non-undef fragments then padding pieces
1690*0b57cec5SDimitry Andric       // with empty location descriptions will automatically be inserted, and if
1691*0b57cec5SDimitry Andric       // all fragments are undef then the whole location list entry is
1692*0b57cec5SDimitry Andric       // redundant.
1693*0b57cec5SDimitry Andric       if (!Instr->isUndefDebugValue()) {
1694*0b57cec5SDimitry Andric         auto Value = getDebugLocValue(Instr);
1695*0b57cec5SDimitry Andric         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1696*0b57cec5SDimitry Andric 
1697*0b57cec5SDimitry Andric         // TODO: Add support for single value fragment locations.
1698*0b57cec5SDimitry Andric         if (Instr->getDebugExpression()->isFragment())
1699*0b57cec5SDimitry Andric           isSafeForSingleLocation = false;
1700*0b57cec5SDimitry Andric 
1701*0b57cec5SDimitry Andric         if (!StartDebugMI)
1702*0b57cec5SDimitry Andric           StartDebugMI = Instr;
1703*0b57cec5SDimitry Andric       } else {
1704*0b57cec5SDimitry Andric         isSafeForSingleLocation = false;
1705*0b57cec5SDimitry Andric       }
1706*0b57cec5SDimitry Andric     }
1707*0b57cec5SDimitry Andric 
1708*0b57cec5SDimitry Andric     // Location list entries with empty location descriptions are redundant
1709*0b57cec5SDimitry Andric     // information in DWARF, so do not emit those.
1710*0b57cec5SDimitry Andric     if (OpenRanges.empty())
1711*0b57cec5SDimitry Andric       continue;
1712*0b57cec5SDimitry Andric 
1713*0b57cec5SDimitry Andric     // Omit entries with empty ranges as they do not have any effect in DWARF.
1714*0b57cec5SDimitry Andric     if (StartLabel == EndLabel) {
1715*0b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1716*0b57cec5SDimitry Andric       continue;
1717*0b57cec5SDimitry Andric     }
1718*0b57cec5SDimitry Andric 
1719*0b57cec5SDimitry Andric     SmallVector<DbgValueLoc, 4> Values;
1720*0b57cec5SDimitry Andric     for (auto &R : OpenRanges)
1721*0b57cec5SDimitry Andric       Values.push_back(R.second);
1722*0b57cec5SDimitry Andric     DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1723*0b57cec5SDimitry Andric 
1724*0b57cec5SDimitry Andric     // Attempt to coalesce the ranges of two otherwise identical
1725*0b57cec5SDimitry Andric     // DebugLocEntries.
1726*0b57cec5SDimitry Andric     auto CurEntry = DebugLoc.rbegin();
1727*0b57cec5SDimitry Andric     LLVM_DEBUG({
1728*0b57cec5SDimitry Andric       dbgs() << CurEntry->getValues().size() << " Values:\n";
1729*0b57cec5SDimitry Andric       for (auto &Value : CurEntry->getValues())
1730*0b57cec5SDimitry Andric         Value.dump();
1731*0b57cec5SDimitry Andric       dbgs() << "-----\n";
1732*0b57cec5SDimitry Andric     });
1733*0b57cec5SDimitry Andric 
1734*0b57cec5SDimitry Andric     auto PrevEntry = std::next(CurEntry);
1735*0b57cec5SDimitry Andric     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1736*0b57cec5SDimitry Andric       DebugLoc.pop_back();
1737*0b57cec5SDimitry Andric   }
1738*0b57cec5SDimitry Andric 
1739e8d8bef9SDimitry Andric   return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1740e8d8bef9SDimitry Andric          validThroughout(LScopes, StartDebugMI, EndMI, getInstOrdering());
1741*0b57cec5SDimitry Andric }
1742*0b57cec5SDimitry Andric 
1743*0b57cec5SDimitry Andric DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1744*0b57cec5SDimitry Andric                                             LexicalScope &Scope,
1745*0b57cec5SDimitry Andric                                             const DINode *Node,
1746*0b57cec5SDimitry Andric                                             const DILocation *Location,
1747*0b57cec5SDimitry Andric                                             const MCSymbol *Sym) {
1748*0b57cec5SDimitry Andric   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1749*0b57cec5SDimitry Andric   if (isa<const DILocalVariable>(Node)) {
1750*0b57cec5SDimitry Andric     ConcreteEntities.push_back(
17518bcb0991SDimitry Andric         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1752*0b57cec5SDimitry Andric                                        Location));
1753*0b57cec5SDimitry Andric     InfoHolder.addScopeVariable(&Scope,
1754*0b57cec5SDimitry Andric         cast<DbgVariable>(ConcreteEntities.back().get()));
1755*0b57cec5SDimitry Andric   } else if (isa<const DILabel>(Node)) {
1756*0b57cec5SDimitry Andric     ConcreteEntities.push_back(
17578bcb0991SDimitry Andric         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1758*0b57cec5SDimitry Andric                                     Location, Sym));
1759*0b57cec5SDimitry Andric     InfoHolder.addScopeLabel(&Scope,
1760*0b57cec5SDimitry Andric         cast<DbgLabel>(ConcreteEntities.back().get()));
1761*0b57cec5SDimitry Andric   }
1762*0b57cec5SDimitry Andric   return ConcreteEntities.back().get();
1763*0b57cec5SDimitry Andric }
1764*0b57cec5SDimitry Andric 
1765*0b57cec5SDimitry Andric // Find variables for each lexical scope.
1766*0b57cec5SDimitry Andric void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1767*0b57cec5SDimitry Andric                                    const DISubprogram *SP,
1768*0b57cec5SDimitry Andric                                    DenseSet<InlinedEntity> &Processed) {
1769*0b57cec5SDimitry Andric   // Grab the variable info that was squirreled away in the MMI side-table.
1770*0b57cec5SDimitry Andric   collectVariableInfoFromMFTable(TheCU, Processed);
1771*0b57cec5SDimitry Andric 
1772*0b57cec5SDimitry Andric   for (const auto &I : DbgValues) {
1773*0b57cec5SDimitry Andric     InlinedEntity IV = I.first;
1774*0b57cec5SDimitry Andric     if (Processed.count(IV))
1775*0b57cec5SDimitry Andric       continue;
1776*0b57cec5SDimitry Andric 
1777*0b57cec5SDimitry Andric     // Instruction ranges, specifying where IV is accessible.
1778*0b57cec5SDimitry Andric     const auto &HistoryMapEntries = I.second;
1779*0b57cec5SDimitry Andric     if (HistoryMapEntries.empty())
1780*0b57cec5SDimitry Andric       continue;
1781*0b57cec5SDimitry Andric 
1782*0b57cec5SDimitry Andric     LexicalScope *Scope = nullptr;
1783*0b57cec5SDimitry Andric     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1784*0b57cec5SDimitry Andric     if (const DILocation *IA = IV.second)
1785*0b57cec5SDimitry Andric       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1786*0b57cec5SDimitry Andric     else
1787*0b57cec5SDimitry Andric       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1788*0b57cec5SDimitry Andric     // If variable scope is not found then skip this variable.
1789*0b57cec5SDimitry Andric     if (!Scope)
1790*0b57cec5SDimitry Andric       continue;
1791*0b57cec5SDimitry Andric 
1792*0b57cec5SDimitry Andric     Processed.insert(IV);
1793*0b57cec5SDimitry Andric     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1794*0b57cec5SDimitry Andric                                             *Scope, LocalVar, IV.second));
1795*0b57cec5SDimitry Andric 
1796*0b57cec5SDimitry Andric     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1797*0b57cec5SDimitry Andric     assert(MInsn->isDebugValue() && "History must begin with debug value");
1798*0b57cec5SDimitry Andric 
1799*0b57cec5SDimitry Andric     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1800*0b57cec5SDimitry Andric     // If the history map contains a single debug value, there may be an
1801*0b57cec5SDimitry Andric     // additional entry which clobbers the debug value.
1802*0b57cec5SDimitry Andric     size_t HistSize = HistoryMapEntries.size();
1803*0b57cec5SDimitry Andric     bool SingleValueWithClobber =
1804*0b57cec5SDimitry Andric         HistSize == 2 && HistoryMapEntries[1].isClobber();
1805*0b57cec5SDimitry Andric     if (HistSize == 1 || SingleValueWithClobber) {
1806*0b57cec5SDimitry Andric       const auto *End =
1807*0b57cec5SDimitry Andric           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1808e8d8bef9SDimitry Andric       if (validThroughout(LScopes, MInsn, End, getInstOrdering())) {
1809*0b57cec5SDimitry Andric         RegVar->initializeDbgValue(MInsn);
1810*0b57cec5SDimitry Andric         continue;
1811*0b57cec5SDimitry Andric       }
1812*0b57cec5SDimitry Andric     }
1813*0b57cec5SDimitry Andric 
1814*0b57cec5SDimitry Andric     // Do not emit location lists if .debug_loc secton is disabled.
1815*0b57cec5SDimitry Andric     if (!useLocSection())
1816*0b57cec5SDimitry Andric       continue;
1817*0b57cec5SDimitry Andric 
1818*0b57cec5SDimitry Andric     // Handle multiple DBG_VALUE instructions describing one variable.
1819*0b57cec5SDimitry Andric     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1820*0b57cec5SDimitry Andric 
1821*0b57cec5SDimitry Andric     // Build the location list for this variable.
1822*0b57cec5SDimitry Andric     SmallVector<DebugLocEntry, 8> Entries;
1823e8d8bef9SDimitry Andric     bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1824*0b57cec5SDimitry Andric 
1825*0b57cec5SDimitry Andric     // Check whether buildLocationList managed to merge all locations to one
1826*0b57cec5SDimitry Andric     // that is valid throughout the variable's scope. If so, produce single
1827*0b57cec5SDimitry Andric     // value location.
1828*0b57cec5SDimitry Andric     if (isValidSingleLocation) {
1829*0b57cec5SDimitry Andric       RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1830*0b57cec5SDimitry Andric       continue;
1831*0b57cec5SDimitry Andric     }
1832*0b57cec5SDimitry Andric 
1833*0b57cec5SDimitry Andric     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1834*0b57cec5SDimitry Andric     // unique identifiers, so don't bother resolving the type with the
1835*0b57cec5SDimitry Andric     // identifier map.
1836*0b57cec5SDimitry Andric     const DIBasicType *BT = dyn_cast<DIBasicType>(
1837*0b57cec5SDimitry Andric         static_cast<const Metadata *>(LocalVar->getType()));
1838*0b57cec5SDimitry Andric 
1839*0b57cec5SDimitry Andric     // Finalize the entry by lowering it into a DWARF bytestream.
1840*0b57cec5SDimitry Andric     for (auto &Entry : Entries)
1841*0b57cec5SDimitry Andric       Entry.finalize(*Asm, List, BT, TheCU);
1842*0b57cec5SDimitry Andric   }
1843*0b57cec5SDimitry Andric 
1844*0b57cec5SDimitry Andric   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1845*0b57cec5SDimitry Andric   // DWARF-related DbgLabel.
1846*0b57cec5SDimitry Andric   for (const auto &I : DbgLabels) {
1847*0b57cec5SDimitry Andric     InlinedEntity IL = I.first;
1848*0b57cec5SDimitry Andric     const MachineInstr *MI = I.second;
1849*0b57cec5SDimitry Andric     if (MI == nullptr)
1850*0b57cec5SDimitry Andric       continue;
1851*0b57cec5SDimitry Andric 
1852*0b57cec5SDimitry Andric     LexicalScope *Scope = nullptr;
1853*0b57cec5SDimitry Andric     const DILabel *Label = cast<DILabel>(IL.first);
18548bcb0991SDimitry Andric     // The scope could have an extra lexical block file.
18558bcb0991SDimitry Andric     const DILocalScope *LocalScope =
18568bcb0991SDimitry Andric         Label->getScope()->getNonLexicalBlockFileScope();
1857*0b57cec5SDimitry Andric     // Get inlined DILocation if it is inlined label.
1858*0b57cec5SDimitry Andric     if (const DILocation *IA = IL.second)
18598bcb0991SDimitry Andric       Scope = LScopes.findInlinedScope(LocalScope, IA);
1860*0b57cec5SDimitry Andric     else
18618bcb0991SDimitry Andric       Scope = LScopes.findLexicalScope(LocalScope);
1862*0b57cec5SDimitry Andric     // If label scope is not found then skip this label.
1863*0b57cec5SDimitry Andric     if (!Scope)
1864*0b57cec5SDimitry Andric       continue;
1865*0b57cec5SDimitry Andric 
1866*0b57cec5SDimitry Andric     Processed.insert(IL);
1867*0b57cec5SDimitry Andric     /// At this point, the temporary label is created.
1868*0b57cec5SDimitry Andric     /// Save the temporary label to DbgLabel entity to get the
1869*0b57cec5SDimitry Andric     /// actually address when generating Dwarf DIE.
1870*0b57cec5SDimitry Andric     MCSymbol *Sym = getLabelBeforeInsn(MI);
1871*0b57cec5SDimitry Andric     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1872*0b57cec5SDimitry Andric   }
1873*0b57cec5SDimitry Andric 
1874*0b57cec5SDimitry Andric   // Collect info for variables/labels that were optimized out.
1875*0b57cec5SDimitry Andric   for (const DINode *DN : SP->getRetainedNodes()) {
1876*0b57cec5SDimitry Andric     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1877*0b57cec5SDimitry Andric       continue;
1878*0b57cec5SDimitry Andric     LexicalScope *Scope = nullptr;
1879*0b57cec5SDimitry Andric     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1880*0b57cec5SDimitry Andric       Scope = LScopes.findLexicalScope(DV->getScope());
1881*0b57cec5SDimitry Andric     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1882*0b57cec5SDimitry Andric       Scope = LScopes.findLexicalScope(DL->getScope());
1883*0b57cec5SDimitry Andric     }
1884*0b57cec5SDimitry Andric 
1885*0b57cec5SDimitry Andric     if (Scope)
1886*0b57cec5SDimitry Andric       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1887*0b57cec5SDimitry Andric   }
1888*0b57cec5SDimitry Andric }
1889*0b57cec5SDimitry Andric 
1890*0b57cec5SDimitry Andric // Process beginning of an instruction.
1891*0b57cec5SDimitry Andric void DwarfDebug::beginInstruction(const MachineInstr *MI) {
18925ffd83dbSDimitry Andric   const MachineFunction &MF = *MI->getMF();
18935ffd83dbSDimitry Andric   const auto *SP = MF.getFunction().getSubprogram();
18945ffd83dbSDimitry Andric   bool NoDebug =
18955ffd83dbSDimitry Andric       !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
18965ffd83dbSDimitry Andric 
18975ffd83dbSDimitry Andric   // Delay slot support check.
18985ffd83dbSDimitry Andric   auto delaySlotSupported = [](const MachineInstr &MI) {
18995ffd83dbSDimitry Andric     if (!MI.isBundledWithSucc())
19005ffd83dbSDimitry Andric       return false;
19015ffd83dbSDimitry Andric     auto Suc = std::next(MI.getIterator());
19025ffd83dbSDimitry Andric     (void)Suc;
19035ffd83dbSDimitry Andric     // Ensure that delay slot instruction is successor of the call instruction.
19045ffd83dbSDimitry Andric     // Ex. CALL_INSTRUCTION {
19055ffd83dbSDimitry Andric     //        DELAY_SLOT_INSTRUCTION }
19065ffd83dbSDimitry Andric     assert(Suc->isBundledWithPred() &&
19075ffd83dbSDimitry Andric            "Call bundle instructions are out of order");
19085ffd83dbSDimitry Andric     return true;
19095ffd83dbSDimitry Andric   };
19105ffd83dbSDimitry Andric 
19115ffd83dbSDimitry Andric   // When describing calls, we need a label for the call instruction.
19125ffd83dbSDimitry Andric   if (!NoDebug && SP->areAllCallsDescribed() &&
19135ffd83dbSDimitry Andric       MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
19145ffd83dbSDimitry Andric       (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
19155ffd83dbSDimitry Andric     const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
19165ffd83dbSDimitry Andric     bool IsTail = TII->isTailCall(*MI);
19175ffd83dbSDimitry Andric     // For tail calls, we need the address of the branch instruction for
19185ffd83dbSDimitry Andric     // DW_AT_call_pc.
19195ffd83dbSDimitry Andric     if (IsTail)
19205ffd83dbSDimitry Andric       requestLabelBeforeInsn(MI);
19215ffd83dbSDimitry Andric     // For non-tail calls, we need the return address for the call for
19225ffd83dbSDimitry Andric     // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
19235ffd83dbSDimitry Andric     // tail calls as well.
19245ffd83dbSDimitry Andric     requestLabelAfterInsn(MI);
19255ffd83dbSDimitry Andric   }
19265ffd83dbSDimitry Andric 
1927*0b57cec5SDimitry Andric   DebugHandlerBase::beginInstruction(MI);
1928e8d8bef9SDimitry Andric   if (!CurMI)
1929e8d8bef9SDimitry Andric     return;
1930*0b57cec5SDimitry Andric 
19315ffd83dbSDimitry Andric   if (NoDebug)
1932*0b57cec5SDimitry Andric     return;
1933*0b57cec5SDimitry Andric 
1934*0b57cec5SDimitry Andric   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1935*0b57cec5SDimitry Andric   // If the instruction is part of the function frame setup code, do not emit
1936*0b57cec5SDimitry Andric   // any line record, as there is no correspondence with any user code.
1937*0b57cec5SDimitry Andric   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1938*0b57cec5SDimitry Andric     return;
1939*0b57cec5SDimitry Andric   const DebugLoc &DL = MI->getDebugLoc();
1940*0b57cec5SDimitry Andric   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1941*0b57cec5SDimitry Andric   // the last line number actually emitted, to see if it was line 0.
1942*0b57cec5SDimitry Andric   unsigned LastAsmLine =
1943*0b57cec5SDimitry Andric       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1944*0b57cec5SDimitry Andric 
1945*0b57cec5SDimitry Andric   if (DL == PrevInstLoc) {
1946*0b57cec5SDimitry Andric     // If we have an ongoing unspecified location, nothing to do here.
1947*0b57cec5SDimitry Andric     if (!DL)
1948*0b57cec5SDimitry Andric       return;
1949*0b57cec5SDimitry Andric     // We have an explicit location, same as the previous location.
1950*0b57cec5SDimitry Andric     // But we might be coming back to it after a line 0 record.
1951*0b57cec5SDimitry Andric     if (LastAsmLine == 0 && DL.getLine() != 0) {
1952*0b57cec5SDimitry Andric       // Reinstate the source location but not marked as a statement.
1953*0b57cec5SDimitry Andric       const MDNode *Scope = DL.getScope();
1954*0b57cec5SDimitry Andric       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1955*0b57cec5SDimitry Andric     }
1956*0b57cec5SDimitry Andric     return;
1957*0b57cec5SDimitry Andric   }
1958*0b57cec5SDimitry Andric 
1959*0b57cec5SDimitry Andric   if (!DL) {
1960*0b57cec5SDimitry Andric     // We have an unspecified location, which might want to be line 0.
1961*0b57cec5SDimitry Andric     // If we have already emitted a line-0 record, don't repeat it.
1962*0b57cec5SDimitry Andric     if (LastAsmLine == 0)
1963*0b57cec5SDimitry Andric       return;
1964*0b57cec5SDimitry Andric     // If user said Don't Do That, don't do that.
1965*0b57cec5SDimitry Andric     if (UnknownLocations == Disable)
1966*0b57cec5SDimitry Andric       return;
1967*0b57cec5SDimitry Andric     // See if we have a reason to emit a line-0 record now.
1968*0b57cec5SDimitry Andric     // Reasons to emit a line-0 record include:
1969*0b57cec5SDimitry Andric     // - User asked for it (UnknownLocations).
1970*0b57cec5SDimitry Andric     // - Instruction has a label, so it's referenced from somewhere else,
1971*0b57cec5SDimitry Andric     //   possibly debug information; we want it to have a source location.
1972*0b57cec5SDimitry Andric     // - Instruction is at the top of a block; we don't want to inherit the
1973*0b57cec5SDimitry Andric     //   location from the physically previous (maybe unrelated) block.
1974*0b57cec5SDimitry Andric     if (UnknownLocations == Enable || PrevLabel ||
1975*0b57cec5SDimitry Andric         (PrevInstBB && PrevInstBB != MI->getParent())) {
1976*0b57cec5SDimitry Andric       // Preserve the file and column numbers, if we can, to save space in
1977*0b57cec5SDimitry Andric       // the encoded line table.
1978*0b57cec5SDimitry Andric       // Do not update PrevInstLoc, it remembers the last non-0 line.
1979*0b57cec5SDimitry Andric       const MDNode *Scope = nullptr;
1980*0b57cec5SDimitry Andric       unsigned Column = 0;
1981*0b57cec5SDimitry Andric       if (PrevInstLoc) {
1982*0b57cec5SDimitry Andric         Scope = PrevInstLoc.getScope();
1983*0b57cec5SDimitry Andric         Column = PrevInstLoc.getCol();
1984*0b57cec5SDimitry Andric       }
1985*0b57cec5SDimitry Andric       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1986*0b57cec5SDimitry Andric     }
1987*0b57cec5SDimitry Andric     return;
1988*0b57cec5SDimitry Andric   }
1989*0b57cec5SDimitry Andric 
1990*0b57cec5SDimitry Andric   // We have an explicit location, different from the previous location.
1991*0b57cec5SDimitry Andric   // Don't repeat a line-0 record, but otherwise emit the new location.
1992*0b57cec5SDimitry Andric   // (The new location might be an explicit line 0, which we do emit.)
1993*0b57cec5SDimitry Andric   if (DL.getLine() == 0 && LastAsmLine == 0)
1994*0b57cec5SDimitry Andric     return;
1995*0b57cec5SDimitry Andric   unsigned Flags = 0;
1996*0b57cec5SDimitry Andric   if (DL == PrologEndLoc) {
1997*0b57cec5SDimitry Andric     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1998*0b57cec5SDimitry Andric     PrologEndLoc = DebugLoc();
1999*0b57cec5SDimitry Andric   }
2000*0b57cec5SDimitry Andric   // If the line changed, we call that a new statement; unless we went to
2001*0b57cec5SDimitry Andric   // line 0 and came back, in which case it is not a new statement.
2002*0b57cec5SDimitry Andric   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2003*0b57cec5SDimitry Andric   if (DL.getLine() && DL.getLine() != OldLine)
2004*0b57cec5SDimitry Andric     Flags |= DWARF2_FLAG_IS_STMT;
2005*0b57cec5SDimitry Andric 
2006*0b57cec5SDimitry Andric   const MDNode *Scope = DL.getScope();
2007*0b57cec5SDimitry Andric   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2008*0b57cec5SDimitry Andric 
2009*0b57cec5SDimitry Andric   // If we're not at line 0, remember this location.
2010*0b57cec5SDimitry Andric   if (DL.getLine())
2011*0b57cec5SDimitry Andric     PrevInstLoc = DL;
2012*0b57cec5SDimitry Andric }
2013*0b57cec5SDimitry Andric 
2014*0b57cec5SDimitry Andric static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
2015*0b57cec5SDimitry Andric   // First known non-DBG_VALUE and non-frame setup location marks
2016*0b57cec5SDimitry Andric   // the beginning of the function body.
2017*0b57cec5SDimitry Andric   for (const auto &MBB : *MF)
2018*0b57cec5SDimitry Andric     for (const auto &MI : MBB)
2019*0b57cec5SDimitry Andric       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
2020*0b57cec5SDimitry Andric           MI.getDebugLoc())
2021*0b57cec5SDimitry Andric         return MI.getDebugLoc();
2022*0b57cec5SDimitry Andric   return DebugLoc();
2023*0b57cec5SDimitry Andric }
2024*0b57cec5SDimitry Andric 
2025*0b57cec5SDimitry Andric /// Register a source line with debug info. Returns the  unique label that was
2026*0b57cec5SDimitry Andric /// emitted and which provides correspondence to the source line list.
2027*0b57cec5SDimitry Andric static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2028*0b57cec5SDimitry Andric                              const MDNode *S, unsigned Flags, unsigned CUID,
2029*0b57cec5SDimitry Andric                              uint16_t DwarfVersion,
2030*0b57cec5SDimitry Andric                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2031*0b57cec5SDimitry Andric   StringRef Fn;
2032*0b57cec5SDimitry Andric   unsigned FileNo = 1;
2033*0b57cec5SDimitry Andric   unsigned Discriminator = 0;
2034*0b57cec5SDimitry Andric   if (auto *Scope = cast_or_null<DIScope>(S)) {
2035*0b57cec5SDimitry Andric     Fn = Scope->getFilename();
2036*0b57cec5SDimitry Andric     if (Line != 0 && DwarfVersion >= 4)
2037*0b57cec5SDimitry Andric       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2038*0b57cec5SDimitry Andric         Discriminator = LBF->getDiscriminator();
2039*0b57cec5SDimitry Andric 
2040*0b57cec5SDimitry Andric     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2041*0b57cec5SDimitry Andric                  .getOrCreateSourceID(Scope->getFile());
2042*0b57cec5SDimitry Andric   }
20435ffd83dbSDimitry Andric   Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2044*0b57cec5SDimitry Andric                                          Discriminator, Fn);
2045*0b57cec5SDimitry Andric }
2046*0b57cec5SDimitry Andric 
2047*0b57cec5SDimitry Andric DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
2048*0b57cec5SDimitry Andric                                              unsigned CUID) {
2049*0b57cec5SDimitry Andric   // Get beginning of function.
2050*0b57cec5SDimitry Andric   if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
2051*0b57cec5SDimitry Andric     // Ensure the compile unit is created if the function is called before
2052*0b57cec5SDimitry Andric     // beginFunction().
2053*0b57cec5SDimitry Andric     (void)getOrCreateDwarfCompileUnit(
2054*0b57cec5SDimitry Andric         MF.getFunction().getSubprogram()->getUnit());
2055*0b57cec5SDimitry Andric     // We'd like to list the prologue as "not statements" but GDB behaves
2056*0b57cec5SDimitry Andric     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2057*0b57cec5SDimitry Andric     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2058*0b57cec5SDimitry Andric     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2059*0b57cec5SDimitry Andric                        CUID, getDwarfVersion(), getUnits());
2060*0b57cec5SDimitry Andric     return PrologEndLoc;
2061*0b57cec5SDimitry Andric   }
2062*0b57cec5SDimitry Andric   return DebugLoc();
2063*0b57cec5SDimitry Andric }
2064*0b57cec5SDimitry Andric 
2065*0b57cec5SDimitry Andric // Gather pre-function debug information.  Assumes being called immediately
2066*0b57cec5SDimitry Andric // after the function entry point has been emitted.
2067*0b57cec5SDimitry Andric void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
2068*0b57cec5SDimitry Andric   CurFn = MF;
2069*0b57cec5SDimitry Andric 
2070*0b57cec5SDimitry Andric   auto *SP = MF->getFunction().getSubprogram();
2071*0b57cec5SDimitry Andric   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
2072*0b57cec5SDimitry Andric   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2073*0b57cec5SDimitry Andric     return;
2074*0b57cec5SDimitry Andric 
2075*0b57cec5SDimitry Andric   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2076*0b57cec5SDimitry Andric 
2077*0b57cec5SDimitry Andric   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2078*0b57cec5SDimitry Andric   // belongs to so that we add to the correct per-cu line table in the
2079*0b57cec5SDimitry Andric   // non-asm case.
2080*0b57cec5SDimitry Andric   if (Asm->OutStreamer->hasRawTextSupport())
2081*0b57cec5SDimitry Andric     // Use a single line table if we are generating assembly.
2082*0b57cec5SDimitry Andric     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2083*0b57cec5SDimitry Andric   else
2084*0b57cec5SDimitry Andric     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
2085*0b57cec5SDimitry Andric 
2086*0b57cec5SDimitry Andric   // Record beginning of function.
2087*0b57cec5SDimitry Andric   PrologEndLoc = emitInitialLocDirective(
2088*0b57cec5SDimitry Andric       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2089*0b57cec5SDimitry Andric }
2090*0b57cec5SDimitry Andric 
2091*0b57cec5SDimitry Andric void DwarfDebug::skippedNonDebugFunction() {
2092*0b57cec5SDimitry Andric   // If we don't have a subprogram for this function then there will be a hole
2093*0b57cec5SDimitry Andric   // in the range information. Keep note of this by setting the previously used
2094*0b57cec5SDimitry Andric   // section to nullptr.
2095*0b57cec5SDimitry Andric   PrevCU = nullptr;
2096*0b57cec5SDimitry Andric   CurFn = nullptr;
2097*0b57cec5SDimitry Andric }
2098*0b57cec5SDimitry Andric 
2099*0b57cec5SDimitry Andric // Gather and emit post-function debug information.
2100*0b57cec5SDimitry Andric void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
2101*0b57cec5SDimitry Andric   const DISubprogram *SP = MF->getFunction().getSubprogram();
2102*0b57cec5SDimitry Andric 
2103*0b57cec5SDimitry Andric   assert(CurFn == MF &&
2104*0b57cec5SDimitry Andric       "endFunction should be called with the same function as beginFunction");
2105*0b57cec5SDimitry Andric 
2106*0b57cec5SDimitry Andric   // Set DwarfDwarfCompileUnitID in MCContext to default value.
2107*0b57cec5SDimitry Andric   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2108*0b57cec5SDimitry Andric 
2109*0b57cec5SDimitry Andric   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2110*0b57cec5SDimitry Andric   assert(!FnScope || SP == FnScope->getScopeNode());
2111*0b57cec5SDimitry Andric   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
2112*0b57cec5SDimitry Andric   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2113*0b57cec5SDimitry Andric     PrevLabel = nullptr;
2114*0b57cec5SDimitry Andric     CurFn = nullptr;
2115*0b57cec5SDimitry Andric     return;
2116*0b57cec5SDimitry Andric   }
2117*0b57cec5SDimitry Andric 
2118*0b57cec5SDimitry Andric   DenseSet<InlinedEntity> Processed;
2119*0b57cec5SDimitry Andric   collectEntityInfo(TheCU, SP, Processed);
2120*0b57cec5SDimitry Andric 
2121*0b57cec5SDimitry Andric   // Add the range of this function to the list of ranges for the CU.
21225ffd83dbSDimitry Andric   // With basic block sections, add ranges for all basic block sections.
21235ffd83dbSDimitry Andric   for (const auto &R : Asm->MBBSectionRanges)
21245ffd83dbSDimitry Andric     TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2125*0b57cec5SDimitry Andric 
2126*0b57cec5SDimitry Andric   // Under -gmlt, skip building the subprogram if there are no inlined
2127*0b57cec5SDimitry Andric   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2128*0b57cec5SDimitry Andric   // is still needed as we need its source location.
2129*0b57cec5SDimitry Andric   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2130*0b57cec5SDimitry Andric       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
2131*0b57cec5SDimitry Andric       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2132*0b57cec5SDimitry Andric     assert(InfoHolder.getScopeVariables().empty());
2133*0b57cec5SDimitry Andric     PrevLabel = nullptr;
2134*0b57cec5SDimitry Andric     CurFn = nullptr;
2135*0b57cec5SDimitry Andric     return;
2136*0b57cec5SDimitry Andric   }
2137*0b57cec5SDimitry Andric 
2138*0b57cec5SDimitry Andric #ifndef NDEBUG
2139*0b57cec5SDimitry Andric   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
2140*0b57cec5SDimitry Andric #endif
2141*0b57cec5SDimitry Andric   // Construct abstract scopes.
2142*0b57cec5SDimitry Andric   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2143*0b57cec5SDimitry Andric     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2144*0b57cec5SDimitry Andric     for (const DINode *DN : SP->getRetainedNodes()) {
2145*0b57cec5SDimitry Andric       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
2146*0b57cec5SDimitry Andric         continue;
2147*0b57cec5SDimitry Andric 
2148*0b57cec5SDimitry Andric       const MDNode *Scope = nullptr;
2149*0b57cec5SDimitry Andric       if (auto *DV = dyn_cast<DILocalVariable>(DN))
2150*0b57cec5SDimitry Andric         Scope = DV->getScope();
2151*0b57cec5SDimitry Andric       else if (auto *DL = dyn_cast<DILabel>(DN))
2152*0b57cec5SDimitry Andric         Scope = DL->getScope();
2153*0b57cec5SDimitry Andric       else
2154*0b57cec5SDimitry Andric         llvm_unreachable("Unexpected DI type!");
2155*0b57cec5SDimitry Andric 
2156*0b57cec5SDimitry Andric       // Collect info for variables/labels that were optimized out.
2157*0b57cec5SDimitry Andric       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
2158*0b57cec5SDimitry Andric       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
2159*0b57cec5SDimitry Andric              && "ensureAbstractEntityIsCreated inserted abstract scopes");
2160*0b57cec5SDimitry Andric     }
2161*0b57cec5SDimitry Andric     constructAbstractSubprogramScopeDIE(TheCU, AScope);
2162*0b57cec5SDimitry Andric   }
2163*0b57cec5SDimitry Andric 
2164*0b57cec5SDimitry Andric   ProcessedSPNodes.insert(SP);
2165*0b57cec5SDimitry Andric   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2166*0b57cec5SDimitry Andric   if (auto *SkelCU = TheCU.getSkeleton())
2167*0b57cec5SDimitry Andric     if (!LScopes.getAbstractScopesList().empty() &&
2168*0b57cec5SDimitry Andric         TheCU.getCUNode()->getSplitDebugInlining())
2169*0b57cec5SDimitry Andric       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2170*0b57cec5SDimitry Andric 
2171*0b57cec5SDimitry Andric   // Construct call site entries.
2172*0b57cec5SDimitry Andric   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2173*0b57cec5SDimitry Andric 
2174*0b57cec5SDimitry Andric   // Clear debug info
2175*0b57cec5SDimitry Andric   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2176*0b57cec5SDimitry Andric   // DbgVariables except those that are also in AbstractVariables (since they
2177*0b57cec5SDimitry Andric   // can be used cross-function)
2178*0b57cec5SDimitry Andric   InfoHolder.getScopeVariables().clear();
2179*0b57cec5SDimitry Andric   InfoHolder.getScopeLabels().clear();
2180*0b57cec5SDimitry Andric   PrevLabel = nullptr;
2181*0b57cec5SDimitry Andric   CurFn = nullptr;
2182*0b57cec5SDimitry Andric }
2183*0b57cec5SDimitry Andric 
2184*0b57cec5SDimitry Andric // Register a source line with debug info. Returns the  unique label that was
2185*0b57cec5SDimitry Andric // emitted and which provides correspondence to the source line list.
2186*0b57cec5SDimitry Andric void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2187*0b57cec5SDimitry Andric                                   unsigned Flags) {
2188*0b57cec5SDimitry Andric   ::recordSourceLine(*Asm, Line, Col, S, Flags,
2189*0b57cec5SDimitry Andric                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2190*0b57cec5SDimitry Andric                      getDwarfVersion(), getUnits());
2191*0b57cec5SDimitry Andric }
2192*0b57cec5SDimitry Andric 
2193*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2194*0b57cec5SDimitry Andric // Emit Methods
2195*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2196*0b57cec5SDimitry Andric 
2197*0b57cec5SDimitry Andric // Emit the debug info section.
2198*0b57cec5SDimitry Andric void DwarfDebug::emitDebugInfo() {
2199*0b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2200*0b57cec5SDimitry Andric   Holder.emitUnits(/* UseOffsets */ false);
2201*0b57cec5SDimitry Andric }
2202*0b57cec5SDimitry Andric 
2203*0b57cec5SDimitry Andric // Emit the abbreviation section.
2204*0b57cec5SDimitry Andric void DwarfDebug::emitAbbreviations() {
2205*0b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2206*0b57cec5SDimitry Andric 
2207*0b57cec5SDimitry Andric   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2208*0b57cec5SDimitry Andric }
2209*0b57cec5SDimitry Andric 
2210*0b57cec5SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeader() {
2211*0b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2212*0b57cec5SDimitry Andric   Holder.getStringPool().emitStringOffsetsTableHeader(
2213*0b57cec5SDimitry Andric       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2214*0b57cec5SDimitry Andric       Holder.getStringOffsetsStartSym());
2215*0b57cec5SDimitry Andric }
2216*0b57cec5SDimitry Andric 
2217*0b57cec5SDimitry Andric template <typename AccelTableT>
2218*0b57cec5SDimitry Andric void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2219*0b57cec5SDimitry Andric                            StringRef TableName) {
2220*0b57cec5SDimitry Andric   Asm->OutStreamer->SwitchSection(Section);
2221*0b57cec5SDimitry Andric 
2222*0b57cec5SDimitry Andric   // Emit the full data.
2223*0b57cec5SDimitry Andric   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2224*0b57cec5SDimitry Andric }
2225*0b57cec5SDimitry Andric 
2226*0b57cec5SDimitry Andric void DwarfDebug::emitAccelDebugNames() {
2227*0b57cec5SDimitry Andric   // Don't emit anything if we have no compilation units to index.
2228*0b57cec5SDimitry Andric   if (getUnits().empty())
2229*0b57cec5SDimitry Andric     return;
2230*0b57cec5SDimitry Andric 
2231*0b57cec5SDimitry Andric   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2232*0b57cec5SDimitry Andric }
2233*0b57cec5SDimitry Andric 
2234*0b57cec5SDimitry Andric // Emit visible names into a hashed accelerator table section.
2235*0b57cec5SDimitry Andric void DwarfDebug::emitAccelNames() {
2236*0b57cec5SDimitry Andric   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2237*0b57cec5SDimitry Andric             "Names");
2238*0b57cec5SDimitry Andric }
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric // Emit objective C classes and categories into a hashed accelerator table
2241*0b57cec5SDimitry Andric // section.
2242*0b57cec5SDimitry Andric void DwarfDebug::emitAccelObjC() {
2243*0b57cec5SDimitry Andric   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2244*0b57cec5SDimitry Andric             "ObjC");
2245*0b57cec5SDimitry Andric }
2246*0b57cec5SDimitry Andric 
2247*0b57cec5SDimitry Andric // Emit namespace dies into a hashed accelerator table.
2248*0b57cec5SDimitry Andric void DwarfDebug::emitAccelNamespaces() {
2249*0b57cec5SDimitry Andric   emitAccel(AccelNamespace,
2250*0b57cec5SDimitry Andric             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2251*0b57cec5SDimitry Andric             "namespac");
2252*0b57cec5SDimitry Andric }
2253*0b57cec5SDimitry Andric 
2254*0b57cec5SDimitry Andric // Emit type dies into a hashed accelerator table.
2255*0b57cec5SDimitry Andric void DwarfDebug::emitAccelTypes() {
2256*0b57cec5SDimitry Andric   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2257*0b57cec5SDimitry Andric             "types");
2258*0b57cec5SDimitry Andric }
2259*0b57cec5SDimitry Andric 
2260*0b57cec5SDimitry Andric // Public name handling.
2261*0b57cec5SDimitry Andric // The format for the various pubnames:
2262*0b57cec5SDimitry Andric //
2263*0b57cec5SDimitry Andric // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2264*0b57cec5SDimitry Andric // for the DIE that is named.
2265*0b57cec5SDimitry Andric //
2266*0b57cec5SDimitry Andric // gnu pubnames - offset/index value/name tuples where the offset is the offset
2267*0b57cec5SDimitry Andric // into the CU and the index value is computed according to the type of value
2268*0b57cec5SDimitry Andric // for the DIE that is named.
2269*0b57cec5SDimitry Andric //
2270*0b57cec5SDimitry Andric // For type units the offset is the offset of the skeleton DIE. For split dwarf
2271*0b57cec5SDimitry Andric // it's the offset within the debug_info/debug_types dwo section, however, the
2272*0b57cec5SDimitry Andric // reference in the pubname header doesn't change.
2273*0b57cec5SDimitry Andric 
2274*0b57cec5SDimitry Andric /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2275*0b57cec5SDimitry Andric static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2276*0b57cec5SDimitry Andric                                                         const DIE *Die) {
2277*0b57cec5SDimitry Andric   // Entities that ended up only in a Type Unit reference the CU instead (since
2278*0b57cec5SDimitry Andric   // the pub entry has offsets within the CU there's no real offset that can be
2279*0b57cec5SDimitry Andric   // provided anyway). As it happens all such entities (namespaces and types,
2280*0b57cec5SDimitry Andric   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2281*0b57cec5SDimitry Andric   // not to be true it would be necessary to persist this information from the
2282*0b57cec5SDimitry Andric   // point at which the entry is added to the index data structure - since by
2283*0b57cec5SDimitry Andric   // the time the index is built from that, the original type/namespace DIE in a
2284*0b57cec5SDimitry Andric   // type unit has already been destroyed so it can't be queried for properties
2285*0b57cec5SDimitry Andric   // like tag, etc.
2286*0b57cec5SDimitry Andric   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2287*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2288*0b57cec5SDimitry Andric                                           dwarf::GIEL_EXTERNAL);
2289*0b57cec5SDimitry Andric   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2290*0b57cec5SDimitry Andric 
2291*0b57cec5SDimitry Andric   // We could have a specification DIE that has our most of our knowledge,
2292*0b57cec5SDimitry Andric   // look for that now.
2293*0b57cec5SDimitry Andric   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2294*0b57cec5SDimitry Andric     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2295*0b57cec5SDimitry Andric     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2296*0b57cec5SDimitry Andric       Linkage = dwarf::GIEL_EXTERNAL;
2297*0b57cec5SDimitry Andric   } else if (Die->findAttribute(dwarf::DW_AT_external))
2298*0b57cec5SDimitry Andric     Linkage = dwarf::GIEL_EXTERNAL;
2299*0b57cec5SDimitry Andric 
2300*0b57cec5SDimitry Andric   switch (Die->getTag()) {
2301*0b57cec5SDimitry Andric   case dwarf::DW_TAG_class_type:
2302*0b57cec5SDimitry Andric   case dwarf::DW_TAG_structure_type:
2303*0b57cec5SDimitry Andric   case dwarf::DW_TAG_union_type:
2304*0b57cec5SDimitry Andric   case dwarf::DW_TAG_enumeration_type:
2305*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(
23068bcb0991SDimitry Andric         dwarf::GIEK_TYPE,
23078bcb0991SDimitry Andric         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
23088bcb0991SDimitry Andric             ? dwarf::GIEL_EXTERNAL
23098bcb0991SDimitry Andric             : dwarf::GIEL_STATIC);
2310*0b57cec5SDimitry Andric   case dwarf::DW_TAG_typedef:
2311*0b57cec5SDimitry Andric   case dwarf::DW_TAG_base_type:
2312*0b57cec5SDimitry Andric   case dwarf::DW_TAG_subrange_type:
2313*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2314*0b57cec5SDimitry Andric   case dwarf::DW_TAG_namespace:
2315*0b57cec5SDimitry Andric     return dwarf::GIEK_TYPE;
2316*0b57cec5SDimitry Andric   case dwarf::DW_TAG_subprogram:
2317*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2318*0b57cec5SDimitry Andric   case dwarf::DW_TAG_variable:
2319*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2320*0b57cec5SDimitry Andric   case dwarf::DW_TAG_enumerator:
2321*0b57cec5SDimitry Andric     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2322*0b57cec5SDimitry Andric                                           dwarf::GIEL_STATIC);
2323*0b57cec5SDimitry Andric   default:
2324*0b57cec5SDimitry Andric     return dwarf::GIEK_NONE;
2325*0b57cec5SDimitry Andric   }
2326*0b57cec5SDimitry Andric }
2327*0b57cec5SDimitry Andric 
2328*0b57cec5SDimitry Andric /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2329*0b57cec5SDimitry Andric /// pubtypes sections.
2330*0b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSections() {
2331*0b57cec5SDimitry Andric   for (const auto &NU : CUMap) {
2332*0b57cec5SDimitry Andric     DwarfCompileUnit *TheU = NU.second;
2333*0b57cec5SDimitry Andric     if (!TheU->hasDwarfPubSections())
2334*0b57cec5SDimitry Andric       continue;
2335*0b57cec5SDimitry Andric 
2336*0b57cec5SDimitry Andric     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2337*0b57cec5SDimitry Andric                     DICompileUnit::DebugNameTableKind::GNU;
2338*0b57cec5SDimitry Andric 
2339*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(
2340*0b57cec5SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2341*0b57cec5SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2342*0b57cec5SDimitry Andric     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2343*0b57cec5SDimitry Andric 
2344*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(
2345*0b57cec5SDimitry Andric         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2346*0b57cec5SDimitry Andric                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2347*0b57cec5SDimitry Andric     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2348*0b57cec5SDimitry Andric   }
2349*0b57cec5SDimitry Andric }
2350*0b57cec5SDimitry Andric 
2351*0b57cec5SDimitry Andric void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2352*0b57cec5SDimitry Andric   if (useSectionsAsReferences())
23535ffd83dbSDimitry Andric     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2354*0b57cec5SDimitry Andric                          CU.getDebugSectionOffset());
2355*0b57cec5SDimitry Andric   else
2356*0b57cec5SDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2357*0b57cec5SDimitry Andric }
2358*0b57cec5SDimitry Andric 
2359*0b57cec5SDimitry Andric void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2360*0b57cec5SDimitry Andric                                      DwarfCompileUnit *TheU,
2361*0b57cec5SDimitry Andric                                      const StringMap<const DIE *> &Globals) {
2362*0b57cec5SDimitry Andric   if (auto *Skeleton = TheU->getSkeleton())
2363*0b57cec5SDimitry Andric     TheU = Skeleton;
2364*0b57cec5SDimitry Andric 
2365*0b57cec5SDimitry Andric   // Emit the header.
2366*0b57cec5SDimitry Andric   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2367*0b57cec5SDimitry Andric   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2368e8d8bef9SDimitry Andric   Asm->emitDwarfUnitLength(EndLabel, BeginLabel,
2369e8d8bef9SDimitry Andric                            "Length of Public " + Name + " Info");
2370*0b57cec5SDimitry Andric 
23715ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(BeginLabel);
2372*0b57cec5SDimitry Andric 
2373*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("DWARF Version");
2374*0b57cec5SDimitry Andric   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2375*0b57cec5SDimitry Andric 
2376*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2377*0b57cec5SDimitry Andric   emitSectionReference(*TheU);
2378*0b57cec5SDimitry Andric 
2379*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Compilation Unit Length");
2380e8d8bef9SDimitry Andric   Asm->emitDwarfLengthOrOffset(TheU->getLength());
2381*0b57cec5SDimitry Andric 
2382*0b57cec5SDimitry Andric   // Emit the pubnames for this compilation unit.
2383*0b57cec5SDimitry Andric   for (const auto &GI : Globals) {
2384*0b57cec5SDimitry Andric     const char *Name = GI.getKeyData();
2385*0b57cec5SDimitry Andric     const DIE *Entity = GI.second;
2386*0b57cec5SDimitry Andric 
2387*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("DIE offset");
2388e8d8bef9SDimitry Andric     Asm->emitDwarfLengthOrOffset(Entity->getOffset());
2389*0b57cec5SDimitry Andric 
2390*0b57cec5SDimitry Andric     if (GnuStyle) {
2391*0b57cec5SDimitry Andric       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2392*0b57cec5SDimitry Andric       Asm->OutStreamer->AddComment(
2393*0b57cec5SDimitry Andric           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2394*0b57cec5SDimitry Andric           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2395*0b57cec5SDimitry Andric       Asm->emitInt8(Desc.toBits());
2396*0b57cec5SDimitry Andric     }
2397*0b57cec5SDimitry Andric 
2398*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("External Name");
23995ffd83dbSDimitry Andric     Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
2400*0b57cec5SDimitry Andric   }
2401*0b57cec5SDimitry Andric 
2402*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("End Mark");
2403e8d8bef9SDimitry Andric   Asm->emitDwarfLengthOrOffset(0);
24045ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(EndLabel);
2405*0b57cec5SDimitry Andric }
2406*0b57cec5SDimitry Andric 
2407*0b57cec5SDimitry Andric /// Emit null-terminated strings into a debug str section.
2408*0b57cec5SDimitry Andric void DwarfDebug::emitDebugStr() {
2409*0b57cec5SDimitry Andric   MCSection *StringOffsetsSection = nullptr;
2410*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable()) {
2411*0b57cec5SDimitry Andric     emitStringOffsetsTableHeader();
2412*0b57cec5SDimitry Andric     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2413*0b57cec5SDimitry Andric   }
2414*0b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2415*0b57cec5SDimitry Andric   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2416*0b57cec5SDimitry Andric                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
2417*0b57cec5SDimitry Andric }
2418*0b57cec5SDimitry Andric 
2419*0b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2420*0b57cec5SDimitry Andric                                    const DebugLocStream::Entry &Entry,
2421*0b57cec5SDimitry Andric                                    const DwarfCompileUnit *CU) {
2422*0b57cec5SDimitry Andric   auto &&Comments = DebugLocs.getComments(Entry);
2423*0b57cec5SDimitry Andric   auto Comment = Comments.begin();
2424*0b57cec5SDimitry Andric   auto End = Comments.end();
2425*0b57cec5SDimitry Andric 
2426*0b57cec5SDimitry Andric   // The expressions are inserted into a byte stream rather early (see
2427*0b57cec5SDimitry Andric   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2428*0b57cec5SDimitry Andric   // need to reference a base_type DIE the offset of that DIE is not yet known.
2429*0b57cec5SDimitry Andric   // To deal with this we instead insert a placeholder early and then extract
2430*0b57cec5SDimitry Andric   // it here and replace it with the real reference.
2431*0b57cec5SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2432*0b57cec5SDimitry Andric   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2433*0b57cec5SDimitry Andric                                     DebugLocs.getBytes(Entry).size()),
2434*0b57cec5SDimitry Andric                           Asm->getDataLayout().isLittleEndian(), PtrSize);
24355ffd83dbSDimitry Andric   DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
2436*0b57cec5SDimitry Andric 
2437*0b57cec5SDimitry Andric   using Encoding = DWARFExpression::Operation::Encoding;
24388bcb0991SDimitry Andric   uint64_t Offset = 0;
2439*0b57cec5SDimitry Andric   for (auto &Op : Expr) {
2440*0b57cec5SDimitry Andric     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2441*0b57cec5SDimitry Andric            "3 operand ops not yet supported");
2442e8d8bef9SDimitry Andric     Streamer.emitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2443*0b57cec5SDimitry Andric     Offset++;
2444*0b57cec5SDimitry Andric     for (unsigned I = 0; I < 2; ++I) {
2445*0b57cec5SDimitry Andric       if (Op.getDescription().Op[I] == Encoding::SizeNA)
2446*0b57cec5SDimitry Andric         continue;
2447*0b57cec5SDimitry Andric       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
24485ffd83dbSDimitry Andric         uint64_t Offset =
24495ffd83dbSDimitry Andric             CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2450*0b57cec5SDimitry Andric         assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
24515ffd83dbSDimitry Andric         Streamer.emitULEB128(Offset, "", ULEB128PadSize);
2452*0b57cec5SDimitry Andric         // Make sure comments stay aligned.
2453*0b57cec5SDimitry Andric         for (unsigned J = 0; J < ULEB128PadSize; ++J)
2454*0b57cec5SDimitry Andric           if (Comment != End)
2455*0b57cec5SDimitry Andric             Comment++;
2456*0b57cec5SDimitry Andric       } else {
24578bcb0991SDimitry Andric         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2458e8d8bef9SDimitry Andric           Streamer.emitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2459*0b57cec5SDimitry Andric       }
2460*0b57cec5SDimitry Andric       Offset = Op.getOperandEndOffset(I);
2461*0b57cec5SDimitry Andric     }
2462*0b57cec5SDimitry Andric     assert(Offset == Op.getEndOffset());
2463*0b57cec5SDimitry Andric   }
2464*0b57cec5SDimitry Andric }
2465*0b57cec5SDimitry Andric 
2466*0b57cec5SDimitry Andric void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2467*0b57cec5SDimitry Andric                                    const DbgValueLoc &Value,
2468*0b57cec5SDimitry Andric                                    DwarfExpression &DwarfExpr) {
2469*0b57cec5SDimitry Andric   auto *DIExpr = Value.getExpression();
2470*0b57cec5SDimitry Andric   DIExpressionCursor ExprCursor(DIExpr);
2471*0b57cec5SDimitry Andric   DwarfExpr.addFragmentOffset(DIExpr);
2472*0b57cec5SDimitry Andric   // Regular entry.
2473*0b57cec5SDimitry Andric   if (Value.isInt()) {
2474*0b57cec5SDimitry Andric     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2475*0b57cec5SDimitry Andric                BT->getEncoding() == dwarf::DW_ATE_signed_char))
2476*0b57cec5SDimitry Andric       DwarfExpr.addSignedConstant(Value.getInt());
2477*0b57cec5SDimitry Andric     else
2478*0b57cec5SDimitry Andric       DwarfExpr.addUnsignedConstant(Value.getInt());
2479*0b57cec5SDimitry Andric   } else if (Value.isLocation()) {
2480*0b57cec5SDimitry Andric     MachineLocation Location = Value.getLoc();
24815ffd83dbSDimitry Andric     DwarfExpr.setLocation(Location, DIExpr);
2482*0b57cec5SDimitry Andric     DIExpressionCursor Cursor(DIExpr);
2483*0b57cec5SDimitry Andric 
24845ffd83dbSDimitry Andric     if (DIExpr->isEntryValue())
24858bcb0991SDimitry Andric       DwarfExpr.beginEntryValueExpression(Cursor);
2486*0b57cec5SDimitry Andric 
2487*0b57cec5SDimitry Andric     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2488*0b57cec5SDimitry Andric     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2489*0b57cec5SDimitry Andric       return;
2490*0b57cec5SDimitry Andric     return DwarfExpr.addExpression(std::move(Cursor));
2491480093f4SDimitry Andric   } else if (Value.isTargetIndexLocation()) {
2492480093f4SDimitry Andric     TargetIndexLocation Loc = Value.getTargetIndexLocation();
2493480093f4SDimitry Andric     // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
2494480093f4SDimitry Andric     // encoding is supported.
2495e8d8bef9SDimitry Andric     assert(AP.TM.getTargetTriple().isWasm());
24965ffd83dbSDimitry Andric     DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
2497e8d8bef9SDimitry Andric       DwarfExpr.addExpression(std::move(ExprCursor));
2498e8d8bef9SDimitry Andric       return;
2499*0b57cec5SDimitry Andric   } else if (Value.isConstantFP()) {
2500e8d8bef9SDimitry Andric     if (AP.getDwarfVersion() >= 4 && !AP.getDwarfDebug()->tuneForSCE() &&
2501e8d8bef9SDimitry Andric         !ExprCursor) {
2502e8d8bef9SDimitry Andric       DwarfExpr.addConstantFP(Value.getConstantFP()->getValueAPF(), AP);
2503e8d8bef9SDimitry Andric       return;
2504e8d8bef9SDimitry Andric     }
2505e8d8bef9SDimitry Andric     if (Value.getConstantFP()->getValueAPF().bitcastToAPInt().getBitWidth() <=
2506e8d8bef9SDimitry Andric         64 /*bits*/)
2507e8d8bef9SDimitry Andric       DwarfExpr.addUnsignedConstant(
2508e8d8bef9SDimitry Andric           Value.getConstantFP()->getValueAPF().bitcastToAPInt());
2509e8d8bef9SDimitry Andric     else
2510e8d8bef9SDimitry Andric       LLVM_DEBUG(
2511e8d8bef9SDimitry Andric           dbgs()
2512e8d8bef9SDimitry Andric           << "Skipped DwarfExpression creation for ConstantFP of size"
2513e8d8bef9SDimitry Andric           << Value.getConstantFP()->getValueAPF().bitcastToAPInt().getBitWidth()
2514e8d8bef9SDimitry Andric           << " bits\n");
2515*0b57cec5SDimitry Andric   }
2516*0b57cec5SDimitry Andric   DwarfExpr.addExpression(std::move(ExprCursor));
2517*0b57cec5SDimitry Andric }
2518*0b57cec5SDimitry Andric 
2519*0b57cec5SDimitry Andric void DebugLocEntry::finalize(const AsmPrinter &AP,
2520*0b57cec5SDimitry Andric                              DebugLocStream::ListBuilder &List,
2521*0b57cec5SDimitry Andric                              const DIBasicType *BT,
2522*0b57cec5SDimitry Andric                              DwarfCompileUnit &TheCU) {
2523*0b57cec5SDimitry Andric   assert(!Values.empty() &&
2524*0b57cec5SDimitry Andric          "location list entries without values are redundant");
2525*0b57cec5SDimitry Andric   assert(Begin != End && "unexpected location list entry with empty range");
2526*0b57cec5SDimitry Andric   DebugLocStream::EntryBuilder Entry(List, Begin, End);
2527*0b57cec5SDimitry Andric   BufferByteStreamer Streamer = Entry.getStreamer();
2528*0b57cec5SDimitry Andric   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2529*0b57cec5SDimitry Andric   const DbgValueLoc &Value = Values[0];
2530*0b57cec5SDimitry Andric   if (Value.isFragment()) {
2531*0b57cec5SDimitry Andric     // Emit all fragments that belong to the same variable and range.
2532*0b57cec5SDimitry Andric     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2533*0b57cec5SDimitry Andric           return P.isFragment();
2534*0b57cec5SDimitry Andric         }) && "all values are expected to be fragments");
25355ffd83dbSDimitry Andric     assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
2536*0b57cec5SDimitry Andric 
2537e8d8bef9SDimitry Andric     for (const auto &Fragment : Values)
2538*0b57cec5SDimitry Andric       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2539*0b57cec5SDimitry Andric 
2540*0b57cec5SDimitry Andric   } else {
2541*0b57cec5SDimitry Andric     assert(Values.size() == 1 && "only fragments may have >1 value");
2542*0b57cec5SDimitry Andric     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2543*0b57cec5SDimitry Andric   }
2544*0b57cec5SDimitry Andric   DwarfExpr.finalize();
2545480093f4SDimitry Andric   if (DwarfExpr.TagOffset)
2546480093f4SDimitry Andric     List.setTagOffset(*DwarfExpr.TagOffset);
2547*0b57cec5SDimitry Andric }
2548*0b57cec5SDimitry Andric 
2549*0b57cec5SDimitry Andric void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2550*0b57cec5SDimitry Andric                                            const DwarfCompileUnit *CU) {
2551*0b57cec5SDimitry Andric   // Emit the size.
2552*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Loc expr size");
2553*0b57cec5SDimitry Andric   if (getDwarfVersion() >= 5)
25545ffd83dbSDimitry Andric     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2555*0b57cec5SDimitry Andric   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2556*0b57cec5SDimitry Andric     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2557*0b57cec5SDimitry Andric   else {
2558*0b57cec5SDimitry Andric     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2559*0b57cec5SDimitry Andric     // can do.
2560*0b57cec5SDimitry Andric     Asm->emitInt16(0);
2561*0b57cec5SDimitry Andric     return;
2562*0b57cec5SDimitry Andric   }
2563*0b57cec5SDimitry Andric   // Emit the entry.
2564*0b57cec5SDimitry Andric   APByteStreamer Streamer(*Asm);
2565*0b57cec5SDimitry Andric   emitDebugLocEntry(Streamer, Entry, CU);
2566*0b57cec5SDimitry Andric }
2567*0b57cec5SDimitry Andric 
2568*0b57cec5SDimitry Andric // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2569*0b57cec5SDimitry Andric // that designates the end of the table for the caller to emit when the table is
2570*0b57cec5SDimitry Andric // complete.
2571*0b57cec5SDimitry Andric static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2572*0b57cec5SDimitry Andric                                          const DwarfFile &Holder) {
25735ffd83dbSDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2574*0b57cec5SDimitry Andric 
2575*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
2576*0b57cec5SDimitry Andric   Asm->emitInt32(Holder.getRangeLists().size());
25775ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2578*0b57cec5SDimitry Andric 
2579*0b57cec5SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
2580e8d8bef9SDimitry Andric     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(),
2581e8d8bef9SDimitry Andric                              Asm->getDwarfOffsetByteSize());
2582*0b57cec5SDimitry Andric 
2583*0b57cec5SDimitry Andric   return TableEnd;
2584*0b57cec5SDimitry Andric }
2585*0b57cec5SDimitry Andric 
2586*0b57cec5SDimitry Andric // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2587*0b57cec5SDimitry Andric // designates the end of the table for the caller to emit when the table is
2588*0b57cec5SDimitry Andric // complete.
2589*0b57cec5SDimitry Andric static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
25908bcb0991SDimitry Andric                                          const DwarfDebug &DD) {
25915ffd83dbSDimitry Andric   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
25928bcb0991SDimitry Andric 
25938bcb0991SDimitry Andric   const auto &DebugLocs = DD.getDebugLocs();
2594*0b57cec5SDimitry Andric 
2595*0b57cec5SDimitry Andric   Asm->OutStreamer->AddComment("Offset entry count");
2596480093f4SDimitry Andric   Asm->emitInt32(DebugLocs.getLists().size());
25975ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2598*0b57cec5SDimitry Andric 
2599480093f4SDimitry Andric   for (const auto &List : DebugLocs.getLists())
2600e8d8bef9SDimitry Andric     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(),
2601e8d8bef9SDimitry Andric                              Asm->getDwarfOffsetByteSize());
2602480093f4SDimitry Andric 
2603*0b57cec5SDimitry Andric   return TableEnd;
2604*0b57cec5SDimitry Andric }
2605*0b57cec5SDimitry Andric 
26068bcb0991SDimitry Andric template <typename Ranges, typename PayloadEmitter>
26078bcb0991SDimitry Andric static void emitRangeList(
26088bcb0991SDimitry Andric     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
26098bcb0991SDimitry Andric     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
26108bcb0991SDimitry Andric     unsigned StartxLength, unsigned EndOfList,
26118bcb0991SDimitry Andric     StringRef (*StringifyEnum)(unsigned),
26128bcb0991SDimitry Andric     bool ShouldUseBaseAddress,
26138bcb0991SDimitry Andric     PayloadEmitter EmitPayload) {
26148bcb0991SDimitry Andric 
26158bcb0991SDimitry Andric   auto Size = Asm->MAI->getCodePointerSize();
26168bcb0991SDimitry Andric   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
26178bcb0991SDimitry Andric 
26188bcb0991SDimitry Andric   // Emit our symbol so we can find the beginning of the range.
26195ffd83dbSDimitry Andric   Asm->OutStreamer->emitLabel(Sym);
26208bcb0991SDimitry Andric 
26218bcb0991SDimitry Andric   // Gather all the ranges that apply to the same section so they can share
26228bcb0991SDimitry Andric   // a base address entry.
26238bcb0991SDimitry Andric   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
26248bcb0991SDimitry Andric 
26258bcb0991SDimitry Andric   for (const auto &Range : R)
26268bcb0991SDimitry Andric     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
26278bcb0991SDimitry Andric 
26288bcb0991SDimitry Andric   const MCSymbol *CUBase = CU.getBaseAddress();
26298bcb0991SDimitry Andric   bool BaseIsSet = false;
26308bcb0991SDimitry Andric   for (const auto &P : SectionRanges) {
26318bcb0991SDimitry Andric     auto *Base = CUBase;
26328bcb0991SDimitry Andric     if (!Base && ShouldUseBaseAddress) {
26338bcb0991SDimitry Andric       const MCSymbol *Begin = P.second.front()->Begin;
26348bcb0991SDimitry Andric       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
26358bcb0991SDimitry Andric       if (!UseDwarf5) {
26368bcb0991SDimitry Andric         Base = NewBase;
26378bcb0991SDimitry Andric         BaseIsSet = true;
26385ffd83dbSDimitry Andric         Asm->OutStreamer->emitIntValue(-1, Size);
26398bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  base address");
26405ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(Base, Size);
26418bcb0991SDimitry Andric       } else if (NewBase != Begin || P.second.size() > 1) {
26428bcb0991SDimitry Andric         // Only use a base address if
26438bcb0991SDimitry Andric         //  * the existing pool address doesn't match (NewBase != Begin)
26448bcb0991SDimitry Andric         //  * or, there's more than one entry to share the base address
26458bcb0991SDimitry Andric         Base = NewBase;
26468bcb0991SDimitry Andric         BaseIsSet = true;
26478bcb0991SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
26488bcb0991SDimitry Andric         Asm->emitInt8(BaseAddressx);
26498bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  base address index");
26505ffd83dbSDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
26518bcb0991SDimitry Andric       }
26528bcb0991SDimitry Andric     } else if (BaseIsSet && !UseDwarf5) {
26538bcb0991SDimitry Andric       BaseIsSet = false;
26548bcb0991SDimitry Andric       assert(!Base);
26555ffd83dbSDimitry Andric       Asm->OutStreamer->emitIntValue(-1, Size);
26565ffd83dbSDimitry Andric       Asm->OutStreamer->emitIntValue(0, Size);
26578bcb0991SDimitry Andric     }
26588bcb0991SDimitry Andric 
26598bcb0991SDimitry Andric     for (const auto *RS : P.second) {
26608bcb0991SDimitry Andric       const MCSymbol *Begin = RS->Begin;
26618bcb0991SDimitry Andric       const MCSymbol *End = RS->End;
26628bcb0991SDimitry Andric       assert(Begin && "Range without a begin symbol?");
26638bcb0991SDimitry Andric       assert(End && "Range without an end symbol?");
26648bcb0991SDimitry Andric       if (Base) {
26658bcb0991SDimitry Andric         if (UseDwarf5) {
26668bcb0991SDimitry Andric           // Emit offset_pair when we have a base.
26678bcb0991SDimitry Andric           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
26688bcb0991SDimitry Andric           Asm->emitInt8(OffsetPair);
26698bcb0991SDimitry Andric           Asm->OutStreamer->AddComment("  starting offset");
26705ffd83dbSDimitry Andric           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
26718bcb0991SDimitry Andric           Asm->OutStreamer->AddComment("  ending offset");
26725ffd83dbSDimitry Andric           Asm->emitLabelDifferenceAsULEB128(End, Base);
26738bcb0991SDimitry Andric         } else {
26745ffd83dbSDimitry Andric           Asm->emitLabelDifference(Begin, Base, Size);
26755ffd83dbSDimitry Andric           Asm->emitLabelDifference(End, Base, Size);
26768bcb0991SDimitry Andric         }
26778bcb0991SDimitry Andric       } else if (UseDwarf5) {
26788bcb0991SDimitry Andric         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
26798bcb0991SDimitry Andric         Asm->emitInt8(StartxLength);
26808bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  start index");
26815ffd83dbSDimitry Andric         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
26828bcb0991SDimitry Andric         Asm->OutStreamer->AddComment("  length");
26835ffd83dbSDimitry Andric         Asm->emitLabelDifferenceAsULEB128(End, Begin);
26848bcb0991SDimitry Andric       } else {
26855ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(Begin, Size);
26865ffd83dbSDimitry Andric         Asm->OutStreamer->emitSymbolValue(End, Size);
26878bcb0991SDimitry Andric       }
26888bcb0991SDimitry Andric       EmitPayload(*RS);
26898bcb0991SDimitry Andric     }
26908bcb0991SDimitry Andric   }
26918bcb0991SDimitry Andric 
26928bcb0991SDimitry Andric   if (UseDwarf5) {
26938bcb0991SDimitry Andric     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
26948bcb0991SDimitry Andric     Asm->emitInt8(EndOfList);
26958bcb0991SDimitry Andric   } else {
26968bcb0991SDimitry Andric     // Terminate the list with two 0 values.
26975ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
26985ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, Size);
26998bcb0991SDimitry Andric   }
27008bcb0991SDimitry Andric }
27018bcb0991SDimitry Andric 
2702480093f4SDimitry Andric // Handles emission of both debug_loclist / debug_loclist.dwo
27038bcb0991SDimitry Andric static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2704480093f4SDimitry Andric   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2705480093f4SDimitry Andric                 *List.CU, dwarf::DW_LLE_base_addressx,
2706480093f4SDimitry Andric                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2707480093f4SDimitry Andric                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
27088bcb0991SDimitry Andric                 /* ShouldUseBaseAddress */ true,
27098bcb0991SDimitry Andric                 [&](const DebugLocStream::Entry &E) {
27108bcb0991SDimitry Andric                   DD.emitDebugLocEntryLocation(E, List.CU);
27118bcb0991SDimitry Andric                 });
27128bcb0991SDimitry Andric }
27138bcb0991SDimitry Andric 
2714480093f4SDimitry Andric void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2715*0b57cec5SDimitry Andric   if (DebugLocs.getLists().empty())
2716*0b57cec5SDimitry Andric     return;
2717*0b57cec5SDimitry Andric 
2718480093f4SDimitry Andric   Asm->OutStreamer->SwitchSection(Sec);
2719480093f4SDimitry Andric 
2720*0b57cec5SDimitry Andric   MCSymbol *TableEnd = nullptr;
2721480093f4SDimitry Andric   if (getDwarfVersion() >= 5)
27228bcb0991SDimitry Andric     TableEnd = emitLoclistsTableHeader(Asm, *this);
2723*0b57cec5SDimitry Andric 
27248bcb0991SDimitry Andric   for (const auto &List : DebugLocs.getLists())
27258bcb0991SDimitry Andric     emitLocList(*this, Asm, List);
2726*0b57cec5SDimitry Andric 
2727*0b57cec5SDimitry Andric   if (TableEnd)
27285ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
2729*0b57cec5SDimitry Andric }
2730*0b57cec5SDimitry Andric 
2731480093f4SDimitry Andric // Emit locations into the .debug_loc/.debug_loclists section.
2732480093f4SDimitry Andric void DwarfDebug::emitDebugLoc() {
2733480093f4SDimitry Andric   emitDebugLocImpl(
2734480093f4SDimitry Andric       getDwarfVersion() >= 5
2735480093f4SDimitry Andric           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2736480093f4SDimitry Andric           : Asm->getObjFileLowering().getDwarfLocSection());
2737480093f4SDimitry Andric }
2738480093f4SDimitry Andric 
2739480093f4SDimitry Andric // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2740*0b57cec5SDimitry Andric void DwarfDebug::emitDebugLocDWO() {
2741480093f4SDimitry Andric   if (getDwarfVersion() >= 5) {
2742480093f4SDimitry Andric     emitDebugLocImpl(
2743480093f4SDimitry Andric         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2744480093f4SDimitry Andric 
2745480093f4SDimitry Andric     return;
2746480093f4SDimitry Andric   }
2747480093f4SDimitry Andric 
2748*0b57cec5SDimitry Andric   for (const auto &List : DebugLocs.getLists()) {
2749*0b57cec5SDimitry Andric     Asm->OutStreamer->SwitchSection(
2750*0b57cec5SDimitry Andric         Asm->getObjFileLowering().getDwarfLocDWOSection());
27515ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(List.Label);
2752480093f4SDimitry Andric 
2753*0b57cec5SDimitry Andric     for (const auto &Entry : DebugLocs.getEntries(List)) {
2754*0b57cec5SDimitry Andric       // GDB only supports startx_length in pre-standard split-DWARF.
2755*0b57cec5SDimitry Andric       // (in v5 standard loclists, it currently* /only/ supports base_address +
2756*0b57cec5SDimitry Andric       // offset_pair, so the implementations can't really share much since they
2757*0b57cec5SDimitry Andric       // need to use different representations)
2758*0b57cec5SDimitry Andric       // * as of October 2018, at least
27595ffd83dbSDimitry Andric       //
27605ffd83dbSDimitry Andric       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
27615ffd83dbSDimitry Andric       // addresses in the address pool to minimize object size/relocations.
2762*0b57cec5SDimitry Andric       Asm->emitInt8(dwarf::DW_LLE_startx_length);
27638bcb0991SDimitry Andric       unsigned idx = AddrPool.getIndex(Entry.Begin);
27645ffd83dbSDimitry Andric       Asm->emitULEB128(idx);
2765480093f4SDimitry Andric       // Also the pre-standard encoding is slightly different, emitting this as
2766480093f4SDimitry Andric       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
27675ffd83dbSDimitry Andric       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2768*0b57cec5SDimitry Andric       emitDebugLocEntryLocation(Entry, List.CU);
2769*0b57cec5SDimitry Andric     }
2770*0b57cec5SDimitry Andric     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2771*0b57cec5SDimitry Andric   }
2772*0b57cec5SDimitry Andric }
2773*0b57cec5SDimitry Andric 
2774*0b57cec5SDimitry Andric struct ArangeSpan {
2775*0b57cec5SDimitry Andric   const MCSymbol *Start, *End;
2776*0b57cec5SDimitry Andric };
2777*0b57cec5SDimitry Andric 
2778*0b57cec5SDimitry Andric // Emit a debug aranges section, containing a CU lookup for any
2779*0b57cec5SDimitry Andric // address we can tie back to a CU.
2780*0b57cec5SDimitry Andric void DwarfDebug::emitDebugARanges() {
2781*0b57cec5SDimitry Andric   // Provides a unique id per text section.
2782*0b57cec5SDimitry Andric   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2783*0b57cec5SDimitry Andric 
2784*0b57cec5SDimitry Andric   // Filter labels by section.
2785*0b57cec5SDimitry Andric   for (const SymbolCU &SCU : ArangeLabels) {
2786*0b57cec5SDimitry Andric     if (SCU.Sym->isInSection()) {
2787*0b57cec5SDimitry Andric       // Make a note of this symbol and it's section.
2788*0b57cec5SDimitry Andric       MCSection *Section = &SCU.Sym->getSection();
2789*0b57cec5SDimitry Andric       if (!Section->getKind().isMetadata())
2790*0b57cec5SDimitry Andric         SectionMap[Section].push_back(SCU);
2791*0b57cec5SDimitry Andric     } else {
2792*0b57cec5SDimitry Andric       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2793*0b57cec5SDimitry Andric       // appear in the output. This sucks as we rely on sections to build
2794*0b57cec5SDimitry Andric       // arange spans. We can do it without, but it's icky.
2795*0b57cec5SDimitry Andric       SectionMap[nullptr].push_back(SCU);
2796*0b57cec5SDimitry Andric     }
2797*0b57cec5SDimitry Andric   }
2798*0b57cec5SDimitry Andric 
2799*0b57cec5SDimitry Andric   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2800*0b57cec5SDimitry Andric 
2801*0b57cec5SDimitry Andric   for (auto &I : SectionMap) {
2802*0b57cec5SDimitry Andric     MCSection *Section = I.first;
2803*0b57cec5SDimitry Andric     SmallVector<SymbolCU, 8> &List = I.second;
2804*0b57cec5SDimitry Andric     if (List.size() < 1)
2805*0b57cec5SDimitry Andric       continue;
2806*0b57cec5SDimitry Andric 
2807*0b57cec5SDimitry Andric     // If we have no section (e.g. common), just write out
2808*0b57cec5SDimitry Andric     // individual spans for each symbol.
2809*0b57cec5SDimitry Andric     if (!Section) {
2810*0b57cec5SDimitry Andric       for (const SymbolCU &Cur : List) {
2811*0b57cec5SDimitry Andric         ArangeSpan Span;
2812*0b57cec5SDimitry Andric         Span.Start = Cur.Sym;
2813*0b57cec5SDimitry Andric         Span.End = nullptr;
2814*0b57cec5SDimitry Andric         assert(Cur.CU);
2815*0b57cec5SDimitry Andric         Spans[Cur.CU].push_back(Span);
2816*0b57cec5SDimitry Andric       }
2817*0b57cec5SDimitry Andric       continue;
2818*0b57cec5SDimitry Andric     }
2819*0b57cec5SDimitry Andric 
2820*0b57cec5SDimitry Andric     // Sort the symbols by offset within the section.
2821*0b57cec5SDimitry Andric     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2822*0b57cec5SDimitry Andric       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2823*0b57cec5SDimitry Andric       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2824*0b57cec5SDimitry Andric 
2825*0b57cec5SDimitry Andric       // Symbols with no order assigned should be placed at the end.
2826*0b57cec5SDimitry Andric       // (e.g. section end labels)
2827*0b57cec5SDimitry Andric       if (IA == 0)
2828*0b57cec5SDimitry Andric         return false;
2829*0b57cec5SDimitry Andric       if (IB == 0)
2830*0b57cec5SDimitry Andric         return true;
2831*0b57cec5SDimitry Andric       return IA < IB;
2832*0b57cec5SDimitry Andric     });
2833*0b57cec5SDimitry Andric 
2834*0b57cec5SDimitry Andric     // Insert a final terminator.
2835*0b57cec5SDimitry Andric     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2836*0b57cec5SDimitry Andric 
2837*0b57cec5SDimitry Andric     // Build spans between each label.
2838*0b57cec5SDimitry Andric     const MCSymbol *StartSym = List[0].Sym;
2839*0b57cec5SDimitry Andric     for (size_t n = 1, e = List.size(); n < e; n++) {
2840*0b57cec5SDimitry Andric       const SymbolCU &Prev = List[n - 1];
2841*0b57cec5SDimitry Andric       const SymbolCU &Cur = List[n];
2842*0b57cec5SDimitry Andric 
2843*0b57cec5SDimitry Andric       // Try and build the longest span we can within the same CU.
2844*0b57cec5SDimitry Andric       if (Cur.CU != Prev.CU) {
2845*0b57cec5SDimitry Andric         ArangeSpan Span;
2846*0b57cec5SDimitry Andric         Span.Start = StartSym;
2847*0b57cec5SDimitry Andric         Span.End = Cur.Sym;
2848*0b57cec5SDimitry Andric         assert(Prev.CU);
2849*0b57cec5SDimitry Andric         Spans[Prev.CU].push_back(Span);
2850*0b57cec5SDimitry Andric         StartSym = Cur.Sym;
2851*0b57cec5SDimitry Andric       }
2852*0b57cec5SDimitry Andric     }
2853*0b57cec5SDimitry Andric   }
2854*0b57cec5SDimitry Andric 
2855*0b57cec5SDimitry Andric   // Start the dwarf aranges section.
2856*0b57cec5SDimitry Andric   Asm->OutStreamer->SwitchSection(
2857*0b57cec5SDimitry Andric       Asm->getObjFileLowering().getDwarfARangesSection());
2858*0b57cec5SDimitry Andric 
2859*0b57cec5SDimitry Andric   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2860*0b57cec5SDimitry Andric 
2861*0b57cec5SDimitry Andric   // Build a list of CUs used.
2862*0b57cec5SDimitry Andric   std::vector<DwarfCompileUnit *> CUs;
2863*0b57cec5SDimitry Andric   for (const auto &it : Spans) {
2864*0b57cec5SDimitry Andric     DwarfCompileUnit *CU = it.first;
2865*0b57cec5SDimitry Andric     CUs.push_back(CU);
2866*0b57cec5SDimitry Andric   }
2867*0b57cec5SDimitry Andric 
2868*0b57cec5SDimitry Andric   // Sort the CU list (again, to ensure consistent output order).
2869*0b57cec5SDimitry Andric   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2870*0b57cec5SDimitry Andric     return A->getUniqueID() < B->getUniqueID();
2871*0b57cec5SDimitry Andric   });
2872*0b57cec5SDimitry Andric 
2873*0b57cec5SDimitry Andric   // Emit an arange table for each CU we used.
2874*0b57cec5SDimitry Andric   for (DwarfCompileUnit *CU : CUs) {
2875*0b57cec5SDimitry Andric     std::vector<ArangeSpan> &List = Spans[CU];
2876*0b57cec5SDimitry Andric 
2877*0b57cec5SDimitry Andric     // Describe the skeleton CU's offset and length, not the dwo file's.
2878*0b57cec5SDimitry Andric     if (auto *Skel = CU->getSkeleton())
2879*0b57cec5SDimitry Andric       CU = Skel;
2880*0b57cec5SDimitry Andric 
2881*0b57cec5SDimitry Andric     // Emit size of content not including length itself.
2882*0b57cec5SDimitry Andric     unsigned ContentSize =
2883*0b57cec5SDimitry Andric         sizeof(int16_t) +               // DWARF ARange version number
2884e8d8bef9SDimitry Andric         Asm->getDwarfOffsetByteSize() + // Offset of CU in the .debug_info
2885e8d8bef9SDimitry Andric                                         // section
2886*0b57cec5SDimitry Andric         sizeof(int8_t) +                // Pointer Size (in bytes)
2887*0b57cec5SDimitry Andric         sizeof(int8_t);                 // Segment Size (in bytes)
2888*0b57cec5SDimitry Andric 
2889*0b57cec5SDimitry Andric     unsigned TupleSize = PtrSize * 2;
2890*0b57cec5SDimitry Andric 
2891*0b57cec5SDimitry Andric     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2892e8d8bef9SDimitry Andric     unsigned Padding = offsetToAlignment(
2893e8d8bef9SDimitry Andric         Asm->getUnitLengthFieldByteSize() + ContentSize, Align(TupleSize));
2894*0b57cec5SDimitry Andric 
2895*0b57cec5SDimitry Andric     ContentSize += Padding;
2896*0b57cec5SDimitry Andric     ContentSize += (List.size() + 1) * TupleSize;
2897*0b57cec5SDimitry Andric 
2898*0b57cec5SDimitry Andric     // For each compile unit, write the list of spans it covers.
2899e8d8bef9SDimitry Andric     Asm->emitDwarfUnitLength(ContentSize, "Length of ARange Set");
2900*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("DWARF Arange version number");
2901*0b57cec5SDimitry Andric     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2902*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2903*0b57cec5SDimitry Andric     emitSectionReference(*CU);
2904*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2905*0b57cec5SDimitry Andric     Asm->emitInt8(PtrSize);
2906*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2907*0b57cec5SDimitry Andric     Asm->emitInt8(0);
2908*0b57cec5SDimitry Andric 
2909*0b57cec5SDimitry Andric     Asm->OutStreamer->emitFill(Padding, 0xff);
2910*0b57cec5SDimitry Andric 
2911*0b57cec5SDimitry Andric     for (const ArangeSpan &Span : List) {
29125ffd83dbSDimitry Andric       Asm->emitLabelReference(Span.Start, PtrSize);
2913*0b57cec5SDimitry Andric 
2914*0b57cec5SDimitry Andric       // Calculate the size as being from the span start to it's end.
2915*0b57cec5SDimitry Andric       if (Span.End) {
29165ffd83dbSDimitry Andric         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
2917*0b57cec5SDimitry Andric       } else {
2918*0b57cec5SDimitry Andric         // For symbols without an end marker (e.g. common), we
2919*0b57cec5SDimitry Andric         // write a single arange entry containing just that one symbol.
2920*0b57cec5SDimitry Andric         uint64_t Size = SymSize[Span.Start];
2921*0b57cec5SDimitry Andric         if (Size == 0)
2922*0b57cec5SDimitry Andric           Size = 1;
2923*0b57cec5SDimitry Andric 
29245ffd83dbSDimitry Andric         Asm->OutStreamer->emitIntValue(Size, PtrSize);
2925*0b57cec5SDimitry Andric       }
2926*0b57cec5SDimitry Andric     }
2927*0b57cec5SDimitry Andric 
2928*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("ARange terminator");
29295ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
29305ffd83dbSDimitry Andric     Asm->OutStreamer->emitIntValue(0, PtrSize);
2931*0b57cec5SDimitry Andric   }
2932*0b57cec5SDimitry Andric }
2933*0b57cec5SDimitry Andric 
2934*0b57cec5SDimitry Andric /// Emit a single range list. We handle both DWARF v5 and earlier.
2935*0b57cec5SDimitry Andric static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2936*0b57cec5SDimitry Andric                           const RangeSpanList &List) {
2937480093f4SDimitry Andric   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
29388bcb0991SDimitry Andric                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
29398bcb0991SDimitry Andric                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
29408bcb0991SDimitry Andric                 llvm::dwarf::RangeListEncodingString,
2941480093f4SDimitry Andric                 List.CU->getCUNode()->getRangesBaseAddress() ||
29428bcb0991SDimitry Andric                     DD.getDwarfVersion() >= 5,
29438bcb0991SDimitry Andric                 [](auto) {});
2944*0b57cec5SDimitry Andric }
2945*0b57cec5SDimitry Andric 
2946480093f4SDimitry Andric void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2947480093f4SDimitry Andric   if (Holder.getRangeLists().empty())
2948480093f4SDimitry Andric     return;
2949480093f4SDimitry Andric 
2950480093f4SDimitry Andric   assert(useRangesSection());
2951480093f4SDimitry Andric   assert(!CUMap.empty());
2952480093f4SDimitry Andric   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2953480093f4SDimitry Andric     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2954480093f4SDimitry Andric   }));
2955480093f4SDimitry Andric 
2956480093f4SDimitry Andric   Asm->OutStreamer->SwitchSection(Section);
2957480093f4SDimitry Andric 
2958480093f4SDimitry Andric   MCSymbol *TableEnd = nullptr;
2959480093f4SDimitry Andric   if (getDwarfVersion() >= 5)
2960480093f4SDimitry Andric     TableEnd = emitRnglistsTableHeader(Asm, Holder);
2961480093f4SDimitry Andric 
2962*0b57cec5SDimitry Andric   for (const RangeSpanList &List : Holder.getRangeLists())
2963480093f4SDimitry Andric     emitRangeList(*this, Asm, List);
2964*0b57cec5SDimitry Andric 
2965*0b57cec5SDimitry Andric   if (TableEnd)
29665ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(TableEnd);
2967*0b57cec5SDimitry Andric }
2968*0b57cec5SDimitry Andric 
2969*0b57cec5SDimitry Andric /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2970*0b57cec5SDimitry Andric /// .debug_rnglists section.
2971*0b57cec5SDimitry Andric void DwarfDebug::emitDebugRanges() {
2972*0b57cec5SDimitry Andric   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2973*0b57cec5SDimitry Andric 
2974480093f4SDimitry Andric   emitDebugRangesImpl(Holder,
2975480093f4SDimitry Andric                       getDwarfVersion() >= 5
2976480093f4SDimitry Andric                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2977480093f4SDimitry Andric                           : Asm->getObjFileLowering().getDwarfRangesSection());
2978*0b57cec5SDimitry Andric }
2979*0b57cec5SDimitry Andric 
2980*0b57cec5SDimitry Andric void DwarfDebug::emitDebugRangesDWO() {
2981480093f4SDimitry Andric   emitDebugRangesImpl(InfoHolder,
2982*0b57cec5SDimitry Andric                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2983*0b57cec5SDimitry Andric }
2984*0b57cec5SDimitry Andric 
2985e8d8bef9SDimitry Andric /// Emit the header of a DWARF 5 macro section, or the GNU extension for
2986e8d8bef9SDimitry Andric /// DWARF 4.
29875ffd83dbSDimitry Andric static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
2988e8d8bef9SDimitry Andric                             const DwarfCompileUnit &CU, uint16_t DwarfVersion) {
29895ffd83dbSDimitry Andric   enum HeaderFlagMask {
29905ffd83dbSDimitry Andric #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
29915ffd83dbSDimitry Andric #include "llvm/BinaryFormat/Dwarf.def"
29925ffd83dbSDimitry Andric   };
29935ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("Macro information version");
2994e8d8bef9SDimitry Andric   Asm->emitInt16(DwarfVersion >= 5 ? DwarfVersion : 4);
2995e8d8bef9SDimitry Andric   // We emit the line offset flag unconditionally here, since line offset should
2996e8d8bef9SDimitry Andric   // be mostly present.
2997e8d8bef9SDimitry Andric   if (Asm->isDwarf64()) {
2998e8d8bef9SDimitry Andric     Asm->OutStreamer->AddComment("Flags: 64 bit, debug_line_offset present");
2999e8d8bef9SDimitry Andric     Asm->emitInt8(MACRO_FLAG_OFFSET_SIZE | MACRO_FLAG_DEBUG_LINE_OFFSET);
3000e8d8bef9SDimitry Andric   } else {
30015ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3002e8d8bef9SDimitry Andric     Asm->emitInt8(MACRO_FLAG_DEBUG_LINE_OFFSET);
3003e8d8bef9SDimitry Andric   }
30045ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("debug_line_offset");
3005e8d8bef9SDimitry Andric   if (DD.useSplitDwarf())
3006e8d8bef9SDimitry Andric     Asm->emitDwarfLengthOrOffset(0);
3007e8d8bef9SDimitry Andric   else
3008e8d8bef9SDimitry Andric     Asm->emitDwarfSymbolReference(CU.getLineTableStartSym());
30095ffd83dbSDimitry Andric }
30105ffd83dbSDimitry Andric 
3011*0b57cec5SDimitry Andric void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3012*0b57cec5SDimitry Andric   for (auto *MN : Nodes) {
3013*0b57cec5SDimitry Andric     if (auto *M = dyn_cast<DIMacro>(MN))
3014*0b57cec5SDimitry Andric       emitMacro(*M);
3015*0b57cec5SDimitry Andric     else if (auto *F = dyn_cast<DIMacroFile>(MN))
3016*0b57cec5SDimitry Andric       emitMacroFile(*F, U);
3017*0b57cec5SDimitry Andric     else
3018*0b57cec5SDimitry Andric       llvm_unreachable("Unexpected DI type!");
3019*0b57cec5SDimitry Andric   }
3020*0b57cec5SDimitry Andric }
3021*0b57cec5SDimitry Andric 
3022*0b57cec5SDimitry Andric void DwarfDebug::emitMacro(DIMacro &M) {
3023*0b57cec5SDimitry Andric   StringRef Name = M.getName();
3024*0b57cec5SDimitry Andric   StringRef Value = M.getValue();
30255ffd83dbSDimitry Andric 
3026e8d8bef9SDimitry Andric   // There should be one space between the macro name and the macro value in
3027e8d8bef9SDimitry Andric   // define entries. In undef entries, only the macro name is emitted.
3028e8d8bef9SDimitry Andric   std::string Str = Value.empty() ? Name.str() : (Name + " " + Value).str();
3029e8d8bef9SDimitry Andric 
3030e8d8bef9SDimitry Andric   if (UseDebugMacroSection) {
3031e8d8bef9SDimitry Andric     if (getDwarfVersion() >= 5) {
30325ffd83dbSDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
30335ffd83dbSDimitry Andric                           ? dwarf::DW_MACRO_define_strx
30345ffd83dbSDimitry Andric                           : dwarf::DW_MACRO_undef_strx;
30355ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
30365ffd83dbSDimitry Andric       Asm->emitULEB128(Type);
30375ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
30385ffd83dbSDimitry Andric       Asm->emitULEB128(M.getLine());
30395ffd83dbSDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3040e8d8bef9SDimitry Andric       Asm->emitULEB128(
3041e8d8bef9SDimitry Andric           InfoHolder.getStringPool().getIndexedEntry(*Asm, Str).getIndex());
3042e8d8bef9SDimitry Andric     } else {
3043e8d8bef9SDimitry Andric       unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3044e8d8bef9SDimitry Andric                           ? dwarf::DW_MACRO_GNU_define_indirect
3045e8d8bef9SDimitry Andric                           : dwarf::DW_MACRO_GNU_undef_indirect;
3046e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment(dwarf::GnuMacroString(Type));
3047e8d8bef9SDimitry Andric       Asm->emitULEB128(Type);
3048e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment("Line Number");
3049e8d8bef9SDimitry Andric       Asm->emitULEB128(M.getLine());
3050e8d8bef9SDimitry Andric       Asm->OutStreamer->AddComment("Macro String");
3051e8d8bef9SDimitry Andric       Asm->emitDwarfSymbolReference(
3052e8d8bef9SDimitry Andric           InfoHolder.getStringPool().getEntry(*Asm, Str).getSymbol());
3053e8d8bef9SDimitry Andric     }
30545ffd83dbSDimitry Andric   } else {
30555ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
30565ffd83dbSDimitry Andric     Asm->emitULEB128(M.getMacinfoType());
30575ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Line Number");
30585ffd83dbSDimitry Andric     Asm->emitULEB128(M.getLine());
30595ffd83dbSDimitry Andric     Asm->OutStreamer->AddComment("Macro String");
3060e8d8bef9SDimitry Andric     Asm->OutStreamer->emitBytes(Str);
3061*0b57cec5SDimitry Andric     Asm->emitInt8('\0');
3062*0b57cec5SDimitry Andric   }
30635ffd83dbSDimitry Andric }
30645ffd83dbSDimitry Andric 
30655ffd83dbSDimitry Andric void DwarfDebug::emitMacroFileImpl(
3066e8d8bef9SDimitry Andric     DIMacroFile &MF, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
30675ffd83dbSDimitry Andric     StringRef (*MacroFormToString)(unsigned Form)) {
30685ffd83dbSDimitry Andric 
30695ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
30705ffd83dbSDimitry Andric   Asm->emitULEB128(StartFile);
30715ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("Line Number");
3072e8d8bef9SDimitry Andric   Asm->emitULEB128(MF.getLine());
30735ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment("File Number");
3074e8d8bef9SDimitry Andric   DIFile &F = *MF.getFile();
3075e8d8bef9SDimitry Andric   if (useSplitDwarf())
3076e8d8bef9SDimitry Andric     Asm->emitULEB128(getDwoLineTable(U)->getFile(
3077e8d8bef9SDimitry Andric         F.getDirectory(), F.getFilename(), getMD5AsBytes(&F),
3078e8d8bef9SDimitry Andric         Asm->OutContext.getDwarfVersion(), F.getSource()));
3079e8d8bef9SDimitry Andric   else
3080e8d8bef9SDimitry Andric     Asm->emitULEB128(U.getOrCreateSourceID(&F));
3081e8d8bef9SDimitry Andric   handleMacroNodes(MF.getElements(), U);
30825ffd83dbSDimitry Andric   Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
30835ffd83dbSDimitry Andric   Asm->emitULEB128(EndFile);
30845ffd83dbSDimitry Andric }
3085*0b57cec5SDimitry Andric 
3086*0b57cec5SDimitry Andric void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
30875ffd83dbSDimitry Andric   // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
30885ffd83dbSDimitry Andric   // so for readibility/uniformity, We are explicitly emitting those.
3089*0b57cec5SDimitry Andric   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3090e8d8bef9SDimitry Andric   if (UseDebugMacroSection)
3091e8d8bef9SDimitry Andric     emitMacroFileImpl(
3092e8d8bef9SDimitry Andric         F, U, dwarf::DW_MACRO_start_file, dwarf::DW_MACRO_end_file,
3093e8d8bef9SDimitry Andric         (getDwarfVersion() >= 5) ? dwarf::MacroString : dwarf::GnuMacroString);
30945ffd83dbSDimitry Andric   else
30955ffd83dbSDimitry Andric     emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
30965ffd83dbSDimitry Andric                       dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
3097*0b57cec5SDimitry Andric }
3098*0b57cec5SDimitry Andric 
3099480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3100*0b57cec5SDimitry Andric   for (const auto &P : CUMap) {
3101*0b57cec5SDimitry Andric     auto &TheCU = *P.second;
3102*0b57cec5SDimitry Andric     auto *SkCU = TheCU.getSkeleton();
3103*0b57cec5SDimitry Andric     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3104*0b57cec5SDimitry Andric     auto *CUNode = cast<DICompileUnit>(P.first);
3105*0b57cec5SDimitry Andric     DIMacroNodeArray Macros = CUNode->getMacros();
3106480093f4SDimitry Andric     if (Macros.empty())
3107480093f4SDimitry Andric       continue;
3108480093f4SDimitry Andric     Asm->OutStreamer->SwitchSection(Section);
31095ffd83dbSDimitry Andric     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3110e8d8bef9SDimitry Andric     if (UseDebugMacroSection)
3111e8d8bef9SDimitry Andric       emitMacroHeader(Asm, *this, U, getDwarfVersion());
3112*0b57cec5SDimitry Andric     handleMacroNodes(Macros, U);
3113*0b57cec5SDimitry Andric     Asm->OutStreamer->AddComment("End Of Macro List Mark");
3114*0b57cec5SDimitry Andric     Asm->emitInt8(0);
3115*0b57cec5SDimitry Andric   }
3116480093f4SDimitry Andric }
3117480093f4SDimitry Andric 
31185ffd83dbSDimitry Andric /// Emit macros into a debug macinfo/macro section.
3119480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfo() {
31205ffd83dbSDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3121e8d8bef9SDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
31225ffd83dbSDimitry Andric                            ? ObjLower.getDwarfMacroSection()
31235ffd83dbSDimitry Andric                            : ObjLower.getDwarfMacinfoSection());
3124480093f4SDimitry Andric }
3125480093f4SDimitry Andric 
3126480093f4SDimitry Andric void DwarfDebug::emitDebugMacinfoDWO() {
31275ffd83dbSDimitry Andric   auto &ObjLower = Asm->getObjFileLowering();
3128e8d8bef9SDimitry Andric   emitDebugMacinfoImpl(UseDebugMacroSection
31295ffd83dbSDimitry Andric                            ? ObjLower.getDwarfMacroDWOSection()
31305ffd83dbSDimitry Andric                            : ObjLower.getDwarfMacinfoDWOSection());
3131480093f4SDimitry Andric }
3132*0b57cec5SDimitry Andric 
3133*0b57cec5SDimitry Andric // DWARF5 Experimental Separate Dwarf emitters.
3134*0b57cec5SDimitry Andric 
3135*0b57cec5SDimitry Andric void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3136*0b57cec5SDimitry Andric                                   std::unique_ptr<DwarfCompileUnit> NewU) {
3137*0b57cec5SDimitry Andric 
3138*0b57cec5SDimitry Andric   if (!CompilationDir.empty())
3139*0b57cec5SDimitry Andric     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3140*0b57cec5SDimitry Andric   addGnuPubAttributes(*NewU, Die);
3141*0b57cec5SDimitry Andric 
3142*0b57cec5SDimitry Andric   SkeletonHolder.addUnit(std::move(NewU));
3143*0b57cec5SDimitry Andric }
3144*0b57cec5SDimitry Andric 
3145*0b57cec5SDimitry Andric DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3146*0b57cec5SDimitry Andric 
31478bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3148480093f4SDimitry Andric       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3149480093f4SDimitry Andric       UnitKind::Skeleton);
3150*0b57cec5SDimitry Andric   DwarfCompileUnit &NewCU = *OwnedUnit;
3151*0b57cec5SDimitry Andric   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
3152*0b57cec5SDimitry Andric 
3153*0b57cec5SDimitry Andric   NewCU.initStmtList();
3154*0b57cec5SDimitry Andric 
3155*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
3156*0b57cec5SDimitry Andric     NewCU.addStringOffsetsStart();
3157*0b57cec5SDimitry Andric 
3158*0b57cec5SDimitry Andric   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3159*0b57cec5SDimitry Andric 
3160*0b57cec5SDimitry Andric   return NewCU;
3161*0b57cec5SDimitry Andric }
3162*0b57cec5SDimitry Andric 
3163*0b57cec5SDimitry Andric // Emit the .debug_info.dwo section for separated dwarf. This contains the
3164*0b57cec5SDimitry Andric // compile units that would normally be in debug_info.
3165*0b57cec5SDimitry Andric void DwarfDebug::emitDebugInfoDWO() {
3166*0b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf debug info?");
3167*0b57cec5SDimitry Andric   // Don't emit relocations into the dwo file.
3168*0b57cec5SDimitry Andric   InfoHolder.emitUnits(/* UseOffsets */ true);
3169*0b57cec5SDimitry Andric }
3170*0b57cec5SDimitry Andric 
3171*0b57cec5SDimitry Andric // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3172*0b57cec5SDimitry Andric // abbreviations for the .debug_info.dwo section.
3173*0b57cec5SDimitry Andric void DwarfDebug::emitDebugAbbrevDWO() {
3174*0b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3175*0b57cec5SDimitry Andric   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3176*0b57cec5SDimitry Andric }
3177*0b57cec5SDimitry Andric 
3178*0b57cec5SDimitry Andric void DwarfDebug::emitDebugLineDWO() {
3179*0b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3180*0b57cec5SDimitry Andric   SplitTypeUnitFileTable.Emit(
3181*0b57cec5SDimitry Andric       *Asm->OutStreamer, MCDwarfLineTableParams(),
3182*0b57cec5SDimitry Andric       Asm->getObjFileLowering().getDwarfLineDWOSection());
3183*0b57cec5SDimitry Andric }
3184*0b57cec5SDimitry Andric 
3185*0b57cec5SDimitry Andric void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3186*0b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3187*0b57cec5SDimitry Andric   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
3188*0b57cec5SDimitry Andric       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
3189*0b57cec5SDimitry Andric       InfoHolder.getStringOffsetsStartSym());
3190*0b57cec5SDimitry Andric }
3191*0b57cec5SDimitry Andric 
3192*0b57cec5SDimitry Andric // Emit the .debug_str.dwo section for separated dwarf. This contains the
3193*0b57cec5SDimitry Andric // string section and is identical in format to traditional .debug_str
3194*0b57cec5SDimitry Andric // sections.
3195*0b57cec5SDimitry Andric void DwarfDebug::emitDebugStrDWO() {
3196*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable())
3197*0b57cec5SDimitry Andric     emitStringOffsetsTableHeaderDWO();
3198*0b57cec5SDimitry Andric   assert(useSplitDwarf() && "No split dwarf?");
3199*0b57cec5SDimitry Andric   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3200*0b57cec5SDimitry Andric   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3201*0b57cec5SDimitry Andric                          OffSec, /* UseRelativeOffsets = */ false);
3202*0b57cec5SDimitry Andric }
3203*0b57cec5SDimitry Andric 
3204*0b57cec5SDimitry Andric // Emit address pool.
3205*0b57cec5SDimitry Andric void DwarfDebug::emitDebugAddr() {
3206*0b57cec5SDimitry Andric   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
3207*0b57cec5SDimitry Andric }
3208*0b57cec5SDimitry Andric 
3209*0b57cec5SDimitry Andric MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
3210*0b57cec5SDimitry Andric   if (!useSplitDwarf())
3211*0b57cec5SDimitry Andric     return nullptr;
3212*0b57cec5SDimitry Andric   const DICompileUnit *DIUnit = CU.getCUNode();
3213*0b57cec5SDimitry Andric   SplitTypeUnitFileTable.maybeSetRootFile(
3214*0b57cec5SDimitry Andric       DIUnit->getDirectory(), DIUnit->getFilename(),
3215e8d8bef9SDimitry Andric       getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
3216*0b57cec5SDimitry Andric   return &SplitTypeUnitFileTable;
3217*0b57cec5SDimitry Andric }
3218*0b57cec5SDimitry Andric 
3219*0b57cec5SDimitry Andric uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
3220*0b57cec5SDimitry Andric   MD5 Hash;
3221*0b57cec5SDimitry Andric   Hash.update(Identifier);
3222*0b57cec5SDimitry Andric   // ... take the least significant 8 bytes and return those. Our MD5
3223*0b57cec5SDimitry Andric   // implementation always returns its results in little endian, so we actually
3224*0b57cec5SDimitry Andric   // need the "high" word.
3225*0b57cec5SDimitry Andric   MD5::MD5Result Result;
3226*0b57cec5SDimitry Andric   Hash.final(Result);
3227*0b57cec5SDimitry Andric   return Result.high();
3228*0b57cec5SDimitry Andric }
3229*0b57cec5SDimitry Andric 
3230*0b57cec5SDimitry Andric void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
3231*0b57cec5SDimitry Andric                                       StringRef Identifier, DIE &RefDie,
3232*0b57cec5SDimitry Andric                                       const DICompositeType *CTy) {
3233*0b57cec5SDimitry Andric   // Fast path if we're building some type units and one has already used the
3234*0b57cec5SDimitry Andric   // address pool we know we're going to throw away all this work anyway, so
3235*0b57cec5SDimitry Andric   // don't bother building dependent types.
3236*0b57cec5SDimitry Andric   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3237*0b57cec5SDimitry Andric     return;
3238*0b57cec5SDimitry Andric 
3239*0b57cec5SDimitry Andric   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3240*0b57cec5SDimitry Andric   if (!Ins.second) {
3241*0b57cec5SDimitry Andric     CU.addDIETypeSignature(RefDie, Ins.first->second);
3242*0b57cec5SDimitry Andric     return;
3243*0b57cec5SDimitry Andric   }
3244*0b57cec5SDimitry Andric 
3245*0b57cec5SDimitry Andric   bool TopLevelType = TypeUnitsUnderConstruction.empty();
3246*0b57cec5SDimitry Andric   AddrPool.resetUsedFlag();
3247*0b57cec5SDimitry Andric 
32488bcb0991SDimitry Andric   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
3249*0b57cec5SDimitry Andric                                                     getDwoLineTable(CU));
3250*0b57cec5SDimitry Andric   DwarfTypeUnit &NewTU = *OwnedUnit;
3251*0b57cec5SDimitry Andric   DIE &UnitDie = NewTU.getUnitDie();
3252*0b57cec5SDimitry Andric   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3253*0b57cec5SDimitry Andric 
3254*0b57cec5SDimitry Andric   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3255*0b57cec5SDimitry Andric                 CU.getLanguage());
3256*0b57cec5SDimitry Andric 
3257*0b57cec5SDimitry Andric   uint64_t Signature = makeTypeSignature(Identifier);
3258*0b57cec5SDimitry Andric   NewTU.setTypeSignature(Signature);
3259*0b57cec5SDimitry Andric   Ins.first->second = Signature;
3260*0b57cec5SDimitry Andric 
3261*0b57cec5SDimitry Andric   if (useSplitDwarf()) {
3262*0b57cec5SDimitry Andric     MCSection *Section =
3263*0b57cec5SDimitry Andric         getDwarfVersion() <= 4
3264*0b57cec5SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3265*0b57cec5SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3266*0b57cec5SDimitry Andric     NewTU.setSection(Section);
3267*0b57cec5SDimitry Andric   } else {
3268*0b57cec5SDimitry Andric     MCSection *Section =
3269*0b57cec5SDimitry Andric         getDwarfVersion() <= 4
3270*0b57cec5SDimitry Andric             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3271*0b57cec5SDimitry Andric             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3272*0b57cec5SDimitry Andric     NewTU.setSection(Section);
3273*0b57cec5SDimitry Andric     // Non-split type units reuse the compile unit's line table.
3274*0b57cec5SDimitry Andric     CU.applyStmtList(UnitDie);
3275*0b57cec5SDimitry Andric   }
3276*0b57cec5SDimitry Andric 
3277*0b57cec5SDimitry Andric   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3278*0b57cec5SDimitry Andric   // units.
3279*0b57cec5SDimitry Andric   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3280*0b57cec5SDimitry Andric     NewTU.addStringOffsetsStart();
3281*0b57cec5SDimitry Andric 
3282*0b57cec5SDimitry Andric   NewTU.setType(NewTU.createTypeDIE(CTy));
3283*0b57cec5SDimitry Andric 
3284*0b57cec5SDimitry Andric   if (TopLevelType) {
3285*0b57cec5SDimitry Andric     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3286*0b57cec5SDimitry Andric     TypeUnitsUnderConstruction.clear();
3287*0b57cec5SDimitry Andric 
3288*0b57cec5SDimitry Andric     // Types referencing entries in the address table cannot be placed in type
3289*0b57cec5SDimitry Andric     // units.
3290*0b57cec5SDimitry Andric     if (AddrPool.hasBeenUsed()) {
3291*0b57cec5SDimitry Andric 
3292*0b57cec5SDimitry Andric       // Remove all the types built while building this type.
3293*0b57cec5SDimitry Andric       // This is pessimistic as some of these types might not be dependent on
3294*0b57cec5SDimitry Andric       // the type that used an address.
3295*0b57cec5SDimitry Andric       for (const auto &TU : TypeUnitsToAdd)
3296*0b57cec5SDimitry Andric         TypeSignatures.erase(TU.second);
3297*0b57cec5SDimitry Andric 
3298*0b57cec5SDimitry Andric       // Construct this type in the CU directly.
3299*0b57cec5SDimitry Andric       // This is inefficient because all the dependent types will be rebuilt
3300*0b57cec5SDimitry Andric       // from scratch, including building them in type units, discovering that
3301*0b57cec5SDimitry Andric       // they depend on addresses, throwing them out and rebuilding them.
3302*0b57cec5SDimitry Andric       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3303*0b57cec5SDimitry Andric       return;
3304*0b57cec5SDimitry Andric     }
3305*0b57cec5SDimitry Andric 
3306*0b57cec5SDimitry Andric     // If the type wasn't dependent on fission addresses, finish adding the type
3307*0b57cec5SDimitry Andric     // and all its dependent types.
3308*0b57cec5SDimitry Andric     for (auto &TU : TypeUnitsToAdd) {
3309*0b57cec5SDimitry Andric       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3310*0b57cec5SDimitry Andric       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3311*0b57cec5SDimitry Andric     }
3312*0b57cec5SDimitry Andric   }
3313*0b57cec5SDimitry Andric   CU.addDIETypeSignature(RefDie, Signature);
3314*0b57cec5SDimitry Andric }
3315*0b57cec5SDimitry Andric 
3316*0b57cec5SDimitry Andric DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3317*0b57cec5SDimitry Andric     : DD(DD),
3318e8d8bef9SDimitry Andric       TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)), AddrPoolUsed(DD->AddrPool.hasBeenUsed()) {
3319*0b57cec5SDimitry Andric   DD->TypeUnitsUnderConstruction.clear();
3320e8d8bef9SDimitry Andric   DD->AddrPool.resetUsedFlag();
3321*0b57cec5SDimitry Andric }
3322*0b57cec5SDimitry Andric 
3323*0b57cec5SDimitry Andric DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3324*0b57cec5SDimitry Andric   DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3325e8d8bef9SDimitry Andric   DD->AddrPool.resetUsedFlag(AddrPoolUsed);
3326*0b57cec5SDimitry Andric }
3327*0b57cec5SDimitry Andric 
3328*0b57cec5SDimitry Andric DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3329*0b57cec5SDimitry Andric   return NonTypeUnitContext(this);
3330*0b57cec5SDimitry Andric }
3331*0b57cec5SDimitry Andric 
3332*0b57cec5SDimitry Andric // Add the Name along with its companion DIE to the appropriate accelerator
3333*0b57cec5SDimitry Andric // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3334*0b57cec5SDimitry Andric // AccelTableKind::Apple, we use the table we got as an argument). If
3335*0b57cec5SDimitry Andric // accelerator tables are disabled, this function does nothing.
3336*0b57cec5SDimitry Andric template <typename DataT>
3337*0b57cec5SDimitry Andric void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3338*0b57cec5SDimitry Andric                                   AccelTable<DataT> &AppleAccel, StringRef Name,
3339*0b57cec5SDimitry Andric                                   const DIE &Die) {
3340*0b57cec5SDimitry Andric   if (getAccelTableKind() == AccelTableKind::None)
3341*0b57cec5SDimitry Andric     return;
3342*0b57cec5SDimitry Andric 
3343*0b57cec5SDimitry Andric   if (getAccelTableKind() != AccelTableKind::Apple &&
3344*0b57cec5SDimitry Andric       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3345*0b57cec5SDimitry Andric     return;
3346*0b57cec5SDimitry Andric 
3347*0b57cec5SDimitry Andric   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3348*0b57cec5SDimitry Andric   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3349*0b57cec5SDimitry Andric 
3350*0b57cec5SDimitry Andric   switch (getAccelTableKind()) {
3351*0b57cec5SDimitry Andric   case AccelTableKind::Apple:
3352*0b57cec5SDimitry Andric     AppleAccel.addName(Ref, Die);
3353*0b57cec5SDimitry Andric     break;
3354*0b57cec5SDimitry Andric   case AccelTableKind::Dwarf:
3355*0b57cec5SDimitry Andric     AccelDebugNames.addName(Ref, Die);
3356*0b57cec5SDimitry Andric     break;
3357*0b57cec5SDimitry Andric   case AccelTableKind::Default:
3358*0b57cec5SDimitry Andric     llvm_unreachable("Default should have already been resolved.");
3359*0b57cec5SDimitry Andric   case AccelTableKind::None:
3360*0b57cec5SDimitry Andric     llvm_unreachable("None handled above");
3361*0b57cec5SDimitry Andric   }
3362*0b57cec5SDimitry Andric }
3363*0b57cec5SDimitry Andric 
3364*0b57cec5SDimitry Andric void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3365*0b57cec5SDimitry Andric                               const DIE &Die) {
3366*0b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelNames, Name, Die);
3367*0b57cec5SDimitry Andric }
3368*0b57cec5SDimitry Andric 
3369*0b57cec5SDimitry Andric void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3370*0b57cec5SDimitry Andric                               const DIE &Die) {
3371*0b57cec5SDimitry Andric   // ObjC names go only into the Apple accelerator tables.
3372*0b57cec5SDimitry Andric   if (getAccelTableKind() == AccelTableKind::Apple)
3373*0b57cec5SDimitry Andric     addAccelNameImpl(CU, AccelObjC, Name, Die);
3374*0b57cec5SDimitry Andric }
3375*0b57cec5SDimitry Andric 
3376*0b57cec5SDimitry Andric void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3377*0b57cec5SDimitry Andric                                    const DIE &Die) {
3378*0b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelNamespace, Name, Die);
3379*0b57cec5SDimitry Andric }
3380*0b57cec5SDimitry Andric 
3381*0b57cec5SDimitry Andric void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3382*0b57cec5SDimitry Andric                               const DIE &Die, char Flags) {
3383*0b57cec5SDimitry Andric   addAccelNameImpl(CU, AccelTypes, Name, Die);
3384*0b57cec5SDimitry Andric }
3385*0b57cec5SDimitry Andric 
3386*0b57cec5SDimitry Andric uint16_t DwarfDebug::getDwarfVersion() const {
3387*0b57cec5SDimitry Andric   return Asm->OutStreamer->getContext().getDwarfVersion();
3388*0b57cec5SDimitry Andric }
3389*0b57cec5SDimitry Andric 
3390e8d8bef9SDimitry Andric dwarf::Form DwarfDebug::getDwarfSectionOffsetForm() const {
3391e8d8bef9SDimitry Andric   if (Asm->getDwarfVersion() >= 4)
3392e8d8bef9SDimitry Andric     return dwarf::Form::DW_FORM_sec_offset;
3393e8d8bef9SDimitry Andric   assert((!Asm->isDwarf64() || (Asm->getDwarfVersion() == 3)) &&
3394e8d8bef9SDimitry Andric          "DWARF64 is not defined prior DWARFv3");
3395e8d8bef9SDimitry Andric   return Asm->isDwarf64() ? dwarf::Form::DW_FORM_data8
3396e8d8bef9SDimitry Andric                           : dwarf::Form::DW_FORM_data4;
3397e8d8bef9SDimitry Andric }
3398e8d8bef9SDimitry Andric 
3399*0b57cec5SDimitry Andric const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3400*0b57cec5SDimitry Andric   return SectionLabels.find(S)->second;
3401*0b57cec5SDimitry Andric }
34025ffd83dbSDimitry Andric void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
34035ffd83dbSDimitry Andric   if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
34045ffd83dbSDimitry Andric     if (useSplitDwarf() || getDwarfVersion() >= 5)
34055ffd83dbSDimitry Andric       AddrPool.getIndex(S);
34065ffd83dbSDimitry Andric }
3407e8d8bef9SDimitry Andric 
3408e8d8bef9SDimitry Andric Optional<MD5::MD5Result> DwarfDebug::getMD5AsBytes(const DIFile *File) const {
3409e8d8bef9SDimitry Andric   assert(File);
3410e8d8bef9SDimitry Andric   if (getDwarfVersion() < 5)
3411e8d8bef9SDimitry Andric     return None;
3412e8d8bef9SDimitry Andric   Optional<DIFile::ChecksumInfo<StringRef>> Checksum = File->getChecksum();
3413e8d8bef9SDimitry Andric   if (!Checksum || Checksum->Kind != DIFile::CSK_MD5)
3414e8d8bef9SDimitry Andric     return None;
3415e8d8bef9SDimitry Andric 
3416e8d8bef9SDimitry Andric   // Convert the string checksum to an MD5Result for the streamer.
3417e8d8bef9SDimitry Andric   // The verifier validates the checksum so we assume it's okay.
3418e8d8bef9SDimitry Andric   // An MD5 checksum is 16 bytes.
3419e8d8bef9SDimitry Andric   std::string ChecksumString = fromHex(Checksum->Value);
3420e8d8bef9SDimitry Andric   MD5::MD5Result CKMem;
3421e8d8bef9SDimitry Andric   std::copy(ChecksumString.begin(), ChecksumString.end(), CKMem.Bytes.data());
3422e8d8bef9SDimitry Andric   return CKMem;
3423e8d8bef9SDimitry Andric }
3424