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