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