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 // Return const expression if value is a GEP to access merged global
77 // constant. e.g.
78 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
79 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
80   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
81   if (!CE || CE->getNumOperands() != 3 ||
82       CE->getOpcode() != Instruction::GetElementPtr)
83     return nullptr;
84 
85   // First operand points to a global struct.
86   Value *Ptr = CE->getOperand(0);
87   GlobalValue *GV = dyn_cast<GlobalValue>(Ptr);
88   if (!GV || !isa<StructType>(GV->getValueType()))
89     return nullptr;
90 
91   // Second operand is zero.
92   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
93   if (!CI || !CI->isZero())
94     return nullptr;
95 
96   // Third operand is offset.
97   if (!isa<ConstantInt>(CE->getOperand(2)))
98     return nullptr;
99 
100   return CE;
101 }
102 
103 /// getOrCreateGlobalVariableDIE - get or create global variable DIE.
104 DIE *DwarfCompileUnit::getOrCreateGlobalVariableDIE(
105     const DIGlobalVariable *GV) {
106   // Check for pre-existence.
107   if (DIE *Die = getDIE(GV))
108     return Die;
109 
110   assert(GV);
111 
112   auto *GVContext = GV->getScope();
113   auto *GTy = DD->resolve(GV->getType());
114 
115   // Construct the context before querying for the existence of the DIE in
116   // case such construction creates the DIE.
117   // For Local Scope, do not construct context DIE.
118   bool IsLocalScope = GVContext && isa<DILocalScope>(GVContext);
119   DIE *ContextDIE = IsLocalScope ? nullptr : getOrCreateContextDIE(GVContext);
120   assert(ContextDIE || IsLocalScope);
121 
122   // Create new global variable and add to map.
123   DIE *VariableDIE = IsLocalScope
124                          ? createDIE(GV->getTag(), GV)
125                          : &createAndAddDIE(GV->getTag(), *ContextDIE, GV);
126 
127   DIScope *DeclContext;
128   if (auto *SDMDecl = GV->getStaticDataMemberDeclaration()) {
129     DeclContext = resolve(SDMDecl->getScope());
130     assert(SDMDecl->isStaticMember() && "Expected static member decl");
131     assert(GV->isDefinition());
132     // We need the declaration DIE that is in the static member's class.
133     DIE *VariableSpecDIE = getOrCreateStaticMemberDIE(SDMDecl);
134     addDIEEntry(*VariableDIE, dwarf::DW_AT_specification, *VariableSpecDIE);
135   } else {
136     DeclContext = GV->getScope();
137     // Add name and type.
138     addString(*VariableDIE, dwarf::DW_AT_name, GV->getDisplayName());
139     addType(*VariableDIE, GTy);
140 
141     // Add scoping info.
142     if (!GV->isLocalToUnit())
143       addFlag(*VariableDIE, dwarf::DW_AT_external);
144 
145     // Add line number info.
146     addSourceLine(*VariableDIE, GV);
147   }
148 
149   if (!GV->isDefinition())
150     addFlag(*VariableDIE, dwarf::DW_AT_declaration);
151   else
152     addGlobalName(GV->getName(), *VariableDIE, DeclContext);
153 
154   // Add location.
155   bool addToAccelTable = false;
156   if (auto *Global = dyn_cast_or_null<GlobalVariable>(GV->getVariable())) {
157     addToAccelTable = true;
158     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
159     const MCSymbol *Sym = Asm->getSymbol(Global);
160     if (Global->isThreadLocal()) {
161       if (Asm->TM.Options.EmulatedTLS) {
162         // TODO: add debug info for emulated thread local mode.
163       } else {
164         // FIXME: Make this work with -gsplit-dwarf.
165         unsigned PointerSize = Asm->getDataLayout().getPointerSize();
166         assert((PointerSize == 4 || PointerSize == 8) &&
167                "Add support for other sizes if necessary");
168         // Based on GCC's support for TLS:
169         if (!DD->useSplitDwarf()) {
170           // 1) Start with a constNu of the appropriate pointer size
171           addUInt(*Loc, dwarf::DW_FORM_data1, PointerSize == 4
172                                                   ? dwarf::DW_OP_const4u
173                                                   : dwarf::DW_OP_const8u);
174           // 2) containing the (relocated) offset of the TLS variable
175           //    within the module's TLS block.
176           addExpr(*Loc, dwarf::DW_FORM_udata,
177                   Asm->getObjFileLowering().getDebugThreadLocalSymbol(Sym));
178         } else {
179           addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_const_index);
180           addUInt(*Loc, dwarf::DW_FORM_udata,
181                   DD->getAddressPool().getIndex(Sym, /* TLS */ true));
182         }
183         // 3) followed by an OP to make the debugger do a TLS lookup.
184         addUInt(*Loc, dwarf::DW_FORM_data1,
185                 DD->useGNUTLSOpcode() ? dwarf::DW_OP_GNU_push_tls_address
186                                       : dwarf::DW_OP_form_tls_address);
187       }
188     } else {
189       DD->addArangeLabel(SymbolCU(this, Sym));
190       addOpAddress(*Loc, Sym);
191     }
192 
193     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
194     addLinkageName(*VariableDIE, GV->getLinkageName());
195   } else if (const ConstantInt *CI =
196                  dyn_cast_or_null<ConstantInt>(GV->getVariable())) {
197     addConstantValue(*VariableDIE, CI, GTy);
198   } else if (const ConstantExpr *CE = getMergedGlobalExpr(GV->getVariable())) {
199     addToAccelTable = true;
200     // GV is a merged global.
201     DIELoc *Loc = new (DIEValueAllocator) DIELoc;
202     auto *Ptr = cast<GlobalValue>(CE->getOperand(0));
203     MCSymbol *Sym = Asm->getSymbol(Ptr);
204     DD->addArangeLabel(SymbolCU(this, Sym));
205     addOpAddress(*Loc, Sym);
206     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
207     SmallVector<Value *, 3> Idx(CE->op_begin() + 1, CE->op_end());
208     addUInt(*Loc, dwarf::DW_FORM_udata,
209             Asm->getDataLayout().getIndexedOffsetInType(Ptr->getValueType(), Idx));
210     addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
211     addBlock(*VariableDIE, dwarf::DW_AT_location, Loc);
212   }
213 
214   if (addToAccelTable) {
215     DD->addAccelName(GV->getName(), *VariableDIE);
216 
217     // If the linkage name is different than the name, go ahead and output
218     // that as well into the name table.
219     if (GV->getLinkageName() != "" && GV->getName() != GV->getLinkageName())
220       DD->addAccelName(GV->getLinkageName(), *VariableDIE);
221   }
222 
223   return VariableDIE;
224 }
225 
226 void DwarfCompileUnit::addRange(RangeSpan Range) {
227   bool SameAsPrevCU = this == DD->getPrevCU();
228   DD->setPrevCU(this);
229   // If we have no current ranges just add the range and return, otherwise,
230   // check the current section and CU against the previous section and CU we
231   // emitted into and the subprogram was contained within. If these are the
232   // same then extend our current range, otherwise add this as a new range.
233   if (CURanges.empty() || !SameAsPrevCU ||
234       (&CURanges.back().getEnd()->getSection() !=
235        &Range.getEnd()->getSection())) {
236     CURanges.push_back(Range);
237     return;
238   }
239 
240   CURanges.back().setEnd(Range.getEnd());
241 }
242 
243 DIE::value_iterator
244 DwarfCompileUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute,
245                                   const MCSymbol *Label, const MCSymbol *Sec) {
246   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
247     return addLabel(Die, Attribute,
248                     DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
249                                                : dwarf::DW_FORM_data4,
250                     Label);
251   return addSectionDelta(Die, Attribute, Label, Sec);
252 }
253 
254 void DwarfCompileUnit::initStmtList() {
255   // Define start line table label for each Compile Unit.
256   MCSymbol *LineTableStartSym =
257       Asm->OutStreamer->getDwarfLineTableSymbol(getUniqueID());
258 
259   // DW_AT_stmt_list is a offset of line number information for this
260   // compile unit in debug_line section. For split dwarf this is
261   // left in the skeleton CU and so not included.
262   // The line table entries are not always emitted in assembly, so it
263   // is not okay to use line_table_start here.
264   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
265   StmtListValue =
266       addSectionLabel(UnitDie, dwarf::DW_AT_stmt_list, LineTableStartSym,
267                       TLOF.getDwarfLineSection()->getBeginSymbol());
268 }
269 
270 void DwarfCompileUnit::applyStmtList(DIE &D) {
271   D.addValue(DIEValueAllocator, *StmtListValue);
272 }
273 
274 void DwarfCompileUnit::attachLowHighPC(DIE &D, const MCSymbol *Begin,
275                                        const MCSymbol *End) {
276   assert(Begin && "Begin label should not be null!");
277   assert(End && "End label should not be null!");
278   assert(Begin->isDefined() && "Invalid starting label");
279   assert(End->isDefined() && "Invalid end label");
280 
281   addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
282   if (DD->getDwarfVersion() < 4)
283     addLabelAddress(D, dwarf::DW_AT_high_pc, End);
284   else
285     addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
286 }
287 
288 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
289 // and DW_AT_high_pc attributes. If there are global variables in this
290 // scope then create and insert DIEs for these variables.
291 DIE &DwarfCompileUnit::updateSubprogramScopeDIE(const DISubprogram *SP) {
292   DIE *SPDie = getOrCreateSubprogramDIE(SP, includeMinimalInlineScopes());
293 
294   attachLowHighPC(*SPDie, Asm->getFunctionBegin(), Asm->getFunctionEnd());
295   if (!DD->getCurrentFunction()->getTarget().Options.DisableFramePointerElim(
296           *DD->getCurrentFunction()))
297     addFlag(*SPDie, dwarf::DW_AT_APPLE_omit_frame_ptr);
298 
299   // Only include DW_AT_frame_base in full debug info
300   if (!includeMinimalInlineScopes()) {
301     const TargetRegisterInfo *RI = Asm->MF->getSubtarget().getRegisterInfo();
302     MachineLocation Location(RI->getFrameRegister(*Asm->MF));
303     if (RI->isPhysicalRegister(Location.getReg()))
304       addAddress(*SPDie, dwarf::DW_AT_frame_base, Location);
305   }
306 
307   // Add name to the name table, we do this here because we're guaranteed
308   // to have concrete versions of our DW_TAG_subprogram nodes.
309   DD->addSubprogramNames(SP, *SPDie);
310 
311   return *SPDie;
312 }
313 
314 // Construct a DIE for this scope.
315 void DwarfCompileUnit::constructScopeDIE(
316     LexicalScope *Scope, SmallVectorImpl<DIE *> &FinalChildren) {
317   if (!Scope || !Scope->getScopeNode())
318     return;
319 
320   auto *DS = Scope->getScopeNode();
321 
322   assert((Scope->getInlinedAt() || !isa<DISubprogram>(DS)) &&
323          "Only handle inlined subprograms here, use "
324          "constructSubprogramScopeDIE for non-inlined "
325          "subprograms");
326 
327   SmallVector<DIE *, 8> Children;
328 
329   // We try to create the scope DIE first, then the children DIEs. This will
330   // avoid creating un-used children then removing them later when we find out
331   // the scope DIE is null.
332   DIE *ScopeDIE;
333   if (Scope->getParent() && isa<DISubprogram>(DS)) {
334     ScopeDIE = constructInlinedScopeDIE(Scope);
335     if (!ScopeDIE)
336       return;
337     // We create children when the scope DIE is not null.
338     createScopeChildrenDIE(Scope, Children);
339   } else {
340     // Early exit when we know the scope DIE is going to be null.
341     if (DD->isLexicalScopeDIENull(Scope))
342       return;
343 
344     bool HasNonScopeChildren;
345 
346     // We create children here when we know the scope DIE is not going to be
347     // null and the children will be added to the scope DIE.
348     createScopeChildrenDIE(Scope, Children, &HasNonScopeChildren);
349 
350     // If there are only other scopes as children, put them directly in the
351     // parent instead, as this scope would serve no purpose.
352     if (!HasNonScopeChildren) {
353       FinalChildren.insert(FinalChildren.end(),
354                            std::make_move_iterator(Children.begin()),
355                            std::make_move_iterator(Children.end()));
356       return;
357     }
358     ScopeDIE = constructLexicalScopeDIE(Scope);
359     assert(ScopeDIE && "Scope DIE should not be null.");
360   }
361 
362   // Add children
363   for (auto &I : Children)
364     ScopeDIE->addChild(std::move(I));
365 
366   FinalChildren.push_back(std::move(ScopeDIE));
367   addLocalScopeDieToLexicalScope(Scope, ScopeDIE);
368 }
369 
370 DIE::value_iterator
371 DwarfCompileUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute,
372                                   const MCSymbol *Hi, const MCSymbol *Lo) {
373   return Die.addValue(DIEValueAllocator, Attribute,
374                       DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
375                                                  : dwarf::DW_FORM_data4,
376                       new (DIEValueAllocator) DIEDelta(Hi, Lo));
377 }
378 
379 void DwarfCompileUnit::addScopeRangeList(DIE &ScopeDIE,
380                                          SmallVector<RangeSpan, 2> Range) {
381   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
382 
383   // Emit offset in .debug_range as a relocatable label. emitDIE will handle
384   // emitting it appropriately.
385   const MCSymbol *RangeSectionSym =
386       TLOF.getDwarfRangesSection()->getBeginSymbol();
387 
388   RangeSpanList List(Asm->createTempSymbol("debug_ranges"), std::move(Range));
389 
390   // Under fission, ranges are specified by constant offsets relative to the
391   // CU's DW_AT_GNU_ranges_base.
392   if (isDwoUnit())
393     addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
394                     RangeSectionSym);
395   else
396     addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges, List.getSym(),
397                     RangeSectionSym);
398 
399   // Add the range list to the set of ranges to be emitted.
400   (Skeleton ? Skeleton : this)->CURangeLists.push_back(std::move(List));
401 }
402 
403 void DwarfCompileUnit::attachRangesOrLowHighPC(
404     DIE &Die, SmallVector<RangeSpan, 2> Ranges) {
405   if (Ranges.size() == 1) {
406     const auto &single = Ranges.front();
407     attachLowHighPC(Die, single.getStart(), single.getEnd());
408   } else
409     addScopeRangeList(Die, std::move(Ranges));
410 }
411 
412 void DwarfCompileUnit::attachRangesOrLowHighPC(
413     DIE &Die, const SmallVectorImpl<InsnRange> &Ranges) {
414   SmallVector<RangeSpan, 2> List;
415   List.reserve(Ranges.size());
416   for (const InsnRange &R : Ranges)
417     List.push_back(RangeSpan(DD->getLabelBeforeInsn(R.first),
418                              DD->getLabelAfterInsn(R.second)));
419   attachRangesOrLowHighPC(Die, std::move(List));
420 }
421 
422 // This scope represents inlined body of a function. Construct DIE to
423 // represent this concrete inlined copy of the function.
424 DIE *DwarfCompileUnit::constructInlinedScopeDIE(LexicalScope *Scope) {
425   assert(Scope->getScopeNode());
426   auto *DS = Scope->getScopeNode();
427   auto *InlinedSP = getDISubprogram(DS);
428   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
429   // was inlined from another compile unit.
430   DIE *OriginDIE = DU->getAbstractSPDies()[InlinedSP];
431   assert(OriginDIE && "Unable to find original DIE for an inlined subprogram.");
432 
433   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_inlined_subroutine);
434   addDIEEntry(*ScopeDIE, dwarf::DW_AT_abstract_origin, *OriginDIE);
435 
436   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
437 
438   // Add the call site information to the DIE.
439   const DILocation *IA = Scope->getInlinedAt();
440   addUInt(*ScopeDIE, dwarf::DW_AT_call_file, None,
441           getOrCreateSourceID(IA->getFilename(), IA->getDirectory()));
442   addUInt(*ScopeDIE, dwarf::DW_AT_call_line, None, IA->getLine());
443   if (IA->getDiscriminator())
444     addUInt(*ScopeDIE, dwarf::DW_AT_GNU_discriminator, None,
445             IA->getDiscriminator());
446 
447   // Add name to the name table, we do this here because we're guaranteed
448   // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
449   DD->addSubprogramNames(InlinedSP, *ScopeDIE);
450 
451   return ScopeDIE;
452 }
453 
454 // Construct new DW_TAG_lexical_block for this scope and attach
455 // DW_AT_low_pc/DW_AT_high_pc labels.
456 DIE *DwarfCompileUnit::constructLexicalScopeDIE(LexicalScope *Scope) {
457   if (DD->isLexicalScopeDIENull(Scope))
458     return nullptr;
459 
460   auto ScopeDIE = DIE::get(DIEValueAllocator, dwarf::DW_TAG_lexical_block);
461   if (Scope->isAbstractScope())
462     return ScopeDIE;
463 
464   attachRangesOrLowHighPC(*ScopeDIE, Scope->getRanges());
465 
466   return ScopeDIE;
467 }
468 
469 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
470 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV, bool Abstract) {
471   auto D = constructVariableDIEImpl(DV, Abstract);
472   DV.setDIE(*D);
473   return D;
474 }
475 
476 DIE *DwarfCompileUnit::constructVariableDIEImpl(const DbgVariable &DV,
477                                                 bool Abstract) {
478   // Define variable debug information entry.
479   auto VariableDie = DIE::get(DIEValueAllocator, DV.getTag());
480 
481   if (Abstract) {
482     applyVariableAttributes(DV, *VariableDie);
483     return VariableDie;
484   }
485 
486   // Add variable address.
487 
488   unsigned Offset = DV.getDebugLocListIndex();
489   if (Offset != ~0U) {
490     addLocationList(*VariableDie, dwarf::DW_AT_location, Offset);
491     return VariableDie;
492   }
493 
494   // Check if variable is described by a DBG_VALUE instruction.
495   if (const MachineInstr *DVInsn = DV.getMInsn()) {
496     assert(DVInsn->getNumOperands() == 4);
497     if (DVInsn->getOperand(0).isReg()) {
498       const MachineOperand RegOp = DVInsn->getOperand(0);
499       // If the second operand is an immediate, this is an indirect value.
500       if (DVInsn->getOperand(1).isImm()) {
501         MachineLocation Location(RegOp.getReg(),
502                                  DVInsn->getOperand(1).getImm());
503         addVariableAddress(DV, *VariableDie, Location);
504       } else if (RegOp.getReg())
505         addVariableAddress(DV, *VariableDie, MachineLocation(RegOp.getReg()));
506     } else if (DVInsn->getOperand(0).isImm()) {
507       // This variable is described by a single constant.
508       // Check whether it has a DIExpression.
509       auto *Expr = DV.getSingleExpression();
510       if (Expr && Expr->getNumElements()) {
511         DIELoc *Loc = new (DIEValueAllocator) DIELoc;
512         DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
513         // If there is an expression, emit raw unsigned bytes.
514         DwarfExpr.AddUnsignedConstant(DVInsn->getOperand(0).getImm());
515         DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
516         addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
517       } else
518         addConstantValue(*VariableDie, DVInsn->getOperand(0), DV.getType());
519     } else if (DVInsn->getOperand(0).isFPImm())
520       addConstantFPValue(*VariableDie, DVInsn->getOperand(0));
521     else if (DVInsn->getOperand(0).isCImm())
522       addConstantValue(*VariableDie, DVInsn->getOperand(0).getCImm(),
523                        DV.getType());
524 
525     return VariableDie;
526   }
527 
528   // .. else use frame index.
529   if (DV.getFrameIndex().empty())
530     return VariableDie;
531 
532   auto Expr = DV.getExpression().begin();
533   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
534   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
535   for (auto FI : DV.getFrameIndex()) {
536     unsigned FrameReg = 0;
537     const TargetFrameLowering *TFI = Asm->MF->getSubtarget().getFrameLowering();
538     int Offset = TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
539     assert(Expr != DV.getExpression().end() && "Wrong number of expressions");
540     DwarfExpr.AddMachineRegIndirect(FrameReg, Offset);
541     DwarfExpr.AddExpression((*Expr)->expr_op_begin(), (*Expr)->expr_op_end());
542     ++Expr;
543   }
544   addBlock(*VariableDie, dwarf::DW_AT_location, Loc);
545 
546   return VariableDie;
547 }
548 
549 DIE *DwarfCompileUnit::constructVariableDIE(DbgVariable &DV,
550                                             const LexicalScope &Scope,
551                                             DIE *&ObjectPointer) {
552   auto Var = constructVariableDIE(DV, Scope.isAbstractScope());
553   if (DV.isObjectPointer())
554     ObjectPointer = Var;
555   return Var;
556 }
557 
558 DIE *DwarfCompileUnit::createScopeChildrenDIE(LexicalScope *Scope,
559                                               SmallVectorImpl<DIE *> &Children,
560                                               bool *HasNonScopeChildren) {
561   DIE *ObjectPointer = nullptr;
562   bool HasLocalDclDie = false;
563   auto *DS = Scope->getScopeNode();
564 
565   for (DbgVariable *DV : DU->getScopeVariables().lookup(Scope))
566     Children.push_back(constructVariableDIE(*DV, *Scope, ObjectPointer));
567 
568   // Skip local declarations in gmlt-like data.
569   if (!includeMinimalInlineScopes()) {
570     for (const auto *DI : LocalDeclNodes[DS]) {
571       DIE *D = nullptr;
572       if (auto *IE = dyn_cast<DIImportedEntity>(DI))
573         D = getOrCreateImportedEntityDIE(IE);
574       else if (auto *GV = dyn_cast<DIGlobalVariable>(DI))
575         D = getOrCreateGlobalVariableDIE(GV);
576       else if (auto *RT = dyn_cast<DIType>(DI))
577         D = getOrCreateTypeDIE(RT);
578       else
579         llvm_unreachable("Unexpected DI node!");
580       addLocalDclDieToLexicalScope(Scope, D);
581       HasLocalDclDie = true;
582     }
583   }
584 
585   if (HasNonScopeChildren)
586     *HasNonScopeChildren = !Children.empty() || HasLocalDclDie;
587 
588   for (LexicalScope *LS : Scope->getChildren())
589     constructScopeDIE(LS, Children);
590 
591   return ObjectPointer;
592 }
593 
594 void DwarfCompileUnit::constructSubprogramScopeDIE(LexicalScope *Scope) {
595   assert(Scope && Scope->getScopeNode());
596   assert(!Scope->getInlinedAt());
597   assert(!Scope->isAbstractScope());
598   auto *Sub = cast<DISubprogram>(Scope->getScopeNode());
599 
600   DD->getProcessedSPNodes().insert(Sub);
601 
602   DIE &ScopeDIE = updateSubprogramScopeDIE(Sub);
603 
604   // If this is a variadic function, add an unspecified parameter.
605   DITypeRefArray FnArgs = Sub->getType()->getTypeArray();
606 
607   // Collect lexical scope children first.
608   // ObjectPointer might be a local (non-argument) local variable if it's a
609   // block's synthetic this pointer.
610   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, ScopeDIE))
611     addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, *ObjectPointer);
612 
613   // If we have a single element of null, it is a function that returns void.
614   // If we have more than one elements and the last one is null, it is a
615   // variadic function.
616   if (FnArgs.size() > 1 && !FnArgs[FnArgs.size() - 1] &&
617       !includeMinimalInlineScopes())
618     ScopeDIE.addChild(
619         DIE::get(DIEValueAllocator, dwarf::DW_TAG_unspecified_parameters));
620 }
621 
622 DIE *DwarfCompileUnit::createAndAddScopeChildren(LexicalScope *Scope,
623                                                  DIE &ScopeDIE) {
624   // We create children when the scope DIE is not null.
625   SmallVector<DIE *, 8> Children;
626   DIE *ObjectPointer = createScopeChildrenDIE(Scope, Children);
627 
628   // Add children
629   for (auto &I : Children)
630     ScopeDIE.addChild(std::move(I));
631 
632   addLocalScopeDieToLexicalScope(Scope, &ScopeDIE);
633 
634   return ObjectPointer;
635 }
636 
637 void DwarfCompileUnit::constructAbstractSubprogramScopeDIE(
638     LexicalScope *Scope) {
639   DIE *&AbsDef = DU->getAbstractSPDies()[Scope->getScopeNode()];
640   if (AbsDef)
641     return;
642 
643   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
644 
645   DIE *ContextDIE;
646 
647   if (includeMinimalInlineScopes())
648     ContextDIE = &getUnitDie();
649   // Some of this is duplicated from DwarfUnit::getOrCreateSubprogramDIE, with
650   // the important distinction that the debug node is not associated with the
651   // DIE (since the debug node will be associated with the concrete DIE, if
652   // any). It could be refactored to some common utility function.
653   else if (auto *SPDecl = SP->getDeclaration()) {
654     ContextDIE = &getUnitDie();
655     getOrCreateSubprogramDIE(SPDecl);
656   } else
657     ContextDIE = getOrCreateContextDIE(resolve(SP->getScope()));
658 
659   // Passing null as the associated node because the abstract definition
660   // shouldn't be found by lookup.
661   AbsDef = &createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, nullptr);
662   applySubprogramAttributesToDefinition(SP, *AbsDef);
663 
664   if (!includeMinimalInlineScopes())
665     addUInt(*AbsDef, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
666   if (DIE *ObjectPointer = createAndAddScopeChildren(Scope, *AbsDef))
667     addDIEEntry(*AbsDef, dwarf::DW_AT_object_pointer, *ObjectPointer);
668 }
669 
670 DIE *DwarfCompileUnit::getOrCreateImportedEntityDIE(
671     const DIImportedEntity *Module) {
672   if (DIE *Die = getDIE(Module))
673     return Die;
674 
675   return constructImportedEntityDIE(Module);
676 }
677 
678 DIE *DwarfCompileUnit::constructImportedEntityDIE(
679     const DIImportedEntity *Module) {
680 
681   assert(!getDIE(Module));
682 
683   DIE *IMDie = createDIE(Module->getTag(), Module);
684   DIE *EntityDie;
685   auto *Entity = resolve(Module->getEntity());
686   if (auto *NS = dyn_cast<DINamespace>(Entity))
687     EntityDie = getOrCreateNameSpace(NS);
688   else if (auto *M = dyn_cast<DIModule>(Entity))
689     EntityDie = getOrCreateModule(M);
690   else if (auto *SP = dyn_cast<DISubprogram>(Entity))
691     EntityDie = getOrCreateSubprogramDIE(SP);
692   else if (auto *T = dyn_cast<DIType>(Entity))
693     EntityDie = getOrCreateTypeDIE(T);
694   else if (auto *GV = dyn_cast<DIGlobalVariable>(Entity))
695     EntityDie = getOrCreateGlobalVariableDIE(GV);
696   else
697     EntityDie = getDIE(Entity);
698   assert(EntityDie);
699   addSourceLine(*IMDie, Module->getLine(), Module->getScope()->getFilename(),
700                 Module->getScope()->getDirectory());
701   addDIEEntry(*IMDie, dwarf::DW_AT_import, *EntityDie);
702   StringRef Name = Module->getName();
703   if (!Name.empty())
704     addString(*IMDie, dwarf::DW_AT_name, Name);
705 
706   return IMDie;
707 }
708 
709 void DwarfCompileUnit::finishSubprogramDefinition(const DISubprogram *SP) {
710   if (DIE *D = getDIE(SP)) {
711     if (DIE *AbsSPDIE = DU->getAbstractSPDies().lookup(SP))
712       // If this subprogram has an abstract definition, reference that
713       addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
714     else
715       // And attach the attributes
716       applySubprogramAttributesToDefinition(SP, *D);
717   }
718 }
719 
720 void DwarfCompileUnit::finishLocalScopeDefinitions() {
721   for (const auto &I : getLSDieInfoMap()) {
722     auto LSInfo = I.second;
723     // Attach all local dcl DIEs to abstract local scope if available,
724     // otherwise attach it to concrete local scope.
725     DIE *LBDie =
726         LSInfo.AbstractLSDie ? LSInfo.AbstractLSDie : LSInfo.ConcreteLSDie;
727     assert(LBDie || LSInfo.LocalDclDies.empty());
728     for (auto &D : LSInfo.LocalDclDies)
729       LBDie->addChild(std::move(D));
730 
731     if (isa<DISubprogram>(I.first))
732       // For function scope there is nothing else to do.
733       // "abstract_origin" dwarf attribute was added somewhere else.
734       continue;
735 
736     if (LSInfo.AbstractLSDie) {
737       // Add "abstract_origin" dwarf attribute to concrete local scope pointing
738       // to the corresponding abstract local scope.
739       if (LSInfo.ConcreteLSDie)
740         addDIEEntry(*LSInfo.ConcreteLSDie, dwarf::DW_AT_abstract_origin,
741                     *LSInfo.AbstractLSDie);
742       // Add "abstract_origin" dwarf attribute to inline local scope pointing
743       // to the corresponding abstract local scope.
744       for (auto &L : LSInfo.InlineLSDies)
745         addDIEEntry(*L, dwarf::DW_AT_abstract_origin, *LSInfo.AbstractLSDie);
746     }
747   }
748 }
749 
750 void DwarfCompileUnit::collectDeadVariables(const DISubprogram *SP) {
751   assert(SP && "CU's subprogram list contains a non-subprogram");
752   assert(SP->isDefinition() &&
753          "CU's subprogram list contains a subprogram declaration");
754   auto Variables = SP->getVariables();
755   if (Variables.size() == 0)
756     return;
757 
758   DIE *SPDIE = DU->getAbstractSPDies().lookup(SP);
759   if (!SPDIE)
760     return;
761   assert(SPDIE);
762   for (const DILocalVariable *DV : Variables) {
763     DbgVariable NewVar(DV, /* IA */ nullptr, DD);
764     auto VariableDie = constructVariableDIE(NewVar);
765     applyVariableAttributes(NewVar, *VariableDie);
766     SPDIE->addChild(std::move(VariableDie));
767   }
768 }
769 
770 void DwarfCompileUnit::emitHeader(bool UseOffsets) {
771   // Don't bother labeling the .dwo unit, as its offset isn't used.
772   if (!Skeleton) {
773     LabelBegin = Asm->createTempSymbol("cu_begin");
774     Asm->OutStreamer->EmitLabel(LabelBegin);
775   }
776 
777   DwarfUnit::emitHeader(UseOffsets);
778 }
779 
780 /// addGlobalName - Add a new global name to the compile unit.
781 void DwarfCompileUnit::addGlobalName(StringRef Name, DIE &Die,
782                                      const DIScope *Context) {
783   if (includeMinimalInlineScopes())
784     return;
785   std::string FullName = getParentContextString(Context) + Name.str();
786   GlobalNames[FullName] = &Die;
787 }
788 
789 /// Add a new global type to the unit.
790 void DwarfCompileUnit::addGlobalType(const DIType *Ty, const DIE &Die,
791                                      const DIScope *Context) {
792   if (includeMinimalInlineScopes())
793     return;
794   std::string FullName = getParentContextString(Context) + Ty->getName().str();
795   GlobalTypes[FullName] = &Die;
796 }
797 
798 /// addVariableAddress - Add DW_AT_location attribute for a
799 /// DbgVariable based on provided MachineLocation.
800 void DwarfCompileUnit::addVariableAddress(const DbgVariable &DV, DIE &Die,
801                                           MachineLocation Location) {
802   if (DV.hasComplexAddress())
803     addComplexAddress(DV, Die, dwarf::DW_AT_location, Location);
804   else if (DV.isBlockByrefVariable())
805     addBlockByrefAddress(DV, Die, dwarf::DW_AT_location, Location);
806   else
807     addAddress(Die, dwarf::DW_AT_location, Location);
808 }
809 
810 /// Add an address attribute to a die based on the location provided.
811 void DwarfCompileUnit::addAddress(DIE &Die, dwarf::Attribute Attribute,
812                                   const MachineLocation &Location) {
813   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
814 
815   bool validReg;
816   if (Location.isReg())
817     validReg = addRegisterOpPiece(*Loc, Location.getReg());
818   else
819     validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset());
820 
821   if (!validReg)
822     return;
823 
824   // Now attach the location information to the DIE.
825   addBlock(Die, Attribute, Loc);
826 }
827 
828 /// Start with the address based on the location provided, and generate the
829 /// DWARF information necessary to find the actual variable given the extra
830 /// address information encoded in the DbgVariable, starting from the starting
831 /// location.  Add the DWARF information to the die.
832 void DwarfCompileUnit::addComplexAddress(const DbgVariable &DV, DIE &Die,
833                                          dwarf::Attribute Attribute,
834                                          const MachineLocation &Location) {
835   DIELoc *Loc = new (DIEValueAllocator) DIELoc;
836   DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc);
837   const DIExpression *Expr = DV.getSingleExpression();
838   bool ValidReg;
839   if (Location.getOffset()) {
840     ValidReg = DwarfExpr.AddMachineRegIndirect(Location.getReg(),
841                                                Location.getOffset());
842     if (ValidReg)
843       DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end());
844   } else
845     ValidReg = DwarfExpr.AddMachineRegExpression(Expr, Location.getReg());
846 
847   // Now attach the location information to the DIE.
848   if (ValidReg)
849     addBlock(Die, Attribute, Loc);
850 }
851 
852 /// Add a Dwarf loclistptr attribute data and value.
853 void DwarfCompileUnit::addLocationList(DIE &Die, dwarf::Attribute Attribute,
854                                        unsigned Index) {
855   dwarf::Form Form = DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset
856                                                 : dwarf::DW_FORM_data4;
857   Die.addValue(DIEValueAllocator, Attribute, Form, DIELocList(Index));
858 }
859 
860 void DwarfCompileUnit::applyVariableAttributes(const DbgVariable &Var,
861                                                DIE &VariableDie) {
862   StringRef Name = Var.getName();
863   if (!Name.empty())
864     addString(VariableDie, dwarf::DW_AT_name, Name);
865   addSourceLine(VariableDie, Var.getVariable());
866   addType(VariableDie, Var.getType());
867   if (Var.isArtificial())
868     addFlag(VariableDie, dwarf::DW_AT_artificial);
869 }
870 
871 /// Add a Dwarf expression attribute data and value.
872 void DwarfCompileUnit::addExpr(DIELoc &Die, dwarf::Form Form,
873                                const MCExpr *Expr) {
874   Die.addValue(DIEValueAllocator, (dwarf::Attribute)0, Form, DIEExpr(Expr));
875 }
876 
877 void DwarfCompileUnit::applySubprogramAttributesToDefinition(
878     const DISubprogram *SP, DIE &SPDie) {
879   auto *SPDecl = SP->getDeclaration();
880   auto *Context = resolve(SPDecl ? SPDecl->getScope() : SP->getScope());
881   applySubprogramAttributes(SP, SPDie, includeMinimalInlineScopes());
882   addGlobalName(SP->getName(), SPDie, Context);
883 }
884 
885 void DwarfCompileUnit::addLocalScopeDieToLexicalScope(LexicalScope *LS,
886                                                       DIE *D) {
887   auto &LSInfo = getLSDieInfoMap()[LS->getScopeNode()];
888   if (LS->isAbstractScope()) {
889     assert(!LSInfo.AbstractLSDie && "Adding abstract LS DIE twice.");
890     LSInfo.AbstractLSDie = D;
891     return;
892   }
893   if (LS->getInlinedAt()) {
894     assert(!LSInfo.InlineLSDies.count(D) && "Adding inline LS DIE twice.");
895     LSInfo.InlineLSDies.insert(D);
896     return;
897   }
898   assert(!LSInfo.ConcreteLSDie && "Adding cocncrete LS DIE twice.");
899   LSInfo.ConcreteLSDie = D;
900   return;
901 }
902 
903 void DwarfCompileUnit::addLocalDclDieToLexicalScope(LexicalScope *LS, DIE *D) {
904   auto &LSInfo = getLSDieInfoMap()[LS->getScopeNode()];
905   LSInfo.LocalDclDies.insert(D);
906   return;
907 }
908 
909 bool DwarfCompileUnit::isDwoUnit() const {
910   return DD->useSplitDwarf() && Skeleton;
911 }
912 
913 bool DwarfCompileUnit::includeMinimalInlineScopes() const {
914   return getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly ||
915          (DD->useSplitDwarf() && !Skeleton);
916 }
917 } // end llvm namespace
918