137c52310SDavid Blaikie #include "DwarfCompileUnit.h"
237c52310SDavid Blaikie 
3cda2aa82SDavid Blaikie #include "llvm/CodeGen/MachineFunction.h"
437c52310SDavid Blaikie #include "llvm/IR/DataLayout.h"
537c52310SDavid Blaikie #include "llvm/IR/GlobalValue.h"
637c52310SDavid Blaikie #include "llvm/IR/GlobalVariable.h"
737c52310SDavid Blaikie #include "llvm/IR/Instruction.h"
837c52310SDavid Blaikie #include "llvm/MC/MCAsmInfo.h"
937c52310SDavid Blaikie #include "llvm/MC/MCStreamer.h"
10ee7df553SDavid Blaikie #include "llvm/Target/TargetFrameLowering.h"
1137c52310SDavid Blaikie #include "llvm/Target/TargetLoweringObjectFile.h"
12cda2aa82SDavid Blaikie #include "llvm/Target/TargetMachine.h"
13cda2aa82SDavid Blaikie #include "llvm/Target/TargetSubtargetInfo.h"
14cda2aa82SDavid Blaikie #include "llvm/Target/TargetRegisterInfo.h"
1537c52310SDavid Blaikie 
1637c52310SDavid Blaikie namespace llvm {
1737c52310SDavid Blaikie 
1837c52310SDavid Blaikie DwarfCompileUnit::DwarfCompileUnit(unsigned UID, DICompileUnit Node,
1937c52310SDavid Blaikie                                    AsmPrinter *A, DwarfDebug *DW,
2037c52310SDavid Blaikie                                    DwarfFile *DWU)
217cbf58afSDavid Blaikie     : DwarfUnit(UID, dwarf::DW_TAG_compile_unit, Node, A, DW, DWU),
22ce343492SDavid Blaikie       Skeleton(nullptr), LabelBegin(nullptr), BaseAddress(nullptr) {
2337c52310SDavid Blaikie   insertDIE(Node, &getUnitDie());
2437c52310SDavid Blaikie }
2537c52310SDavid Blaikie 
2637c52310SDavid Blaikie /// addLabelAddress - Add a dwarf label attribute data and value using
2737c52310SDavid Blaikie /// DW_FORM_addr or DW_FORM_GNU_addr_index.
2837c52310SDavid Blaikie ///
2937c52310SDavid Blaikie void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
3037c52310SDavid Blaikie                                        const MCSymbol *Label) {
3137c52310SDavid Blaikie 
3237c52310SDavid Blaikie   // Don't use the address pool in non-fission or in the skeleton unit itself.
3337c52310SDavid Blaikie   // FIXME: Once GDB supports this, it's probably worthwhile using the address
3437c52310SDavid Blaikie   // pool from the skeleton - maybe even in non-fission (possibly fewer
3537c52310SDavid Blaikie   // relocations by sharing them in the pool, but we have other ideas about how
3637c52310SDavid Blaikie   // to reduce the number of relocations as well/instead).
3737c52310SDavid Blaikie   if (!DD->useSplitDwarf() || !Skeleton)
3837c52310SDavid Blaikie     return addLocalLabelAddress(Die, Attribute, Label);
3937c52310SDavid Blaikie 
4037c52310SDavid Blaikie   if (Label)
4137c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
4237c52310SDavid Blaikie 
4337c52310SDavid Blaikie   unsigned idx = DD->getAddressPool().getIndex(Label);
4437c52310SDavid Blaikie   DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx);
4537c52310SDavid Blaikie   Die.addValue(Attribute, dwarf::DW_FORM_GNU_addr_index, Value);
4637c52310SDavid Blaikie }
4737c52310SDavid Blaikie 
4837c52310SDavid Blaikie void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
4937c52310SDavid Blaikie                                             dwarf::Attribute Attribute,
5037c52310SDavid Blaikie                                             const MCSymbol *Label) {
5137c52310SDavid Blaikie   if (Label)
5237c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Label));
5337c52310SDavid Blaikie 
5437c52310SDavid Blaikie   Die.addValue(Attribute, dwarf::DW_FORM_addr,
5537c52310SDavid Blaikie                Label ? (DIEValue *)new (DIEValueAllocator) DIELabel(Label)
5637c52310SDavid Blaikie                      : new (DIEValueAllocator) DIEInteger(0));
5737c52310SDavid Blaikie }
5837c52310SDavid Blaikie 
598945219dSDavid Blaikie unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
608945219dSDavid Blaikie                                                StringRef DirName) {
6137c52310SDavid Blaikie   // If we print assembly, we can't separate .file entries according to
6237c52310SDavid Blaikie   // compile units. Thus all files will belong to the default compile unit.
6337c52310SDavid Blaikie 
6437c52310SDavid Blaikie   // FIXME: add a better feature test than hasRawTextSupport. Even better,
6537c52310SDavid Blaikie   // extend .file to support this.
6637c52310SDavid Blaikie   return Asm->OutStreamer.EmitDwarfFileDirective(
6737c52310SDavid Blaikie       0, DirName, FileName,
6837c52310SDavid Blaikie       Asm->OutStreamer.hasRawTextSupport() ? 0 : getUniqueID());
6937c52310SDavid Blaikie }
7037c52310SDavid Blaikie 
7137c52310SDavid Blaikie // Return const expression if value is a GEP to access merged global
7237c52310SDavid Blaikie // constant. e.g.
7337c52310SDavid Blaikie // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
7437c52310SDavid Blaikie static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
7537c52310SDavid Blaikie   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
7637c52310SDavid Blaikie   if (!CE || CE->getNumOperands() != 3 ||
7737c52310SDavid Blaikie       CE->getOpcode() != Instruction::GetElementPtr)
7837c52310SDavid Blaikie     return nullptr;
7937c52310SDavid Blaikie 
8037c52310SDavid Blaikie   // First operand points to a global struct.
8137c52310SDavid Blaikie   Value *Ptr = CE->getOperand(0);
8237c52310SDavid Blaikie   if (!isa<GlobalValue>(Ptr) ||
8337c52310SDavid Blaikie       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
8437c52310SDavid Blaikie     return nullptr;
8537c52310SDavid Blaikie 
8637c52310SDavid Blaikie   // Second operand is zero.
8737c52310SDavid Blaikie   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
8837c52310SDavid Blaikie   if (!CI || !CI->isZero())
8937c52310SDavid Blaikie     return nullptr;
9037c52310SDavid Blaikie 
9137c52310SDavid Blaikie   // Third operand is offset.
9237c52310SDavid Blaikie   if (!isa<ConstantInt>(CE->getOperand(2)))
9337c52310SDavid Blaikie     return nullptr;
9437c52310SDavid Blaikie 
9537c52310SDavid Blaikie   return CE;
9637c52310SDavid Blaikie }
9737c52310SDavid Blaikie 
9837c52310SDavid Blaikie /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
9937c52310SDavid Blaikie DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(DIGlobalVariable GV) {
10037c52310SDavid Blaikie   // Check for pre-existence.
10137c52310SDavid Blaikie   if (DIE *Die = getDIE(GV))
10237c52310SDavid Blaikie     return Die;
10337c52310SDavid Blaikie 
10437c52310SDavid Blaikie   assert(GV.isGlobalVariable());
10537c52310SDavid Blaikie 
106*f0a582baSManman Ren   DIScope GVContext = GV.getContext();
10737c52310SDavid Blaikie   DIType GTy = DD->resolve(GV.getType());
10837c52310SDavid Blaikie 
10937c52310SDavid Blaikie   // Construct the context before querying for the existence of the DIE in
11037c52310SDavid Blaikie   // case such construction creates the DIE.
11137c52310SDavid Blaikie   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
11237c52310SDavid Blaikie 
11337c52310SDavid Blaikie   // Add to map.
11449cfc8caSDavid Blaikie   DIE *VariableDIE = &createAndAddDIE(GV.getTag(), *ContextDIE, GV);
11549cfc8caSDavid Blaikie   DIScope DeclContext;
11637c52310SDavid Blaikie 
11749cfc8caSDavid Blaikie   if (DIDerivedType SDMDecl = GV.getStaticDataMemberDeclaration()) {
11849cfc8caSDavid Blaikie     DeclContext = resolve(SDMDecl.getContext());
11949cfc8caSDavid Blaikie     assert(SDMDecl.isStaticMember() && "Expected static member decl");
12049cfc8caSDavid Blaikie     assert(GV.isDefinition());
12149cfc8caSDavid Blaikie     // We need the declaration DIE that is in the static member's class.
12249cfc8caSDavid Blaikie     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
12349cfc8caSDavid Blaikie     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
12449cfc8caSDavid Blaikie   } else {
125*f0a582baSManman Ren     DeclContext = GV.getContext();
12637c52310SDavid Blaikie     // Add name and type.
12737c52310SDavid Blaikie     addString(*VariableDIE, dwarf::DW_AT_name, GV.getDisplayName());
12837c52310SDavid Blaikie     addType(*VariableDIE, GTy);
12937c52310SDavid Blaikie 
13037c52310SDavid Blaikie     // Add scoping info.
13137c52310SDavid Blaikie     if (!GV.isLocalToUnit())
13237c52310SDavid Blaikie       addFlag(*VariableDIE, dwarf::DW_AT_external);
13337c52310SDavid Blaikie 
13437c52310SDavid Blaikie     // Add line number info.
13537c52310SDavid Blaikie     addSourceLine(*VariableDIE, GV);
13637c52310SDavid Blaikie   }
13737c52310SDavid Blaikie 
13849cfc8caSDavid Blaikie   if (!GV.isDefinition())
13949cfc8caSDavid Blaikie     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
14049cfc8caSDavid Blaikie 
14137c52310SDavid Blaikie   // Add location.
14237c52310SDavid Blaikie   bool addToAccelTable = false;
14337c52310SDavid Blaikie   bool isGlobalVariable = GV.getGlobal() != nullptr;
14437c52310SDavid Blaikie   if (isGlobalVariable) {
14537c52310SDavid Blaikie     addToAccelTable = true;
14637c52310SDavid Blaikie     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
14737c52310SDavid Blaikie     const MCSymbol *Sym = Asm->getSymbol(GV.getGlobal());
14837c52310SDavid Blaikie     if (GV.getGlobal()->isThreadLocal()) {
14937c52310SDavid Blaikie       // FIXME: Make this work with -gsplit-dwarf.
15037c52310SDavid Blaikie       unsigned PointerSize = Asm->getDataLayout().getPointerSize();
15137c52310SDavid Blaikie       assert((PointerSize == 4 || PointerSize == 8) &&
15237c52310SDavid Blaikie              "Add support for other sizes if necessary");
15337c52310SDavid Blaikie       // Based on GCC's support for TLS:
15437c52310SDavid Blaikie       if (!DD->useSplitDwarf()) {
15537c52310SDavid Blaikie         // 1) Start with a constNu of the appropriate pointer size
15637c52310SDavid Blaikie         addUInt(*Loc, dwarf::DW_FORM_data1,
15737c52310SDavid Blaikie                 PointerSize == 4 ? dwarf::DW_OP_const4u : dwarf::DW_OP_const8u);
15837c52310SDavid Blaikie         // 2) containing the (relocated) offset of the TLS variable
15937c52310SDavid Blaikie         //    within the module's TLS block.
16037c52310SDavid Blaikie         addExpr(*Loc, dwarf::DW_FORM_udata,
16137c52310SDavid Blaikie                 Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
16237c52310SDavid Blaikie       } else {
16337c52310SDavid Blaikie         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
16437c52310SDavid Blaikie         addUInt(*Loc, dwarf::DW_FORM_udata,
16537c52310SDavid Blaikie                 DD->getAddressPool().getIndex(Sym, /* TLS */ true));
16637c52310SDavid Blaikie       }
16737c52310SDavid Blaikie       // 3) followed by a custom OP to make the debugger do a TLS lookup.
16837c52310SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_push_tls_address);
16937c52310SDavid Blaikie     } else {
17037c52310SDavid Blaikie       DD->addArangeLabel(SymbolCU(this, Sym));
17137c52310SDavid Blaikie       addOpAddress(*Loc, Sym);
17237c52310SDavid Blaikie     }
17349cfc8caSDavid Blaikie 
17437c52310SDavid Blaikie     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
17537c52310SDavid Blaikie     // Add the linkage name.
17637c52310SDavid Blaikie     StringRef LinkageName = GV.getLinkageName();
17737c52310SDavid Blaikie     if (!LinkageName.empty())
17837c52310SDavid Blaikie       // From DWARF4: DIEs to which DW_AT_linkage_name may apply include:
17937c52310SDavid Blaikie       // TAG_common_block, TAG_constant, TAG_entry_point, TAG_subprogram and
18037c52310SDavid Blaikie       // TAG_variable.
18149cfc8caSDavid Blaikie       addString(*VariableDIE,
18237c52310SDavid Blaikie                 DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name
18337c52310SDavid Blaikie                                            : dwarf::DW_AT_MIPS_linkage_name,
18437c52310SDavid Blaikie                 GlobalValue::getRealLinkageName(LinkageName));
18537c52310SDavid Blaikie   } else if (const ConstantInt *CI =
18637c52310SDavid Blaikie                  dyn_cast_or_null<ConstantInt>(GV.getConstant())) {
18737c52310SDavid Blaikie     addConstantValue(*VariableDIE, CI, GTy);
18837c52310SDavid Blaikie   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV.getConstant())) {
18937c52310SDavid Blaikie     addToAccelTable = true;
19037c52310SDavid Blaikie     // GV is a merged global.
19137c52310SDavid Blaikie     DIELoc *Loc = new (DIEValueAllocator) DIELoc();
19237c52310SDavid Blaikie     Value *Ptr = CE->getOperand(0);
19337c52310SDavid Blaikie     MCSymbol *Sym = Asm->getSymbol(cast<GlobalValue>(Ptr));
19437c52310SDavid Blaikie     DD->addArangeLabel(SymbolCU(this, Sym));
19537c52310SDavid Blaikie     addOpAddress(*Loc, Sym);
19637c52310SDavid Blaikie     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
19737c52310SDavid Blaikie     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
19837c52310SDavid Blaikie     addUInt(*Loc, dwarf::DW_FORM_udata,
19937c52310SDavid Blaikie             Asm->getDataLayout().getIndexedOffset(Ptr->getType(), Idx));
20037c52310SDavid Blaikie     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
20137c52310SDavid Blaikie     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
20237c52310SDavid Blaikie   }
20337c52310SDavid Blaikie 
20437c52310SDavid Blaikie   if (addToAccelTable) {
20549cfc8caSDavid Blaikie     DD->addAccelName(GV.getName(), *VariableDIE);
20637c52310SDavid Blaikie 
20737c52310SDavid Blaikie     // If the linkage name is different than the name, go ahead and output
20837c52310SDavid Blaikie     // that as well into the name table.
20937c52310SDavid Blaikie     if (GV.getLinkageName() != "" && GV.getName() != GV.getLinkageName())
21049cfc8caSDavid Blaikie       DD->addAccelName(GV.getLinkageName(), *VariableDIE);
21137c52310SDavid Blaikie   }
21237c52310SDavid Blaikie 
21349cfc8caSDavid Blaikie   addGlobalName(GV.getName(), *VariableDIE, DeclContext);
21449cfc8caSDavid Blaikie   return VariableDIE;
21537c52310SDavid Blaikie }
21637c52310SDavid Blaikie 
21737c52310SDavid Blaikie void DwarfCompileUnit::addRange(RangeSpan Range) {
21837c52310SDavid Blaikie   bool SameAsPrevCU = this == DD->getPrevCU();
21937c52310SDavid Blaikie   DD->setPrevCU(this);
22037c52310SDavid Blaikie   // If we have no current ranges just add the range and return, otherwise,
22137c52310SDavid Blaikie   // check the current section and CU against the previous section and CU we
22237c52310SDavid Blaikie   // emitted into and the subprogram was contained within. If these are the
22337c52310SDavid Blaikie   // same then extend our current range, otherwise add this as a new range.
22437c52310SDavid Blaikie   if (CURanges.empty() || !SameAsPrevCU ||
22537c52310SDavid Blaikie       (&CURanges.back().getEnd()->getSection() !=
22637c52310SDavid Blaikie        &Range.getEnd()->getSection())) {
22737c52310SDavid Blaikie     CURanges.push_back(Range);
22837c52310SDavid Blaikie     return;
22937c52310SDavid Blaikie   }
23037c52310SDavid Blaikie 
23137c52310SDavid Blaikie   CURanges.back().setEnd(Range.getEnd());
23237c52310SDavid Blaikie }
23337c52310SDavid Blaikie 
2346c0ee4ecSDavid Blaikie void DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
2356c0ee4ecSDavid Blaikie                                        const MCSymbol *Label,
2366c0ee4ecSDavid Blaikie                                        const MCSymbol *Sec) {
2376c0ee4ecSDavid Blaikie   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2386c0ee4ecSDavid Blaikie     addLabel(Die, Attribute,
2396c0ee4ecSDavid Blaikie              DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
2406c0ee4ecSDavid Blaikie                                         : dwarf::DW_FORM_data4,
2416c0ee4ecSDavid Blaikie              Label);
2426c0ee4ecSDavid Blaikie   else
2436c0ee4ecSDavid Blaikie     addSectionDelta(Die, Attribute, Label, Sec);
2446c0ee4ecSDavid Blaikie }
2456c0ee4ecSDavid Blaikie 
24637c52310SDavid Blaikie void DwarfCompileUnit::initStmtList(MCSymbol *DwarfLineSectionSym) {
24737c52310SDavid Blaikie   // Define start line table label for each Compile Unit.
24837c52310SDavid Blaikie   MCSymbol *LineTableStartSym =
24937c52310SDavid Blaikie       Asm->OutStreamer.getDwarfLineTableSymbol(getUniqueID());
25037c52310SDavid Blaikie 
25137c52310SDavid Blaikie   stmtListIndex = UnitDie.getValues().size();
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.
2586c0ee4ecSDavid Blaikie   addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
25937c52310SDavid Blaikie                   DwarfLineSectionSym);
26037c52310SDavid Blaikie }
26137c52310SDavid Blaikie 
26237c52310SDavid Blaikie void DwarfCompileUnit::applyStmtList(DIE &D) {
26337c52310SDavid Blaikie   D.addValue(dwarf::DW_AT_stmt_list,
26437c52310SDavid Blaikie              UnitDie.getAbbrev().getData()[stmtListIndex].getForm(),
26537c52310SDavid Blaikie              UnitDie.getValues()[stmtListIndex]);
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.
285cda2aa82SDavid Blaikie DIE &DwarfCompileUnit::updateSubprogramScopeDIE(DISubprogram SP) {
2863a443c29SDavid Blaikie   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
287cda2aa82SDavid Blaikie 
288cda2aa82SDavid Blaikie   attachLowHighPC(*SPDie, DD->getFunctionBeginSym(), DD->getFunctionEndSym());
289cda2aa82SDavid Blaikie   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
290cda2aa82SDavid Blaikie           *DD->getCurrentFunction()))
291cda2aa82SDavid Blaikie     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
292cda2aa82SDavid Blaikie 
293cda2aa82SDavid Blaikie   // Only include DW_AT_frame_base in full debug info
2943a443c29SDavid Blaikie   if (!includeMinimalInlineScopes()) {
295cda2aa82SDavid Blaikie     const TargetRegisterInfo *RI =
296cda2aa82SDavid Blaikie         Asm->TM.getSubtargetImpl()->getRegisterInfo();
297cda2aa82SDavid Blaikie     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
298cda2aa82SDavid Blaikie     addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
299cda2aa82SDavid Blaikie   }
300cda2aa82SDavid Blaikie 
301cda2aa82SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
302cda2aa82SDavid Blaikie   // to have concrete versions of our DW_TAG_subprogram nodes.
303cda2aa82SDavid Blaikie   DD->addSubprogramNames(SP, *SPDie);
304cda2aa82SDavid Blaikie 
305cda2aa82SDavid Blaikie   return *SPDie;
306cda2aa82SDavid Blaikie }
307cda2aa82SDavid Blaikie 
3089c65b135SDavid Blaikie // Construct a DIE for this scope.
3099c65b135SDavid Blaikie void DwarfCompileUnit::constructScopeDIE(
3109c65b135SDavid Blaikie     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &FinalChildren) {
3119c65b135SDavid Blaikie   if (!Scope || !Scope->getScopeNode())
3129c65b135SDavid Blaikie     return;
3139c65b135SDavid Blaikie 
3149c65b135SDavid Blaikie   DIScope DS(Scope->getScopeNode());
3159c65b135SDavid Blaikie 
3169c65b135SDavid Blaikie   assert((Scope->getInlinedAt() || !DS.isSubprogram()) &&
3179c65b135SDavid Blaikie          "Only handle inlined subprograms here, use "
3189c65b135SDavid Blaikie          "constructSubprogramScopeDIE for non-inlined "
3199c65b135SDavid Blaikie          "subprograms");
3209c65b135SDavid Blaikie 
3219c65b135SDavid Blaikie   SmallVector<std::unique_ptr<DIE>, 8> Children;
3229c65b135SDavid Blaikie 
3239c65b135SDavid Blaikie   // We try to create the scope DIE first, then the children DIEs. This will
3249c65b135SDavid Blaikie   // avoid creating un-used children then removing them later when we find out
3259c65b135SDavid Blaikie   // the scope DIE is null.
3269c65b135SDavid Blaikie   std::unique_ptr<DIE> ScopeDIE;
3279c65b135SDavid Blaikie   if (Scope->getParent() && DS.isSubprogram()) {
32801b48a84SDavid Blaikie     ScopeDIE = constructInlinedScopeDIE(Scope);
3299c65b135SDavid Blaikie     if (!ScopeDIE)
3309c65b135SDavid Blaikie       return;
3319c65b135SDavid Blaikie     // We create children when the scope DIE is not null.
3328b2fdb83SDavid Blaikie     createScopeChildrenDIE(Scope, Children);
3339c65b135SDavid Blaikie   } else {
3349c65b135SDavid Blaikie     // Early exit when we know the scope DIE is going to be null.
3359c65b135SDavid Blaikie     if (DD->isLexicalScopeDIENull(Scope))
3369c65b135SDavid Blaikie       return;
3379c65b135SDavid Blaikie 
3389c65b135SDavid Blaikie     unsigned ChildScopeCount;
3399c65b135SDavid Blaikie 
3409c65b135SDavid Blaikie     // We create children here when we know the scope DIE is not going to be
3419c65b135SDavid Blaikie     // null and the children will be added to the scope DIE.
3428b2fdb83SDavid Blaikie     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
3439c65b135SDavid Blaikie 
3443a443c29SDavid Blaikie     // Skip imported directives in gmlt-like data.
3453a443c29SDavid Blaikie     if (!includeMinimalInlineScopes()) {
3469c65b135SDavid Blaikie       // There is no need to emit empty lexical block DIE.
3479c65b135SDavid Blaikie       for (const auto &E : DD->findImportedEntitiesForScope(DS))
3489c65b135SDavid Blaikie         Children.push_back(
3499c65b135SDavid Blaikie             constructImportedEntityDIE(DIImportedEntity(E.second)));
3503a443c29SDavid Blaikie     }
3513a443c29SDavid Blaikie 
3529c65b135SDavid Blaikie     // If there are only other scopes as children, put them directly in the
3539c65b135SDavid Blaikie     // parent instead, as this scope would serve no purpose.
3549c65b135SDavid Blaikie     if (Children.size() == ChildScopeCount) {
3559c65b135SDavid Blaikie       FinalChildren.insert(FinalChildren.end(),
3569c65b135SDavid Blaikie                            std::make_move_iterator(Children.begin()),
3579c65b135SDavid Blaikie                            std::make_move_iterator(Children.end()));
3589c65b135SDavid Blaikie       return;
3599c65b135SDavid Blaikie     }
3600fbf8bdbSDavid Blaikie     ScopeDIE = constructLexicalScopeDIE(Scope);
3619c65b135SDavid Blaikie     assert(ScopeDIE && "Scope DIE should not be null.");
3629c65b135SDavid Blaikie   }
3639c65b135SDavid Blaikie 
3649c65b135SDavid Blaikie   // Add children
3659c65b135SDavid Blaikie   for (auto &I : Children)
3669c65b135SDavid Blaikie     ScopeDIE->addChild(std::move(I));
3679c65b135SDavid Blaikie 
3689c65b135SDavid Blaikie   FinalChildren.push_back(std::move(ScopeDIE));
3699c65b135SDavid Blaikie }
3709c65b135SDavid Blaikie 
371e5feec50SDavid Blaikie void DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
372e5feec50SDavid Blaikie                                        const MCSymbol *Hi, const MCSymbol *Lo) {
373e5feec50SDavid Blaikie   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
374e5feec50SDavid Blaikie   Die.addValue(Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
375e5feec50SDavid Blaikie                                                      : dwarf::DW_FORM_data4,
376e5feec50SDavid Blaikie                Value);
377e5feec50SDavid Blaikie }
378e5feec50SDavid Blaikie 
3795b02a19fSDavid Blaikie void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
3805b02a19fSDavid Blaikie                                          SmallVector<RangeSpan, 2> Range) {
38152400200SDavid Blaikie   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
38252400200SDavid Blaikie   // emitting it appropriately.
38352400200SDavid Blaikie   auto *RangeSectionSym = DD->getRangeSectionSym();
38452400200SDavid Blaikie 
3855b02a19fSDavid Blaikie   RangeSpanList List(
3865b02a19fSDavid Blaikie       Asm->GetTempSymbol("debug_ranges", DD->getNextRangeNumber()),
3875b02a19fSDavid Blaikie       std::move(Range));
3885b02a19fSDavid Blaikie 
38952400200SDavid Blaikie   // Under fission, ranges are specified by constant offsets relative to the
39052400200SDavid Blaikie   // CU's DW_AT_GNU_ranges_base.
3915b02a19fSDavid Blaikie   if (isDwoUnit())
3925b02a19fSDavid Blaikie     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3935b02a19fSDavid Blaikie                     RangeSectionSym);
39452400200SDavid Blaikie   else
3955b02a19fSDavid Blaikie     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
3965b02a19fSDavid Blaikie                     RangeSectionSym);
39752400200SDavid Blaikie 
39852400200SDavid Blaikie   // Add the range list to the set of ranges to be emitted.
399542616d4SDavid Blaikie   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
40052400200SDavid Blaikie }
40152400200SDavid Blaikie 
402de12375cSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
4035b02a19fSDavid Blaikie     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
4045b02a19fSDavid Blaikie   if (Ranges.size() == 1) {
4055b02a19fSDavid Blaikie     const auto &single = Ranges.front();
4065b02a19fSDavid Blaikie     attachLowHighPC(Die, single.getStart(), single.getEnd());
4075b02a19fSDavid Blaikie   } else
4085b02a19fSDavid Blaikie     addScopeRangeList(Die, std::move(Ranges));
4095b02a19fSDavid Blaikie }
4105b02a19fSDavid Blaikie 
4115b02a19fSDavid Blaikie void DwarfCompileUnit::attachRangesOrLowHighPC(
412de12375cSDavid Blaikie     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
4135b02a19fSDavid Blaikie   SmallVector<RangeSpan, 2> List;
4145b02a19fSDavid Blaikie   List.reserve(Ranges.size());
4155b02a19fSDavid Blaikie   for (const InsnRange &R : Ranges)
4165b02a19fSDavid Blaikie     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
4175b02a19fSDavid Blaikie                              DD->getLabelAfterInsn(R.second)));
4185b02a19fSDavid Blaikie   attachRangesOrLowHighPC(Die, std::move(List));
419de12375cSDavid Blaikie }
420de12375cSDavid Blaikie 
42101b48a84SDavid Blaikie // This scope represents inlined body of a function. Construct DIE to
42201b48a84SDavid Blaikie // represent this concrete inlined copy of the function.
42301b48a84SDavid Blaikie std::unique_ptr<DIE>
42401b48a84SDavid Blaikie DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
42501b48a84SDavid Blaikie   assert(Scope->getScopeNode());
42601b48a84SDavid Blaikie   DIScope DS(Scope->getScopeNode());
42701b48a84SDavid Blaikie   DISubprogram InlinedSP = getDISubprogram(DS);
42801b48a84SDavid Blaikie   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
42901b48a84SDavid Blaikie   // was inlined from another compile unit.
430f6dac29aSDavid Blaikie   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
43101b48a84SDavid Blaikie   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
43201b48a84SDavid Blaikie 
43301b48a84SDavid Blaikie   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_inlined_subroutine);
43401b48a84SDavid Blaikie   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
43501b48a84SDavid Blaikie 
43601b48a84SDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
43701b48a84SDavid Blaikie 
43801b48a84SDavid Blaikie   // Add the call site information to the DIE.
43901b48a84SDavid Blaikie   DILocation DL(Scope->getInlinedAt());
44001b48a84SDavid Blaikie   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
44101b48a84SDavid Blaikie           getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
44201b48a84SDavid Blaikie   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
44301b48a84SDavid Blaikie 
44401b48a84SDavid Blaikie   // Add name to the name table, we do this here because we're guaranteed
44501b48a84SDavid Blaikie   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
44601b48a84SDavid Blaikie   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
44701b48a84SDavid Blaikie 
44801b48a84SDavid Blaikie   return ScopeDIE;
44901b48a84SDavid Blaikie }
45001b48a84SDavid Blaikie 
4510fbf8bdbSDavid Blaikie // Construct new DW_TAG_lexical_block for this scope and attach
4520fbf8bdbSDavid Blaikie // DW_AT_low_pc/DW_AT_high_pc labels.
4530fbf8bdbSDavid Blaikie std::unique_ptr<DIE>
4540fbf8bdbSDavid Blaikie DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
4550fbf8bdbSDavid Blaikie   if (DD->isLexicalScopeDIENull(Scope))
4560fbf8bdbSDavid Blaikie     return nullptr;
4570fbf8bdbSDavid Blaikie 
4580fbf8bdbSDavid Blaikie   auto ScopeDIE = make_unique<DIE>(dwarf::DW_TAG_lexical_block);
4590fbf8bdbSDavid Blaikie   if (Scope->isAbstractScope())
4600fbf8bdbSDavid Blaikie     return ScopeDIE;
4610fbf8bdbSDavid Blaikie 
4620fbf8bdbSDavid Blaikie   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
4630fbf8bdbSDavid Blaikie 
4640fbf8bdbSDavid Blaikie   return ScopeDIE;
4650fbf8bdbSDavid Blaikie }
4660fbf8bdbSDavid Blaikie 
467ee7df553SDavid Blaikie /// constructVariableDIE - Construct a DIE for the given DbgVariable.
468ee7df553SDavid Blaikie std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
469ee7df553SDavid Blaikie                                                             bool Abstract) {
470ee7df553SDavid Blaikie   auto D = constructVariableDIEImpl(DV, Abstract);
471ee7df553SDavid Blaikie   DV.setDIE(*D);
472ee7df553SDavid Blaikie   return D;
473ee7df553SDavid Blaikie }
474ee7df553SDavid Blaikie 
475ee7df553SDavid Blaikie std::unique_ptr<DIE>
476ee7df553SDavid Blaikie DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
477ee7df553SDavid Blaikie                                            bool Abstract) {
478ee7df553SDavid Blaikie   // Define variable debug information entry.
479ee7df553SDavid Blaikie   auto VariableDie = make_unique<DIE>(DV.getTag());
480ee7df553SDavid Blaikie 
481ee7df553SDavid Blaikie   if (Abstract) {
482ee7df553SDavid Blaikie     applyVariableAttributes(DV, *VariableDie);
483ee7df553SDavid Blaikie     return VariableDie;
484ee7df553SDavid Blaikie   }
485ee7df553SDavid Blaikie 
486ee7df553SDavid Blaikie   // Add variable address.
487ee7df553SDavid Blaikie 
488ee7df553SDavid Blaikie   unsigned Offset = DV.getDotDebugLocOffset();
489ee7df553SDavid Blaikie   if (Offset != ~0U) {
490ee7df553SDavid Blaikie     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
491ee7df553SDavid Blaikie     return VariableDie;
492ee7df553SDavid Blaikie   }
493ee7df553SDavid Blaikie 
494ee7df553SDavid Blaikie   // Check if variable is described by a DBG_VALUE instruction.
495ee7df553SDavid Blaikie   if (const MachineInstr *DVInsn = DV.getMInsn()) {
496ee7df553SDavid Blaikie     assert(DVInsn->getNumOperands() == 4);
497ee7df553SDavid Blaikie     if (DVInsn->getOperand(0).isReg()) {
498ee7df553SDavid Blaikie       const MachineOperand RegOp = DVInsn->getOperand(0);
499ee7df553SDavid Blaikie       // If the second operand is an immediate, this is an indirect value.
500ee7df553SDavid Blaikie       if (DVInsn->getOperand(1).isImm()) {
501ee7df553SDavid Blaikie         MachineLocation Location(RegOp.getReg(),
502ee7df553SDavid Blaikie                                  DVInsn->getOperand(1).getImm());
503ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, Location);
504ee7df553SDavid Blaikie       } else if (RegOp.getReg())
505ee7df553SDavid Blaikie         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
506ee7df553SDavid Blaikie     } else if (DVInsn->getOperand(0).isImm())
507ee7df553SDavid Blaikie       addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
508ee7df553SDavid Blaikie     else if (DVInsn->getOperand(0).isFPImm())
509ee7df553SDavid Blaikie       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
510ee7df553SDavid Blaikie     else if (DVInsn->getOperand(0).isCImm())
511ee7df553SDavid Blaikie       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
512ee7df553SDavid Blaikie                        DV.getType());
513ee7df553SDavid Blaikie 
514ee7df553SDavid Blaikie     return VariableDie;
515ee7df553SDavid Blaikie   }
516ee7df553SDavid Blaikie 
517ee7df553SDavid Blaikie   // .. else use frame index.
518ee7df553SDavid Blaikie   int FI = DV.getFrameIndex();
519ee7df553SDavid Blaikie   if (FI != ~0) {
520ee7df553SDavid Blaikie     unsigned FrameReg = 0;
521ee7df553SDavid Blaikie     const TargetFrameLowering *TFI =
522ee7df553SDavid Blaikie         Asm->TM.getSubtargetImpl()->getFrameLowering();
523ee7df553SDavid Blaikie     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
524ee7df553SDavid Blaikie     MachineLocation Location(FrameReg, Offset);
525ee7df553SDavid Blaikie     addVariableAddress(DV, *VariableDie, Location);
526ee7df553SDavid Blaikie   }
527ee7df553SDavid Blaikie 
528ee7df553SDavid Blaikie   return VariableDie;
529ee7df553SDavid Blaikie }
530ee7df553SDavid Blaikie 
5314a1a44e3SDavid Blaikie std::unique_ptr<DIE> DwarfCompileUnit::constructVariableDIE(
5324a1a44e3SDavid Blaikie     DbgVariable &DV, const LexicalScope &Scope, DIE *&ObjectPointer) {
5334a1a44e3SDavid Blaikie   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
5344a1a44e3SDavid Blaikie   if (DV.isObjectPointer())
5354a1a44e3SDavid Blaikie     ObjectPointer = Var.get();
5364a1a44e3SDavid Blaikie   return Var;
5374a1a44e3SDavid Blaikie }
5384a1a44e3SDavid Blaikie 
5398b2fdb83SDavid Blaikie DIE *DwarfCompileUnit::createScopeChildrenDIE(
5408b2fdb83SDavid Blaikie     LexicalScope *Scope, SmallVectorImpl<std::unique_ptr<DIE>> &Children,
5418b2fdb83SDavid Blaikie     unsigned *ChildScopeCount) {
5428b2fdb83SDavid Blaikie   DIE *ObjectPointer = nullptr;
5438b2fdb83SDavid Blaikie 
54480e5b1ebSDavid Blaikie   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
5458b2fdb83SDavid Blaikie     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
5468b2fdb83SDavid Blaikie 
5478b2fdb83SDavid Blaikie   unsigned ChildCountWithoutScopes = Children.size();
5488b2fdb83SDavid Blaikie 
5498b2fdb83SDavid Blaikie   for (LexicalScope *LS : Scope->getChildren())
5508b2fdb83SDavid Blaikie     constructScopeDIE(LS, Children);
5518b2fdb83SDavid Blaikie 
5528b2fdb83SDavid Blaikie   if (ChildScopeCount)
5538b2fdb83SDavid Blaikie     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
5548b2fdb83SDavid Blaikie 
5558b2fdb83SDavid Blaikie   return ObjectPointer;
5568b2fdb83SDavid Blaikie }
5578b2fdb83SDavid Blaikie 
5581d072348SDavid Blaikie void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
5591d072348SDavid Blaikie   assert(Scope && Scope->getScopeNode());
5601d072348SDavid Blaikie   assert(!Scope->getInlinedAt());
5611d072348SDavid Blaikie   assert(!Scope->isAbstractScope());
5621d072348SDavid Blaikie   DISubprogram Sub(Scope->getScopeNode());
5631d072348SDavid Blaikie 
5641d072348SDavid Blaikie   assert(Sub.isSubprogram());
5651d072348SDavid Blaikie 
5661d072348SDavid Blaikie   DD->getProcessedSPNodes().insert(Sub);
5671d072348SDavid Blaikie 
5681d072348SDavid Blaikie   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
5691d072348SDavid Blaikie 
5701d072348SDavid Blaikie   // If this is a variadic function, add an unspecified parameter.
5711d072348SDavid Blaikie   DITypeArray FnArgs = Sub.getType().getTypeArray();
5721dd573dbSDavid Blaikie 
5731dd573dbSDavid Blaikie   // Collect lexical scope children first.
5741dd573dbSDavid Blaikie   // ObjectPointer might be a local (non-argument) local variable if it's a
5751dd573dbSDavid Blaikie   // block's synthetic this pointer.
5761dd573dbSDavid Blaikie   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
5771dd573dbSDavid Blaikie     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
5781dd573dbSDavid Blaikie 
5791d072348SDavid Blaikie   // If we have a single element of null, it is a function that returns void.
5801d072348SDavid Blaikie   // If we have more than one elements and the last one is null, it is a
5811d072348SDavid Blaikie   // variadic function.
5821d072348SDavid Blaikie   if (FnArgs.getNumElements() > 1 &&
5833a443c29SDavid Blaikie       !FnArgs.getElement(FnArgs.getNumElements() - 1) &&
5843a443c29SDavid Blaikie       !includeMinimalInlineScopes())
5851d072348SDavid Blaikie     ScopeDIE.addChild(make_unique<DIE>(dwarf::DW_TAG_unspecified_parameters));
5861d072348SDavid Blaikie }
5871d072348SDavid Blaikie 
58878b65b6fSDavid Blaikie DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
58978b65b6fSDavid Blaikie                                                  DIE &ScopeDIE) {
59078b65b6fSDavid Blaikie   // We create children when the scope DIE is not null.
59178b65b6fSDavid Blaikie   SmallVector<std::unique_ptr<DIE>, 8> Children;
59278b65b6fSDavid Blaikie   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
59378b65b6fSDavid Blaikie 
59478b65b6fSDavid Blaikie   // Add children
59578b65b6fSDavid Blaikie   for (auto &I : Children)
59678b65b6fSDavid Blaikie     ScopeDIE.addChild(std::move(I));
59778b65b6fSDavid Blaikie 
59878b65b6fSDavid Blaikie   return ObjectPointer;
59978b65b6fSDavid Blaikie }
60078b65b6fSDavid Blaikie 
60149be5b35SDavid Blaikie void
60258410f24SDavid Blaikie DwarfCompileUnit::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
603f6dac29aSDavid Blaikie   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
60449be5b35SDavid Blaikie   if (AbsDef)
60549be5b35SDavid Blaikie     return;
60649be5b35SDavid Blaikie 
60758410f24SDavid Blaikie   DISubprogram SP(Scope->getScopeNode());
60858410f24SDavid Blaikie 
60958410f24SDavid Blaikie   DIE *ContextDIE;
61058410f24SDavid Blaikie 
6113a443c29SDavid Blaikie   if (includeMinimalInlineScopes())
6123a443c29SDavid Blaikie     ContextDIE = &getUnitDie();
61358410f24SDavid Blaikie   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
61458410f24SDavid Blaikie   // the important distinction that the DIDescriptor is not associated with the
61558410f24SDavid Blaikie   // DIE (since the DIDescriptor will be associated with the concrete DIE, if
61658410f24SDavid Blaikie   // any). It could be refactored to some common utility function.
6173a443c29SDavid Blaikie   else if (DISubprogram SPDecl = SP.getFunctionDeclaration()) {
61858410f24SDavid Blaikie     ContextDIE = &getUnitDie();
61958410f24SDavid Blaikie     getOrCreateSubprogramDIE(SPDecl);
62058410f24SDavid Blaikie   } else
62158410f24SDavid Blaikie     ContextDIE = getOrCreateContextDIE(resolve(SP.getContext()));
62258410f24SDavid Blaikie 
62358410f24SDavid Blaikie   // Passing null as the associated DIDescriptor because the abstract definition
62458410f24SDavid Blaikie   // shouldn't be found by lookup.
62549be5b35SDavid Blaikie   AbsDef =
62649be5b35SDavid Blaikie       &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, DIDescriptor());
62749be5b35SDavid Blaikie   applySubprogramAttributesToDefinition(SP, *AbsDef);
62858410f24SDavid Blaikie 
6293a443c29SDavid Blaikie   if (!includeMinimalInlineScopes())
63049be5b35SDavid Blaikie     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
63149be5b35SDavid Blaikie   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
63249be5b35SDavid Blaikie     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
63358410f24SDavid Blaikie }
63458410f24SDavid Blaikie 
635987fe227SFrederic Riss std::unique_ptr<DIE>
636987fe227SFrederic Riss DwarfCompileUnit::constructImportedEntityDIE(const DIImportedEntity &Module) {
637987fe227SFrederic Riss   assert(Module.Verify() &&
638987fe227SFrederic Riss          "Use one of the MDNode * overloads to handle invalid metadata");
639987fe227SFrederic Riss   std::unique_ptr<DIE> IMDie = make_unique<DIE>((dwarf::Tag)Module.getTag());
640987fe227SFrederic Riss   insertDIE(Module, IMDie.get());
641987fe227SFrederic Riss   DIE *EntityDie;
642987fe227SFrederic Riss   DIDescriptor Entity = resolve(Module.getEntity());
643987fe227SFrederic Riss   if (Entity.isNameSpace())
644987fe227SFrederic Riss     EntityDie = getOrCreateNameSpace(DINameSpace(Entity));
645987fe227SFrederic Riss   else if (Entity.isSubprogram())
646987fe227SFrederic Riss     EntityDie = getOrCreateSubprogramDIE(DISubprogram(Entity));
647987fe227SFrederic Riss   else if (Entity.isType())
648987fe227SFrederic Riss     EntityDie = getOrCreateTypeDIE(DIType(Entity));
649fdccfc1eSFrederic Riss   else if (Entity.isGlobalVariable())
650fdccfc1eSFrederic Riss     EntityDie = getOrCreateGlobalVariableDIE(DIGlobalVariable(Entity));
651987fe227SFrederic Riss   else
652987fe227SFrederic Riss     EntityDie = getDIE(Entity);
653987fe227SFrederic Riss   assert(EntityDie);
654987fe227SFrederic Riss   addSourceLine(*IMDie, Module.getLineNumber(),
655987fe227SFrederic Riss                 Module.getContext().getFilename(),
656987fe227SFrederic Riss                 Module.getContext().getDirectory());
657987fe227SFrederic Riss   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
658987fe227SFrederic Riss   StringRef Name = Module.getName();
659987fe227SFrederic Riss   if (!Name.empty())
660987fe227SFrederic Riss     addString(*IMDie, dwarf::DW_AT_name, Name);
661987fe227SFrederic Riss 
662987fe227SFrederic Riss   return IMDie;
663987fe227SFrederic Riss }
664987fe227SFrederic Riss 
6654191cbceSDavid Blaikie void DwarfCompileUnit::finishSubprogramDefinition(DISubprogram SP) {
6664191cbceSDavid Blaikie   DIE *D = getDIE(SP);
667f6dac29aSDavid Blaikie   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
6684191cbceSDavid Blaikie     if (D)
6694191cbceSDavid Blaikie       // If this subprogram has an abstract definition, reference that
6704191cbceSDavid Blaikie       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
6714191cbceSDavid Blaikie   } else {
6723a443c29SDavid Blaikie     if (!D && !includeMinimalInlineScopes())
6734191cbceSDavid Blaikie       // Lazily construct the subprogram if we didn't see either concrete or
6744191cbceSDavid Blaikie       // inlined versions during codegen. (except in -gmlt ^ where we want
6754191cbceSDavid Blaikie       // to omit these entirely)
6764191cbceSDavid Blaikie       D = getOrCreateSubprogramDIE(SP);
6774191cbceSDavid Blaikie     if (D)
6784191cbceSDavid Blaikie       // And attach the attributes
6794191cbceSDavid Blaikie       applySubprogramAttributesToDefinition(SP, *D);
6804191cbceSDavid Blaikie   }
6814191cbceSDavid Blaikie }
6821d96cc2fSDavid Blaikie void DwarfCompileUnit::collectDeadVariables(DISubprogram SP) {
6831d96cc2fSDavid Blaikie   assert(SP.isSubprogram() && "CU's subprogram list contains a non-subprogram");
6841d96cc2fSDavid Blaikie   assert(SP.isDefinition() &&
6851d96cc2fSDavid Blaikie          "CU's subprogram list contains a subprogram declaration");
6861d96cc2fSDavid Blaikie   DIArray Variables = SP.getVariables();
6871d96cc2fSDavid Blaikie   if (Variables.getNumElements() == 0)
6881d96cc2fSDavid Blaikie     return;
6891d96cc2fSDavid Blaikie 
690f6dac29aSDavid Blaikie   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
6911d96cc2fSDavid Blaikie   if (!SPDIE)
6921d96cc2fSDavid Blaikie     SPDIE = getDIE(SP);
6931d96cc2fSDavid Blaikie   assert(SPDIE);
6941d96cc2fSDavid Blaikie   for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
6951d96cc2fSDavid Blaikie     DIVariable DV(Variables.getElement(vi));
6961d96cc2fSDavid Blaikie     assert(DV.isVariable());
6971d96cc2fSDavid Blaikie     DbgVariable NewVar(DV, DIExpression(nullptr), DD);
6981d96cc2fSDavid Blaikie     auto VariableDie = constructVariableDIE(NewVar);
6991d96cc2fSDavid Blaikie     applyVariableAttributes(NewVar, *VariableDie);
7001d96cc2fSDavid Blaikie     SPDIE->addChild(std::move(VariableDie));
7011d96cc2fSDavid Blaikie   }
7021d96cc2fSDavid Blaikie }
7034191cbceSDavid Blaikie 
704ae57e66eSDavid Blaikie void DwarfCompileUnit::emitHeader(const MCSymbol *ASectionSym) const {
705b6726a9eSDavid Blaikie   // Don't bother labeling the .dwo unit, as its offset isn't used.
706b6726a9eSDavid Blaikie   if (!Skeleton)
707ae57e66eSDavid Blaikie     Asm->OutStreamer.EmitLabel(LabelBegin);
708ae57e66eSDavid Blaikie 
709ae57e66eSDavid Blaikie   DwarfUnit::emitHeader(ASectionSym);
710ae57e66eSDavid Blaikie }
711ae57e66eSDavid Blaikie 
712192b45c1SDavid Blaikie /// addGlobalName - Add a new global name to the compile unit.
713192b45c1SDavid Blaikie void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
714192b45c1SDavid Blaikie                                      DIScope Context) {
7153a443c29SDavid Blaikie   if (includeMinimalInlineScopes())
716192b45c1SDavid Blaikie     return;
717192b45c1SDavid Blaikie   std::string FullName = getParentContextString(Context) + Name.str();
718192b45c1SDavid Blaikie   GlobalNames[FullName] = &Die;
719192b45c1SDavid Blaikie }
720192b45c1SDavid Blaikie 
721192b45c1SDavid Blaikie /// Add a new global type to the unit.
722192b45c1SDavid Blaikie void DwarfCompileUnit::addGlobalType(DIType Ty, const DIE &Die,
723192b45c1SDavid Blaikie                                      DIScope Context) {
7243a443c29SDavid Blaikie   if (includeMinimalInlineScopes())
725192b45c1SDavid Blaikie     return;
726192b45c1SDavid Blaikie   std::string FullName = getParentContextString(Context) + Ty.getName().str();
727192b45c1SDavid Blaikie   GlobalTypes[FullName] = &Die;
728192b45c1SDavid Blaikie }
729ae57e66eSDavid Blaikie 
7307d48be2bSDavid Blaikie /// addVariableAddress - Add DW_AT_location attribute for a
7317d48be2bSDavid Blaikie /// DbgVariable based on provided MachineLocation.
7327d48be2bSDavid Blaikie void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
7337d48be2bSDavid Blaikie                                           MachineLocation Location) {
7347d48be2bSDavid Blaikie   if (DV.variableHasComplexAddress())
7357d48be2bSDavid Blaikie     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
7367d48be2bSDavid Blaikie   else if (DV.isBlockByrefVariable())
7377d48be2bSDavid Blaikie     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
7387d48be2bSDavid Blaikie   else
7397d48be2bSDavid Blaikie     addAddress(Die, dwarf::DW_AT_location, Location,
7407d48be2bSDavid Blaikie                DV.getVariable().isIndirect());
7417d48be2bSDavid Blaikie }
742f7435ee6SDavid Blaikie 
743f7435ee6SDavid Blaikie /// Add an address attribute to a die based on the location provided.
744f7435ee6SDavid Blaikie void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
745f7435ee6SDavid Blaikie                                   const MachineLocation &Location,
746f7435ee6SDavid Blaikie                                   bool Indirect) {
747f7435ee6SDavid Blaikie   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
748f7435ee6SDavid Blaikie 
749f7435ee6SDavid Blaikie   if (Location.isReg() && !Indirect)
750f7435ee6SDavid Blaikie     addRegisterOpPiece(*Loc, Location.getReg());
751f7435ee6SDavid Blaikie   else {
752f7435ee6SDavid Blaikie     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
753f7435ee6SDavid Blaikie     if (Indirect && !Location.isReg()) {
754f7435ee6SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
755f7435ee6SDavid Blaikie     }
756f7435ee6SDavid Blaikie   }
757f7435ee6SDavid Blaikie 
758f7435ee6SDavid Blaikie   // Now attach the location information to the DIE.
759f7435ee6SDavid Blaikie   addBlock(Die, Attribute, Loc);
760f7435ee6SDavid Blaikie }
76177895fb2SDavid Blaikie 
76277895fb2SDavid Blaikie /// Start with the address based on the location provided, and generate the
76377895fb2SDavid Blaikie /// DWARF information necessary to find the actual variable given the extra
76477895fb2SDavid Blaikie /// address information encoded in the DbgVariable, starting from the starting
76577895fb2SDavid Blaikie /// location.  Add the DWARF information to the die.
76677895fb2SDavid Blaikie void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
76777895fb2SDavid Blaikie                                          dwarf::Attribute Attribute,
76877895fb2SDavid Blaikie                                          const MachineLocation &Location) {
76977895fb2SDavid Blaikie   DIELoc *Loc = new (DIEValueAllocator) DIELoc();
77077895fb2SDavid Blaikie   unsigned N = DV.getNumAddrElements();
77177895fb2SDavid Blaikie   unsigned i = 0;
77277895fb2SDavid Blaikie   if (Location.isReg()) {
77377895fb2SDavid Blaikie     if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_plus) {
77477895fb2SDavid Blaikie       assert(!DV.getVariable().isIndirect() &&
77577895fb2SDavid Blaikie              "double indirection not handled");
77677895fb2SDavid Blaikie       // If first address element is OpPlus then emit
77777895fb2SDavid Blaikie       // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
77877895fb2SDavid Blaikie       addRegisterOffset(*Loc, Location.getReg(), DV.getAddrElement(1));
77977895fb2SDavid Blaikie       i = 2;
78077895fb2SDavid Blaikie     } else if (N >= 2 && DV.getAddrElement(0) == dwarf::DW_OP_deref) {
78177895fb2SDavid Blaikie       assert(!DV.getVariable().isIndirect() &&
78277895fb2SDavid Blaikie              "double indirection not handled");
78377895fb2SDavid Blaikie       addRegisterOpPiece(*Loc, Location.getReg(),
78477895fb2SDavid Blaikie                          DV.getExpression().getPieceSize(),
78577895fb2SDavid Blaikie                          DV.getExpression().getPieceOffset());
78677895fb2SDavid Blaikie       i = 3;
78777895fb2SDavid Blaikie     } else
78877895fb2SDavid Blaikie       addRegisterOpPiece(*Loc, Location.getReg());
78977895fb2SDavid Blaikie   } else
79077895fb2SDavid Blaikie     addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
79177895fb2SDavid Blaikie 
79277895fb2SDavid Blaikie   for (; i < N; ++i) {
79377895fb2SDavid Blaikie     uint64_t Element = DV.getAddrElement(i);
79477895fb2SDavid Blaikie     if (Element == dwarf::DW_OP_plus) {
79577895fb2SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
79677895fb2SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_udata, DV.getAddrElement(++i));
79777895fb2SDavid Blaikie 
79877895fb2SDavid Blaikie     } else if (Element == dwarf::DW_OP_deref) {
79977895fb2SDavid Blaikie       if (!Location.isReg())
80077895fb2SDavid Blaikie         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
80177895fb2SDavid Blaikie 
80277895fb2SDavid Blaikie     } else if (Element == dwarf::DW_OP_piece) {
80377895fb2SDavid Blaikie       const unsigned SizeOfByte = 8;
80477895fb2SDavid Blaikie       unsigned PieceOffsetInBits = DV.getAddrElement(++i) * SizeOfByte;
80577895fb2SDavid Blaikie       unsigned PieceSizeInBits = DV.getAddrElement(++i) * SizeOfByte;
80677895fb2SDavid Blaikie       // Emit DW_OP_bit_piece Size Offset.
80777895fb2SDavid Blaikie       assert(PieceSizeInBits > 0 && "piece has zero size");
80877895fb2SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_bit_piece);
80977895fb2SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_udata, PieceSizeInBits);
81077895fb2SDavid Blaikie       addUInt(*Loc, dwarf::DW_FORM_udata, PieceOffsetInBits);
81177895fb2SDavid Blaikie     } else
81277895fb2SDavid Blaikie       llvm_unreachable("unknown DIBuilder Opcode");
81377895fb2SDavid Blaikie   }
81477895fb2SDavid Blaikie 
81577895fb2SDavid Blaikie   // Now attach the location information to the DIE.
81677895fb2SDavid Blaikie   addBlock(Die, Attribute, Loc);
81777895fb2SDavid Blaikie }
8184bc0881aSDavid Blaikie 
8194bc0881aSDavid Blaikie /// Add a Dwarf loclistptr attribute data and value.
8204bc0881aSDavid Blaikie void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
8214bc0881aSDavid Blaikie                                        unsigned Index) {
8224bc0881aSDavid Blaikie   DIEValue *Value = new (DIEValueAllocator) DIELocList(Index);
8234bc0881aSDavid Blaikie   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
8244bc0881aSDavid Blaikie                                                 : dwarf::DW_FORM_data4;
8254bc0881aSDavid Blaikie   Die.addValue(Attribute, Form, Value);
8264bc0881aSDavid Blaikie }
82702a6333bSDavid Blaikie 
8288c485b5dSDavid Blaikie void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
82902a6333bSDavid Blaikie                                                DIE &VariableDie) {
83002a6333bSDavid Blaikie   StringRef Name = Var.getName();
83102a6333bSDavid Blaikie   if (!Name.empty())
83202a6333bSDavid Blaikie     addString(VariableDie, dwarf::DW_AT_name, Name);
83302a6333bSDavid Blaikie   addSourceLine(VariableDie, Var.getVariable());
83402a6333bSDavid Blaikie   addType(VariableDie, Var.getType());
83502a6333bSDavid Blaikie   if (Var.isArtificial())
83602a6333bSDavid Blaikie     addFlag(VariableDie, dwarf::DW_AT_artificial);
83702a6333bSDavid Blaikie }
83897802080SDavid Blaikie 
83997802080SDavid Blaikie /// Add a Dwarf expression attribute data and value.
84097802080SDavid Blaikie void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
84197802080SDavid Blaikie                                const MCExpr *Expr) {
84297802080SDavid Blaikie   DIEValue *Value = new (DIEValueAllocator) DIEExpr(Expr);
84397802080SDavid Blaikie   Die.addValue((dwarf::Attribute)0, Form, Value);
84497802080SDavid Blaikie }
8453363a57cSDavid Blaikie 
8463363a57cSDavid Blaikie void DwarfCompileUnit::applySubprogramAttributesToDefinition(DISubprogram SP,
8473363a57cSDavid Blaikie                                                              DIE &SPDie) {
8483363a57cSDavid Blaikie   DISubprogram SPDecl = SP.getFunctionDeclaration();
8493363a57cSDavid Blaikie   DIScope Context = resolve(SPDecl ? SPDecl.getContext() : SP.getContext());
8503a443c29SDavid Blaikie   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
8513363a57cSDavid Blaikie   addGlobalName(SP.getName(), SPDie, Context);
8523363a57cSDavid Blaikie }
853cafd962dSDavid Blaikie 
854cafd962dSDavid Blaikie bool DwarfCompileUnit::isDwoUnit() const {
855cafd962dSDavid Blaikie   return DD->useSplitDwarf() && Skeleton;
856cafd962dSDavid Blaikie }
8573a443c29SDavid Blaikie 
8583a443c29SDavid Blaikie bool DwarfCompileUnit::includeMinimalInlineScopes() const {
8593a443c29SDavid Blaikie   return getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly ||
8603a443c29SDavid Blaikie          (DD->useSplitDwarf() && !Skeleton);
8613a443c29SDavid Blaikie }
86237c52310SDavid Blaikie } // end llvm namespace
863