1 //===-- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp --*- C++ -*--===//
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 Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeViewDebug.h"
15 #include "llvm/ADT/TinyPtrVector.h"
16 #include "llvm/DebugInfo/CodeView/CodeView.h"
17 #include "llvm/DebugInfo/CodeView/FieldListRecordBuilder.h"
18 #include "llvm/DebugInfo/CodeView/Line.h"
19 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
20 #include "llvm/DebugInfo/CodeView/TypeDumper.h"
21 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
22 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCSectionCOFF.h"
25 #include "llvm/MC/MCSymbol.h"
26 #include "llvm/Support/COFF.h"
27 #include "llvm/Support/ScopedPrinter.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31 
32 using namespace llvm;
33 using namespace llvm::codeview;
34 
35 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
36     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), CurFn(nullptr) {
37   // If module doesn't have named metadata anchors or COFF debug section
38   // is not available, skip any debug info related stuff.
39   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
40       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
41     Asm = nullptr;
42     return;
43   }
44 
45   // Tell MMI that we have debug info.
46   MMI->setDebugInfoAvailability(true);
47 }
48 
49 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
50   std::string &Filepath = FileToFilepathMap[File];
51   if (!Filepath.empty())
52     return Filepath;
53 
54   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
55 
56   // Clang emits directory and relative filename info into the IR, but CodeView
57   // operates on full paths.  We could change Clang to emit full paths too, but
58   // that would increase the IR size and probably not needed for other users.
59   // For now, just concatenate and canonicalize the path here.
60   if (Filename.find(':') == 1)
61     Filepath = Filename;
62   else
63     Filepath = (Dir + "\\" + Filename).str();
64 
65   // Canonicalize the path.  We have to do it textually because we may no longer
66   // have access the file in the filesystem.
67   // First, replace all slashes with backslashes.
68   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
69 
70   // Remove all "\.\" with "\".
71   size_t Cursor = 0;
72   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
73     Filepath.erase(Cursor, 2);
74 
75   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
76   // path should be well-formatted, e.g. start with a drive letter, etc.
77   Cursor = 0;
78   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
79     // Something's wrong if the path starts with "\..\", abort.
80     if (Cursor == 0)
81       break;
82 
83     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
84     if (PrevSlash == std::string::npos)
85       // Something's wrong, abort.
86       break;
87 
88     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
89     // The next ".." might be following the one we've just erased.
90     Cursor = PrevSlash;
91   }
92 
93   // Remove all duplicate backslashes.
94   Cursor = 0;
95   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
96     Filepath.erase(Cursor, 1);
97 
98   return Filepath;
99 }
100 
101 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
102   unsigned NextId = FileIdMap.size() + 1;
103   auto Insertion = FileIdMap.insert(std::make_pair(F, NextId));
104   if (Insertion.second) {
105     // We have to compute the full filepath and emit a .cv_file directive.
106     StringRef FullPath = getFullFilepath(F);
107     NextId = OS.EmitCVFileDirective(NextId, FullPath);
108     assert(NextId == FileIdMap.size() && ".cv_file directive failed");
109   }
110   return Insertion.first->second;
111 }
112 
113 CodeViewDebug::InlineSite &
114 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
115                              const DISubprogram *Inlinee) {
116   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
117   InlineSite *Site = &SiteInsertion.first->second;
118   if (SiteInsertion.second) {
119     Site->SiteFuncId = NextFuncId++;
120     Site->Inlinee = Inlinee;
121     InlinedSubprograms.insert(Inlinee);
122     getFuncIdForSubprogram(Inlinee);
123   }
124   return *Site;
125 }
126 
127 static const DISubprogram *getQualifiedNameComponents(
128     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
129   const DISubprogram *ClosestSubprogram = nullptr;
130   while (Scope != nullptr) {
131     if (ClosestSubprogram == nullptr)
132       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
133     StringRef ScopeName = Scope->getName();
134     if (!ScopeName.empty())
135       QualifiedNameComponents.push_back(ScopeName);
136     Scope = Scope->getScope().resolve();
137   }
138   return ClosestSubprogram;
139 }
140 
141 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
142                                     StringRef TypeName) {
143   std::string FullyQualifiedName;
144   for (StringRef QualifiedNameComponent : reverse(QualifiedNameComponents)) {
145     FullyQualifiedName.append(QualifiedNameComponent);
146     FullyQualifiedName.append("::");
147   }
148   FullyQualifiedName.append(TypeName);
149   return FullyQualifiedName;
150 }
151 
152 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
153   SmallVector<StringRef, 5> QualifiedNameComponents;
154   getQualifiedNameComponents(Scope, QualifiedNameComponents);
155   return getQualifiedName(QualifiedNameComponents, Name);
156 }
157 
158 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
159   // No scope means global scope and that uses the zero index.
160   if (!Scope || isa<DIFile>(Scope))
161     return TypeIndex();
162 
163   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
164 
165   // Check if we've already translated this scope.
166   auto I = TypeIndices.find({Scope, nullptr});
167   if (I != TypeIndices.end())
168     return I->second;
169 
170   // Build the fully qualified name of the scope.
171   std::string ScopeName =
172       getFullyQualifiedName(Scope->getScope().resolve(), Scope->getName());
173   TypeIndex TI =
174       TypeTable.writeStringId(StringIdRecord(TypeIndex(), ScopeName));
175   return recordTypeIndexForDINode(Scope, TI);
176 }
177 
178 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
179   // It's possible to ask for the FuncId of a function which doesn't have a
180   // subprogram: inlining a function with debug info into a function with none.
181   if (!SP)
182     return TypeIndex::None();
183 
184   // Check if we've already translated this subprogram.
185   auto I = TypeIndices.find({SP, nullptr});
186   if (I != TypeIndices.end())
187     return I->second;
188 
189   // The display name includes function template arguments. Drop them to match
190   // MSVC.
191   StringRef DisplayName = SP->getDisplayName().split('<').first;
192 
193   const DIScope *Scope = SP->getScope().resolve();
194   TypeIndex TI;
195   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
196     // If the scope is a DICompositeType, then this must be a method. Member
197     // function types take some special handling, and require access to the
198     // subprogram.
199     TypeIndex ClassType = getTypeIndex(Class);
200     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
201                                DisplayName);
202     TI = TypeTable.writeMemberFuncId(MFuncId);
203   } else {
204     // Otherwise, this must be a free function.
205     TypeIndex ParentScope = getScopeIndex(Scope);
206     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
207     TI = TypeTable.writeFuncId(FuncId);
208   }
209 
210   return recordTypeIndexForDINode(SP, TI);
211 }
212 
213 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
214                                                const DICompositeType *Class) {
215   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
216   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
217   auto I = TypeIndices.find({SP, nullptr});
218   if (I != TypeIndices.end())
219     return I->second;
220 
221   // FIXME: Get the ThisAdjustment off of SP when it is available.
222   TypeIndex TI =
223       lowerTypeMemberFunction(SP->getType(), Class, /*ThisAdjustment=*/0);
224 
225   return recordTypeIndexForDINode(SP, TI, Class);
226 }
227 
228 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI,
229                                              const DIType *ClassTy) {
230   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
231   (void)InsertResult;
232   assert(InsertResult.second && "DINode was already assigned a type index");
233   return TI;
234 }
235 
236 unsigned CodeViewDebug::getPointerSizeInBytes() {
237   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
238 }
239 
240 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
241                                         const DILocation *InlinedAt) {
242   if (InlinedAt) {
243     // This variable was inlined. Associate it with the InlineSite.
244     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
245     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
246     Site.InlinedLocals.emplace_back(Var);
247   } else {
248     // This variable goes in the main ProcSym.
249     CurFn->Locals.emplace_back(Var);
250   }
251 }
252 
253 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
254                                const DILocation *Loc) {
255   auto B = Locs.begin(), E = Locs.end();
256   if (std::find(B, E, Loc) == E)
257     Locs.push_back(Loc);
258 }
259 
260 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
261                                         const MachineFunction *MF) {
262   // Skip this instruction if it has the same location as the previous one.
263   if (DL == CurFn->LastLoc)
264     return;
265 
266   const DIScope *Scope = DL.get()->getScope();
267   if (!Scope)
268     return;
269 
270   // Skip this line if it is longer than the maximum we can record.
271   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
272   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
273       LI.isNeverStepInto())
274     return;
275 
276   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
277   if (CI.getStartColumn() != DL.getCol())
278     return;
279 
280   if (!CurFn->HaveLineInfo)
281     CurFn->HaveLineInfo = true;
282   unsigned FileId = 0;
283   if (CurFn->LastLoc.get() && CurFn->LastLoc->getFile() == DL->getFile())
284     FileId = CurFn->LastFileId;
285   else
286     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
287   CurFn->LastLoc = DL;
288 
289   unsigned FuncId = CurFn->FuncId;
290   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
291     const DILocation *Loc = DL.get();
292 
293     // If this location was actually inlined from somewhere else, give it the ID
294     // of the inline call site.
295     FuncId =
296         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
297 
298     // Ensure we have links in the tree of inline call sites.
299     bool FirstLoc = true;
300     while ((SiteLoc = Loc->getInlinedAt())) {
301       InlineSite &Site =
302           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
303       if (!FirstLoc)
304         addLocIfNotPresent(Site.ChildSites, Loc);
305       FirstLoc = false;
306       Loc = SiteLoc;
307     }
308     addLocIfNotPresent(CurFn->ChildSites, Loc);
309   }
310 
311   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
312                         /*PrologueEnd=*/false,
313                         /*IsStmt=*/false, DL->getFilename());
314 }
315 
316 void CodeViewDebug::emitCodeViewMagicVersion() {
317   OS.EmitValueToAlignment(4);
318   OS.AddComment("Debug section magic");
319   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
320 }
321 
322 void CodeViewDebug::endModule() {
323   if (!Asm || !MMI->hasDebugInfo())
324     return;
325 
326   assert(Asm != nullptr);
327 
328   // The COFF .debug$S section consists of several subsections, each starting
329   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
330   // of the payload followed by the payload itself.  The subsections are 4-byte
331   // aligned.
332 
333   // Use the generic .debug$S section, and make a subsection for all the inlined
334   // subprograms.
335   switchToDebugSectionForSymbol(nullptr);
336   emitInlineeLinesSubsection();
337 
338   // Emit per-function debug information.
339   for (auto &P : FnDebugInfo)
340     if (!P.first->isDeclarationForLinker())
341       emitDebugInfoForFunction(P.first, P.second);
342 
343   // Emit global variable debug information.
344   setCurrentSubprogram(nullptr);
345   emitDebugInfoForGlobals();
346 
347   // Emit retained types.
348   emitDebugInfoForRetainedTypes();
349 
350   // Switch back to the generic .debug$S section after potentially processing
351   // comdat symbol sections.
352   switchToDebugSectionForSymbol(nullptr);
353 
354   // Emit UDT records for any types used by global variables.
355   if (!GlobalUDTs.empty()) {
356     MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
357     emitDebugInfoForUDTs(GlobalUDTs);
358     endCVSubsection(SymbolsEnd);
359   }
360 
361   // This subsection holds a file index to offset in string table table.
362   OS.AddComment("File index to string table offset subsection");
363   OS.EmitCVFileChecksumsDirective();
364 
365   // This subsection holds the string table.
366   OS.AddComment("String table");
367   OS.EmitCVStringTableDirective();
368 
369   // Emit type information last, so that any types we translate while emitting
370   // function info are included.
371   emitTypeInformation();
372 
373   clear();
374 }
375 
376 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
377   // Microsoft's linker seems to have trouble with symbol names longer than
378   // 0xffd8 bytes.
379   S = S.substr(0, 0xffd8);
380   SmallString<32> NullTerminatedString(S);
381   NullTerminatedString.push_back('\0');
382   OS.EmitBytes(NullTerminatedString);
383 }
384 
385 void CodeViewDebug::emitTypeInformation() {
386   // Do nothing if we have no debug info or if no non-trivial types were emitted
387   // to TypeTable during codegen.
388   NamedMDNode *CU_Nodes = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
389   if (!CU_Nodes)
390     return;
391   if (TypeTable.empty())
392     return;
393 
394   // Start the .debug$T section with 0x4.
395   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
396   emitCodeViewMagicVersion();
397 
398   SmallString<8> CommentPrefix;
399   if (OS.isVerboseAsm()) {
400     CommentPrefix += '\t';
401     CommentPrefix += Asm->MAI->getCommentString();
402     CommentPrefix += ' ';
403   }
404 
405   CVTypeDumper CVTD(nullptr, /*PrintRecordBytes=*/false);
406   TypeTable.ForEachRecord(
407       [&](TypeIndex Index, StringRef Record) {
408         if (OS.isVerboseAsm()) {
409           // Emit a block comment describing the type record for readability.
410           SmallString<512> CommentBlock;
411           raw_svector_ostream CommentOS(CommentBlock);
412           ScopedPrinter SP(CommentOS);
413           SP.setPrefix(CommentPrefix);
414           CVTD.setPrinter(&SP);
415           Error EC = CVTD.dump({Record.bytes_begin(), Record.bytes_end()});
416           assert(!EC && "produced malformed type record");
417           consumeError(std::move(EC));
418           // emitRawComment will insert its own tab and comment string before
419           // the first line, so strip off our first one. It also prints its own
420           // newline.
421           OS.emitRawComment(
422               CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
423         }
424         OS.EmitBinaryData(Record);
425       });
426 }
427 
428 void CodeViewDebug::emitInlineeLinesSubsection() {
429   if (InlinedSubprograms.empty())
430     return;
431 
432   OS.AddComment("Inlinee lines subsection");
433   MCSymbol *InlineEnd = beginCVSubsection(ModuleSubstreamKind::InlineeLines);
434 
435   // We don't provide any extra file info.
436   // FIXME: Find out if debuggers use this info.
437   OS.AddComment("Inlinee lines signature");
438   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
439 
440   for (const DISubprogram *SP : InlinedSubprograms) {
441     assert(TypeIndices.count({SP, nullptr}));
442     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
443 
444     OS.AddBlankLine();
445     unsigned FileId = maybeRecordFile(SP->getFile());
446     OS.AddComment("Inlined function " + SP->getDisplayName() + " starts at " +
447                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
448     OS.AddBlankLine();
449     // The filechecksum table uses 8 byte entries for now, and file ids start at
450     // 1.
451     unsigned FileOffset = (FileId - 1) * 8;
452     OS.AddComment("Type index of inlined function");
453     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
454     OS.AddComment("Offset into filechecksum table");
455     OS.EmitIntValue(FileOffset, 4);
456     OS.AddComment("Starting line number");
457     OS.EmitIntValue(SP->getLine(), 4);
458   }
459 
460   endCVSubsection(InlineEnd);
461 }
462 
463 void CodeViewDebug::collectInlineSiteChildren(
464     SmallVectorImpl<unsigned> &Children, const FunctionInfo &FI,
465     const InlineSite &Site) {
466   for (const DILocation *ChildSiteLoc : Site.ChildSites) {
467     auto I = FI.InlineSites.find(ChildSiteLoc);
468     const InlineSite &ChildSite = I->second;
469     Children.push_back(ChildSite.SiteFuncId);
470     collectInlineSiteChildren(Children, FI, ChildSite);
471   }
472 }
473 
474 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
475                                         const DILocation *InlinedAt,
476                                         const InlineSite &Site) {
477   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
478            *InlineEnd = MMI->getContext().createTempSymbol();
479 
480   assert(TypeIndices.count({Site.Inlinee, nullptr}));
481   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
482 
483   // SymbolRecord
484   OS.AddComment("Record length");
485   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
486   OS.EmitLabel(InlineBegin);
487   OS.AddComment("Record kind: S_INLINESITE");
488   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
489 
490   OS.AddComment("PtrParent");
491   OS.EmitIntValue(0, 4);
492   OS.AddComment("PtrEnd");
493   OS.EmitIntValue(0, 4);
494   OS.AddComment("Inlinee type index");
495   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
496 
497   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
498   unsigned StartLineNum = Site.Inlinee->getLine();
499   SmallVector<unsigned, 3> SecondaryFuncIds;
500   collectInlineSiteChildren(SecondaryFuncIds, FI, Site);
501 
502   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
503                                     FI.Begin, FI.End, SecondaryFuncIds);
504 
505   OS.EmitLabel(InlineEnd);
506 
507   for (const LocalVariable &Var : Site.InlinedLocals)
508     emitLocalVariable(Var);
509 
510   // Recurse on child inlined call sites before closing the scope.
511   for (const DILocation *ChildSite : Site.ChildSites) {
512     auto I = FI.InlineSites.find(ChildSite);
513     assert(I != FI.InlineSites.end() &&
514            "child site not in function inline site map");
515     emitInlinedCallSite(FI, ChildSite, I->second);
516   }
517 
518   // Close the scope.
519   OS.AddComment("Record length");
520   OS.EmitIntValue(2, 2);                                  // RecordLength
521   OS.AddComment("Record kind: S_INLINESITE_END");
522   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
523 }
524 
525 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
526   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
527   // comdat key. A section may be comdat because of -ffunction-sections or
528   // because it is comdat in the IR.
529   MCSectionCOFF *GVSec =
530       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
531   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
532 
533   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
534       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
535   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
536 
537   OS.SwitchSection(DebugSec);
538 
539   // Emit the magic version number if this is the first time we've switched to
540   // this section.
541   if (ComdatDebugSections.insert(DebugSec).second)
542     emitCodeViewMagicVersion();
543 }
544 
545 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
546                                              FunctionInfo &FI) {
547   // For each function there is a separate subsection
548   // which holds the PC to file:line table.
549   const MCSymbol *Fn = Asm->getSymbol(GV);
550   assert(Fn);
551 
552   // Switch to the to a comdat section, if appropriate.
553   switchToDebugSectionForSymbol(Fn);
554 
555   std::string FuncName;
556   auto *SP = GV->getSubprogram();
557   setCurrentSubprogram(SP);
558 
559   // If we have a display name, build the fully qualified name by walking the
560   // chain of scopes.
561   if (SP != nullptr && !SP->getDisplayName().empty())
562     FuncName =
563         getFullyQualifiedName(SP->getScope().resolve(), SP->getDisplayName());
564 
565   // If our DISubprogram name is empty, use the mangled name.
566   if (FuncName.empty())
567     FuncName = GlobalValue::getRealLinkageName(GV->getName());
568 
569   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
570   OS.AddComment("Symbol subsection for " + Twine(FuncName));
571   MCSymbol *SymbolsEnd = beginCVSubsection(ModuleSubstreamKind::Symbols);
572   {
573     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
574              *ProcRecordEnd = MMI->getContext().createTempSymbol();
575     OS.AddComment("Record length");
576     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
577     OS.EmitLabel(ProcRecordBegin);
578 
579     OS.AddComment("Record kind: S_GPROC32_ID");
580     OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
581 
582     // These fields are filled in by tools like CVPACK which run after the fact.
583     OS.AddComment("PtrParent");
584     OS.EmitIntValue(0, 4);
585     OS.AddComment("PtrEnd");
586     OS.EmitIntValue(0, 4);
587     OS.AddComment("PtrNext");
588     OS.EmitIntValue(0, 4);
589     // This is the important bit that tells the debugger where the function
590     // code is located and what's its size:
591     OS.AddComment("Code size");
592     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
593     OS.AddComment("Offset after prologue");
594     OS.EmitIntValue(0, 4);
595     OS.AddComment("Offset before epilogue");
596     OS.EmitIntValue(0, 4);
597     OS.AddComment("Function type index");
598     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
599     OS.AddComment("Function section relative address");
600     OS.EmitCOFFSecRel32(Fn);
601     OS.AddComment("Function section index");
602     OS.EmitCOFFSectionIndex(Fn);
603     OS.AddComment("Flags");
604     OS.EmitIntValue(0, 1);
605     // Emit the function display name as a null-terminated string.
606     OS.AddComment("Function name");
607     // Truncate the name so we won't overflow the record length field.
608     emitNullTerminatedSymbolName(OS, FuncName);
609     OS.EmitLabel(ProcRecordEnd);
610 
611     for (const LocalVariable &Var : FI.Locals)
612       emitLocalVariable(Var);
613 
614     // Emit inlined call site information. Only emit functions inlined directly
615     // into the parent function. We'll emit the other sites recursively as part
616     // of their parent inline site.
617     for (const DILocation *InlinedAt : FI.ChildSites) {
618       auto I = FI.InlineSites.find(InlinedAt);
619       assert(I != FI.InlineSites.end() &&
620              "child site not in function inline site map");
621       emitInlinedCallSite(FI, InlinedAt, I->second);
622     }
623 
624     if (SP != nullptr)
625       emitDebugInfoForUDTs(LocalUDTs);
626 
627     // We're done with this function.
628     OS.AddComment("Record length");
629     OS.EmitIntValue(0x0002, 2);
630     OS.AddComment("Record kind: S_PROC_ID_END");
631     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
632   }
633   endCVSubsection(SymbolsEnd);
634 
635   // We have an assembler directive that takes care of the whole line table.
636   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
637 }
638 
639 CodeViewDebug::LocalVarDefRange
640 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
641   LocalVarDefRange DR;
642   DR.InMemory = -1;
643   DR.DataOffset = Offset;
644   assert(DR.DataOffset == Offset && "truncation");
645   DR.StructOffset = 0;
646   DR.CVRegister = CVRegister;
647   return DR;
648 }
649 
650 CodeViewDebug::LocalVarDefRange
651 CodeViewDebug::createDefRangeReg(uint16_t CVRegister) {
652   LocalVarDefRange DR;
653   DR.InMemory = 0;
654   DR.DataOffset = 0;
655   DR.StructOffset = 0;
656   DR.CVRegister = CVRegister;
657   return DR;
658 }
659 
660 void CodeViewDebug::collectVariableInfoFromMMITable(
661     DenseSet<InlinedVariable> &Processed) {
662   const TargetSubtargetInfo &TSI = Asm->MF->getSubtarget();
663   const TargetFrameLowering *TFI = TSI.getFrameLowering();
664   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
665 
666   for (const MachineModuleInfo::VariableDbgInfo &VI :
667        MMI->getVariableDbgInfo()) {
668     if (!VI.Var)
669       continue;
670     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
671            "Expected inlined-at fields to agree");
672 
673     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
674     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
675 
676     // If variable scope is not found then skip this variable.
677     if (!Scope)
678       continue;
679 
680     // Get the frame register used and the offset.
681     unsigned FrameReg = 0;
682     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
683     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
684 
685     // Calculate the label ranges.
686     LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset);
687     for (const InsnRange &Range : Scope->getRanges()) {
688       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
689       const MCSymbol *End = getLabelAfterInsn(Range.second);
690       End = End ? End : Asm->getFunctionEnd();
691       DefRange.Ranges.emplace_back(Begin, End);
692     }
693 
694     LocalVariable Var;
695     Var.DIVar = VI.Var;
696     Var.DefRanges.emplace_back(std::move(DefRange));
697     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
698   }
699 }
700 
701 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
702   DenseSet<InlinedVariable> Processed;
703   // Grab the variable info that was squirreled away in the MMI side-table.
704   collectVariableInfoFromMMITable(Processed);
705 
706   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
707 
708   for (const auto &I : DbgValues) {
709     InlinedVariable IV = I.first;
710     if (Processed.count(IV))
711       continue;
712     const DILocalVariable *DIVar = IV.first;
713     const DILocation *InlinedAt = IV.second;
714 
715     // Instruction ranges, specifying where IV is accessible.
716     const auto &Ranges = I.second;
717 
718     LexicalScope *Scope = nullptr;
719     if (InlinedAt)
720       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
721     else
722       Scope = LScopes.findLexicalScope(DIVar->getScope());
723     // If variable scope is not found then skip this variable.
724     if (!Scope)
725       continue;
726 
727     LocalVariable Var;
728     Var.DIVar = DIVar;
729 
730     // Calculate the definition ranges.
731     for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
732       const InsnRange &Range = *I;
733       const MachineInstr *DVInst = Range.first;
734       assert(DVInst->isDebugValue() && "Invalid History entry");
735       const DIExpression *DIExpr = DVInst->getDebugExpression();
736 
737       // Bail if there is a complex DWARF expression for now.
738       if (DIExpr && DIExpr->getNumElements() > 0)
739         continue;
740 
741       // Bail if operand 0 is not a valid register. This means the variable is a
742       // simple constant, or is described by a complex expression.
743       // FIXME: Find a way to represent constant variables, since they are
744       // relatively common.
745       unsigned Reg =
746           DVInst->getOperand(0).isReg() ? DVInst->getOperand(0).getReg() : 0;
747       if (Reg == 0)
748         continue;
749 
750       // Handle the two cases we can handle: indirect in memory and in register.
751       bool IsIndirect = DVInst->getOperand(1).isImm();
752       unsigned CVReg = TRI->getCodeViewRegNum(DVInst->getOperand(0).getReg());
753       {
754         LocalVarDefRange DefRange;
755         if (IsIndirect) {
756           int64_t Offset = DVInst->getOperand(1).getImm();
757           DefRange = createDefRangeMem(CVReg, Offset);
758         } else {
759           DefRange = createDefRangeReg(CVReg);
760         }
761         if (Var.DefRanges.empty() ||
762             Var.DefRanges.back().isDifferentLocation(DefRange)) {
763           Var.DefRanges.emplace_back(std::move(DefRange));
764         }
765       }
766 
767       // Compute the label range.
768       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
769       const MCSymbol *End = getLabelAfterInsn(Range.second);
770       if (!End) {
771         if (std::next(I) != E)
772           End = getLabelBeforeInsn(std::next(I)->first);
773         else
774           End = Asm->getFunctionEnd();
775       }
776 
777       // If the last range end is our begin, just extend the last range.
778       // Otherwise make a new range.
779       SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &Ranges =
780           Var.DefRanges.back().Ranges;
781       if (!Ranges.empty() && Ranges.back().second == Begin)
782         Ranges.back().second = End;
783       else
784         Ranges.emplace_back(Begin, End);
785 
786       // FIXME: Do more range combining.
787     }
788 
789     recordLocalVariable(std::move(Var), InlinedAt);
790   }
791 }
792 
793 void CodeViewDebug::beginFunction(const MachineFunction *MF) {
794   assert(!CurFn && "Can't process two functions at once!");
795 
796   if (!Asm || !MMI->hasDebugInfo())
797     return;
798 
799   DebugHandlerBase::beginFunction(MF);
800 
801   const Function *GV = MF->getFunction();
802   assert(FnDebugInfo.count(GV) == false);
803   CurFn = &FnDebugInfo[GV];
804   CurFn->FuncId = NextFuncId++;
805   CurFn->Begin = Asm->getFunctionBegin();
806 
807   // Find the end of the function prolog.  First known non-DBG_VALUE and
808   // non-frame setup location marks the beginning of the function body.
809   // FIXME: is there a simpler a way to do this? Can we just search
810   // for the first instruction of the function, not the last of the prolog?
811   DebugLoc PrologEndLoc;
812   bool EmptyPrologue = true;
813   for (const auto &MBB : *MF) {
814     for (const auto &MI : MBB) {
815       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
816           MI.getDebugLoc()) {
817         PrologEndLoc = MI.getDebugLoc();
818         break;
819       } else if (!MI.isDebugValue()) {
820         EmptyPrologue = false;
821       }
822     }
823   }
824 
825   // Record beginning of function if we have a non-empty prologue.
826   if (PrologEndLoc && !EmptyPrologue) {
827     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
828     maybeRecordLocation(FnStartDL, MF);
829   }
830 }
831 
832 void CodeViewDebug::addToUDTs(const DIType *Ty, TypeIndex TI) {
833   SmallVector<StringRef, 5> QualifiedNameComponents;
834   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
835       Ty->getScope().resolve(), QualifiedNameComponents);
836 
837   std::string FullyQualifiedName =
838       getQualifiedName(QualifiedNameComponents, Ty->getName());
839 
840   if (ClosestSubprogram == nullptr)
841     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
842   else if (ClosestSubprogram == CurrentSubprogram)
843     LocalUDTs.emplace_back(std::move(FullyQualifiedName), TI);
844 
845   // TODO: What if the ClosestSubprogram is neither null or the current
846   // subprogram?  Currently, the UDT just gets dropped on the floor.
847   //
848   // The current behavior is not desirable.  To get maximal fidelity, we would
849   // need to perform all type translation before beginning emission of .debug$S
850   // and then make LocalUDTs a member of FunctionInfo
851 }
852 
853 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
854   // Generic dispatch for lowering an unknown type.
855   switch (Ty->getTag()) {
856   case dwarf::DW_TAG_array_type:
857     return lowerTypeArray(cast<DICompositeType>(Ty));
858   case dwarf::DW_TAG_typedef:
859     return lowerTypeAlias(cast<DIDerivedType>(Ty));
860   case dwarf::DW_TAG_base_type:
861     return lowerTypeBasic(cast<DIBasicType>(Ty));
862   case dwarf::DW_TAG_pointer_type:
863   case dwarf::DW_TAG_reference_type:
864   case dwarf::DW_TAG_rvalue_reference_type:
865     return lowerTypePointer(cast<DIDerivedType>(Ty));
866   case dwarf::DW_TAG_ptr_to_member_type:
867     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
868   case dwarf::DW_TAG_const_type:
869   case dwarf::DW_TAG_volatile_type:
870     return lowerTypeModifier(cast<DIDerivedType>(Ty));
871   case dwarf::DW_TAG_subroutine_type:
872     if (ClassTy) {
873       // The member function type of a member function pointer has no
874       // ThisAdjustment.
875       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
876                                      /*ThisAdjustment=*/0);
877     }
878     return lowerTypeFunction(cast<DISubroutineType>(Ty));
879   case dwarf::DW_TAG_enumeration_type:
880     return lowerTypeEnum(cast<DICompositeType>(Ty));
881   case dwarf::DW_TAG_class_type:
882   case dwarf::DW_TAG_structure_type:
883     return lowerTypeClass(cast<DICompositeType>(Ty));
884   case dwarf::DW_TAG_union_type:
885     return lowerTypeUnion(cast<DICompositeType>(Ty));
886   default:
887     // Use the null type index.
888     return TypeIndex();
889   }
890 }
891 
892 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
893   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
894   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
895   StringRef TypeName = Ty->getName();
896 
897   addToUDTs(Ty, UnderlyingTypeIndex);
898 
899   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
900       TypeName == "HRESULT")
901     return TypeIndex(SimpleTypeKind::HResult);
902   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
903       TypeName == "wchar_t")
904     return TypeIndex(SimpleTypeKind::WideCharacter);
905 
906   return UnderlyingTypeIndex;
907 }
908 
909 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
910   DITypeRef ElementTypeRef = Ty->getBaseType();
911   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
912   // IndexType is size_t, which depends on the bitness of the target.
913   TypeIndex IndexType = Asm->MAI->getPointerSize() == 8
914                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
915                             : TypeIndex(SimpleTypeKind::UInt32Long);
916   uint64_t Size = Ty->getSizeInBits() / 8;
917   ArrayRecord Record(ElementTypeIndex, IndexType, Size, Ty->getName());
918   return TypeTable.writeArray(Record);
919 }
920 
921 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
922   TypeIndex Index;
923   dwarf::TypeKind Kind;
924   uint32_t ByteSize;
925 
926   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
927   ByteSize = Ty->getSizeInBits() / 8;
928 
929   SimpleTypeKind STK = SimpleTypeKind::None;
930   switch (Kind) {
931   case dwarf::DW_ATE_address:
932     // FIXME: Translate
933     break;
934   case dwarf::DW_ATE_boolean:
935     switch (ByteSize) {
936     case 1:  STK = SimpleTypeKind::Boolean8;   break;
937     case 2:  STK = SimpleTypeKind::Boolean16;  break;
938     case 4:  STK = SimpleTypeKind::Boolean32;  break;
939     case 8:  STK = SimpleTypeKind::Boolean64;  break;
940     case 16: STK = SimpleTypeKind::Boolean128; break;
941     }
942     break;
943   case dwarf::DW_ATE_complex_float:
944     switch (ByteSize) {
945     case 2:  STK = SimpleTypeKind::Complex16;  break;
946     case 4:  STK = SimpleTypeKind::Complex32;  break;
947     case 8:  STK = SimpleTypeKind::Complex64;  break;
948     case 10: STK = SimpleTypeKind::Complex80;  break;
949     case 16: STK = SimpleTypeKind::Complex128; break;
950     }
951     break;
952   case dwarf::DW_ATE_float:
953     switch (ByteSize) {
954     case 2:  STK = SimpleTypeKind::Float16;  break;
955     case 4:  STK = SimpleTypeKind::Float32;  break;
956     case 6:  STK = SimpleTypeKind::Float48;  break;
957     case 8:  STK = SimpleTypeKind::Float64;  break;
958     case 10: STK = SimpleTypeKind::Float80;  break;
959     case 16: STK = SimpleTypeKind::Float128; break;
960     }
961     break;
962   case dwarf::DW_ATE_signed:
963     switch (ByteSize) {
964     case 1:  STK = SimpleTypeKind::SByte;      break;
965     case 2:  STK = SimpleTypeKind::Int16Short; break;
966     case 4:  STK = SimpleTypeKind::Int32;      break;
967     case 8:  STK = SimpleTypeKind::Int64Quad;  break;
968     case 16: STK = SimpleTypeKind::Int128Oct;  break;
969     }
970     break;
971   case dwarf::DW_ATE_unsigned:
972     switch (ByteSize) {
973     case 1:  STK = SimpleTypeKind::Byte;        break;
974     case 2:  STK = SimpleTypeKind::UInt16Short; break;
975     case 4:  STK = SimpleTypeKind::UInt32;      break;
976     case 8:  STK = SimpleTypeKind::UInt64Quad;  break;
977     case 16: STK = SimpleTypeKind::UInt128Oct;  break;
978     }
979     break;
980   case dwarf::DW_ATE_UTF:
981     switch (ByteSize) {
982     case 2: STK = SimpleTypeKind::Character16; break;
983     case 4: STK = SimpleTypeKind::Character32; break;
984     }
985     break;
986   case dwarf::DW_ATE_signed_char:
987     if (ByteSize == 1)
988       STK = SimpleTypeKind::SignedCharacter;
989     break;
990   case dwarf::DW_ATE_unsigned_char:
991     if (ByteSize == 1)
992       STK = SimpleTypeKind::UnsignedCharacter;
993     break;
994   default:
995     break;
996   }
997 
998   // Apply some fixups based on the source-level type name.
999   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1000     STK = SimpleTypeKind::Int32Long;
1001   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1002     STK = SimpleTypeKind::UInt32Long;
1003   if (STK == SimpleTypeKind::UInt16Short &&
1004       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1005     STK = SimpleTypeKind::WideCharacter;
1006   if ((STK == SimpleTypeKind::SignedCharacter ||
1007        STK == SimpleTypeKind::UnsignedCharacter) &&
1008       Ty->getName() == "char")
1009     STK = SimpleTypeKind::NarrowCharacter;
1010 
1011   return TypeIndex(STK);
1012 }
1013 
1014 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1015   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1016 
1017   // While processing the type being pointed to it is possible we already
1018   // created this pointer type.  If so, we check here and return the existing
1019   // pointer type.
1020   auto I = TypeIndices.find({Ty, nullptr});
1021   if (I != TypeIndices.end())
1022     return I->second;
1023 
1024   // Pointers to simple types can use SimpleTypeMode, rather than having a
1025   // dedicated pointer type record.
1026   if (PointeeTI.isSimple() &&
1027       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1028       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1029     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1030                               ? SimpleTypeMode::NearPointer64
1031                               : SimpleTypeMode::NearPointer32;
1032     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1033   }
1034 
1035   PointerKind PK =
1036       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1037   PointerMode PM = PointerMode::Pointer;
1038   switch (Ty->getTag()) {
1039   default: llvm_unreachable("not a pointer tag type");
1040   case dwarf::DW_TAG_pointer_type:
1041     PM = PointerMode::Pointer;
1042     break;
1043   case dwarf::DW_TAG_reference_type:
1044     PM = PointerMode::LValueReference;
1045     break;
1046   case dwarf::DW_TAG_rvalue_reference_type:
1047     PM = PointerMode::RValueReference;
1048     break;
1049   }
1050   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1051   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1052   // do.
1053   PointerOptions PO = PointerOptions::None;
1054   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1055   return TypeTable.writePointer(PR);
1056 }
1057 
1058 static PointerToMemberRepresentation
1059 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1060   // SizeInBytes being zero generally implies that the member pointer type was
1061   // incomplete, which can happen if it is part of a function prototype. In this
1062   // case, use the unknown model instead of the general model.
1063   if (IsPMF) {
1064     switch (Flags & DINode::FlagPtrToMemberRep) {
1065     case 0:
1066       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1067                               : PointerToMemberRepresentation::GeneralFunction;
1068     case DINode::FlagSingleInheritance:
1069       return PointerToMemberRepresentation::SingleInheritanceFunction;
1070     case DINode::FlagMultipleInheritance:
1071       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1072     case DINode::FlagVirtualInheritance:
1073       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1074     }
1075   } else {
1076     switch (Flags & DINode::FlagPtrToMemberRep) {
1077     case 0:
1078       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1079                               : PointerToMemberRepresentation::GeneralData;
1080     case DINode::FlagSingleInheritance:
1081       return PointerToMemberRepresentation::SingleInheritanceData;
1082     case DINode::FlagMultipleInheritance:
1083       return PointerToMemberRepresentation::MultipleInheritanceData;
1084     case DINode::FlagVirtualInheritance:
1085       return PointerToMemberRepresentation::VirtualInheritanceData;
1086     }
1087   }
1088   llvm_unreachable("invalid ptr to member representation");
1089 }
1090 
1091 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1092   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1093   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1094   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1095   PointerKind PK = Asm->MAI->getPointerSize() == 8 ? PointerKind::Near64
1096                                                    : PointerKind::Near32;
1097   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1098   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1099                          : PointerMode::PointerToDataMember;
1100   PointerOptions PO = PointerOptions::None; // FIXME
1101   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1102   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1103   MemberPointerInfo MPI(
1104       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1105   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1106   return TypeTable.writePointer(PR);
1107 }
1108 
1109 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1110 /// have a translation, use the NearC convention.
1111 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1112   switch (DwarfCC) {
1113   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1114   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1115   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1116   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1117   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1118   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1119   }
1120   return CallingConvention::NearC;
1121 }
1122 
1123 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1124   ModifierOptions Mods = ModifierOptions::None;
1125   bool IsModifier = true;
1126   const DIType *BaseTy = Ty;
1127   while (IsModifier && BaseTy) {
1128     // FIXME: Need to add DWARF tag for __unaligned.
1129     switch (BaseTy->getTag()) {
1130     case dwarf::DW_TAG_const_type:
1131       Mods |= ModifierOptions::Const;
1132       break;
1133     case dwarf::DW_TAG_volatile_type:
1134       Mods |= ModifierOptions::Volatile;
1135       break;
1136     default:
1137       IsModifier = false;
1138       break;
1139     }
1140     if (IsModifier)
1141       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1142   }
1143   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1144 
1145   // While processing the type being pointed to, it is possible we already
1146   // created this modifier type.  If so, we check here and return the existing
1147   // modifier type.
1148   auto I = TypeIndices.find({Ty, nullptr});
1149   if (I != TypeIndices.end())
1150     return I->second;
1151 
1152   ModifierRecord MR(ModifiedTI, Mods);
1153   return TypeTable.writeModifier(MR);
1154 }
1155 
1156 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1157   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1158   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1159     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1160 
1161   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1162   ArrayRef<TypeIndex> ArgTypeIndices = None;
1163   if (!ReturnAndArgTypeIndices.empty()) {
1164     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1165     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1166     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1167   }
1168 
1169   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1170   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1171 
1172   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1173 
1174   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1175                             ArgTypeIndices.size(), ArgListIndex);
1176   return TypeTable.writeProcedure(Procedure);
1177 }
1178 
1179 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1180                                                  const DIType *ClassTy,
1181                                                  int ThisAdjustment) {
1182   // Lower the containing class type.
1183   TypeIndex ClassType = getTypeIndex(ClassTy);
1184 
1185   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1186   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1187     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1188 
1189   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1190   ArrayRef<TypeIndex> ArgTypeIndices = None;
1191   if (!ReturnAndArgTypeIndices.empty()) {
1192     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1193     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1194     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1195   }
1196   TypeIndex ThisTypeIndex = TypeIndex::Void();
1197   if (!ArgTypeIndices.empty()) {
1198     ThisTypeIndex = ArgTypeIndices.front();
1199     ArgTypeIndices = ArgTypeIndices.drop_front();
1200   }
1201 
1202   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1203   TypeIndex ArgListIndex = TypeTable.writeArgList(ArgListRec);
1204 
1205   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1206 
1207   // TODO: Need to use the correct values for:
1208   //       FunctionOptions
1209   //       ThisPointerAdjustment.
1210   TypeIndex TI = TypeTable.writeMemberFunction(MemberFunctionRecord(
1211       ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FunctionOptions::None,
1212       ArgTypeIndices.size(), ArgListIndex, ThisAdjustment));
1213 
1214   return TI;
1215 }
1216 
1217 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1218   switch (Flags & DINode::FlagAccessibility) {
1219   case DINode::FlagPrivate:   return MemberAccess::Private;
1220   case DINode::FlagPublic:    return MemberAccess::Public;
1221   case DINode::FlagProtected: return MemberAccess::Protected;
1222   case 0:
1223     // If there was no explicit access control, provide the default for the tag.
1224     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1225                                                  : MemberAccess::Public;
1226   }
1227   llvm_unreachable("access flags are exclusive");
1228 }
1229 
1230 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1231   if (SP->isArtificial())
1232     return MethodOptions::CompilerGenerated;
1233 
1234   // FIXME: Handle other MethodOptions.
1235 
1236   return MethodOptions::None;
1237 }
1238 
1239 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1240                                            bool Introduced) {
1241   switch (SP->getVirtuality()) {
1242   case dwarf::DW_VIRTUALITY_none:
1243     break;
1244   case dwarf::DW_VIRTUALITY_virtual:
1245     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1246   case dwarf::DW_VIRTUALITY_pure_virtual:
1247     return Introduced ? MethodKind::PureIntroducingVirtual
1248                       : MethodKind::PureVirtual;
1249   default:
1250     llvm_unreachable("unhandled virtuality case");
1251   }
1252 
1253   // FIXME: Get Clang to mark DISubprogram as static and do something with it.
1254 
1255   return MethodKind::Vanilla;
1256 }
1257 
1258 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1259   switch (Ty->getTag()) {
1260   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1261   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1262   }
1263   llvm_unreachable("unexpected tag");
1264 }
1265 
1266 /// Return the HasUniqueName option if it should be present in ClassOptions, or
1267 /// None otherwise.
1268 static ClassOptions getRecordUniqueNameOption(const DICompositeType *Ty) {
1269   // MSVC always sets this flag now, even for local types. Clang doesn't always
1270   // appear to give every type a linkage name, which may be problematic for us.
1271   // FIXME: Investigate the consequences of not following them here.
1272   return !Ty->getIdentifier().empty() ? ClassOptions::HasUniqueName
1273                                       : ClassOptions::None;
1274 }
1275 
1276 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1277   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1278   TypeIndex FTI;
1279   unsigned EnumeratorCount = 0;
1280 
1281   if (Ty->isForwardDecl()) {
1282     CO |= ClassOptions::ForwardReference;
1283   } else {
1284     FieldListRecordBuilder Fields;
1285     for (const DINode *Element : Ty->getElements()) {
1286       // We assume that the frontend provides all members in source declaration
1287       // order, which is what MSVC does.
1288       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1289         Fields.writeEnumerator(EnumeratorRecord(
1290             MemberAccess::Public, APSInt::getUnsigned(Enumerator->getValue()),
1291             Enumerator->getName()));
1292         EnumeratorCount++;
1293       }
1294     }
1295     FTI = TypeTable.writeFieldList(Fields);
1296   }
1297 
1298   std::string FullName =
1299       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1300 
1301   return TypeTable.writeEnum(EnumRecord(EnumeratorCount, CO, FTI, FullName,
1302                                         Ty->getIdentifier(),
1303                                         getTypeIndex(Ty->getBaseType())));
1304 }
1305 
1306 //===----------------------------------------------------------------------===//
1307 // ClassInfo
1308 //===----------------------------------------------------------------------===//
1309 
1310 struct llvm::ClassInfo {
1311   struct MemberInfo {
1312     const DIDerivedType *MemberTypeNode;
1313     unsigned BaseOffset;
1314   };
1315   // [MemberInfo]
1316   typedef std::vector<MemberInfo> MemberList;
1317 
1318   typedef TinyPtrVector<const DISubprogram *> MethodsList;
1319   // MethodName -> MethodsList
1320   typedef MapVector<MDString *, MethodsList> MethodsMap;
1321 
1322   /// Base classes.
1323   std::vector<const DIDerivedType *> Inheritance;
1324 
1325   /// Direct members.
1326   MemberList Members;
1327   // Direct overloaded methods gathered by name.
1328   MethodsMap Methods;
1329 };
1330 
1331 void CodeViewDebug::clear() {
1332   assert(CurFn == nullptr);
1333   FileIdMap.clear();
1334   FnDebugInfo.clear();
1335   FileToFilepathMap.clear();
1336   LocalUDTs.clear();
1337   GlobalUDTs.clear();
1338   TypeIndices.clear();
1339   CompleteTypeIndices.clear();
1340 }
1341 
1342 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1343                                       const DIDerivedType *DDTy) {
1344   if (!DDTy->getName().empty()) {
1345     Info.Members.push_back({DDTy, 0});
1346     return;
1347   }
1348   // An unnamed member must represent a nested struct or union. Add all the
1349   // indirect fields to the current record.
1350   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1351   unsigned Offset = DDTy->getOffsetInBits() / 8;
1352   const DIType *Ty = DDTy->getBaseType().resolve();
1353   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1354   ClassInfo NestedInfo = collectClassInfo(DCTy);
1355   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1356     Info.Members.push_back(
1357         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1358 }
1359 
1360 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1361   ClassInfo Info;
1362   // Add elements to structure type.
1363   DINodeArray Elements = Ty->getElements();
1364   for (auto *Element : Elements) {
1365     // We assume that the frontend provides all members in source declaration
1366     // order, which is what MSVC does.
1367     if (!Element)
1368       continue;
1369     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1370       Info.Methods[SP->getRawName()].push_back(SP);
1371     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1372       if (DDTy->getTag() == dwarf::DW_TAG_member) {
1373         collectMemberInfo(Info, DDTy);
1374       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1375         Info.Inheritance.push_back(DDTy);
1376       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1377         // Ignore friend members. It appears that MSVC emitted info about
1378         // friends in the past, but modern versions do not.
1379       }
1380       // FIXME: Get Clang to emit function virtual table here and handle it.
1381       // FIXME: Get clang to emit nested types here and do something with
1382       // them.
1383     }
1384     // Skip other unrecognized kinds of elements.
1385   }
1386   return Info;
1387 }
1388 
1389 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1390   // First, construct the forward decl.  Don't look into Ty to compute the
1391   // forward decl options, since it might not be available in all TUs.
1392   TypeRecordKind Kind = getRecordKind(Ty);
1393   ClassOptions CO =
1394       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1395   std::string FullName =
1396       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1397   TypeIndex FwdDeclTI = TypeTable.writeClass(ClassRecord(
1398       Kind, 0, CO, HfaKind::None, WindowsRTClassKind::None, TypeIndex(),
1399       TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()));
1400   if (!Ty->isForwardDecl())
1401     DeferredCompleteTypes.push_back(Ty);
1402   return FwdDeclTI;
1403 }
1404 
1405 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1406   // Construct the field list and complete type record.
1407   TypeRecordKind Kind = getRecordKind(Ty);
1408   // FIXME: Other ClassOptions, like ContainsNestedClass and NestedClass.
1409   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1410   TypeIndex FieldTI;
1411   TypeIndex VShapeTI;
1412   unsigned FieldCount;
1413   std::tie(FieldTI, VShapeTI, FieldCount) = lowerRecordFieldList(Ty);
1414 
1415   std::string FullName =
1416       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1417 
1418   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1419 
1420   TypeIndex ClassTI = TypeTable.writeClass(ClassRecord(
1421       Kind, FieldCount, CO, HfaKind::None, WindowsRTClassKind::None, FieldTI,
1422       TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()));
1423 
1424   TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1425       ClassTI, TypeTable.writeStringId(StringIdRecord(
1426                    TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1427       Ty->getLine()));
1428 
1429   addToUDTs(Ty, ClassTI);
1430 
1431   return ClassTI;
1432 }
1433 
1434 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1435   ClassOptions CO =
1436       ClassOptions::ForwardReference | getRecordUniqueNameOption(Ty);
1437   std::string FullName =
1438       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1439   TypeIndex FwdDeclTI =
1440       TypeTable.writeUnion(UnionRecord(0, CO, HfaKind::None, TypeIndex(), 0,
1441                                        FullName, Ty->getIdentifier()));
1442   if (!Ty->isForwardDecl())
1443     DeferredCompleteTypes.push_back(Ty);
1444   return FwdDeclTI;
1445 }
1446 
1447 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1448   ClassOptions CO = ClassOptions::None | getRecordUniqueNameOption(Ty);
1449   TypeIndex FieldTI;
1450   unsigned FieldCount;
1451   std::tie(FieldTI, std::ignore, FieldCount) = lowerRecordFieldList(Ty);
1452   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1453   std::string FullName =
1454       getFullyQualifiedName(Ty->getScope().resolve(), Ty->getName());
1455 
1456   TypeIndex UnionTI = TypeTable.writeUnion(
1457       UnionRecord(FieldCount, CO, HfaKind::None, FieldTI, SizeInBytes, FullName,
1458                   Ty->getIdentifier()));
1459 
1460   TypeTable.writeUdtSourceLine(UdtSourceLineRecord(
1461       UnionTI, TypeTable.writeStringId(StringIdRecord(
1462                    TypeIndex(0x0), getFullFilepath(Ty->getFile()))),
1463       Ty->getLine()));
1464 
1465   addToUDTs(Ty, UnionTI);
1466 
1467   return UnionTI;
1468 }
1469 
1470 std::tuple<TypeIndex, TypeIndex, unsigned>
1471 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1472   // Manually count members. MSVC appears to count everything that generates a
1473   // field list record. Each individual overload in a method overload group
1474   // contributes to this count, even though the overload group is a single field
1475   // list record.
1476   unsigned MemberCount = 0;
1477   ClassInfo Info = collectClassInfo(Ty);
1478   FieldListRecordBuilder Fields;
1479 
1480   // Create base classes.
1481   for (const DIDerivedType *I : Info.Inheritance) {
1482     if (I->getFlags() & DINode::FlagVirtual) {
1483       // Virtual base.
1484       // FIXME: Emit VBPtrOffset when the frontend provides it.
1485       unsigned VBPtrOffset = 0;
1486       // FIXME: Despite the accessor name, the offset is really in bytes.
1487       unsigned VBTableIndex = I->getOffsetInBits() / 4;
1488       Fields.writeVirtualBaseClass(VirtualBaseClassRecord(
1489           translateAccessFlags(Ty->getTag(), I->getFlags()),
1490           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1491           VBTableIndex));
1492     } else {
1493       assert(I->getOffsetInBits() % 8 == 0 &&
1494              "bases must be on byte boundaries");
1495       Fields.writeBaseClass(BaseClassRecord(
1496           translateAccessFlags(Ty->getTag(), I->getFlags()),
1497           getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8));
1498     }
1499   }
1500 
1501   // Create members.
1502   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1503     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1504     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1505 
1506     if (Member->isStaticMember()) {
1507       Fields.writeStaticDataMember(StaticDataMemberRecord(
1508           translateAccessFlags(Ty->getTag(), Member->getFlags()),
1509           MemberBaseType, Member->getName()));
1510       MemberCount++;
1511       continue;
1512     }
1513 
1514     uint64_t OffsetInBytes = MemberInfo.BaseOffset;
1515 
1516     // FIXME: Handle bitfield type memeber.
1517     OffsetInBytes += Member->getOffsetInBits() / 8;
1518 
1519     Fields.writeDataMember(
1520         DataMemberRecord(translateAccessFlags(Ty->getTag(), Member->getFlags()),
1521                          MemberBaseType, OffsetInBytes, Member->getName()));
1522     MemberCount++;
1523   }
1524 
1525   // Create methods
1526   for (auto &MethodItr : Info.Methods) {
1527     StringRef Name = MethodItr.first->getString();
1528 
1529     std::vector<OneMethodRecord> Methods;
1530     for (const DISubprogram *SP : MethodItr.second) {
1531       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
1532       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
1533 
1534       unsigned VFTableOffset = -1;
1535       if (Introduced)
1536         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
1537 
1538       Methods.push_back(
1539           OneMethodRecord(MethodType, translateMethodKindFlags(SP, Introduced),
1540                           translateMethodOptionFlags(SP),
1541                           translateAccessFlags(Ty->getTag(), SP->getFlags()),
1542                           VFTableOffset, Name));
1543       MemberCount++;
1544     }
1545     assert(Methods.size() > 0 && "Empty methods map entry");
1546     if (Methods.size() == 1)
1547       Fields.writeOneMethod(Methods[0]);
1548     else {
1549       TypeIndex MethodList =
1550           TypeTable.writeMethodOverloadList(MethodOverloadListRecord(Methods));
1551       Fields.writeOverloadedMethod(
1552           OverloadedMethodRecord(Methods.size(), MethodList, Name));
1553     }
1554   }
1555   TypeIndex FieldTI = TypeTable.writeFieldList(Fields);
1556   return std::make_tuple(FieldTI, TypeIndex(), MemberCount);
1557 }
1558 
1559 TypeIndex CodeViewDebug::getVBPTypeIndex() {
1560   if (!VBPType.getIndex()) {
1561     // Make a 'const int *' type.
1562     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
1563     TypeIndex ModifiedTI = TypeTable.writeModifier(MR);
1564 
1565     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1566                                                   : PointerKind::Near32;
1567     PointerMode PM = PointerMode::Pointer;
1568     PointerOptions PO = PointerOptions::None;
1569     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
1570 
1571     VBPType = TypeTable.writePointer(PR);
1572   }
1573 
1574   return VBPType;
1575 }
1576 
1577 struct CodeViewDebug::TypeLoweringScope {
1578   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
1579   ~TypeLoweringScope() {
1580     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
1581     // inner TypeLoweringScopes don't attempt to emit deferred types.
1582     if (CVD.TypeEmissionLevel == 1)
1583       CVD.emitDeferredCompleteTypes();
1584     --CVD.TypeEmissionLevel;
1585   }
1586   CodeViewDebug &CVD;
1587 };
1588 
1589 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
1590   const DIType *Ty = TypeRef.resolve();
1591   const DIType *ClassTy = ClassTyRef.resolve();
1592 
1593   // The null DIType is the void type. Don't try to hash it.
1594   if (!Ty)
1595     return TypeIndex::Void();
1596 
1597   // Check if we've already translated this type. Don't try to do a
1598   // get-or-create style insertion that caches the hash lookup across the
1599   // lowerType call. It will update the TypeIndices map.
1600   auto I = TypeIndices.find({Ty, ClassTy});
1601   if (I != TypeIndices.end())
1602     return I->second;
1603 
1604   TypeIndex TI;
1605   {
1606     TypeLoweringScope S(*this);
1607     TI = lowerType(Ty, ClassTy);
1608     recordTypeIndexForDINode(Ty, TI, ClassTy);
1609   }
1610 
1611   return TI;
1612 }
1613 
1614 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
1615   const DIType *Ty = TypeRef.resolve();
1616 
1617   // The null DIType is the void type. Don't try to hash it.
1618   if (!Ty)
1619     return TypeIndex::Void();
1620 
1621   // If this is a non-record type, the complete type index is the same as the
1622   // normal type index. Just call getTypeIndex.
1623   switch (Ty->getTag()) {
1624   case dwarf::DW_TAG_class_type:
1625   case dwarf::DW_TAG_structure_type:
1626   case dwarf::DW_TAG_union_type:
1627     break;
1628   default:
1629     return getTypeIndex(Ty);
1630   }
1631 
1632   // Check if we've already translated the complete record type.  Lowering a
1633   // complete type should never trigger lowering another complete type, so we
1634   // can reuse the hash table lookup result.
1635   const auto *CTy = cast<DICompositeType>(Ty);
1636   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
1637   if (!InsertResult.second)
1638     return InsertResult.first->second;
1639 
1640   TypeLoweringScope S(*this);
1641 
1642   // Make sure the forward declaration is emitted first. It's unclear if this
1643   // is necessary, but MSVC does it, and we should follow suit until we can show
1644   // otherwise.
1645   TypeIndex FwdDeclTI = getTypeIndex(CTy);
1646 
1647   // Just use the forward decl if we don't have complete type info. This might
1648   // happen if the frontend is using modules and expects the complete definition
1649   // to be emitted elsewhere.
1650   if (CTy->isForwardDecl())
1651     return FwdDeclTI;
1652 
1653   TypeIndex TI;
1654   switch (CTy->getTag()) {
1655   case dwarf::DW_TAG_class_type:
1656   case dwarf::DW_TAG_structure_type:
1657     TI = lowerCompleteTypeClass(CTy);
1658     break;
1659   case dwarf::DW_TAG_union_type:
1660     TI = lowerCompleteTypeUnion(CTy);
1661     break;
1662   default:
1663     llvm_unreachable("not a record");
1664   }
1665 
1666   InsertResult.first->second = TI;
1667   return TI;
1668 }
1669 
1670 /// Emit all the deferred complete record types. Try to do this in FIFO order,
1671 /// and do this until fixpoint, as each complete record type typically references
1672 /// many other record types.
1673 void CodeViewDebug::emitDeferredCompleteTypes() {
1674   SmallVector<const DICompositeType *, 4> TypesToEmit;
1675   while (!DeferredCompleteTypes.empty()) {
1676     std::swap(DeferredCompleteTypes, TypesToEmit);
1677     for (const DICompositeType *RecordTy : TypesToEmit)
1678       getCompleteTypeIndex(RecordTy);
1679     TypesToEmit.clear();
1680   }
1681 }
1682 
1683 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
1684   // LocalSym record, see SymbolRecord.h for more info.
1685   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
1686            *LocalEnd = MMI->getContext().createTempSymbol();
1687   OS.AddComment("Record length");
1688   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
1689   OS.EmitLabel(LocalBegin);
1690 
1691   OS.AddComment("Record kind: S_LOCAL");
1692   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
1693 
1694   LocalSymFlags Flags = LocalSymFlags::None;
1695   if (Var.DIVar->isParameter())
1696     Flags |= LocalSymFlags::IsParameter;
1697   if (Var.DefRanges.empty())
1698     Flags |= LocalSymFlags::IsOptimizedOut;
1699 
1700   OS.AddComment("TypeIndex");
1701   TypeIndex TI = getCompleteTypeIndex(Var.DIVar->getType());
1702   OS.EmitIntValue(TI.getIndex(), 4);
1703   OS.AddComment("Flags");
1704   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
1705   // Truncate the name so we won't overflow the record length field.
1706   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
1707   OS.EmitLabel(LocalEnd);
1708 
1709   // Calculate the on disk prefix of the appropriate def range record. The
1710   // records and on disk formats are described in SymbolRecords.h. BytePrefix
1711   // should be big enough to hold all forms without memory allocation.
1712   SmallString<20> BytePrefix;
1713   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
1714     BytePrefix.clear();
1715     // FIXME: Handle bitpieces.
1716     if (DefRange.StructOffset != 0)
1717       continue;
1718 
1719     if (DefRange.InMemory) {
1720       DefRangeRegisterRelSym Sym(DefRange.CVRegister, 0, DefRange.DataOffset, 0,
1721                                  0, 0, ArrayRef<LocalVariableAddrGap>());
1722       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
1723       BytePrefix +=
1724           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1725       BytePrefix +=
1726           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1727                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1728     } else {
1729       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
1730       // Unclear what matters here.
1731       DefRangeRegisterSym Sym(DefRange.CVRegister, 0, 0, 0, 0,
1732                               ArrayRef<LocalVariableAddrGap>());
1733       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
1734       BytePrefix +=
1735           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
1736       BytePrefix +=
1737           StringRef(reinterpret_cast<const char *>(&Sym.Header),
1738                     sizeof(Sym.Header) - sizeof(LocalVariableAddrRange));
1739     }
1740     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
1741   }
1742 }
1743 
1744 void CodeViewDebug::endFunction(const MachineFunction *MF) {
1745   if (!Asm || !CurFn)  // We haven't created any debug info for this function.
1746     return;
1747 
1748   const Function *GV = MF->getFunction();
1749   assert(FnDebugInfo.count(GV));
1750   assert(CurFn == &FnDebugInfo[GV]);
1751 
1752   collectVariableInfo(GV->getSubprogram());
1753 
1754   DebugHandlerBase::endFunction(MF);
1755 
1756   // Don't emit anything if we don't have any line tables.
1757   if (!CurFn->HaveLineInfo) {
1758     FnDebugInfo.erase(GV);
1759     CurFn = nullptr;
1760     return;
1761   }
1762 
1763   CurFn->End = Asm->getFunctionEnd();
1764 
1765   CurFn = nullptr;
1766 }
1767 
1768 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
1769   DebugHandlerBase::beginInstruction(MI);
1770 
1771   // Ignore DBG_VALUE locations and function prologue.
1772   if (!Asm || MI->isDebugValue() || MI->getFlag(MachineInstr::FrameSetup))
1773     return;
1774   DebugLoc DL = MI->getDebugLoc();
1775   if (DL == PrevInstLoc || !DL)
1776     return;
1777   maybeRecordLocation(DL, Asm->MF);
1778 }
1779 
1780 MCSymbol *CodeViewDebug::beginCVSubsection(ModuleSubstreamKind Kind) {
1781   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
1782            *EndLabel = MMI->getContext().createTempSymbol();
1783   OS.EmitIntValue(unsigned(Kind), 4);
1784   OS.AddComment("Subsection size");
1785   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
1786   OS.EmitLabel(BeginLabel);
1787   return EndLabel;
1788 }
1789 
1790 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
1791   OS.EmitLabel(EndLabel);
1792   // Every subsection must be aligned to a 4-byte boundary.
1793   OS.EmitValueToAlignment(4);
1794 }
1795 
1796 void CodeViewDebug::emitDebugInfoForUDTs(
1797     ArrayRef<std::pair<std::string, TypeIndex>> UDTs) {
1798   for (const std::pair<std::string, codeview::TypeIndex> &UDT : UDTs) {
1799     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
1800              *UDTRecordEnd = MMI->getContext().createTempSymbol();
1801     OS.AddComment("Record length");
1802     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
1803     OS.EmitLabel(UDTRecordBegin);
1804 
1805     OS.AddComment("Record kind: S_UDT");
1806     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
1807 
1808     OS.AddComment("Type");
1809     OS.EmitIntValue(UDT.second.getIndex(), 4);
1810 
1811     emitNullTerminatedSymbolName(OS, UDT.first);
1812     OS.EmitLabel(UDTRecordEnd);
1813   }
1814 }
1815 
1816 void CodeViewDebug::emitDebugInfoForGlobals() {
1817   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1818   for (const MDNode *Node : CUs->operands()) {
1819     const auto *CU = cast<DICompileUnit>(Node);
1820 
1821     // First, emit all globals that are not in a comdat in a single symbol
1822     // substream. MSVC doesn't like it if the substream is empty, so only open
1823     // it if we have at least one global to emit.
1824     switchToDebugSectionForSymbol(nullptr);
1825     MCSymbol *EndLabel = nullptr;
1826     for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1827       if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
1828         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
1829           if (!EndLabel) {
1830             OS.AddComment("Symbol subsection for globals");
1831             EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1832           }
1833           emitDebugInfoForGlobal(G, Asm->getSymbol(GV));
1834         }
1835       }
1836     }
1837     if (EndLabel)
1838       endCVSubsection(EndLabel);
1839 
1840     // Second, emit each global that is in a comdat into its own .debug$S
1841     // section along with its own symbol substream.
1842     for (const DIGlobalVariable *G : CU->getGlobalVariables()) {
1843       if (const auto *GV = dyn_cast_or_null<GlobalVariable>(G->getVariable())) {
1844         if (GV->hasComdat()) {
1845           MCSymbol *GVSym = Asm->getSymbol(GV);
1846           OS.AddComment("Symbol subsection for " +
1847                         Twine(GlobalValue::getRealLinkageName(GV->getName())));
1848           switchToDebugSectionForSymbol(GVSym);
1849           EndLabel = beginCVSubsection(ModuleSubstreamKind::Symbols);
1850           emitDebugInfoForGlobal(G, GVSym);
1851           endCVSubsection(EndLabel);
1852         }
1853       }
1854     }
1855   }
1856 }
1857 
1858 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
1859   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
1860   for (const MDNode *Node : CUs->operands()) {
1861     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
1862       if (DIType *RT = dyn_cast<DIType>(Ty)) {
1863         getTypeIndex(RT);
1864         // FIXME: Add to global/local DTU list.
1865       }
1866     }
1867   }
1868 }
1869 
1870 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
1871                                            MCSymbol *GVSym) {
1872   // DataSym record, see SymbolRecord.h for more info.
1873   // FIXME: Thread local data, etc
1874   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
1875            *DataEnd = MMI->getContext().createTempSymbol();
1876   OS.AddComment("Record length");
1877   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
1878   OS.EmitLabel(DataBegin);
1879   OS.AddComment("Record kind: S_GDATA32");
1880   OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
1881   OS.AddComment("Type");
1882   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
1883   OS.AddComment("DataOffset");
1884   OS.EmitCOFFSecRel32(GVSym);
1885   OS.AddComment("Segment");
1886   OS.EmitCOFFSectionIndex(GVSym);
1887   OS.AddComment("Name");
1888   emitNullTerminatedSymbolName(OS, DIGV->getName());
1889   OS.EmitLabel(DataEnd);
1890 }
1891