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