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