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