1 //===- llvm/CodeGen/DwarfCompileUnit.cpp - Dwarf Compile Units ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for constructing a dwarf compile unit.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfCompileUnit.h"
15 #include "AddressPool.h"
16 #include "DwarfDebug.h"
17 #include "DwarfExpression.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/None.h"
20 #include "llvm/ADT/STLExtras.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/TargetLoweringObjectFile.h"
32 #include "llvm/CodeGen/TargetRegisterInfo.h"
33 #include "llvm/CodeGen/TargetSubtargetInfo.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/DebugInfo.h"
36 #include "llvm/IR/DebugInfoMetadata.h"
37 #include "llvm/IR/GlobalVariable.h"
38 #include "llvm/MC/MCSection.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/MC/MachineLocation.h"
42 #include "llvm/Support/Casting.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)
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, dwarf::DW_FORM_GNU_addr_index,
80                DIEInteger(idx));
81 }
82 
83 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
84                                             dwarf::Attribute Attribute,
85                                             const MCSymbol *Label) {
86   if (Label)
87     DD->addArangeLabel(SymbolCU(this, Label));
88 
89   if (Label)
90     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
91                  DIELabel(Label));
92   else
93     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
94                  DIEInteger(0));
95 }
96 
97 unsigned DwarfCompileUnit::getOrCreateSourceID(const DIFile *File) {
98   // If we print assembly, we can't separate .file entries according to
99   // compile units. Thus all files will belong to the default compile unit.
100 
101   // FIXME: add a better feature test than hasRawTextSupport. Even better,
102   // extend .file to support this.
103   unsigned CUID = Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID();
104   if (!File)
105     return Asm->OutStreamer->EmitDwarfFileDirective(0, "", "", nullptr, None, CUID);
106   return Asm->OutStreamer->EmitDwarfFileDirective(
107       0, File->getDirectory(), File->getFilename(), getMD5AsBytes(File),
108       File->getSource(), CUID);
109 }
110 
111 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
112     const DIGlobalVariable *GV, ArrayRef<GlobalExpr> GlobalExprs) {
113   // Check for pre-existence.
114   if (DIE *Die = getDIE(GV))
115     return Die;
116 
117   assert(GV);
118 
119   auto *GVContext = GV->getScope();
120   auto *GTy = DD->resolve(GV->getType());
121 
122   // Construct the context before querying for the existence of the DIE in
123   // case such construction creates the DIE.
124   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
125 
126   // Add to map.
127   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
128   DIScope *DeclContext;
129   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
130     DeclContext = resolve(SDMDecl->getScope());
131     assert(SDMDecl->isStaticMember() && "Expected static member decl");
132     assert(GV->isDefinition());
133     // We need the declaration DIE that is in the static member's class.
134     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
135     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
136     // If the global variable's type is different from the one in the class
137     // member type, assume that it's more specific and also emit it.
138     if (GTy != DD->resolve(SDMDecl->getBaseType()))
139       addType(*VariableDIE, GTy);
140   } else {
141     DeclContext = GV->getScope();
142     // Add name and type.
143     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
144     addType(*VariableDIE, GTy);
145 
146     // Add scoping info.
147     if (!GV->isLocalToUnit())
148       addFlag(*VariableDIE, dwarf::DW_AT_external);
149 
150     // Add line number info.
151     addSourceLine(*VariableDIE, GV);
152   }
153 
154   if (!GV->isDefinition())
155     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
156   else
157     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
158 
159   if (uint32_t AlignInBytes = GV->getAlignInBytes())
160     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
161             AlignInBytes);
162 
163   // Add location.
164   bool addToAccelTable = false;
165   DIELoc *Loc = nullptr;
166   std::unique_ptr<DIEDwarfExpression> DwarfExpr;
167   for (const auto &GE : GlobalExprs) {
168     const GlobalVariable *Global = GE.Var;
169     const DIExpression *Expr = GE.Expr;
170 
171     // For compatibility with DWARF 3 and earlier,
172     // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
173     // DW_AT_const_value(X).
174     if (GlobalExprs.size() == 1 && Expr && Expr->isConstant()) {
175       addToAccelTable = true;
176       addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
177       break;
178     }
179 
180     // We cannot describe the location of dllimport'd variables: the
181     // computation of their address requires loads from the IAT.
182     if (Global && Global->hasDLLImportStorageClass())
183       continue;
184 
185     // Nothing to describe without address or constant.
186     if (!Global && (!Expr || !Expr->isConstant()))
187       continue;
188 
189     if (!Loc) {
190       addToAccelTable = true;
191       Loc = new (DIEValueAllocator) DIELoc;
192       DwarfExpr = llvm::make_unique<DIEDwarfExpression>(*Asm, *this, *Loc);
193     }
194 
195     if (Expr)
196       DwarfExpr->addFragmentOffset(Expr);
197 
198     if (Global) {
199       const MCSymbol *Sym = Asm->getSymbol(Global);
200       if (Global->isThreadLocal()) {
201         if (Asm->TM.useEmulatedTLS()) {
202           // TODO: add debug info for emulated thread local mode.
203         } else {
204           // FIXME: Make this work with -gsplit-dwarf.
205           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
206           assert((PointerSize == 4 || PointerSize == 8) &&
207                  "Add support for other sizes if necessary");
208           // Based on GCC's support for TLS:
209           if (!DD->useSplitDwarf()) {
210             // 1) Start with a constNu of the appropriate pointer size
211             addUInt(*Loc, dwarf::DW_FORM_data1,
212                     PointerSize == 4 ? dwarf::DW_OP_const4u
213                                      : dwarf::DW_OP_const8u);
214             // 2) containing the (relocated) offset of the TLS variable
215             //    within the module's TLS block.
216             addExpr(*Loc, dwarf::DW_FORM_udata,
217                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
218           } else {
219             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
220             addUInt(*Loc, dwarf::DW_FORM_udata,
221                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
222           }
223           // 3) followed by an OP to make the debugger do a TLS lookup.
224           addUInt(*Loc, dwarf::DW_FORM_data1,
225                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
226                                         : dwarf::DW_OP_form_tls_address);
227         }
228       } else {
229         DD->addArangeLabel(SymbolCU(this, Sym));
230         addOpAddress(*Loc, Sym);
231       }
232     }
233     if (Expr)
234       DwarfExpr->addExpression(Expr);
235   }
236   if (Loc)
237     addBlock(*VariableDIE, dwarf::DW_AT_location, DwarfExpr->finalize());
238 
239   if (DD->useAllLinkageNames())
240     addLinkageName(*VariableDIE, GV->getLinkageName());
241 
242   if (addToAccelTable) {
243     DD->addAccelName(GV->getName(), *VariableDIE);
244 
245     // If the linkage name is different than the name, go ahead and output
246     // that as well into the name table.
247     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
248       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
249   }
250 
251   return VariableDIE;
252 }
253 
254 void DwarfCompileUnit::addRange(RangeSpan Range) {
255   bool SameAsPrevCU = this == DD->getPrevCU();
256   DD->setPrevCU(this);
257   // If we have no current ranges just add the range and return, otherwise,
258   // check the current section and CU against the previous section and CU we
259   // emitted into and the subprogram was contained within. If these are the
260   // same then extend our current range, otherwise add this as a new range.
261   if (CURanges.empty() || !SameAsPrevCU ||
262       (&CURanges.back().getEnd()->getSection() !=
263        &Range.getEnd()->getSection())) {
264     CURanges.push_back(Range);
265     return;
266   }
267 
268   CURanges.back().setEnd(Range.getEnd());
269 }
270 
271 void DwarfCompileUnit::initStmtList() {
272   // Define start line table label for each Compile Unit.
273   MCSymbol *LineTableStartSym =
274       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
275 
276   // DW_AT_stmt_list is a offset of line number information for this
277   // compile unit in debug_line section. For split dwarf this is
278   // left in the skeleton CU and so not included.
279   // The line table entries are not always emitted in assembly, so it
280   // is not okay to use line_table_start here.
281   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
282   StmtListValue =
283       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
284                       TLOF.getDwarfLineSection()->getBeginSymbol());
285 }
286 
287 void DwarfCompileUnit::applyStmtList(DIE &D) {
288   D.addValue(DIEValueAllocator, *StmtListValue);
289 }
290 
291 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
292                                        const MCSymbol *End) {
293   assert(Begin && "Begin label should not be null!");
294   assert(End && "End label should not be null!");
295   assert(Begin->isDefined() && "Invalid starting label");
296   assert(End->isDefined() && "Invalid end label");
297 
298   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
299   if (DD->getDwarfVersion() < 4)
300     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
301   else
302     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
303 }
304 
305 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
306 // and DW_AT_high_pc attributes. If there are global variables in this
307 // scope then create and insert DIEs for these variables.
308 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
309   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
310 
311   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
312   if (DD->useAppleExtensionAttributes() &&
313       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
314           *DD->getCurrentFunction()))
315     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
316 
317   // Only include DW_AT_frame_base in full debug info
318   if (!includeMinimalInlineScopes()) {
319     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
320     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
321     if (RI->isPhysicalRegister(Location.getReg()))
322       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
323   }
324 
325   // Add name to the name table, we do this here because we're guaranteed
326   // to have concrete versions of our DW_TAG_subprogram nodes.
327   DD->addSubprogramNames(SP, *SPDie);
328 
329   return *SPDie;
330 }
331 
332 // Construct a DIE for this scope.
333 void DwarfCompileUnit::constructScopeDIE(
334     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
335   if (!Scope || !Scope->getScopeNode())
336     return;
337 
338   auto *DS = Scope->getScopeNode();
339 
340   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
341          "Only handle inlined subprograms here, use "
342          "constructSubprogramScopeDIE for non-inlined "
343          "subprograms");
344 
345   SmallVector<DIE *, 8> Children;
346 
347   // We try to create the scope DIE first, then the children DIEs. This will
348   // avoid creating un-used children then removing them later when we find out
349   // the scope DIE is null.
350   DIE *ScopeDIE;
351   if (Scope->getParent() && isa<DISubprogram>(DS)) {
352     ScopeDIE = constructInlinedScopeDIE(Scope);
353     if (!ScopeDIE)
354       return;
355     // We create children when the scope DIE is not null.
356     createScopeChildrenDIE(Scope, Children);
357   } else {
358     // Early exit when we know the scope DIE is going to be null.
359     if (DD->isLexicalScopeDIENull(Scope))
360       return;
361 
362     bool HasNonScopeChildren = false;
363 
364     // We create children here when we know the scope DIE is not going to be
365     // null and the children will be added to the scope DIE.
366     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
367 
368     // If there are only other scopes as children, put them directly in the
369     // parent instead, as this scope would serve no purpose.
370     if (!HasNonScopeChildren) {
371       FinalChildren.insert(FinalChildren.end(),
372                            std::make_move_iterator(Children.begin()),
373                            std::make_move_iterator(Children.end()));
374       return;
375     }
376     ScopeDIE = constructLexicalScopeDIE(Scope);
377     assert(ScopeDIE && "Scope DIE should not be null.");
378   }
379 
380   // Add children
381   for (auto &I : Children)
382     ScopeDIE->addChild(std::move(I));
383 
384   FinalChildren.push_back(std::move(ScopeDIE));
385 }
386 
387 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
388                                          SmallVector<RangeSpan, 2> Range) {
389   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
390 
391   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
392   // emitting it appropriately.
393   const MCSymbol *RangeSectionSym =
394       TLOF.getDwarfRangesSection()->getBeginSymbol();
395 
396   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
397 
398   // Under fission, ranges are specified by constant offsets relative to the
399   // CU's DW_AT_GNU_ranges_base.
400   if (isDwoUnit())
401     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
402                     RangeSectionSym);
403   else
404     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
405                     RangeSectionSym);
406 
407   // Add the range list to the set of ranges to be emitted.
408   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
409 }
410 
411 void DwarfCompileUnit::attachRangesOrLowHighPC(
412     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
413   if (Ranges.size() == 1) {
414     const auto &single = Ranges.front();
415     attachLowHighPC(Die, single.getStart(), single.getEnd());
416   } else
417     addScopeRangeList(Die, std::move(Ranges));
418 }
419 
420 void DwarfCompileUnit::attachRangesOrLowHighPC(
421     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
422   SmallVector<RangeSpan, 2> List;
423   List.reserve(Ranges.size());
424   for (const InsnRange &R : Ranges)
425     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
426                              DD->getLabelAfterInsn(R.second)));
427   attachRangesOrLowHighPC(Die, std::move(List));
428 }
429 
430 // This scope represents inlined body of a function. Construct DIE to
431 // represent this concrete inlined copy of the function.
432 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
433   assert(Scope->getScopeNode());
434   auto *DS = Scope->getScopeNode();
435   auto *InlinedSP = getDISubprogram(DS);
436   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
437   // was inlined from another compile unit.
438   DIE *OriginDIE = getAbstractSPDies()[InlinedSP];
439   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
440 
441   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
442   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
443 
444   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
445 
446   // Add the call site information to the DIE.
447   const DILocation *IA = Scope->getInlinedAt();
448   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
449           getOrCreateSourceID(IA->getFile()));
450   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
451   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
452     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
453             IA->getDiscriminator());
454 
455   // Add name to the name table, we do this here because we're guaranteed
456   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
457   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
458 
459   return ScopeDIE;
460 }
461 
462 // Construct new DW_TAG_lexical_block for this scope and attach
463 // DW_AT_low_pc/DW_AT_high_pc labels.
464 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
465   if (DD->isLexicalScopeDIENull(Scope))
466     return nullptr;
467 
468   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
469   if (Scope->isAbstractScope())
470     return ScopeDIE;
471 
472   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
473 
474   return ScopeDIE;
475 }
476 
477 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
478 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
479   auto D = constructVariableDIEImpl(DV, Abstract);
480   DV.setDIE(*D);
481   return D;
482 }
483 
484 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
485                                                 bool Abstract) {
486   // Define variable debug information entry.
487   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
488   insertDIE(DV.getVariable(), VariableDie);
489 
490   if (Abstract) {
491     applyVariableAttributes(DV, *VariableDie);
492     return VariableDie;
493   }
494 
495   // Add variable address.
496 
497   unsigned Offset = DV.getDebugLocListIndex();
498   if (Offset != ~0U) {
499     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
500     return VariableDie;
501   }
502 
503   // Check if variable is described by a DBG_VALUE instruction.
504   if (const MachineInstr *DVInsn = DV.getMInsn()) {
505     assert(DVInsn->getNumOperands() == 4);
506     if (DVInsn->getOperand(0).isReg()) {
507       auto RegOp = DVInsn->getOperand(0);
508       auto Op1 = DVInsn->getOperand(1);
509       // If the second operand is an immediate, this is an indirect value.
510       assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
511       MachineLocation Location(RegOp.getReg(), Op1.isImm());
512       addVariableAddress(DV, *VariableDie, Location);
513     } else if (DVInsn->getOperand(0).isImm()) {
514       // This variable is described by a single constant.
515       // Check whether it has a DIExpression.
516       auto *Expr = DV.getSingleExpression();
517       if (Expr && Expr->getNumElements()) {
518         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
519         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
520         // If there is an expression, emit raw unsigned bytes.
521         DwarfExpr.addFragmentOffset(Expr);
522         DwarfExpr.addUnsignedConstant(DVInsn->getOperand(0).getImm());
523         DwarfExpr.addExpression(Expr);
524         addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
525       } else
526         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
527     } else if (DVInsn->getOperand(0).isFPImm())
528       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
529     else if (DVInsn->getOperand(0).isCImm())
530       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
531                        DV.getType());
532 
533     return VariableDie;
534   }
535 
536   // .. else use frame index.
537   if (!DV.hasFrameIndexExprs())
538     return VariableDie;
539 
540   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
541   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
542   for (auto &Fragment : DV.getFrameIndexExprs()) {
543     unsigned FrameReg = 0;
544     const DIExpression *Expr = Fragment.Expr;
545     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
546     int Offset = TFI->getFrameIndexReference(*Asm->MF, Fragment.FI, FrameReg);
547     DwarfExpr.addFragmentOffset(Expr);
548     SmallVector<uint64_t, 8> Ops;
549     Ops.push_back(dwarf::DW_OP_plus_uconst);
550     Ops.push_back(Offset);
551     Ops.append(Expr->elements_begin(), Expr->elements_end());
552     DIExpressionCursor Cursor(Ops);
553     DwarfExpr.setMemoryLocationKind();
554     DwarfExpr.addMachineRegExpression(
555         *Asm->MF->getSubtarget().getRegisterInfo(), Cursor, FrameReg);
556     DwarfExpr.addExpression(std::move(Cursor));
557   }
558   addBlock(*VariableDie, dwarf::DW_AT_location, DwarfExpr.finalize());
559 
560   return VariableDie;
561 }
562 
563 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
564                                             const LexicalScope &Scope,
565                                             DIE *&ObjectPointer) {
566   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
567   if (DV.isObjectPointer())
568     ObjectPointer = Var;
569   return Var;
570 }
571 
572 /// Return all DIVariables that appear in count: expressions.
573 static SmallVector<const DIVariable *, 2> dependencies(DbgVariable *Var) {
574   SmallVector<const DIVariable *, 2> Result;
575   auto *Array = dyn_cast<DICompositeType>(Var->getType());
576   if (!Array || Array->getTag() != dwarf::DW_TAG_array_type)
577     return Result;
578   for (auto *El : Array->getElements()) {
579     if (auto *Subrange = dyn_cast<DISubrange>(El)) {
580       auto Count = Subrange->getCount();
581       if (auto *Dependency = Count.dyn_cast<DIVariable *>())
582         Result.push_back(Dependency);
583     }
584   }
585   return Result;
586 }
587 
588 /// Sort local variables so that variables appearing inside of helper
589 /// expressions come first.
590 static SmallVector<DbgVariable *, 8>
591 sortLocalVars(SmallVectorImpl<DbgVariable *> &Input) {
592   SmallVector<DbgVariable *, 8> Result;
593   SmallVector<PointerIntPair<DbgVariable *, 1>, 8> WorkList;
594   // Map back from a DIVariable to its containing DbgVariable.
595   SmallDenseMap<const DILocalVariable *, DbgVariable *> DbgVar;
596   // Set of DbgVariables in Result.
597   SmallDenseSet<DbgVariable *, 8> Visited;
598   // For cycle detection.
599   SmallDenseSet<DbgVariable *, 8> Visiting;
600 
601   // Initialize the worklist and the DIVariable lookup table.
602   for (auto Var : reverse(Input)) {
603     DbgVar.insert({Var->getVariable(), Var});
604     WorkList.push_back({Var, 0});
605   }
606 
607   // Perform a stable topological sort by doing a DFS.
608   while (!WorkList.empty()) {
609     auto Item = WorkList.back();
610     DbgVariable *Var = Item.getPointer();
611     bool visitedAllDependencies = Item.getInt();
612     WorkList.pop_back();
613 
614     // Dependency is in a different lexical scope or a global.
615     if (!Var)
616       continue;
617 
618     // Already handled.
619     if (Visited.count(Var))
620       continue;
621 
622     // Add to Result if all dependencies are visited.
623     if (visitedAllDependencies) {
624       Visited.insert(Var);
625       Result.push_back(Var);
626       continue;
627     }
628 
629     // Detect cycles.
630     auto Res = Visiting.insert(Var);
631     if (!Res.second) {
632       assert(false && "dependency cycle in local variables");
633       return Result;
634     }
635 
636     // Push dependencies and this node onto the worklist, so that this node is
637     // visited again after all of its dependencies are handled.
638     WorkList.push_back({Var, 1});
639     for (auto *Dependency : dependencies(Var)) {
640       auto Dep = dyn_cast_or_null<const DILocalVariable>(Dependency);
641       WorkList.push_back({DbgVar[Dep], 0});
642     }
643   }
644   return Result;
645 }
646 
647 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
648                                               SmallVectorImpl<DIE *> &Children,
649                                               bool *HasNonScopeChildren) {
650   assert(Children.empty());
651   DIE *ObjectPointer = nullptr;
652 
653   // Emit function arguments (order is significant).
654   auto Vars = DU->getScopeVariables().lookup(Scope);
655   for (auto &DV : Vars.Args)
656     Children.push_back(constructVariableDIE(*DV.second, *Scope, ObjectPointer));
657 
658   // Emit local variables.
659   auto Locals = sortLocalVars(Vars.Locals);
660   for (DbgVariable *DV : Locals)
661     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
662 
663   // Skip imported directives in gmlt-like data.
664   if (!includeMinimalInlineScopes()) {
665     // There is no need to emit empty lexical block DIE.
666     for (const auto *IE : ImportedEntities[Scope->getScopeNode()])
667       Children.push_back(
668           constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
669   }
670 
671   if (HasNonScopeChildren)
672     *HasNonScopeChildren = !Children.empty();
673 
674   for (LexicalScope *LS : Scope->getChildren())
675     constructScopeDIE(LS, Children);
676 
677   return ObjectPointer;
678 }
679 
680 void DwarfCompileUnit::constructSubprogramScopeDIE(const DISubprogram *Sub, LexicalScope *Scope) {
681   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
682 
683   if (Scope) {
684     assert(!Scope->getInlinedAt());
685     assert(!Scope->isAbstractScope());
686     // Collect lexical scope children first.
687     // ObjectPointer might be a local (non-argument) local variable if it's a
688     // block's synthetic this pointer.
689     if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
690       addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
691   }
692 
693   // If this is a variadic function, add an unspecified parameter.
694   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
695 
696   // If we have a single element of null, it is a function that returns void.
697   // If we have more than one elements and the last one is null, it is a
698   // variadic function.
699   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
700       !includeMinimalInlineScopes())
701     ScopeDIE.addChild(
702         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
703 }
704 
705 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
706                                                  DIE &ScopeDIE) {
707   // We create children when the scope DIE is not null.
708   SmallVector<DIE *, 8> Children;
709   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
710 
711   // Add children
712   for (auto &I : Children)
713     ScopeDIE.addChild(std::move(I));
714 
715   return ObjectPointer;
716 }
717 
718 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
719     LexicalScope *Scope) {
720   DIE *&AbsDef = getAbstractSPDies()[Scope->getScopeNode()];
721   if (AbsDef)
722     return;
723 
724   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
725 
726   DIE *ContextDIE;
727   DwarfCompileUnit *ContextCU = this;
728 
729   if (includeMinimalInlineScopes())
730     ContextDIE = &getUnitDie();
731   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
732   // the important distinction that the debug node is not associated with the
733   // DIE (since the debug node will be associated with the concrete DIE, if
734   // any). It could be refactored to some common utility function.
735   else if (auto *SPDecl = SP->getDeclaration()) {
736     ContextDIE = &getUnitDie();
737     getOrCreateSubprogramDIE(SPDecl);
738   } else {
739     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
740     // The scope may be shared with a subprogram that has already been
741     // constructed in another CU, in which case we need to construct this
742     // subprogram in the same CU.
743     ContextCU = DD->lookupCU(ContextDIE->getUnitDie());
744   }
745 
746   // Passing null as the associated node because the abstract definition
747   // shouldn't be found by lookup.
748   AbsDef = &ContextCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
749   ContextCU->applySubprogramAttributesToDefinition(SP, *AbsDef);
750 
751   if (!ContextCU->includeMinimalInlineScopes())
752     ContextCU->addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
753   if (DIE *ObjectPointer = ContextCU->createAndAddScopeChildren(Scope, *AbsDef))
754     ContextCU->addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
755 }
756 
757 DIE *DwarfCompileUnit::constructImportedEntityDIE(
758     const DIImportedEntity *Module) {
759   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
760   insertDIE(Module, IMDie);
761   DIE *EntityDie;
762   auto *Entity = resolve(Module->getEntity());
763   if (auto *NS = dyn_cast<DINamespace>(Entity))
764     EntityDie = getOrCreateNameSpace(NS);
765   else if (auto *M = dyn_cast<DIModule>(Entity))
766     EntityDie = getOrCreateModule(M);
767   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
768     EntityDie = getOrCreateSubprogramDIE(SP);
769   else if (auto *T = dyn_cast<DIType>(Entity))
770     EntityDie = getOrCreateTypeDIE(T);
771   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
772     EntityDie = getOrCreateGlobalVariableDIE(GV, {});
773   else
774     EntityDie = getDIE(Entity);
775   assert(EntityDie);
776   addSourceLine(*IMDie, Module->getLine(), Module->getFile());
777   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
778   StringRef Name = Module->getName();
779   if (!Name.empty())
780     addString(*IMDie, dwarf::DW_AT_name, Name);
781 
782   return IMDie;
783 }
784 
785 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
786   DIE *D = getDIE(SP);
787   if (DIE *AbsSPDIE = getAbstractSPDies().lookup(SP)) {
788     if (D)
789       // If this subprogram has an abstract definition, reference that
790       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
791   } else {
792     assert(D || includeMinimalInlineScopes());
793     if (D)
794       // And attach the attributes
795       applySubprogramAttributesToDefinition(SP, *D);
796   }
797 }
798 
799 void DwarfCompileUnit::finishVariableDefinition(const DbgVariable &Var) {
800   DbgVariable *AbsVar = getExistingAbstractVariable(
801       InlinedVariable(Var.getVariable(), Var.getInlinedAt()));
802   auto *VariableDie = Var.getDIE();
803   if (AbsVar && AbsVar->getDIE()) {
804     addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
805                       *AbsVar->getDIE());
806   } else
807     applyVariableAttributes(Var, *VariableDie);
808 }
809 
810 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(InlinedVariable IV) {
811   const DILocalVariable *Cleansed;
812   return getExistingAbstractVariable(IV, Cleansed);
813 }
814 
815 // Find abstract variable, if any, associated with Var.
816 DbgVariable *DwarfCompileUnit::getExistingAbstractVariable(
817     InlinedVariable IV, const DILocalVariable *&Cleansed) {
818   // More then one inlined variable corresponds to one abstract variable.
819   Cleansed = IV.first;
820   auto &AbstractVariables = getAbstractVariables();
821   auto I = AbstractVariables.find(Cleansed);
822   if (I != AbstractVariables.end())
823     return I->second.get();
824   return nullptr;
825 }
826 
827 void DwarfCompileUnit::createAbstractVariable(const DILocalVariable *Var,
828                                         LexicalScope *Scope) {
829   assert(Scope && Scope->isAbstractScope());
830   auto AbsDbgVariable = llvm::make_unique<DbgVariable>(Var, /* IA */ nullptr);
831   DU->addScopeVariable(Scope, AbsDbgVariable.get());
832   getAbstractVariables()[Var] = std::move(AbsDbgVariable);
833 }
834 
835 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
836   // Don't bother labeling the .dwo unit, as its offset isn't used.
837   if (!Skeleton) {
838     LabelBegin = Asm->createTempSymbol("cu_begin");
839     Asm->OutStreamer->EmitLabel(LabelBegin);
840   }
841 
842   dwarf::UnitType UT = Skeleton ? dwarf::DW_UT_split_compile
843                                 : DD->useSplitDwarf() ? dwarf::DW_UT_skeleton
844                                                       : dwarf::DW_UT_compile;
845   DwarfUnit::emitCommonHeader(UseOffsets, UT);
846 }
847 
848 bool DwarfCompileUnit::hasDwarfPubSections() const {
849   // Opting in to GNU Pubnames/types overrides the default to ensure these are
850   // generated for things like Gold's gdb_index generation.
851   if (CUNode->getGnuPubnames())
852     return true;
853 
854   return DD->tuneForGDB() && !includeMinimalInlineScopes();
855 }
856 
857 /// addGlobalName - Add a new global name to the compile unit.
858 void DwarfCompileUnit::addGlobalName(StringRef Name, const DIE &Die,
859                                      const DIScope *Context) {
860   if (!hasDwarfPubSections())
861     return;
862   std::string FullName = getParentContextString(Context) + Name.str();
863   GlobalNames[FullName] = &Die;
864 }
865 
866 void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
867                                                 const DIScope *Context) {
868   if (!hasDwarfPubSections())
869     return;
870   std::string FullName = getParentContextString(Context) + Name.str();
871   // Insert, allowing the entry to remain as-is if it's already present
872   // This way the CU-level type DIE is preferred over the "can't describe this
873   // type as a unit offset because it's not really in the CU at all, it's only
874   // in a type unit"
875   GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
876 }
877 
878 /// Add a new global type to the unit.
879 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
880                                      const DIScope *Context) {
881   if (!hasDwarfPubSections())
882     return;
883   std::string FullName = getParentContextString(Context) + Ty->getName().str();
884   GlobalTypes[FullName] = &Die;
885 }
886 
887 void DwarfCompileUnit::addGlobalTypeUnitType(const DIType *Ty,
888                                              const DIScope *Context) {
889   if (!hasDwarfPubSections())
890     return;
891   std::string FullName = getParentContextString(Context) + Ty->getName().str();
892   // Insert, allowing the entry to remain as-is if it's already present
893   // This way the CU-level type DIE is preferred over the "can't describe this
894   // type as a unit offset because it's not really in the CU at all, it's only
895   // in a type unit"
896   GlobalTypes.insert(std::make_pair(std::move(FullName), &getUnitDie()));
897 }
898 
899 /// addVariableAddress - Add DW_AT_location attribute for a
900 /// DbgVariable based on provided MachineLocation.
901 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
902                                           MachineLocation Location) {
903   // addBlockByrefAddress is obsolete and will be removed soon.
904   // The clang frontend always generates block byref variables with a
905   // complex expression that encodes exactly what addBlockByrefAddress
906   // would do.
907   assert((!DV.isBlockByrefVariable() || DV.hasComplexAddress()) &&
908          "block byref variable without a complex expression");
909   if (DV.hasComplexAddress())
910     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
911   else if (DV.isBlockByrefVariable())
912     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
913   else
914     addAddress(Die, dwarf::DW_AT_location, Location);
915 }
916 
917 /// Add an address attribute to a die based on the location provided.
918 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
919                                   const MachineLocation &Location) {
920   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
921   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
922   if (Location.isIndirect())
923     DwarfExpr.setMemoryLocationKind();
924 
925   DIExpressionCursor Cursor({});
926   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
927   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
928     return;
929   DwarfExpr.addExpression(std::move(Cursor));
930 
931   // Now attach the location information to the DIE.
932   addBlock(Die, Attribute, DwarfExpr.finalize());
933 }
934 
935 /// Start with the address based on the location provided, and generate the
936 /// DWARF information necessary to find the actual variable given the extra
937 /// address information encoded in the DbgVariable, starting from the starting
938 /// location.  Add the DWARF information to the die.
939 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
940                                          dwarf::Attribute Attribute,
941                                          const MachineLocation &Location) {
942   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
943   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
944   const DIExpression *DIExpr = DV.getSingleExpression();
945   DwarfExpr.addFragmentOffset(DIExpr);
946   if (Location.isIndirect())
947     DwarfExpr.setMemoryLocationKind();
948 
949   DIExpressionCursor Cursor(DIExpr);
950   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
951   if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
952     return;
953   DwarfExpr.addExpression(std::move(Cursor));
954 
955   // Now attach the location information to the DIE.
956   addBlock(Die, Attribute, DwarfExpr.finalize());
957 }
958 
959 /// Add a Dwarf loclistptr attribute data and value.
960 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
961                                        unsigned Index) {
962   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
963                                                 : dwarf::DW_FORM_data4;
964   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
965 }
966 
967 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
968                                                DIE &VariableDie) {
969   StringRef Name = Var.getName();
970   if (!Name.empty())
971     addString(VariableDie, dwarf::DW_AT_name, Name);
972   const auto *DIVar = Var.getVariable();
973   if (DIVar)
974     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
975       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
976               AlignInBytes);
977 
978   addSourceLine(VariableDie, DIVar);
979   addType(VariableDie, Var.getType());
980   if (Var.isArtificial())
981     addFlag(VariableDie, dwarf::DW_AT_artificial);
982 }
983 
984 /// Add a Dwarf expression attribute data and value.
985 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
986                                const MCExpr *Expr) {
987   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
988 }
989 
990 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
991     const DISubprogram *SP, DIE &SPDie) {
992   auto *SPDecl = SP->getDeclaration();
993   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
994   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
995   addGlobalName(SP->getName(), SPDie, Context);
996 }
997 
998 bool DwarfCompileUnit::isDwoUnit() const {
999   return DD->useSplitDwarf() && Skeleton;
1000 }
1001 
1002 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
1003   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
1004          (DD->useSplitDwarf() && !Skeleton);
1005 }
1006