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