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