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