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