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