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