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