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