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