xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp (revision c14a5a8800a0f7a007f8cd197b4cad4d26a78f8c)
1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing Microsoft CodeView debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "CodeViewDebug.h"
14 #include "DwarfExpression.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/TinyPtrVector.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/BinaryFormat/COFF.h"
30 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/CodeGen/AsmPrinter.h"
32 #include "llvm/CodeGen/LexicalScopes.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/TargetFrameLowering.h"
39 #include "llvm/CodeGen/TargetRegisterInfo.h"
40 #include "llvm/CodeGen/TargetSubtargetInfo.h"
41 #include "llvm/Config/llvm-config.h"
42 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
43 #include "llvm/DebugInfo/CodeView/CodeView.h"
44 #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
45 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
46 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
47 #include "llvm/DebugInfo/CodeView/EnumTables.h"
48 #include "llvm/DebugInfo/CodeView/Line.h"
49 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
50 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
51 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
52 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
53 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
54 #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugInfoMetadata.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/GlobalVariable.h"
62 #include "llvm/IR/Metadata.h"
63 #include "llvm/IR/Module.h"
64 #include "llvm/MC/MCAsmInfo.h"
65 #include "llvm/MC/MCContext.h"
66 #include "llvm/MC/MCSectionCOFF.h"
67 #include "llvm/MC/MCStreamer.h"
68 #include "llvm/MC/MCSymbol.h"
69 #include "llvm/Support/BinaryByteStream.h"
70 #include "llvm/Support/BinaryStreamReader.h"
71 #include "llvm/Support/BinaryStreamWriter.h"
72 #include "llvm/Support/Casting.h"
73 #include "llvm/Support/CommandLine.h"
74 #include "llvm/Support/Compiler.h"
75 #include "llvm/Support/Endian.h"
76 #include "llvm/Support/Error.h"
77 #include "llvm/Support/ErrorHandling.h"
78 #include "llvm/Support/FormatVariadic.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/SMLoc.h"
81 #include "llvm/Support/ScopedPrinter.h"
82 #include "llvm/Target/TargetLoweringObjectFile.h"
83 #include "llvm/Target/TargetMachine.h"
84 #include <algorithm>
85 #include <cassert>
86 #include <cctype>
87 #include <cstddef>
88 #include <cstdint>
89 #include <iterator>
90 #include <limits>
91 #include <string>
92 #include <utility>
93 #include <vector>
94 
95 using namespace llvm;
96 using namespace llvm::codeview;
97 
98 namespace {
99 class CVMCAdapter : public CodeViewRecordStreamer {
100 public:
101   CVMCAdapter(MCStreamer &OS) : OS(&OS) {}
102 
103   void EmitBytes(StringRef Data) { OS->EmitBytes(Data); }
104 
105   void EmitIntValue(uint64_t Value, unsigned Size) {
106     OS->EmitIntValueInHex(Value, Size);
107   }
108 
109   void EmitBinaryData(StringRef Data) { OS->EmitBinaryData(Data); }
110 
111   void AddComment(const Twine &T) { OS->AddComment(T); }
112 
113 private:
114   MCStreamer *OS = nullptr;
115 };
116 } // namespace
117 
118 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
119   switch (Type) {
120   case Triple::ArchType::x86:
121     return CPUType::Pentium3;
122   case Triple::ArchType::x86_64:
123     return CPUType::X64;
124   case Triple::ArchType::thumb:
125     return CPUType::Thumb;
126   case Triple::ArchType::aarch64:
127     return CPUType::ARM64;
128   default:
129     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
130   }
131 }
132 
133 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
134     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
135   // If module doesn't have named metadata anchors or COFF debug section
136   // is not available, skip any debug info related stuff.
137   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
138       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
139     Asm = nullptr;
140     MMI->setDebugInfoAvailability(false);
141     return;
142   }
143   // Tell MMI that we have debug info.
144   MMI->setDebugInfoAvailability(true);
145 
146   TheCPU =
147       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
148 
149   collectGlobalVariableInfo();
150 
151   // Check if we should emit type record hashes.
152   ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
153       MMI->getModule()->getModuleFlag("CodeViewGHash"));
154   EmitDebugGlobalHashes = GH && !GH->isZero();
155 }
156 
157 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
158   std::string &Filepath = FileToFilepathMap[File];
159   if (!Filepath.empty())
160     return Filepath;
161 
162   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
163 
164   // If this is a Unix-style path, just use it as is. Don't try to canonicalize
165   // it textually because one of the path components could be a symlink.
166   if (Dir.startswith("/") || Filename.startswith("/")) {
167     if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
168       return Filename;
169     Filepath = Dir;
170     if (Dir.back() != '/')
171       Filepath += '/';
172     Filepath += Filename;
173     return Filepath;
174   }
175 
176   // Clang emits directory and relative filename info into the IR, but CodeView
177   // operates on full paths.  We could change Clang to emit full paths too, but
178   // that would increase the IR size and probably not needed for other users.
179   // For now, just concatenate and canonicalize the path here.
180   if (Filename.find(':') == 1)
181     Filepath = Filename;
182   else
183     Filepath = (Dir + "\\" + Filename).str();
184 
185   // Canonicalize the path.  We have to do it textually because we may no longer
186   // have access the file in the filesystem.
187   // First, replace all slashes with backslashes.
188   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
189 
190   // Remove all "\.\" with "\".
191   size_t Cursor = 0;
192   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
193     Filepath.erase(Cursor, 2);
194 
195   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
196   // path should be well-formatted, e.g. start with a drive letter, etc.
197   Cursor = 0;
198   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
199     // Something's wrong if the path starts with "\..\", abort.
200     if (Cursor == 0)
201       break;
202 
203     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
204     if (PrevSlash == std::string::npos)
205       // Something's wrong, abort.
206       break;
207 
208     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
209     // The next ".." might be following the one we've just erased.
210     Cursor = PrevSlash;
211   }
212 
213   // Remove all duplicate backslashes.
214   Cursor = 0;
215   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
216     Filepath.erase(Cursor, 1);
217 
218   return Filepath;
219 }
220 
221 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
222   StringRef FullPath = getFullFilepath(F);
223   unsigned NextId = FileIdMap.size() + 1;
224   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
225   if (Insertion.second) {
226     // We have to compute the full filepath and emit a .cv_file directive.
227     ArrayRef<uint8_t> ChecksumAsBytes;
228     FileChecksumKind CSKind = FileChecksumKind::None;
229     if (F->getChecksum()) {
230       std::string Checksum = fromHex(F->getChecksum()->Value);
231       void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
232       memcpy(CKMem, Checksum.data(), Checksum.size());
233       ChecksumAsBytes = ArrayRef<uint8_t>(
234           reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
235       switch (F->getChecksum()->Kind) {
236       case DIFile::CSK_MD5:  CSKind = FileChecksumKind::MD5; break;
237       case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
238       }
239     }
240     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
241                                           static_cast<unsigned>(CSKind));
242     (void)Success;
243     assert(Success && ".cv_file directive failed");
244   }
245   return Insertion.first->second;
246 }
247 
248 CodeViewDebug::InlineSite &
249 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
250                              const DISubprogram *Inlinee) {
251   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
252   InlineSite *Site = &SiteInsertion.first->second;
253   if (SiteInsertion.second) {
254     unsigned ParentFuncId = CurFn->FuncId;
255     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
256       ParentFuncId =
257           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
258               .SiteFuncId;
259 
260     Site->SiteFuncId = NextFuncId++;
261     OS.EmitCVInlineSiteIdDirective(
262         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
263         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
264     Site->Inlinee = Inlinee;
265     InlinedSubprograms.insert(Inlinee);
266     getFuncIdForSubprogram(Inlinee);
267   }
268   return *Site;
269 }
270 
271 static StringRef getPrettyScopeName(const DIScope *Scope) {
272   StringRef ScopeName = Scope->getName();
273   if (!ScopeName.empty())
274     return ScopeName;
275 
276   switch (Scope->getTag()) {
277   case dwarf::DW_TAG_enumeration_type:
278   case dwarf::DW_TAG_class_type:
279   case dwarf::DW_TAG_structure_type:
280   case dwarf::DW_TAG_union_type:
281     return "<unnamed-tag>";
282   case dwarf::DW_TAG_namespace:
283     return "`anonymous namespace'";
284   }
285 
286   return StringRef();
287 }
288 
289 static const DISubprogram *getQualifiedNameComponents(
290     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
291   const DISubprogram *ClosestSubprogram = nullptr;
292   while (Scope != nullptr) {
293     if (ClosestSubprogram == nullptr)
294       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
295     StringRef ScopeName = getPrettyScopeName(Scope);
296     if (!ScopeName.empty())
297       QualifiedNameComponents.push_back(ScopeName);
298     Scope = Scope->getScope();
299   }
300   return ClosestSubprogram;
301 }
302 
303 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
304                                     StringRef TypeName) {
305   std::string FullyQualifiedName;
306   for (StringRef QualifiedNameComponent :
307        llvm::reverse(QualifiedNameComponents)) {
308     FullyQualifiedName.append(QualifiedNameComponent);
309     FullyQualifiedName.append("::");
310   }
311   FullyQualifiedName.append(TypeName);
312   return FullyQualifiedName;
313 }
314 
315 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
316   SmallVector<StringRef, 5> QualifiedNameComponents;
317   getQualifiedNameComponents(Scope, QualifiedNameComponents);
318   return getQualifiedName(QualifiedNameComponents, Name);
319 }
320 
321 struct CodeViewDebug::TypeLoweringScope {
322   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
323   ~TypeLoweringScope() {
324     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
325     // inner TypeLoweringScopes don't attempt to emit deferred types.
326     if (CVD.TypeEmissionLevel == 1)
327       CVD.emitDeferredCompleteTypes();
328     --CVD.TypeEmissionLevel;
329   }
330   CodeViewDebug &CVD;
331 };
332 
333 static std::string getFullyQualifiedName(const DIScope *Ty) {
334   const DIScope *Scope = Ty->getScope();
335   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
336 }
337 
338 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
339   // No scope means global scope and that uses the zero index.
340   if (!Scope || isa<DIFile>(Scope))
341     return TypeIndex();
342 
343   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
344 
345   // Check if we've already translated this scope.
346   auto I = TypeIndices.find({Scope, nullptr});
347   if (I != TypeIndices.end())
348     return I->second;
349 
350   // Build the fully qualified name of the scope.
351   std::string ScopeName = getFullyQualifiedName(Scope);
352   StringIdRecord SID(TypeIndex(), ScopeName);
353   auto TI = TypeTable.writeLeafType(SID);
354   return recordTypeIndexForDINode(Scope, TI);
355 }
356 
357 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
358   assert(SP);
359 
360   // Check if we've already translated this subprogram.
361   auto I = TypeIndices.find({SP, nullptr});
362   if (I != TypeIndices.end())
363     return I->second;
364 
365   // The display name includes function template arguments. Drop them to match
366   // MSVC.
367   StringRef DisplayName = SP->getName().split('<').first;
368 
369   const DIScope *Scope = SP->getScope();
370   TypeIndex TI;
371   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
372     // If the scope is a DICompositeType, then this must be a method. Member
373     // function types take some special handling, and require access to the
374     // subprogram.
375     TypeIndex ClassType = getTypeIndex(Class);
376     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
377                                DisplayName);
378     TI = TypeTable.writeLeafType(MFuncId);
379   } else {
380     // Otherwise, this must be a free function.
381     TypeIndex ParentScope = getScopeIndex(Scope);
382     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
383     TI = TypeTable.writeLeafType(FuncId);
384   }
385 
386   return recordTypeIndexForDINode(SP, TI);
387 }
388 
389 static bool isNonTrivial(const DICompositeType *DCTy) {
390   return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
391 }
392 
393 static FunctionOptions
394 getFunctionOptions(const DISubroutineType *Ty,
395                    const DICompositeType *ClassTy = nullptr,
396                    StringRef SPName = StringRef("")) {
397   FunctionOptions FO = FunctionOptions::None;
398   const DIType *ReturnTy = nullptr;
399   if (auto TypeArray = Ty->getTypeArray()) {
400     if (TypeArray.size())
401       ReturnTy = TypeArray[0];
402   }
403 
404   if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
405     if (isNonTrivial(ReturnDCTy))
406       FO |= FunctionOptions::CxxReturnUdt;
407   }
408 
409   // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
410   if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
411     FO |= FunctionOptions::Constructor;
412 
413   // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
414 
415   }
416   return FO;
417 }
418 
419 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
420                                                const DICompositeType *Class) {
421   // Always use the method declaration as the key for the function type. The
422   // method declaration contains the this adjustment.
423   if (SP->getDeclaration())
424     SP = SP->getDeclaration();
425   assert(!SP->getDeclaration() && "should use declaration as key");
426 
427   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
428   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
429   auto I = TypeIndices.find({SP, Class});
430   if (I != TypeIndices.end())
431     return I->second;
432 
433   // Make sure complete type info for the class is emitted *after* the member
434   // function type, as the complete class type is likely to reference this
435   // member function type.
436   TypeLoweringScope S(*this);
437   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
438 
439   FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
440   TypeIndex TI = lowerTypeMemberFunction(
441       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
442   return recordTypeIndexForDINode(SP, TI, Class);
443 }
444 
445 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
446                                                   TypeIndex TI,
447                                                   const DIType *ClassTy) {
448   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
449   (void)InsertResult;
450   assert(InsertResult.second && "DINode was already assigned a type index");
451   return TI;
452 }
453 
454 unsigned CodeViewDebug::getPointerSizeInBytes() {
455   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
456 }
457 
458 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
459                                         const LexicalScope *LS) {
460   if (const DILocation *InlinedAt = LS->getInlinedAt()) {
461     // This variable was inlined. Associate it with the InlineSite.
462     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
463     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
464     Site.InlinedLocals.emplace_back(Var);
465   } else {
466     // This variable goes into the corresponding lexical scope.
467     ScopeVariables[LS].emplace_back(Var);
468   }
469 }
470 
471 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
472                                const DILocation *Loc) {
473   auto B = Locs.begin(), E = Locs.end();
474   if (std::find(B, E, Loc) == E)
475     Locs.push_back(Loc);
476 }
477 
478 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
479                                         const MachineFunction *MF) {
480   // Skip this instruction if it has the same location as the previous one.
481   if (!DL || DL == PrevInstLoc)
482     return;
483 
484   const DIScope *Scope = DL.get()->getScope();
485   if (!Scope)
486     return;
487 
488   // Skip this line if it is longer than the maximum we can record.
489   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
490   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
491       LI.isNeverStepInto())
492     return;
493 
494   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
495   if (CI.getStartColumn() != DL.getCol())
496     return;
497 
498   if (!CurFn->HaveLineInfo)
499     CurFn->HaveLineInfo = true;
500   unsigned FileId = 0;
501   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
502     FileId = CurFn->LastFileId;
503   else
504     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
505   PrevInstLoc = DL;
506 
507   unsigned FuncId = CurFn->FuncId;
508   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
509     const DILocation *Loc = DL.get();
510 
511     // If this location was actually inlined from somewhere else, give it the ID
512     // of the inline call site.
513     FuncId =
514         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
515 
516     // Ensure we have links in the tree of inline call sites.
517     bool FirstLoc = true;
518     while ((SiteLoc = Loc->getInlinedAt())) {
519       InlineSite &Site =
520           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
521       if (!FirstLoc)
522         addLocIfNotPresent(Site.ChildSites, Loc);
523       FirstLoc = false;
524       Loc = SiteLoc;
525     }
526     addLocIfNotPresent(CurFn->ChildSites, Loc);
527   }
528 
529   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
530                         /*PrologueEnd=*/false, /*IsStmt=*/false,
531                         DL->getFilename(), SMLoc());
532 }
533 
534 void CodeViewDebug::emitCodeViewMagicVersion() {
535   OS.EmitValueToAlignment(4);
536   OS.AddComment("Debug section magic");
537   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
538 }
539 
540 void CodeViewDebug::endModule() {
541   if (!Asm || !MMI->hasDebugInfo())
542     return;
543 
544   assert(Asm != nullptr);
545 
546   // The COFF .debug$S section consists of several subsections, each starting
547   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
548   // of the payload followed by the payload itself.  The subsections are 4-byte
549   // aligned.
550 
551   // Use the generic .debug$S section, and make a subsection for all the inlined
552   // subprograms.
553   switchToDebugSectionForSymbol(nullptr);
554 
555   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
556   emitCompilerInformation();
557   endCVSubsection(CompilerInfo);
558 
559   emitInlineeLinesSubsection();
560 
561   // Emit per-function debug information.
562   for (auto &P : FnDebugInfo)
563     if (!P.first->isDeclarationForLinker())
564       emitDebugInfoForFunction(P.first, *P.second);
565 
566   // Emit global variable debug information.
567   setCurrentSubprogram(nullptr);
568   emitDebugInfoForGlobals();
569 
570   // Emit retained types.
571   emitDebugInfoForRetainedTypes();
572 
573   // Switch back to the generic .debug$S section after potentially processing
574   // comdat symbol sections.
575   switchToDebugSectionForSymbol(nullptr);
576 
577   // Emit UDT records for any types used by global variables.
578   if (!GlobalUDTs.empty()) {
579     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
580     emitDebugInfoForUDTs(GlobalUDTs);
581     endCVSubsection(SymbolsEnd);
582   }
583 
584   // This subsection holds a file index to offset in string table table.
585   OS.AddComment("File index to string table offset subsection");
586   OS.EmitCVFileChecksumsDirective();
587 
588   // This subsection holds the string table.
589   OS.AddComment("String table");
590   OS.EmitCVStringTableDirective();
591 
592   // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
593   // subsection in the generic .debug$S section at the end. There is no
594   // particular reason for this ordering other than to match MSVC.
595   emitBuildInfo();
596 
597   // Emit type information and hashes last, so that any types we translate while
598   // emitting function info are included.
599   emitTypeInformation();
600 
601   if (EmitDebugGlobalHashes)
602     emitTypeGlobalHashes();
603 
604   clear();
605 }
606 
607 static void
608 emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
609                              unsigned MaxFixedRecordLength = 0xF00) {
610   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
611   // after a fixed length portion of the record. The fixed length portion should
612   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
613   // overall record size is less than the maximum allowed.
614   SmallString<32> NullTerminatedString(
615       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
616   NullTerminatedString.push_back('\0');
617   OS.EmitBytes(NullTerminatedString);
618 }
619 
620 static StringRef getTypeLeafName(TypeLeafKind TypeKind) {
621   for (const EnumEntry<TypeLeafKind> &EE : getTypeLeafNames())
622     if (EE.Value == TypeKind)
623       return EE.Name;
624   return "";
625 }
626 
627 void CodeViewDebug::emitTypeInformation() {
628   if (TypeTable.empty())
629     return;
630 
631   // Start the .debug$T or .debug$P section with 0x4.
632   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
633   emitCodeViewMagicVersion();
634 
635   SmallString<8> CommentPrefix;
636   if (OS.isVerboseAsm()) {
637     CommentPrefix += '\t';
638     CommentPrefix += Asm->MAI->getCommentString();
639     CommentPrefix += ' ';
640   }
641 
642   TypeTableCollection Table(TypeTable.records());
643   SmallString<512> CommentBlock;
644   raw_svector_ostream CommentOS(CommentBlock);
645   std::unique_ptr<ScopedPrinter> SP;
646   std::unique_ptr<TypeDumpVisitor> TDV;
647   TypeVisitorCallbackPipeline Pipeline;
648 
649   if (OS.isVerboseAsm()) {
650     // To construct block comment describing the type record for readability.
651     SP = llvm::make_unique<ScopedPrinter>(CommentOS);
652     SP->setPrefix(CommentPrefix);
653     TDV = llvm::make_unique<TypeDumpVisitor>(Table, SP.get(), false);
654     Pipeline.addCallbackToPipeline(*TDV);
655   }
656 
657   // To emit type record using Codeview MCStreamer adapter
658   CVMCAdapter CVMCOS(OS);
659   TypeRecordMapping typeMapping(CVMCOS);
660   Pipeline.addCallbackToPipeline(typeMapping);
661 
662   Optional<TypeIndex> B = Table.getFirst();
663   while (B) {
664     // This will fail if the record data is invalid.
665     CVType Record = Table.getType(*B);
666 
667     CommentBlock.clear();
668 
669     auto RecordLen = Record.length();
670     auto RecordKind = Record.kind();
671     if (OS.isVerboseAsm())
672       CVMCOS.AddComment("Record length");
673     CVMCOS.EmitIntValue(RecordLen - 2, 2);
674     if (OS.isVerboseAsm())
675       CVMCOS.AddComment("Record kind: " + getTypeLeafName(RecordKind));
676     CVMCOS.EmitIntValue(RecordKind, sizeof(RecordKind));
677 
678     Error E = codeview::visitTypeRecord(Record, *B, Pipeline);
679 
680     if (E) {
681       logAllUnhandledErrors(std::move(E), errs(), "error: ");
682       llvm_unreachable("produced malformed type record");
683     }
684 
685     if (OS.isVerboseAsm()) {
686       // emitRawComment will insert its own tab and comment string before
687       // the first line, so strip off our first one. It also prints its own
688       // newline.
689       OS.emitRawComment(
690           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
691     }
692     B = Table.getNext(*B);
693   }
694 }
695 
696 void CodeViewDebug::emitTypeGlobalHashes() {
697   if (TypeTable.empty())
698     return;
699 
700   // Start the .debug$H section with the version and hash algorithm, currently
701   // hardcoded to version 0, SHA1.
702   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
703 
704   OS.EmitValueToAlignment(4);
705   OS.AddComment("Magic");
706   OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
707   OS.AddComment("Section Version");
708   OS.EmitIntValue(0, 2);
709   OS.AddComment("Hash Algorithm");
710   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
711 
712   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
713   for (const auto &GHR : TypeTable.hashes()) {
714     if (OS.isVerboseAsm()) {
715       // Emit an EOL-comment describing which TypeIndex this hash corresponds
716       // to, as well as the stringified SHA1 hash.
717       SmallString<32> Comment;
718       raw_svector_ostream CommentOS(Comment);
719       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
720       OS.AddComment(Comment);
721       ++TI;
722     }
723     assert(GHR.Hash.size() == 8);
724     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
725                 GHR.Hash.size());
726     OS.EmitBinaryData(S);
727   }
728 }
729 
730 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
731   switch (DWLang) {
732   case dwarf::DW_LANG_C:
733   case dwarf::DW_LANG_C89:
734   case dwarf::DW_LANG_C99:
735   case dwarf::DW_LANG_C11:
736   case dwarf::DW_LANG_ObjC:
737     return SourceLanguage::C;
738   case dwarf::DW_LANG_C_plus_plus:
739   case dwarf::DW_LANG_C_plus_plus_03:
740   case dwarf::DW_LANG_C_plus_plus_11:
741   case dwarf::DW_LANG_C_plus_plus_14:
742     return SourceLanguage::Cpp;
743   case dwarf::DW_LANG_Fortran77:
744   case dwarf::DW_LANG_Fortran90:
745   case dwarf::DW_LANG_Fortran03:
746   case dwarf::DW_LANG_Fortran08:
747     return SourceLanguage::Fortran;
748   case dwarf::DW_LANG_Pascal83:
749     return SourceLanguage::Pascal;
750   case dwarf::DW_LANG_Cobol74:
751   case dwarf::DW_LANG_Cobol85:
752     return SourceLanguage::Cobol;
753   case dwarf::DW_LANG_Java:
754     return SourceLanguage::Java;
755   case dwarf::DW_LANG_D:
756     return SourceLanguage::D;
757   case dwarf::DW_LANG_Swift:
758     return SourceLanguage::Swift;
759   default:
760     // There's no CodeView representation for this language, and CV doesn't
761     // have an "unknown" option for the language field, so we'll use MASM,
762     // as it's very low level.
763     return SourceLanguage::Masm;
764   }
765 }
766 
767 namespace {
768 struct Version {
769   int Part[4];
770 };
771 } // end anonymous namespace
772 
773 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
774 // the version number.
775 static Version parseVersion(StringRef Name) {
776   Version V = {{0}};
777   int N = 0;
778   for (const char C : Name) {
779     if (isdigit(C)) {
780       V.Part[N] *= 10;
781       V.Part[N] += C - '0';
782     } else if (C == '.') {
783       ++N;
784       if (N >= 4)
785         return V;
786     } else if (N > 0)
787       return V;
788   }
789   return V;
790 }
791 
792 void CodeViewDebug::emitCompilerInformation() {
793   MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
794   uint32_t Flags = 0;
795 
796   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
797   const MDNode *Node = *CUs->operands().begin();
798   const auto *CU = cast<DICompileUnit>(Node);
799 
800   // The low byte of the flags indicates the source language.
801   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
802   // TODO:  Figure out which other flags need to be set.
803 
804   OS.AddComment("Flags and language");
805   OS.EmitIntValue(Flags, 4);
806 
807   OS.AddComment("CPUType");
808   OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
809 
810   StringRef CompilerVersion = CU->getProducer();
811   Version FrontVer = parseVersion(CompilerVersion);
812   OS.AddComment("Frontend version");
813   for (int N = 0; N < 4; ++N)
814     OS.EmitIntValue(FrontVer.Part[N], 2);
815 
816   // Some Microsoft tools, like Binscope, expect a backend version number of at
817   // least 8.something, so we'll coerce the LLVM version into a form that
818   // guarantees it'll be big enough without really lying about the version.
819   int Major = 1000 * LLVM_VERSION_MAJOR +
820               10 * LLVM_VERSION_MINOR +
821               LLVM_VERSION_PATCH;
822   // Clamp it for builds that use unusually large version numbers.
823   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
824   Version BackVer = {{ Major, 0, 0, 0 }};
825   OS.AddComment("Backend version");
826   for (int N = 0; N < 4; ++N)
827     OS.EmitIntValue(BackVer.Part[N], 2);
828 
829   OS.AddComment("Null-terminated compiler version string");
830   emitNullTerminatedSymbolName(OS, CompilerVersion);
831 
832   endSymbolRecord(CompilerEnd);
833 }
834 
835 static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
836                                     StringRef S) {
837   StringIdRecord SIR(TypeIndex(0x0), S);
838   return TypeTable.writeLeafType(SIR);
839 }
840 
841 void CodeViewDebug::emitBuildInfo() {
842   // First, make LF_BUILDINFO. It's a sequence of strings with various bits of
843   // build info. The known prefix is:
844   // - Absolute path of current directory
845   // - Compiler path
846   // - Main source file path, relative to CWD or absolute
847   // - Type server PDB file
848   // - Canonical compiler command line
849   // If frontend and backend compilation are separated (think llc or LTO), it's
850   // not clear if the compiler path should refer to the executable for the
851   // frontend or the backend. Leave it blank for now.
852   TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
853   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
854   const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
855   const auto *CU = cast<DICompileUnit>(Node);
856   const DIFile *MainSourceFile = CU->getFile();
857   BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
858       getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
859   BuildInfoArgs[BuildInfoRecord::SourceFile] =
860       getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
861   // FIXME: Path to compiler and command line. PDB is intentionally blank unless
862   // we implement /Zi type servers.
863   BuildInfoRecord BIR(BuildInfoArgs);
864   TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
865 
866   // Make a new .debug$S subsection for the S_BUILDINFO record, which points
867   // from the module symbols into the type stream.
868   MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
869   MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
870   OS.AddComment("LF_BUILDINFO index");
871   OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
872   endSymbolRecord(BIEnd);
873   endCVSubsection(BISubsecEnd);
874 }
875 
876 void CodeViewDebug::emitInlineeLinesSubsection() {
877   if (InlinedSubprograms.empty())
878     return;
879 
880   OS.AddComment("Inlinee lines subsection");
881   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
882 
883   // We emit the checksum info for files.  This is used by debuggers to
884   // determine if a pdb matches the source before loading it.  Visual Studio,
885   // for instance, will display a warning that the breakpoints are not valid if
886   // the pdb does not match the source.
887   OS.AddComment("Inlinee lines signature");
888   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
889 
890   for (const DISubprogram *SP : InlinedSubprograms) {
891     assert(TypeIndices.count({SP, nullptr}));
892     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
893 
894     OS.AddBlankLine();
895     unsigned FileId = maybeRecordFile(SP->getFile());
896     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
897                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
898     OS.AddBlankLine();
899     OS.AddComment("Type index of inlined function");
900     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
901     OS.AddComment("Offset into filechecksum table");
902     OS.EmitCVFileChecksumOffsetDirective(FileId);
903     OS.AddComment("Starting line number");
904     OS.EmitIntValue(SP->getLine(), 4);
905   }
906 
907   endCVSubsection(InlineEnd);
908 }
909 
910 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
911                                         const DILocation *InlinedAt,
912                                         const InlineSite &Site) {
913   assert(TypeIndices.count({Site.Inlinee, nullptr}));
914   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
915 
916   // SymbolRecord
917   MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
918 
919   OS.AddComment("PtrParent");
920   OS.EmitIntValue(0, 4);
921   OS.AddComment("PtrEnd");
922   OS.EmitIntValue(0, 4);
923   OS.AddComment("Inlinee type index");
924   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
925 
926   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
927   unsigned StartLineNum = Site.Inlinee->getLine();
928 
929   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
930                                     FI.Begin, FI.End);
931 
932   endSymbolRecord(InlineEnd);
933 
934   emitLocalVariableList(FI, Site.InlinedLocals);
935 
936   // Recurse on child inlined call sites before closing the scope.
937   for (const DILocation *ChildSite : Site.ChildSites) {
938     auto I = FI.InlineSites.find(ChildSite);
939     assert(I != FI.InlineSites.end() &&
940            "child site not in function inline site map");
941     emitInlinedCallSite(FI, ChildSite, I->second);
942   }
943 
944   // Close the scope.
945   emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
946 }
947 
948 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
949   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
950   // comdat key. A section may be comdat because of -ffunction-sections or
951   // because it is comdat in the IR.
952   MCSectionCOFF *GVSec =
953       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
954   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
955 
956   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
957       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
958   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
959 
960   OS.SwitchSection(DebugSec);
961 
962   // Emit the magic version number if this is the first time we've switched to
963   // this section.
964   if (ComdatDebugSections.insert(DebugSec).second)
965     emitCodeViewMagicVersion();
966 }
967 
968 // Emit an S_THUNK32/S_END symbol pair for a thunk routine.
969 // The only supported thunk ordinal is currently the standard type.
970 void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
971                                           FunctionInfo &FI,
972                                           const MCSymbol *Fn) {
973   std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
974   const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
975 
976   OS.AddComment("Symbol subsection for " + Twine(FuncName));
977   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
978 
979   // Emit S_THUNK32
980   MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
981   OS.AddComment("PtrParent");
982   OS.EmitIntValue(0, 4);
983   OS.AddComment("PtrEnd");
984   OS.EmitIntValue(0, 4);
985   OS.AddComment("PtrNext");
986   OS.EmitIntValue(0, 4);
987   OS.AddComment("Thunk section relative address");
988   OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
989   OS.AddComment("Thunk section index");
990   OS.EmitCOFFSectionIndex(Fn);
991   OS.AddComment("Code size");
992   OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
993   OS.AddComment("Ordinal");
994   OS.EmitIntValue(unsigned(ordinal), 1);
995   OS.AddComment("Function name");
996   emitNullTerminatedSymbolName(OS, FuncName);
997   // Additional fields specific to the thunk ordinal would go here.
998   endSymbolRecord(ThunkRecordEnd);
999 
1000   // Local variables/inlined routines are purposely omitted here.  The point of
1001   // marking this as a thunk is so Visual Studio will NOT stop in this routine.
1002 
1003   // Emit S_PROC_ID_END
1004   emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1005 
1006   endCVSubsection(SymbolsEnd);
1007 }
1008 
1009 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
1010                                              FunctionInfo &FI) {
1011   // For each function there is a separate subsection which holds the PC to
1012   // file:line table.
1013   const MCSymbol *Fn = Asm->getSymbol(GV);
1014   assert(Fn);
1015 
1016   // Switch to the to a comdat section, if appropriate.
1017   switchToDebugSectionForSymbol(Fn);
1018 
1019   std::string FuncName;
1020   auto *SP = GV->getSubprogram();
1021   assert(SP);
1022   setCurrentSubprogram(SP);
1023 
1024   if (SP->isThunk()) {
1025     emitDebugInfoForThunk(GV, FI, Fn);
1026     return;
1027   }
1028 
1029   // If we have a display name, build the fully qualified name by walking the
1030   // chain of scopes.
1031   if (!SP->getName().empty())
1032     FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
1033 
1034   // If our DISubprogram name is empty, use the mangled name.
1035   if (FuncName.empty())
1036     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
1037 
1038   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
1039   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
1040     OS.EmitCVFPOData(Fn);
1041 
1042   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
1043   OS.AddComment("Symbol subsection for " + Twine(FuncName));
1044   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
1045   {
1046     SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
1047                                                 : SymbolKind::S_GPROC32_ID;
1048     MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
1049 
1050     // These fields are filled in by tools like CVPACK which run after the fact.
1051     OS.AddComment("PtrParent");
1052     OS.EmitIntValue(0, 4);
1053     OS.AddComment("PtrEnd");
1054     OS.EmitIntValue(0, 4);
1055     OS.AddComment("PtrNext");
1056     OS.EmitIntValue(0, 4);
1057     // This is the important bit that tells the debugger where the function
1058     // code is located and what's its size:
1059     OS.AddComment("Code size");
1060     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
1061     OS.AddComment("Offset after prologue");
1062     OS.EmitIntValue(0, 4);
1063     OS.AddComment("Offset before epilogue");
1064     OS.EmitIntValue(0, 4);
1065     OS.AddComment("Function type index");
1066     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
1067     OS.AddComment("Function section relative address");
1068     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
1069     OS.AddComment("Function section index");
1070     OS.EmitCOFFSectionIndex(Fn);
1071     OS.AddComment("Flags");
1072     OS.EmitIntValue(0, 1);
1073     // Emit the function display name as a null-terminated string.
1074     OS.AddComment("Function name");
1075     // Truncate the name so we won't overflow the record length field.
1076     emitNullTerminatedSymbolName(OS, FuncName);
1077     endSymbolRecord(ProcRecordEnd);
1078 
1079     MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
1080     // Subtract out the CSR size since MSVC excludes that and we include it.
1081     OS.AddComment("FrameSize");
1082     OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
1083     OS.AddComment("Padding");
1084     OS.EmitIntValue(0, 4);
1085     OS.AddComment("Offset of padding");
1086     OS.EmitIntValue(0, 4);
1087     OS.AddComment("Bytes of callee saved registers");
1088     OS.EmitIntValue(FI.CSRSize, 4);
1089     OS.AddComment("Exception handler offset");
1090     OS.EmitIntValue(0, 4);
1091     OS.AddComment("Exception handler section");
1092     OS.EmitIntValue(0, 2);
1093     OS.AddComment("Flags (defines frame register)");
1094     OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
1095     endSymbolRecord(FrameProcEnd);
1096 
1097     emitLocalVariableList(FI, FI.Locals);
1098     emitGlobalVariableList(FI.Globals);
1099     emitLexicalBlockList(FI.ChildBlocks, FI);
1100 
1101     // Emit inlined call site information. Only emit functions inlined directly
1102     // into the parent function. We'll emit the other sites recursively as part
1103     // of their parent inline site.
1104     for (const DILocation *InlinedAt : FI.ChildSites) {
1105       auto I = FI.InlineSites.find(InlinedAt);
1106       assert(I != FI.InlineSites.end() &&
1107              "child site not in function inline site map");
1108       emitInlinedCallSite(FI, InlinedAt, I->second);
1109     }
1110 
1111     for (auto Annot : FI.Annotations) {
1112       MCSymbol *Label = Annot.first;
1113       MDTuple *Strs = cast<MDTuple>(Annot.second);
1114       MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
1115       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
1116       // FIXME: Make sure we don't overflow the max record size.
1117       OS.EmitCOFFSectionIndex(Label);
1118       OS.EmitIntValue(Strs->getNumOperands(), 2);
1119       for (Metadata *MD : Strs->operands()) {
1120         // MDStrings are null terminated, so we can do EmitBytes and get the
1121         // nice .asciz directive.
1122         StringRef Str = cast<MDString>(MD)->getString();
1123         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
1124         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
1125       }
1126       endSymbolRecord(AnnotEnd);
1127     }
1128 
1129     for (auto HeapAllocSite : FI.HeapAllocSites) {
1130       const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
1131       const MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
1132       const DIType *DITy = std::get<2>(HeapAllocSite);
1133       MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
1134       OS.AddComment("Call site offset");
1135       OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
1136       OS.AddComment("Call site section index");
1137       OS.EmitCOFFSectionIndex(BeginLabel);
1138       OS.AddComment("Call instruction length");
1139       OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
1140       OS.AddComment("Type index");
1141       OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
1142       endSymbolRecord(HeapAllocEnd);
1143     }
1144 
1145     if (SP != nullptr)
1146       emitDebugInfoForUDTs(LocalUDTs);
1147 
1148     // We're done with this function.
1149     emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
1150   }
1151   endCVSubsection(SymbolsEnd);
1152 
1153   // We have an assembler directive that takes care of the whole line table.
1154   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
1155 }
1156 
1157 CodeViewDebug::LocalVarDefRange
1158 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
1159   LocalVarDefRange DR;
1160   DR.InMemory = -1;
1161   DR.DataOffset = Offset;
1162   assert(DR.DataOffset == Offset && "truncation");
1163   DR.IsSubfield = 0;
1164   DR.StructOffset = 0;
1165   DR.CVRegister = CVRegister;
1166   return DR;
1167 }
1168 
1169 void CodeViewDebug::collectVariableInfoFromMFTable(
1170     DenseSet<InlinedEntity> &Processed) {
1171   const MachineFunction &MF = *Asm->MF;
1172   const TargetSubtargetInfo &TSI = MF.getSubtarget();
1173   const TargetFrameLowering *TFI = TSI.getFrameLowering();
1174   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1175 
1176   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
1177     if (!VI.Var)
1178       continue;
1179     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1180            "Expected inlined-at fields to agree");
1181 
1182     Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
1183     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1184 
1185     // If variable scope is not found then skip this variable.
1186     if (!Scope)
1187       continue;
1188 
1189     // If the variable has an attached offset expression, extract it.
1190     // FIXME: Try to handle DW_OP_deref as well.
1191     int64_t ExprOffset = 0;
1192     bool Deref = false;
1193     if (VI.Expr) {
1194       // If there is one DW_OP_deref element, use offset of 0 and keep going.
1195       if (VI.Expr->getNumElements() == 1 &&
1196           VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
1197         Deref = true;
1198       else if (!VI.Expr->extractIfOffset(ExprOffset))
1199         continue;
1200     }
1201 
1202     // Get the frame register used and the offset.
1203     unsigned FrameReg = 0;
1204     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1205     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1206 
1207     // Calculate the label ranges.
1208     LocalVarDefRange DefRange =
1209         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1210 
1211     for (const InsnRange &Range : Scope->getRanges()) {
1212       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1213       const MCSymbol *End = getLabelAfterInsn(Range.second);
1214       End = End ? End : Asm->getFunctionEnd();
1215       DefRange.Ranges.emplace_back(Begin, End);
1216     }
1217 
1218     LocalVariable Var;
1219     Var.DIVar = VI.Var;
1220     Var.DefRanges.emplace_back(std::move(DefRange));
1221     if (Deref)
1222       Var.UseReferenceType = true;
1223 
1224     recordLocalVariable(std::move(Var), Scope);
1225   }
1226 }
1227 
1228 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1229   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1230 }
1231 
1232 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1233   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1234 }
1235 
1236 void CodeViewDebug::calculateRanges(
1237     LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
1238   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1239 
1240   // Calculate the definition ranges.
1241   for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
1242     const auto &Entry = *I;
1243     if (!Entry.isDbgValue())
1244       continue;
1245     const MachineInstr *DVInst = Entry.getInstr();
1246     assert(DVInst->isDebugValue() && "Invalid History entry");
1247     // FIXME: Find a way to represent constant variables, since they are
1248     // relatively common.
1249     Optional<DbgVariableLocation> Location =
1250         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1251     if (!Location)
1252       continue;
1253 
1254     // CodeView can only express variables in register and variables in memory
1255     // at a constant offset from a register. However, for variables passed
1256     // indirectly by pointer, it is common for that pointer to be spilled to a
1257     // stack location. For the special case of one offseted load followed by a
1258     // zero offset load (a pointer spilled to the stack), we change the type of
1259     // the local variable from a value type to a reference type. This tricks the
1260     // debugger into doing the load for us.
1261     if (Var.UseReferenceType) {
1262       // We're using a reference type. Drop the last zero offset load.
1263       if (canUseReferenceType(*Location))
1264         Location->LoadChain.pop_back();
1265       else
1266         continue;
1267     } else if (needsReferenceType(*Location)) {
1268       // This location can't be expressed without switching to a reference type.
1269       // Start over using that.
1270       Var.UseReferenceType = true;
1271       Var.DefRanges.clear();
1272       calculateRanges(Var, Entries);
1273       return;
1274     }
1275 
1276     // We can only handle a register or an offseted load of a register.
1277     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1278       continue;
1279     {
1280       LocalVarDefRange DR;
1281       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1282       DR.InMemory = !Location->LoadChain.empty();
1283       DR.DataOffset =
1284           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1285       if (Location->FragmentInfo) {
1286         DR.IsSubfield = true;
1287         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1288       } else {
1289         DR.IsSubfield = false;
1290         DR.StructOffset = 0;
1291       }
1292 
1293       if (Var.DefRanges.empty() ||
1294           Var.DefRanges.back().isDifferentLocation(DR)) {
1295         Var.DefRanges.emplace_back(std::move(DR));
1296       }
1297     }
1298 
1299     // Compute the label range.
1300     const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
1301     const MCSymbol *End;
1302     if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
1303       auto &EndingEntry = Entries[Entry.getEndIndex()];
1304       End = EndingEntry.isDbgValue()
1305                 ? getLabelBeforeInsn(EndingEntry.getInstr())
1306                 : getLabelAfterInsn(EndingEntry.getInstr());
1307     } else
1308       End = Asm->getFunctionEnd();
1309 
1310     // If the last range end is our begin, just extend the last range.
1311     // Otherwise make a new range.
1312     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1313         Var.DefRanges.back().Ranges;
1314     if (!R.empty() && R.back().second == Begin)
1315       R.back().second = End;
1316     else
1317       R.emplace_back(Begin, End);
1318 
1319     // FIXME: Do more range combining.
1320   }
1321 }
1322 
1323 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1324   DenseSet<InlinedEntity> Processed;
1325   // Grab the variable info that was squirreled away in the MMI side-table.
1326   collectVariableInfoFromMFTable(Processed);
1327 
1328   for (const auto &I : DbgValues) {
1329     InlinedEntity IV = I.first;
1330     if (Processed.count(IV))
1331       continue;
1332     const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
1333     const DILocation *InlinedAt = IV.second;
1334 
1335     // Instruction ranges, specifying where IV is accessible.
1336     const auto &Entries = I.second;
1337 
1338     LexicalScope *Scope = nullptr;
1339     if (InlinedAt)
1340       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1341     else
1342       Scope = LScopes.findLexicalScope(DIVar->getScope());
1343     // If variable scope is not found then skip this variable.
1344     if (!Scope)
1345       continue;
1346 
1347     LocalVariable Var;
1348     Var.DIVar = DIVar;
1349 
1350     calculateRanges(Var, Entries);
1351     recordLocalVariable(std::move(Var), Scope);
1352   }
1353 }
1354 
1355 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1356   const TargetSubtargetInfo &TSI = MF->getSubtarget();
1357   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
1358   const MachineFrameInfo &MFI = MF->getFrameInfo();
1359   const Function &GV = MF->getFunction();
1360   auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
1361   assert(Insertion.second && "function already has info");
1362   CurFn = Insertion.first->second.get();
1363   CurFn->FuncId = NextFuncId++;
1364   CurFn->Begin = Asm->getFunctionBegin();
1365 
1366   // The S_FRAMEPROC record reports the stack size, and how many bytes of
1367   // callee-saved registers were used. For targets that don't use a PUSH
1368   // instruction (AArch64), this will be zero.
1369   CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
1370   CurFn->FrameSize = MFI.getStackSize();
1371   CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
1372   CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
1373 
1374   // For this function S_FRAMEPROC record, figure out which codeview register
1375   // will be the frame pointer.
1376   CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
1377   CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
1378   if (CurFn->FrameSize > 0) {
1379     if (!TSI.getFrameLowering()->hasFP(*MF)) {
1380       CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1381       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
1382     } else {
1383       // If there is an FP, parameters are always relative to it.
1384       CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
1385       if (CurFn->HasStackRealignment) {
1386         // If the stack needs realignment, locals are relative to SP or VFRAME.
1387         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
1388       } else {
1389         // Otherwise, locals are relative to EBP, and we probably have VLAs or
1390         // other stack adjustments.
1391         CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
1392       }
1393     }
1394   }
1395 
1396   // Compute other frame procedure options.
1397   FrameProcedureOptions FPO = FrameProcedureOptions::None;
1398   if (MFI.hasVarSizedObjects())
1399     FPO |= FrameProcedureOptions::HasAlloca;
1400   if (MF->exposesReturnsTwice())
1401     FPO |= FrameProcedureOptions::HasSetJmp;
1402   // FIXME: Set HasLongJmp if we ever track that info.
1403   if (MF->hasInlineAsm())
1404     FPO |= FrameProcedureOptions::HasInlineAssembly;
1405   if (GV.hasPersonalityFn()) {
1406     if (isAsynchronousEHPersonality(
1407             classifyEHPersonality(GV.getPersonalityFn())))
1408       FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
1409     else
1410       FPO |= FrameProcedureOptions::HasExceptionHandling;
1411   }
1412   if (GV.hasFnAttribute(Attribute::InlineHint))
1413     FPO |= FrameProcedureOptions::MarkedInline;
1414   if (GV.hasFnAttribute(Attribute::Naked))
1415     FPO |= FrameProcedureOptions::Naked;
1416   if (MFI.hasStackProtectorIndex())
1417     FPO |= FrameProcedureOptions::SecurityChecks;
1418   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
1419   FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
1420   if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
1421       !GV.hasOptSize() && !GV.hasOptNone())
1422     FPO |= FrameProcedureOptions::OptimizedForSpeed;
1423   // FIXME: Set GuardCfg when it is implemented.
1424   CurFn->FrameProcOpts = FPO;
1425 
1426   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1427 
1428   // Find the end of the function prolog.  First known non-DBG_VALUE and
1429   // non-frame setup location marks the beginning of the function body.
1430   // FIXME: is there a simpler a way to do this? Can we just search
1431   // for the first instruction of the function, not the last of the prolog?
1432   DebugLoc PrologEndLoc;
1433   bool EmptyPrologue = true;
1434   for (const auto &MBB : *MF) {
1435     for (const auto &MI : MBB) {
1436       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1437           MI.getDebugLoc()) {
1438         PrologEndLoc = MI.getDebugLoc();
1439         break;
1440       } else if (!MI.isMetaInstruction()) {
1441         EmptyPrologue = false;
1442       }
1443     }
1444   }
1445 
1446   // Record beginning of function if we have a non-empty prologue.
1447   if (PrologEndLoc && !EmptyPrologue) {
1448     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1449     maybeRecordLocation(FnStartDL, MF);
1450   }
1451 
1452   // Find heap alloc sites and emit labels around them.
1453   for (const auto &MBB : *MF) {
1454     for (const auto &MI : MBB) {
1455       if (MI.getHeapAllocMarker()) {
1456         requestLabelBeforeInsn(&MI);
1457         requestLabelAfterInsn(&MI);
1458       }
1459     }
1460   }
1461 }
1462 
1463 static bool shouldEmitUdt(const DIType *T) {
1464   if (!T)
1465     return false;
1466 
1467   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1468   if (T->getTag() == dwarf::DW_TAG_typedef) {
1469     if (DIScope *Scope = T->getScope()) {
1470       switch (Scope->getTag()) {
1471       case dwarf::DW_TAG_structure_type:
1472       case dwarf::DW_TAG_class_type:
1473       case dwarf::DW_TAG_union_type:
1474         return false;
1475       }
1476     }
1477   }
1478 
1479   while (true) {
1480     if (!T || T->isForwardDecl())
1481       return false;
1482 
1483     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1484     if (!DT)
1485       return true;
1486     T = DT->getBaseType();
1487   }
1488   return true;
1489 }
1490 
1491 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1492   // Don't record empty UDTs.
1493   if (Ty->getName().empty())
1494     return;
1495   if (!shouldEmitUdt(Ty))
1496     return;
1497 
1498   SmallVector<StringRef, 5> QualifiedNameComponents;
1499   const DISubprogram *ClosestSubprogram =
1500       getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents);
1501 
1502   std::string FullyQualifiedName =
1503       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1504 
1505   if (ClosestSubprogram == nullptr) {
1506     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1507   } else if (ClosestSubprogram == CurrentSubprogram) {
1508     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1509   }
1510 
1511   // TODO: What if the ClosestSubprogram is neither null or the current
1512   // subprogram?  Currently, the UDT just gets dropped on the floor.
1513   //
1514   // The current behavior is not desirable.  To get maximal fidelity, we would
1515   // need to perform all type translation before beginning emission of .debug$S
1516   // and then make LocalUDTs a member of FunctionInfo
1517 }
1518 
1519 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1520   // Generic dispatch for lowering an unknown type.
1521   switch (Ty->getTag()) {
1522   case dwarf::DW_TAG_array_type:
1523     return lowerTypeArray(cast<DICompositeType>(Ty));
1524   case dwarf::DW_TAG_typedef:
1525     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1526   case dwarf::DW_TAG_base_type:
1527     return lowerTypeBasic(cast<DIBasicType>(Ty));
1528   case dwarf::DW_TAG_pointer_type:
1529     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1530       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1531     LLVM_FALLTHROUGH;
1532   case dwarf::DW_TAG_reference_type:
1533   case dwarf::DW_TAG_rvalue_reference_type:
1534     return lowerTypePointer(cast<DIDerivedType>(Ty));
1535   case dwarf::DW_TAG_ptr_to_member_type:
1536     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1537   case dwarf::DW_TAG_restrict_type:
1538   case dwarf::DW_TAG_const_type:
1539   case dwarf::DW_TAG_volatile_type:
1540   // TODO: add support for DW_TAG_atomic_type here
1541     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1542   case dwarf::DW_TAG_subroutine_type:
1543     if (ClassTy) {
1544       // The member function type of a member function pointer has no
1545       // ThisAdjustment.
1546       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1547                                      /*ThisAdjustment=*/0,
1548                                      /*IsStaticMethod=*/false);
1549     }
1550     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1551   case dwarf::DW_TAG_enumeration_type:
1552     return lowerTypeEnum(cast<DICompositeType>(Ty));
1553   case dwarf::DW_TAG_class_type:
1554   case dwarf::DW_TAG_structure_type:
1555     return lowerTypeClass(cast<DICompositeType>(Ty));
1556   case dwarf::DW_TAG_union_type:
1557     return lowerTypeUnion(cast<DICompositeType>(Ty));
1558   case dwarf::DW_TAG_unspecified_type:
1559     if (Ty->getName() == "decltype(nullptr)")
1560       return TypeIndex::NullptrT();
1561     return TypeIndex::None();
1562   default:
1563     // Use the null type index.
1564     return TypeIndex();
1565   }
1566 }
1567 
1568 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1569   TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
1570   StringRef TypeName = Ty->getName();
1571 
1572   addToUDTs(Ty);
1573 
1574   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1575       TypeName == "HRESULT")
1576     return TypeIndex(SimpleTypeKind::HResult);
1577   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1578       TypeName == "wchar_t")
1579     return TypeIndex(SimpleTypeKind::WideCharacter);
1580 
1581   return UnderlyingTypeIndex;
1582 }
1583 
1584 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1585   const DIType *ElementType = Ty->getBaseType();
1586   TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
1587   // IndexType is size_t, which depends on the bitness of the target.
1588   TypeIndex IndexType = getPointerSizeInBytes() == 8
1589                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1590                             : TypeIndex(SimpleTypeKind::UInt32Long);
1591 
1592   uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
1593 
1594   // Add subranges to array type.
1595   DINodeArray Elements = Ty->getElements();
1596   for (int i = Elements.size() - 1; i >= 0; --i) {
1597     const DINode *Element = Elements[i];
1598     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1599 
1600     const DISubrange *Subrange = cast<DISubrange>(Element);
1601     assert(Subrange->getLowerBound() == 0 &&
1602            "codeview doesn't support subranges with lower bounds");
1603     int64_t Count = -1;
1604     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1605       Count = CI->getSExtValue();
1606 
1607     // Forward declarations of arrays without a size and VLAs use a count of -1.
1608     // Emit a count of zero in these cases to match what MSVC does for arrays
1609     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1610     // should do for them even if we could distinguish them.
1611     if (Count == -1)
1612       Count = 0;
1613 
1614     // Update the element size and element type index for subsequent subranges.
1615     ElementSize *= Count;
1616 
1617     // If this is the outermost array, use the size from the array. It will be
1618     // more accurate if we had a VLA or an incomplete element type size.
1619     uint64_t ArraySize =
1620         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1621 
1622     StringRef Name = (i == 0) ? Ty->getName() : "";
1623     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1624     ElementTypeIndex = TypeTable.writeLeafType(AR);
1625   }
1626 
1627   return ElementTypeIndex;
1628 }
1629 
1630 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1631   TypeIndex Index;
1632   dwarf::TypeKind Kind;
1633   uint32_t ByteSize;
1634 
1635   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1636   ByteSize = Ty->getSizeInBits() / 8;
1637 
1638   SimpleTypeKind STK = SimpleTypeKind::None;
1639   switch (Kind) {
1640   case dwarf::DW_ATE_address:
1641     // FIXME: Translate
1642     break;
1643   case dwarf::DW_ATE_boolean:
1644     switch (ByteSize) {
1645     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1646     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1647     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1648     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1649     case 16: STK = SimpleTypeKind::Boolean128; break;
1650     }
1651     break;
1652   case dwarf::DW_ATE_complex_float:
1653     switch (ByteSize) {
1654     case 2:  STK = SimpleTypeKind::Complex16;  break;
1655     case 4:  STK = SimpleTypeKind::Complex32;  break;
1656     case 8:  STK = SimpleTypeKind::Complex64;  break;
1657     case 10: STK = SimpleTypeKind::Complex80;  break;
1658     case 16: STK = SimpleTypeKind::Complex128; break;
1659     }
1660     break;
1661   case dwarf::DW_ATE_float:
1662     switch (ByteSize) {
1663     case 2:  STK = SimpleTypeKind::Float16;  break;
1664     case 4:  STK = SimpleTypeKind::Float32;  break;
1665     case 6:  STK = SimpleTypeKind::Float48;  break;
1666     case 8:  STK = SimpleTypeKind::Float64;  break;
1667     case 10: STK = SimpleTypeKind::Float80;  break;
1668     case 16: STK = SimpleTypeKind::Float128; break;
1669     }
1670     break;
1671   case dwarf::DW_ATE_signed:
1672     switch (ByteSize) {
1673     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1674     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1675     case 4:  STK = SimpleTypeKind::Int32;           break;
1676     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1677     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1678     }
1679     break;
1680   case dwarf::DW_ATE_unsigned:
1681     switch (ByteSize) {
1682     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1683     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1684     case 4:  STK = SimpleTypeKind::UInt32;            break;
1685     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1686     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1687     }
1688     break;
1689   case dwarf::DW_ATE_UTF:
1690     switch (ByteSize) {
1691     case 2: STK = SimpleTypeKind::Character16; break;
1692     case 4: STK = SimpleTypeKind::Character32; break;
1693     }
1694     break;
1695   case dwarf::DW_ATE_signed_char:
1696     if (ByteSize == 1)
1697       STK = SimpleTypeKind::SignedCharacter;
1698     break;
1699   case dwarf::DW_ATE_unsigned_char:
1700     if (ByteSize == 1)
1701       STK = SimpleTypeKind::UnsignedCharacter;
1702     break;
1703   default:
1704     break;
1705   }
1706 
1707   // Apply some fixups based on the source-level type name.
1708   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1709     STK = SimpleTypeKind::Int32Long;
1710   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1711     STK = SimpleTypeKind::UInt32Long;
1712   if (STK == SimpleTypeKind::UInt16Short &&
1713       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1714     STK = SimpleTypeKind::WideCharacter;
1715   if ((STK == SimpleTypeKind::SignedCharacter ||
1716        STK == SimpleTypeKind::UnsignedCharacter) &&
1717       Ty->getName() == "char")
1718     STK = SimpleTypeKind::NarrowCharacter;
1719 
1720   return TypeIndex(STK);
1721 }
1722 
1723 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
1724                                           PointerOptions PO) {
1725   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1726 
1727   // Pointers to simple types without any options can use SimpleTypeMode, rather
1728   // than having a dedicated pointer type record.
1729   if (PointeeTI.isSimple() && PO == PointerOptions::None &&
1730       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1731       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1732     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1733                               ? SimpleTypeMode::NearPointer64
1734                               : SimpleTypeMode::NearPointer32;
1735     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1736   }
1737 
1738   PointerKind PK =
1739       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1740   PointerMode PM = PointerMode::Pointer;
1741   switch (Ty->getTag()) {
1742   default: llvm_unreachable("not a pointer tag type");
1743   case dwarf::DW_TAG_pointer_type:
1744     PM = PointerMode::Pointer;
1745     break;
1746   case dwarf::DW_TAG_reference_type:
1747     PM = PointerMode::LValueReference;
1748     break;
1749   case dwarf::DW_TAG_rvalue_reference_type:
1750     PM = PointerMode::RValueReference;
1751     break;
1752   }
1753 
1754   if (Ty->isObjectPointer())
1755     PO |= PointerOptions::Const;
1756 
1757   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1758   return TypeTable.writeLeafType(PR);
1759 }
1760 
1761 static PointerToMemberRepresentation
1762 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1763   // SizeInBytes being zero generally implies that the member pointer type was
1764   // incomplete, which can happen if it is part of a function prototype. In this
1765   // case, use the unknown model instead of the general model.
1766   if (IsPMF) {
1767     switch (Flags & DINode::FlagPtrToMemberRep) {
1768     case 0:
1769       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1770                               : PointerToMemberRepresentation::GeneralFunction;
1771     case DINode::FlagSingleInheritance:
1772       return PointerToMemberRepresentation::SingleInheritanceFunction;
1773     case DINode::FlagMultipleInheritance:
1774       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1775     case DINode::FlagVirtualInheritance:
1776       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1777     }
1778   } else {
1779     switch (Flags & DINode::FlagPtrToMemberRep) {
1780     case 0:
1781       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1782                               : PointerToMemberRepresentation::GeneralData;
1783     case DINode::FlagSingleInheritance:
1784       return PointerToMemberRepresentation::SingleInheritanceData;
1785     case DINode::FlagMultipleInheritance:
1786       return PointerToMemberRepresentation::MultipleInheritanceData;
1787     case DINode::FlagVirtualInheritance:
1788       return PointerToMemberRepresentation::VirtualInheritanceData;
1789     }
1790   }
1791   llvm_unreachable("invalid ptr to member representation");
1792 }
1793 
1794 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
1795                                                 PointerOptions PO) {
1796   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1797   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1798   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1799   PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
1800                                                 : PointerKind::Near32;
1801   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1802   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1803                          : PointerMode::PointerToDataMember;
1804 
1805   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1806   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1807   MemberPointerInfo MPI(
1808       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1809   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1810   return TypeTable.writeLeafType(PR);
1811 }
1812 
1813 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1814 /// have a translation, use the NearC convention.
1815 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1816   switch (DwarfCC) {
1817   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1818   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1819   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1820   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1821   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1822   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1823   }
1824   return CallingConvention::NearC;
1825 }
1826 
1827 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1828   ModifierOptions Mods = ModifierOptions::None;
1829   PointerOptions PO = PointerOptions::None;
1830   bool IsModifier = true;
1831   const DIType *BaseTy = Ty;
1832   while (IsModifier && BaseTy) {
1833     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1834     switch (BaseTy->getTag()) {
1835     case dwarf::DW_TAG_const_type:
1836       Mods |= ModifierOptions::Const;
1837       PO |= PointerOptions::Const;
1838       break;
1839     case dwarf::DW_TAG_volatile_type:
1840       Mods |= ModifierOptions::Volatile;
1841       PO |= PointerOptions::Volatile;
1842       break;
1843     case dwarf::DW_TAG_restrict_type:
1844       // Only pointer types be marked with __restrict. There is no known flag
1845       // for __restrict in LF_MODIFIER records.
1846       PO |= PointerOptions::Restrict;
1847       break;
1848     default:
1849       IsModifier = false;
1850       break;
1851     }
1852     if (IsModifier)
1853       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
1854   }
1855 
1856   // Check if the inner type will use an LF_POINTER record. If so, the
1857   // qualifiers will go in the LF_POINTER record. This comes up for types like
1858   // 'int *const' and 'int *__restrict', not the more common cases like 'const
1859   // char *'.
1860   if (BaseTy) {
1861     switch (BaseTy->getTag()) {
1862     case dwarf::DW_TAG_pointer_type:
1863     case dwarf::DW_TAG_reference_type:
1864     case dwarf::DW_TAG_rvalue_reference_type:
1865       return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
1866     case dwarf::DW_TAG_ptr_to_member_type:
1867       return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
1868     default:
1869       break;
1870     }
1871   }
1872 
1873   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1874 
1875   // Return the base type index if there aren't any modifiers. For example, the
1876   // metadata could contain restrict wrappers around non-pointer types.
1877   if (Mods == ModifierOptions::None)
1878     return ModifiedTI;
1879 
1880   ModifierRecord MR(ModifiedTI, Mods);
1881   return TypeTable.writeLeafType(MR);
1882 }
1883 
1884 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1885   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1886   for (const DIType *ArgType : Ty->getTypeArray())
1887     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
1888 
1889   // MSVC uses type none for variadic argument.
1890   if (ReturnAndArgTypeIndices.size() > 1 &&
1891       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1892     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1893   }
1894   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1895   ArrayRef<TypeIndex> ArgTypeIndices = None;
1896   if (!ReturnAndArgTypeIndices.empty()) {
1897     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1898     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1899     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1900   }
1901 
1902   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1903   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1904 
1905   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1906 
1907   FunctionOptions FO = getFunctionOptions(Ty);
1908   ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
1909                             ArgListIndex);
1910   return TypeTable.writeLeafType(Procedure);
1911 }
1912 
1913 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1914                                                  const DIType *ClassTy,
1915                                                  int ThisAdjustment,
1916                                                  bool IsStaticMethod,
1917                                                  FunctionOptions FO) {
1918   // Lower the containing class type.
1919   TypeIndex ClassType = getTypeIndex(ClassTy);
1920 
1921   DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
1922 
1923   unsigned Index = 0;
1924   SmallVector<TypeIndex, 8> ArgTypeIndices;
1925   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1926   if (ReturnAndArgs.size() > Index) {
1927     ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
1928   }
1929 
1930   // If the first argument is a pointer type and this isn't a static method,
1931   // treat it as the special 'this' parameter, which is encoded separately from
1932   // the arguments.
1933   TypeIndex ThisTypeIndex;
1934   if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
1935     if (const DIDerivedType *PtrTy =
1936             dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
1937       if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
1938         ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
1939         Index++;
1940       }
1941     }
1942   }
1943 
1944   while (Index < ReturnAndArgs.size())
1945     ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
1946 
1947   // MSVC uses type none for variadic argument.
1948   if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
1949     ArgTypeIndices.back() = TypeIndex::None();
1950 
1951   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1952   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1953 
1954   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1955 
1956   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
1957                            ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
1958   return TypeTable.writeLeafType(MFR);
1959 }
1960 
1961 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1962   unsigned VSlotCount =
1963       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1964   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1965 
1966   VFTableShapeRecord VFTSR(Slots);
1967   return TypeTable.writeLeafType(VFTSR);
1968 }
1969 
1970 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1971   switch (Flags & DINode::FlagAccessibility) {
1972   case DINode::FlagPrivate:   return MemberAccess::Private;
1973   case DINode::FlagPublic:    return MemberAccess::Public;
1974   case DINode::FlagProtected: return MemberAccess::Protected;
1975   case 0:
1976     // If there was no explicit access control, provide the default for the tag.
1977     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1978                                                  : MemberAccess::Public;
1979   }
1980   llvm_unreachable("access flags are exclusive");
1981 }
1982 
1983 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1984   if (SP->isArtificial())
1985     return MethodOptions::CompilerGenerated;
1986 
1987   // FIXME: Handle other MethodOptions.
1988 
1989   return MethodOptions::None;
1990 }
1991 
1992 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1993                                            bool Introduced) {
1994   if (SP->getFlags() & DINode::FlagStaticMember)
1995     return MethodKind::Static;
1996 
1997   switch (SP->getVirtuality()) {
1998   case dwarf::DW_VIRTUALITY_none:
1999     break;
2000   case dwarf::DW_VIRTUALITY_virtual:
2001     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
2002   case dwarf::DW_VIRTUALITY_pure_virtual:
2003     return Introduced ? MethodKind::PureIntroducingVirtual
2004                       : MethodKind::PureVirtual;
2005   default:
2006     llvm_unreachable("unhandled virtuality case");
2007   }
2008 
2009   return MethodKind::Vanilla;
2010 }
2011 
2012 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
2013   switch (Ty->getTag()) {
2014   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
2015   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
2016   }
2017   llvm_unreachable("unexpected tag");
2018 }
2019 
2020 /// Return ClassOptions that should be present on both the forward declaration
2021 /// and the defintion of a tag type.
2022 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
2023   ClassOptions CO = ClassOptions::None;
2024 
2025   // MSVC always sets this flag, even for local types. Clang doesn't always
2026   // appear to give every type a linkage name, which may be problematic for us.
2027   // FIXME: Investigate the consequences of not following them here.
2028   if (!Ty->getIdentifier().empty())
2029     CO |= ClassOptions::HasUniqueName;
2030 
2031   // Put the Nested flag on a type if it appears immediately inside a tag type.
2032   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
2033   // here. That flag is only set on definitions, and not forward declarations.
2034   const DIScope *ImmediateScope = Ty->getScope();
2035   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
2036     CO |= ClassOptions::Nested;
2037 
2038   // Put the Scoped flag on function-local types. MSVC puts this flag for enum
2039   // type only when it has an immediate function scope. Clang never puts enums
2040   // inside DILexicalBlock scopes. Enum types, as generated by clang, are
2041   // always in function, class, or file scopes.
2042   if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
2043     if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
2044       CO |= ClassOptions::Scoped;
2045   } else {
2046     for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
2047          Scope = Scope->getScope()) {
2048       if (isa<DISubprogram>(Scope)) {
2049         CO |= ClassOptions::Scoped;
2050         break;
2051       }
2052     }
2053   }
2054 
2055   return CO;
2056 }
2057 
2058 void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
2059   switch (Ty->getTag()) {
2060   case dwarf::DW_TAG_class_type:
2061   case dwarf::DW_TAG_structure_type:
2062   case dwarf::DW_TAG_union_type:
2063   case dwarf::DW_TAG_enumeration_type:
2064     break;
2065   default:
2066     return;
2067   }
2068 
2069   if (const auto *File = Ty->getFile()) {
2070     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
2071     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
2072 
2073     UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
2074     TypeTable.writeLeafType(USLR);
2075   }
2076 }
2077 
2078 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
2079   ClassOptions CO = getCommonClassOptions(Ty);
2080   TypeIndex FTI;
2081   unsigned EnumeratorCount = 0;
2082 
2083   if (Ty->isForwardDecl()) {
2084     CO |= ClassOptions::ForwardReference;
2085   } else {
2086     ContinuationRecordBuilder ContinuationBuilder;
2087     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2088     for (const DINode *Element : Ty->getElements()) {
2089       // We assume that the frontend provides all members in source declaration
2090       // order, which is what MSVC does.
2091       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
2092         EnumeratorRecord ER(MemberAccess::Public,
2093                             APSInt::getUnsigned(Enumerator->getValue()),
2094                             Enumerator->getName());
2095         ContinuationBuilder.writeMemberType(ER);
2096         EnumeratorCount++;
2097       }
2098     }
2099     FTI = TypeTable.insertRecord(ContinuationBuilder);
2100   }
2101 
2102   std::string FullName = getFullyQualifiedName(Ty);
2103 
2104   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
2105                 getTypeIndex(Ty->getBaseType()));
2106   TypeIndex EnumTI = TypeTable.writeLeafType(ER);
2107 
2108   addUDTSrcLine(Ty, EnumTI);
2109 
2110   return EnumTI;
2111 }
2112 
2113 //===----------------------------------------------------------------------===//
2114 // ClassInfo
2115 //===----------------------------------------------------------------------===//
2116 
2117 struct llvm::ClassInfo {
2118   struct MemberInfo {
2119     const DIDerivedType *MemberTypeNode;
2120     uint64_t BaseOffset;
2121   };
2122   // [MemberInfo]
2123   using MemberList = std::vector<MemberInfo>;
2124 
2125   using MethodsList = TinyPtrVector<const DISubprogram *>;
2126   // MethodName -> MethodsList
2127   using MethodsMap = MapVector<MDString *, MethodsList>;
2128 
2129   /// Base classes.
2130   std::vector<const DIDerivedType *> Inheritance;
2131 
2132   /// Direct members.
2133   MemberList Members;
2134   // Direct overloaded methods gathered by name.
2135   MethodsMap Methods;
2136 
2137   TypeIndex VShapeTI;
2138 
2139   std::vector<const DIType *> NestedTypes;
2140 };
2141 
2142 void CodeViewDebug::clear() {
2143   assert(CurFn == nullptr);
2144   FileIdMap.clear();
2145   FnDebugInfo.clear();
2146   FileToFilepathMap.clear();
2147   LocalUDTs.clear();
2148   GlobalUDTs.clear();
2149   TypeIndices.clear();
2150   CompleteTypeIndices.clear();
2151   ScopeGlobals.clear();
2152 }
2153 
2154 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
2155                                       const DIDerivedType *DDTy) {
2156   if (!DDTy->getName().empty()) {
2157     Info.Members.push_back({DDTy, 0});
2158     return;
2159   }
2160 
2161   // An unnamed member may represent a nested struct or union. Attempt to
2162   // interpret the unnamed member as a DICompositeType possibly wrapped in
2163   // qualifier types. Add all the indirect fields to the current record if that
2164   // succeeds, and drop the member if that fails.
2165   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
2166   uint64_t Offset = DDTy->getOffsetInBits();
2167   const DIType *Ty = DDTy->getBaseType();
2168   bool FullyResolved = false;
2169   while (!FullyResolved) {
2170     switch (Ty->getTag()) {
2171     case dwarf::DW_TAG_const_type:
2172     case dwarf::DW_TAG_volatile_type:
2173       // FIXME: we should apply the qualifier types to the indirect fields
2174       // rather than dropping them.
2175       Ty = cast<DIDerivedType>(Ty)->getBaseType();
2176       break;
2177     default:
2178       FullyResolved = true;
2179       break;
2180     }
2181   }
2182 
2183   const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
2184   if (!DCTy)
2185     return;
2186 
2187   ClassInfo NestedInfo = collectClassInfo(DCTy);
2188   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
2189     Info.Members.push_back(
2190         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
2191 }
2192 
2193 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
2194   ClassInfo Info;
2195   // Add elements to structure type.
2196   DINodeArray Elements = Ty->getElements();
2197   for (auto *Element : Elements) {
2198     // We assume that the frontend provides all members in source declaration
2199     // order, which is what MSVC does.
2200     if (!Element)
2201       continue;
2202     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
2203       Info.Methods[SP->getRawName()].push_back(SP);
2204     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
2205       if (DDTy->getTag() == dwarf::DW_TAG_member) {
2206         collectMemberInfo(Info, DDTy);
2207       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
2208         Info.Inheritance.push_back(DDTy);
2209       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
2210                  DDTy->getName() == "__vtbl_ptr_type") {
2211         Info.VShapeTI = getTypeIndex(DDTy);
2212       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
2213         Info.NestedTypes.push_back(DDTy);
2214       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
2215         // Ignore friend members. It appears that MSVC emitted info about
2216         // friends in the past, but modern versions do not.
2217       }
2218     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
2219       Info.NestedTypes.push_back(Composite);
2220     }
2221     // Skip other unrecognized kinds of elements.
2222   }
2223   return Info;
2224 }
2225 
2226 static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
2227   // This routine is used by lowerTypeClass and lowerTypeUnion to determine
2228   // if a complete type should be emitted instead of a forward reference.
2229   return Ty->getName().empty() && Ty->getIdentifier().empty() &&
2230       !Ty->isForwardDecl();
2231 }
2232 
2233 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
2234   // Emit the complete type for unnamed structs.  C++ classes with methods
2235   // which have a circular reference back to the class type are expected to
2236   // be named by the front-end and should not be "unnamed".  C unnamed
2237   // structs should not have circular references.
2238   if (shouldAlwaysEmitCompleteClassType(Ty)) {
2239     // If this unnamed complete type is already in the process of being defined
2240     // then the description of the type is malformed and cannot be emitted
2241     // into CodeView correctly so report a fatal error.
2242     auto I = CompleteTypeIndices.find(Ty);
2243     if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
2244       report_fatal_error("cannot debug circular reference to unnamed type");
2245     return getCompleteTypeIndex(Ty);
2246   }
2247 
2248   // First, construct the forward decl.  Don't look into Ty to compute the
2249   // forward decl options, since it might not be available in all TUs.
2250   TypeRecordKind Kind = getRecordKind(Ty);
2251   ClassOptions CO =
2252       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2253   std::string FullName = getFullyQualifiedName(Ty);
2254   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
2255                  FullName, Ty->getIdentifier());
2256   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
2257   if (!Ty->isForwardDecl())
2258     DeferredCompleteTypes.push_back(Ty);
2259   return FwdDeclTI;
2260 }
2261 
2262 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
2263   // Construct the field list and complete type record.
2264   TypeRecordKind Kind = getRecordKind(Ty);
2265   ClassOptions CO = getCommonClassOptions(Ty);
2266   TypeIndex FieldTI;
2267   TypeIndex VShapeTI;
2268   unsigned FieldCount;
2269   bool ContainsNestedClass;
2270   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
2271       lowerRecordFieldList(Ty);
2272 
2273   if (ContainsNestedClass)
2274     CO |= ClassOptions::ContainsNestedClass;
2275 
2276   // MSVC appears to set this flag by searching any destructor or method with
2277   // FunctionOptions::Constructor among the emitted members. Clang AST has all
2278   // the members, however special member functions are not yet emitted into
2279   // debug information. For now checking a class's non-triviality seems enough.
2280   // FIXME: not true for a nested unnamed struct.
2281   if (isNonTrivial(Ty))
2282     CO |= ClassOptions::HasConstructorOrDestructor;
2283 
2284   std::string FullName = getFullyQualifiedName(Ty);
2285 
2286   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2287 
2288   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
2289                  SizeInBytes, FullName, Ty->getIdentifier());
2290   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
2291 
2292   addUDTSrcLine(Ty, ClassTI);
2293 
2294   addToUDTs(Ty);
2295 
2296   return ClassTI;
2297 }
2298 
2299 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
2300   // Emit the complete type for unnamed unions.
2301   if (shouldAlwaysEmitCompleteClassType(Ty))
2302     return getCompleteTypeIndex(Ty);
2303 
2304   ClassOptions CO =
2305       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
2306   std::string FullName = getFullyQualifiedName(Ty);
2307   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
2308   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
2309   if (!Ty->isForwardDecl())
2310     DeferredCompleteTypes.push_back(Ty);
2311   return FwdDeclTI;
2312 }
2313 
2314 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
2315   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
2316   TypeIndex FieldTI;
2317   unsigned FieldCount;
2318   bool ContainsNestedClass;
2319   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
2320       lowerRecordFieldList(Ty);
2321 
2322   if (ContainsNestedClass)
2323     CO |= ClassOptions::ContainsNestedClass;
2324 
2325   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
2326   std::string FullName = getFullyQualifiedName(Ty);
2327 
2328   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
2329                  Ty->getIdentifier());
2330   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
2331 
2332   addUDTSrcLine(Ty, UnionTI);
2333 
2334   addToUDTs(Ty);
2335 
2336   return UnionTI;
2337 }
2338 
2339 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
2340 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
2341   // Manually count members. MSVC appears to count everything that generates a
2342   // field list record. Each individual overload in a method overload group
2343   // contributes to this count, even though the overload group is a single field
2344   // list record.
2345   unsigned MemberCount = 0;
2346   ClassInfo Info = collectClassInfo(Ty);
2347   ContinuationRecordBuilder ContinuationBuilder;
2348   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
2349 
2350   // Create base classes.
2351   for (const DIDerivedType *I : Info.Inheritance) {
2352     if (I->getFlags() & DINode::FlagVirtual) {
2353       // Virtual base.
2354       unsigned VBPtrOffset = I->getVBPtrOffset();
2355       // FIXME: Despite the accessor name, the offset is really in bytes.
2356       unsigned VBTableIndex = I->getOffsetInBits() / 4;
2357       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
2358                             ? TypeRecordKind::IndirectVirtualBaseClass
2359                             : TypeRecordKind::VirtualBaseClass;
2360       VirtualBaseClassRecord VBCR(
2361           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
2362           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
2363           VBTableIndex);
2364 
2365       ContinuationBuilder.writeMemberType(VBCR);
2366       MemberCount++;
2367     } else {
2368       assert(I->getOffsetInBits() % 8 == 0 &&
2369              "bases must be on byte boundaries");
2370       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
2371                           getTypeIndex(I->getBaseType()),
2372                           I->getOffsetInBits() / 8);
2373       ContinuationBuilder.writeMemberType(BCR);
2374       MemberCount++;
2375     }
2376   }
2377 
2378   // Create members.
2379   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
2380     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
2381     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
2382     StringRef MemberName = Member->getName();
2383     MemberAccess Access =
2384         translateAccessFlags(Ty->getTag(), Member->getFlags());
2385 
2386     if (Member->isStaticMember()) {
2387       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
2388       ContinuationBuilder.writeMemberType(SDMR);
2389       MemberCount++;
2390       continue;
2391     }
2392 
2393     // Virtual function pointer member.
2394     if ((Member->getFlags() & DINode::FlagArtificial) &&
2395         Member->getName().startswith("_vptr$")) {
2396       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2397       ContinuationBuilder.writeMemberType(VFPR);
2398       MemberCount++;
2399       continue;
2400     }
2401 
2402     // Data member.
2403     uint64_t MemberOffsetInBits =
2404         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2405     if (Member->isBitField()) {
2406       uint64_t StartBitOffset = MemberOffsetInBits;
2407       if (const auto *CI =
2408               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2409         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2410       }
2411       StartBitOffset -= MemberOffsetInBits;
2412       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2413                          StartBitOffset);
2414       MemberBaseType = TypeTable.writeLeafType(BFR);
2415     }
2416     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2417     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2418                          MemberName);
2419     ContinuationBuilder.writeMemberType(DMR);
2420     MemberCount++;
2421   }
2422 
2423   // Create methods
2424   for (auto &MethodItr : Info.Methods) {
2425     StringRef Name = MethodItr.first->getString();
2426 
2427     std::vector<OneMethodRecord> Methods;
2428     for (const DISubprogram *SP : MethodItr.second) {
2429       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2430       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2431 
2432       unsigned VFTableOffset = -1;
2433       if (Introduced)
2434         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2435 
2436       Methods.push_back(OneMethodRecord(
2437           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2438           translateMethodKindFlags(SP, Introduced),
2439           translateMethodOptionFlags(SP), VFTableOffset, Name));
2440       MemberCount++;
2441     }
2442     assert(!Methods.empty() && "Empty methods map entry");
2443     if (Methods.size() == 1)
2444       ContinuationBuilder.writeMemberType(Methods[0]);
2445     else {
2446       // FIXME: Make this use its own ContinuationBuilder so that
2447       // MethodOverloadList can be split correctly.
2448       MethodOverloadListRecord MOLR(Methods);
2449       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2450 
2451       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2452       ContinuationBuilder.writeMemberType(OMR);
2453     }
2454   }
2455 
2456   // Create nested classes.
2457   for (const DIType *Nested : Info.NestedTypes) {
2458     NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
2459     ContinuationBuilder.writeMemberType(R);
2460     MemberCount++;
2461   }
2462 
2463   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2464   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2465                          !Info.NestedTypes.empty());
2466 }
2467 
2468 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2469   if (!VBPType.getIndex()) {
2470     // Make a 'const int *' type.
2471     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2472     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2473 
2474     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2475                                                   : PointerKind::Near32;
2476     PointerMode PM = PointerMode::Pointer;
2477     PointerOptions PO = PointerOptions::None;
2478     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2479     VBPType = TypeTable.writeLeafType(PR);
2480   }
2481 
2482   return VBPType;
2483 }
2484 
2485 TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
2486   // The null DIType is the void type. Don't try to hash it.
2487   if (!Ty)
2488     return TypeIndex::Void();
2489 
2490   // Check if we've already translated this type. Don't try to do a
2491   // get-or-create style insertion that caches the hash lookup across the
2492   // lowerType call. It will update the TypeIndices map.
2493   auto I = TypeIndices.find({Ty, ClassTy});
2494   if (I != TypeIndices.end())
2495     return I->second;
2496 
2497   TypeLoweringScope S(*this);
2498   TypeIndex TI = lowerType(Ty, ClassTy);
2499   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2500 }
2501 
2502 codeview::TypeIndex
2503 CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
2504                                       const DISubroutineType *SubroutineTy) {
2505   assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
2506          "this type must be a pointer type");
2507 
2508   PointerOptions Options = PointerOptions::None;
2509   if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
2510     Options = PointerOptions::LValueRefThisPointer;
2511   else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
2512     Options = PointerOptions::RValueRefThisPointer;
2513 
2514   // Check if we've already translated this type.  If there is no ref qualifier
2515   // on the function then we look up this pointer type with no associated class
2516   // so that the TypeIndex for the this pointer can be shared with the type
2517   // index for other pointers to this class type.  If there is a ref qualifier
2518   // then we lookup the pointer using the subroutine as the parent type.
2519   auto I = TypeIndices.find({PtrTy, SubroutineTy});
2520   if (I != TypeIndices.end())
2521     return I->second;
2522 
2523   TypeLoweringScope S(*this);
2524   TypeIndex TI = lowerTypePointer(PtrTy, Options);
2525   return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
2526 }
2527 
2528 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
2529   PointerRecord PR(getTypeIndex(Ty),
2530                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2531                                                 : PointerKind::Near32,
2532                    PointerMode::LValueReference, PointerOptions::None,
2533                    Ty->getSizeInBits() / 8);
2534   return TypeTable.writeLeafType(PR);
2535 }
2536 
2537 TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
2538   // The null DIType is the void type. Don't try to hash it.
2539   if (!Ty)
2540     return TypeIndex::Void();
2541 
2542   // Look through typedefs when getting the complete type index. Call
2543   // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
2544   // emitted only once.
2545   if (Ty->getTag() == dwarf::DW_TAG_typedef)
2546     (void)getTypeIndex(Ty);
2547   while (Ty->getTag() == dwarf::DW_TAG_typedef)
2548     Ty = cast<DIDerivedType>(Ty)->getBaseType();
2549 
2550   // If this is a non-record type, the complete type index is the same as the
2551   // normal type index. Just call getTypeIndex.
2552   switch (Ty->getTag()) {
2553   case dwarf::DW_TAG_class_type:
2554   case dwarf::DW_TAG_structure_type:
2555   case dwarf::DW_TAG_union_type:
2556     break;
2557   default:
2558     return getTypeIndex(Ty);
2559   }
2560 
2561   const auto *CTy = cast<DICompositeType>(Ty);
2562 
2563   TypeLoweringScope S(*this);
2564 
2565   // Make sure the forward declaration is emitted first. It's unclear if this
2566   // is necessary, but MSVC does it, and we should follow suit until we can show
2567   // otherwise.
2568   // We only emit a forward declaration for named types.
2569   if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
2570     TypeIndex FwdDeclTI = getTypeIndex(CTy);
2571 
2572     // Just use the forward decl if we don't have complete type info. This
2573     // might happen if the frontend is using modules and expects the complete
2574     // definition to be emitted elsewhere.
2575     if (CTy->isForwardDecl())
2576       return FwdDeclTI;
2577   }
2578 
2579   // Check if we've already translated the complete record type.
2580   // Insert the type with a null TypeIndex to signify that the type is currently
2581   // being lowered.
2582   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2583   if (!InsertResult.second)
2584     return InsertResult.first->second;
2585 
2586   TypeIndex TI;
2587   switch (CTy->getTag()) {
2588   case dwarf::DW_TAG_class_type:
2589   case dwarf::DW_TAG_structure_type:
2590     TI = lowerCompleteTypeClass(CTy);
2591     break;
2592   case dwarf::DW_TAG_union_type:
2593     TI = lowerCompleteTypeUnion(CTy);
2594     break;
2595   default:
2596     llvm_unreachable("not a record");
2597   }
2598 
2599   // Update the type index associated with this CompositeType.  This cannot
2600   // use the 'InsertResult' iterator above because it is potentially
2601   // invalidated by map insertions which can occur while lowering the class
2602   // type above.
2603   CompleteTypeIndices[CTy] = TI;
2604   return TI;
2605 }
2606 
2607 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2608 /// and do this until fixpoint, as each complete record type typically
2609 /// references
2610 /// many other record types.
2611 void CodeViewDebug::emitDeferredCompleteTypes() {
2612   SmallVector<const DICompositeType *, 4> TypesToEmit;
2613   while (!DeferredCompleteTypes.empty()) {
2614     std::swap(DeferredCompleteTypes, TypesToEmit);
2615     for (const DICompositeType *RecordTy : TypesToEmit)
2616       getCompleteTypeIndex(RecordTy);
2617     TypesToEmit.clear();
2618   }
2619 }
2620 
2621 void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
2622                                           ArrayRef<LocalVariable> Locals) {
2623   // Get the sorted list of parameters and emit them first.
2624   SmallVector<const LocalVariable *, 6> Params;
2625   for (const LocalVariable &L : Locals)
2626     if (L.DIVar->isParameter())
2627       Params.push_back(&L);
2628   llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
2629     return L->DIVar->getArg() < R->DIVar->getArg();
2630   });
2631   for (const LocalVariable *L : Params)
2632     emitLocalVariable(FI, *L);
2633 
2634   // Next emit all non-parameters in the order that we found them.
2635   for (const LocalVariable &L : Locals)
2636     if (!L.DIVar->isParameter())
2637       emitLocalVariable(FI, L);
2638 }
2639 
2640 /// Only call this on endian-specific types like ulittle16_t and little32_t, or
2641 /// structs composed of them.
2642 template <typename T>
2643 static void copyBytesForDefRange(SmallString<20> &BytePrefix,
2644                                  SymbolKind SymKind, const T &DefRangeHeader) {
2645   BytePrefix.resize(2 + sizeof(T));
2646   ulittle16_t SymKindLE = ulittle16_t(SymKind);
2647   memcpy(&BytePrefix[0], &SymKindLE, 2);
2648   memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
2649 }
2650 
2651 void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
2652                                       const LocalVariable &Var) {
2653   // LocalSym record, see SymbolRecord.h for more info.
2654   MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
2655 
2656   LocalSymFlags Flags = LocalSymFlags::None;
2657   if (Var.DIVar->isParameter())
2658     Flags |= LocalSymFlags::IsParameter;
2659   if (Var.DefRanges.empty())
2660     Flags |= LocalSymFlags::IsOptimizedOut;
2661 
2662   OS.AddComment("TypeIndex");
2663   TypeIndex TI = Var.UseReferenceType
2664                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2665                      : getCompleteTypeIndex(Var.DIVar->getType());
2666   OS.EmitIntValue(TI.getIndex(), 4);
2667   OS.AddComment("Flags");
2668   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2669   // Truncate the name so we won't overflow the record length field.
2670   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2671   endSymbolRecord(LocalEnd);
2672 
2673   // Calculate the on disk prefix of the appropriate def range record. The
2674   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2675   // should be big enough to hold all forms without memory allocation.
2676   SmallString<20> BytePrefix;
2677   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2678     BytePrefix.clear();
2679     if (DefRange.InMemory) {
2680       int Offset = DefRange.DataOffset;
2681       unsigned Reg = DefRange.CVRegister;
2682 
2683       // 32-bit x86 call sequences often use PUSH instructions, which disrupt
2684       // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
2685       // instead. In frames without stack realignment, $T0 will be the CFA.
2686       if (RegisterId(Reg) == RegisterId::ESP) {
2687         Reg = unsigned(RegisterId::VFRAME);
2688         Offset += FI.OffsetAdjustment;
2689       }
2690 
2691       // If we can use the chosen frame pointer for the frame and this isn't a
2692       // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
2693       // Otherwise, use S_DEFRANGE_REGISTER_REL.
2694       EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
2695       if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
2696           (bool(Flags & LocalSymFlags::IsParameter)
2697                ? (EncFP == FI.EncodedParamFramePtrReg)
2698                : (EncFP == FI.EncodedLocalFramePtrReg))) {
2699         little32_t FPOffset = little32_t(Offset);
2700         copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
2701       } else {
2702         uint16_t RegRelFlags = 0;
2703         if (DefRange.IsSubfield) {
2704           RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2705                         (DefRange.StructOffset
2706                          << DefRangeRegisterRelSym::OffsetInParentShift);
2707         }
2708         DefRangeRegisterRelSym::Header DRHdr;
2709         DRHdr.Register = Reg;
2710         DRHdr.Flags = RegRelFlags;
2711         DRHdr.BasePointerOffset = Offset;
2712         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
2713       }
2714     } else {
2715       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2716       if (DefRange.IsSubfield) {
2717         DefRangeSubfieldRegisterSym::Header DRHdr;
2718         DRHdr.Register = DefRange.CVRegister;
2719         DRHdr.MayHaveNoName = 0;
2720         DRHdr.OffsetInParent = DefRange.StructOffset;
2721         copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
2722       } else {
2723         DefRangeRegisterSym::Header DRHdr;
2724         DRHdr.Register = DefRange.CVRegister;
2725         DRHdr.MayHaveNoName = 0;
2726         copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
2727       }
2728     }
2729     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2730   }
2731 }
2732 
2733 void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
2734                                          const FunctionInfo& FI) {
2735   for (LexicalBlock *Block : Blocks)
2736     emitLexicalBlock(*Block, FI);
2737 }
2738 
2739 /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
2740 /// lexical block scope.
2741 void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
2742                                      const FunctionInfo& FI) {
2743   MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
2744   OS.AddComment("PtrParent");
2745   OS.EmitIntValue(0, 4);                                  // PtrParent
2746   OS.AddComment("PtrEnd");
2747   OS.EmitIntValue(0, 4);                                  // PtrEnd
2748   OS.AddComment("Code size");
2749   OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4);   // Code Size
2750   OS.AddComment("Function section relative address");
2751   OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0);         // Func Offset
2752   OS.AddComment("Function section index");
2753   OS.EmitCOFFSectionIndex(FI.Begin);                      // Func Symbol
2754   OS.AddComment("Lexical block name");
2755   emitNullTerminatedSymbolName(OS, Block.Name);           // Name
2756   endSymbolRecord(RecordEnd);
2757 
2758   // Emit variables local to this lexical block.
2759   emitLocalVariableList(FI, Block.Locals);
2760   emitGlobalVariableList(Block.Globals);
2761 
2762   // Emit lexical blocks contained within this block.
2763   emitLexicalBlockList(Block.Children, FI);
2764 
2765   // Close the lexical block scope.
2766   emitEndSymbolRecord(SymbolKind::S_END);
2767 }
2768 
2769 /// Convenience routine for collecting lexical block information for a list
2770 /// of lexical scopes.
2771 void CodeViewDebug::collectLexicalBlockInfo(
2772         SmallVectorImpl<LexicalScope *> &Scopes,
2773         SmallVectorImpl<LexicalBlock *> &Blocks,
2774         SmallVectorImpl<LocalVariable> &Locals,
2775         SmallVectorImpl<CVGlobalVariable> &Globals) {
2776   for (LexicalScope *Scope : Scopes)
2777     collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
2778 }
2779 
2780 /// Populate the lexical blocks and local variable lists of the parent with
2781 /// information about the specified lexical scope.
2782 void CodeViewDebug::collectLexicalBlockInfo(
2783     LexicalScope &Scope,
2784     SmallVectorImpl<LexicalBlock *> &ParentBlocks,
2785     SmallVectorImpl<LocalVariable> &ParentLocals,
2786     SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
2787   if (Scope.isAbstractScope())
2788     return;
2789 
2790   // Gather information about the lexical scope including local variables,
2791   // global variables, and address ranges.
2792   bool IgnoreScope = false;
2793   auto LI = ScopeVariables.find(&Scope);
2794   SmallVectorImpl<LocalVariable> *Locals =
2795       LI != ScopeVariables.end() ? &LI->second : nullptr;
2796   auto GI = ScopeGlobals.find(Scope.getScopeNode());
2797   SmallVectorImpl<CVGlobalVariable> *Globals =
2798       GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
2799   const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
2800   const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
2801 
2802   // Ignore lexical scopes which do not contain variables.
2803   if (!Locals && !Globals)
2804     IgnoreScope = true;
2805 
2806   // Ignore lexical scopes which are not lexical blocks.
2807   if (!DILB)
2808     IgnoreScope = true;
2809 
2810   // Ignore scopes which have too many address ranges to represent in the
2811   // current CodeView format or do not have a valid address range.
2812   //
2813   // For lexical scopes with multiple address ranges you may be tempted to
2814   // construct a single range covering every instruction where the block is
2815   // live and everything in between.  Unfortunately, Visual Studio only
2816   // displays variables from the first matching lexical block scope.  If the
2817   // first lexical block contains exception handling code or cold code which
2818   // is moved to the bottom of the routine creating a single range covering
2819   // nearly the entire routine, then it will hide all other lexical blocks
2820   // and the variables they contain.
2821   if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
2822     IgnoreScope = true;
2823 
2824   if (IgnoreScope) {
2825     // This scope can be safely ignored and eliminating it will reduce the
2826     // size of the debug information. Be sure to collect any variable and scope
2827     // information from the this scope or any of its children and collapse them
2828     // into the parent scope.
2829     if (Locals)
2830       ParentLocals.append(Locals->begin(), Locals->end());
2831     if (Globals)
2832       ParentGlobals.append(Globals->begin(), Globals->end());
2833     collectLexicalBlockInfo(Scope.getChildren(),
2834                             ParentBlocks,
2835                             ParentLocals,
2836                             ParentGlobals);
2837     return;
2838   }
2839 
2840   // Create a new CodeView lexical block for this lexical scope.  If we've
2841   // seen this DILexicalBlock before then the scope tree is malformed and
2842   // we can handle this gracefully by not processing it a second time.
2843   auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
2844   if (!BlockInsertion.second)
2845     return;
2846 
2847   // Create a lexical block containing the variables and collect the the
2848   // lexical block information for the children.
2849   const InsnRange &Range = Ranges.front();
2850   assert(Range.first && Range.second);
2851   LexicalBlock &Block = BlockInsertion.first->second;
2852   Block.Begin = getLabelBeforeInsn(Range.first);
2853   Block.End = getLabelAfterInsn(Range.second);
2854   assert(Block.Begin && "missing label for scope begin");
2855   assert(Block.End && "missing label for scope end");
2856   Block.Name = DILB->getName();
2857   if (Locals)
2858     Block.Locals = std::move(*Locals);
2859   if (Globals)
2860     Block.Globals = std::move(*Globals);
2861   ParentBlocks.push_back(&Block);
2862   collectLexicalBlockInfo(Scope.getChildren(),
2863                           Block.Children,
2864                           Block.Locals,
2865                           Block.Globals);
2866 }
2867 
2868 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2869   const Function &GV = MF->getFunction();
2870   assert(FnDebugInfo.count(&GV));
2871   assert(CurFn == FnDebugInfo[&GV].get());
2872 
2873   collectVariableInfo(GV.getSubprogram());
2874 
2875   // Build the lexical block structure to emit for this routine.
2876   if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
2877     collectLexicalBlockInfo(*CFS,
2878                             CurFn->ChildBlocks,
2879                             CurFn->Locals,
2880                             CurFn->Globals);
2881 
2882   // Clear the scope and variable information from the map which will not be
2883   // valid after we have finished processing this routine.  This also prepares
2884   // the map for the subsequent routine.
2885   ScopeVariables.clear();
2886 
2887   // Don't emit anything if we don't have any line tables.
2888   // Thunks are compiler-generated and probably won't have source correlation.
2889   if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
2890     FnDebugInfo.erase(&GV);
2891     CurFn = nullptr;
2892     return;
2893   }
2894 
2895   // Find heap alloc sites and add to list.
2896   for (const auto &MBB : *MF) {
2897     for (const auto &MI : MBB) {
2898       if (MDNode *MD = MI.getHeapAllocMarker()) {
2899         CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI),
2900                                                         getLabelAfterInsn(&MI),
2901                                                         dyn_cast<DIType>(MD)));
2902       }
2903     }
2904   }
2905 
2906   CurFn->Annotations = MF->getCodeViewAnnotations();
2907 
2908   CurFn->End = Asm->getFunctionEnd();
2909 
2910   CurFn = nullptr;
2911 }
2912 
2913 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2914   DebugHandlerBase::beginInstruction(MI);
2915 
2916   // Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
2917   if (!Asm || !CurFn || MI->isDebugInstr() ||
2918       MI->getFlag(MachineInstr::FrameSetup))
2919     return;
2920 
2921   // If the first instruction of a new MBB has no location, find the first
2922   // instruction with a location and use that.
2923   DebugLoc DL = MI->getDebugLoc();
2924   if (!DL && MI->getParent() != PrevInstBB) {
2925     for (const auto &NextMI : *MI->getParent()) {
2926       if (NextMI.isDebugInstr())
2927         continue;
2928       DL = NextMI.getDebugLoc();
2929       if (DL)
2930         break;
2931     }
2932   }
2933   PrevInstBB = MI->getParent();
2934 
2935   // If we still don't have a debug location, don't record a location.
2936   if (!DL)
2937     return;
2938 
2939   maybeRecordLocation(DL, Asm->MF);
2940 }
2941 
2942 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2943   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2944            *EndLabel = MMI->getContext().createTempSymbol();
2945   OS.EmitIntValue(unsigned(Kind), 4);
2946   OS.AddComment("Subsection size");
2947   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2948   OS.EmitLabel(BeginLabel);
2949   return EndLabel;
2950 }
2951 
2952 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2953   OS.EmitLabel(EndLabel);
2954   // Every subsection must be aligned to a 4-byte boundary.
2955   OS.EmitValueToAlignment(4);
2956 }
2957 
2958 static StringRef getSymbolName(SymbolKind SymKind) {
2959   for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
2960     if (EE.Value == SymKind)
2961       return EE.Name;
2962   return "";
2963 }
2964 
2965 MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
2966   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2967            *EndLabel = MMI->getContext().createTempSymbol();
2968   OS.AddComment("Record length");
2969   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
2970   OS.EmitLabel(BeginLabel);
2971   if (OS.isVerboseAsm())
2972     OS.AddComment("Record kind: " + getSymbolName(SymKind));
2973   OS.EmitIntValue(unsigned(SymKind), 2);
2974   return EndLabel;
2975 }
2976 
2977 void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
2978   // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
2979   // an extra copy of every symbol record in LLD. This increases object file
2980   // size by less than 1% in the clang build, and is compatible with the Visual
2981   // C++ linker.
2982   OS.EmitValueToAlignment(4);
2983   OS.EmitLabel(SymEnd);
2984 }
2985 
2986 void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
2987   OS.AddComment("Record length");
2988   OS.EmitIntValue(2, 2);
2989   if (OS.isVerboseAsm())
2990     OS.AddComment("Record kind: " + getSymbolName(EndKind));
2991   OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
2992 }
2993 
2994 void CodeViewDebug::emitDebugInfoForUDTs(
2995     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2996   for (const auto &UDT : UDTs) {
2997     const DIType *T = UDT.second;
2998     assert(shouldEmitUdt(T));
2999 
3000     MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
3001     OS.AddComment("Type");
3002     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
3003     emitNullTerminatedSymbolName(OS, UDT.first);
3004     endSymbolRecord(UDTRecordEnd);
3005   }
3006 }
3007 
3008 void CodeViewDebug::collectGlobalVariableInfo() {
3009   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
3010       GlobalMap;
3011   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
3012     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
3013     GV.getDebugInfo(GVEs);
3014     for (const auto *GVE : GVEs)
3015       GlobalMap[GVE] = &GV;
3016   }
3017 
3018   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3019   for (const MDNode *Node : CUs->operands()) {
3020     const auto *CU = cast<DICompileUnit>(Node);
3021     for (const auto *GVE : CU->getGlobalVariables()) {
3022       const DIGlobalVariable *DIGV = GVE->getVariable();
3023       const DIExpression *DIE = GVE->getExpression();
3024 
3025       // Emit constant global variables in a global symbol section.
3026       if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
3027         CVGlobalVariable CVGV = {DIGV, DIE};
3028         GlobalVariables.emplace_back(std::move(CVGV));
3029       }
3030 
3031       const auto *GV = GlobalMap.lookup(GVE);
3032       if (!GV || GV->isDeclarationForLinker())
3033         continue;
3034 
3035       DIScope *Scope = DIGV->getScope();
3036       SmallVector<CVGlobalVariable, 1> *VariableList;
3037       if (Scope && isa<DILocalScope>(Scope)) {
3038         // Locate a global variable list for this scope, creating one if
3039         // necessary.
3040         auto Insertion = ScopeGlobals.insert(
3041             {Scope, std::unique_ptr<GlobalVariableList>()});
3042         if (Insertion.second)
3043           Insertion.first->second = llvm::make_unique<GlobalVariableList>();
3044         VariableList = Insertion.first->second.get();
3045       } else if (GV->hasComdat())
3046         // Emit this global variable into a COMDAT section.
3047         VariableList = &ComdatVariables;
3048       else
3049         // Emit this global variable in a single global symbol section.
3050         VariableList = &GlobalVariables;
3051       CVGlobalVariable CVGV = {DIGV, GV};
3052       VariableList->emplace_back(std::move(CVGV));
3053     }
3054   }
3055 }
3056 
3057 void CodeViewDebug::emitDebugInfoForGlobals() {
3058   // First, emit all globals that are not in a comdat in a single symbol
3059   // substream. MSVC doesn't like it if the substream is empty, so only open
3060   // it if we have at least one global to emit.
3061   switchToDebugSectionForSymbol(nullptr);
3062   if (!GlobalVariables.empty()) {
3063     OS.AddComment("Symbol subsection for globals");
3064     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3065     emitGlobalVariableList(GlobalVariables);
3066     endCVSubsection(EndLabel);
3067   }
3068 
3069   // Second, emit each global that is in a comdat into its own .debug$S
3070   // section along with its own symbol substream.
3071   for (const CVGlobalVariable &CVGV : ComdatVariables) {
3072     const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
3073     MCSymbol *GVSym = Asm->getSymbol(GV);
3074     OS.AddComment("Symbol subsection for " +
3075                   Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
3076     switchToDebugSectionForSymbol(GVSym);
3077     MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
3078     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3079     emitDebugInfoForGlobal(CVGV);
3080     endCVSubsection(EndLabel);
3081   }
3082 }
3083 
3084 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
3085   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
3086   for (const MDNode *Node : CUs->operands()) {
3087     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
3088       if (DIType *RT = dyn_cast<DIType>(Ty)) {
3089         getTypeIndex(RT);
3090         // FIXME: Add to global/local DTU list.
3091       }
3092     }
3093   }
3094 }
3095 
3096 // Emit each global variable in the specified array.
3097 void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
3098   for (const CVGlobalVariable &CVGV : Globals) {
3099     // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
3100     emitDebugInfoForGlobal(CVGV);
3101   }
3102 }
3103 
3104 void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
3105   const DIGlobalVariable *DIGV = CVGV.DIGV;
3106   if (const GlobalVariable *GV =
3107           CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
3108     // DataSym record, see SymbolRecord.h for more info. Thread local data
3109     // happens to have the same format as global data.
3110     MCSymbol *GVSym = Asm->getSymbol(GV);
3111     SymbolKind DataSym = GV->isThreadLocal()
3112                              ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
3113                                                       : SymbolKind::S_GTHREAD32)
3114                              : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
3115                                                       : SymbolKind::S_GDATA32);
3116     MCSymbol *DataEnd = beginSymbolRecord(DataSym);
3117     OS.AddComment("Type");
3118     OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
3119     OS.AddComment("DataOffset");
3120     OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
3121     OS.AddComment("Segment");
3122     OS.EmitCOFFSectionIndex(GVSym);
3123     OS.AddComment("Name");
3124     const unsigned LengthOfDataRecord = 12;
3125     emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
3126     endSymbolRecord(DataEnd);
3127   } else {
3128     // FIXME: Currently this only emits the global variables in the IR metadata.
3129     // This should also emit enums and static data members.
3130     const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
3131     assert(DIE->isConstant() &&
3132            "Global constant variables must contain a constant expression.");
3133     uint64_t Val = DIE->getElement(1);
3134 
3135     MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
3136     OS.AddComment("Type");
3137     OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
3138     OS.AddComment("Value");
3139 
3140     // Encoded integers shouldn't need more than 10 bytes.
3141     uint8_t data[10];
3142     BinaryStreamWriter Writer(data, llvm::support::endianness::little);
3143     CodeViewRecordIO IO(Writer);
3144     cantFail(IO.mapEncodedInteger(Val));
3145     StringRef SRef((char *)data, Writer.getOffset());
3146     OS.EmitBinaryData(SRef);
3147 
3148     OS.AddComment("Name");
3149     const DIScope *Scope = DIGV->getScope();
3150     // For static data members, get the scope from the declaration.
3151     if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
3152             DIGV->getRawStaticDataMemberDeclaration()))
3153       Scope = MemberDecl->getScope();
3154     emitNullTerminatedSymbolName(OS,
3155                                  getFullyQualifiedName(Scope, DIGV->getName()));
3156     endSymbolRecord(SConstantEnd);
3157   }
3158 }
3159