1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
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 writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "DIE.h"
17 #include "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
45 using namespace llvm;
46
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
48 cl::Hidden,
49 cl::desc("Disable debug info printing"));
50
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
53 cl::init(false));
54
55 namespace {
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
59
60 //===----------------------------------------------------------------------===//
61
62 /// Configuration values for initial hash set sizes (log2).
63 ///
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
65
66 namespace llvm {
67
getType() const68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
71 // addresses instead.
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
79
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
82
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
88
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
91
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
97 DIType subType = Ty;
98 unsigned tag = Ty.getTag();
99
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
103 }
104
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
107
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
113 }
114 return Ty;
115 }
116 return Ty;
117 }
118
119 } // end llvm namespace
120
DwarfDebug(AsmPrinter * A,Module * M)121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
124 PrevLabel(NULL) {
125 NextStringPoolNumber = 0;
126
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
131 {
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
133 beginModule(M);
134 }
135 }
~DwarfDebug()136 DwarfDebug::~DwarfDebug() {
137 }
138
getStringPoolEntry(StringRef Str)139 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
140 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
141 if (Entry.first) return Entry.first;
142
143 Entry.second = NextStringPoolNumber++;
144 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
145 }
146
147
148 /// assignAbbrevNumber - Define a unique number for the abbreviation.
149 ///
assignAbbrevNumber(DIEAbbrev & Abbrev)150 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
151 // Profile the node so that we can make it unique.
152 FoldingSetNodeID ID;
153 Abbrev.Profile(ID);
154
155 // Check the set for priors.
156 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
157
158 // If it's newly added.
159 if (InSet == &Abbrev) {
160 // Add to abbreviation list.
161 Abbreviations.push_back(&Abbrev);
162
163 // Assign the vector position + 1 as its number.
164 Abbrev.setNumber(Abbreviations.size());
165 } else {
166 // Assign existing abbreviation number.
167 Abbrev.setNumber(InSet->getNumber());
168 }
169 }
170
171 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
172 /// printer to not emit usual symbol prefix before the symbol name is used then
173 /// return linkage name after skipping this special LLVM prefix.
getRealLinkageName(StringRef LinkageName)174 static StringRef getRealLinkageName(StringRef LinkageName) {
175 char One = '\1';
176 if (LinkageName.startswith(StringRef(&One, 1)))
177 return LinkageName.substr(1);
178 return LinkageName;
179 }
180
181 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
182 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
183 /// If there are global variables in this scope then create and insert
184 /// DIEs for these variables.
updateSubprogramScopeDIE(CompileUnit * SPCU,const MDNode * SPNode)185 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
186 const MDNode *SPNode) {
187 DIE *SPDie = SPCU->getDIE(SPNode);
188
189 assert(SPDie && "Unable to find subprogram DIE!");
190 DISubprogram SP(SPNode);
191
192 DISubprogram SPDecl = SP.getFunctionDeclaration();
193 if (SPDecl.isSubprogram())
194 // Refer function declaration directly.
195 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
196 SPCU->getOrCreateSubprogramDIE(SPDecl));
197 else {
198 // There is not any need to generate specification DIE for a function
199 // defined at compile unit level. If a function is defined inside another
200 // function then gdb prefers the definition at top level and but does not
201 // expect specification DIE in parent function. So avoid creating
202 // specification DIE for a function defined inside a function.
203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
204 !SP.getContext().isFile() &&
205 !isSubprogramContext(SP.getContext())) {
206 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
207
208 // Add arguments.
209 DICompositeType SPTy = SP.getType();
210 DIArray Args = SPTy.getTypeArray();
211 unsigned SPTag = SPTy.getTag();
212 if (SPTag == dwarf::DW_TAG_subroutine_type)
213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
215 DIType ATy = DIType(DIType(Args.getElement(i)));
216 SPCU->addType(Arg, ATy);
217 if (ATy.isArtificial())
218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
219 SPDie->addChild(Arg);
220 }
221 DIE *SPDeclDie = SPDie;
222 SPDie = new DIE(dwarf::DW_TAG_subprogram);
223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
224 SPDeclDie);
225 SPCU->addDie(SPDie);
226 }
227 }
228 // Pick up abstract subprogram DIE.
229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
230 SPDie = new DIE(dwarf::DW_TAG_subprogram);
231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
232 dwarf::DW_FORM_ref4, AbsSPDIE);
233 SPCU->addDie(SPDie);
234 }
235
236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
241 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
243
244 return SPDie;
245 }
246
247 /// constructLexicalScope - Construct new DW_TAG_lexical_block
248 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
constructLexicalScopeDIE(CompileUnit * TheCU,LexicalScope * Scope)249 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
250 LexicalScope *Scope) {
251
252 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
253 if (Scope->isAbstractScope())
254 return ScopeDIE;
255
256 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
257 if (Ranges.empty())
258 return 0;
259
260 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
261 if (Ranges.size() > 1) {
262 // .debug_range section has not been laid out yet. Emit offset in
263 // .debug_range as a uint, size 4, for now. emitDIE will handle
264 // DW_AT_ranges appropriately.
265 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
266 DebugRangeSymbols.size()
267 * Asm->getTargetData().getPointerSize());
268 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
269 RE = Ranges.end(); RI != RE; ++RI) {
270 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
271 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
272 }
273 DebugRangeSymbols.push_back(NULL);
274 DebugRangeSymbols.push_back(NULL);
275 return ScopeDIE;
276 }
277
278 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
279 const MCSymbol *End = getLabelAfterInsn(RI->second);
280
281 if (End == 0) return 0;
282
283 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
284 assert(End->isDefined() && "Invalid end label for an inlined scope!");
285
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
287 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
288
289 return ScopeDIE;
290 }
291
292 /// constructInlinedScopeDIE - This scope represents inlined body of
293 /// a function. Construct DIE to represent this concrete inlined copy
294 /// of the function.
constructInlinedScopeDIE(CompileUnit * TheCU,LexicalScope * Scope)295 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
296 LexicalScope *Scope) {
297
298 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
299 assert (Ranges.empty() == false
300 && "LexicalScope does not have instruction markers!");
301
302 if (!Scope->getScopeNode())
303 return NULL;
304 DIScope DS(Scope->getScopeNode());
305 DISubprogram InlinedSP = getDISubprogram(DS);
306 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
307 if (!OriginDIE) {
308 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
309 return NULL;
310 }
311
312 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
313 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
314 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
315
316 if (StartLabel == 0 || EndLabel == 0) {
317 assert (0 && "Unexpected Start and End labels for a inlined scope!");
318 return 0;
319 }
320 assert(StartLabel->isDefined() &&
321 "Invalid starting label for an inlined scope!");
322 assert(EndLabel->isDefined() &&
323 "Invalid end label for an inlined scope!");
324
325 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
326 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
327 dwarf::DW_FORM_ref4, OriginDIE);
328
329 if (Ranges.size() > 1) {
330 // .debug_range section has not been laid out yet. Emit offset in
331 // .debug_range as a uint, size 4, for now. emitDIE will handle
332 // DW_AT_ranges appropriately.
333 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
334 DebugRangeSymbols.size()
335 * Asm->getTargetData().getPointerSize());
336 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
337 RE = Ranges.end(); RI != RE; ++RI) {
338 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
339 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
340 }
341 DebugRangeSymbols.push_back(NULL);
342 DebugRangeSymbols.push_back(NULL);
343 } else {
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
345 StartLabel);
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
347 EndLabel);
348 }
349
350 InlinedSubprogramDIEs.insert(OriginDIE);
351
352 // Track the start label for this inlined function.
353 //.debug_inlined section specification does not clearly state how
354 // to emit inlined scope that is split into multiple instruction ranges.
355 // For now, use first instruction range and emit low_pc/high_pc pair and
356 // corresponding .debug_inlined section entry for this pair.
357 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
358 I = InlineInfo.find(InlinedSP);
359
360 if (I == InlineInfo.end()) {
361 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
362 ScopeDIE));
363 InlinedSPNodes.push_back(InlinedSP);
364 } else
365 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
366
367 DILocation DL(Scope->getInlinedAt());
368 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
370
371 return ScopeDIE;
372 }
373
374 /// constructScopeDIE - Construct a DIE for this scope.
constructScopeDIE(CompileUnit * TheCU,LexicalScope * Scope)375 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
376 if (!Scope || !Scope->getScopeNode())
377 return NULL;
378
379 SmallVector <DIE *, 8> Children;
380
381 // Collect arguments for current function.
382 if (LScopes.isCurrentFunctionScope(Scope))
383 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
384 if (DbgVariable *ArgDV = CurrentFnArguments[i])
385 if (DIE *Arg =
386 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
387 Children.push_back(Arg);
388
389 // Collect lexical scope children first.
390 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
391 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
392 if (DIE *Variable =
393 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
394 Children.push_back(Variable);
395 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
396 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
397 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
398 Children.push_back(Nested);
399 DIScope DS(Scope->getScopeNode());
400 DIE *ScopeDIE = NULL;
401 if (Scope->getInlinedAt())
402 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
403 else if (DS.isSubprogram()) {
404 ProcessedSPNodes.insert(DS);
405 if (Scope->isAbstractScope()) {
406 ScopeDIE = TheCU->getDIE(DS);
407 // Note down abstract DIE.
408 if (ScopeDIE)
409 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
410 }
411 else
412 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
413 }
414 else {
415 // There is no need to emit empty lexical block DIE.
416 if (Children.empty())
417 return NULL;
418 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
419 }
420
421 if (!ScopeDIE) return NULL;
422
423 // Add children
424 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
425 E = Children.end(); I != E; ++I)
426 ScopeDIE->addChild(*I);
427
428 if (DS.isSubprogram())
429 TheCU->addPubTypes(DISubprogram(DS));
430
431 return ScopeDIE;
432 }
433
434 /// GetOrCreateSourceID - Look up the source id with the given directory and
435 /// source file names. If none currently exists, create a new id and insert it
436 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
437 /// maps as well.
438
GetOrCreateSourceID(StringRef FileName,StringRef DirName)439 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
440 StringRef DirName) {
441 // If FE did not provide a file name, then assume stdin.
442 if (FileName.empty())
443 return GetOrCreateSourceID("<stdin>", StringRef());
444
445 // MCStream expects full path name as filename.
446 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
447 SmallString<128> FullPathName = DirName;
448 sys::path::append(FullPathName, FileName);
449 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
450 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
451 }
452
453 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
454 if (Entry.getValue())
455 return Entry.getValue();
456
457 unsigned SrcId = SourceIdMap.size();
458 Entry.setValue(SrcId);
459
460 // Print out a .file directive to specify files for .loc directives.
461 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
462
463 return SrcId;
464 }
465
466 /// constructCompileUnit - Create new CompileUnit for the given
467 /// metadata node with tag DW_TAG_compile_unit.
constructCompileUnit(const MDNode * N)468 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
469 DICompileUnit DIUnit(N);
470 StringRef FN = DIUnit.getFilename();
471 StringRef Dir = DIUnit.getDirectory();
472 unsigned ID = GetOrCreateSourceID(FN, Dir);
473
474 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
475 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
476 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
477 DIUnit.getProducer());
478 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
479 DIUnit.getLanguage());
480 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
481 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
482 // simplifies debug range entries.
483 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
484 // DW_AT_stmt_list is a offset of line number information for this
485 // compile unit in debug_line section.
486 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
487 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
488 Asm->GetTempSymbol("section_line"));
489 else
490 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
491
492 if (!Dir.empty())
493 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
494 if (DIUnit.isOptimized())
495 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
496
497 StringRef Flags = DIUnit.getFlags();
498 if (!Flags.empty())
499 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
500 Flags);
501
502 unsigned RVer = DIUnit.getRunTimeVersion();
503 if (RVer)
504 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
505 dwarf::DW_FORM_data1, RVer);
506
507 if (!FirstCU)
508 FirstCU = NewCU;
509 CUMap.insert(std::make_pair(N, NewCU));
510 return NewCU;
511 }
512
513 /// construct SubprogramDIE - Construct subprogram DIE.
constructSubprogramDIE(CompileUnit * TheCU,const MDNode * N)514 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
515 const MDNode *N) {
516 DISubprogram SP(N);
517 if (!SP.isDefinition())
518 // This is a method declaration which will be handled while constructing
519 // class type.
520 return;
521
522 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
523
524 // Add to map.
525 TheCU->insertDIE(N, SubprogramDie);
526
527 // Add to context owner.
528 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
529
530 // Expose as global.
531 TheCU->addGlobal(SP.getName(), SubprogramDie);
532
533 SPMap[N] = TheCU;
534 return;
535 }
536
537 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
538 /// as llvm.dbg.enum and llvm.dbg.ty
collectInfoFromNamedMDNodes(Module * M)539 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
540 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
541 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
542 const MDNode *N = NMD->getOperand(i);
543 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
544 constructSubprogramDIE(CU, N);
545 }
546
547 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
548 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
549 const MDNode *N = NMD->getOperand(i);
550 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
551 CU->createGlobalVariableDIE(N);
552 }
553
554 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
555 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
556 DIType Ty(NMD->getOperand(i));
557 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
558 CU->getOrCreateTypeDIE(Ty);
559 }
560
561 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
562 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
563 DIType Ty(NMD->getOperand(i));
564 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
565 CU->getOrCreateTypeDIE(Ty);
566 }
567 }
568
569 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
570 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
collectLegacyDebugInfo(Module * M)571 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
572 DebugInfoFinder DbgFinder;
573 DbgFinder.processModule(*M);
574
575 bool HasDebugInfo = false;
576 // Scan all the compile-units to see if there are any marked as the main
577 // unit. If not, we do not generate debug info.
578 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
579 E = DbgFinder.compile_unit_end(); I != E; ++I) {
580 if (DICompileUnit(*I).isMain()) {
581 HasDebugInfo = true;
582 break;
583 }
584 }
585 if (!HasDebugInfo) return false;
586
587 // Create all the compile unit DIEs.
588 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
589 E = DbgFinder.compile_unit_end(); I != E; ++I)
590 constructCompileUnit(*I);
591
592 // Create DIEs for each global variable.
593 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
594 E = DbgFinder.global_variable_end(); I != E; ++I) {
595 const MDNode *N = *I;
596 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
597 CU->createGlobalVariableDIE(N);
598 }
599
600 // Create DIEs for each subprogram.
601 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
602 E = DbgFinder.subprogram_end(); I != E; ++I) {
603 const MDNode *N = *I;
604 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
605 constructSubprogramDIE(CU, N);
606 }
607
608 return HasDebugInfo;
609 }
610
611 /// beginModule - Emit all Dwarf sections that should come prior to the
612 /// content. Create global DIEs and emit initial debug info sections.
613 /// This is invoked by the target AsmPrinter.
beginModule(Module * M)614 void DwarfDebug::beginModule(Module *M) {
615 if (DisableDebugInfoPrinting)
616 return;
617
618 // If module has named metadata anchors then use them, otherwise scan the
619 // module using debug info finder to collect debug info.
620 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
621 if (CU_Nodes) {
622 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
623 DICompileUnit CUNode(CU_Nodes->getOperand(i));
624 CompileUnit *CU = constructCompileUnit(CUNode);
625 DIArray GVs = CUNode.getGlobalVariables();
626 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
627 CU->createGlobalVariableDIE(GVs.getElement(i));
628 DIArray SPs = CUNode.getSubprograms();
629 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
630 constructSubprogramDIE(CU, SPs.getElement(i));
631 DIArray EnumTypes = CUNode.getEnumTypes();
632 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
633 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
634 DIArray RetainedTypes = CUNode.getRetainedTypes();
635 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
636 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
637 }
638 } else if (!collectLegacyDebugInfo(M))
639 return;
640
641 collectInfoFromNamedMDNodes(M);
642
643 // Tell MMI that we have debug info.
644 MMI->setDebugInfoAvailability(true);
645
646 // Emit initial sections.
647 EmitSectionLabels();
648
649 // Prime section data.
650 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
651 }
652
653 /// endModule - Emit all Dwarf sections that should come after the content.
654 ///
endModule()655 void DwarfDebug::endModule() {
656 if (!FirstCU) return;
657 const Module *M = MMI->getModule();
658 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
659
660 // Collect info for variables that were optimized out.
661 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
662 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
663 DICompileUnit TheCU(CU_Nodes->getOperand(i));
664 DIArray Subprograms = TheCU.getSubprograms();
665 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
666 DISubprogram SP(Subprograms.getElement(i));
667 if (ProcessedSPNodes.count(SP) != 0) continue;
668 if (!SP.Verify()) continue;
669 if (!SP.isDefinition()) continue;
670 DIArray Variables = SP.getVariables();
671 if (Variables.getNumElements() == 0) continue;
672
673 LexicalScope *Scope =
674 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
675 DeadFnScopeMap[SP] = Scope;
676
677 // Construct subprogram DIE and add variables DIEs.
678 CompileUnit *SPCU = CUMap.lookup(TheCU);
679 assert (SPCU && "Unable to find Compile Unit!");
680 constructSubprogramDIE(SPCU, SP);
681 DIE *ScopeDIE = SPCU->getDIE(SP);
682 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
683 DIVariable DV(Variables.getElement(vi));
684 if (!DV.Verify()) continue;
685 DbgVariable *NewVar = new DbgVariable(DV, NULL);
686 if (DIE *VariableDIE =
687 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
688 ScopeDIE->addChild(VariableDIE);
689 }
690 }
691 }
692 }
693
694 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
695 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
696 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
697 DIE *ISP = *AI;
698 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
699 }
700
701 // Emit DW_AT_containing_type attribute to connect types with their
702 // vtable holding type.
703 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
704 CUE = CUMap.end(); CUI != CUE; ++CUI) {
705 CompileUnit *TheCU = CUI->second;
706 TheCU->constructContainingTypeDIEs();
707 }
708
709 // Standard sections final addresses.
710 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
711 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
712 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
713 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
714
715 // End text sections.
716 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
717 Asm->OutStreamer.SwitchSection(SectionMap[i]);
718 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
719 }
720
721 // Compute DIE offsets and sizes.
722 computeSizeAndOffsets();
723
724 // Emit all the DIEs into a debug info section
725 emitDebugInfo();
726
727 // Corresponding abbreviations into a abbrev section.
728 emitAbbreviations();
729
730 // Emit info into a debug pubnames section.
731 emitDebugPubNames();
732
733 // Emit info into a debug pubtypes section.
734 emitDebugPubTypes();
735
736 // Emit info into a debug loc section.
737 emitDebugLoc();
738
739 // Emit info into a debug aranges section.
740 EmitDebugARanges();
741
742 // Emit info into a debug ranges section.
743 emitDebugRanges();
744
745 // Emit info into a debug macinfo section.
746 emitDebugMacInfo();
747
748 // Emit inline info.
749 emitDebugInlineInfo();
750
751 // Emit info into a debug str section.
752 emitDebugStr();
753
754 // clean up.
755 DeleteContainerSeconds(DeadFnScopeMap);
756 SPMap.clear();
757 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
758 E = CUMap.end(); I != E; ++I)
759 delete I->second;
760 FirstCU = NULL; // Reset for the next Module, if any.
761 }
762
763 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
findAbstractVariable(DIVariable & DV,DebugLoc ScopeLoc)764 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
765 DebugLoc ScopeLoc) {
766 LLVMContext &Ctx = DV->getContext();
767 // More then one inlined variable corresponds to one abstract variable.
768 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
769 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
770 if (AbsDbgVariable)
771 return AbsDbgVariable;
772
773 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
774 if (!Scope)
775 return NULL;
776
777 AbsDbgVariable = new DbgVariable(Var, NULL);
778 addScopeVariable(Scope, AbsDbgVariable);
779 AbstractVariables[Var] = AbsDbgVariable;
780 return AbsDbgVariable;
781 }
782
783 /// addCurrentFnArgument - If Var is a current function argument then add
784 /// it to CurrentFnArguments list.
addCurrentFnArgument(const MachineFunction * MF,DbgVariable * Var,LexicalScope * Scope)785 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
786 DbgVariable *Var, LexicalScope *Scope) {
787 if (!LScopes.isCurrentFunctionScope(Scope))
788 return false;
789 DIVariable DV = Var->getVariable();
790 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
791 return false;
792 unsigned ArgNo = DV.getArgNumber();
793 if (ArgNo == 0)
794 return false;
795
796 size_t Size = CurrentFnArguments.size();
797 if (Size == 0)
798 CurrentFnArguments.resize(MF->getFunction()->arg_size());
799 // llvm::Function argument size is not good indicator of how many
800 // arguments does the function have at source level.
801 if (ArgNo > Size)
802 CurrentFnArguments.resize(ArgNo * 2);
803 CurrentFnArguments[ArgNo - 1] = Var;
804 return true;
805 }
806
807 /// collectVariableInfoFromMMITable - Collect variable information from
808 /// side table maintained by MMI.
809 void
collectVariableInfoFromMMITable(const MachineFunction * MF,SmallPtrSet<const MDNode *,16> & Processed)810 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
811 SmallPtrSet<const MDNode *, 16> &Processed) {
812 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
813 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
814 VE = VMap.end(); VI != VE; ++VI) {
815 const MDNode *Var = VI->first;
816 if (!Var) continue;
817 Processed.insert(Var);
818 DIVariable DV(Var);
819 const std::pair<unsigned, DebugLoc> &VP = VI->second;
820
821 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
822
823 // If variable scope is not found then skip this variable.
824 if (Scope == 0)
825 continue;
826
827 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
828 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
829 RegVar->setFrameIndex(VP.first);
830 if (!addCurrentFnArgument(MF, RegVar, Scope))
831 addScopeVariable(Scope, RegVar);
832 if (AbsDbgVariable)
833 AbsDbgVariable->setFrameIndex(VP.first);
834 }
835 }
836
837 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
838 /// DBG_VALUE instruction, is in a defined reg.
isDbgValueInDefinedReg(const MachineInstr * MI)839 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
840 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
841 return MI->getNumOperands() == 3 &&
842 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
843 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
844 }
845
846 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
847 /// at MI.
getDebugLocEntry(AsmPrinter * Asm,const MCSymbol * FLabel,const MCSymbol * SLabel,const MachineInstr * MI)848 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
849 const MCSymbol *FLabel,
850 const MCSymbol *SLabel,
851 const MachineInstr *MI) {
852 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
853
854 if (MI->getNumOperands() != 3) {
855 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
856 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
857 }
858 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
859 MachineLocation MLoc;
860 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
861 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
862 }
863 if (MI->getOperand(0).isImm())
864 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
865 if (MI->getOperand(0).isFPImm())
866 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
867 if (MI->getOperand(0).isCImm())
868 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
869
870 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
871 return DotDebugLocEntry();
872 }
873
874 /// collectVariableInfo - Find variables for each lexical scope.
875 void
collectVariableInfo(const MachineFunction * MF,SmallPtrSet<const MDNode *,16> & Processed)876 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
877 SmallPtrSet<const MDNode *, 16> &Processed) {
878
879 /// collection info from MMI table.
880 collectVariableInfoFromMMITable(MF, Processed);
881
882 for (SmallVectorImpl<const MDNode*>::const_iterator
883 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
884 ++UVI) {
885 const MDNode *Var = *UVI;
886 if (Processed.count(Var))
887 continue;
888
889 // History contains relevant DBG_VALUE instructions for Var and instructions
890 // clobbering it.
891 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
892 if (History.empty())
893 continue;
894 const MachineInstr *MInsn = History.front();
895
896 DIVariable DV(Var);
897 LexicalScope *Scope = NULL;
898 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
899 DISubprogram(DV.getContext()).describes(MF->getFunction()))
900 Scope = LScopes.getCurrentFunctionScope();
901 else {
902 if (DV.getVersion() <= LLVMDebugVersion9)
903 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
904 else {
905 if (MDNode *IA = DV.getInlinedAt())
906 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
907 else
908 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
909 }
910 }
911 // If variable scope is not found then skip this variable.
912 if (!Scope)
913 continue;
914
915 Processed.insert(DV);
916 assert(MInsn->isDebugValue() && "History must begin with debug value");
917 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
918 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
919 if (!addCurrentFnArgument(MF, RegVar, Scope))
920 addScopeVariable(Scope, RegVar);
921 if (AbsVar)
922 AbsVar->setMInsn(MInsn);
923
924 // Simple ranges that are fully coalesced.
925 if (History.size() <= 1 || (History.size() == 2 &&
926 MInsn->isIdenticalTo(History.back()))) {
927 RegVar->setMInsn(MInsn);
928 continue;
929 }
930
931 // handle multiple DBG_VALUE instructions describing one variable.
932 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
933
934 for (SmallVectorImpl<const MachineInstr*>::const_iterator
935 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
936 const MachineInstr *Begin = *HI;
937 assert(Begin->isDebugValue() && "Invalid History entry");
938
939 // Check if DBG_VALUE is truncating a range.
940 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
941 && !Begin->getOperand(0).getReg())
942 continue;
943
944 // Compute the range for a register location.
945 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
946 const MCSymbol *SLabel = 0;
947
948 if (HI + 1 == HE)
949 // If Begin is the last instruction in History then its value is valid
950 // until the end of the function.
951 SLabel = FunctionEndSym;
952 else {
953 const MachineInstr *End = HI[1];
954 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
955 << "\t" << *Begin << "\t" << *End << "\n");
956 if (End->isDebugValue())
957 SLabel = getLabelBeforeInsn(End);
958 else {
959 // End is a normal instruction clobbering the range.
960 SLabel = getLabelAfterInsn(End);
961 assert(SLabel && "Forgot label after clobber instruction");
962 ++HI;
963 }
964 }
965
966 // The value is valid until the next DBG_VALUE or clobber.
967 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
968 }
969 DotDebugLocEntries.push_back(DotDebugLocEntry());
970 }
971
972 // Collect info for variables that were optimized out.
973 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
974 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
975 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
976 DIVariable DV(Variables.getElement(i));
977 if (!DV || !DV.Verify() || !Processed.insert(DV))
978 continue;
979 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
980 addScopeVariable(Scope, new DbgVariable(DV, NULL));
981 }
982 }
983
984 /// getLabelBeforeInsn - Return Label preceding the instruction.
getLabelBeforeInsn(const MachineInstr * MI)985 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
986 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
987 assert(Label && "Didn't insert label before instruction");
988 return Label;
989 }
990
991 /// getLabelAfterInsn - Return Label immediately following the instruction.
getLabelAfterInsn(const MachineInstr * MI)992 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
993 return LabelsAfterInsn.lookup(MI);
994 }
995
996 /// beginInstruction - Process beginning of an instruction.
beginInstruction(const MachineInstr * MI)997 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
998 // Check if source location changes, but ignore DBG_VALUE locations.
999 if (!MI->isDebugValue()) {
1000 DebugLoc DL = MI->getDebugLoc();
1001 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1002 unsigned Flags = DWARF2_FLAG_IS_STMT;
1003 PrevInstLoc = DL;
1004 if (DL == PrologEndLoc) {
1005 Flags |= DWARF2_FLAG_PROLOGUE_END;
1006 PrologEndLoc = DebugLoc();
1007 }
1008 if (!DL.isUnknown()) {
1009 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1010 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1011 } else
1012 recordSourceLine(0, 0, 0, 0);
1013 }
1014 }
1015
1016 // Insert labels where requested.
1017 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1018 LabelsBeforeInsn.find(MI);
1019
1020 // No label needed.
1021 if (I == LabelsBeforeInsn.end())
1022 return;
1023
1024 // Label already assigned.
1025 if (I->second)
1026 return;
1027
1028 if (!PrevLabel) {
1029 PrevLabel = MMI->getContext().CreateTempSymbol();
1030 Asm->OutStreamer.EmitLabel(PrevLabel);
1031 }
1032 I->second = PrevLabel;
1033 }
1034
1035 /// endInstruction - Process end of an instruction.
endInstruction(const MachineInstr * MI)1036 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1037 // Don't create a new label after DBG_VALUE instructions.
1038 // They don't generate code.
1039 if (!MI->isDebugValue())
1040 PrevLabel = 0;
1041
1042 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1043 LabelsAfterInsn.find(MI);
1044
1045 // No label needed.
1046 if (I == LabelsAfterInsn.end())
1047 return;
1048
1049 // Label already assigned.
1050 if (I->second)
1051 return;
1052
1053 // We need a label after this instruction.
1054 if (!PrevLabel) {
1055 PrevLabel = MMI->getContext().CreateTempSymbol();
1056 Asm->OutStreamer.EmitLabel(PrevLabel);
1057 }
1058 I->second = PrevLabel;
1059 }
1060
1061 /// identifyScopeMarkers() -
1062 /// Each LexicalScope has first instruction and last instruction to mark
1063 /// beginning and end of a scope respectively. Create an inverse map that list
1064 /// scopes starts (and ends) with an instruction. One instruction may start (or
1065 /// end) multiple scopes. Ignore scopes that are not reachable.
identifyScopeMarkers()1066 void DwarfDebug::identifyScopeMarkers() {
1067 SmallVector<LexicalScope *, 4> WorkList;
1068 WorkList.push_back(LScopes.getCurrentFunctionScope());
1069 while (!WorkList.empty()) {
1070 LexicalScope *S = WorkList.pop_back_val();
1071
1072 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1073 if (!Children.empty())
1074 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1075 SE = Children.end(); SI != SE; ++SI)
1076 WorkList.push_back(*SI);
1077
1078 if (S->isAbstractScope())
1079 continue;
1080
1081 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1082 if (Ranges.empty())
1083 continue;
1084 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1085 RE = Ranges.end(); RI != RE; ++RI) {
1086 assert(RI->first && "InsnRange does not have first instruction!");
1087 assert(RI->second && "InsnRange does not have second instruction!");
1088 requestLabelBeforeInsn(RI->first);
1089 requestLabelAfterInsn(RI->second);
1090 }
1091 }
1092 }
1093
1094 /// getScopeNode - Get MDNode for DebugLoc's scope.
getScopeNode(DebugLoc DL,const LLVMContext & Ctx)1095 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1096 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1097 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1098 return DL.getScope(Ctx);
1099 }
1100
1101 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1102 /// line number info for the function.
getFnDebugLoc(DebugLoc DL,const LLVMContext & Ctx)1103 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1104 const MDNode *Scope = getScopeNode(DL, Ctx);
1105 DISubprogram SP = getDISubprogram(Scope);
1106 if (SP.Verify())
1107 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1108 return DebugLoc();
1109 }
1110
1111 /// beginFunction - Gather pre-function debug information. Assumes being
1112 /// emitted immediately after the function entry point.
beginFunction(const MachineFunction * MF)1113 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1114 if (!MMI->hasDebugInfo()) return;
1115 LScopes.initialize(*MF);
1116 if (LScopes.empty()) return;
1117 identifyScopeMarkers();
1118
1119 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1120 Asm->getFunctionNumber());
1121 // Assumes in correct section after the entry point.
1122 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1123
1124 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1125
1126 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1127 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1128 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1129
1130 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1131 I != E; ++I) {
1132 bool AtBlockEntry = true;
1133 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1134 II != IE; ++II) {
1135 const MachineInstr *MI = II;
1136
1137 if (MI->isDebugValue()) {
1138 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1139
1140 // Keep track of user variables.
1141 const MDNode *Var =
1142 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1143
1144 // Variable is in a register, we need to check for clobbers.
1145 if (isDbgValueInDefinedReg(MI))
1146 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1147
1148 // Check the history of this variable.
1149 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1150 if (History.empty()) {
1151 UserVariables.push_back(Var);
1152 // The first mention of a function argument gets the FunctionBeginSym
1153 // label, so arguments are visible when breaking at function entry.
1154 DIVariable DV(Var);
1155 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1156 DISubprogram(getDISubprogram(DV.getContext()))
1157 .describes(MF->getFunction()))
1158 LabelsBeforeInsn[MI] = FunctionBeginSym;
1159 } else {
1160 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1161 const MachineInstr *Prev = History.back();
1162 if (Prev->isDebugValue()) {
1163 // Coalesce identical entries at the end of History.
1164 if (History.size() >= 2 &&
1165 Prev->isIdenticalTo(History[History.size() - 2])) {
1166 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1167 << "\t" << *Prev
1168 << "\t" << *History[History.size() - 2] << "\n");
1169 History.pop_back();
1170 }
1171
1172 // Terminate old register assignments that don't reach MI;
1173 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1174 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1175 isDbgValueInDefinedReg(Prev)) {
1176 // Previous register assignment needs to terminate at the end of
1177 // its basic block.
1178 MachineBasicBlock::const_iterator LastMI =
1179 PrevMBB->getLastNonDebugInstr();
1180 if (LastMI == PrevMBB->end()) {
1181 // Drop DBG_VALUE for empty range.
1182 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1183 << "\t" << *Prev << "\n");
1184 History.pop_back();
1185 }
1186 else {
1187 // Terminate after LastMI.
1188 History.push_back(LastMI);
1189 }
1190 }
1191 }
1192 }
1193 History.push_back(MI);
1194 } else {
1195 // Not a DBG_VALUE instruction.
1196 if (!MI->isLabel())
1197 AtBlockEntry = false;
1198
1199 // First known non DBG_VALUE location marks beginning of function
1200 // body.
1201 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1202 PrologEndLoc = MI->getDebugLoc();
1203
1204 // Check if the instruction clobbers any registers with debug vars.
1205 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1206 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1207 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1208 continue;
1209 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1210 unsigned Reg = *AI; ++AI) {
1211 const MDNode *Var = LiveUserVar[Reg];
1212 if (!Var)
1213 continue;
1214 // Reg is now clobbered.
1215 LiveUserVar[Reg] = 0;
1216
1217 // Was MD last defined by a DBG_VALUE referring to Reg?
1218 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1219 if (HistI == DbgValues.end())
1220 continue;
1221 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1222 if (History.empty())
1223 continue;
1224 const MachineInstr *Prev = History.back();
1225 // Sanity-check: Register assignments are terminated at the end of
1226 // their block.
1227 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1228 continue;
1229 // Is the variable still in Reg?
1230 if (!isDbgValueInDefinedReg(Prev) ||
1231 Prev->getOperand(0).getReg() != Reg)
1232 continue;
1233 // Var is clobbered. Make sure the next instruction gets a label.
1234 History.push_back(MI);
1235 }
1236 }
1237 }
1238 }
1239 }
1240
1241 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1242 I != E; ++I) {
1243 SmallVectorImpl<const MachineInstr*> &History = I->second;
1244 if (History.empty())
1245 continue;
1246
1247 // Make sure the final register assignments are terminated.
1248 const MachineInstr *Prev = History.back();
1249 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1250 const MachineBasicBlock *PrevMBB = Prev->getParent();
1251 MachineBasicBlock::const_iterator LastMI =
1252 PrevMBB->getLastNonDebugInstr();
1253 if (LastMI == PrevMBB->end())
1254 // Drop DBG_VALUE for empty range.
1255 History.pop_back();
1256 else {
1257 // Terminate after LastMI.
1258 History.push_back(LastMI);
1259 }
1260 }
1261 // Request labels for the full history.
1262 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1263 const MachineInstr *MI = History[i];
1264 if (MI->isDebugValue())
1265 requestLabelBeforeInsn(MI);
1266 else
1267 requestLabelAfterInsn(MI);
1268 }
1269 }
1270
1271 PrevInstLoc = DebugLoc();
1272 PrevLabel = FunctionBeginSym;
1273
1274 // Record beginning of function.
1275 if (!PrologEndLoc.isUnknown()) {
1276 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1277 MF->getFunction()->getContext());
1278 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1279 FnStartDL.getScope(MF->getFunction()->getContext()),
1280 DWARF2_FLAG_IS_STMT);
1281 }
1282 }
1283
addScopeVariable(LexicalScope * LS,DbgVariable * Var)1284 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1285 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1286 ScopeVariables[LS].push_back(Var);
1287 // Vars.push_back(Var);
1288 }
1289
1290 /// endFunction - Gather and emit post-function debug information.
1291 ///
endFunction(const MachineFunction * MF)1292 void DwarfDebug::endFunction(const MachineFunction *MF) {
1293 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1294
1295 // Define end label for subprogram.
1296 FunctionEndSym = Asm->GetTempSymbol("func_end",
1297 Asm->getFunctionNumber());
1298 // Assumes in correct section after the entry point.
1299 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1300
1301 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1302 collectVariableInfo(MF, ProcessedVars);
1303
1304 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1305 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1306 assert (TheCU && "Unable to find compile unit!");
1307
1308 // Construct abstract scopes.
1309 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1310 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1311 LexicalScope *AScope = AList[i];
1312 DISubprogram SP(AScope->getScopeNode());
1313 if (SP.Verify()) {
1314 // Collect info for variables that were optimized out.
1315 DIArray Variables = SP.getVariables();
1316 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1317 DIVariable DV(Variables.getElement(i));
1318 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1319 continue;
1320 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1321 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1322 }
1323 }
1324 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1325 constructScopeDIE(TheCU, AScope);
1326 }
1327
1328 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1329
1330 if (!DisableFramePointerElim(*MF))
1331 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1332 dwarf::DW_FORM_flag, 1);
1333
1334 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1335 MMI->getFrameMoves()));
1336
1337 // Clear debug info
1338 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1339 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1340 DeleteContainerPointers(I->second);
1341 ScopeVariables.clear();
1342 DeleteContainerPointers(CurrentFnArguments);
1343 UserVariables.clear();
1344 DbgValues.clear();
1345 AbstractVariables.clear();
1346 LabelsBeforeInsn.clear();
1347 LabelsAfterInsn.clear();
1348 PrevLabel = NULL;
1349 }
1350
1351 /// recordSourceLine - Register a source line with debug info. Returns the
1352 /// unique label that was emitted and which provides correspondence to
1353 /// the source line list.
recordSourceLine(unsigned Line,unsigned Col,const MDNode * S,unsigned Flags)1354 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1355 unsigned Flags) {
1356 StringRef Fn;
1357 StringRef Dir;
1358 unsigned Src = 1;
1359 if (S) {
1360 DIDescriptor Scope(S);
1361
1362 if (Scope.isCompileUnit()) {
1363 DICompileUnit CU(S);
1364 Fn = CU.getFilename();
1365 Dir = CU.getDirectory();
1366 } else if (Scope.isFile()) {
1367 DIFile F(S);
1368 Fn = F.getFilename();
1369 Dir = F.getDirectory();
1370 } else if (Scope.isSubprogram()) {
1371 DISubprogram SP(S);
1372 Fn = SP.getFilename();
1373 Dir = SP.getDirectory();
1374 } else if (Scope.isLexicalBlockFile()) {
1375 DILexicalBlockFile DBF(S);
1376 Fn = DBF.getFilename();
1377 Dir = DBF.getDirectory();
1378 } else if (Scope.isLexicalBlock()) {
1379 DILexicalBlock DB(S);
1380 Fn = DB.getFilename();
1381 Dir = DB.getDirectory();
1382 } else
1383 assert(0 && "Unexpected scope info");
1384
1385 Src = GetOrCreateSourceID(Fn, Dir);
1386 }
1387 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1388 }
1389
1390 //===----------------------------------------------------------------------===//
1391 // Emit Methods
1392 //===----------------------------------------------------------------------===//
1393
1394 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1395 ///
1396 unsigned
computeSizeAndOffset(DIE * Die,unsigned Offset,bool Last)1397 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1398 // Get the children.
1399 const std::vector<DIE *> &Children = Die->getChildren();
1400
1401 // If not last sibling and has children then add sibling offset attribute.
1402 if (!Last && !Children.empty())
1403 Die->addSiblingOffset(DIEValueAllocator);
1404
1405 // Record the abbreviation.
1406 assignAbbrevNumber(Die->getAbbrev());
1407
1408 // Get the abbreviation for this DIE.
1409 unsigned AbbrevNumber = Die->getAbbrevNumber();
1410 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1411
1412 // Set DIE offset
1413 Die->setOffset(Offset);
1414
1415 // Start the size with the size of abbreviation code.
1416 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1417
1418 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1419 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1420
1421 // Size the DIE attribute values.
1422 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1423 // Size attribute value.
1424 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1425
1426 // Size the DIE children if any.
1427 if (!Children.empty()) {
1428 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1429 "Children flag not set");
1430
1431 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1432 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1433
1434 // End of children marker.
1435 Offset += sizeof(int8_t);
1436 }
1437
1438 Die->setSize(Offset - Die->getOffset());
1439 return Offset;
1440 }
1441
1442 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1443 ///
computeSizeAndOffsets()1444 void DwarfDebug::computeSizeAndOffsets() {
1445 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1446 E = CUMap.end(); I != E; ++I) {
1447 // Compute size of compile unit header.
1448 unsigned Offset =
1449 sizeof(int32_t) + // Length of Compilation Unit Info
1450 sizeof(int16_t) + // DWARF version number
1451 sizeof(int32_t) + // Offset Into Abbrev. Section
1452 sizeof(int8_t); // Pointer Size (in bytes)
1453 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1454 }
1455 }
1456
1457 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1458 /// temporary label to it if SymbolStem is specified.
EmitSectionSym(AsmPrinter * Asm,const MCSection * Section,const char * SymbolStem=0)1459 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1460 const char *SymbolStem = 0) {
1461 Asm->OutStreamer.SwitchSection(Section);
1462 if (!SymbolStem) return 0;
1463
1464 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1465 Asm->OutStreamer.EmitLabel(TmpSym);
1466 return TmpSym;
1467 }
1468
1469 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1470 /// the start of each one.
EmitSectionLabels()1471 void DwarfDebug::EmitSectionLabels() {
1472 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1473
1474 // Dwarf sections base addresses.
1475 DwarfInfoSectionSym =
1476 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1477 DwarfAbbrevSectionSym =
1478 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1479 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1480
1481 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1482 EmitSectionSym(Asm, MacroInfo);
1483
1484 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1485 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1486 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1487 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1488 DwarfStrSectionSym =
1489 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1490 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1491 "debug_range");
1492
1493 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1494 "section_debug_loc");
1495
1496 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1497 EmitSectionSym(Asm, TLOF.getDataSection());
1498 }
1499
1500 /// emitDIE - Recursively emits a debug information entry.
1501 ///
emitDIE(DIE * Die)1502 void DwarfDebug::emitDIE(DIE *Die) {
1503 // Get the abbreviation for this DIE.
1504 unsigned AbbrevNumber = Die->getAbbrevNumber();
1505 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1506
1507 // Emit the code (index) for the abbreviation.
1508 if (Asm->isVerbose())
1509 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1510 Twine::utohexstr(Die->getOffset()) + ":0x" +
1511 Twine::utohexstr(Die->getSize()) + " " +
1512 dwarf::TagString(Abbrev->getTag()));
1513 Asm->EmitULEB128(AbbrevNumber);
1514
1515 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1516 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1517
1518 // Emit the DIE attribute values.
1519 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1520 unsigned Attr = AbbrevData[i].getAttribute();
1521 unsigned Form = AbbrevData[i].getForm();
1522 assert(Form && "Too many attributes for DIE (check abbreviation)");
1523
1524 if (Asm->isVerbose())
1525 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1526
1527 switch (Attr) {
1528 case dwarf::DW_AT_sibling:
1529 Asm->EmitInt32(Die->getSiblingOffset());
1530 break;
1531 case dwarf::DW_AT_abstract_origin: {
1532 DIEEntry *E = cast<DIEEntry>(Values[i]);
1533 DIE *Origin = E->getEntry();
1534 unsigned Addr = Origin->getOffset();
1535 Asm->EmitInt32(Addr);
1536 break;
1537 }
1538 case dwarf::DW_AT_ranges: {
1539 // DW_AT_range Value encodes offset in debug_range section.
1540 DIEInteger *V = cast<DIEInteger>(Values[i]);
1541
1542 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1543 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1544 V->getValue(),
1545 4);
1546 } else {
1547 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1548 V->getValue(),
1549 DwarfDebugRangeSectionSym,
1550 4);
1551 }
1552 break;
1553 }
1554 case dwarf::DW_AT_location: {
1555 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1556 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1557 else
1558 Values[i]->EmitValue(Asm, Form);
1559 break;
1560 }
1561 case dwarf::DW_AT_accessibility: {
1562 if (Asm->isVerbose()) {
1563 DIEInteger *V = cast<DIEInteger>(Values[i]);
1564 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1565 }
1566 Values[i]->EmitValue(Asm, Form);
1567 break;
1568 }
1569 default:
1570 // Emit an attribute using the defined form.
1571 Values[i]->EmitValue(Asm, Form);
1572 break;
1573 }
1574 }
1575
1576 // Emit the DIE children if any.
1577 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1578 const std::vector<DIE *> &Children = Die->getChildren();
1579
1580 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1581 emitDIE(Children[j]);
1582
1583 if (Asm->isVerbose())
1584 Asm->OutStreamer.AddComment("End Of Children Mark");
1585 Asm->EmitInt8(0);
1586 }
1587 }
1588
1589 /// emitDebugInfo - Emit the debug info section.
1590 ///
emitDebugInfo()1591 void DwarfDebug::emitDebugInfo() {
1592 // Start debug info section.
1593 Asm->OutStreamer.SwitchSection(
1594 Asm->getObjFileLowering().getDwarfInfoSection());
1595 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1596 E = CUMap.end(); I != E; ++I) {
1597 CompileUnit *TheCU = I->second;
1598 DIE *Die = TheCU->getCUDie();
1599
1600 // Emit the compile units header.
1601 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1602 TheCU->getID()));
1603
1604 // Emit size of content not including length itself
1605 unsigned ContentSize = Die->getSize() +
1606 sizeof(int16_t) + // DWARF version number
1607 sizeof(int32_t) + // Offset Into Abbrev. Section
1608 sizeof(int8_t); // Pointer Size (in bytes)
1609
1610 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1611 Asm->EmitInt32(ContentSize);
1612 Asm->OutStreamer.AddComment("DWARF version number");
1613 Asm->EmitInt16(dwarf::DWARF_VERSION);
1614 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1615 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1616 DwarfAbbrevSectionSym);
1617 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1618 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1619
1620 emitDIE(Die);
1621 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1622 }
1623 }
1624
1625 /// emitAbbreviations - Emit the abbreviation section.
1626 ///
emitAbbreviations() const1627 void DwarfDebug::emitAbbreviations() const {
1628 // Check to see if it is worth the effort.
1629 if (!Abbreviations.empty()) {
1630 // Start the debug abbrev section.
1631 Asm->OutStreamer.SwitchSection(
1632 Asm->getObjFileLowering().getDwarfAbbrevSection());
1633
1634 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1635
1636 // For each abbrevation.
1637 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1638 // Get abbreviation data
1639 const DIEAbbrev *Abbrev = Abbreviations[i];
1640
1641 // Emit the abbrevations code (base 1 index.)
1642 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1643
1644 // Emit the abbreviations data.
1645 Abbrev->Emit(Asm);
1646 }
1647
1648 // Mark end of abbreviations.
1649 Asm->EmitULEB128(0, "EOM(3)");
1650
1651 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1652 }
1653 }
1654
1655 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1656 /// the line matrix.
1657 ///
emitEndOfLineMatrix(unsigned SectionEnd)1658 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1659 // Define last address of section.
1660 Asm->OutStreamer.AddComment("Extended Op");
1661 Asm->EmitInt8(0);
1662
1663 Asm->OutStreamer.AddComment("Op size");
1664 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1665 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1666 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1667
1668 Asm->OutStreamer.AddComment("Section end label");
1669
1670 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1671 Asm->getTargetData().getPointerSize(),
1672 0/*AddrSpace*/);
1673
1674 // Mark end of matrix.
1675 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1676 Asm->EmitInt8(0);
1677 Asm->EmitInt8(1);
1678 Asm->EmitInt8(1);
1679 }
1680
1681 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1682 ///
emitDebugPubNames()1683 void DwarfDebug::emitDebugPubNames() {
1684 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1685 E = CUMap.end(); I != E; ++I) {
1686 CompileUnit *TheCU = I->second;
1687 // Start the dwarf pubnames section.
1688 Asm->OutStreamer.SwitchSection(
1689 Asm->getObjFileLowering().getDwarfPubNamesSection());
1690
1691 Asm->OutStreamer.AddComment("Length of Public Names Info");
1692 Asm->EmitLabelDifference(
1693 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1694 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1695
1696 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1697 TheCU->getID()));
1698
1699 Asm->OutStreamer.AddComment("DWARF Version");
1700 Asm->EmitInt16(dwarf::DWARF_VERSION);
1701
1702 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1703 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1704 DwarfInfoSectionSym);
1705
1706 Asm->OutStreamer.AddComment("Compilation Unit Length");
1707 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1708 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1709 4);
1710
1711 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1712 for (StringMap<DIE*>::const_iterator
1713 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1714 const char *Name = GI->getKeyData();
1715 DIE *Entity = GI->second;
1716
1717 Asm->OutStreamer.AddComment("DIE offset");
1718 Asm->EmitInt32(Entity->getOffset());
1719
1720 if (Asm->isVerbose())
1721 Asm->OutStreamer.AddComment("External Name");
1722 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1723 }
1724
1725 Asm->OutStreamer.AddComment("End Mark");
1726 Asm->EmitInt32(0);
1727 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1728 TheCU->getID()));
1729 }
1730 }
1731
emitDebugPubTypes()1732 void DwarfDebug::emitDebugPubTypes() {
1733 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1734 E = CUMap.end(); I != E; ++I) {
1735 CompileUnit *TheCU = I->second;
1736 // Start the dwarf pubnames section.
1737 Asm->OutStreamer.SwitchSection(
1738 Asm->getObjFileLowering().getDwarfPubTypesSection());
1739 Asm->OutStreamer.AddComment("Length of Public Types Info");
1740 Asm->EmitLabelDifference(
1741 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1742 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1743
1744 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1745 TheCU->getID()));
1746
1747 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1748 Asm->EmitInt16(dwarf::DWARF_VERSION);
1749
1750 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1751 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1752 DwarfInfoSectionSym);
1753
1754 Asm->OutStreamer.AddComment("Compilation Unit Length");
1755 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1756 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1757 4);
1758
1759 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1760 for (StringMap<DIE*>::const_iterator
1761 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1762 const char *Name = GI->getKeyData();
1763 DIE *Entity = GI->second;
1764
1765 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1766 Asm->EmitInt32(Entity->getOffset());
1767
1768 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1769 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1770 }
1771
1772 Asm->OutStreamer.AddComment("End Mark");
1773 Asm->EmitInt32(0);
1774 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1775 TheCU->getID()));
1776 }
1777 }
1778
1779 /// emitDebugStr - Emit visible names into a debug str section.
1780 ///
emitDebugStr()1781 void DwarfDebug::emitDebugStr() {
1782 // Check to see if it is worth the effort.
1783 if (StringPool.empty()) return;
1784
1785 // Start the dwarf str section.
1786 Asm->OutStreamer.SwitchSection(
1787 Asm->getObjFileLowering().getDwarfStrSection());
1788
1789 // Get all of the string pool entries and put them in an array by their ID so
1790 // we can sort them.
1791 SmallVector<std::pair<unsigned,
1792 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1793
1794 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1795 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1796 Entries.push_back(std::make_pair(I->second.second, &*I));
1797
1798 array_pod_sort(Entries.begin(), Entries.end());
1799
1800 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1801 // Emit a label for reference from debug information entries.
1802 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1803
1804 // Emit the string itself.
1805 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1806 }
1807 }
1808
1809 /// emitDebugLoc - Emit visible names into a debug loc section.
1810 ///
emitDebugLoc()1811 void DwarfDebug::emitDebugLoc() {
1812 if (DotDebugLocEntries.empty())
1813 return;
1814
1815 for (SmallVector<DotDebugLocEntry, 4>::iterator
1816 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1817 I != E; ++I) {
1818 DotDebugLocEntry &Entry = *I;
1819 if (I + 1 != DotDebugLocEntries.end())
1820 Entry.Merge(I+1);
1821 }
1822
1823 // Start the dwarf loc section.
1824 Asm->OutStreamer.SwitchSection(
1825 Asm->getObjFileLowering().getDwarfLocSection());
1826 unsigned char Size = Asm->getTargetData().getPointerSize();
1827 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1828 unsigned index = 1;
1829 for (SmallVector<DotDebugLocEntry, 4>::iterator
1830 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1831 I != E; ++I, ++index) {
1832 DotDebugLocEntry &Entry = *I;
1833 if (Entry.isMerged()) continue;
1834 if (Entry.isEmpty()) {
1835 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1836 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1837 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1838 } else {
1839 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1840 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1841 DIVariable DV(Entry.Variable);
1842 Asm->OutStreamer.AddComment("Loc expr size");
1843 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1844 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1845 Asm->EmitLabelDifference(end, begin, 2);
1846 Asm->OutStreamer.EmitLabel(begin);
1847 if (Entry.isInt()) {
1848 DIBasicType BTy(DV.getType());
1849 if (BTy.Verify() &&
1850 (BTy.getEncoding() == dwarf::DW_ATE_signed
1851 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1852 Asm->OutStreamer.AddComment("DW_OP_consts");
1853 Asm->EmitInt8(dwarf::DW_OP_consts);
1854 Asm->EmitSLEB128(Entry.getInt());
1855 } else {
1856 Asm->OutStreamer.AddComment("DW_OP_constu");
1857 Asm->EmitInt8(dwarf::DW_OP_constu);
1858 Asm->EmitULEB128(Entry.getInt());
1859 }
1860 } else if (Entry.isLocation()) {
1861 if (!DV.hasComplexAddress())
1862 // Regular entry.
1863 Asm->EmitDwarfRegOp(Entry.Loc);
1864 else {
1865 // Complex address entry.
1866 unsigned N = DV.getNumAddrElements();
1867 unsigned i = 0;
1868 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1869 if (Entry.Loc.getOffset()) {
1870 i = 2;
1871 Asm->EmitDwarfRegOp(Entry.Loc);
1872 Asm->OutStreamer.AddComment("DW_OP_deref");
1873 Asm->EmitInt8(dwarf::DW_OP_deref);
1874 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1875 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1876 Asm->EmitSLEB128(DV.getAddrElement(1));
1877 } else {
1878 // If first address element is OpPlus then emit
1879 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1880 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1881 Asm->EmitDwarfRegOp(Loc);
1882 i = 2;
1883 }
1884 } else {
1885 Asm->EmitDwarfRegOp(Entry.Loc);
1886 }
1887
1888 // Emit remaining complex address elements.
1889 for (; i < N; ++i) {
1890 uint64_t Element = DV.getAddrElement(i);
1891 if (Element == DIBuilder::OpPlus) {
1892 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1893 Asm->EmitULEB128(DV.getAddrElement(++i));
1894 } else if (Element == DIBuilder::OpDeref)
1895 Asm->EmitInt8(dwarf::DW_OP_deref);
1896 else llvm_unreachable("unknown Opcode found in complex address");
1897 }
1898 }
1899 }
1900 // else ... ignore constant fp. There is not any good way to
1901 // to represent them here in dwarf.
1902 Asm->OutStreamer.EmitLabel(end);
1903 }
1904 }
1905 }
1906
1907 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1908 ///
EmitDebugARanges()1909 void DwarfDebug::EmitDebugARanges() {
1910 // Start the dwarf aranges section.
1911 Asm->OutStreamer.SwitchSection(
1912 Asm->getObjFileLowering().getDwarfARangesSection());
1913 }
1914
1915 /// emitDebugRanges - Emit visible names into a debug ranges section.
1916 ///
emitDebugRanges()1917 void DwarfDebug::emitDebugRanges() {
1918 // Start the dwarf ranges section.
1919 Asm->OutStreamer.SwitchSection(
1920 Asm->getObjFileLowering().getDwarfRangesSection());
1921 unsigned char Size = Asm->getTargetData().getPointerSize();
1922 for (SmallVector<const MCSymbol *, 8>::iterator
1923 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1924 I != E; ++I) {
1925 if (*I)
1926 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1927 else
1928 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1929 }
1930 }
1931
1932 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1933 ///
emitDebugMacInfo()1934 void DwarfDebug::emitDebugMacInfo() {
1935 if (const MCSection *LineInfo =
1936 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1937 // Start the dwarf macinfo section.
1938 Asm->OutStreamer.SwitchSection(LineInfo);
1939 }
1940 }
1941
1942 /// emitDebugInlineInfo - Emit inline info using following format.
1943 /// Section Header:
1944 /// 1. length of section
1945 /// 2. Dwarf version number
1946 /// 3. address size.
1947 ///
1948 /// Entries (one "entry" for each function that was inlined):
1949 ///
1950 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1951 /// otherwise offset into __debug_str for regular function name.
1952 /// 2. offset into __debug_str section for regular function name.
1953 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1954 /// instances for the function.
1955 ///
1956 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1957 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1958 /// __debug_info section, and the low_pc is the starting address for the
1959 /// inlining instance.
emitDebugInlineInfo()1960 void DwarfDebug::emitDebugInlineInfo() {
1961 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1962 return;
1963
1964 if (!FirstCU)
1965 return;
1966
1967 Asm->OutStreamer.SwitchSection(
1968 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1969
1970 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1971 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1972 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1973
1974 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1975
1976 Asm->OutStreamer.AddComment("Dwarf Version");
1977 Asm->EmitInt16(dwarf::DWARF_VERSION);
1978 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1979 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1980
1981 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
1982 E = InlinedSPNodes.end(); I != E; ++I) {
1983
1984 const MDNode *Node = *I;
1985 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
1986 = InlineInfo.find(Node);
1987 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
1988 DISubprogram SP(Node);
1989 StringRef LName = SP.getLinkageName();
1990 StringRef Name = SP.getName();
1991
1992 Asm->OutStreamer.AddComment("MIPS linkage name");
1993 if (LName.empty()) {
1994 Asm->OutStreamer.EmitBytes(Name, 0);
1995 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
1996 } else
1997 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
1998 DwarfStrSectionSym);
1999
2000 Asm->OutStreamer.AddComment("Function name");
2001 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2002 Asm->EmitULEB128(Labels.size(), "Inline count");
2003
2004 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2005 LE = Labels.end(); LI != LE; ++LI) {
2006 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2007 Asm->EmitInt32(LI->second->getOffset());
2008
2009 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2010 Asm->OutStreamer.EmitSymbolValue(LI->first,
2011 Asm->getTargetData().getPointerSize(),0);
2012 }
2013 }
2014
2015 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2016 }
2017