1 #include "DwarfCompileUnit.h"
2 #include "DwarfExpression.h"
3 #include "llvm/CodeGen/MachineFunction.h"
4 #include "llvm/IR/Constants.h"
5 #include "llvm/IR/DataLayout.h"
6 #include "llvm/IR/GlobalValue.h"
7 #include "llvm/IR/GlobalVariable.h"
8 #include "llvm/IR/Instruction.h"
9 #include "llvm/MC/MCAsmInfo.h"
10 #include "llvm/MC/MCStreamer.h"
11 #include "llvm/Target/TargetFrameLowering.h"
12 #include "llvm/Target/TargetLoweringObjectFile.h"
13 #include "llvm/Target/TargetMachine.h"
14 #include "llvm/Target/TargetRegisterInfo.h"
15 #include "llvm/Target/TargetSubtargetInfo.h"
16 
17 namespace llvm {
18 
19 DwarfCompileUnit::DwarfCompileUnit(unsigned UID, const DICompileUnit *Node,
20                                    AsmPrinter *A, DwarfDebug *DW,
21                                    DwarfFile *DWU)
22     : DwarfUnit(dwarf::DW_TAG_compile_unit, Node, A, DW, DWU), UniqueID(UID),
23       Skeleton(nullptr), BaseAddress(nullptr) {
24   insertDIE(Node, &getUnitDie());
25   MacroLabelBegin = Asm->createTempSymbol("cu_macro_begin");
26 }
27 
28 /// addLabelAddress - Add a dwarf label attribute data and value using
29 /// DW_FORM_addr or DW_FORM_GNU_addr_index.
30 ///
31 void DwarfCompileUnit::addLabelAddress(DIE &Die, dwarf::Attribute Attribute,
32                                        const MCSymbol *Label) {
33 
34   // Don't use the address pool in non-fission or in the skeleton unit itself.
35   // FIXME: Once GDB supports this, it's probably worthwhile using the address
36   // pool from the skeleton - maybe even in non-fission (possibly fewer
37   // relocations by sharing them in the pool, but we have other ideas about how
38   // to reduce the number of relocations as well/instead).
39   if (!DD->useSplitDwarf() || !Skeleton)
40     return addLocalLabelAddress(Die, Attribute, Label);
41 
42   if (Label)
43     DD->addArangeLabel(SymbolCU(this, Label));
44 
45   unsigned idx = DD->getAddressPool().getIndex(Label);
46   Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_GNU_addr_index,
47                DIEInteger(idx));
48 }
49 
50 void DwarfCompileUnit::addLocalLabelAddress(DIE &Die,
51                                             dwarf::Attribute Attribute,
52                                             const MCSymbol *Label) {
53   if (Label)
54     DD->addArangeLabel(SymbolCU(this, Label));
55 
56   if (Label)
57     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
58                  DIELabel(Label));
59   else
60     Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_addr,
61                  DIEInteger(0));
62 }
63 
64 unsigned DwarfCompileUnit::getOrCreateSourceID(StringRef FileName,
65                                                StringRef DirName) {
66   // If we print assembly, we can't separate .file entries according to
67   // compile units. Thus all files will belong to the default compile unit.
68 
69   // FIXME: add a better feature test than hasRawTextSupport. Even better,
70   // extend .file to support this.
71   return Asm->OutStreamer->EmitDwarfFileDirective(
72       0, DirName, FileName,
73       Asm->OutStreamer->hasRawTextSupport() ? 0 : getUniqueID());
74 }
75 
76 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
77 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
78     const DIGlobalVariable *GV, const GlobalVariable *Global) {
79   // Check for pre-existence.
80   if (DIE *Die = getDIE(GV))
81     return Die;
82 
83   assert(GV);
84 
85   auto *GVContext = GV->getScope();
86   auto *GTy = DD->resolve(GV->getType());
87 
88   // Construct the context before querying for the existence of the DIE in
89   // case such construction creates the DIE.
90   DIE *ContextDIE = getOrCreateContextDIE(GVContext);
91 
92   // Add to map.
93   DIE *VariableDIE = &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
94   DIScope *DeclContext;
95   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
96     DeclContext = resolve(SDMDecl->getScope());
97     assert(SDMDecl->isStaticMember() && "Expected static member decl");
98     assert(GV->isDefinition());
99     // We need the declaration DIE that is in the static member's class.
100     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
101     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
102     // If the global variable's type is different from the one in the class
103     // member type, assume that it's more specific and also emit it.
104     if (GTy != DD->resolve(SDMDecl->getBaseType()))
105       addType(*VariableDIE, GTy);
106   } else {
107     DeclContext = GV->getScope();
108     // Add name and type.
109     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
110     addType(*VariableDIE, GTy);
111 
112     // Add scoping info.
113     if (!GV->isLocalToUnit())
114       addFlag(*VariableDIE, dwarf::DW_AT_external);
115 
116     // Add line number info.
117     addSourceLine(*VariableDIE, GV);
118   }
119 
120   if (!GV->isDefinition())
121     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
122   else
123     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
124 
125   if (uint32_t AlignInBytes = GV->getAlignInBytes())
126     addUInt(*VariableDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
127             AlignInBytes);
128 
129   // Add location.
130   bool addToAccelTable = false;
131 
132   DIExpression *Expr = GV->getExpr();
133 
134   // For compatibility with DWARF 3 and earlier,
135   // DW_AT_location(DW_OP_constu, X, DW_OP_stack_value) becomes
136   // DW_AT_const_value(X).
137   if (Expr && Expr->getNumElements() == 3 &&
138       Expr->getElement(0) == dwarf::DW_OP_constu &&
139       Expr->getElement(2) == dwarf::DW_OP_stack_value) {
140     addConstantValue(*VariableDIE, /*Unsigned=*/true, Expr->getElement(1));
141     // We cannot describe the location of dllimport'd variables: the computation
142     // of their address requires loads from the IAT.
143   } else if (!Global || !Global->hasDLLImportStorageClass()) {
144     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
145     if (Global) {
146       addToAccelTable = true;
147       const MCSymbol *Sym = Asm->getSymbol(Global);
148       if (Global->isThreadLocal()) {
149         if (Asm->TM.Options.EmulatedTLS) {
150           // TODO: add debug info for emulated thread local mode.
151         } else {
152           // FIXME: Make this work with -gsplit-dwarf.
153           unsigned PointerSize = Asm->getDataLayout().getPointerSize();
154           assert((PointerSize == 4 || PointerSize == 8) &&
155                  "Add support for other sizes if necessary");
156           // Based on GCC's support for TLS:
157           if (!DD->useSplitDwarf()) {
158             // 1) Start with a constNu of the appropriate pointer size
159             addUInt(*Loc, dwarf::DW_FORM_data1, PointerSize == 4
160                                                     ? dwarf::DW_OP_const4u
161                                                     : dwarf::DW_OP_const8u);
162             // 2) containing the (relocated) offset of the TLS variable
163             //    within the module's TLS block.
164             addExpr(*Loc, dwarf::DW_FORM_udata,
165                     Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
166           } else {
167             addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
168             addUInt(*Loc, dwarf::DW_FORM_udata,
169                     DD->getAddressPool().getIndex(Sym, /* TLS */ true));
170           }
171           // 3) followed by an OP to make the debugger do a TLS lookup.
172           addUInt(*Loc, dwarf::DW_FORM_data1,
173                   DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
174                                         : dwarf::DW_OP_form_tls_address);
175         }
176       } else {
177         DD->addArangeLabel(SymbolCU(this, Sym));
178         addOpAddress(*Loc, Sym);
179       }
180 
181       if (Expr) {
182         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
183         DwarfExpr.addFragmentOffset(Expr);
184         DwarfExpr.AddExpression(Expr);
185         DwarfExpr.finalize();
186       }
187     }
188 
189     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
190 
191     if (DD->useAllLinkageNames())
192       addLinkageName(*VariableDIE, GV->getLinkageName());
193   }
194 
195   if (addToAccelTable) {
196     DD->addAccelName(GV->getName(), *VariableDIE);
197 
198     // If the linkage name is different than the name, go ahead and output
199     // that as well into the name table.
200     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
201       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
202   }
203 
204   return VariableDIE;
205 }
206 
207 void DwarfCompileUnit::addRange(RangeSpan Range) {
208   bool SameAsPrevCU = this == DD->getPrevCU();
209   DD->setPrevCU(this);
210   // If we have no current ranges just add the range and return, otherwise,
211   // check the current section and CU against the previous section and CU we
212   // emitted into and the subprogram was contained within. If these are the
213   // same then extend our current range, otherwise add this as a new range.
214   if (CURanges.empty() || !SameAsPrevCU ||
215       (&CURanges.back().getEnd()->getSection() !=
216        &Range.getEnd()->getSection())) {
217     CURanges.push_back(Range);
218     return;
219   }
220 
221   CURanges.back().setEnd(Range.getEnd());
222 }
223 
224 DIE::value_iterator
225 DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
226                                   const MCSymbol *Label, const MCSymbol *Sec) {
227   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
228     return addLabel(Die, Attribute,
229                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
230                                                : dwarf::DW_FORM_data4,
231                     Label);
232   return addSectionDelta(Die, Attribute, Label, Sec);
233 }
234 
235 void DwarfCompileUnit::initStmtList() {
236   // Define start line table label for each Compile Unit.
237   MCSymbol *LineTableStartSym =
238       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
239 
240   // DW_AT_stmt_list is a offset of line number information for this
241   // compile unit in debug_line section. For split dwarf this is
242   // left in the skeleton CU and so not included.
243   // The line table entries are not always emitted in assembly, so it
244   // is not okay to use line_table_start here.
245   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
246   StmtListValue =
247       addSectionLabel(getUnitDie(), dwarf::DW_AT_stmt_list, LineTableStartSym,
248                       TLOF.getDwarfLineSection()->getBeginSymbol());
249 }
250 
251 void DwarfCompileUnit::applyStmtList(DIE &D) {
252   D.addValue(DIEValueAllocator, *StmtListValue);
253 }
254 
255 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
256                                        const MCSymbol *End) {
257   assert(Begin && "Begin label should not be null!");
258   assert(End && "End label should not be null!");
259   assert(Begin->isDefined() && "Invalid starting label");
260   assert(End->isDefined() && "Invalid end label");
261 
262   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
263   if (DD->getDwarfVersion() < 4)
264     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
265   else
266     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
267 }
268 
269 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
270 // and DW_AT_high_pc attributes. If there are global variables in this
271 // scope then create and insert DIEs for these variables.
272 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
273   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
274 
275   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
276   if (DD->useAppleExtensionAttributes() &&
277       !DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
278           *DD->getCurrentFunction()))
279     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
280 
281   // Only include DW_AT_frame_base in full debug info
282   if (!includeMinimalInlineScopes()) {
283     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
284     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
285     if (RI->isPhysicalRegister(Location.getReg()))
286       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
287   }
288 
289   // Add name to the name table, we do this here because we're guaranteed
290   // to have concrete versions of our DW_TAG_subprogram nodes.
291   DD->addSubprogramNames(SP, *SPDie);
292 
293   return *SPDie;
294 }
295 
296 // Construct a DIE for this scope.
297 void DwarfCompileUnit::constructScopeDIE(
298     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
299   if (!Scope || !Scope->getScopeNode())
300     return;
301 
302   auto *DS = Scope->getScopeNode();
303 
304   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
305          "Only handle inlined subprograms here, use "
306          "constructSubprogramScopeDIE for non-inlined "
307          "subprograms");
308 
309   SmallVector<DIE *, 8> Children;
310 
311   // We try to create the scope DIE first, then the children DIEs. This will
312   // avoid creating un-used children then removing them later when we find out
313   // the scope DIE is null.
314   DIE *ScopeDIE;
315   if (Scope->getParent() && isa<DISubprogram>(DS)) {
316     ScopeDIE = constructInlinedScopeDIE(Scope);
317     if (!ScopeDIE)
318       return;
319     // We create children when the scope DIE is not null.
320     createScopeChildrenDIE(Scope, Children);
321   } else {
322     // Early exit when we know the scope DIE is going to be null.
323     if (DD->isLexicalScopeDIENull(Scope))
324       return;
325 
326     unsigned ChildScopeCount;
327 
328     // We create children here when we know the scope DIE is not going to be
329     // null and the children will be added to the scope DIE.
330     createScopeChildrenDIE(Scope, Children, &ChildScopeCount);
331 
332     // Skip imported directives in gmlt-like data.
333     if (!includeMinimalInlineScopes()) {
334       // There is no need to emit empty lexical block DIE.
335       for (const auto *IE : ImportedEntities[DS])
336         Children.push_back(
337             constructImportedEntityDIE(cast<DIImportedEntity>(IE)));
338     }
339 
340     // If there are only other scopes as children, put them directly in the
341     // parent instead, as this scope would serve no purpose.
342     if (Children.size() == ChildScopeCount) {
343       FinalChildren.insert(FinalChildren.end(),
344                            std::make_move_iterator(Children.begin()),
345                            std::make_move_iterator(Children.end()));
346       return;
347     }
348     ScopeDIE = constructLexicalScopeDIE(Scope);
349     assert(ScopeDIE && "Scope DIE should not be null.");
350   }
351 
352   // Add children
353   for (auto &I : Children)
354     ScopeDIE->addChild(std::move(I));
355 
356   FinalChildren.push_back(std::move(ScopeDIE));
357 }
358 
359 DIE::value_iterator
360 DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
361                                   const MCSymbol *Hi, const MCSymbol *Lo) {
362   return Die.addValue(DIEValueAllocator, Attribute,
363                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
364                                                  : dwarf::DW_FORM_data4,
365                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
366 }
367 
368 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
369                                          SmallVector<RangeSpan, 2> Range) {
370   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
371 
372   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
373   // emitting it appropriately.
374   const MCSymbol *RangeSectionSym =
375       TLOF.getDwarfRangesSection()->getBeginSymbol();
376 
377   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
378 
379   // Under fission, ranges are specified by constant offsets relative to the
380   // CU's DW_AT_GNU_ranges_base.
381   if (isDwoUnit())
382     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
383                     RangeSectionSym);
384   else
385     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
386                     RangeSectionSym);
387 
388   // Add the range list to the set of ranges to be emitted.
389   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
390 }
391 
392 void DwarfCompileUnit::attachRangesOrLowHighPC(
393     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
394   if (Ranges.size() == 1) {
395     const auto &single = Ranges.front();
396     attachLowHighPC(Die, single.getStart(), single.getEnd());
397   } else
398     addScopeRangeList(Die, std::move(Ranges));
399 }
400 
401 void DwarfCompileUnit::attachRangesOrLowHighPC(
402     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
403   SmallVector<RangeSpan, 2> List;
404   List.reserve(Ranges.size());
405   for (const InsnRange &R : Ranges)
406     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
407                              DD->getLabelAfterInsn(R.second)));
408   attachRangesOrLowHighPC(Die, std::move(List));
409 }
410 
411 // This scope represents inlined body of a function. Construct DIE to
412 // represent this concrete inlined copy of the function.
413 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
414   assert(Scope->getScopeNode());
415   auto *DS = Scope->getScopeNode();
416   auto *InlinedSP = getDISubprogram(DS);
417   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
418   // was inlined from another compile unit.
419   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
420   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
421 
422   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
423   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
424 
425   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
426 
427   // Add the call site information to the DIE.
428   const DILocation *IA = Scope->getInlinedAt();
429   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
430           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
431   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
432   if (IA->getDiscriminator() && DD->getDwarfVersion() >= 4)
433     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
434             IA->getDiscriminator());
435 
436   // Add name to the name table, we do this here because we're guaranteed
437   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
438   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
439 
440   return ScopeDIE;
441 }
442 
443 // Construct new DW_TAG_lexical_block for this scope and attach
444 // DW_AT_low_pc/DW_AT_high_pc labels.
445 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
446   if (DD->isLexicalScopeDIENull(Scope))
447     return nullptr;
448 
449   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
450   if (Scope->isAbstractScope())
451     return ScopeDIE;
452 
453   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
454 
455   return ScopeDIE;
456 }
457 
458 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
459 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
460   auto D = constructVariableDIEImpl(DV, Abstract);
461   DV.setDIE(*D);
462   return D;
463 }
464 
465 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
466                                                 bool Abstract) {
467   // Define variable debug information entry.
468   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
469 
470   if (Abstract) {
471     applyVariableAttributes(DV, *VariableDie);
472     return VariableDie;
473   }
474 
475   // Add variable address.
476 
477   unsigned Offset = DV.getDebugLocListIndex();
478   if (Offset != ~0U) {
479     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
480     return VariableDie;
481   }
482 
483   // Check if variable is described by a DBG_VALUE instruction.
484   if (const MachineInstr *DVInsn = DV.getMInsn()) {
485     assert(DVInsn->getNumOperands() == 4);
486     if (DVInsn->getOperand(0).isReg()) {
487       const MachineOperand RegOp = DVInsn->getOperand(0);
488       // If the second operand is an immediate, this is an indirect value.
489       if (DVInsn->getOperand(1).isImm()) {
490         MachineLocation Location(RegOp.getReg(),
491                                  DVInsn->getOperand(1).getImm());
492         addVariableAddress(DV, *VariableDie, Location);
493       } else if (RegOp.getReg())
494         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
495     } else if (DVInsn->getOperand(0).isImm()) {
496       // This variable is described by a single constant.
497       // Check whether it has a DIExpression.
498       auto *Expr = DV.getSingleExpression();
499       if (Expr && Expr->getNumElements()) {
500         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
501         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
502         // If there is an expression, emit raw unsigned bytes.
503         DwarfExpr.addFragmentOffset(Expr);
504         DwarfExpr.AddUnsignedConstant(DVInsn->getOperand(0).getImm());
505         DwarfExpr.AddExpression(Expr);
506         DwarfExpr.finalize();
507         addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
508       } else
509         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
510     } else if (DVInsn->getOperand(0).isFPImm())
511       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
512     else if (DVInsn->getOperand(0).isCImm())
513       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
514                        DV.getType());
515 
516     return VariableDie;
517   }
518 
519   // .. else use frame index.
520   if (DV.getFrameIndex().empty())
521     return VariableDie;
522 
523   auto Expr = DV.getExpression().begin();
524   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
525   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
526   for (auto FI : DV.getFrameIndex()) {
527     unsigned FrameReg = 0;
528     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
529     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
530     assert(Expr != DV.getExpression().end() && "Wrong number of expressions");
531     DwarfExpr.addFragmentOffset(*Expr);
532     DwarfExpr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
533                                     FrameReg, Offset);
534     DwarfExpr.AddExpression(*Expr);
535     ++Expr;
536   }
537   DwarfExpr.finalize();
538   addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
539 
540   return VariableDie;
541 }
542 
543 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
544                                             const LexicalScope &Scope,
545                                             DIE *&ObjectPointer) {
546   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
547   if (DV.isObjectPointer())
548     ObjectPointer = Var;
549   return Var;
550 }
551 
552 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
553                                               SmallVectorImpl<DIE *> &Children,
554                                               unsigned *ChildScopeCount) {
555   DIE *ObjectPointer = nullptr;
556 
557   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
558     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
559 
560   unsigned ChildCountWithoutScopes = Children.size();
561 
562   for (LexicalScope *LS : Scope->getChildren())
563     constructScopeDIE(LS, Children);
564 
565   if (ChildScopeCount)
566     *ChildScopeCount = Children.size() - ChildCountWithoutScopes;
567 
568   return ObjectPointer;
569 }
570 
571 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
572   assert(Scope && Scope->getScopeNode());
573   assert(!Scope->getInlinedAt());
574   assert(!Scope->isAbstractScope());
575   auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
576 
577   DD->getProcessedSPNodes().insert(Sub);
578 
579   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
580 
581   // If this is a variadic function, add an unspecified parameter.
582   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
583 
584   // Collect lexical scope children first.
585   // ObjectPointer might be a local (non-argument) local variable if it's a
586   // block's synthetic this pointer.
587   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
588     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
589 
590   // If we have a single element of null, it is a function that returns void.
591   // If we have more than one elements and the last one is null, it is a
592   // variadic function.
593   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
594       !includeMinimalInlineScopes())
595     ScopeDIE.addChild(
596         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
597 }
598 
599 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
600                                                  DIE &ScopeDIE) {
601   // We create children when the scope DIE is not null.
602   SmallVector<DIE *, 8> Children;
603   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
604 
605   // Add children
606   for (auto &I : Children)
607     ScopeDIE.addChild(std::move(I));
608 
609   return ObjectPointer;
610 }
611 
612 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
613     LexicalScope *Scope) {
614   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
615   if (AbsDef)
616     return;
617 
618   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
619 
620   DIE *ContextDIE;
621 
622   if (includeMinimalInlineScopes())
623     ContextDIE = &getUnitDie();
624   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
625   // the important distinction that the debug node is not associated with the
626   // DIE (since the debug node will be associated with the concrete DIE, if
627   // any). It could be refactored to some common utility function.
628   else if (auto *SPDecl = SP->getDeclaration()) {
629     ContextDIE = &getUnitDie();
630     getOrCreateSubprogramDIE(SPDecl);
631   } else
632     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
633 
634   // Passing null as the associated node because the abstract definition
635   // shouldn't be found by lookup.
636   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
637   applySubprogramAttributesToDefinition(SP, *AbsDef);
638 
639   if (!includeMinimalInlineScopes())
640     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
641   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
642     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
643 }
644 
645 DIE *DwarfCompileUnit::constructImportedEntityDIE(
646     const DIImportedEntity *Module) {
647   DIE *IMDie = DIE::get(DIEValueAllocator, (dwarf::Tag)Module->getTag());
648   insertDIE(Module, IMDie);
649   DIE *EntityDie;
650   auto *Entity = resolve(Module->getEntity());
651   if (auto *NS = dyn_cast<DINamespace>(Entity))
652     EntityDie = getOrCreateNameSpace(NS);
653   else if (auto *M = dyn_cast<DIModule>(Entity))
654     EntityDie = getOrCreateModule(M);
655   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
656     EntityDie = getOrCreateSubprogramDIE(SP);
657   else if (auto *T = dyn_cast<DIType>(Entity))
658     EntityDie = getOrCreateTypeDIE(T);
659   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
660     EntityDie = getOrCreateGlobalVariableDIE(GV, nullptr);
661   else
662     EntityDie = getDIE(Entity);
663   assert(EntityDie);
664   addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
665                 Module->getScope()->getDirectory());
666   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
667   StringRef Name = Module->getName();
668   if (!Name.empty())
669     addString(*IMDie, dwarf::DW_AT_name, Name);
670 
671   return IMDie;
672 }
673 
674 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
675   DIE *D = getDIE(SP);
676   if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP)) {
677     if (D)
678       // If this subprogram has an abstract definition, reference that
679       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
680   } else {
681     if (!D && !includeMinimalInlineScopes())
682       // Lazily construct the subprogram if we didn't see either concrete or
683       // inlined versions during codegen. (except in -gmlt ^ where we want
684       // to omit these entirely)
685       D = getOrCreateSubprogramDIE(SP);
686     if (D)
687       // And attach the attributes
688       applySubprogramAttributesToDefinition(SP, *D);
689   }
690 }
691 
692 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
693   // Don't bother labeling the .dwo unit, as its offset isn't used.
694   if (!Skeleton) {
695     LabelBegin = Asm->createTempSymbol("cu_begin");
696     Asm->OutStreamer->EmitLabel(LabelBegin);
697   }
698 
699   DwarfUnit::emitHeader(UseOffsets);
700 }
701 
702 /// addGlobalName - Add a new global name to the compile unit.
703 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
704                                      const DIScope *Context) {
705   if (includeMinimalInlineScopes())
706     return;
707   std::string FullName = getParentContextString(Context) + Name.str();
708   GlobalNames[FullName] = &Die;
709 }
710 
711 /// Add a new global type to the unit.
712 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
713                                      const DIScope *Context) {
714   if (includeMinimalInlineScopes())
715     return;
716   std::string FullName = getParentContextString(Context) + Ty->getName().str();
717   GlobalTypes[FullName] = &Die;
718 }
719 
720 /// addVariableAddress - Add DW_AT_location attribute for a
721 /// DbgVariable based on provided MachineLocation.
722 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
723                                           MachineLocation Location) {
724   if (DV.hasComplexAddress())
725     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
726   else if (DV.isBlockByrefVariable())
727     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
728   else
729     addAddress(Die, dwarf::DW_AT_location, Location);
730 }
731 
732 /// Add an address attribute to a die based on the location provided.
733 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
734                                   const MachineLocation &Location) {
735   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
736   DIEDwarfExpression Expr(*Asm, *this, *Loc);
737 
738   bool validReg;
739   if (Location.isReg())
740     validReg = Expr.AddMachineReg(*Asm->MF->getSubtarget().getRegisterInfo(),
741                                   Location.getReg());
742   else
743     validReg =
744         Expr.AddMachineRegIndirect(*Asm->MF->getSubtarget().getRegisterInfo(),
745                                    Location.getReg(), Location.getOffset());
746 
747   if (!validReg)
748     return;
749 
750   Expr.finalize();
751 
752   // Now attach the location information to the DIE.
753   addBlock(Die, Attribute, Loc);
754 }
755 
756 /// Start with the address based on the location provided, and generate the
757 /// DWARF information necessary to find the actual variable given the extra
758 /// address information encoded in the DbgVariable, starting from the starting
759 /// location.  Add the DWARF information to the die.
760 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
761                                          dwarf::Attribute Attribute,
762                                          const MachineLocation &Location) {
763   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
764   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
765   const DIExpression *Expr = DV.getSingleExpression();
766   DIExpressionCursor ExprCursor(Expr);
767   const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo();
768   auto Reg = Location.getReg();
769   DwarfExpr.addFragmentOffset(Expr);
770   bool ValidReg =
771       Location.getOffset()
772           ? DwarfExpr.AddMachineRegIndirect(TRI, Reg, Location.getOffset())
773           : DwarfExpr.AddMachineRegExpression(TRI, ExprCursor, Reg);
774 
775   if (!ValidReg)
776     return;
777 
778   DwarfExpr.AddExpression(std::move(ExprCursor));
779 
780   // Now attach the location information to the DIE.
781   addBlock(Die, Attribute, Loc);
782 }
783 
784 /// Add a Dwarf loclistptr attribute data and value.
785 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
786                                        unsigned Index) {
787   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
788                                                 : dwarf::DW_FORM_data4;
789   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
790 }
791 
792 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
793                                                DIE &VariableDie) {
794   StringRef Name = Var.getName();
795   if (!Name.empty())
796     addString(VariableDie, dwarf::DW_AT_name, Name);
797   const auto *DIVar = Var.getVariable();
798   if (DIVar)
799     if (uint32_t AlignInBytes = DIVar->getAlignInBytes())
800       addUInt(VariableDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata,
801               AlignInBytes);
802 
803   addSourceLine(VariableDie, DIVar);
804   addType(VariableDie, Var.getType());
805   if (Var.isArtificial())
806     addFlag(VariableDie, dwarf::DW_AT_artificial);
807 }
808 
809 /// Add a Dwarf expression attribute data and value.
810 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
811                                const MCExpr *Expr) {
812   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
813 }
814 
815 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
816     const DISubprogram *SP, DIE &SPDie) {
817   auto *SPDecl = SP->getDeclaration();
818   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
819   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
820   addGlobalName(SP->getName(), SPDie, Context);
821 }
822 
823 bool DwarfCompileUnit::isDwoUnit() const {
824   return DD->useSplitDwarf() && Skeleton;
825 }
826 
827 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
828   return getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly ||
829          (DD->useSplitDwarf() && !Skeleton);
830 }
831 } // end llvm namespace
832