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