1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for constructing a dwarf compile unit.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfCompileUnit.h"
14 #include "AddressPool.h"
15 #include "DwarfDebug.h"
16 #include "DwarfExpression.h"
17 #include "DwarfUnit.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/BinaryFormat/Dwarf.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/DIE.h"
26 #include "llvm/CodeGen/LexicalScopes.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineOperand.h"
30 #include "llvm/CodeGen/TargetFrameLowering.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/TargetSubtargetInfo.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DebugInfo.h"
35 #include "llvm/IR/DebugInfoMetadata.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/MC/MachineLocation.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Target/TargetLoweringObjectFile.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstdint>
48 #include <iterator>
49 #include <memory>
50 #include <string>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
56                                    AsmPrinter *A, DwarfDebug *DW,
57                                    DwarfFile *DWU)
58     : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID) {
59   insertDIE(Node, &getUnitDie());
60   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
61 }
62 
63 /// addLabelAddress - Add a dwarf label attribute data and value using
64 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
65 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
66                                        const MCSymbol *Label) {
67   // Don't use the address pool in non-fission or in the skeleton unit itself.
68   // FIXME: Once GDB supports this, it's probably worthwhile using the address
69   // pool from the skeleton - maybe even in non-fission (possibly fewer
70   // relocations by sharing them in the pool, but we have other ideas about how
71   // to reduce the number of relocations as well/instead).
72   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
73     return addLocalLabelAddress(Die, Attribute, Label);
74 
75   if (Label)
76     DD->addArangeLabel(SymbolCU(this, Label));
77 
78   unsigned idx = DD->getAddressPool().getIndex(Label);
79   Die.addValue(DIEValueAllocator, Attribute,
80                DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
81                                           : dwarf::DW_FORM_GNU_addr_index,
82                DIEInteger(idx));
83 }
84 
85 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
86                                             dwarf::Attribute Attribute,
87                                             const MCSymbol *Label) {
88   if (Label)
89     DD->addArangeLabel(SymbolCU(this, Label));
90 
91   if (Label)
92     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
93                  DIELabel(Label));
94   else
95     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
96                  DIEInteger(0));
97 }
98 
99 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
100   // If we print assembly, we can't separate .file entries according to
101   // compile units. Thus all files will belong to the default compile unit.
102 
103   // FIXME: add a better feature test than hasRawTextSupport. Even better,
104   // extend .file to support this.
105   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
106   if (!File)
107     return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", None, None, CUID);
108   return Asm->OutStreamer->EmitDwarfFileDirective(
109       0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
110       File->getSource(), CUID);
111 }
112 
113 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
114     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
115   // Check for pre-existence.
116   if (DIE *Die = getDIE(GV))
117     return Die;
118 
119   assert(GV);
120 
121   auto *GVContext = GV->getScope();
122   const DIType *GTy = GV->getType();
123 
124   // Construct the context before querying for the existence of the DIE in
125   // case such construction creates the DIE.
126   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
127   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
128     : getOrCreateContextDIE(GVContext);
129 
130   // Add to map.
131   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
132   DIScope *DeclContext;
133   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
134     DeclContext = SDMDecl->getScope();
135     assert(SDMDecl->isStaticMember() && "Expected static member decl");
136     assert(GV->isDefinition());
137     // We need the declaration DIE that is in the static member's class.
138     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
139     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
140     // If the global variable's type is different from the one in the class
141     // member type, assume that it's more specific and also emit it.
142     if (GTy != SDMDecl->getBaseType())
143       addType(*VariableDIE, GTy);
144   } else {
145     DeclContext = GV->getScope();
146     // Add name and type.
147     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
148     addType(*VariableDIE, GTy);
149 
150     // Add scoping info.
151     if (!GV->isLocalToUnit())
152       addFlag(*VariableDIE, dwarf::DW_AT_external);
153 
154     // Add line number info.
155     addSourceLine(*VariableDIE, GV);
156   }
157 
158   if (!GV->isDefinition())
159     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
160   else
161     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
162 
163   if (uint32_t AlignInBytes = GV->getAlignInBytes())
164     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
165             AlignInBytes);
166 
167   if (MDTuple *TP = GV->getTemplateParams())
168     addTemplateParams(*VariableDIE, DINodeArray(TP));
169 
170   // Add location.
171   addLocationAttribute(VariableDIE, GV, GlobalExprs);
172 
173   return VariableDIE;
174 }
175 
176 void DwarfCompileUnit::addLocationAttribute(
177     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
178   bool addToAccelTable = false;
179   DIELoc *Loc = nullptr;
180   Optional<unsigned> NVPTXAddressSpace;
181   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
182   for (const auto &GE : GlobalExprs) {
183     const GlobalVariable *Global = GE.Var;
184     const DIExpression *Expr = GE.Expr;
185 
186     // For compatibility with DWARF 3 and earlier,
187     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
188     // DW_AT_const_value(X).
189     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
190       addToAccelTable = true;
191       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
192       break;
193     }
194 
195     // We cannot describe the location of dllimport'd variables: the
196     // computation of their address requires loads from the IAT.
197     if (Global && Global->hasDLLImportStorageClass())
198       continue;
199 
200     // Nothing to describe without address or constant.
201     if (!Global && (!Expr || !Expr->isConstant()))
202       continue;
203 
204     if (Global && Global->isThreadLocal() &&
205         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
206       continue;
207 
208     if (!Loc) {
209       addToAccelTable = true;
210       Loc = new (DIEValueAllocator) DIELoc;
211       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
212     }
213 
214     if (Expr) {
215       // According to
216       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
217       // cuda-gdb requires DW_AT_address_class for all variables to be able to
218       // correctly interpret address space of the variable address.
219       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
220       // sequence for the NVPTX + gdb target.
221       unsigned LocalNVPTXAddressSpace;
222       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
223         const DIExpression *NewExpr =
224             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
225         if (NewExpr != Expr) {
226           Expr = NewExpr;
227           NVPTXAddressSpace = LocalNVPTXAddressSpace;
228         }
229       }
230       DwarfExpr->addFragmentOffset(Expr);
231     }
232 
233     if (Global) {
234       const MCSymbol *Sym = Asm->getSymbol(Global);
235       if (Global->isThreadLocal()) {
236         if (Asm->TM.useEmulatedTLS()) {
237           // TODO: add debug info for emulated thread local mode.
238         } else {
239           // FIXME: Make this work with -gsplit-dwarf.
240           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
241           assert((PointerSize == 4 || PointerSize == 8) &&
242                  "Add support for other sizes if necessary");
243           // Based on GCC's support for TLS:
244           if (!DD->useSplitDwarf()) {
245             // 1) Start with a constNu of the appropriate pointer size
246             addUInt(*Loc, dwarf::DW_FORM_data1,
247                     PointerSize == 4 ? dwarf::DW_OP_const4u
248                                      : dwarf::DW_OP_const8u);
249             // 2) containing the (relocated) offset of the TLS variable
250             //    within the module's TLS block.
251             addExpr(*Loc, dwarf::DW_FORM_udata,
252                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
253           } else {
254             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
255             addUInt(*Loc, dwarf::DW_FORM_udata,
256                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
257           }
258           // 3) followed by an OP to make the debugger do a TLS lookup.
259           addUInt(*Loc, dwarf::DW_FORM_data1,
260                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
261                                         : dwarf::DW_OP_form_tls_address);
262         }
263       } else {
264         DD->addArangeLabel(SymbolCU(this, Sym));
265         addOpAddress(*Loc, Sym);
266       }
267     }
268     // Global variables attached to symbols are memory locations.
269     // It would be better if this were unconditional, but malformed input that
270     // mixes non-fragments and fragments for the same variable is too expensive
271     // to detect in the verifier.
272     if (DwarfExpr->isUnknownLocation())
273       DwarfExpr->setMemoryLocationKind();
274     DwarfExpr->addExpression(Expr);
275   }
276   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
277     // According to
278     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
279     // cuda-gdb requires DW_AT_address_class for all variables to be able to
280     // correctly interpret address space of the variable address.
281     const unsigned NVPTX_ADDR_global_space = 5;
282     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
283             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
284   }
285   if (Loc)
286     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
287 
288   if (DD->useAllLinkageNames())
289     addLinkageName(*VariableDIE, GV->getLinkageName());
290 
291   if (addToAccelTable) {
292     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
293 
294     // If the linkage name is different than the name, go ahead and output
295     // that as well into the name table.
296     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
297         DD->useAllLinkageNames())
298       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
299   }
300 }
301 
302 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
303     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
304   // Construct the context before querying for the existence of the DIE in case
305   // such construction creates the DIE.
306   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
307 
308   if (DIE *NDie = getDIE(CB))
309     return NDie;
310   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
311   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
312   addString(NDie, dwarf::DW_AT_name, Name);
313   addGlobalName(Name, NDie, CB->getScope());
314   if (CB->getFile())
315     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
316   if (DIGlobalVariable *V = CB->getDecl())
317     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
318   return &NDie;
319 }
320 
321 void DwarfCompileUnit::addRange(RangeSpan Range) {
322   bool SameAsPrevCU = this == DD->getPrevCU();
323   DD->setPrevCU(this);
324   // If we have no current ranges just add the range and return, otherwise,
325   // check the current section and CU against the previous section and CU we
326   // emitted into and the subprogram was contained within. If these are the
327   // same then extend our current range, otherwise add this as a new range.
328   if (CURanges.empty() || !SameAsPrevCU ||
329       (&CURanges.back().getEnd()->getSection() !=
330        &Range.getEnd()->getSection())) {
331     CURanges.push_back(Range);
332     DD->addSectionLabel(Range.getStart());
333     return;
334   }
335 
336   CURanges.back().setEnd(Range.getEnd());
337 }
338 
339 void DwarfCompileUnit::initStmtList() {
340   if (CUNode->isDebugDirectivesOnly())
341     return;
342 
343   // Define start line table label for each Compile Unit.
344   MCSymbol *LineTableStartSym;
345   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
346   if (DD->useSectionsAsReferences()) {
347     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
348   } else {
349     LineTableStartSym =
350         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
351   }
352 
353   // DW_AT_stmt_list is a offset of line number information for this
354   // compile unit in debug_line section. For split dwarf this is
355   // left in the skeleton CU and so not included.
356   // The line table entries are not always emitted in assembly, so it
357   // is not okay to use line_table_start here.
358   StmtListValue =
359       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
360                       TLOF.getDwarfLineSection()->getBeginSymbol());
361 }
362 
363 void DwarfCompileUnit::applyStmtList(DIE &D) {
364   D.addValue(DIEValueAllocator, *StmtListValue);
365 }
366 
367 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
368                                        const MCSymbol *End) {
369   assert(Begin && "Begin label should not be null!");
370   assert(End && "End label should not be null!");
371   assert(Begin->isDefined() && "Invalid starting label");
372   assert(End->isDefined() && "Invalid end label");
373 
374   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
375   if (DD->getDwarfVersion() < 4)
376     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
377   else
378     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
379 }
380 
381 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
382 // and DW_AT_high_pc attributes. If there are global variables in this
383 // scope then create and insert DIEs for these variables.
384 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
385   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
386 
387   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
388   if (DD->useAppleExtensionAttributes() &&
389       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
390           *DD->getCurrentFunction()))
391     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
392 
393   // Only include DW_AT_frame_base in full debug info
394   if (!includeMinimalInlineScopes()) {
395     if (Asm->MF->getTarget().getTargetTriple().isNVPTX()) {
396       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
397       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
398       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
399     } else {
400       const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
401       MachineLocation Location(RI->getFrameRegister(*Asm->MF));
402       if (RI->isPhysicalRegister(Location.getReg()))
403         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
404     }
405   }
406 
407   // Add name to the name table, we do this here because we're guaranteed
408   // to have concrete versions of our DW_TAG_subprogram nodes.
409   DD->addSubprogramNames(*CUNode, SP, *SPDie);
410 
411   return *SPDie;
412 }
413 
414 // Construct a DIE for this scope.
415 void DwarfCompileUnit::constructScopeDIE(
416     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
417   if (!Scope || !Scope->getScopeNode())
418     return;
419 
420   auto *DS = Scope->getScopeNode();
421 
422   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
423          "Only handle inlined subprograms here, use "
424          "constructSubprogramScopeDIE for non-inlined "
425          "subprograms");
426 
427   SmallVector<DIE *, 8> Children;
428 
429   // We try to create the scope DIE first, then the children DIEs. This will
430   // avoid creating un-used children then removing them later when we find out
431   // the scope DIE is null.
432   DIE *ScopeDIE;
433   if (Scope->getParent() && isa<DISubprogram>(DS)) {
434     ScopeDIE = constructInlinedScopeDIE(Scope);
435     if (!ScopeDIE)
436       return;
437     // We create children when the scope DIE is not null.
438     createScopeChildrenDIE(Scope, Children);
439   } else {
440     // Early exit when we know the scope DIE is going to be null.
441     if (DD->isLexicalScopeDIENull(Scope))
442       return;
443 
444     bool HasNonScopeChildren = false;
445 
446     // We create children here when we know the scope DIE is not going to be
447     // null and the children will be added to the scope DIE.
448     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
449 
450     // If there are only other scopes as children, put them directly in the
451     // parent instead, as this scope would serve no purpose.
452     if (!HasNonScopeChildren) {
453       FinalChildren.insert(FinalChildren.end(),
454                            std::make_move_iterator(Children.begin()),
455                            std::make_move_iterator(Children.end()));
456       return;
457     }
458     ScopeDIE = constructLexicalScopeDIE(Scope);
459     assert(ScopeDIE && "Scope DIE should not be null.");
460   }
461 
462   // Add children
463   for (auto &I : Children)
464     ScopeDIE->addChild(std::move(I));
465 
466   FinalChildren.push_back(std::move(ScopeDIE));
467 }
468 
469 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
470                                          SmallVector<RangeSpan, 2> Range) {
471   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
472 
473   // Emit the offset into .debug_ranges or .debug_rnglists as a relocatable
474   // label. emitDIE() will handle emitting it appropriately.
475   const MCSymbol *RangeSectionSym =
476       DD->getDwarfVersion() >= 5
477           ? TLOF.getDwarfRnglistsSection()->getBeginSymbol()
478           : TLOF.getDwarfRangesSection()->getBeginSymbol();
479 
480   HasRangeLists = true;
481 
482   // Add the range list to the set of ranges to be emitted.
483   auto IndexAndList =
484       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
485           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
486 
487   uint32_t Index = IndexAndList.first;
488   auto &List = *IndexAndList.second;
489 
490   // Under fission, ranges are specified by constant offsets relative to the
491   // CU's DW_AT_GNU_ranges_base.
492   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
493   // fission until we support the forms using the .debug_addr section
494   // (DW_RLE_startx_endx etc.).
495   if (DD->getDwarfVersion() >= 5)
496     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
497   else if (isDwoUnit())
498     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
499                     RangeSectionSym);
500   else
501     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
502                     RangeSectionSym);
503 }
504 
505 void DwarfCompileUnit::attachRangesOrLowHighPC(
506     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
507   if (Ranges.size() == 1 || !DD->useRangesSection()) {
508     const RangeSpan &Front = Ranges.front();
509     const RangeSpan &Back = Ranges.back();
510     attachLowHighPC(Die, Front.getStart(), Back.getEnd());
511   } else
512     addScopeRangeList(Die, std::move(Ranges));
513 }
514 
515 void DwarfCompileUnit::attachRangesOrLowHighPC(
516     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
517   SmallVector<RangeSpan, 2> List;
518   List.reserve(Ranges.size());
519   for (const InsnRange &R : Ranges)
520     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
521                              DD->getLabelAfterInsn(R.second)));
522   attachRangesOrLowHighPC(Die, std::move(List));
523 }
524 
525 // This scope represents inlined body of a function. Construct DIE to
526 // represent this concrete inlined copy of the function.
527 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
528   assert(Scope->getScopeNode());
529   auto *DS = Scope->getScopeNode();
530   auto *InlinedSP = getDISubprogram(DS);
531   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
532   // was inlined from another compile unit.
533   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
534   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
535 
536   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
537   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
538 
539   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
540 
541   // Add the call site information to the DIE.
542   const DILocation *IA = Scope->getInlinedAt();
543   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
544           getOrCreateSourceID(IA->getFile()));
545   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
546   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
547     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
548             IA->getDiscriminator());
549 
550   // Add name to the name table, we do this here because we're guaranteed
551   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
552   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
553 
554   return ScopeDIE;
555 }
556 
557 // Construct new DW_TAG_lexical_block for this scope and attach
558 // DW_AT_low_pc/DW_AT_high_pc labels.
559 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
560   if (DD->isLexicalScopeDIENull(Scope))
561     return nullptr;
562 
563   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
564   if (Scope->isAbstractScope())
565     return ScopeDIE;
566 
567   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
568 
569   return ScopeDIE;
570 }
571 
572 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
573 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
574   auto D = constructVariableDIEImpl(DV, Abstract);
575   DV.setDIE(*D);
576   return D;
577 }
578 
579 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
580                                          const LexicalScope &Scope) {
581   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
582   insertDIE(DL.getLabel(), LabelDie);
583   DL.setDIE(*LabelDie);
584 
585   if (Scope.isAbstractScope())
586     applyLabelAttributes(DL, *LabelDie);
587 
588   return LabelDie;
589 }
590 
591 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
592                                                 bool Abstract) {
593   // Define variable debug information entry.
594   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
595   insertDIE(DV.getVariable(), VariableDie);
596 
597   if (Abstract) {
598     applyVariableAttributes(DV, *VariableDie);
599     return VariableDie;
600   }
601 
602   // Add variable address.
603 
604   unsigned Offset = DV.getDebugLocListIndex();
605   if (Offset != ~0U) {
606     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
607     return VariableDie;
608   }
609 
610   // Check if variable has a single location description.
611   if (auto *DVal = DV.getValueLoc()) {
612     if (DVal->isLocation())
613       addVariableAddress(DV, *VariableDie, DVal->getLoc());
614     else if (DVal->isInt()) {
615       auto *Expr = DV.getSingleExpression();
616       if (Expr && Expr->getNumElements()) {
617         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
618         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
619         // If there is an expression, emit raw unsigned bytes.
620         DwarfExpr.addFragmentOffset(Expr);
621         DwarfExpr.addUnsignedConstant(DVal->getInt());
622         DwarfExpr.addExpression(Expr);
623         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
624       } else
625         addConstantValue(*VariableDie, DVal->getInt(), DV.getType());
626     } else if (DVal->isConstantFP()) {
627       addConstantFPValue(*VariableDie, DVal->getConstantFP());
628     } else if (DVal->isConstantInt()) {
629       addConstantValue(*VariableDie, DVal->getConstantInt(), DV.getType());
630     }
631     return VariableDie;
632   }
633 
634   // .. else use frame index.
635   if (!DV.hasFrameIndexExprs())
636     return VariableDie;
637 
638   Optional<unsigned> NVPTXAddressSpace;
639   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
640   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
641   for (auto &Fragment : DV.getFrameIndexExprs()) {
642     unsigned FrameReg = 0;
643     const DIExpression *Expr = Fragment.Expr;
644     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
645     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
646     DwarfExpr.addFragmentOffset(Expr);
647     SmallVector<uint64_t, 8> Ops;
648     Ops.push_back(dwarf::DW_OP_plus_uconst);
649     Ops.push_back(Offset);
650     // According to
651     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
652     // cuda-gdb requires DW_AT_address_class for all variables to be able to
653     // correctly interpret address space of the variable address.
654     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
655     // sequence for the NVPTX + gdb target.
656     unsigned LocalNVPTXAddressSpace;
657     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
658       const DIExpression *NewExpr =
659           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
660       if (NewExpr != Expr) {
661         Expr = NewExpr;
662         NVPTXAddressSpace = LocalNVPTXAddressSpace;
663       }
664     }
665     if (Expr)
666       Ops.append(Expr->elements_begin(), Expr->elements_end());
667     DIExpressionCursor Cursor(Ops);
668     DwarfExpr.setMemoryLocationKind();
669     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
670       addOpAddress(*Loc, FrameSymbol);
671     else
672       DwarfExpr.addMachineRegExpression(
673           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
674     DwarfExpr.addExpression(std::move(Cursor));
675   }
676   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
677     // According to
678     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
679     // cuda-gdb requires DW_AT_address_class for all variables to be able to
680     // correctly interpret address space of the variable address.
681     const unsigned NVPTX_ADDR_local_space = 6;
682     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
683             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
684   }
685   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
686   if (DwarfExpr.TagOffset)
687     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
688             *DwarfExpr.TagOffset);
689 
690   return VariableDie;
691 }
692 
693 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
694                                             const LexicalScope &Scope,
695                                             DIE *&ObjectPointer) {
696   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
697   if (DV.isObjectPointer())
698     ObjectPointer = Var;
699   return Var;
700 }
701 
702 /// Return all DIVariables that appear in count: expressions.
703 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
704   SmallVector<const DIVariable *, 2> Result;
705   auto *Array = dyn_cast<DICompositeType>(Var->getType());
706   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
707     return Result;
708   for (auto *El : Array->getElements()) {
709     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
710       auto Count = Subrange->getCount();
711       if (auto *Dependency = Count.dyn_cast<DIVariable *>())
712         Result.push_back(Dependency);
713     }
714   }
715   return Result;
716 }
717 
718 /// Sort local variables so that variables appearing inside of helper
719 /// expressions come first.
720 static SmallVector<DbgVariable *, 8>
721 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
722   SmallVector<DbgVariable *, 8> Result;
723   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
724   // Map back from a DIVariable to its containing DbgVariable.
725   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
726   // Set of DbgVariables in Result.
727   SmallDenseSet<DbgVariable *, 8> Visited;
728   // For cycle detection.
729   SmallDenseSet<DbgVariable *, 8> Visiting;
730 
731   // Initialize the worklist and the DIVariable lookup table.
732   for (auto Var : reverse(Input)) {
733     DbgVar.insert({Var->getVariable(), Var});
734     WorkList.push_back({Var, 0});
735   }
736 
737   // Perform a stable topological sort by doing a DFS.
738   while (!WorkList.empty()) {
739     auto Item = WorkList.back();
740     DbgVariable *Var = Item.getPointer();
741     bool visitedAllDependencies = Item.getInt();
742     WorkList.pop_back();
743 
744     // Dependency is in a different lexical scope or a global.
745     if (!Var)
746       continue;
747 
748     // Already handled.
749     if (Visited.count(Var))
750       continue;
751 
752     // Add to Result if all dependencies are visited.
753     if (visitedAllDependencies) {
754       Visited.insert(Var);
755       Result.push_back(Var);
756       continue;
757     }
758 
759     // Detect cycles.
760     auto Res = Visiting.insert(Var);
761     if (!Res.second) {
762       assert(false && "dependency cycle in local variables");
763       return Result;
764     }
765 
766     // Push dependencies and this node onto the worklist, so that this node is
767     // visited again after all of its dependencies are handled.
768     WorkList.push_back({Var, 1});
769     for (auto *Dependency : dependencies(Var)) {
770       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
771       WorkList.push_back({DbgVar[Dep], 0});
772     }
773   }
774   return Result;
775 }
776 
777 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
778                                               SmallVectorImpl<DIE *> &Children,
779                                               bool *HasNonScopeChildren) {
780   assert(Children.empty());
781   DIE *ObjectPointer = nullptr;
782 
783   // Emit function arguments (order is significant).
784   auto Vars = DU->getScopeVariables().lookup(Scope);
785   for (auto &DV : Vars.Args)
786     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
787 
788   // Emit local variables.
789   auto Locals = sortLocalVars(Vars.Locals);
790   for (DbgVariable *DV : Locals)
791     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
792 
793   // Skip imported directives in gmlt-like data.
794   if (!includeMinimalInlineScopes()) {
795     // There is no need to emit empty lexical block DIE.
796     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
797       Children.push_back(
798           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
799   }
800 
801   if (HasNonScopeChildren)
802     *HasNonScopeChildren = !Children.empty();
803 
804   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
805     Children.push_back(constructLabelDIE(*DL, *Scope));
806 
807   for (LexicalScope *LS : Scope->getChildren())
808     constructScopeDIE(LS, Children);
809 
810   return ObjectPointer;
811 }
812 
813 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
814                                                    LexicalScope *Scope) {
815   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
816 
817   if (Scope) {
818     assert(!Scope->getInlinedAt());
819     assert(!Scope->isAbstractScope());
820     // Collect lexical scope children first.
821     // ObjectPointer might be a local (non-argument) local variable if it's a
822     // block's synthetic this pointer.
823     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
824       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
825   }
826 
827   // If this is a variadic function, add an unspecified parameter.
828   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
829 
830   // If we have a single element of null, it is a function that returns void.
831   // If we have more than one elements and the last one is null, it is a
832   // variadic function.
833   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
834       !includeMinimalInlineScopes())
835     ScopeDIE.addChild(
836         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
837 
838   return ScopeDIE;
839 }
840 
841 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
842                                                  DIE &ScopeDIE) {
843   // We create children when the scope DIE is not null.
844   SmallVector<DIE *, 8> Children;
845   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
846 
847   // Add children
848   for (auto &I : Children)
849     ScopeDIE.addChild(std::move(I));
850 
851   return ObjectPointer;
852 }
853 
854 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
855     LexicalScope *Scope) {
856   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
857   if (AbsDef)
858     return;
859 
860   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
861 
862   DIE *ContextDIE;
863   DwarfCompileUnit *ContextCU = this;
864 
865   if (includeMinimalInlineScopes())
866     ContextDIE = &getUnitDie();
867   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
868   // the important distinction that the debug node is not associated with the
869   // DIE (since the debug node will be associated with the concrete DIE, if
870   // any). It could be refactored to some common utility function.
871   else if (auto *SPDecl = SP->getDeclaration()) {
872     ContextDIE = &getUnitDie();
873     getOrCreateSubprogramDIE(SPDecl);
874   } else {
875     ContextDIE = getOrCreateContextDIE(SP->getScope());
876     // The scope may be shared with a subprogram that has already been
877     // constructed in another CU, in which case we need to construct this
878     // subprogram in the same CU.
879     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
880   }
881 
882   // Passing null as the associated node because the abstract definition
883   // shouldn't be found by lookup.
884   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
885   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
886 
887   if (!ContextCU->includeMinimalInlineScopes())
888     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
889   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
890     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
891 }
892 
893 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUCallSiteTag(dwarf::Tag Tag) {
894   bool ApplyGNUExtensions = DD->getDwarfVersion() == 4 && DD->tuneForGDB();
895   if (!ApplyGNUExtensions)
896     return Tag;
897   switch (Tag) {
898   case dwarf::DW_TAG_call_site:
899     return dwarf::DW_TAG_GNU_call_site;
900   case dwarf::DW_TAG_call_site_parameter:
901     return dwarf::DW_TAG_GNU_call_site_parameter;
902   default:
903     llvm_unreachable("unhandled call site tag");
904   }
905 }
906 
907 dwarf::Attribute
908 DwarfCompileUnit::getDwarf5OrGNUCallSiteAttr(dwarf::Attribute Attr) {
909   bool ApplyGNUExtensions = DD->getDwarfVersion() == 4 && DD->tuneForGDB();
910   if (!ApplyGNUExtensions)
911     return Attr;
912   switch (Attr) {
913   case dwarf::DW_AT_call_all_calls:
914     return dwarf::DW_AT_GNU_all_call_sites;
915   case dwarf::DW_AT_call_target:
916     return dwarf::DW_AT_GNU_call_site_target;
917   case dwarf::DW_AT_call_origin:
918     return dwarf::DW_AT_abstract_origin;
919   case dwarf::DW_AT_call_pc:
920     return dwarf::DW_AT_low_pc;
921   case dwarf::DW_AT_call_value:
922     return dwarf::DW_AT_GNU_call_site_value;
923   case dwarf::DW_AT_call_tail_call:
924     return dwarf::DW_AT_GNU_tail_call;
925   default:
926     llvm_unreachable("unhandled call site attribute");
927   }
928 }
929 
930 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(
931     DIE &ScopeDIE, const DISubprogram *CalleeSP, bool IsTail,
932     const MCSymbol *PCAddr, const MCExpr *PCOffset, unsigned CallReg) {
933   // Insert a call site entry DIE within ScopeDIE.
934   DIE &CallSiteDIE = createAndAddDIE(
935       getDwarf5OrGNUCallSiteTag(dwarf::DW_TAG_call_site), ScopeDIE, nullptr);
936 
937   if (CallReg) {
938     // Indirect call.
939     addAddress(CallSiteDIE,
940                getDwarf5OrGNUCallSiteAttr(dwarf::DW_AT_call_target),
941                MachineLocation(CallReg));
942   } else {
943     DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
944     assert(CalleeDIE && "Could not create DIE for call site entry origin");
945     addDIEEntry(CallSiteDIE,
946                 getDwarf5OrGNUCallSiteAttr(dwarf::DW_AT_call_origin),
947                 *CalleeDIE);
948   }
949 
950   if (IsTail)
951     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
952     addFlag(CallSiteDIE,
953             getDwarf5OrGNUCallSiteAttr(dwarf::DW_AT_call_tail_call));
954 
955   // Attach the return PC to allow the debugger to disambiguate call paths
956   // from one function to another.
957   if (DD->getDwarfVersion() == 4 && DD->tuneForGDB()) {
958     assert(PCAddr && "Missing PC information for a call");
959     addLabelAddress(CallSiteDIE, dwarf::DW_AT_low_pc, PCAddr);
960   } else if (!IsTail || DD->tuneForGDB()) {
961     assert(PCOffset && "Missing return PC information for a call");
962     addAddressExpr(CallSiteDIE, dwarf::DW_AT_call_return_pc, PCOffset);
963   }
964 
965   return CallSiteDIE;
966 }
967 
968 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
969     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
970   for (auto &Param : Params) {
971     unsigned Register = Param.getRegister();
972     auto CallSiteDieParam =
973         DIE::get(DIEValueAllocator,
974                  getDwarf5OrGNUCallSiteTag(dwarf::DW_TAG_call_site_parameter));
975     insertDIE(CallSiteDieParam);
976     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
977                MachineLocation(Register));
978 
979     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
980     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
981     DwarfExpr.setCallSiteParamValueFlag();
982 
983     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
984 
985     addBlock(*CallSiteDieParam,
986              getDwarf5OrGNUCallSiteAttr(dwarf::DW_AT_call_value),
987              DwarfExpr.finalize());
988 
989     CallSiteDIE.addChild(CallSiteDieParam);
990   }
991 }
992 
993 DIE *DwarfCompileUnit::constructImportedEntityDIE(
994     const DIImportedEntity *Module) {
995   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
996   insertDIE(Module, IMDie);
997   DIE *EntityDie;
998   auto *Entity = Module->getEntity();
999   if (auto *NS = dyn_cast<DINamespace>(Entity))
1000     EntityDie = getOrCreateNameSpace(NS);
1001   else if (auto *M = dyn_cast<DIModule>(Entity))
1002     EntityDie = getOrCreateModule(M);
1003   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1004     EntityDie = getOrCreateSubprogramDIE(SP);
1005   else if (auto *T = dyn_cast<DIType>(Entity))
1006     EntityDie = getOrCreateTypeDIE(T);
1007   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1008     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1009   else
1010     EntityDie = getDIE(Entity);
1011   assert(EntityDie);
1012   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1013   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1014   StringRef Name = Module->getName();
1015   if (!Name.empty())
1016     addString(*IMDie, dwarf::DW_AT_name, Name);
1017 
1018   return IMDie;
1019 }
1020 
1021 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1022   DIE *D = getDIE(SP);
1023   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1024     if (D)
1025       // If this subprogram has an abstract definition, reference that
1026       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1027   } else {
1028     assert(D || includeMinimalInlineScopes());
1029     if (D)
1030       // And attach the attributes
1031       applySubprogramAttributesToDefinition(SP, *D);
1032   }
1033 }
1034 
1035 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1036   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1037 
1038   auto *Die = Entity->getDIE();
1039   /// Label may be used to generate DW_AT_low_pc, so put it outside
1040   /// if/else block.
1041   const DbgLabel *Label = nullptr;
1042   if (AbsEntity && AbsEntity->getDIE()) {
1043     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1044     Label = dyn_cast<const DbgLabel>(Entity);
1045   } else {
1046     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1047       applyVariableAttributes(*Var, *Die);
1048     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1049       applyLabelAttributes(*Label, *Die);
1050     else
1051       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1052   }
1053 
1054   if (Label)
1055     if (const auto *Sym = Label->getSymbol())
1056       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1057 }
1058 
1059 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1060   auto &AbstractEntities = getAbstractEntities();
1061   auto I = AbstractEntities.find(Node);
1062   if (I != AbstractEntities.end())
1063     return I->second.get();
1064   return nullptr;
1065 }
1066 
1067 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1068                                             LexicalScope *Scope) {
1069   assert(Scope && Scope->isAbstractScope());
1070   auto &Entity = getAbstractEntities()[Node];
1071   if (isa<const DILocalVariable>(Node)) {
1072     Entity = llvm::make_unique<DbgVariable>(
1073                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
1074     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1075   } else if (isa<const DILabel>(Node)) {
1076     Entity = llvm::make_unique<DbgLabel>(
1077                         cast<const DILabel>(Node), nullptr /* IA */);
1078     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1079   }
1080 }
1081 
1082 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1083   // Don't bother labeling the .dwo unit, as its offset isn't used.
1084   if (!Skeleton && !DD->useSectionsAsReferences()) {
1085     LabelBegin = Asm->createTempSymbol("cu_begin");
1086     Asm->OutStreamer->EmitLabel(LabelBegin);
1087   }
1088 
1089   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1090                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1091                                                       : dwarf::DW_UT_compile;
1092   DwarfUnit::emitCommonHeader(UseOffsets, UT);
1093   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1094     Asm->emitInt64(getDWOId());
1095 }
1096 
1097 bool DwarfCompileUnit::hasDwarfPubSections() const {
1098   switch (CUNode->getNameTableKind()) {
1099   case DICompileUnit::DebugNameTableKind::None:
1100     return false;
1101     // Opting in to GNU Pubnames/types overrides the default to ensure these are
1102     // generated for things like Gold's gdb_index generation.
1103   case DICompileUnit::DebugNameTableKind::GNU:
1104     return true;
1105   case DICompileUnit::DebugNameTableKind::Default:
1106     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1107            !CUNode->isDebugDirectivesOnly() &&
1108            DD->getAccelTableKind() != AccelTableKind::Apple &&
1109            DD->getDwarfVersion() < 5;
1110   }
1111   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1112 }
1113 
1114 /// addGlobalName - Add a new global name to the compile unit.
1115 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1116                                      const DIScope *Context) {
1117   if (!hasDwarfPubSections())
1118     return;
1119   std::string FullName = getParentContextString(Context) + Name.str();
1120   GlobalNames[FullName] = &Die;
1121 }
1122 
1123 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1124                                                 const DIScope *Context) {
1125   if (!hasDwarfPubSections())
1126     return;
1127   std::string FullName = getParentContextString(Context) + Name.str();
1128   // Insert, allowing the entry to remain as-is if it's already present
1129   // This way the CU-level type DIE is preferred over the "can't describe this
1130   // type as a unit offset because it's not really in the CU at all, it's only
1131   // in a type unit"
1132   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1133 }
1134 
1135 /// Add a new global type to the unit.
1136 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1137                                      const DIScope *Context) {
1138   if (!hasDwarfPubSections())
1139     return;
1140   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1141   GlobalTypes[FullName] = &Die;
1142 }
1143 
1144 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1145                                              const DIScope *Context) {
1146   if (!hasDwarfPubSections())
1147     return;
1148   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1149   // Insert, allowing the entry to remain as-is if it's already present
1150   // This way the CU-level type DIE is preferred over the "can't describe this
1151   // type as a unit offset because it's not really in the CU at all, it's only
1152   // in a type unit"
1153   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1154 }
1155 
1156 /// addVariableAddress - Add DW_AT_location attribute for a
1157 /// DbgVariable based on provided MachineLocation.
1158 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1159                                           MachineLocation Location) {
1160   // addBlockByrefAddress is obsolete and will be removed soon.
1161   // The clang frontend always generates block byref variables with a
1162   // complex expression that encodes exactly what addBlockByrefAddress
1163   // would do.
1164   assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
1165          "block byref variable without a complex expression");
1166   if (DV.hasComplexAddress())
1167     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1168   else
1169     addAddress(Die, dwarf::DW_AT_location, Location);
1170 }
1171 
1172 /// Add an address attribute to a die based on the location provided.
1173 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1174                                   const MachineLocation &Location) {
1175   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1176   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1177   if (Location.isIndirect())
1178     DwarfExpr.setMemoryLocationKind();
1179 
1180   DIExpressionCursor Cursor({});
1181   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1182   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1183     return;
1184   DwarfExpr.addExpression(std::move(Cursor));
1185 
1186   // Now attach the location information to the DIE.
1187   addBlock(Die, Attribute, DwarfExpr.finalize());
1188 }
1189 
1190 /// Start with the address based on the location provided, and generate the
1191 /// DWARF information necessary to find the actual variable given the extra
1192 /// address information encoded in the DbgVariable, starting from the starting
1193 /// location.  Add the DWARF information to the die.
1194 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1195                                          dwarf::Attribute Attribute,
1196                                          const MachineLocation &Location) {
1197   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1198   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1199   const DIExpression *DIExpr = DV.getSingleExpression();
1200   DwarfExpr.addFragmentOffset(DIExpr);
1201   if (Location.isIndirect())
1202     DwarfExpr.setMemoryLocationKind();
1203 
1204   DIExpressionCursor Cursor(DIExpr);
1205 
1206   if (DIExpr->isEntryValue()) {
1207     DwarfExpr.setEntryValueFlag();
1208     DwarfExpr.addEntryValueExpression(Cursor);
1209   }
1210 
1211   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1212   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1213     return;
1214   DwarfExpr.addExpression(std::move(Cursor));
1215 
1216   // Now attach the location information to the DIE.
1217   addBlock(Die, Attribute, DwarfExpr.finalize());
1218 }
1219 
1220 /// Add a Dwarf loclistptr attribute data and value.
1221 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1222                                        unsigned Index) {
1223   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
1224                                                 : dwarf::DW_FORM_data4;
1225   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
1226 }
1227 
1228 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1229                                                DIE &VariableDie) {
1230   StringRef Name = Var.getName();
1231   if (!Name.empty())
1232     addString(VariableDie, dwarf::DW_AT_name, Name);
1233   const auto *DIVar = Var.getVariable();
1234   if (DIVar)
1235     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1236       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1237               AlignInBytes);
1238 
1239   addSourceLine(VariableDie, DIVar);
1240   addType(VariableDie, Var.getType());
1241   if (Var.isArtificial())
1242     addFlag(VariableDie, dwarf::DW_AT_artificial);
1243 }
1244 
1245 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1246                                             DIE &LabelDie) {
1247   StringRef Name = Label.getName();
1248   if (!Name.empty())
1249     addString(LabelDie, dwarf::DW_AT_name, Name);
1250   const auto *DILabel = Label.getLabel();
1251   addSourceLine(LabelDie, DILabel);
1252 }
1253 
1254 /// Add a Dwarf expression attribute data and value.
1255 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1256                                const MCExpr *Expr) {
1257   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1258 }
1259 
1260 void DwarfCompileUnit::addAddressExpr(DIE &Die, dwarf::Attribute Attribute,
1261                                       const MCExpr *Expr) {
1262   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
1263                DIEExpr(Expr));
1264 }
1265 
1266 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1267     const DISubprogram *SP, DIE &SPDie) {
1268   auto *SPDecl = SP->getDeclaration();
1269   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1270   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1271   addGlobalName(SP->getName(), SPDie, Context);
1272 }
1273 
1274 bool DwarfCompileUnit::isDwoUnit() const {
1275   return DD->useSplitDwarf() && Skeleton;
1276 }
1277 
1278 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1279   constructTypeDIE(D, CTy);
1280 }
1281 
1282 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1283   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1284          (DD->useSplitDwarf() && !Skeleton);
1285 }
1286 
1287 void DwarfCompileUnit::addAddrTableBase() {
1288   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1289   MCSymbol *Label = DD->getAddressPool().getLabel();
1290   addSectionLabel(getUnitDie(),
1291                   getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1292                                          : dwarf::DW_AT_GNU_addr_base,
1293                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1294 }
1295 
1296 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1297   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1298                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1299 }
1300 
1301 void DwarfCompileUnit::createBaseTypeDIEs() {
1302   // Insert the base_type DIEs directly after the CU so that their offsets will
1303   // fit in the fixed size ULEB128 used inside the location expressions.
1304   // Maintain order by iterating backwards and inserting to the front of CU
1305   // child list.
1306   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1307     DIE &Die = getUnitDie().addChildFront(
1308       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1309     SmallString<32> Str;
1310     addString(Die, dwarf::DW_AT_name,
1311               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1312                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
1313     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1314     addUInt(Die, dwarf::DW_AT_byte_size, None, Btr.BitSize / 8);
1315 
1316     Btr.Die = &Die;
1317   }
1318 }
1319