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 "DwarfExpression.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/CodeGen/AsmPrinter.h"
21 #include "llvm/CodeGen/DIE.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/CodeGen/MachineOperand.h"
25 #include "llvm/CodeGen/TargetFrameLowering.h"
26 #include "llvm/CodeGen/TargetRegisterInfo.h"
27 #include "llvm/CodeGen/TargetSubtargetInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/MC/MCSection.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/MC/MCSymbolWasm.h"
35 #include "llvm/MC/MachineLocation.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetMachine.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include <iterator>
40 #include <string>
41 #include <utility>
42 
43 using namespace llvm;
44 
45 static dwarf::Tag GetCompileUnitType(UnitKind Kind, DwarfDebug *DW) {
46 
47   //  According to DWARF Debugging Information Format Version 5,
48   //  3.1.2 Skeleton Compilation Unit Entries:
49   //  "When generating a split DWARF object file (see Section 7.3.2
50   //  on page 187), the compilation unit in the .debug_info section
51   //  is a "skeleton" compilation unit with the tag DW_TAG_skeleton_unit"
52   if (DW->getDwarfVersion() >= 5 && Kind == UnitKind::Skeleton)
53     return dwarf::DW_TAG_skeleton_unit;
54 
55   return dwarf::DW_TAG_compile_unit;
56 }
57 
58 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
59                                    AsmPrinter *A, DwarfDebug *DW,
60                                    DwarfFile *DWU, UnitKind Kind)
61     : DwarfUnit(GetCompileUnitType(Kind, DW), Node, A, DW, DWU), UniqueID(UID) {
62   insertDIE(Node, &getUnitDie());
63   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
64 }
65 
66 /// addLabelAddress - Add a dwarf label attribute data and value using
67 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
68 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
69                                        const MCSymbol *Label) {
70   if ((Skeleton || !DD->useSplitDwarf()) && Label)
71     DD->addArangeLabel(SymbolCU(this, Label));
72 
73   // Don't use the address pool in non-fission or in the skeleton unit itself.
74   if ((!DD->useSplitDwarf() || !Skeleton) && DD->getDwarfVersion() < 5)
75     return addLocalLabelAddress(Die, Attribute, Label);
76 
77   bool UseAddrOffsetFormOrExpressions =
78       DD->useAddrOffsetForm() || DD->useAddrOffsetExpressions();
79 
80   const MCSymbol *Base = nullptr;
81   if (Label->isInSection() && UseAddrOffsetFormOrExpressions)
82     Base = DD->getSectionLabel(&Label->getSection());
83 
84   if (!Base || Base == Label) {
85     unsigned idx = DD->getAddressPool().getIndex(Label);
86     addAttribute(Die, Attribute,
87                  DD->getDwarfVersion() >= 5 ? dwarf::DW_FORM_addrx
88                                             : dwarf::DW_FORM_GNU_addr_index,
89                  DIEInteger(idx));
90     return;
91   }
92 
93   // Could be extended to work with DWARFv4 Split DWARF if that's important for
94   // someone. In that case DW_FORM_data would be used.
95   assert(DD->getDwarfVersion() >= 5 &&
96          "Addr+offset expressions are only valuable when using debug_addr (to "
97          "reduce relocations) available in DWARFv5 or higher");
98   if (DD->useAddrOffsetExpressions()) {
99     auto *Loc = new (DIEValueAllocator) DIEBlock();
100     addPoolOpAddress(*Loc, Label);
101     addBlock(Die, Attribute, dwarf::DW_FORM_exprloc, Loc);
102   } else
103     addAttribute(Die, Attribute, dwarf::DW_FORM_LLVM_addrx_offset,
104                  new (DIEValueAllocator) DIEAddrOffset(
105                      DD->getAddressPool().getIndex(Base), Label, Base));
106 }
107 
108 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
109                                             dwarf::Attribute Attribute,
110                                             const MCSymbol *Label) {
111   if (Label)
112     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIELabel(Label));
113   else
114     addAttribute(Die, Attribute, dwarf::DW_FORM_addr, DIEInteger(0));
115 }
116 
117 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
118   // If we print assembly, we can't separate .file entries according to
119   // compile units. Thus all files will belong to the default compile unit.
120 
121   // FIXME: add a better feature test than hasRawTextSupport. Even better,
122   // extend .file to support this.
123   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
124   if (!File)
125     return Asm->OutStreamer->emitDwarfFileDirective(0, "", "", None, None,
126                                                     CUID);
127 
128   if (LastFile != File) {
129     LastFile = File;
130     LastFileID = Asm->OutStreamer->emitDwarfFileDirective(
131         0, File->getDirectory(), File->getFilename(), DD->getMD5AsBytes(File),
132         File->getSource(), CUID);
133   }
134   return LastFileID;
135 }
136 
137 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
138     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
139   // Check for pre-existence.
140   if (DIE *Die = getDIE(GV))
141     return Die;
142 
143   assert(GV);
144 
145   auto *GVContext = GV->getScope();
146   const DIType *GTy = GV->getType();
147 
148   auto *CB = GVContext ? dyn_cast<DICommonBlock>(GVContext) : nullptr;
149   DIE *ContextDIE = CB ? getOrCreateCommonBlock(CB, GlobalExprs)
150     : getOrCreateContextDIE(GVContext);
151 
152   // Add to map.
153   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
154   DIScope *DeclContext;
155   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
156     DeclContext = SDMDecl->getScope();
157     assert(SDMDecl->isStaticMember() && "Expected static member decl");
158     assert(GV->isDefinition());
159     // We need the declaration DIE that is in the static member's class.
160     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
161     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
162     // If the global variable's type is different from the one in the class
163     // member type, assume that it's more specific and also emit it.
164     if (GTy != SDMDecl->getBaseType())
165       addType(*VariableDIE, GTy);
166   } else {
167     DeclContext = GV->getScope();
168     // Add name and type.
169     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
170     if (GTy)
171       addType(*VariableDIE, GTy);
172 
173     // Add scoping info.
174     if (!GV->isLocalToUnit())
175       addFlag(*VariableDIE, dwarf::DW_AT_external);
176 
177     // Add line number info.
178     addSourceLine(*VariableDIE, GV);
179   }
180 
181   if (!GV->isDefinition())
182     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
183   else
184     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
185 
186   addAnnotation(*VariableDIE, GV->getAnnotations());
187 
188   if (uint32_t AlignInBytes = GV->getAlignInBytes())
189     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
190             AlignInBytes);
191 
192   if (MDTuple *TP = GV->getTemplateParams())
193     addTemplateParams(*VariableDIE, DINodeArray(TP));
194 
195   // Add location.
196   addLocationAttribute(VariableDIE, GV, GlobalExprs);
197 
198   return VariableDIE;
199 }
200 
201 void DwarfCompileUnit::addLocationAttribute(
202     DIE *VariableDIE, const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
203   bool addToAccelTable = false;
204   DIELoc *Loc = nullptr;
205   Optional<unsigned> NVPTXAddressSpace;
206   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
207   for (const auto &GE : GlobalExprs) {
208     const GlobalVariable *Global = GE.Var;
209     const DIExpression *Expr = GE.Expr;
210 
211     // For compatibility with DWARF 3 and earlier,
212     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) or
213     // DW_AT_location(DW_OP_consts, X, DW_OP_stack_value) becomes
214     // DW_AT_const_value(X).
215     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
216       addToAccelTable = true;
217       addConstantValue(
218           *VariableDIE,
219           DIExpression::SignedOrUnsignedConstant::UnsignedConstant ==
220               *Expr->isConstant(),
221           Expr->getElement(1));
222       break;
223     }
224 
225     // We cannot describe the location of dllimport'd variables: the
226     // computation of their address requires loads from the IAT.
227     if (Global && Global->hasDLLImportStorageClass())
228       continue;
229 
230     // Nothing to describe without address or constant.
231     if (!Global && (!Expr || !Expr->isConstant()))
232       continue;
233 
234     if (Global && Global->isThreadLocal() &&
235         !Asm->getObjFileLowering().supportDebugThreadLocalLocation())
236       continue;
237 
238     if (!Loc) {
239       addToAccelTable = true;
240       Loc = new (DIEValueAllocator) DIELoc;
241       DwarfExpr = std::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
242     }
243 
244     if (Expr) {
245       // According to
246       // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
247       // cuda-gdb requires DW_AT_address_class for all variables to be able to
248       // correctly interpret address space of the variable address.
249       // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
250       // sequence for the NVPTX + gdb target.
251       unsigned LocalNVPTXAddressSpace;
252       if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
253         const DIExpression *NewExpr =
254             DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
255         if (NewExpr != Expr) {
256           Expr = NewExpr;
257           NVPTXAddressSpace = LocalNVPTXAddressSpace;
258         }
259       }
260       DwarfExpr->addFragmentOffset(Expr);
261     }
262 
263     if (Global) {
264       const MCSymbol *Sym = Asm->getSymbol(Global);
265       // 16-bit platforms like MSP430 and AVR take this path, so sink this
266       // assert to platforms that use it.
267       auto GetPointerSizedFormAndOp = [this]() {
268         unsigned PointerSize = Asm->getDataLayout().getPointerSize();
269         assert((PointerSize == 4 || PointerSize == 8) &&
270                "Add support for other sizes if necessary");
271         struct FormAndOp {
272           dwarf::Form Form;
273           dwarf::LocationAtom Op;
274         };
275         return PointerSize == 4
276                    ? FormAndOp{dwarf::DW_FORM_data4, dwarf::DW_OP_const4u}
277                    : FormAndOp{dwarf::DW_FORM_data8, dwarf::DW_OP_const8u};
278       };
279       if (Global->isThreadLocal()) {
280         if (Asm->TM.useEmulatedTLS()) {
281           // TODO: add debug info for emulated thread local mode.
282         } else {
283           // FIXME: Make this work with -gsplit-dwarf.
284           // Based on GCC's support for TLS:
285           if (!DD->useSplitDwarf()) {
286             auto FormAndOp = GetPointerSizedFormAndOp();
287             // 1) Start with a constNu of the appropriate pointer size
288             addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
289             // 2) containing the (relocated) offset of the TLS variable
290             //    within the module's TLS block.
291             addExpr(*Loc, FormAndOp.Form,
292                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
293           } else {
294             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
295             addUInt(*Loc, dwarf::DW_FORM_udata,
296                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
297           }
298           // 3) followed by an OP to make the debugger do a TLS lookup.
299           addUInt(*Loc, dwarf::DW_FORM_data1,
300                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
301                                         : dwarf::DW_OP_form_tls_address);
302         }
303       } else if (Asm->TM.getRelocationModel() == Reloc::RWPI ||
304                  Asm->TM.getRelocationModel() == Reloc::ROPI_RWPI) {
305         auto FormAndOp = GetPointerSizedFormAndOp();
306         // Constant
307         addUInt(*Loc, dwarf::DW_FORM_data1, FormAndOp.Op);
308         // Relocation offset
309         addExpr(*Loc, FormAndOp.Form,
310                 Asm->getObjFileLowering().getIndirectSymViaRWPI(Sym));
311         // Base register
312         Register BaseReg = Asm->getObjFileLowering().getStaticBase();
313         BaseReg = Asm->TM.getMCRegisterInfo()->getDwarfRegNum(BaseReg, false);
314         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + BaseReg);
315         // Offset from base register
316         addSInt(*Loc, dwarf::DW_FORM_sdata, 0);
317         // Operation
318         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
319       } else {
320         DD->addArangeLabel(SymbolCU(this, Sym));
321         addOpAddress(*Loc, Sym);
322       }
323     }
324     // Global variables attached to symbols are memory locations.
325     // It would be better if this were unconditional, but malformed input that
326     // mixes non-fragments and fragments for the same variable is too expensive
327     // to detect in the verifier.
328     if (DwarfExpr->isUnknownLocation())
329       DwarfExpr->setMemoryLocationKind();
330     DwarfExpr->addExpression(Expr);
331   }
332   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
333     // According to
334     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
335     // cuda-gdb requires DW_AT_address_class for all variables to be able to
336     // correctly interpret address space of the variable address.
337     const unsigned NVPTX_ADDR_global_space = 5;
338     addUInt(*VariableDIE, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
339             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_global_space);
340   }
341   if (Loc)
342     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
343 
344   if (DD->useAllLinkageNames())
345     addLinkageName(*VariableDIE, GV->getLinkageName());
346 
347   if (addToAccelTable) {
348     DD->addAccelName(*CUNode, GV->getName(), *VariableDIE);
349 
350     // If the linkage name is different than the name, go ahead and output
351     // that as well into the name table.
352     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName() &&
353         DD->useAllLinkageNames())
354       DD->addAccelName(*CUNode, GV->getLinkageName(), *VariableDIE);
355   }
356 }
357 
358 DIE *DwarfCompileUnit::getOrCreateCommonBlock(
359     const DICommonBlock *CB, ArrayRef<GlobalExpr> GlobalExprs) {
360   // Check for pre-existence.
361   if (DIE *NDie = getDIE(CB))
362     return NDie;
363   DIE *ContextDIE = getOrCreateContextDIE(CB->getScope());
364   DIE &NDie = createAndAddDIE(dwarf::DW_TAG_common_block, *ContextDIE, CB);
365   StringRef Name = CB->getName().empty() ? "_BLNK_" : CB->getName();
366   addString(NDie, dwarf::DW_AT_name, Name);
367   addGlobalName(Name, NDie, CB->getScope());
368   if (CB->getFile())
369     addSourceLine(NDie, CB->getLineNo(), CB->getFile());
370   if (DIGlobalVariable *V = CB->getDecl())
371     getCU().addLocationAttribute(&NDie, V, GlobalExprs);
372   return &NDie;
373 }
374 
375 void DwarfCompileUnit::addRange(RangeSpan Range) {
376   DD->insertSectionLabel(Range.Begin);
377 
378   auto *PrevCU = DD->getPrevCU();
379   bool SameAsPrevCU = this == PrevCU;
380   DD->setPrevCU(this);
381   // If we have no current ranges just add the range and return, otherwise,
382   // check the current section and CU against the previous section and CU we
383   // emitted into and the subprogram was contained within. If these are the
384   // same then extend our current range, otherwise add this as a new range.
385   if (CURanges.empty() || !SameAsPrevCU ||
386       (&CURanges.back().End->getSection() !=
387        &Range.End->getSection())) {
388     // Before a new range is added, always terminate the prior line table.
389     if (PrevCU)
390       DD->terminateLineTable(PrevCU);
391     CURanges.push_back(Range);
392     return;
393   }
394 
395   CURanges.back().End = Range.End;
396 }
397 
398 void DwarfCompileUnit::initStmtList() {
399   if (CUNode->isDebugDirectivesOnly())
400     return;
401 
402   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
403   if (DD->useSectionsAsReferences()) {
404     LineTableStartSym = TLOF.getDwarfLineSection()->getBeginSymbol();
405   } else {
406     LineTableStartSym =
407         Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
408   }
409 
410   // DW_AT_stmt_list is a offset of line number information for this
411   // compile unit in debug_line section. For split dwarf this is
412   // left in the skeleton CU and so not included.
413   // The line table entries are not always emitted in assembly, so it
414   // is not okay to use line_table_start here.
415       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
416                       TLOF.getDwarfLineSection()->getBeginSymbol());
417 }
418 
419 void DwarfCompileUnit::applyStmtList(DIE &D) {
420   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
421   addSectionLabel(D, dwarf::DW_AT_stmt_list, LineTableStartSym,
422                   TLOF.getDwarfLineSection()->getBeginSymbol());
423 }
424 
425 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
426                                        const MCSymbol *End) {
427   assert(Begin && "Begin label should not be null!");
428   assert(End && "End label should not be null!");
429   assert(Begin->isDefined() && "Invalid starting label");
430   assert(End->isDefined() && "Invalid end label");
431 
432   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
433   if (DD->getDwarfVersion() < 4)
434     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
435   else
436     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
437 }
438 
439 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
440 // and DW_AT_high_pc attributes. If there are global variables in this
441 // scope then create and insert DIEs for these variables.
442 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
443   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
444 
445   SmallVector<RangeSpan, 2> BB_List;
446   // If basic block sections are on, ranges for each basic block section has
447   // to be emitted separately.
448   for (const auto &R : Asm->MBBSectionRanges)
449     BB_List.push_back({R.second.BeginLabel, R.second.EndLabel});
450 
451   attachRangesOrLowHighPC(*SPDie, BB_List);
452 
453   if (DD->useAppleExtensionAttributes() &&
454       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
455           *DD->getCurrentFunction()))
456     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
457 
458   // Only include DW_AT_frame_base in full debug info
459   if (!includeMinimalInlineScopes()) {
460     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
461     TargetFrameLowering::DwarfFrameBase FrameBase =
462         TFI->getDwarfFrameBase(*Asm->MF);
463     switch (FrameBase.Kind) {
464     case TargetFrameLowering::DwarfFrameBase::Register: {
465       if (Register::isPhysicalRegister(FrameBase.Location.Reg)) {
466         MachineLocation Location(FrameBase.Location.Reg);
467         addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
468       }
469       break;
470     }
471     case TargetFrameLowering::DwarfFrameBase::CFA: {
472       DIELoc *Loc = new (DIEValueAllocator) DIELoc;
473       addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_call_frame_cfa);
474       addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
475       break;
476     }
477     case TargetFrameLowering::DwarfFrameBase::WasmFrameBase: {
478       // FIXME: duplicated from Target/WebAssembly/WebAssembly.h
479       // don't want to depend on target specific headers in this code?
480       const unsigned TI_GLOBAL_RELOC = 3;
481       if (FrameBase.Location.WasmLoc.Kind == TI_GLOBAL_RELOC) {
482         // These need to be relocatable.
483         assert(FrameBase.Location.WasmLoc.Index == 0);  // Only SP so far.
484         auto SPSym = cast<MCSymbolWasm>(
485           Asm->GetExternalSymbolSymbol("__stack_pointer"));
486         // FIXME: this repeats what WebAssemblyMCInstLower::
487         // GetExternalSymbolSymbol does, since if there's no code that
488         // refers to this symbol, we have to set it here.
489         SPSym->setType(wasm::WASM_SYMBOL_TYPE_GLOBAL);
490         SPSym->setGlobalType(wasm::WasmGlobalType{
491             uint8_t(Asm->getSubtargetInfo().getTargetTriple().getArch() ==
492                             Triple::wasm64
493                         ? wasm::WASM_TYPE_I64
494                         : wasm::WASM_TYPE_I32),
495             true});
496         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
497         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_WASM_location);
498         addSInt(*Loc, dwarf::DW_FORM_sdata, TI_GLOBAL_RELOC);
499         if (!isDwoUnit()) {
500           addLabel(*Loc, dwarf::DW_FORM_data4, SPSym);
501         } else {
502           // FIXME: when writing dwo, we need to avoid relocations. Probably
503           // the "right" solution is to treat globals the way func and data
504           // symbols are (with entries in .debug_addr).
505           // For now, since we only ever use index 0, this should work as-is.
506           addUInt(*Loc, dwarf::DW_FORM_data4, FrameBase.Location.WasmLoc.Index);
507         }
508         addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value);
509         addBlock(*SPDie, dwarf::DW_AT_frame_base, Loc);
510       } else {
511         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
512         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
513         DIExpressionCursor Cursor({});
514         DwarfExpr.addWasmLocation(FrameBase.Location.WasmLoc.Kind,
515             FrameBase.Location.WasmLoc.Index);
516         DwarfExpr.addExpression(std::move(Cursor));
517         addBlock(*SPDie, dwarf::DW_AT_frame_base, DwarfExpr.finalize());
518       }
519       break;
520     }
521     }
522   }
523 
524   // Add name to the name table, we do this here because we're guaranteed
525   // to have concrete versions of our DW_TAG_subprogram nodes.
526   DD->addSubprogramNames(*CUNode, SP, *SPDie);
527 
528   return *SPDie;
529 }
530 
531 // Construct a DIE for this scope.
532 void DwarfCompileUnit::constructScopeDIE(LexicalScope *Scope,
533                                          DIE &ParentScopeDIE) {
534   if (!Scope || !Scope->getScopeNode())
535     return;
536 
537   auto *DS = Scope->getScopeNode();
538 
539   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
540          "Only handle inlined subprograms here, use "
541          "constructSubprogramScopeDIE for non-inlined "
542          "subprograms");
543 
544   // Emit inlined subprograms.
545   if (Scope->getParent() && isa<DISubprogram>(DS)) {
546     DIE *ScopeDIE = constructInlinedScopeDIE(Scope);
547     if (!ScopeDIE)
548       return;
549 
550     ParentScopeDIE.addChild(ScopeDIE);
551     createAndAddScopeChildren(Scope, *ScopeDIE);
552     return;
553   }
554 
555   // Early exit when we know the scope DIE is going to be null.
556   if (DD->isLexicalScopeDIENull(Scope))
557     return;
558 
559   // Emit lexical blocks.
560   DIE *ScopeDIE = constructLexicalScopeDIE(Scope);
561   assert(ScopeDIE && "Scope DIE should not be null.");
562 
563   ParentScopeDIE.addChild(ScopeDIE);
564   createAndAddScopeChildren(Scope, *ScopeDIE);
565 }
566 
567 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
568                                          SmallVector<RangeSpan, 2> Range) {
569 
570   HasRangeLists = true;
571 
572   // Add the range list to the set of ranges to be emitted.
573   auto IndexAndList =
574       (DD->getDwarfVersion() < 5 && Skeleton ? Skeleton->DU : DU)
575           ->addRange(*(Skeleton ? Skeleton : this), std::move(Range));
576 
577   uint32_t Index = IndexAndList.first;
578   auto &List = *IndexAndList.second;
579 
580   // Under fission, ranges are specified by constant offsets relative to the
581   // CU's DW_AT_GNU_ranges_base.
582   // FIXME: For DWARF v5, do not generate the DW_AT_ranges attribute under
583   // fission until we support the forms using the .debug_addr section
584   // (DW_RLE_startx_endx etc.).
585   if (DD->getDwarfVersion() >= 5)
586     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_rnglistx, Index);
587   else {
588     const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
589     const MCSymbol *RangeSectionSym =
590         TLOF.getDwarfRangesSection()->getBeginSymbol();
591     if (isDwoUnit())
592       addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
593                       RangeSectionSym);
594     else
595       addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.Label,
596                       RangeSectionSym);
597   }
598 }
599 
600 void DwarfCompileUnit::attachRangesOrLowHighPC(
601     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
602   assert(!Ranges.empty());
603   if (!DD->useRangesSection() ||
604       (Ranges.size() == 1 &&
605        (!DD->alwaysUseRanges() ||
606         DD->getSectionLabel(&Ranges.front().Begin->getSection()) ==
607             Ranges.front().Begin))) {
608     const RangeSpan &Front = Ranges.front();
609     const RangeSpan &Back = Ranges.back();
610     attachLowHighPC(Die, Front.Begin, Back.End);
611   } else
612     addScopeRangeList(Die, std::move(Ranges));
613 }
614 
615 void DwarfCompileUnit::attachRangesOrLowHighPC(
616     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
617   SmallVector<RangeSpan, 2> List;
618   List.reserve(Ranges.size());
619   for (const InsnRange &R : Ranges) {
620     auto *BeginLabel = DD->getLabelBeforeInsn(R.first);
621     auto *EndLabel = DD->getLabelAfterInsn(R.second);
622 
623     const auto *BeginMBB = R.first->getParent();
624     const auto *EndMBB = R.second->getParent();
625 
626     const auto *MBB = BeginMBB;
627     // Basic block sections allows basic block subsets to be placed in unique
628     // sections. For each section, the begin and end label must be added to the
629     // list. If there is more than one range, debug ranges must be used.
630     // Otherwise, low/high PC can be used.
631     // FIXME: Debug Info Emission depends on block order and this assumes that
632     // the order of blocks will be frozen beyond this point.
633     do {
634       if (MBB->sameSection(EndMBB) || MBB->isEndSection()) {
635         auto MBBSectionRange = Asm->MBBSectionRanges[MBB->getSectionIDNum()];
636         List.push_back(
637             {MBB->sameSection(BeginMBB) ? BeginLabel
638                                         : MBBSectionRange.BeginLabel,
639              MBB->sameSection(EndMBB) ? EndLabel : MBBSectionRange.EndLabel});
640       }
641       if (MBB->sameSection(EndMBB))
642         break;
643       MBB = MBB->getNextNode();
644     } while (true);
645   }
646   attachRangesOrLowHighPC(Die, std::move(List));
647 }
648 
649 // This scope represents inlined body of a function. Construct DIE to
650 // represent this concrete inlined copy of the function.
651 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
652   assert(Scope->getScopeNode());
653   auto *DS = Scope->getScopeNode();
654   auto *InlinedSP = getDISubprogram(DS);
655   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
656   // was inlined from another compile unit.
657   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
658   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
659 
660   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
661   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
662 
663   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
664 
665   // Add the call site information to the DIE.
666   const DILocation *IA = Scope->getInlinedAt();
667   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
668           getOrCreateSourceID(IA->getFile()));
669   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
670   if (IA->getColumn())
671     addUInt(*ScopeDIE, dwarf::DW_AT_call_column, None, IA->getColumn());
672   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
673     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
674             IA->getDiscriminator());
675 
676   // Add name to the name table, we do this here because we're guaranteed
677   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
678   DD->addSubprogramNames(*CUNode, InlinedSP, *ScopeDIE);
679 
680   return ScopeDIE;
681 }
682 
683 // Construct new DW_TAG_lexical_block for this scope and attach
684 // DW_AT_low_pc/DW_AT_high_pc labels.
685 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
686   if (DD->isLexicalScopeDIENull(Scope))
687     return nullptr;
688 
689   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
690   if (Scope->isAbstractScope())
691     return ScopeDIE;
692 
693   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
694 
695   return ScopeDIE;
696 }
697 
698 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
699 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
700   auto D = constructVariableDIEImpl(DV, Abstract);
701   DV.setDIE(*D);
702   return D;
703 }
704 
705 DIE *DwarfCompileUnit::constructLabelDIE(DbgLabel &DL,
706                                          const LexicalScope &Scope) {
707   auto LabelDie = DIE::get(DIEValueAllocator, DL.getTag());
708   insertDIE(DL.getLabel(), LabelDie);
709   DL.setDIE(*LabelDie);
710 
711   if (Scope.isAbstractScope())
712     applyLabelAttributes(DL, *LabelDie);
713 
714   return LabelDie;
715 }
716 
717 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
718                                                 bool Abstract) {
719   // Define variable debug information entry.
720   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
721   insertDIE(DV.getVariable(), VariableDie);
722 
723   if (Abstract) {
724     applyVariableAttributes(DV, *VariableDie);
725     return VariableDie;
726   }
727 
728   // Add variable address.
729 
730   unsigned Index = DV.getDebugLocListIndex();
731   if (Index != ~0U) {
732     addLocationList(*VariableDie, dwarf::DW_AT_location, Index);
733     auto TagOffset = DV.getDebugLocListTagOffset();
734     if (TagOffset)
735       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
736               *TagOffset);
737     return VariableDie;
738   }
739 
740   // Check if variable has a single location description.
741   if (auto *DVal = DV.getValueLoc()) {
742     if (!DVal->isVariadic()) {
743       const DbgValueLocEntry *Entry = DVal->getLocEntries().begin();
744       if (Entry->isLocation()) {
745         addVariableAddress(DV, *VariableDie, Entry->getLoc());
746       } else if (Entry->isInt()) {
747         auto *Expr = DV.getSingleExpression();
748         if (Expr && Expr->getNumElements()) {
749           DIELoc *Loc = new (DIEValueAllocator) DIELoc;
750           DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
751           // If there is an expression, emit raw unsigned bytes.
752           DwarfExpr.addFragmentOffset(Expr);
753           DwarfExpr.addUnsignedConstant(Entry->getInt());
754           DwarfExpr.addExpression(Expr);
755           addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
756           if (DwarfExpr.TagOffset)
757             addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset,
758                     dwarf::DW_FORM_data1, *DwarfExpr.TagOffset);
759         } else
760           addConstantValue(*VariableDie, Entry->getInt(), DV.getType());
761       } else if (Entry->isConstantFP()) {
762         addConstantFPValue(*VariableDie, Entry->getConstantFP());
763       } else if (Entry->isConstantInt()) {
764         addConstantValue(*VariableDie, Entry->getConstantInt(), DV.getType());
765       } else if (Entry->isTargetIndexLocation()) {
766         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
767         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
768         const DIBasicType *BT = dyn_cast<DIBasicType>(
769             static_cast<const Metadata *>(DV.getVariable()->getType()));
770         DwarfDebug::emitDebugLocValue(*Asm, BT, *DVal, DwarfExpr);
771         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
772       }
773       return VariableDie;
774     }
775     // If any of the location entries are registers with the value 0, then the
776     // location is undefined.
777     if (any_of(DVal->getLocEntries(), [](const DbgValueLocEntry &Entry) {
778           return Entry.isLocation() && !Entry.getLoc().getReg();
779         }))
780       return VariableDie;
781     const DIExpression *Expr = DV.getSingleExpression();
782     assert(Expr && "Variadic Debug Value must have an Expression.");
783     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
784     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
785     DwarfExpr.addFragmentOffset(Expr);
786     DIExpressionCursor Cursor(Expr);
787     const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
788 
789     auto AddEntry = [&](const DbgValueLocEntry &Entry,
790                         DIExpressionCursor &Cursor) {
791       if (Entry.isLocation()) {
792         if (!DwarfExpr.addMachineRegExpression(TRI, Cursor,
793                                                Entry.getLoc().getReg()))
794           return false;
795       } else if (Entry.isInt()) {
796         // If there is an expression, emit raw unsigned bytes.
797         DwarfExpr.addUnsignedConstant(Entry.getInt());
798       } else if (Entry.isConstantFP()) {
799         // DwarfExpression does not support arguments wider than 64 bits
800         // (see PR52584).
801         // TODO: Consider chunking expressions containing overly wide
802         // arguments into separate pointer-sized fragment expressions.
803         APInt RawBytes = Entry.getConstantFP()->getValueAPF().bitcastToAPInt();
804         if (RawBytes.getBitWidth() > 64)
805           return false;
806         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
807       } else if (Entry.isConstantInt()) {
808         APInt RawBytes = Entry.getConstantInt()->getValue();
809         if (RawBytes.getBitWidth() > 64)
810           return false;
811         DwarfExpr.addUnsignedConstant(RawBytes.getZExtValue());
812       } else if (Entry.isTargetIndexLocation()) {
813         TargetIndexLocation Loc = Entry.getTargetIndexLocation();
814         // TODO TargetIndexLocation is a target-independent. Currently only the
815         // WebAssembly-specific encoding is supported.
816         assert(Asm->TM.getTargetTriple().isWasm());
817         DwarfExpr.addWasmLocation(Loc.Index, static_cast<uint64_t>(Loc.Offset));
818       } else {
819         llvm_unreachable("Unsupported Entry type.");
820       }
821       return true;
822     };
823 
824     if (!DwarfExpr.addExpression(
825             std::move(Cursor),
826             [&](unsigned Idx, DIExpressionCursor &Cursor) -> bool {
827               return AddEntry(DVal->getLocEntries()[Idx], Cursor);
828             }))
829       return VariableDie;
830 
831     // Now attach the location information to the DIE.
832     addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
833     if (DwarfExpr.TagOffset)
834       addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
835               *DwarfExpr.TagOffset);
836 
837     return VariableDie;
838   }
839 
840   // .. else use frame index.
841   if (!DV.hasFrameIndexExprs())
842     return VariableDie;
843 
844   Optional<unsigned> NVPTXAddressSpace;
845   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
846   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
847   for (auto &Fragment : DV.getFrameIndexExprs()) {
848     Register FrameReg;
849     const DIExpression *Expr = Fragment.Expr;
850     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
851     StackOffset Offset =
852         TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
853     DwarfExpr.addFragmentOffset(Expr);
854 
855     auto *TRI = Asm->MF->getSubtarget().getRegisterInfo();
856     SmallVector<uint64_t, 8> Ops;
857     TRI->getOffsetOpcodes(Offset, Ops);
858 
859     // According to
860     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
861     // cuda-gdb requires DW_AT_address_class for all variables to be able to
862     // correctly interpret address space of the variable address.
863     // Decode DW_OP_constu <DWARF Address Space> DW_OP_swap DW_OP_xderef
864     // sequence for the NVPTX + gdb target.
865     unsigned LocalNVPTXAddressSpace;
866     if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
867       const DIExpression *NewExpr =
868           DIExpression::extractAddressClass(Expr, LocalNVPTXAddressSpace);
869       if (NewExpr != Expr) {
870         Expr = NewExpr;
871         NVPTXAddressSpace = LocalNVPTXAddressSpace;
872       }
873     }
874     if (Expr)
875       Ops.append(Expr->elements_begin(), Expr->elements_end());
876     DIExpressionCursor Cursor(Ops);
877     DwarfExpr.setMemoryLocationKind();
878     if (const MCSymbol *FrameSymbol = Asm->getFunctionFrameSymbol())
879       addOpAddress(*Loc, FrameSymbol);
880     else
881       DwarfExpr.addMachineRegExpression(
882           *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
883     DwarfExpr.addExpression(std::move(Cursor));
884   }
885   if (Asm->TM.getTargetTriple().isNVPTX() && DD->tuneForGDB()) {
886     // According to
887     // https://docs.nvidia.com/cuda/archive/10.0/ptx-writers-guide-to-interoperability/index.html#cuda-specific-dwarf
888     // cuda-gdb requires DW_AT_address_class for all variables to be able to
889     // correctly interpret address space of the variable address.
890     const unsigned NVPTX_ADDR_local_space = 6;
891     addUInt(*VariableDie, dwarf::DW_AT_address_class, dwarf::DW_FORM_data1,
892             NVPTXAddressSpace ? *NVPTXAddressSpace : NVPTX_ADDR_local_space);
893   }
894   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
895   if (DwarfExpr.TagOffset)
896     addUInt(*VariableDie, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
897             *DwarfExpr.TagOffset);
898 
899   return VariableDie;
900 }
901 
902 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
903                                             const LexicalScope &Scope,
904                                             DIE *&ObjectPointer) {
905   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
906   if (DV.isObjectPointer())
907     ObjectPointer = Var;
908   return Var;
909 }
910 
911 /// Return all DIVariables that appear in count: expressions.
912 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
913   SmallVector<const DIVariable *, 2> Result;
914   auto *Array = dyn_cast<DICompositeType>(Var->getType());
915   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
916     return Result;
917   if (auto *DLVar = Array->getDataLocation())
918     Result.push_back(DLVar);
919   if (auto *AsVar = Array->getAssociated())
920     Result.push_back(AsVar);
921   if (auto *AlVar = Array->getAllocated())
922     Result.push_back(AlVar);
923   for (auto *El : Array->getElements()) {
924     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
925       if (auto Count = Subrange->getCount())
926         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
927           Result.push_back(Dependency);
928       if (auto LB = Subrange->getLowerBound())
929         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
930           Result.push_back(Dependency);
931       if (auto UB = Subrange->getUpperBound())
932         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
933           Result.push_back(Dependency);
934       if (auto ST = Subrange->getStride())
935         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
936           Result.push_back(Dependency);
937     } else if (auto *GenericSubrange = dyn_cast<DIGenericSubrange>(El)) {
938       if (auto Count = GenericSubrange->getCount())
939         if (auto *Dependency = Count.dyn_cast<DIVariable *>())
940           Result.push_back(Dependency);
941       if (auto LB = GenericSubrange->getLowerBound())
942         if (auto *Dependency = LB.dyn_cast<DIVariable *>())
943           Result.push_back(Dependency);
944       if (auto UB = GenericSubrange->getUpperBound())
945         if (auto *Dependency = UB.dyn_cast<DIVariable *>())
946           Result.push_back(Dependency);
947       if (auto ST = GenericSubrange->getStride())
948         if (auto *Dependency = ST.dyn_cast<DIVariable *>())
949           Result.push_back(Dependency);
950     }
951   }
952   return Result;
953 }
954 
955 /// Sort local variables so that variables appearing inside of helper
956 /// expressions come first.
957 static SmallVector<DbgVariable *, 8>
958 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
959   SmallVector<DbgVariable *, 8> Result;
960   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
961   // Map back from a DIVariable to its containing DbgVariable.
962   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
963   // Set of DbgVariables in Result.
964   SmallDenseSet<DbgVariable *, 8> Visited;
965   // For cycle detection.
966   SmallDenseSet<DbgVariable *, 8> Visiting;
967 
968   // Initialize the worklist and the DIVariable lookup table.
969   for (auto Var : reverse(Input)) {
970     DbgVar.insert({Var->getVariable(), Var});
971     WorkList.push_back({Var, 0});
972   }
973 
974   // Perform a stable topological sort by doing a DFS.
975   while (!WorkList.empty()) {
976     auto Item = WorkList.back();
977     DbgVariable *Var = Item.getPointer();
978     bool visitedAllDependencies = Item.getInt();
979     WorkList.pop_back();
980 
981     assert(Var);
982 
983     // Already handled.
984     if (Visited.count(Var))
985       continue;
986 
987     // Add to Result if all dependencies are visited.
988     if (visitedAllDependencies) {
989       Visited.insert(Var);
990       Result.push_back(Var);
991       continue;
992     }
993 
994     // Detect cycles.
995     auto Res = Visiting.insert(Var);
996     if (!Res.second) {
997       assert(false && "dependency cycle in local variables");
998       return Result;
999     }
1000 
1001     // Push dependencies and this node onto the worklist, so that this node is
1002     // visited again after all of its dependencies are handled.
1003     WorkList.push_back({Var, 1});
1004     for (auto *Dependency : dependencies(Var)) {
1005       // Don't add dependency if it is in a different lexical scope or a global.
1006       if (const auto *Dep = dyn_cast<const DILocalVariable>(Dependency))
1007         if (DbgVariable *Var = DbgVar.lookup(Dep))
1008           WorkList.push_back({Var, 0});
1009     }
1010   }
1011   return Result;
1012 }
1013 
1014 DIE &DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub,
1015                                                    LexicalScope *Scope) {
1016   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
1017 
1018   if (Scope) {
1019     assert(!Scope->getInlinedAt());
1020     assert(!Scope->isAbstractScope());
1021     // Collect lexical scope children first.
1022     // ObjectPointer might be a local (non-argument) local variable if it's a
1023     // block's synthetic this pointer.
1024     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
1025       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
1026   }
1027 
1028   // If this is a variadic function, add an unspecified parameter.
1029   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
1030 
1031   // If we have a single element of null, it is a function that returns void.
1032   // If we have more than one elements and the last one is null, it is a
1033   // variadic function.
1034   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
1035       !includeMinimalInlineScopes())
1036     ScopeDIE.addChild(
1037         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
1038 
1039   return ScopeDIE;
1040 }
1041 
1042 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
1043                                                  DIE &ScopeDIE) {
1044   DIE *ObjectPointer = nullptr;
1045 
1046   // Emit function arguments (order is significant).
1047   auto Vars = DU->getScopeVariables().lookup(Scope);
1048   for (auto &DV : Vars.Args)
1049     ScopeDIE.addChild(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
1050 
1051   // Emit local variables.
1052   auto Locals = sortLocalVars(Vars.Locals);
1053   for (DbgVariable *DV : Locals)
1054     ScopeDIE.addChild(constructVariableDIE(*DV, *Scope, ObjectPointer));
1055 
1056   // Emit imported entities (skipped in gmlt-like data).
1057   if (!includeMinimalInlineScopes()) {
1058     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
1059       ScopeDIE.addChild(constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
1060   }
1061 
1062   // Emit labels.
1063   for (DbgLabel *DL : DU->getScopeLabels().lookup(Scope))
1064     ScopeDIE.addChild(constructLabelDIE(*DL, *Scope));
1065 
1066   // Emit inner lexical scopes.
1067   auto needToEmitLexicalScope = [this](LexicalScope *LS) {
1068     if (isa<DISubprogram>(LS->getScopeNode()))
1069       return true;
1070     auto Vars = DU->getScopeVariables().lookup(LS);
1071     if (!Vars.Args.empty() || !Vars.Locals.empty())
1072       return true;
1073     if (!includeMinimalInlineScopes() &&
1074         !ImportedEntities[LS->getScopeNode()].empty())
1075       return true;
1076     return false;
1077   };
1078   for (LexicalScope *LS : Scope->getChildren()) {
1079     // If the lexical block doesn't have non-scope children, skip
1080     // its emission and put its children directly to the parent scope.
1081     if (needToEmitLexicalScope(LS))
1082       constructScopeDIE(LS, ScopeDIE);
1083     else
1084       createAndAddScopeChildren(LS, ScopeDIE);
1085   }
1086 
1087   return ObjectPointer;
1088 }
1089 
1090 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
1091     LexicalScope *Scope) {
1092   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
1093   if (AbsDef)
1094     return;
1095 
1096   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
1097 
1098   DIE *ContextDIE;
1099   DwarfCompileUnit *ContextCU = this;
1100 
1101   if (includeMinimalInlineScopes())
1102     ContextDIE = &getUnitDie();
1103   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
1104   // the important distinction that the debug node is not associated with the
1105   // DIE (since the debug node will be associated with the concrete DIE, if
1106   // any). It could be refactored to some common utility function.
1107   else if (auto *SPDecl = SP->getDeclaration()) {
1108     ContextDIE = &getUnitDie();
1109     getOrCreateSubprogramDIE(SPDecl);
1110   } else {
1111     ContextDIE = getOrCreateContextDIE(SP->getScope());
1112     // The scope may be shared with a subprogram that has already been
1113     // constructed in another CU, in which case we need to construct this
1114     // subprogram in the same CU.
1115     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
1116   }
1117 
1118   // Passing null as the associated node because the abstract definition
1119   // shouldn't be found by lookup.
1120   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
1121   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
1122   ContextCU->addSInt(*AbsDef, dwarf::DW_AT_inline,
1123                      DD->getDwarfVersion() <= 4 ? Optional<dwarf::Form>()
1124                                                 : dwarf::DW_FORM_implicit_const,
1125                      dwarf::DW_INL_inlined);
1126   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
1127     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
1128 }
1129 
1130 bool DwarfCompileUnit::useGNUAnalogForDwarf5Feature() const {
1131   return DD->getDwarfVersion() == 4 && !DD->tuneForLLDB();
1132 }
1133 
1134 dwarf::Tag DwarfCompileUnit::getDwarf5OrGNUTag(dwarf::Tag Tag) const {
1135   if (!useGNUAnalogForDwarf5Feature())
1136     return Tag;
1137   switch (Tag) {
1138   case dwarf::DW_TAG_call_site:
1139     return dwarf::DW_TAG_GNU_call_site;
1140   case dwarf::DW_TAG_call_site_parameter:
1141     return dwarf::DW_TAG_GNU_call_site_parameter;
1142   default:
1143     llvm_unreachable("DWARF5 tag with no GNU analog");
1144   }
1145 }
1146 
1147 dwarf::Attribute
1148 DwarfCompileUnit::getDwarf5OrGNUAttr(dwarf::Attribute Attr) const {
1149   if (!useGNUAnalogForDwarf5Feature())
1150     return Attr;
1151   switch (Attr) {
1152   case dwarf::DW_AT_call_all_calls:
1153     return dwarf::DW_AT_GNU_all_call_sites;
1154   case dwarf::DW_AT_call_target:
1155     return dwarf::DW_AT_GNU_call_site_target;
1156   case dwarf::DW_AT_call_origin:
1157     return dwarf::DW_AT_abstract_origin;
1158   case dwarf::DW_AT_call_return_pc:
1159     return dwarf::DW_AT_low_pc;
1160   case dwarf::DW_AT_call_value:
1161     return dwarf::DW_AT_GNU_call_site_value;
1162   case dwarf::DW_AT_call_tail_call:
1163     return dwarf::DW_AT_GNU_tail_call;
1164   default:
1165     llvm_unreachable("DWARF5 attribute with no GNU analog");
1166   }
1167 }
1168 
1169 dwarf::LocationAtom
1170 DwarfCompileUnit::getDwarf5OrGNULocationAtom(dwarf::LocationAtom Loc) const {
1171   if (!useGNUAnalogForDwarf5Feature())
1172     return Loc;
1173   switch (Loc) {
1174   case dwarf::DW_OP_entry_value:
1175     return dwarf::DW_OP_GNU_entry_value;
1176   default:
1177     llvm_unreachable("DWARF5 location atom with no GNU analog");
1178   }
1179 }
1180 
1181 DIE &DwarfCompileUnit::constructCallSiteEntryDIE(DIE &ScopeDIE,
1182                                                  const DISubprogram *CalleeSP,
1183                                                  bool IsTail,
1184                                                  const MCSymbol *PCAddr,
1185                                                  const MCSymbol *CallAddr,
1186                                                  unsigned CallReg) {
1187   // Insert a call site entry DIE within ScopeDIE.
1188   DIE &CallSiteDIE = createAndAddDIE(getDwarf5OrGNUTag(dwarf::DW_TAG_call_site),
1189                                      ScopeDIE, nullptr);
1190 
1191   if (CallReg) {
1192     // Indirect call.
1193     addAddress(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_target),
1194                MachineLocation(CallReg));
1195   } else {
1196     DIE *CalleeDIE = getOrCreateSubprogramDIE(CalleeSP);
1197     assert(CalleeDIE && "Could not create DIE for call site entry origin");
1198     addDIEEntry(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_origin),
1199                 *CalleeDIE);
1200   }
1201 
1202   if (IsTail) {
1203     // Attach DW_AT_call_tail_call to tail calls for standards compliance.
1204     addFlag(CallSiteDIE, getDwarf5OrGNUAttr(dwarf::DW_AT_call_tail_call));
1205 
1206     // Attach the address of the branch instruction to allow the debugger to
1207     // show where the tail call occurred. This attribute has no GNU analog.
1208     //
1209     // GDB works backwards from non-standard usage of DW_AT_low_pc (in DWARF4
1210     // mode -- equivalently, in DWARF5 mode, DW_AT_call_return_pc) at tail-call
1211     // site entries to figure out the PC of tail-calling branch instructions.
1212     // This means it doesn't need the compiler to emit DW_AT_call_pc, so we
1213     // don't emit it here.
1214     //
1215     // There's no need to tie non-GDB debuggers to this non-standardness, as it
1216     // adds unnecessary complexity to the debugger. For non-GDB debuggers, emit
1217     // the standard DW_AT_call_pc info.
1218     if (!useGNUAnalogForDwarf5Feature())
1219       addLabelAddress(CallSiteDIE, dwarf::DW_AT_call_pc, CallAddr);
1220   }
1221 
1222   // Attach the return PC to allow the debugger to disambiguate call paths
1223   // from one function to another.
1224   //
1225   // The return PC is only really needed when the call /isn't/ a tail call, but
1226   // GDB expects it in DWARF4 mode, even for tail calls (see the comment above
1227   // the DW_AT_call_pc emission logic for an explanation).
1228   if (!IsTail || useGNUAnalogForDwarf5Feature()) {
1229     assert(PCAddr && "Missing return PC information for a call");
1230     addLabelAddress(CallSiteDIE,
1231                     getDwarf5OrGNUAttr(dwarf::DW_AT_call_return_pc), PCAddr);
1232   }
1233 
1234   return CallSiteDIE;
1235 }
1236 
1237 void DwarfCompileUnit::constructCallSiteParmEntryDIEs(
1238     DIE &CallSiteDIE, SmallVector<DbgCallSiteParam, 4> &Params) {
1239   for (const auto &Param : Params) {
1240     unsigned Register = Param.getRegister();
1241     auto CallSiteDieParam =
1242         DIE::get(DIEValueAllocator,
1243                  getDwarf5OrGNUTag(dwarf::DW_TAG_call_site_parameter));
1244     insertDIE(CallSiteDieParam);
1245     addAddress(*CallSiteDieParam, dwarf::DW_AT_location,
1246                MachineLocation(Register));
1247 
1248     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1249     DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1250     DwarfExpr.setCallSiteParamValueFlag();
1251 
1252     DwarfDebug::emitDebugLocValue(*Asm, nullptr, Param.getValue(), DwarfExpr);
1253 
1254     addBlock(*CallSiteDieParam, getDwarf5OrGNUAttr(dwarf::DW_AT_call_value),
1255              DwarfExpr.finalize());
1256 
1257     CallSiteDIE.addChild(CallSiteDieParam);
1258   }
1259 }
1260 
1261 DIE *DwarfCompileUnit::constructImportedEntityDIE(
1262     const DIImportedEntity *Module) {
1263   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
1264   insertDIE(Module, IMDie);
1265   DIE *EntityDie;
1266   auto *Entity = Module->getEntity();
1267   if (auto *NS = dyn_cast<DINamespace>(Entity))
1268     EntityDie = getOrCreateNameSpace(NS);
1269   else if (auto *M = dyn_cast<DIModule>(Entity))
1270     EntityDie = getOrCreateModule(M);
1271   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
1272     EntityDie = getOrCreateSubprogramDIE(SP);
1273   else if (auto *T = dyn_cast<DIType>(Entity))
1274     EntityDie = getOrCreateTypeDIE(T);
1275   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
1276     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
1277   else
1278     EntityDie = getDIE(Entity);
1279   assert(EntityDie);
1280   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
1281   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
1282   StringRef Name = Module->getName();
1283   if (!Name.empty())
1284     addString(*IMDie, dwarf::DW_AT_name, Name);
1285 
1286   // This is for imported module with renamed entities (such as variables and
1287   // subprograms).
1288   DINodeArray Elements = Module->getElements();
1289   for (const auto *Element : Elements) {
1290     if (!Element)
1291       continue;
1292     IMDie->addChild(
1293         constructImportedEntityDIE(cast<DIImportedEntity>(Element)));
1294   }
1295 
1296   return IMDie;
1297 }
1298 
1299 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
1300   DIE *D = getDIE(SP);
1301   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
1302     if (D)
1303       // If this subprogram has an abstract definition, reference that
1304       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
1305   } else {
1306     assert(D || includeMinimalInlineScopes());
1307     if (D)
1308       // And attach the attributes
1309       applySubprogramAttributesToDefinition(SP, *D);
1310   }
1311 }
1312 
1313 void DwarfCompileUnit::finishEntityDefinition(const DbgEntity *Entity) {
1314   DbgEntity *AbsEntity = getExistingAbstractEntity(Entity->getEntity());
1315 
1316   auto *Die = Entity->getDIE();
1317   /// Label may be used to generate DW_AT_low_pc, so put it outside
1318   /// if/else block.
1319   const DbgLabel *Label = nullptr;
1320   if (AbsEntity && AbsEntity->getDIE()) {
1321     addDIEEntry(*Die, dwarf::DW_AT_abstract_origin, *AbsEntity->getDIE());
1322     Label = dyn_cast<const DbgLabel>(Entity);
1323   } else {
1324     if (const DbgVariable *Var = dyn_cast<const DbgVariable>(Entity))
1325       applyVariableAttributes(*Var, *Die);
1326     else if ((Label = dyn_cast<const DbgLabel>(Entity)))
1327       applyLabelAttributes(*Label, *Die);
1328     else
1329       llvm_unreachable("DbgEntity must be DbgVariable or DbgLabel.");
1330   }
1331 
1332   if (Label)
1333     if (const auto *Sym = Label->getSymbol())
1334       addLabelAddress(*Die, dwarf::DW_AT_low_pc, Sym);
1335 }
1336 
1337 DbgEntity *DwarfCompileUnit::getExistingAbstractEntity(const DINode *Node) {
1338   auto &AbstractEntities = getAbstractEntities();
1339   auto I = AbstractEntities.find(Node);
1340   if (I != AbstractEntities.end())
1341     return I->second.get();
1342   return nullptr;
1343 }
1344 
1345 void DwarfCompileUnit::createAbstractEntity(const DINode *Node,
1346                                             LexicalScope *Scope) {
1347   assert(Scope && Scope->isAbstractScope());
1348   auto &Entity = getAbstractEntities()[Node];
1349   if (isa<const DILocalVariable>(Node)) {
1350     Entity = std::make_unique<DbgVariable>(
1351                         cast<const DILocalVariable>(Node), nullptr /* IA */);;
1352     DU->addScopeVariable(Scope, cast<DbgVariable>(Entity.get()));
1353   } else if (isa<const DILabel>(Node)) {
1354     Entity = std::make_unique<DbgLabel>(
1355                         cast<const DILabel>(Node), nullptr /* IA */);
1356     DU->addScopeLabel(Scope, cast<DbgLabel>(Entity.get()));
1357   }
1358 }
1359 
1360 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
1361   // Don't bother labeling the .dwo unit, as its offset isn't used.
1362   if (!Skeleton && !DD->useSectionsAsReferences()) {
1363     LabelBegin = Asm->createTempSymbol("cu_begin");
1364     Asm->OutStreamer->emitLabel(LabelBegin);
1365   }
1366 
1367   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
1368                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
1369                                                       : dwarf::DW_UT_compile;
1370   DwarfUnit::emitCommonHeader(UseOffsets, UT);
1371   if (DD->getDwarfVersion() >= 5 && UT != dwarf::DW_UT_compile)
1372     Asm->emitInt64(getDWOId());
1373 }
1374 
1375 bool DwarfCompileUnit::hasDwarfPubSections() const {
1376   switch (CUNode->getNameTableKind()) {
1377   case DICompileUnit::DebugNameTableKind::None:
1378     return false;
1379     // Opting in to GNU Pubnames/types overrides the default to ensure these are
1380     // generated for things like Gold's gdb_index generation.
1381   case DICompileUnit::DebugNameTableKind::GNU:
1382     return true;
1383   case DICompileUnit::DebugNameTableKind::Default:
1384     return DD->tuneForGDB() && !includeMinimalInlineScopes() &&
1385            !CUNode->isDebugDirectivesOnly() &&
1386            DD->getAccelTableKind() != AccelTableKind::Apple &&
1387            DD->getDwarfVersion() < 5;
1388   }
1389   llvm_unreachable("Unhandled DICompileUnit::DebugNameTableKind enum");
1390 }
1391 
1392 /// addGlobalName - Add a new global name to the compile unit.
1393 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
1394                                      const DIScope *Context) {
1395   if (!hasDwarfPubSections())
1396     return;
1397   std::string FullName = getParentContextString(Context) + Name.str();
1398   GlobalNames[FullName] = &Die;
1399 }
1400 
1401 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
1402                                                 const DIScope *Context) {
1403   if (!hasDwarfPubSections())
1404     return;
1405   std::string FullName = getParentContextString(Context) + Name.str();
1406   // Insert, allowing the entry to remain as-is if it's already present
1407   // This way the CU-level type DIE is preferred over the "can't describe this
1408   // type as a unit offset because it's not really in the CU at all, it's only
1409   // in a type unit"
1410   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1411 }
1412 
1413 /// Add a new global type to the unit.
1414 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
1415                                      const DIScope *Context) {
1416   if (!hasDwarfPubSections())
1417     return;
1418   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1419   GlobalTypes[FullName] = &Die;
1420 }
1421 
1422 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
1423                                              const DIScope *Context) {
1424   if (!hasDwarfPubSections())
1425     return;
1426   std::string FullName = getParentContextString(Context) + Ty->getName().str();
1427   // Insert, allowing the entry to remain as-is if it's already present
1428   // This way the CU-level type DIE is preferred over the "can't describe this
1429   // type as a unit offset because it's not really in the CU at all, it's only
1430   // in a type unit"
1431   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
1432 }
1433 
1434 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
1435                                           MachineLocation Location) {
1436   if (DV.hasComplexAddress())
1437     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
1438   else
1439     addAddress(Die, dwarf::DW_AT_location, Location);
1440 }
1441 
1442 /// Add an address attribute to a die based on the location provided.
1443 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
1444                                   const MachineLocation &Location) {
1445   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1446   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1447   if (Location.isIndirect())
1448     DwarfExpr.setMemoryLocationKind();
1449 
1450   DIExpressionCursor Cursor({});
1451   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1452   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1453     return;
1454   DwarfExpr.addExpression(std::move(Cursor));
1455 
1456   // Now attach the location information to the DIE.
1457   addBlock(Die, Attribute, DwarfExpr.finalize());
1458 
1459   if (DwarfExpr.TagOffset)
1460     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1461             *DwarfExpr.TagOffset);
1462 }
1463 
1464 /// Start with the address based on the location provided, and generate the
1465 /// DWARF information necessary to find the actual variable given the extra
1466 /// address information encoded in the DbgVariable, starting from the starting
1467 /// location.  Add the DWARF information to the die.
1468 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
1469                                          dwarf::Attribute Attribute,
1470                                          const MachineLocation &Location) {
1471   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
1472   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
1473   const DIExpression *DIExpr = DV.getSingleExpression();
1474   DwarfExpr.addFragmentOffset(DIExpr);
1475   DwarfExpr.setLocation(Location, DIExpr);
1476 
1477   DIExpressionCursor Cursor(DIExpr);
1478 
1479   if (DIExpr->isEntryValue())
1480     DwarfExpr.beginEntryValueExpression(Cursor);
1481 
1482   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
1483   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1484     return;
1485   DwarfExpr.addExpression(std::move(Cursor));
1486 
1487   // Now attach the location information to the DIE.
1488   addBlock(Die, Attribute, DwarfExpr.finalize());
1489 
1490   if (DwarfExpr.TagOffset)
1491     addUInt(Die, dwarf::DW_AT_LLVM_tag_offset, dwarf::DW_FORM_data1,
1492             *DwarfExpr.TagOffset);
1493 }
1494 
1495 /// Add a Dwarf loclistptr attribute data and value.
1496 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
1497                                        unsigned Index) {
1498   dwarf::Form Form = (DD->getDwarfVersion() >= 5)
1499                          ? dwarf::DW_FORM_loclistx
1500                          : DD->getDwarfSectionOffsetForm();
1501   addAttribute(Die, Attribute, Form, DIELocList(Index));
1502 }
1503 
1504 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
1505                                                DIE &VariableDie) {
1506   StringRef Name = Var.getName();
1507   if (!Name.empty())
1508     addString(VariableDie, dwarf::DW_AT_name, Name);
1509   const auto *DIVar = Var.getVariable();
1510   if (DIVar) {
1511     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
1512       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
1513               AlignInBytes);
1514     addAnnotation(VariableDie, DIVar->getAnnotations());
1515   }
1516 
1517   addSourceLine(VariableDie, DIVar);
1518   addType(VariableDie, Var.getType());
1519   if (Var.isArtificial())
1520     addFlag(VariableDie, dwarf::DW_AT_artificial);
1521 }
1522 
1523 void DwarfCompileUnit::applyLabelAttributes(const DbgLabel &Label,
1524                                             DIE &LabelDie) {
1525   StringRef Name = Label.getName();
1526   if (!Name.empty())
1527     addString(LabelDie, dwarf::DW_AT_name, Name);
1528   const auto *DILabel = Label.getLabel();
1529   addSourceLine(LabelDie, DILabel);
1530 }
1531 
1532 /// Add a Dwarf expression attribute data and value.
1533 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
1534                                const MCExpr *Expr) {
1535   addAttribute(Die, (dwarf::Attribute)0, Form, DIEExpr(Expr));
1536 }
1537 
1538 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
1539     const DISubprogram *SP, DIE &SPDie) {
1540   auto *SPDecl = SP->getDeclaration();
1541   auto *Context = SPDecl ? SPDecl->getScope() : SP->getScope();
1542   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
1543   addGlobalName(SP->getName(), SPDie, Context);
1544 }
1545 
1546 bool DwarfCompileUnit::isDwoUnit() const {
1547   return DD->useSplitDwarf() && Skeleton;
1548 }
1549 
1550 void DwarfCompileUnit::finishNonUnitTypeDIE(DIE& D, const DICompositeType *CTy) {
1551   constructTypeDIE(D, CTy);
1552 }
1553 
1554 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1555   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1556          (DD->useSplitDwarf() && !Skeleton);
1557 }
1558 
1559 void DwarfCompileUnit::addAddrTableBase() {
1560   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1561   MCSymbol *Label = DD->getAddressPool().getLabel();
1562   addSectionLabel(getUnitDie(),
1563                   DD->getDwarfVersion() >= 5 ? dwarf::DW_AT_addr_base
1564                                              : dwarf::DW_AT_GNU_addr_base,
1565                   Label, TLOF.getDwarfAddrSection()->getBeginSymbol());
1566 }
1567 
1568 void DwarfCompileUnit::addBaseTypeRef(DIEValueList &Die, int64_t Idx) {
1569   addAttribute(Die, (dwarf::Attribute)0, dwarf::DW_FORM_udata,
1570                new (DIEValueAllocator) DIEBaseTypeRef(this, Idx));
1571 }
1572 
1573 void DwarfCompileUnit::createBaseTypeDIEs() {
1574   // Insert the base_type DIEs directly after the CU so that their offsets will
1575   // fit in the fixed size ULEB128 used inside the location expressions.
1576   // Maintain order by iterating backwards and inserting to the front of CU
1577   // child list.
1578   for (auto &Btr : reverse(ExprRefedBaseTypes)) {
1579     DIE &Die = getUnitDie().addChildFront(
1580       DIE::get(DIEValueAllocator, dwarf::DW_TAG_base_type));
1581     SmallString<32> Str;
1582     addString(Die, dwarf::DW_AT_name,
1583               Twine(dwarf::AttributeEncodingString(Btr.Encoding) +
1584                     "_" + Twine(Btr.BitSize)).toStringRef(Str));
1585     addUInt(Die, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, Btr.Encoding);
1586     // Round up to smallest number of bytes that contains this number of bits.
1587     addUInt(Die, dwarf::DW_AT_byte_size, None, divideCeil(Btr.BitSize, 8));
1588 
1589     Btr.Die = &Die;
1590   }
1591 }
1592