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