13443575cSPaul Robinson //===-- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units -----------===//
23443575cSPaul Robinson //
33443575cSPaul Robinson //                     The LLVM Compiler Infrastructure
43443575cSPaul Robinson //
53443575cSPaul Robinson // This file is distributed under the University of Illinois Open Source
63443575cSPaul Robinson // License. See LICENSE.TXT for details.
73443575cSPaul Robinson //
83443575cSPaul Robinson //===----------------------------------------------------------------------===//
93443575cSPaul Robinson //
103443575cSPaul Robinson // This file contains support for constructing a dwarf compile unit.
113443575cSPaul Robinson //
123443575cSPaul Robinson //===----------------------------------------------------------------------===//
133443575cSPaul Robinson 
1437c52310SDavid Blaikie #include "DwarfCompileUnit.h"
157813d9c9SAdrian Prantl #include "DwarfExpression.h"
16cda2aa82SDavid Blaikie #include "llvm/CodeGen/MachineFunction.h"
17364a3005SDuncan P. N. Exon Smith #include "llvm/IR/Constants.h"
1837c52310SDavid Blaikie #include "llvm/IR/DataLayout.h"
1937c52310SDavid Blaikie #include "llvm/IR/GlobalValue.h"
2037c52310SDavid Blaikie #include "llvm/IR/GlobalVariable.h"
2137c52310SDavid Blaikie #include "llvm/IR/Instruction.h"
2237c52310SDavid Blaikie #include "llvm/MC/MCAsmInfo.h"
2337c52310SDavid Blaikie #include "llvm/MC/MCStreamer.h"
24ee7df553SDavid Blaikie #include "llvm/Target/TargetFrameLowering.h"
2537c52310SDavid Blaikie #include "llvm/Target/TargetLoweringObjectFile.h"
26cda2aa82SDavid Blaikie #include "llvm/Target/TargetMachine.h"
27cda2aa82SDavid Blaikie #include "llvm/Target/TargetRegisterInfo.h"
28d9903888SChandler Carruth #include "llvm/Target/TargetSubtargetInfo.h"
2937c52310SDavid Blaikie 
3037c52310SDavid Blaikie namespace llvm {
3137c52310SDavid Blaikie 
32a9308c49SDuncan P. N. Exon Smith DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
3337c52310SDavid Blaikie                                    AsmPrinter *A, DwarfDebug *DW,
3437c52310SDavid Blaikie                                    DwarfFile *DWU)
357c384cceSPeter Collingbourne     : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
36063d725fSRafael Espindola       Skeleton(nullptr), BaseAddress(nullptr) {
3737c52310SDavid Blaikie   insertDIE(Node, &getUnitDie());
388bbce8adSAmjad Aboud   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
3937c52310SDavid Blaikie }
4037c52310SDavid Blaikie 
4137c52310SDavid Blaikie /// addLabelAddress - Add a dwarf label attribute data and value using
4237c52310SDavid Blaikie /// DW_FORM_addr or DW_FORM_GNU_addr_index.
4337c52310SDavid Blaikie ///
4437c52310SDavid Blaikie void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
4537c52310SDavid Blaikie                                        const MCSymbol *Label) {
4637c52310SDavid Blaikie 
4737c52310SDavid Blaikie   // Don't use the address pool in non-fission or in the skeleton unit itself.
4837c52310SDavid Blaikie   // FIXME: Once GDB supports this, it's probably worthwhile using the address
4937c52310SDavid Blaikie   // pool from the skeleton - maybe even in non-fission (possibly fewer
5037c52310SDavid Blaikie   // relocations by sharing them in the pool, but we have other ideas about how
5137c52310SDavid Blaikie   // to reduce the number of relocations as well/instead).
5237c52310SDavid Blaikie   if (!DD->useSplitDwarf() || !Skeleton)
5337c52310SDavid Blaikie     return addLocalLabelAddress(Die, Attribute, Label);
5437c52310SDavid Blaikie 
5537c52310SDavid Blaikie   if (Label)
5637c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
5737c52310SDavid Blaikie 
5837c52310SDavid Blaikie   unsigned idx = DD->getAddressPool().getIndex(Label);
594fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
604fb1f9cdSDuncan P. N. Exon Smith                DIEInteger(idx));
6137c52310SDavid Blaikie }
6237c52310SDavid Blaikie 
6337c52310SDavid Blaikie void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
6437c52310SDavid Blaikie                                             dwarf::Attribute Attribute,
6537c52310SDavid Blaikie                                             const MCSymbol *Label) {
6637c52310SDavid Blaikie   if (Label)
6737c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
6837c52310SDavid Blaikie 
69815a6eb5SDuncan P. N. Exon Smith   if (Label)
704fb1f9cdSDuncan P. N. Exon Smith     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
714fb1f9cdSDuncan P. N. Exon Smith                  DIELabel(Label));
72815a6eb5SDuncan P. N. Exon Smith   else
734fb1f9cdSDuncan P. N. Exon Smith     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
744fb1f9cdSDuncan P. N. Exon Smith                  DIEInteger(0));
7537c52310SDavid Blaikie }
7637c52310SDavid Blaikie 
778945219dSDavid Blaikie unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
788945219dSDavid Blaikie                                                StringRef DirName) {
7937c52310SDavid Blaikie   // If we print assembly, we can't separate .file entries according to
8037c52310SDavid Blaikie   // compile units. Thus all files will belong to the default compile unit.
8137c52310SDavid Blaikie 
8237c52310SDavid Blaikie   // FIXME: add a better feature test than hasRawTextSupport. Even better,
8337c52310SDavid Blaikie   // extend .file to support this.
849ff69c8fSLang Hames   return Asm->OutStreamer->EmitDwarfFileDirective(
8537c52310SDavid Blaikie       0, DirName, FileName,
869ff69c8fSLang Hames       Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
8737c52310SDavid Blaikie }
8837c52310SDavid Blaikie 
8960635e39SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
90bceaaa96SAdrian Prantl     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
9137c52310SDavid Blaikie   // Check for pre-existence.
9237c52310SDavid Blaikie   if (DIE *Die = getDIE(GV))
9337c52310SDavid Blaikie     return Die;
9437c52310SDavid Blaikie 
95e686f159SDuncan P. N. Exon Smith   assert(GV);
9637c52310SDavid Blaikie 
97be9e4fe7SDuncan P. N. Exon Smith   auto *GVContext = GV->getScope();
98be9e4fe7SDuncan P. N. Exon Smith   auto *GTy = DD->resolve(GV->getType());
9937c52310SDavid Blaikie 
10037c52310SDavid Blaikie   // Construct the context before querying for the existence of the DIE in
10137c52310SDavid Blaikie   // case such construction creates the DIE.
10272da9391SAmjad Aboud   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
10337c52310SDavid Blaikie 
10472da9391SAmjad Aboud   // Add to map.
10572da9391SAmjad Aboud   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
106a9308c49SDuncan P. N. Exon Smith   DIScope *DeclContext;
107b1055640SDuncan P. N. Exon Smith   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
108b1055640SDuncan P. N. Exon Smith     DeclContext = resolve(SDMDecl->getScope());
109b1055640SDuncan P. N. Exon Smith     assert(SDMDecl->isStaticMember() && "Expected static member decl");
1107348ddaaSDuncan P. N. Exon Smith     assert(GV->isDefinition());
11149cfc8caSDavid Blaikie     // We need the declaration DIE that is in the static member's class.
11249cfc8caSDavid Blaikie     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
11349cfc8caSDavid Blaikie     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
1143502f208SAdrian Prantl     // If the global variable's type is different from the one in the class
1153502f208SAdrian Prantl     // member type, assume that it's more specific and also emit it.
1163502f208SAdrian Prantl     if (GTy != DD->resolve(SDMDecl->getBaseType()))
1173502f208SAdrian Prantl       addType(*VariableDIE, GTy);
11849cfc8caSDavid Blaikie   } else {
1197348ddaaSDuncan P. N. Exon Smith     DeclContext = GV->getScope();
12037c52310SDavid Blaikie     // Add name and type.
1217348ddaaSDuncan P. N. Exon Smith     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
12237c52310SDavid Blaikie     addType(*VariableDIE, GTy);
12337c52310SDavid Blaikie 
12437c52310SDavid Blaikie     // Add scoping info.
1257348ddaaSDuncan P. N. Exon Smith     if (!GV->isLocalToUnit())
12637c52310SDavid Blaikie       addFlag(*VariableDIE, dwarf::DW_AT_external);
12737c52310SDavid Blaikie 
12837c52310SDavid Blaikie     // Add line number info.
12937c52310SDavid Blaikie     addSourceLine(*VariableDIE, GV);
13037c52310SDavid Blaikie   }
13137c52310SDavid Blaikie 
1327348ddaaSDuncan P. N. Exon Smith   if (!GV->isDefinition())
13349cfc8caSDavid Blaikie     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
134877354a2SDavid Blaikie   else
135877354a2SDavid Blaikie     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
13649cfc8caSDavid Blaikie 
1373c989984SVictor Leschuk   if (uint32_t AlignInBytes = GV->getAlignInBytes())
1383c989984SVictor Leschuk     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1393c989984SVictor Leschuk             AlignInBytes);
1403c989984SVictor Leschuk 
14137c52310SDavid Blaikie   // Add location.
14237c52310SDavid Blaikie   bool addToAccelTable = false;
143bceaaa96SAdrian Prantl   DIELoc *Loc = nullptr;
144bceaaa96SAdrian Prantl   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
145bceaaa96SAdrian Prantl   for (const auto &GE : GlobalExprs) {
146bceaaa96SAdrian Prantl     const GlobalVariable *Global = GE.Var;
147bceaaa96SAdrian Prantl     const DIExpression *Expr = GE.Expr;
148b216e3e9SAdrian Prantl 
149d4135bbcSPeter Collingbourne     // For compatibility with DWARF 3 and earlier,
150d4135bbcSPeter Collingbourne     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
151d4135bbcSPeter Collingbourne     // DW_AT_const_value(X).
152bceaaa96SAdrian Prantl     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
153b216e3e9SAdrian Prantl       addToAccelTable = true;
154d4135bbcSPeter Collingbourne       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
155b216e3e9SAdrian Prantl       break;
156b216e3e9SAdrian Prantl     }
157b216e3e9SAdrian Prantl 
158bceaaa96SAdrian Prantl     // We cannot describe the location of dllimport'd variables: the
159bceaaa96SAdrian Prantl     // computation of their address requires loads from the IAT.
160b216e3e9SAdrian Prantl     if (Global && Global->hasDLLImportStorageClass())
161b216e3e9SAdrian Prantl       continue;
162b216e3e9SAdrian Prantl 
163b216e3e9SAdrian Prantl     // Nothing to describe without address or constant.
164b216e3e9SAdrian Prantl     if (!Global && (!Expr || !Expr->isConstant()))
165b216e3e9SAdrian Prantl       continue;
166b216e3e9SAdrian Prantl 
167bceaaa96SAdrian Prantl     if (!Loc) {
168b216e3e9SAdrian Prantl       addToAccelTable = true;
169bceaaa96SAdrian Prantl       Loc = new (DIEValueAllocator) DIELoc;
170bceaaa96SAdrian Prantl       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
171bceaaa96SAdrian Prantl     }
172b216e3e9SAdrian Prantl 
173bceaaa96SAdrian Prantl     if (Global) {
174cca5f68eSDuncan P. N. Exon Smith       const MCSymbol *Sym = Asm->getSymbol(Global);
175cca5f68eSDuncan P. N. Exon Smith       if (Global->isThreadLocal()) {
1761e859582SChih-Hung Hsieh         if (Asm->TM.Options.EmulatedTLS) {
1771e859582SChih-Hung Hsieh           // TODO: add debug info for emulated thread local mode.
1781e859582SChih-Hung Hsieh         } else {
17937c52310SDavid Blaikie           // FIXME: Make this work with -gsplit-dwarf.
18037c52310SDavid Blaikie           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
18137c52310SDavid Blaikie           assert((PointerSize == 4 || PointerSize == 8) &&
18237c52310SDavid Blaikie                  "Add support for other sizes if necessary");
18337c52310SDavid Blaikie           // Based on GCC's support for TLS:
18437c52310SDavid Blaikie           if (!DD->useSplitDwarf()) {
18537c52310SDavid Blaikie             // 1) Start with a constNu of the appropriate pointer size
186bceaaa96SAdrian Prantl             addUInt(*Loc, dwarf::DW_FORM_data1,
187bceaaa96SAdrian Prantl                     PointerSize == 4 ? dwarf::DW_OP_const4u
18854511353SDehao Chen                                      : dwarf::DW_OP_const8u);
18937c52310SDavid Blaikie             // 2) containing the (relocated) offset of the TLS variable
19037c52310SDavid Blaikie             //    within the module's TLS block.
19137c52310SDavid Blaikie             addExpr(*Loc, dwarf::DW_FORM_udata,
19237c52310SDavid Blaikie                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
19337c52310SDavid Blaikie           } else {
19437c52310SDavid Blaikie             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
19537c52310SDavid Blaikie             addUInt(*Loc, dwarf::DW_FORM_udata,
19637c52310SDavid Blaikie                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
19737c52310SDavid Blaikie           }
19878cc0821SPaul Robinson           // 3) followed by an OP to make the debugger do a TLS lookup.
19978cc0821SPaul Robinson           addUInt(*Loc, dwarf::DW_FORM_data1,
20078cc0821SPaul Robinson                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
20178cc0821SPaul Robinson                                         : dwarf::DW_OP_form_tls_address);
2021e859582SChih-Hung Hsieh         }
20337c52310SDavid Blaikie       } else {
20437c52310SDavid Blaikie         DD->addArangeLabel(SymbolCU(this, Sym));
20537c52310SDavid Blaikie         addOpAddress(*Loc, Sym);
20637c52310SDavid Blaikie       }
207bceaaa96SAdrian Prantl     }
208d4135bbcSPeter Collingbourne     if (Expr) {
209bceaaa96SAdrian Prantl       DwarfExpr->addFragmentOffset(Expr);
210a63b8e82SAdrian Prantl       DwarfExpr->addExpression(Expr);
211d4135bbcSPeter Collingbourne     }
212d4135bbcSPeter Collingbourne   }
213bceaaa96SAdrian Prantl   if (Loc)
214bceaaa96SAdrian Prantl     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
215d4135bbcSPeter Collingbourne 
21643d1e453SPaul Robinson   if (DD->useAllLinkageNames())
2177348ddaaSDuncan P. N. Exon Smith     addLinkageName(*VariableDIE, GV->getLinkageName());
21837c52310SDavid Blaikie 
21937c52310SDavid Blaikie   if (addToAccelTable) {
2207348ddaaSDuncan P. N. Exon Smith     DD->addAccelName(GV->getName(), *VariableDIE);
22137c52310SDavid Blaikie 
22237c52310SDavid Blaikie     // If the linkage name is different than the name, go ahead and output
22337c52310SDavid Blaikie     // that as well into the name table.
2247348ddaaSDuncan P. N. Exon Smith     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
2257348ddaaSDuncan P. N. Exon Smith       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
22637c52310SDavid Blaikie   }
22737c52310SDavid Blaikie 
22849cfc8caSDavid Blaikie   return VariableDIE;
22937c52310SDavid Blaikie }
23037c52310SDavid Blaikie 
23137c52310SDavid Blaikie void DwarfCompileUnit::addRange(RangeSpan Range) {
23237c52310SDavid Blaikie   bool SameAsPrevCU = this == DD->getPrevCU();
23337c52310SDavid Blaikie   DD->setPrevCU(this);
23437c52310SDavid Blaikie   // If we have no current ranges just add the range and return, otherwise,
23537c52310SDavid Blaikie   // check the current section and CU against the previous section and CU we
23637c52310SDavid Blaikie   // emitted into and the subprogram was contained within. If these are the
23737c52310SDavid Blaikie   // same then extend our current range, otherwise add this as a new range.
23837c52310SDavid Blaikie   if (CURanges.empty() || !SameAsPrevCU ||
23937c52310SDavid Blaikie       (&CURanges.back().getEnd()->getSection() !=
24037c52310SDavid Blaikie        &Range.getEnd()->getSection())) {
24137c52310SDavid Blaikie     CURanges.push_back(Range);
24237c52310SDavid Blaikie     return;
24337c52310SDavid Blaikie   }
24437c52310SDavid Blaikie 
24537c52310SDavid Blaikie   CURanges.back().setEnd(Range.getEnd());
24637c52310SDavid Blaikie }
24737c52310SDavid Blaikie 
248063d725fSRafael Espindola void DwarfCompileUnit::initStmtList() {
24937c52310SDavid Blaikie   // Define start line table label for each Compile Unit.
25037c52310SDavid Blaikie   MCSymbol *LineTableStartSym =
2519ff69c8fSLang Hames       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
25237c52310SDavid Blaikie 
25337c52310SDavid Blaikie   // DW_AT_stmt_list is a offset of line number information for this
25437c52310SDavid Blaikie   // compile unit in debug_line section. For split dwarf this is
25537c52310SDavid Blaikie   // left in the skeleton CU and so not included.
25637c52310SDavid Blaikie   // The line table entries are not always emitted in assembly, so it
25737c52310SDavid Blaikie   // is not okay to use line_table_start here.
258063d725fSRafael Espindola   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2594fb1f9cdSDuncan P. N. Exon Smith   StmtListValue =
26035630c33SGreg Clayton       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
261063d725fSRafael Espindola                       TLOF.getDwarfLineSection()->getBeginSymbol());
26237c52310SDavid Blaikie }
26337c52310SDavid Blaikie 
26437c52310SDavid Blaikie void DwarfCompileUnit::applyStmtList(DIE &D) {
2654fb1f9cdSDuncan P. N. Exon Smith   D.addValue(DIEValueAllocator, *StmtListValue);
26637c52310SDavid Blaikie }
26737c52310SDavid Blaikie 
26814499a7dSDavid Blaikie void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
26914499a7dSDavid Blaikie                                        const MCSymbol *End) {
27014499a7dSDavid Blaikie   assert(Begin && "Begin label should not be null!");
27114499a7dSDavid Blaikie   assert(End && "End label should not be null!");
27214499a7dSDavid Blaikie   assert(Begin->isDefined() && "Invalid starting label");
27314499a7dSDavid Blaikie   assert(End->isDefined() && "Invalid end label");
27414499a7dSDavid Blaikie 
27514499a7dSDavid Blaikie   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
27614499a7dSDavid Blaikie   if (DD->getDwarfVersion() < 4)
27714499a7dSDavid Blaikie     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
27814499a7dSDavid Blaikie   else
27914499a7dSDavid Blaikie     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
28014499a7dSDavid Blaikie }
28114499a7dSDavid Blaikie 
282cda2aa82SDavid Blaikie // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
283cda2aa82SDavid Blaikie // and DW_AT_high_pc attributes. If there are global variables in this
284cda2aa82SDavid Blaikie // scope then create and insert DIEs for these variables.
285a9308c49SDuncan P. N. Exon Smith DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
2863a443c29SDavid Blaikie   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
287cda2aa82SDavid Blaikie 
28807c03d31SRafael Espindola   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
289c53e18d9SDavid Blaikie   if (DD->useAppleExtensionAttributes() &&
290c53e18d9SDavid Blaikie       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
291cda2aa82SDavid Blaikie           *DD->getCurrentFunction()))
292cda2aa82SDavid Blaikie     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
293cda2aa82SDavid Blaikie 
294cda2aa82SDavid Blaikie   // Only include DW_AT_frame_base in full debug info
2953a443c29SDavid Blaikie   if (!includeMinimalInlineScopes()) {
296d4e723f2SEric Christopher     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
297cda2aa82SDavid Blaikie     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
2988efadbf8SAdrian Prantl     if (RI->isPhysicalRegister(Location.getReg()))
299cda2aa82SDavid Blaikie       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
300cda2aa82SDavid Blaikie   }
301cda2aa82SDavid Blaikie 
302cda2aa82SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
303cda2aa82SDavid Blaikie   // to have concrete versions of our DW_TAG_subprogram nodes.
304cda2aa82SDavid Blaikie   DD->addSubprogramNames(SP, *SPDie);
305cda2aa82SDavid Blaikie 
306cda2aa82SDavid Blaikie   return *SPDie;
307cda2aa82SDavid Blaikie }
308cda2aa82SDavid Blaikie 
3099c65b135SDavid Blaikie // Construct a DIE for this scope.
3109c65b135SDavid Blaikie void DwarfCompileUnit::constructScopeDIE(
311827200c8SDuncan P. N. Exon Smith     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
3129c65b135SDavid Blaikie   if (!Scope || !Scope->getScopeNode())
3139c65b135SDavid Blaikie     return;
3149c65b135SDavid Blaikie 
315be9e4fe7SDuncan P. N. Exon Smith   auto *DS = Scope->getScopeNode();
3169c65b135SDavid Blaikie 
317a9308c49SDuncan P. N. Exon Smith   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
3189c65b135SDavid Blaikie          "Only handle inlined subprograms here, use "
3199c65b135SDavid Blaikie          "constructSubprogramScopeDIE for non-inlined "
3209c65b135SDavid Blaikie          "subprograms");
3219c65b135SDavid Blaikie 
322827200c8SDuncan P. N. Exon Smith   SmallVector<DIE *, 8> Children;
3239c65b135SDavid Blaikie 
3249c65b135SDavid Blaikie   // We try to create the scope DIE first, then the children DIEs. This will
3259c65b135SDavid Blaikie   // avoid creating un-used children then removing them later when we find out
3269c65b135SDavid Blaikie   // the scope DIE is null.
327827200c8SDuncan P. N. Exon Smith   DIE *ScopeDIE;
328a9308c49SDuncan P. N. Exon Smith   if (Scope->getParent() && isa<DISubprogram>(DS)) {
32901b48a84SDavid Blaikie     ScopeDIE = constructInlinedScopeDIE(Scope);
3309c65b135SDavid Blaikie     if (!ScopeDIE)
3319c65b135SDavid Blaikie       return;
3329c65b135SDavid Blaikie     // We create children when the scope DIE is not null.
3338b2fdb83SDavid Blaikie     createScopeChildrenDIE(Scope, Children);
3349c65b135SDavid Blaikie   } else {
3359c65b135SDavid Blaikie     // Early exit when we know the scope DIE is going to be null.
3369c65b135SDavid Blaikie     if (DD->isLexicalScopeDIENull(Scope))
3379c65b135SDavid Blaikie       return;
3389c65b135SDavid Blaikie 
33972da9391SAmjad Aboud     unsigned ChildScopeCount;
3409c65b135SDavid Blaikie 
3419c65b135SDavid Blaikie     // We create children here when we know the scope DIE is not going to be
3429c65b135SDavid Blaikie     // null and the children will be added to the scope DIE.
34372da9391SAmjad Aboud     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
34472da9391SAmjad Aboud 
34572da9391SAmjad Aboud     // Skip imported directives in gmlt-like data.
34672da9391SAmjad Aboud     if (!includeMinimalInlineScopes()) {
34772da9391SAmjad Aboud       // There is no need to emit empty lexical block DIE.
34872da9391SAmjad Aboud       for (const auto *IE : ImportedEntities[DS])
34972da9391SAmjad Aboud         Children.push_back(
35072da9391SAmjad Aboud             constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
35172da9391SAmjad Aboud     }
3523a443c29SDavid Blaikie 
3539c65b135SDavid Blaikie     // If there are only other scopes as children, put them directly in the
3549c65b135SDavid Blaikie     // parent instead, as this scope would serve no purpose.
35572da9391SAmjad Aboud     if (Children.size() == ChildScopeCount) {
3569c65b135SDavid Blaikie       FinalChildren.insert(FinalChildren.end(),
3579c65b135SDavid Blaikie                            std::make_move_iterator(Children.begin()),
3589c65b135SDavid Blaikie                            std::make_move_iterator(Children.end()));
3599c65b135SDavid Blaikie       return;
3609c65b135SDavid Blaikie     }
3610fbf8bdbSDavid Blaikie     ScopeDIE = constructLexicalScopeDIE(Scope);
3629c65b135SDavid Blaikie     assert(ScopeDIE && "Scope DIE should not be null.");
3639c65b135SDavid Blaikie   }
3649c65b135SDavid Blaikie 
3659c65b135SDavid Blaikie   // Add children
3669c65b135SDavid Blaikie   for (auto &I : Children)
3679c65b135SDavid Blaikie     ScopeDIE->addChild(std::move(I));
3689c65b135SDavid Blaikie 
3699c65b135SDavid Blaikie   FinalChildren.push_back(std::move(ScopeDIE));
3709c65b135SDavid Blaikie }
3719c65b135SDavid Blaikie 
3725b02a19fSDavid Blaikie void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
3735b02a19fSDavid Blaikie                                          SmallVector<RangeSpan, 2> Range) {
374063d725fSRafael Espindola   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
375063d725fSRafael Espindola 
37652400200SDavid Blaikie   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
37752400200SDavid Blaikie   // emitting it appropriately.
378063d725fSRafael Espindola   const MCSymbol *RangeSectionSym =
379063d725fSRafael Espindola       TLOF.getDwarfRangesSection()->getBeginSymbol();
38052400200SDavid Blaikie 
3819ab09237SRafael Espindola   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
3825b02a19fSDavid Blaikie 
38352400200SDavid Blaikie   // Under fission, ranges are specified by constant offsets relative to the
38452400200SDavid Blaikie   // CU's DW_AT_GNU_ranges_base.
3855b02a19fSDavid Blaikie   if (isDwoUnit())
3865b02a19fSDavid Blaikie     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3875b02a19fSDavid Blaikie                     RangeSectionSym);
38852400200SDavid Blaikie   else
3895b02a19fSDavid Blaikie     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3905b02a19fSDavid Blaikie                     RangeSectionSym);
39152400200SDavid Blaikie 
39252400200SDavid Blaikie   // Add the range list to the set of ranges to be emitted.
393542616d4SDavid Blaikie   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
39452400200SDavid Blaikie }
39552400200SDavid Blaikie 
396de12375cSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
3975b02a19fSDavid Blaikie     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
3985b02a19fSDavid Blaikie   if (Ranges.size() == 1) {
3995b02a19fSDavid Blaikie     const auto &single = Ranges.front();
4005b02a19fSDavid Blaikie     attachLowHighPC(Die, single.getStart(), single.getEnd());
4015b02a19fSDavid Blaikie   } else
4025b02a19fSDavid Blaikie     addScopeRangeList(Die, std::move(Ranges));
4035b02a19fSDavid Blaikie }
4045b02a19fSDavid Blaikie 
4055b02a19fSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
406de12375cSDavid Blaikie     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
4075b02a19fSDavid Blaikie   SmallVector<RangeSpan, 2> List;
4085b02a19fSDavid Blaikie   List.reserve(Ranges.size());
4095b02a19fSDavid Blaikie   for (const InsnRange &R : Ranges)
4105b02a19fSDavid Blaikie     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
4115b02a19fSDavid Blaikie                              DD->getLabelAfterInsn(R.second)));
4125b02a19fSDavid Blaikie   attachRangesOrLowHighPC(Die, std::move(List));
413de12375cSDavid Blaikie }
414de12375cSDavid Blaikie 
41501b48a84SDavid Blaikie // This scope represents inlined body of a function. Construct DIE to
41601b48a84SDavid Blaikie // represent this concrete inlined copy of the function.
417827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
41801b48a84SDavid Blaikie   assert(Scope->getScopeNode());
419be9e4fe7SDuncan P. N. Exon Smith   auto *DS = Scope->getScopeNode();
420be9e4fe7SDuncan P. N. Exon Smith   auto *InlinedSP = getDISubprogram(DS);
42101b48a84SDavid Blaikie   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
42201b48a84SDavid Blaikie   // was inlined from another compile unit.
423488393f8SDavid Blaikie   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
42401b48a84SDavid Blaikie   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
42501b48a84SDavid Blaikie 
426827200c8SDuncan P. N. Exon Smith   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
42701b48a84SDavid Blaikie   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
42801b48a84SDavid Blaikie 
42901b48a84SDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
43001b48a84SDavid Blaikie 
43101b48a84SDavid Blaikie   // Add the call site information to the DIE.
432a9308c49SDuncan P. N. Exon Smith   const DILocation *IA = Scope->getInlinedAt();
43301b48a84SDavid Blaikie   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
434b7e221baSDuncan P. N. Exon Smith           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
435b7e221baSDuncan P. N. Exon Smith   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
4366e0c8446SDehao Chen   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
43754511353SDehao Chen     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
43854511353SDehao Chen             IA->getDiscriminator());
43901b48a84SDavid Blaikie 
44001b48a84SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
44101b48a84SDavid Blaikie   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
44201b48a84SDavid Blaikie   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
44301b48a84SDavid Blaikie 
44401b48a84SDavid Blaikie   return ScopeDIE;
44501b48a84SDavid Blaikie }
44601b48a84SDavid Blaikie 
4470fbf8bdbSDavid Blaikie // Construct new DW_TAG_lexical_block for this scope and attach
4480fbf8bdbSDavid Blaikie // DW_AT_low_pc/DW_AT_high_pc labels.
449827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
4500fbf8bdbSDavid Blaikie   if (DD->isLexicalScopeDIENull(Scope))
4510fbf8bdbSDavid Blaikie     return nullptr;
4520fbf8bdbSDavid Blaikie 
453827200c8SDuncan P. N. Exon Smith   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
4540fbf8bdbSDavid Blaikie   if (Scope->isAbstractScope())
4550fbf8bdbSDavid Blaikie     return ScopeDIE;
4560fbf8bdbSDavid Blaikie 
4570fbf8bdbSDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
4580fbf8bdbSDavid Blaikie 
4590fbf8bdbSDavid Blaikie   return ScopeDIE;
4600fbf8bdbSDavid Blaikie }
4610fbf8bdbSDavid Blaikie 
462ee7df553SDavid Blaikie /// constructVariableDIE - Construct a DIE for the given DbgVariable.
463827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
464ee7df553SDavid Blaikie   auto D = constructVariableDIEImpl(DV, Abstract);
465ee7df553SDavid Blaikie   DV.setDIE(*D);
466ee7df553SDavid Blaikie   return D;
467ee7df553SDavid Blaikie }
468ee7df553SDavid Blaikie 
469827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
470ee7df553SDavid Blaikie                                                 bool Abstract) {
471ee7df553SDavid Blaikie   // Define variable debug information entry.
472827200c8SDuncan P. N. Exon Smith   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
473ee7df553SDavid Blaikie 
474ee7df553SDavid Blaikie   if (Abstract) {
475ee7df553SDavid Blaikie     applyVariableAttributes(DV, *VariableDie);
476ee7df553SDavid Blaikie     return VariableDie;
477ee7df553SDavid Blaikie   }
478ee7df553SDavid Blaikie 
479ee7df553SDavid Blaikie   // Add variable address.
480ee7df553SDavid Blaikie 
481364a3005SDuncan P. N. Exon Smith   unsigned Offset = DV.getDebugLocListIndex();
482ee7df553SDavid Blaikie   if (Offset != ~0U) {
483ee7df553SDavid Blaikie     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
484ee7df553SDavid Blaikie     return VariableDie;
485ee7df553SDavid Blaikie   }
486ee7df553SDavid Blaikie 
487ee7df553SDavid Blaikie   // Check if variable is described by a DBG_VALUE instruction.
488ee7df553SDavid Blaikie   if (const MachineInstr *DVInsn = DV.getMInsn()) {
489ee7df553SDavid Blaikie     assert(DVInsn->getNumOperands() == 4);
490ee7df553SDavid Blaikie     if (DVInsn->getOperand(0).isReg()) {
491ee7df553SDavid Blaikie       const MachineOperand RegOp = DVInsn->getOperand(0);
492ee7df553SDavid Blaikie       // If the second operand is an immediate, this is an indirect value.
493ee7df553SDavid Blaikie       if (DVInsn->getOperand(1).isImm()) {
494ee7df553SDavid Blaikie         MachineLocation Location(RegOp.getReg(),
495ee7df553SDavid Blaikie                                  DVInsn->getOperand(1).getImm());
496ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, Location);
497ee7df553SDavid Blaikie       } else if (RegOp.getReg())
498ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
4993b89e663SAdrian Prantl     } else if (DVInsn->getOperand(0).isImm()) {
5003b89e663SAdrian Prantl       // This variable is described by a single constant.
5013b89e663SAdrian Prantl       // Check whether it has a DIExpression.
5023b89e663SAdrian Prantl       auto *Expr = DV.getSingleExpression();
5033b89e663SAdrian Prantl       if (Expr && Expr->getNumElements()) {
5043b89e663SAdrian Prantl         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
5053b89e663SAdrian Prantl         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
5063b89e663SAdrian Prantl         // If there is an expression, emit raw unsigned bytes.
5078fafb8d3SAdrian Prantl         DwarfExpr.addFragmentOffset(Expr);
508a63b8e82SAdrian Prantl         DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
509a63b8e82SAdrian Prantl         DwarfExpr.addExpression(Expr);
510bceaaa96SAdrian Prantl         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
5113b89e663SAdrian Prantl       } else
512ee7df553SDavid Blaikie         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
5133b89e663SAdrian Prantl     } else if (DVInsn->getOperand(0).isFPImm())
514ee7df553SDavid Blaikie       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
515ee7df553SDavid Blaikie     else if (DVInsn->getOperand(0).isCImm())
516ee7df553SDavid Blaikie       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
517ee7df553SDavid Blaikie                        DV.getType());
518ee7df553SDavid Blaikie 
519ee7df553SDavid Blaikie     return VariableDie;
520ee7df553SDavid Blaikie   }
521ee7df553SDavid Blaikie 
522ee7df553SDavid Blaikie   // .. else use frame index.
52367c24422SAdrian Prantl   if (!DV.hasFrameIndexExprs())
524ca7e4702SAdrian Prantl     return VariableDie;
525ca7e4702SAdrian Prantl 
526e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
527ca7e4702SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
52867c24422SAdrian Prantl   for (auto &Fragment : DV.getFrameIndexExprs()) {
529ee7df553SDavid Blaikie     unsigned FrameReg = 0;
5306825fb64SAdrian Prantl     const DIExpression *Expr = Fragment.Expr;
531d4e723f2SEric Christopher     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
53267c24422SAdrian Prantl     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
5336825fb64SAdrian Prantl     DwarfExpr.addFragmentOffset(Expr);
534956484b7SAdrian Prantl     SmallVector<uint64_t, 8> Ops;
535ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
536956484b7SAdrian Prantl     Ops.push_back(Offset);
5376825fb64SAdrian Prantl     Ops.append(Expr->elements_begin(), Expr->elements_end());
5386825fb64SAdrian Prantl     DIExpressionCursor Cursor(Ops);
539c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
540c12cee36SAdrian Prantl     DwarfExpr.addMachineRegExpression(
541c12cee36SAdrian Prantl         *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
5426825fb64SAdrian Prantl     DwarfExpr.addExpression(std::move(Cursor));
543ee7df553SDavid Blaikie   }
544bceaaa96SAdrian Prantl   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
545ee7df553SDavid Blaikie 
546ee7df553SDavid Blaikie   return VariableDie;
547ee7df553SDavid Blaikie }
548ee7df553SDavid Blaikie 
549827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
550827200c8SDuncan P. N. Exon Smith                                             const LexicalScope &Scope,
551827200c8SDuncan P. N. Exon Smith                                             DIE *&ObjectPointer) {
5524a1a44e3SDavid Blaikie   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
5534a1a44e3SDavid Blaikie   if (DV.isObjectPointer())
554827200c8SDuncan P. N. Exon Smith     ObjectPointer = Var;
5554a1a44e3SDavid Blaikie   return Var;
5564a1a44e3SDavid Blaikie }
5574a1a44e3SDavid Blaikie 
558827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
559827200c8SDuncan P. N. Exon Smith                                               SmallVectorImpl<DIE *> &Children,
56072da9391SAmjad Aboud                                               unsigned *ChildScopeCount) {
5618b2fdb83SDavid Blaikie   DIE *ObjectPointer = nullptr;
5628b2fdb83SDavid Blaikie 
56380e5b1ebSDavid Blaikie   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
5648b2fdb83SDavid Blaikie     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
5658b2fdb83SDavid Blaikie 
56672da9391SAmjad Aboud   unsigned ChildCountWithoutScopes = Children.size();
5678b2fdb83SDavid Blaikie 
5688b2fdb83SDavid Blaikie   for (LexicalScope *LS : Scope->getChildren())
5698b2fdb83SDavid Blaikie     constructScopeDIE(LS, Children);
5708b2fdb83SDavid Blaikie 
57172da9391SAmjad Aboud   if (ChildScopeCount)
57272da9391SAmjad Aboud     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
57372da9391SAmjad Aboud 
5748b2fdb83SDavid Blaikie   return ObjectPointer;
5758b2fdb83SDavid Blaikie }
5768b2fdb83SDavid Blaikie 
5773e3eb33eSDavid Blaikie void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
5781d072348SDavid Blaikie   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
5791d072348SDavid Blaikie 
5803e3eb33eSDavid Blaikie   if (Scope) {
5813e3eb33eSDavid Blaikie     assert(!Scope->getInlinedAt());
5823e3eb33eSDavid Blaikie     assert(!Scope->isAbstractScope());
5831dd573dbSDavid Blaikie     // Collect lexical scope children first.
5841dd573dbSDavid Blaikie     // ObjectPointer might be a local (non-argument) local variable if it's a
5851dd573dbSDavid Blaikie     // block's synthetic this pointer.
5861dd573dbSDavid Blaikie     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
5871dd573dbSDavid Blaikie       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
5883e3eb33eSDavid Blaikie   }
5893e3eb33eSDavid Blaikie 
5903e3eb33eSDavid Blaikie   // If this is a variadic function, add an unspecified parameter.
5913e3eb33eSDavid Blaikie   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
5921dd573dbSDavid Blaikie 
5931d072348SDavid Blaikie   // If we have a single element of null, it is a function that returns void.
5941d072348SDavid Blaikie   // If we have more than one elements and the last one is null, it is a
5951d072348SDavid Blaikie   // variadic function.
596000fa2c6SDuncan P. N. Exon Smith   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
5973a443c29SDavid Blaikie       !includeMinimalInlineScopes())
598827200c8SDuncan P. N. Exon Smith     ScopeDIE.addChild(
599827200c8SDuncan P. N. Exon Smith         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
6001d072348SDavid Blaikie }
6011d072348SDavid Blaikie 
60278b65b6fSDavid Blaikie DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
60378b65b6fSDavid Blaikie                                                  DIE &ScopeDIE) {
60478b65b6fSDavid Blaikie   // We create children when the scope DIE is not null.
605827200c8SDuncan P. N. Exon Smith   SmallVector<DIE *, 8> Children;
60678b65b6fSDavid Blaikie   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
60778b65b6fSDavid Blaikie 
60878b65b6fSDavid Blaikie   // Add children
60978b65b6fSDavid Blaikie   for (auto &I : Children)
61078b65b6fSDavid Blaikie     ScopeDIE.addChild(std::move(I));
61178b65b6fSDavid Blaikie 
61278b65b6fSDavid Blaikie   return ObjectPointer;
61378b65b6fSDavid Blaikie }
61478b65b6fSDavid Blaikie 
61554511353SDehao Chen void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
61654511353SDehao Chen     LexicalScope *Scope) {
617488393f8SDavid Blaikie   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
61849be5b35SDavid Blaikie   if (AbsDef)
61949be5b35SDavid Blaikie     return;
62049be5b35SDavid Blaikie 
621a9308c49SDuncan P. N. Exon Smith   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
62258410f24SDavid Blaikie 
62358410f24SDavid Blaikie   DIE *ContextDIE;
62458410f24SDavid Blaikie 
6253a443c29SDavid Blaikie   if (includeMinimalInlineScopes())
6263a443c29SDavid Blaikie     ContextDIE = &getUnitDie();
62758410f24SDavid Blaikie   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
6287c60f20eSDuncan P. N. Exon Smith   // the important distinction that the debug node is not associated with the
6297c60f20eSDuncan P. N. Exon Smith   // DIE (since the debug node will be associated with the concrete DIE, if
63058410f24SDavid Blaikie   // any). It could be refactored to some common utility function.
631537b4a81SDuncan P. N. Exon Smith   else if (auto *SPDecl = SP->getDeclaration()) {
63258410f24SDavid Blaikie     ContextDIE = &getUnitDie();
63358410f24SDavid Blaikie     getOrCreateSubprogramDIE(SPDecl);
63458410f24SDavid Blaikie   } else
635537b4a81SDuncan P. N. Exon Smith     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
63658410f24SDavid Blaikie 
6377c60f20eSDuncan P. N. Exon Smith   // Passing null as the associated node because the abstract definition
63858410f24SDavid Blaikie   // shouldn't be found by lookup.
6397c60f20eSDuncan P. N. Exon Smith   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
64049be5b35SDavid Blaikie   applySubprogramAttributesToDefinition(SP, *AbsDef);
64158410f24SDavid Blaikie 
6423a443c29SDavid Blaikie   if (!includeMinimalInlineScopes())
64349be5b35SDavid Blaikie     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
64449be5b35SDavid Blaikie   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
64549be5b35SDavid Blaikie     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
64658410f24SDavid Blaikie }
64758410f24SDavid Blaikie 
648827200c8SDuncan P. N. Exon Smith DIE *DwarfCompileUnit::constructImportedEntityDIE(
649827200c8SDuncan P. N. Exon Smith     const DIImportedEntity *Module) {
65072da9391SAmjad Aboud   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
65172da9391SAmjad Aboud   insertDIE(Module, IMDie);
652987fe227SFrederic Riss   DIE *EntityDie;
653de8e4273SDuncan P. N. Exon Smith   auto *Entity = resolve(Module->getEntity());
654a9308c49SDuncan P. N. Exon Smith   if (auto *NS = dyn_cast<DINamespace>(Entity))
655e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateNameSpace(NS);
65608a388baSAdrian Prantl   else if (auto *M = dyn_cast<DIModule>(Entity))
65708a388baSAdrian Prantl     EntityDie = getOrCreateModule(M);
658a9308c49SDuncan P. N. Exon Smith   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
659e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateSubprogramDIE(SP);
660a9308c49SDuncan P. N. Exon Smith   else if (auto *T = dyn_cast<DIType>(Entity))
661e686f159SDuncan P. N. Exon Smith     EntityDie = getOrCreateTypeDIE(T);
662a9308c49SDuncan P. N. Exon Smith   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
663bceaaa96SAdrian Prantl     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
664987fe227SFrederic Riss   else
665987fe227SFrederic Riss     EntityDie = getDIE(Entity);
666987fe227SFrederic Riss   assert(EntityDie);
667*d63bfd21SAdrian Prantl   auto *File = Module->getFile();
668*d63bfd21SAdrian Prantl   addSourceLine(*IMDie, Module->getLine(), File ? File->getFilename() : "",
669*d63bfd21SAdrian Prantl                 File ? File->getDirectory() : "");
670987fe227SFrederic Riss   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
671de8e4273SDuncan P. N. Exon Smith   StringRef Name = Module->getName();
672987fe227SFrederic Riss   if (!Name.empty())
673987fe227SFrederic Riss     addString(*IMDie, dwarf::DW_AT_name, Name);
674987fe227SFrederic Riss 
675987fe227SFrederic Riss   return IMDie;
676987fe227SFrederic Riss }
677987fe227SFrederic Riss 
678a9308c49SDuncan P. N. Exon Smith void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
67972da9391SAmjad Aboud   DIE *D = getDIE(SP);
680488393f8SDavid Blaikie   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
68172da9391SAmjad Aboud     if (D)
6824191cbceSDavid Blaikie       // If this subprogram has an abstract definition, reference that
6834191cbceSDavid Blaikie       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
68472da9391SAmjad Aboud   } else {
6853e3eb33eSDavid Blaikie     assert(D || includeMinimalInlineScopes());
68672da9391SAmjad Aboud     if (D)
6874191cbceSDavid Blaikie       // And attach the attributes
6884191cbceSDavid Blaikie       applySubprogramAttributesToDefinition(SP, *D);
6894191cbceSDavid Blaikie   }
6904191cbceSDavid Blaikie }
6914191cbceSDavid Blaikie 
692488393f8SDavid Blaikie void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) {
693488393f8SDavid Blaikie   DbgVariable *AbsVar = getExistingAbstractVariable(
694488393f8SDavid Blaikie       InlinedVariable(Var.getVariable(), Var.getInlinedAt()));
695488393f8SDavid Blaikie   auto *VariableDie = Var.getDIE();
696488393f8SDavid Blaikie   if (AbsVar && AbsVar->getDIE()) {
697488393f8SDavid Blaikie     addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
698488393f8SDavid Blaikie                       *AbsVar->getDIE());
699488393f8SDavid Blaikie   } else
700488393f8SDavid Blaikie     applyVariableAttributes(Var, *VariableDie);
701488393f8SDavid Blaikie }
702488393f8SDavid Blaikie 
703488393f8SDavid Blaikie DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) {
704488393f8SDavid Blaikie   const DILocalVariable *Cleansed;
705488393f8SDavid Blaikie   return getExistingAbstractVariable(IV, Cleansed);
706488393f8SDavid Blaikie }
707488393f8SDavid Blaikie 
708488393f8SDavid Blaikie // Find abstract variable, if any, associated with Var.
709488393f8SDavid Blaikie DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(
710488393f8SDavid Blaikie     InlinedVariable IV, const DILocalVariable *&Cleansed) {
711488393f8SDavid Blaikie   // More then one inlined variable corresponds to one abstract variable.
712488393f8SDavid Blaikie   Cleansed = IV.first;
713488393f8SDavid Blaikie   auto &AbstractVariables = getAbstractVariables();
714488393f8SDavid Blaikie   auto I = AbstractVariables.find(Cleansed);
715488393f8SDavid Blaikie   if (I != AbstractVariables.end())
716488393f8SDavid Blaikie     return I->second.get();
717488393f8SDavid Blaikie   return nullptr;
718488393f8SDavid Blaikie }
719488393f8SDavid Blaikie 
720488393f8SDavid Blaikie void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var,
721488393f8SDavid Blaikie                                         LexicalScope *Scope) {
722488393f8SDavid Blaikie   assert(Scope && Scope->isAbstractScope());
723488393f8SDavid Blaikie   auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr);
724488393f8SDavid Blaikie   DU->addScopeVariable(Scope, AbsDbgVariable.get());
725488393f8SDavid Blaikie   getAbstractVariables()[Var] = std::move(AbsDbgVariable);
726488393f8SDavid Blaikie }
727488393f8SDavid Blaikie 
728063d725fSRafael Espindola void DwarfCompileUnit::emitHeader(bool UseOffsets) {
729b6726a9eSDavid Blaikie   // Don't bother labeling the .dwo unit, as its offset isn't used.
7303c311148SRafael Espindola   if (!Skeleton) {
7319ab09237SRafael Espindola     LabelBegin = Asm->createTempSymbol("cu_begin");
7329ff69c8fSLang Hames     Asm->OutStreamer->EmitLabel(LabelBegin);
7333c311148SRafael Espindola   }
734ae57e66eSDavid Blaikie 
735cddd6044SPaul Robinson   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
736cddd6044SPaul Robinson                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
737cddd6044SPaul Robinson                                                       : dwarf::DW_UT_compile;
738cddd6044SPaul Robinson   DwarfUnit::emitCommonHeader(UseOffsets, UT);
739ae57e66eSDavid Blaikie }
740ae57e66eSDavid Blaikie 
741192b45c1SDavid Blaikie /// addGlobalName - Add a new global name to the compile unit.
742a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
743a9308c49SDuncan P. N. Exon Smith                                      const DIScope *Context) {
744b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
745192b45c1SDavid Blaikie     return;
746192b45c1SDavid Blaikie   std::string FullName = getParentContextString(Context) + Name.str();
747192b45c1SDavid Blaikie   GlobalNames[FullName] = &Die;
748192b45c1SDavid Blaikie }
749192b45c1SDavid Blaikie 
750a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
751a0e3c751SDavid Blaikie                                                 const DIScope *Context) {
752b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
753a0e3c751SDavid Blaikie     return;
754a0e3c751SDavid Blaikie   std::string FullName = getParentContextString(Context) + Name.str();
755a0e3c751SDavid Blaikie   // Insert, allowing the entry to remain as-is if it's already present
756a0e3c751SDavid Blaikie   // This way the CU-level type DIE is preferred over the "can't describe this
757a0e3c751SDavid Blaikie   // type as a unit offset because it's not really in the CU at all, it's only
758a0e3c751SDavid Blaikie   // in a type unit"
759a0e3c751SDavid Blaikie   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
760a0e3c751SDavid Blaikie }
761a0e3c751SDavid Blaikie 
762192b45c1SDavid Blaikie /// Add a new global type to the unit.
763a9308c49SDuncan P. N. Exon Smith void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
764a9308c49SDuncan P. N. Exon Smith                                      const DIScope *Context) {
765b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
766192b45c1SDavid Blaikie     return;
767b1055640SDuncan P. N. Exon Smith   std::string FullName = getParentContextString(Context) + Ty->getName().str();
768192b45c1SDavid Blaikie   GlobalTypes[FullName] = &Die;
769192b45c1SDavid Blaikie }
770ae57e66eSDavid Blaikie 
771a0e3c751SDavid Blaikie void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
772a0e3c751SDavid Blaikie                                              const DIScope *Context) {
773b3cee2fbSDavid Blaikie   if (!DD->hasDwarfPubSections(includeMinimalInlineScopes()))
774a0e3c751SDavid Blaikie     return;
775a0e3c751SDavid Blaikie   std::string FullName = getParentContextString(Context) + Ty->getName().str();
776a0e3c751SDavid Blaikie   // Insert, allowing the entry to remain as-is if it's already present
777a0e3c751SDavid Blaikie   // This way the CU-level type DIE is preferred over the "can't describe this
778a0e3c751SDavid Blaikie   // type as a unit offset because it's not really in the CU at all, it's only
779a0e3c751SDavid Blaikie   // in a type unit"
780a0e3c751SDavid Blaikie   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
781a0e3c751SDavid Blaikie }
782a0e3c751SDavid Blaikie 
7837d48be2bSDavid Blaikie /// addVariableAddress - Add DW_AT_location attribute for a
7847d48be2bSDavid Blaikie /// DbgVariable based on provided MachineLocation.
7857d48be2bSDavid Blaikie void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
7867d48be2bSDavid Blaikie                                           MachineLocation Location) {
787e6cc531bSDuncan P. N. Exon Smith   if (DV.hasComplexAddress())
7887d48be2bSDavid Blaikie     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
7897d48be2bSDavid Blaikie   else if (DV.isBlockByrefVariable())
7907d48be2bSDavid Blaikie     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
7917d48be2bSDavid Blaikie   else
7925883af3fSAdrian Prantl     addAddress(Die, dwarf::DW_AT_location, Location);
7937d48be2bSDavid Blaikie }
794f7435ee6SDavid Blaikie 
795f7435ee6SDavid Blaikie /// Add an address attribute to a die based on the location provided.
796f7435ee6SDavid Blaikie void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
7975883af3fSAdrian Prantl                                   const MachineLocation &Location) {
798e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
799956484b7SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
800c12cee36SAdrian Prantl   if (Location.isIndirect())
801c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
802f7435ee6SDavid Blaikie 
803956484b7SAdrian Prantl   SmallVector<uint64_t, 8> Ops;
8046825fb64SAdrian Prantl   if (Location.isIndirect() && Location.getOffset()) {
805ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
806956484b7SAdrian Prantl     Ops.push_back(Location.getOffset());
807956484b7SAdrian Prantl   }
808956484b7SAdrian Prantl   DIExpressionCursor Cursor(Ops);
809956484b7SAdrian Prantl   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
810c12cee36SAdrian Prantl   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
811ab255fcdSAdrian Prantl     return;
812956484b7SAdrian Prantl   DwarfExpr.addExpression(std::move(Cursor));
813ab255fcdSAdrian Prantl 
814f7435ee6SDavid Blaikie   // Now attach the location information to the DIE.
815956484b7SAdrian Prantl   addBlock(Die, Attribute, DwarfExpr.finalize());
816f7435ee6SDavid Blaikie }
81777895fb2SDavid Blaikie 
81877895fb2SDavid Blaikie /// Start with the address based on the location provided, and generate the
81977895fb2SDavid Blaikie /// DWARF information necessary to find the actual variable given the extra
82077895fb2SDavid Blaikie /// address information encoded in the DbgVariable, starting from the starting
82177895fb2SDavid Blaikie /// location.  Add the DWARF information to the die.
82277895fb2SDavid Blaikie void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
82377895fb2SDavid Blaikie                                          dwarf::Attribute Attribute,
82477895fb2SDavid Blaikie                                          const MachineLocation &Location) {
825e7e1d0c7SDuncan P. N. Exon Smith   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
8267813d9c9SAdrian Prantl   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
827956484b7SAdrian Prantl   const DIExpression *DIExpr = DV.getSingleExpression();
828956484b7SAdrian Prantl   DwarfExpr.addFragmentOffset(DIExpr);
829c12cee36SAdrian Prantl   if (Location.isIndirect())
830c12cee36SAdrian Prantl     DwarfExpr.setMemoryLocationKind();
831956484b7SAdrian Prantl 
832956484b7SAdrian Prantl   SmallVector<uint64_t, 8> Ops;
8336825fb64SAdrian Prantl   if (Location.isIndirect() && Location.getOffset()) {
834ffc498dfSFlorian Hahn     Ops.push_back(dwarf::DW_OP_plus_uconst);
835956484b7SAdrian Prantl     Ops.push_back(Location.getOffset());
836956484b7SAdrian Prantl   }
837956484b7SAdrian Prantl   Ops.append(DIExpr->elements_begin(), DIExpr->elements_end());
838956484b7SAdrian Prantl   DIExpressionCursor Cursor(Ops);
83996c9ae6aSPeter Collingbourne   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
840c12cee36SAdrian Prantl   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
84154286bdaSAdrian Prantl     return;
842956484b7SAdrian Prantl   DwarfExpr.addExpression(std::move(Cursor));
84377895fb2SDavid Blaikie 
84477895fb2SDavid Blaikie   // Now attach the location information to the DIE.
845956484b7SAdrian Prantl   addBlock(Die, Attribute, DwarfExpr.finalize());
84677895fb2SDavid Blaikie }
8474bc0881aSDavid Blaikie 
8484bc0881aSDavid Blaikie /// Add a Dwarf loclistptr attribute data and value.
8494bc0881aSDavid Blaikie void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
8504bc0881aSDavid Blaikie                                        unsigned Index) {
8514bc0881aSDavid Blaikie   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
8524bc0881aSDavid Blaikie                                                 : dwarf::DW_FORM_data4;
8534fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
8544bc0881aSDavid Blaikie }
85502a6333bSDavid Blaikie 
8568c485b5dSDavid Blaikie void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
85702a6333bSDavid Blaikie                                                DIE &VariableDie) {
85802a6333bSDavid Blaikie   StringRef Name = Var.getName();
85902a6333bSDavid Blaikie   if (!Name.empty())
86002a6333bSDavid Blaikie     addString(VariableDie, dwarf::DW_AT_name, Name);
8613c989984SVictor Leschuk   const auto *DIVar = Var.getVariable();
8623c989984SVictor Leschuk   if (DIVar)
8633c989984SVictor Leschuk     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
8643c989984SVictor Leschuk       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
8653c989984SVictor Leschuk               AlignInBytes);
8663c989984SVictor Leschuk 
8673c989984SVictor Leschuk   addSourceLine(VariableDie, DIVar);
86802a6333bSDavid Blaikie   addType(VariableDie, Var.getType());
86902a6333bSDavid Blaikie   if (Var.isArtificial())
87002a6333bSDavid Blaikie     addFlag(VariableDie, dwarf::DW_AT_artificial);
87102a6333bSDavid Blaikie }
87297802080SDavid Blaikie 
87397802080SDavid Blaikie /// Add a Dwarf expression attribute data and value.
87497802080SDavid Blaikie void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
87597802080SDavid Blaikie                                const MCExpr *Expr) {
8764fb1f9cdSDuncan P. N. Exon Smith   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
87797802080SDavid Blaikie }
8783363a57cSDavid Blaikie 
8792fbe1354SDuncan P. N. Exon Smith void DwarfCompileUnit::applySubprogramAttributesToDefinition(
880a9308c49SDuncan P. N. Exon Smith     const DISubprogram *SP, DIE &SPDie) {
881537b4a81SDuncan P. N. Exon Smith   auto *SPDecl = SP->getDeclaration();
882be9e4fe7SDuncan P. N. Exon Smith   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
8833a443c29SDavid Blaikie   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
884537b4a81SDuncan P. N. Exon Smith   addGlobalName(SP->getName(), SPDie, Context);
8853363a57cSDavid Blaikie }
886cafd962dSDavid Blaikie 
887cafd962dSDavid Blaikie bool DwarfCompileUnit::isDwoUnit() const {
888cafd962dSDavid Blaikie   return DD->useSplitDwarf() && Skeleton;
889cafd962dSDavid Blaikie }
8903a443c29SDavid Blaikie 
8913a443c29SDavid Blaikie bool DwarfCompileUnit::includeMinimalInlineScopes() const {
892b939a257SAdrian Prantl   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
8933a443c29SDavid Blaikie          (DD->useSplitDwarf() && !Skeleton);
8943a443c29SDavid Blaikie }
895f00654e3SAlexander Kornienko } // end llvm namespace
896