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