1 //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing Microsoft CodeView debug info.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeViewDebug.h"
15 #include "DwarfExpression.h"
16 #include "llvm/ADT/APSInt.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/MapVector.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/TinyPtrVector.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/BinaryFormat/COFF.h"
31 #include "llvm/BinaryFormat/Dwarf.h"
32 #include "llvm/CodeGen/AsmPrinter.h"
33 #include "llvm/CodeGen/LexicalScopes.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineInstr.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineOperand.h"
38 #include "llvm/CodeGen/TargetFrameLowering.h"
39 #include "llvm/CodeGen/TargetLoweringObjectFile.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/Config/llvm-config.h"
43 #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
44 #include "llvm/DebugInfo/CodeView/CodeView.h"
45 #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
46 #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
47 #include "llvm/DebugInfo/CodeView/Line.h"
48 #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
49 #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
50 #include "llvm/DebugInfo/CodeView/TypeIndex.h"
51 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
52 #include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugInfoMetadata.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/GlobalValue.h"
59 #include "llvm/IR/GlobalVariable.h"
60 #include "llvm/IR/Metadata.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/MC/MCAsmInfo.h"
63 #include "llvm/MC/MCContext.h"
64 #include "llvm/MC/MCSectionCOFF.h"
65 #include "llvm/MC/MCStreamer.h"
66 #include "llvm/MC/MCSymbol.h"
67 #include "llvm/Support/BinaryByteStream.h"
68 #include "llvm/Support/BinaryStreamReader.h"
69 #include "llvm/Support/Casting.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/Endian.h"
73 #include "llvm/Support/Error.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/FormatVariadic.h"
76 #include "llvm/Support/SMLoc.h"
77 #include "llvm/Support/ScopedPrinter.h"
78 #include "llvm/Target/TargetMachine.h"
79 #include <algorithm>
80 #include <cassert>
81 #include <cctype>
82 #include <cstddef>
83 #include <cstdint>
84 #include <iterator>
85 #include <limits>
86 #include <string>
87 #include <utility>
88 #include <vector>
89 
90 using namespace llvm;
91 using namespace llvm::codeview;
92 
93 static cl::opt<bool> EmitDebugGlobalHashes("emit-codeview-ghash-section",
94                                            cl::ReallyHidden, cl::init(false));
95 
96 CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
97     : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
98   // If module doesn't have named metadata anchors or COFF debug section
99   // is not available, skip any debug info related stuff.
100   if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
101       !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
102     Asm = nullptr;
103     return;
104   }
105 
106   // Tell MMI that we have debug info.
107   MMI->setDebugInfoAvailability(true);
108 }
109 
110 StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
111   std::string &Filepath = FileToFilepathMap[File];
112   if (!Filepath.empty())
113     return Filepath;
114 
115   StringRef Dir = File->getDirectory(), Filename = File->getFilename();
116 
117   // Clang emits directory and relative filename info into the IR, but CodeView
118   // operates on full paths.  We could change Clang to emit full paths too, but
119   // that would increase the IR size and probably not needed for other users.
120   // For now, just concatenate and canonicalize the path here.
121   if (Filename.find(':') == 1)
122     Filepath = Filename;
123   else
124     Filepath = (Dir + "\\" + Filename).str();
125 
126   // Canonicalize the path.  We have to do it textually because we may no longer
127   // have access the file in the filesystem.
128   // First, replace all slashes with backslashes.
129   std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
130 
131   // Remove all "\.\" with "\".
132   size_t Cursor = 0;
133   while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
134     Filepath.erase(Cursor, 2);
135 
136   // Replace all "\XXX\..\" with "\".  Don't try too hard though as the original
137   // path should be well-formatted, e.g. start with a drive letter, etc.
138   Cursor = 0;
139   while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
140     // Something's wrong if the path starts with "\..\", abort.
141     if (Cursor == 0)
142       break;
143 
144     size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
145     if (PrevSlash == std::string::npos)
146       // Something's wrong, abort.
147       break;
148 
149     Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
150     // The next ".." might be following the one we've just erased.
151     Cursor = PrevSlash;
152   }
153 
154   // Remove all duplicate backslashes.
155   Cursor = 0;
156   while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
157     Filepath.erase(Cursor, 1);
158 
159   return Filepath;
160 }
161 
162 unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
163   StringRef FullPath = getFullFilepath(F);
164   unsigned NextId = FileIdMap.size() + 1;
165   auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
166   if (Insertion.second) {
167     // We have to compute the full filepath and emit a .cv_file directive.
168     std::string Checksum = fromHex(F->getChecksum());
169     void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
170     memcpy(CKMem, Checksum.data(), Checksum.size());
171     ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
172                                       Checksum.size());
173     DIFile::ChecksumKind ChecksumKind = F->getChecksumKind();
174     bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
175                                           static_cast<unsigned>(ChecksumKind));
176     (void)Success;
177     assert(Success && ".cv_file directive failed");
178   }
179   return Insertion.first->second;
180 }
181 
182 CodeViewDebug::InlineSite &
183 CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
184                              const DISubprogram *Inlinee) {
185   auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
186   InlineSite *Site = &SiteInsertion.first->second;
187   if (SiteInsertion.second) {
188     unsigned ParentFuncId = CurFn->FuncId;
189     if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
190       ParentFuncId =
191           getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
192               .SiteFuncId;
193 
194     Site->SiteFuncId = NextFuncId++;
195     OS.EmitCVInlineSiteIdDirective(
196         Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
197         InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
198     Site->Inlinee = Inlinee;
199     InlinedSubprograms.insert(Inlinee);
200     getFuncIdForSubprogram(Inlinee);
201   }
202   return *Site;
203 }
204 
205 static StringRef getPrettyScopeName(const DIScope *Scope) {
206   StringRef ScopeName = Scope->getName();
207   if (!ScopeName.empty())
208     return ScopeName;
209 
210   switch (Scope->getTag()) {
211   case dwarf::DW_TAG_enumeration_type:
212   case dwarf::DW_TAG_class_type:
213   case dwarf::DW_TAG_structure_type:
214   case dwarf::DW_TAG_union_type:
215     return "<unnamed-tag>";
216   case dwarf::DW_TAG_namespace:
217     return "`anonymous namespace'";
218   }
219 
220   return StringRef();
221 }
222 
223 static const DISubprogram *getQualifiedNameComponents(
224     const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
225   const DISubprogram *ClosestSubprogram = nullptr;
226   while (Scope != nullptr) {
227     if (ClosestSubprogram == nullptr)
228       ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
229     StringRef ScopeName = getPrettyScopeName(Scope);
230     if (!ScopeName.empty())
231       QualifiedNameComponents.push_back(ScopeName);
232     Scope = Scope->getScope().resolve();
233   }
234   return ClosestSubprogram;
235 }
236 
237 static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
238                                     StringRef TypeName) {
239   std::string FullyQualifiedName;
240   for (StringRef QualifiedNameComponent :
241        llvm::reverse(QualifiedNameComponents)) {
242     FullyQualifiedName.append(QualifiedNameComponent);
243     FullyQualifiedName.append("::");
244   }
245   FullyQualifiedName.append(TypeName);
246   return FullyQualifiedName;
247 }
248 
249 static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
250   SmallVector<StringRef, 5> QualifiedNameComponents;
251   getQualifiedNameComponents(Scope, QualifiedNameComponents);
252   return getQualifiedName(QualifiedNameComponents, Name);
253 }
254 
255 struct CodeViewDebug::TypeLoweringScope {
256   TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
257   ~TypeLoweringScope() {
258     // Don't decrement TypeEmissionLevel until after emitting deferred types, so
259     // inner TypeLoweringScopes don't attempt to emit deferred types.
260     if (CVD.TypeEmissionLevel == 1)
261       CVD.emitDeferredCompleteTypes();
262     --CVD.TypeEmissionLevel;
263   }
264   CodeViewDebug &CVD;
265 };
266 
267 static std::string getFullyQualifiedName(const DIScope *Ty) {
268   const DIScope *Scope = Ty->getScope().resolve();
269   return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
270 }
271 
272 TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
273   // No scope means global scope and that uses the zero index.
274   if (!Scope || isa<DIFile>(Scope))
275     return TypeIndex();
276 
277   assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
278 
279   // Check if we've already translated this scope.
280   auto I = TypeIndices.find({Scope, nullptr});
281   if (I != TypeIndices.end())
282     return I->second;
283 
284   // Build the fully qualified name of the scope.
285   std::string ScopeName = getFullyQualifiedName(Scope);
286   StringIdRecord SID(TypeIndex(), ScopeName);
287   auto TI = TypeTable.writeLeafType(SID);
288   return recordTypeIndexForDINode(Scope, TI);
289 }
290 
291 TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
292   assert(SP);
293 
294   // Check if we've already translated this subprogram.
295   auto I = TypeIndices.find({SP, nullptr});
296   if (I != TypeIndices.end())
297     return I->second;
298 
299   // The display name includes function template arguments. Drop them to match
300   // MSVC.
301   StringRef DisplayName = SP->getName().split('<').first;
302 
303   const DIScope *Scope = SP->getScope().resolve();
304   TypeIndex TI;
305   if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
306     // If the scope is a DICompositeType, then this must be a method. Member
307     // function types take some special handling, and require access to the
308     // subprogram.
309     TypeIndex ClassType = getTypeIndex(Class);
310     MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
311                                DisplayName);
312     TI = TypeTable.writeLeafType(MFuncId);
313   } else {
314     // Otherwise, this must be a free function.
315     TypeIndex ParentScope = getScopeIndex(Scope);
316     FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
317     TI = TypeTable.writeLeafType(FuncId);
318   }
319 
320   return recordTypeIndexForDINode(SP, TI);
321 }
322 
323 TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
324                                                const DICompositeType *Class) {
325   // Always use the method declaration as the key for the function type. The
326   // method declaration contains the this adjustment.
327   if (SP->getDeclaration())
328     SP = SP->getDeclaration();
329   assert(!SP->getDeclaration() && "should use declaration as key");
330 
331   // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
332   // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
333   auto I = TypeIndices.find({SP, Class});
334   if (I != TypeIndices.end())
335     return I->second;
336 
337   // Make sure complete type info for the class is emitted *after* the member
338   // function type, as the complete class type is likely to reference this
339   // member function type.
340   TypeLoweringScope S(*this);
341   const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
342   TypeIndex TI = lowerTypeMemberFunction(
343       SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod);
344   return recordTypeIndexForDINode(SP, TI, Class);
345 }
346 
347 TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
348                                                   TypeIndex TI,
349                                                   const DIType *ClassTy) {
350   auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
351   (void)InsertResult;
352   assert(InsertResult.second && "DINode was already assigned a type index");
353   return TI;
354 }
355 
356 unsigned CodeViewDebug::getPointerSizeInBytes() {
357   return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
358 }
359 
360 void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
361                                         const DILocation *InlinedAt) {
362   if (InlinedAt) {
363     // This variable was inlined. Associate it with the InlineSite.
364     const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
365     InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
366     Site.InlinedLocals.emplace_back(Var);
367   } else {
368     // This variable goes in the main ProcSym.
369     CurFn->Locals.emplace_back(Var);
370   }
371 }
372 
373 static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
374                                const DILocation *Loc) {
375   auto B = Locs.begin(), E = Locs.end();
376   if (std::find(B, E, Loc) == E)
377     Locs.push_back(Loc);
378 }
379 
380 void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
381                                         const MachineFunction *MF) {
382   // Skip this instruction if it has the same location as the previous one.
383   if (!DL || DL == PrevInstLoc)
384     return;
385 
386   const DIScope *Scope = DL.get()->getScope();
387   if (!Scope)
388     return;
389 
390   // Skip this line if it is longer than the maximum we can record.
391   LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
392   if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
393       LI.isNeverStepInto())
394     return;
395 
396   ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
397   if (CI.getStartColumn() != DL.getCol())
398     return;
399 
400   if (!CurFn->HaveLineInfo)
401     CurFn->HaveLineInfo = true;
402   unsigned FileId = 0;
403   if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
404     FileId = CurFn->LastFileId;
405   else
406     FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
407   PrevInstLoc = DL;
408 
409   unsigned FuncId = CurFn->FuncId;
410   if (const DILocation *SiteLoc = DL->getInlinedAt()) {
411     const DILocation *Loc = DL.get();
412 
413     // If this location was actually inlined from somewhere else, give it the ID
414     // of the inline call site.
415     FuncId =
416         getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
417 
418     // Ensure we have links in the tree of inline call sites.
419     bool FirstLoc = true;
420     while ((SiteLoc = Loc->getInlinedAt())) {
421       InlineSite &Site =
422           getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
423       if (!FirstLoc)
424         addLocIfNotPresent(Site.ChildSites, Loc);
425       FirstLoc = false;
426       Loc = SiteLoc;
427     }
428     addLocIfNotPresent(CurFn->ChildSites, Loc);
429   }
430 
431   OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
432                         /*PrologueEnd=*/false, /*IsStmt=*/false,
433                         DL->getFilename(), SMLoc());
434 }
435 
436 void CodeViewDebug::emitCodeViewMagicVersion() {
437   OS.EmitValueToAlignment(4);
438   OS.AddComment("Debug section magic");
439   OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
440 }
441 
442 void CodeViewDebug::endModule() {
443   if (!Asm || !MMI->hasDebugInfo())
444     return;
445 
446   assert(Asm != nullptr);
447 
448   // The COFF .debug$S section consists of several subsections, each starting
449   // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
450   // of the payload followed by the payload itself.  The subsections are 4-byte
451   // aligned.
452 
453   // Use the generic .debug$S section, and make a subsection for all the inlined
454   // subprograms.
455   switchToDebugSectionForSymbol(nullptr);
456 
457   MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
458   emitCompilerInformation();
459   endCVSubsection(CompilerInfo);
460 
461   emitInlineeLinesSubsection();
462 
463   // Emit per-function debug information.
464   for (auto &P : FnDebugInfo)
465     if (!P.first->isDeclarationForLinker())
466       emitDebugInfoForFunction(P.first, P.second);
467 
468   // Emit global variable debug information.
469   setCurrentSubprogram(nullptr);
470   emitDebugInfoForGlobals();
471 
472   // Emit retained types.
473   emitDebugInfoForRetainedTypes();
474 
475   // Switch back to the generic .debug$S section after potentially processing
476   // comdat symbol sections.
477   switchToDebugSectionForSymbol(nullptr);
478 
479   // Emit UDT records for any types used by global variables.
480   if (!GlobalUDTs.empty()) {
481     MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
482     emitDebugInfoForUDTs(GlobalUDTs);
483     endCVSubsection(SymbolsEnd);
484   }
485 
486   // This subsection holds a file index to offset in string table table.
487   OS.AddComment("File index to string table offset subsection");
488   OS.EmitCVFileChecksumsDirective();
489 
490   // This subsection holds the string table.
491   OS.AddComment("String table");
492   OS.EmitCVStringTableDirective();
493 
494   // Emit type information and hashes last, so that any types we translate while
495   // emitting function info are included.
496   emitTypeInformation();
497 
498   if (EmitDebugGlobalHashes)
499     emitTypeGlobalHashes();
500 
501   clear();
502 }
503 
504 static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S) {
505   // The maximum CV record length is 0xFF00. Most of the strings we emit appear
506   // after a fixed length portion of the record. The fixed length portion should
507   // always be less than 0xF00 (3840) bytes, so truncate the string so that the
508   // overall record size is less than the maximum allowed.
509   unsigned MaxFixedRecordLength = 0xF00;
510   SmallString<32> NullTerminatedString(
511       S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
512   NullTerminatedString.push_back('\0');
513   OS.EmitBytes(NullTerminatedString);
514 }
515 
516 void CodeViewDebug::emitTypeInformation() {
517   if (TypeTable.empty())
518     return;
519 
520   // Start the .debug$T section with 0x4.
521   OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
522   emitCodeViewMagicVersion();
523 
524   SmallString<8> CommentPrefix;
525   if (OS.isVerboseAsm()) {
526     CommentPrefix += '\t';
527     CommentPrefix += Asm->MAI->getCommentString();
528     CommentPrefix += ' ';
529   }
530 
531   TypeTableCollection Table(TypeTable.records());
532   Optional<TypeIndex> B = Table.getFirst();
533   while (B) {
534     // This will fail if the record data is invalid.
535     CVType Record = Table.getType(*B);
536 
537     if (OS.isVerboseAsm()) {
538       // Emit a block comment describing the type record for readability.
539       SmallString<512> CommentBlock;
540       raw_svector_ostream CommentOS(CommentBlock);
541       ScopedPrinter SP(CommentOS);
542       SP.setPrefix(CommentPrefix);
543       TypeDumpVisitor TDV(Table, &SP, false);
544 
545       Error E = codeview::visitTypeRecord(Record, *B, TDV);
546       if (E) {
547         logAllUnhandledErrors(std::move(E), errs(), "error: ");
548         llvm_unreachable("produced malformed type record");
549       }
550       // emitRawComment will insert its own tab and comment string before
551       // the first line, so strip off our first one. It also prints its own
552       // newline.
553       OS.emitRawComment(
554           CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
555     }
556     OS.EmitBinaryData(Record.str_data());
557     B = Table.getNext(*B);
558   }
559 }
560 
561 void CodeViewDebug::emitTypeGlobalHashes() {
562   if (TypeTable.empty())
563     return;
564 
565   // Start the .debug$H section with the version and hash algorithm, currently
566   // hardcoded to version 0, SHA1.
567   OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
568 
569   OS.EmitValueToAlignment(4);
570   OS.AddComment("Magic");
571   OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
572   OS.AddComment("Section Version");
573   OS.EmitIntValue(0, 2);
574   OS.AddComment("Hash Algorithm");
575   OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1), 2);
576 
577   TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
578   for (const auto &GHR : TypeTable.hashes()) {
579     if (OS.isVerboseAsm()) {
580       // Emit an EOL-comment describing which TypeIndex this hash corresponds
581       // to, as well as the stringified SHA1 hash.
582       SmallString<32> Comment;
583       raw_svector_ostream CommentOS(Comment);
584       CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
585       OS.AddComment(Comment);
586       ++TI;
587     }
588     assert(GHR.Hash.size() % 20 == 0);
589     StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
590                 GHR.Hash.size());
591     OS.EmitBinaryData(S);
592   }
593 }
594 
595 static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
596   switch (DWLang) {
597   case dwarf::DW_LANG_C:
598   case dwarf::DW_LANG_C89:
599   case dwarf::DW_LANG_C99:
600   case dwarf::DW_LANG_C11:
601   case dwarf::DW_LANG_ObjC:
602     return SourceLanguage::C;
603   case dwarf::DW_LANG_C_plus_plus:
604   case dwarf::DW_LANG_C_plus_plus_03:
605   case dwarf::DW_LANG_C_plus_plus_11:
606   case dwarf::DW_LANG_C_plus_plus_14:
607     return SourceLanguage::Cpp;
608   case dwarf::DW_LANG_Fortran77:
609   case dwarf::DW_LANG_Fortran90:
610   case dwarf::DW_LANG_Fortran03:
611   case dwarf::DW_LANG_Fortran08:
612     return SourceLanguage::Fortran;
613   case dwarf::DW_LANG_Pascal83:
614     return SourceLanguage::Pascal;
615   case dwarf::DW_LANG_Cobol74:
616   case dwarf::DW_LANG_Cobol85:
617     return SourceLanguage::Cobol;
618   case dwarf::DW_LANG_Java:
619     return SourceLanguage::Java;
620   case dwarf::DW_LANG_D:
621     return SourceLanguage::D;
622   default:
623     // There's no CodeView representation for this language, and CV doesn't
624     // have an "unknown" option for the language field, so we'll use MASM,
625     // as it's very low level.
626     return SourceLanguage::Masm;
627   }
628 }
629 
630 namespace {
631 struct Version {
632   int Part[4];
633 };
634 } // end anonymous namespace
635 
636 // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
637 // the version number.
638 static Version parseVersion(StringRef Name) {
639   Version V = {{0}};
640   int N = 0;
641   for (const char C : Name) {
642     if (isdigit(C)) {
643       V.Part[N] *= 10;
644       V.Part[N] += C - '0';
645     } else if (C == '.') {
646       ++N;
647       if (N >= 4)
648         return V;
649     } else if (N > 0)
650       return V;
651   }
652   return V;
653 }
654 
655 static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
656   switch (Type) {
657   case Triple::ArchType::x86:
658     return CPUType::Pentium3;
659   case Triple::ArchType::x86_64:
660     return CPUType::X64;
661   case Triple::ArchType::thumb:
662     return CPUType::Thumb;
663   case Triple::ArchType::aarch64:
664     return CPUType::ARM64;
665   default:
666     report_fatal_error("target architecture doesn't map to a CodeView CPUType");
667   }
668 }
669 
670 void CodeViewDebug::emitCompilerInformation() {
671   MCContext &Context = MMI->getContext();
672   MCSymbol *CompilerBegin = Context.createTempSymbol(),
673            *CompilerEnd = Context.createTempSymbol();
674   OS.AddComment("Record length");
675   OS.emitAbsoluteSymbolDiff(CompilerEnd, CompilerBegin, 2);
676   OS.EmitLabel(CompilerBegin);
677   OS.AddComment("Record kind: S_COMPILE3");
678   OS.EmitIntValue(SymbolKind::S_COMPILE3, 2);
679   uint32_t Flags = 0;
680 
681   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
682   const MDNode *Node = *CUs->operands().begin();
683   const auto *CU = cast<DICompileUnit>(Node);
684 
685   // The low byte of the flags indicates the source language.
686   Flags = MapDWLangToCVLang(CU->getSourceLanguage());
687   // TODO:  Figure out which other flags need to be set.
688 
689   OS.AddComment("Flags and language");
690   OS.EmitIntValue(Flags, 4);
691 
692   OS.AddComment("CPUType");
693   CPUType CPU =
694       mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
695   OS.EmitIntValue(static_cast<uint64_t>(CPU), 2);
696 
697   StringRef CompilerVersion = CU->getProducer();
698   Version FrontVer = parseVersion(CompilerVersion);
699   OS.AddComment("Frontend version");
700   for (int N = 0; N < 4; ++N)
701     OS.EmitIntValue(FrontVer.Part[N], 2);
702 
703   // Some Microsoft tools, like Binscope, expect a backend version number of at
704   // least 8.something, so we'll coerce the LLVM version into a form that
705   // guarantees it'll be big enough without really lying about the version.
706   int Major = 1000 * LLVM_VERSION_MAJOR +
707               10 * LLVM_VERSION_MINOR +
708               LLVM_VERSION_PATCH;
709   // Clamp it for builds that use unusually large version numbers.
710   Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
711   Version BackVer = {{ Major, 0, 0, 0 }};
712   OS.AddComment("Backend version");
713   for (int N = 0; N < 4; ++N)
714     OS.EmitIntValue(BackVer.Part[N], 2);
715 
716   OS.AddComment("Null-terminated compiler version string");
717   emitNullTerminatedSymbolName(OS, CompilerVersion);
718 
719   OS.EmitLabel(CompilerEnd);
720 }
721 
722 void CodeViewDebug::emitInlineeLinesSubsection() {
723   if (InlinedSubprograms.empty())
724     return;
725 
726   OS.AddComment("Inlinee lines subsection");
727   MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
728 
729   // We emit the checksum info for files.  This is used by debuggers to
730   // determine if a pdb matches the source before loading it.  Visual Studio,
731   // for instance, will display a warning that the breakpoints are not valid if
732   // the pdb does not match the source.
733   OS.AddComment("Inlinee lines signature");
734   OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
735 
736   for (const DISubprogram *SP : InlinedSubprograms) {
737     assert(TypeIndices.count({SP, nullptr}));
738     TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
739 
740     OS.AddBlankLine();
741     unsigned FileId = maybeRecordFile(SP->getFile());
742     OS.AddComment("Inlined function " + SP->getName() + " starts at " +
743                   SP->getFilename() + Twine(':') + Twine(SP->getLine()));
744     OS.AddBlankLine();
745     OS.AddComment("Type index of inlined function");
746     OS.EmitIntValue(InlineeIdx.getIndex(), 4);
747     OS.AddComment("Offset into filechecksum table");
748     OS.EmitCVFileChecksumOffsetDirective(FileId);
749     OS.AddComment("Starting line number");
750     OS.EmitIntValue(SP->getLine(), 4);
751   }
752 
753   endCVSubsection(InlineEnd);
754 }
755 
756 void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
757                                         const DILocation *InlinedAt,
758                                         const InlineSite &Site) {
759   MCSymbol *InlineBegin = MMI->getContext().createTempSymbol(),
760            *InlineEnd = MMI->getContext().createTempSymbol();
761 
762   assert(TypeIndices.count({Site.Inlinee, nullptr}));
763   TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
764 
765   // SymbolRecord
766   OS.AddComment("Record length");
767   OS.emitAbsoluteSymbolDiff(InlineEnd, InlineBegin, 2);   // RecordLength
768   OS.EmitLabel(InlineBegin);
769   OS.AddComment("Record kind: S_INLINESITE");
770   OS.EmitIntValue(SymbolKind::S_INLINESITE, 2); // RecordKind
771 
772   OS.AddComment("PtrParent");
773   OS.EmitIntValue(0, 4);
774   OS.AddComment("PtrEnd");
775   OS.EmitIntValue(0, 4);
776   OS.AddComment("Inlinee type index");
777   OS.EmitIntValue(InlineeIdx.getIndex(), 4);
778 
779   unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
780   unsigned StartLineNum = Site.Inlinee->getLine();
781 
782   OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
783                                     FI.Begin, FI.End);
784 
785   OS.EmitLabel(InlineEnd);
786 
787   emitLocalVariableList(Site.InlinedLocals);
788 
789   // Recurse on child inlined call sites before closing the scope.
790   for (const DILocation *ChildSite : Site.ChildSites) {
791     auto I = FI.InlineSites.find(ChildSite);
792     assert(I != FI.InlineSites.end() &&
793            "child site not in function inline site map");
794     emitInlinedCallSite(FI, ChildSite, I->second);
795   }
796 
797   // Close the scope.
798   OS.AddComment("Record length");
799   OS.EmitIntValue(2, 2);                                  // RecordLength
800   OS.AddComment("Record kind: S_INLINESITE_END");
801   OS.EmitIntValue(SymbolKind::S_INLINESITE_END, 2); // RecordKind
802 }
803 
804 void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
805   // If we have a symbol, it may be in a section that is COMDAT. If so, find the
806   // comdat key. A section may be comdat because of -ffunction-sections or
807   // because it is comdat in the IR.
808   MCSectionCOFF *GVSec =
809       GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
810   const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
811 
812   MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
813       Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
814   DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
815 
816   OS.SwitchSection(DebugSec);
817 
818   // Emit the magic version number if this is the first time we've switched to
819   // this section.
820   if (ComdatDebugSections.insert(DebugSec).second)
821     emitCodeViewMagicVersion();
822 }
823 
824 void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
825                                              FunctionInfo &FI) {
826   // For each function there is a separate subsection
827   // which holds the PC to file:line table.
828   const MCSymbol *Fn = Asm->getSymbol(GV);
829   assert(Fn);
830 
831   // Switch to the to a comdat section, if appropriate.
832   switchToDebugSectionForSymbol(Fn);
833 
834   std::string FuncName;
835   auto *SP = GV->getSubprogram();
836   assert(SP);
837   setCurrentSubprogram(SP);
838 
839   // If we have a display name, build the fully qualified name by walking the
840   // chain of scopes.
841   if (!SP->getName().empty())
842     FuncName =
843         getFullyQualifiedName(SP->getScope().resolve(), SP->getName());
844 
845   // If our DISubprogram name is empty, use the mangled name.
846   if (FuncName.empty())
847     FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
848 
849   // Emit FPO data, but only on 32-bit x86. No other platforms use it.
850   if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
851     OS.EmitCVFPOData(Fn);
852 
853   // Emit a symbol subsection, required by VS2012+ to find function boundaries.
854   OS.AddComment("Symbol subsection for " + Twine(FuncName));
855   MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
856   {
857     MCSymbol *ProcRecordBegin = MMI->getContext().createTempSymbol(),
858              *ProcRecordEnd = MMI->getContext().createTempSymbol();
859     OS.AddComment("Record length");
860     OS.emitAbsoluteSymbolDiff(ProcRecordEnd, ProcRecordBegin, 2);
861     OS.EmitLabel(ProcRecordBegin);
862 
863     if (GV->hasLocalLinkage()) {
864       OS.AddComment("Record kind: S_LPROC32_ID");
865       OS.EmitIntValue(unsigned(SymbolKind::S_LPROC32_ID), 2);
866     } else {
867       OS.AddComment("Record kind: S_GPROC32_ID");
868       OS.EmitIntValue(unsigned(SymbolKind::S_GPROC32_ID), 2);
869     }
870 
871     // These fields are filled in by tools like CVPACK which run after the fact.
872     OS.AddComment("PtrParent");
873     OS.EmitIntValue(0, 4);
874     OS.AddComment("PtrEnd");
875     OS.EmitIntValue(0, 4);
876     OS.AddComment("PtrNext");
877     OS.EmitIntValue(0, 4);
878     // This is the important bit that tells the debugger where the function
879     // code is located and what's its size:
880     OS.AddComment("Code size");
881     OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
882     OS.AddComment("Offset after prologue");
883     OS.EmitIntValue(0, 4);
884     OS.AddComment("Offset before epilogue");
885     OS.EmitIntValue(0, 4);
886     OS.AddComment("Function type index");
887     OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
888     OS.AddComment("Function section relative address");
889     OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
890     OS.AddComment("Function section index");
891     OS.EmitCOFFSectionIndex(Fn);
892     OS.AddComment("Flags");
893     OS.EmitIntValue(0, 1);
894     // Emit the function display name as a null-terminated string.
895     OS.AddComment("Function name");
896     // Truncate the name so we won't overflow the record length field.
897     emitNullTerminatedSymbolName(OS, FuncName);
898     OS.EmitLabel(ProcRecordEnd);
899 
900     emitLocalVariableList(FI.Locals);
901 
902     // Emit inlined call site information. Only emit functions inlined directly
903     // into the parent function. We'll emit the other sites recursively as part
904     // of their parent inline site.
905     for (const DILocation *InlinedAt : FI.ChildSites) {
906       auto I = FI.InlineSites.find(InlinedAt);
907       assert(I != FI.InlineSites.end() &&
908              "child site not in function inline site map");
909       emitInlinedCallSite(FI, InlinedAt, I->second);
910     }
911 
912     for (auto Annot : FI.Annotations) {
913       MCSymbol *Label = Annot.first;
914       MDTuple *Strs = cast<MDTuple>(Annot.second);
915       MCSymbol *AnnotBegin = MMI->getContext().createTempSymbol(),
916                *AnnotEnd = MMI->getContext().createTempSymbol();
917       OS.AddComment("Record length");
918       OS.emitAbsoluteSymbolDiff(AnnotEnd, AnnotBegin, 2);
919       OS.EmitLabel(AnnotBegin);
920       OS.AddComment("Record kind: S_ANNOTATION");
921       OS.EmitIntValue(SymbolKind::S_ANNOTATION, 2);
922       OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
923       // FIXME: Make sure we don't overflow the max record size.
924       OS.EmitCOFFSectionIndex(Label);
925       OS.EmitIntValue(Strs->getNumOperands(), 2);
926       for (Metadata *MD : Strs->operands()) {
927         // MDStrings are null terminated, so we can do EmitBytes and get the
928         // nice .asciz directive.
929         StringRef Str = cast<MDString>(MD)->getString();
930         assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
931         OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
932       }
933       OS.EmitLabel(AnnotEnd);
934     }
935 
936     if (SP != nullptr)
937       emitDebugInfoForUDTs(LocalUDTs);
938 
939     // We're done with this function.
940     OS.AddComment("Record length");
941     OS.EmitIntValue(0x0002, 2);
942     OS.AddComment("Record kind: S_PROC_ID_END");
943     OS.EmitIntValue(unsigned(SymbolKind::S_PROC_ID_END), 2);
944   }
945   endCVSubsection(SymbolsEnd);
946 
947   // We have an assembler directive that takes care of the whole line table.
948   OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
949 }
950 
951 CodeViewDebug::LocalVarDefRange
952 CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
953   LocalVarDefRange DR;
954   DR.InMemory = -1;
955   DR.DataOffset = Offset;
956   assert(DR.DataOffset == Offset && "truncation");
957   DR.IsSubfield = 0;
958   DR.StructOffset = 0;
959   DR.CVRegister = CVRegister;
960   return DR;
961 }
962 
963 CodeViewDebug::LocalVarDefRange
964 CodeViewDebug::createDefRangeGeneral(uint16_t CVRegister, bool InMemory,
965                                      int Offset, bool IsSubfield,
966                                      uint16_t StructOffset) {
967   LocalVarDefRange DR;
968   DR.InMemory = InMemory;
969   DR.DataOffset = Offset;
970   DR.IsSubfield = IsSubfield;
971   DR.StructOffset = StructOffset;
972   DR.CVRegister = CVRegister;
973   return DR;
974 }
975 
976 void CodeViewDebug::collectVariableInfoFromMFTable(
977     DenseSet<InlinedVariable> &Processed) {
978   const MachineFunction &MF = *Asm->MF;
979   const TargetSubtargetInfo &TSI = MF.getSubtarget();
980   const TargetFrameLowering *TFI = TSI.getFrameLowering();
981   const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
982 
983   for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
984     if (!VI.Var)
985       continue;
986     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
987            "Expected inlined-at fields to agree");
988 
989     Processed.insert(InlinedVariable(VI.Var, VI.Loc->getInlinedAt()));
990     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
991 
992     // If variable scope is not found then skip this variable.
993     if (!Scope)
994       continue;
995 
996     // If the variable has an attached offset expression, extract it.
997     // FIXME: Try to handle DW_OP_deref as well.
998     int64_t ExprOffset = 0;
999     if (VI.Expr)
1000       if (!VI.Expr->extractIfOffset(ExprOffset))
1001         continue;
1002 
1003     // Get the frame register used and the offset.
1004     unsigned FrameReg = 0;
1005     int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
1006     uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
1007 
1008     // Calculate the label ranges.
1009     LocalVarDefRange DefRange =
1010         createDefRangeMem(CVReg, FrameOffset + ExprOffset);
1011     for (const InsnRange &Range : Scope->getRanges()) {
1012       const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1013       const MCSymbol *End = getLabelAfterInsn(Range.second);
1014       End = End ? End : Asm->getFunctionEnd();
1015       DefRange.Ranges.emplace_back(Begin, End);
1016     }
1017 
1018     LocalVariable Var;
1019     Var.DIVar = VI.Var;
1020     Var.DefRanges.emplace_back(std::move(DefRange));
1021     recordLocalVariable(std::move(Var), VI.Loc->getInlinedAt());
1022   }
1023 }
1024 
1025 static bool canUseReferenceType(const DbgVariableLocation &Loc) {
1026   return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
1027 }
1028 
1029 static bool needsReferenceType(const DbgVariableLocation &Loc) {
1030   return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
1031 }
1032 
1033 void CodeViewDebug::calculateRanges(
1034     LocalVariable &Var, const DbgValueHistoryMap::InstrRanges &Ranges) {
1035   const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
1036 
1037   // Calculate the definition ranges.
1038   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1039     const InsnRange &Range = *I;
1040     const MachineInstr *DVInst = Range.first;
1041     assert(DVInst->isDebugValue() && "Invalid History entry");
1042     // FIXME: Find a way to represent constant variables, since they are
1043     // relatively common.
1044     Optional<DbgVariableLocation> Location =
1045         DbgVariableLocation::extractFromMachineInstruction(*DVInst);
1046     if (!Location)
1047       continue;
1048 
1049     // CodeView can only express variables in register and variables in memory
1050     // at a constant offset from a register. However, for variables passed
1051     // indirectly by pointer, it is common for that pointer to be spilled to a
1052     // stack location. For the special case of one offseted load followed by a
1053     // zero offset load (a pointer spilled to the stack), we change the type of
1054     // the local variable from a value type to a reference type. This tricks the
1055     // debugger into doing the load for us.
1056     if (Var.UseReferenceType) {
1057       // We're using a reference type. Drop the last zero offset load.
1058       if (canUseReferenceType(*Location))
1059         Location->LoadChain.pop_back();
1060       else
1061         continue;
1062     } else if (needsReferenceType(*Location)) {
1063       // This location can't be expressed without switching to a reference type.
1064       // Start over using that.
1065       Var.UseReferenceType = true;
1066       Var.DefRanges.clear();
1067       calculateRanges(Var, Ranges);
1068       return;
1069     }
1070 
1071     // We can only handle a register or an offseted load of a register.
1072     if (Location->Register == 0 || Location->LoadChain.size() > 1)
1073       continue;
1074     {
1075       LocalVarDefRange DR;
1076       DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
1077       DR.InMemory = !Location->LoadChain.empty();
1078       DR.DataOffset =
1079           !Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
1080       if (Location->FragmentInfo) {
1081         DR.IsSubfield = true;
1082         DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
1083       } else {
1084         DR.IsSubfield = false;
1085         DR.StructOffset = 0;
1086       }
1087 
1088       if (Var.DefRanges.empty() ||
1089           Var.DefRanges.back().isDifferentLocation(DR)) {
1090         Var.DefRanges.emplace_back(std::move(DR));
1091       }
1092     }
1093 
1094     // Compute the label range.
1095     const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
1096     const MCSymbol *End = getLabelAfterInsn(Range.second);
1097     if (!End) {
1098       // This range is valid until the next overlapping bitpiece. In the
1099       // common case, ranges will not be bitpieces, so they will overlap.
1100       auto J = std::next(I);
1101       const DIExpression *DIExpr = DVInst->getDebugExpression();
1102       while (J != E &&
1103              !fragmentsOverlap(DIExpr, J->first->getDebugExpression()))
1104         ++J;
1105       if (J != E)
1106         End = getLabelBeforeInsn(J->first);
1107       else
1108         End = Asm->getFunctionEnd();
1109     }
1110 
1111     // If the last range end is our begin, just extend the last range.
1112     // Otherwise make a new range.
1113     SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
1114         Var.DefRanges.back().Ranges;
1115     if (!R.empty() && R.back().second == Begin)
1116       R.back().second = End;
1117     else
1118       R.emplace_back(Begin, End);
1119 
1120     // FIXME: Do more range combining.
1121   }
1122 }
1123 
1124 void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
1125   DenseSet<InlinedVariable> Processed;
1126   // Grab the variable info that was squirreled away in the MMI side-table.
1127   collectVariableInfoFromMFTable(Processed);
1128 
1129   for (const auto &I : DbgValues) {
1130     InlinedVariable IV = I.first;
1131     if (Processed.count(IV))
1132       continue;
1133     const DILocalVariable *DIVar = IV.first;
1134     const DILocation *InlinedAt = IV.second;
1135 
1136     // Instruction ranges, specifying where IV is accessible.
1137     const auto &Ranges = I.second;
1138 
1139     LexicalScope *Scope = nullptr;
1140     if (InlinedAt)
1141       Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
1142     else
1143       Scope = LScopes.findLexicalScope(DIVar->getScope());
1144     // If variable scope is not found then skip this variable.
1145     if (!Scope)
1146       continue;
1147 
1148     LocalVariable Var;
1149     Var.DIVar = DIVar;
1150 
1151     calculateRanges(Var, Ranges);
1152     recordLocalVariable(std::move(Var), InlinedAt);
1153   }
1154 }
1155 
1156 void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
1157   const Function &GV = MF->getFunction();
1158   assert(FnDebugInfo.count(&GV) == false);
1159   CurFn = &FnDebugInfo[&GV];
1160   CurFn->FuncId = NextFuncId++;
1161   CurFn->Begin = Asm->getFunctionBegin();
1162 
1163   OS.EmitCVFuncIdDirective(CurFn->FuncId);
1164 
1165   // Find the end of the function prolog.  First known non-DBG_VALUE and
1166   // non-frame setup location marks the beginning of the function body.
1167   // FIXME: is there a simpler a way to do this? Can we just search
1168   // for the first instruction of the function, not the last of the prolog?
1169   DebugLoc PrologEndLoc;
1170   bool EmptyPrologue = true;
1171   for (const auto &MBB : *MF) {
1172     for (const auto &MI : MBB) {
1173       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1174           MI.getDebugLoc()) {
1175         PrologEndLoc = MI.getDebugLoc();
1176         break;
1177       } else if (!MI.isMetaInstruction()) {
1178         EmptyPrologue = false;
1179       }
1180     }
1181   }
1182 
1183   // Record beginning of function if we have a non-empty prologue.
1184   if (PrologEndLoc && !EmptyPrologue) {
1185     DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
1186     maybeRecordLocation(FnStartDL, MF);
1187   }
1188 }
1189 
1190 static bool shouldEmitUdt(const DIType *T) {
1191   if (!T)
1192     return false;
1193 
1194   // MSVC does not emit UDTs for typedefs that are scoped to classes.
1195   if (T->getTag() == dwarf::DW_TAG_typedef) {
1196     if (DIScope *Scope = T->getScope().resolve()) {
1197       switch (Scope->getTag()) {
1198       case dwarf::DW_TAG_structure_type:
1199       case dwarf::DW_TAG_class_type:
1200       case dwarf::DW_TAG_union_type:
1201         return false;
1202       }
1203     }
1204   }
1205 
1206   while (true) {
1207     if (!T || T->isForwardDecl())
1208       return false;
1209 
1210     const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
1211     if (!DT)
1212       return true;
1213     T = DT->getBaseType().resolve();
1214   }
1215   return true;
1216 }
1217 
1218 void CodeViewDebug::addToUDTs(const DIType *Ty) {
1219   // Don't record empty UDTs.
1220   if (Ty->getName().empty())
1221     return;
1222   if (!shouldEmitUdt(Ty))
1223     return;
1224 
1225   SmallVector<StringRef, 5> QualifiedNameComponents;
1226   const DISubprogram *ClosestSubprogram = getQualifiedNameComponents(
1227       Ty->getScope().resolve(), QualifiedNameComponents);
1228 
1229   std::string FullyQualifiedName =
1230       getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
1231 
1232   if (ClosestSubprogram == nullptr) {
1233     GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1234   } else if (ClosestSubprogram == CurrentSubprogram) {
1235     LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
1236   }
1237 
1238   // TODO: What if the ClosestSubprogram is neither null or the current
1239   // subprogram?  Currently, the UDT just gets dropped on the floor.
1240   //
1241   // The current behavior is not desirable.  To get maximal fidelity, we would
1242   // need to perform all type translation before beginning emission of .debug$S
1243   // and then make LocalUDTs a member of FunctionInfo
1244 }
1245 
1246 TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
1247   // Generic dispatch for lowering an unknown type.
1248   switch (Ty->getTag()) {
1249   case dwarf::DW_TAG_array_type:
1250     return lowerTypeArray(cast<DICompositeType>(Ty));
1251   case dwarf::DW_TAG_typedef:
1252     return lowerTypeAlias(cast<DIDerivedType>(Ty));
1253   case dwarf::DW_TAG_base_type:
1254     return lowerTypeBasic(cast<DIBasicType>(Ty));
1255   case dwarf::DW_TAG_pointer_type:
1256     if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
1257       return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
1258     LLVM_FALLTHROUGH;
1259   case dwarf::DW_TAG_reference_type:
1260   case dwarf::DW_TAG_rvalue_reference_type:
1261     return lowerTypePointer(cast<DIDerivedType>(Ty));
1262   case dwarf::DW_TAG_ptr_to_member_type:
1263     return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
1264   case dwarf::DW_TAG_const_type:
1265   case dwarf::DW_TAG_volatile_type:
1266   // TODO: add support for DW_TAG_atomic_type here
1267     return lowerTypeModifier(cast<DIDerivedType>(Ty));
1268   case dwarf::DW_TAG_subroutine_type:
1269     if (ClassTy) {
1270       // The member function type of a member function pointer has no
1271       // ThisAdjustment.
1272       return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
1273                                      /*ThisAdjustment=*/0,
1274                                      /*IsStaticMethod=*/false);
1275     }
1276     return lowerTypeFunction(cast<DISubroutineType>(Ty));
1277   case dwarf::DW_TAG_enumeration_type:
1278     return lowerTypeEnum(cast<DICompositeType>(Ty));
1279   case dwarf::DW_TAG_class_type:
1280   case dwarf::DW_TAG_structure_type:
1281     return lowerTypeClass(cast<DICompositeType>(Ty));
1282   case dwarf::DW_TAG_union_type:
1283     return lowerTypeUnion(cast<DICompositeType>(Ty));
1284   case dwarf::DW_TAG_unspecified_type:
1285     return TypeIndex::None();
1286   default:
1287     // Use the null type index.
1288     return TypeIndex();
1289   }
1290 }
1291 
1292 TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
1293   DITypeRef UnderlyingTypeRef = Ty->getBaseType();
1294   TypeIndex UnderlyingTypeIndex = getTypeIndex(UnderlyingTypeRef);
1295   StringRef TypeName = Ty->getName();
1296 
1297   addToUDTs(Ty);
1298 
1299   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
1300       TypeName == "HRESULT")
1301     return TypeIndex(SimpleTypeKind::HResult);
1302   if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
1303       TypeName == "wchar_t")
1304     return TypeIndex(SimpleTypeKind::WideCharacter);
1305 
1306   return UnderlyingTypeIndex;
1307 }
1308 
1309 TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
1310   DITypeRef ElementTypeRef = Ty->getBaseType();
1311   TypeIndex ElementTypeIndex = getTypeIndex(ElementTypeRef);
1312   // IndexType is size_t, which depends on the bitness of the target.
1313   TypeIndex IndexType = Asm->TM.getPointerSize() == 8
1314                             ? TypeIndex(SimpleTypeKind::UInt64Quad)
1315                             : TypeIndex(SimpleTypeKind::UInt32Long);
1316 
1317   uint64_t ElementSize = getBaseTypeSize(ElementTypeRef) / 8;
1318 
1319   // Add subranges to array type.
1320   DINodeArray Elements = Ty->getElements();
1321   for (int i = Elements.size() - 1; i >= 0; --i) {
1322     const DINode *Element = Elements[i];
1323     assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
1324 
1325     const DISubrange *Subrange = cast<DISubrange>(Element);
1326     assert(Subrange->getLowerBound() == 0 &&
1327            "codeview doesn't support subranges with lower bounds");
1328     int64_t Count = -1;
1329     if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
1330       Count = CI->getSExtValue();
1331 
1332     // Forward declarations of arrays without a size and VLAs use a count of -1.
1333     // Emit a count of zero in these cases to match what MSVC does for arrays
1334     // without a size. MSVC doesn't support VLAs, so it's not clear what we
1335     // should do for them even if we could distinguish them.
1336     if (Count == -1)
1337       Count = 0;
1338 
1339     // Update the element size and element type index for subsequent subranges.
1340     ElementSize *= Count;
1341 
1342     // If this is the outermost array, use the size from the array. It will be
1343     // more accurate if we had a VLA or an incomplete element type size.
1344     uint64_t ArraySize =
1345         (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
1346 
1347     StringRef Name = (i == 0) ? Ty->getName() : "";
1348     ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
1349     ElementTypeIndex = TypeTable.writeLeafType(AR);
1350   }
1351 
1352   return ElementTypeIndex;
1353 }
1354 
1355 TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
1356   TypeIndex Index;
1357   dwarf::TypeKind Kind;
1358   uint32_t ByteSize;
1359 
1360   Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
1361   ByteSize = Ty->getSizeInBits() / 8;
1362 
1363   SimpleTypeKind STK = SimpleTypeKind::None;
1364   switch (Kind) {
1365   case dwarf::DW_ATE_address:
1366     // FIXME: Translate
1367     break;
1368   case dwarf::DW_ATE_boolean:
1369     switch (ByteSize) {
1370     case 1:  STK = SimpleTypeKind::Boolean8;   break;
1371     case 2:  STK = SimpleTypeKind::Boolean16;  break;
1372     case 4:  STK = SimpleTypeKind::Boolean32;  break;
1373     case 8:  STK = SimpleTypeKind::Boolean64;  break;
1374     case 16: STK = SimpleTypeKind::Boolean128; break;
1375     }
1376     break;
1377   case dwarf::DW_ATE_complex_float:
1378     switch (ByteSize) {
1379     case 2:  STK = SimpleTypeKind::Complex16;  break;
1380     case 4:  STK = SimpleTypeKind::Complex32;  break;
1381     case 8:  STK = SimpleTypeKind::Complex64;  break;
1382     case 10: STK = SimpleTypeKind::Complex80;  break;
1383     case 16: STK = SimpleTypeKind::Complex128; break;
1384     }
1385     break;
1386   case dwarf::DW_ATE_float:
1387     switch (ByteSize) {
1388     case 2:  STK = SimpleTypeKind::Float16;  break;
1389     case 4:  STK = SimpleTypeKind::Float32;  break;
1390     case 6:  STK = SimpleTypeKind::Float48;  break;
1391     case 8:  STK = SimpleTypeKind::Float64;  break;
1392     case 10: STK = SimpleTypeKind::Float80;  break;
1393     case 16: STK = SimpleTypeKind::Float128; break;
1394     }
1395     break;
1396   case dwarf::DW_ATE_signed:
1397     switch (ByteSize) {
1398     case 1:  STK = SimpleTypeKind::SignedCharacter; break;
1399     case 2:  STK = SimpleTypeKind::Int16Short;      break;
1400     case 4:  STK = SimpleTypeKind::Int32;           break;
1401     case 8:  STK = SimpleTypeKind::Int64Quad;       break;
1402     case 16: STK = SimpleTypeKind::Int128Oct;       break;
1403     }
1404     break;
1405   case dwarf::DW_ATE_unsigned:
1406     switch (ByteSize) {
1407     case 1:  STK = SimpleTypeKind::UnsignedCharacter; break;
1408     case 2:  STK = SimpleTypeKind::UInt16Short;       break;
1409     case 4:  STK = SimpleTypeKind::UInt32;            break;
1410     case 8:  STK = SimpleTypeKind::UInt64Quad;        break;
1411     case 16: STK = SimpleTypeKind::UInt128Oct;        break;
1412     }
1413     break;
1414   case dwarf::DW_ATE_UTF:
1415     switch (ByteSize) {
1416     case 2: STK = SimpleTypeKind::Character16; break;
1417     case 4: STK = SimpleTypeKind::Character32; break;
1418     }
1419     break;
1420   case dwarf::DW_ATE_signed_char:
1421     if (ByteSize == 1)
1422       STK = SimpleTypeKind::SignedCharacter;
1423     break;
1424   case dwarf::DW_ATE_unsigned_char:
1425     if (ByteSize == 1)
1426       STK = SimpleTypeKind::UnsignedCharacter;
1427     break;
1428   default:
1429     break;
1430   }
1431 
1432   // Apply some fixups based on the source-level type name.
1433   if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
1434     STK = SimpleTypeKind::Int32Long;
1435   if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
1436     STK = SimpleTypeKind::UInt32Long;
1437   if (STK == SimpleTypeKind::UInt16Short &&
1438       (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
1439     STK = SimpleTypeKind::WideCharacter;
1440   if ((STK == SimpleTypeKind::SignedCharacter ||
1441        STK == SimpleTypeKind::UnsignedCharacter) &&
1442       Ty->getName() == "char")
1443     STK = SimpleTypeKind::NarrowCharacter;
1444 
1445   return TypeIndex(STK);
1446 }
1447 
1448 TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty) {
1449   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
1450 
1451   // Pointers to simple types can use SimpleTypeMode, rather than having a
1452   // dedicated pointer type record.
1453   if (PointeeTI.isSimple() &&
1454       PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
1455       Ty->getTag() == dwarf::DW_TAG_pointer_type) {
1456     SimpleTypeMode Mode = Ty->getSizeInBits() == 64
1457                               ? SimpleTypeMode::NearPointer64
1458                               : SimpleTypeMode::NearPointer32;
1459     return TypeIndex(PointeeTI.getSimpleKind(), Mode);
1460   }
1461 
1462   PointerKind PK =
1463       Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
1464   PointerMode PM = PointerMode::Pointer;
1465   switch (Ty->getTag()) {
1466   default: llvm_unreachable("not a pointer tag type");
1467   case dwarf::DW_TAG_pointer_type:
1468     PM = PointerMode::Pointer;
1469     break;
1470   case dwarf::DW_TAG_reference_type:
1471     PM = PointerMode::LValueReference;
1472     break;
1473   case dwarf::DW_TAG_rvalue_reference_type:
1474     PM = PointerMode::RValueReference;
1475     break;
1476   }
1477   // FIXME: MSVC folds qualifiers into PointerOptions in the context of a method
1478   // 'this' pointer, but not normal contexts. Figure out what we're supposed to
1479   // do.
1480   PointerOptions PO = PointerOptions::None;
1481   PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
1482   return TypeTable.writeLeafType(PR);
1483 }
1484 
1485 static PointerToMemberRepresentation
1486 translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
1487   // SizeInBytes being zero generally implies that the member pointer type was
1488   // incomplete, which can happen if it is part of a function prototype. In this
1489   // case, use the unknown model instead of the general model.
1490   if (IsPMF) {
1491     switch (Flags & DINode::FlagPtrToMemberRep) {
1492     case 0:
1493       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1494                               : PointerToMemberRepresentation::GeneralFunction;
1495     case DINode::FlagSingleInheritance:
1496       return PointerToMemberRepresentation::SingleInheritanceFunction;
1497     case DINode::FlagMultipleInheritance:
1498       return PointerToMemberRepresentation::MultipleInheritanceFunction;
1499     case DINode::FlagVirtualInheritance:
1500       return PointerToMemberRepresentation::VirtualInheritanceFunction;
1501     }
1502   } else {
1503     switch (Flags & DINode::FlagPtrToMemberRep) {
1504     case 0:
1505       return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
1506                               : PointerToMemberRepresentation::GeneralData;
1507     case DINode::FlagSingleInheritance:
1508       return PointerToMemberRepresentation::SingleInheritanceData;
1509     case DINode::FlagMultipleInheritance:
1510       return PointerToMemberRepresentation::MultipleInheritanceData;
1511     case DINode::FlagVirtualInheritance:
1512       return PointerToMemberRepresentation::VirtualInheritanceData;
1513     }
1514   }
1515   llvm_unreachable("invalid ptr to member representation");
1516 }
1517 
1518 TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty) {
1519   assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
1520   TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
1521   TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
1522   PointerKind PK = Asm->TM.getPointerSize() == 8 ? PointerKind::Near64
1523                                                  : PointerKind::Near32;
1524   bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
1525   PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
1526                          : PointerMode::PointerToDataMember;
1527   PointerOptions PO = PointerOptions::None; // FIXME
1528   assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
1529   uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
1530   MemberPointerInfo MPI(
1531       ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
1532   PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
1533   return TypeTable.writeLeafType(PR);
1534 }
1535 
1536 /// Given a DWARF calling convention, get the CodeView equivalent. If we don't
1537 /// have a translation, use the NearC convention.
1538 static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
1539   switch (DwarfCC) {
1540   case dwarf::DW_CC_normal:             return CallingConvention::NearC;
1541   case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
1542   case dwarf::DW_CC_BORLAND_thiscall:   return CallingConvention::ThisCall;
1543   case dwarf::DW_CC_BORLAND_stdcall:    return CallingConvention::NearStdCall;
1544   case dwarf::DW_CC_BORLAND_pascal:     return CallingConvention::NearPascal;
1545   case dwarf::DW_CC_LLVM_vectorcall:    return CallingConvention::NearVector;
1546   }
1547   return CallingConvention::NearC;
1548 }
1549 
1550 TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
1551   ModifierOptions Mods = ModifierOptions::None;
1552   bool IsModifier = true;
1553   const DIType *BaseTy = Ty;
1554   while (IsModifier && BaseTy) {
1555     // FIXME: Need to add DWARF tags for __unaligned and _Atomic
1556     switch (BaseTy->getTag()) {
1557     case dwarf::DW_TAG_const_type:
1558       Mods |= ModifierOptions::Const;
1559       break;
1560     case dwarf::DW_TAG_volatile_type:
1561       Mods |= ModifierOptions::Volatile;
1562       break;
1563     default:
1564       IsModifier = false;
1565       break;
1566     }
1567     if (IsModifier)
1568       BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType().resolve();
1569   }
1570   TypeIndex ModifiedTI = getTypeIndex(BaseTy);
1571   ModifierRecord MR(ModifiedTI, Mods);
1572   return TypeTable.writeLeafType(MR);
1573 }
1574 
1575 TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
1576   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1577   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1578     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1579 
1580   // MSVC uses type none for variadic argument.
1581   if (ReturnAndArgTypeIndices.size() > 1 &&
1582       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1583     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1584   }
1585   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1586   ArrayRef<TypeIndex> ArgTypeIndices = None;
1587   if (!ReturnAndArgTypeIndices.empty()) {
1588     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1589     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1590     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1591   }
1592 
1593   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1594   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1595 
1596   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1597 
1598   ProcedureRecord Procedure(ReturnTypeIndex, CC, FunctionOptions::None,
1599                             ArgTypeIndices.size(), ArgListIndex);
1600   return TypeTable.writeLeafType(Procedure);
1601 }
1602 
1603 TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
1604                                                  const DIType *ClassTy,
1605                                                  int ThisAdjustment,
1606                                                  bool IsStaticMethod) {
1607   // Lower the containing class type.
1608   TypeIndex ClassType = getTypeIndex(ClassTy);
1609 
1610   SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
1611   for (DITypeRef ArgTypeRef : Ty->getTypeArray())
1612     ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgTypeRef));
1613 
1614   // MSVC uses type none for variadic argument.
1615   if (ReturnAndArgTypeIndices.size() > 1 &&
1616       ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
1617     ReturnAndArgTypeIndices.back() = TypeIndex::None();
1618   }
1619   TypeIndex ReturnTypeIndex = TypeIndex::Void();
1620   ArrayRef<TypeIndex> ArgTypeIndices = None;
1621   if (!ReturnAndArgTypeIndices.empty()) {
1622     auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
1623     ReturnTypeIndex = ReturnAndArgTypesRef.front();
1624     ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
1625   }
1626   TypeIndex ThisTypeIndex;
1627   if (!IsStaticMethod && !ArgTypeIndices.empty()) {
1628     ThisTypeIndex = ArgTypeIndices.front();
1629     ArgTypeIndices = ArgTypeIndices.drop_front();
1630   }
1631 
1632   ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
1633   TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
1634 
1635   CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
1636 
1637   // TODO: Need to use the correct values for FunctionOptions.
1638   MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC,
1639                            FunctionOptions::None, ArgTypeIndices.size(),
1640                            ArgListIndex, ThisAdjustment);
1641   return TypeTable.writeLeafType(MFR);
1642 }
1643 
1644 TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
1645   unsigned VSlotCount =
1646       Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
1647   SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
1648 
1649   VFTableShapeRecord VFTSR(Slots);
1650   return TypeTable.writeLeafType(VFTSR);
1651 }
1652 
1653 static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
1654   switch (Flags & DINode::FlagAccessibility) {
1655   case DINode::FlagPrivate:   return MemberAccess::Private;
1656   case DINode::FlagPublic:    return MemberAccess::Public;
1657   case DINode::FlagProtected: return MemberAccess::Protected;
1658   case 0:
1659     // If there was no explicit access control, provide the default for the tag.
1660     return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
1661                                                  : MemberAccess::Public;
1662   }
1663   llvm_unreachable("access flags are exclusive");
1664 }
1665 
1666 static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
1667   if (SP->isArtificial())
1668     return MethodOptions::CompilerGenerated;
1669 
1670   // FIXME: Handle other MethodOptions.
1671 
1672   return MethodOptions::None;
1673 }
1674 
1675 static MethodKind translateMethodKindFlags(const DISubprogram *SP,
1676                                            bool Introduced) {
1677   if (SP->getFlags() & DINode::FlagStaticMember)
1678     return MethodKind::Static;
1679 
1680   switch (SP->getVirtuality()) {
1681   case dwarf::DW_VIRTUALITY_none:
1682     break;
1683   case dwarf::DW_VIRTUALITY_virtual:
1684     return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
1685   case dwarf::DW_VIRTUALITY_pure_virtual:
1686     return Introduced ? MethodKind::PureIntroducingVirtual
1687                       : MethodKind::PureVirtual;
1688   default:
1689     llvm_unreachable("unhandled virtuality case");
1690   }
1691 
1692   return MethodKind::Vanilla;
1693 }
1694 
1695 static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
1696   switch (Ty->getTag()) {
1697   case dwarf::DW_TAG_class_type:     return TypeRecordKind::Class;
1698   case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
1699   }
1700   llvm_unreachable("unexpected tag");
1701 }
1702 
1703 /// Return ClassOptions that should be present on both the forward declaration
1704 /// and the defintion of a tag type.
1705 static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
1706   ClassOptions CO = ClassOptions::None;
1707 
1708   // MSVC always sets this flag, even for local types. Clang doesn't always
1709   // appear to give every type a linkage name, which may be problematic for us.
1710   // FIXME: Investigate the consequences of not following them here.
1711   if (!Ty->getIdentifier().empty())
1712     CO |= ClassOptions::HasUniqueName;
1713 
1714   // Put the Nested flag on a type if it appears immediately inside a tag type.
1715   // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
1716   // here. That flag is only set on definitions, and not forward declarations.
1717   const DIScope *ImmediateScope = Ty->getScope().resolve();
1718   if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
1719     CO |= ClassOptions::Nested;
1720 
1721   // Put the Scoped flag on function-local types.
1722   for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
1723        Scope = Scope->getScope().resolve()) {
1724     if (isa<DISubprogram>(Scope)) {
1725       CO |= ClassOptions::Scoped;
1726       break;
1727     }
1728   }
1729 
1730   return CO;
1731 }
1732 
1733 TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
1734   ClassOptions CO = getCommonClassOptions(Ty);
1735   TypeIndex FTI;
1736   unsigned EnumeratorCount = 0;
1737 
1738   if (Ty->isForwardDecl()) {
1739     CO |= ClassOptions::ForwardReference;
1740   } else {
1741     ContinuationRecordBuilder ContinuationBuilder;
1742     ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
1743     for (const DINode *Element : Ty->getElements()) {
1744       // We assume that the frontend provides all members in source declaration
1745       // order, which is what MSVC does.
1746       if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
1747         EnumeratorRecord ER(MemberAccess::Public,
1748                             APSInt::getUnsigned(Enumerator->getValue()),
1749                             Enumerator->getName());
1750         ContinuationBuilder.writeMemberType(ER);
1751         EnumeratorCount++;
1752       }
1753     }
1754     FTI = TypeTable.insertRecord(ContinuationBuilder);
1755   }
1756 
1757   std::string FullName = getFullyQualifiedName(Ty);
1758 
1759   EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
1760                 getTypeIndex(Ty->getBaseType()));
1761   return TypeTable.writeLeafType(ER);
1762 }
1763 
1764 //===----------------------------------------------------------------------===//
1765 // ClassInfo
1766 //===----------------------------------------------------------------------===//
1767 
1768 struct llvm::ClassInfo {
1769   struct MemberInfo {
1770     const DIDerivedType *MemberTypeNode;
1771     uint64_t BaseOffset;
1772   };
1773   // [MemberInfo]
1774   using MemberList = std::vector<MemberInfo>;
1775 
1776   using MethodsList = TinyPtrVector<const DISubprogram *>;
1777   // MethodName -> MethodsList
1778   using MethodsMap = MapVector<MDString *, MethodsList>;
1779 
1780   /// Base classes.
1781   std::vector<const DIDerivedType *> Inheritance;
1782 
1783   /// Direct members.
1784   MemberList Members;
1785   // Direct overloaded methods gathered by name.
1786   MethodsMap Methods;
1787 
1788   TypeIndex VShapeTI;
1789 
1790   std::vector<const DIType *> NestedTypes;
1791 };
1792 
1793 void CodeViewDebug::clear() {
1794   assert(CurFn == nullptr);
1795   FileIdMap.clear();
1796   FnDebugInfo.clear();
1797   FileToFilepathMap.clear();
1798   LocalUDTs.clear();
1799   GlobalUDTs.clear();
1800   TypeIndices.clear();
1801   CompleteTypeIndices.clear();
1802 }
1803 
1804 void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
1805                                       const DIDerivedType *DDTy) {
1806   if (!DDTy->getName().empty()) {
1807     Info.Members.push_back({DDTy, 0});
1808     return;
1809   }
1810   // An unnamed member must represent a nested struct or union. Add all the
1811   // indirect fields to the current record.
1812   assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
1813   uint64_t Offset = DDTy->getOffsetInBits();
1814   const DIType *Ty = DDTy->getBaseType().resolve();
1815   const DICompositeType *DCTy = cast<DICompositeType>(Ty);
1816   ClassInfo NestedInfo = collectClassInfo(DCTy);
1817   for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
1818     Info.Members.push_back(
1819         {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
1820 }
1821 
1822 ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
1823   ClassInfo Info;
1824   // Add elements to structure type.
1825   DINodeArray Elements = Ty->getElements();
1826   for (auto *Element : Elements) {
1827     // We assume that the frontend provides all members in source declaration
1828     // order, which is what MSVC does.
1829     if (!Element)
1830       continue;
1831     if (auto *SP = dyn_cast<DISubprogram>(Element)) {
1832       Info.Methods[SP->getRawName()].push_back(SP);
1833     } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
1834       if (DDTy->getTag() == dwarf::DW_TAG_member) {
1835         collectMemberInfo(Info, DDTy);
1836       } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
1837         Info.Inheritance.push_back(DDTy);
1838       } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
1839                  DDTy->getName() == "__vtbl_ptr_type") {
1840         Info.VShapeTI = getTypeIndex(DDTy);
1841       } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
1842         Info.NestedTypes.push_back(DDTy);
1843       } else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
1844         // Ignore friend members. It appears that MSVC emitted info about
1845         // friends in the past, but modern versions do not.
1846       }
1847     } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
1848       Info.NestedTypes.push_back(Composite);
1849     }
1850     // Skip other unrecognized kinds of elements.
1851   }
1852   return Info;
1853 }
1854 
1855 TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
1856   // First, construct the forward decl.  Don't look into Ty to compute the
1857   // forward decl options, since it might not be available in all TUs.
1858   TypeRecordKind Kind = getRecordKind(Ty);
1859   ClassOptions CO =
1860       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1861   std::string FullName = getFullyQualifiedName(Ty);
1862   ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
1863                  FullName, Ty->getIdentifier());
1864   TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
1865   if (!Ty->isForwardDecl())
1866     DeferredCompleteTypes.push_back(Ty);
1867   return FwdDeclTI;
1868 }
1869 
1870 TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
1871   // Construct the field list and complete type record.
1872   TypeRecordKind Kind = getRecordKind(Ty);
1873   ClassOptions CO = getCommonClassOptions(Ty);
1874   TypeIndex FieldTI;
1875   TypeIndex VShapeTI;
1876   unsigned FieldCount;
1877   bool ContainsNestedClass;
1878   std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
1879       lowerRecordFieldList(Ty);
1880 
1881   if (ContainsNestedClass)
1882     CO |= ClassOptions::ContainsNestedClass;
1883 
1884   std::string FullName = getFullyQualifiedName(Ty);
1885 
1886   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1887 
1888   ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
1889                  SizeInBytes, FullName, Ty->getIdentifier());
1890   TypeIndex ClassTI = TypeTable.writeLeafType(CR);
1891 
1892   if (const auto *File = Ty->getFile()) {
1893     StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
1894     TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
1895 
1896     UdtSourceLineRecord USLR(ClassTI, SIDI, Ty->getLine());
1897     TypeTable.writeLeafType(USLR);
1898   }
1899 
1900   addToUDTs(Ty);
1901 
1902   return ClassTI;
1903 }
1904 
1905 TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
1906   ClassOptions CO =
1907       ClassOptions::ForwardReference | getCommonClassOptions(Ty);
1908   std::string FullName = getFullyQualifiedName(Ty);
1909   UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
1910   TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
1911   if (!Ty->isForwardDecl())
1912     DeferredCompleteTypes.push_back(Ty);
1913   return FwdDeclTI;
1914 }
1915 
1916 TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
1917   ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
1918   TypeIndex FieldTI;
1919   unsigned FieldCount;
1920   bool ContainsNestedClass;
1921   std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
1922       lowerRecordFieldList(Ty);
1923 
1924   if (ContainsNestedClass)
1925     CO |= ClassOptions::ContainsNestedClass;
1926 
1927   uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
1928   std::string FullName = getFullyQualifiedName(Ty);
1929 
1930   UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
1931                  Ty->getIdentifier());
1932   TypeIndex UnionTI = TypeTable.writeLeafType(UR);
1933 
1934   StringIdRecord SIR(TypeIndex(0x0), getFullFilepath(Ty->getFile()));
1935   TypeIndex SIRI = TypeTable.writeLeafType(SIR);
1936 
1937   UdtSourceLineRecord USLR(UnionTI, SIRI, Ty->getLine());
1938   TypeTable.writeLeafType(USLR);
1939 
1940   addToUDTs(Ty);
1941 
1942   return UnionTI;
1943 }
1944 
1945 std::tuple<TypeIndex, TypeIndex, unsigned, bool>
1946 CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
1947   // Manually count members. MSVC appears to count everything that generates a
1948   // field list record. Each individual overload in a method overload group
1949   // contributes to this count, even though the overload group is a single field
1950   // list record.
1951   unsigned MemberCount = 0;
1952   ClassInfo Info = collectClassInfo(Ty);
1953   ContinuationRecordBuilder ContinuationBuilder;
1954   ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
1955 
1956   // Create base classes.
1957   for (const DIDerivedType *I : Info.Inheritance) {
1958     if (I->getFlags() & DINode::FlagVirtual) {
1959       // Virtual base.
1960       // FIXME: Emit VBPtrOffset when the frontend provides it.
1961       unsigned VBPtrOffset = 0;
1962       // FIXME: Despite the accessor name, the offset is really in bytes.
1963       unsigned VBTableIndex = I->getOffsetInBits() / 4;
1964       auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
1965                             ? TypeRecordKind::IndirectVirtualBaseClass
1966                             : TypeRecordKind::VirtualBaseClass;
1967       VirtualBaseClassRecord VBCR(
1968           RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
1969           getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
1970           VBTableIndex);
1971 
1972       ContinuationBuilder.writeMemberType(VBCR);
1973     } else {
1974       assert(I->getOffsetInBits() % 8 == 0 &&
1975              "bases must be on byte boundaries");
1976       BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
1977                           getTypeIndex(I->getBaseType()),
1978                           I->getOffsetInBits() / 8);
1979       ContinuationBuilder.writeMemberType(BCR);
1980     }
1981   }
1982 
1983   // Create members.
1984   for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
1985     const DIDerivedType *Member = MemberInfo.MemberTypeNode;
1986     TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
1987     StringRef MemberName = Member->getName();
1988     MemberAccess Access =
1989         translateAccessFlags(Ty->getTag(), Member->getFlags());
1990 
1991     if (Member->isStaticMember()) {
1992       StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
1993       ContinuationBuilder.writeMemberType(SDMR);
1994       MemberCount++;
1995       continue;
1996     }
1997 
1998     // Virtual function pointer member.
1999     if ((Member->getFlags() & DINode::FlagArtificial) &&
2000         Member->getName().startswith("_vptr$")) {
2001       VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
2002       ContinuationBuilder.writeMemberType(VFPR);
2003       MemberCount++;
2004       continue;
2005     }
2006 
2007     // Data member.
2008     uint64_t MemberOffsetInBits =
2009         Member->getOffsetInBits() + MemberInfo.BaseOffset;
2010     if (Member->isBitField()) {
2011       uint64_t StartBitOffset = MemberOffsetInBits;
2012       if (const auto *CI =
2013               dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
2014         MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
2015       }
2016       StartBitOffset -= MemberOffsetInBits;
2017       BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
2018                          StartBitOffset);
2019       MemberBaseType = TypeTable.writeLeafType(BFR);
2020     }
2021     uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
2022     DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
2023                          MemberName);
2024     ContinuationBuilder.writeMemberType(DMR);
2025     MemberCount++;
2026   }
2027 
2028   // Create methods
2029   for (auto &MethodItr : Info.Methods) {
2030     StringRef Name = MethodItr.first->getString();
2031 
2032     std::vector<OneMethodRecord> Methods;
2033     for (const DISubprogram *SP : MethodItr.second) {
2034       TypeIndex MethodType = getMemberFunctionType(SP, Ty);
2035       bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
2036 
2037       unsigned VFTableOffset = -1;
2038       if (Introduced)
2039         VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
2040 
2041       Methods.push_back(OneMethodRecord(
2042           MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
2043           translateMethodKindFlags(SP, Introduced),
2044           translateMethodOptionFlags(SP), VFTableOffset, Name));
2045       MemberCount++;
2046     }
2047     assert(!Methods.empty() && "Empty methods map entry");
2048     if (Methods.size() == 1)
2049       ContinuationBuilder.writeMemberType(Methods[0]);
2050     else {
2051       // FIXME: Make this use its own ContinuationBuilder so that
2052       // MethodOverloadList can be split correctly.
2053       MethodOverloadListRecord MOLR(Methods);
2054       TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
2055 
2056       OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
2057       ContinuationBuilder.writeMemberType(OMR);
2058     }
2059   }
2060 
2061   // Create nested classes.
2062   for (const DIType *Nested : Info.NestedTypes) {
2063     NestedTypeRecord R(getTypeIndex(DITypeRef(Nested)), Nested->getName());
2064     ContinuationBuilder.writeMemberType(R);
2065     MemberCount++;
2066   }
2067 
2068   TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
2069   return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
2070                          !Info.NestedTypes.empty());
2071 }
2072 
2073 TypeIndex CodeViewDebug::getVBPTypeIndex() {
2074   if (!VBPType.getIndex()) {
2075     // Make a 'const int *' type.
2076     ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
2077     TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
2078 
2079     PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
2080                                                   : PointerKind::Near32;
2081     PointerMode PM = PointerMode::Pointer;
2082     PointerOptions PO = PointerOptions::None;
2083     PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
2084     VBPType = TypeTable.writeLeafType(PR);
2085   }
2086 
2087   return VBPType;
2088 }
2089 
2090 TypeIndex CodeViewDebug::getTypeIndex(DITypeRef TypeRef, DITypeRef ClassTyRef) {
2091   const DIType *Ty = TypeRef.resolve();
2092   const DIType *ClassTy = ClassTyRef.resolve();
2093 
2094   // The null DIType is the void type. Don't try to hash it.
2095   if (!Ty)
2096     return TypeIndex::Void();
2097 
2098   // Check if we've already translated this type. Don't try to do a
2099   // get-or-create style insertion that caches the hash lookup across the
2100   // lowerType call. It will update the TypeIndices map.
2101   auto I = TypeIndices.find({Ty, ClassTy});
2102   if (I != TypeIndices.end())
2103     return I->second;
2104 
2105   TypeLoweringScope S(*this);
2106   TypeIndex TI = lowerType(Ty, ClassTy);
2107   return recordTypeIndexForDINode(Ty, TI, ClassTy);
2108 }
2109 
2110 TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(DITypeRef TypeRef) {
2111   DIType *Ty = TypeRef.resolve();
2112   PointerRecord PR(getTypeIndex(Ty),
2113                    getPointerSizeInBytes() == 8 ? PointerKind::Near64
2114                                                 : PointerKind::Near32,
2115                    PointerMode::LValueReference, PointerOptions::None,
2116                    Ty->getSizeInBits() / 8);
2117   return TypeTable.writeLeafType(PR);
2118 }
2119 
2120 TypeIndex CodeViewDebug::getCompleteTypeIndex(DITypeRef TypeRef) {
2121   const DIType *Ty = TypeRef.resolve();
2122 
2123   // The null DIType is the void type. Don't try to hash it.
2124   if (!Ty)
2125     return TypeIndex::Void();
2126 
2127   // If this is a non-record type, the complete type index is the same as the
2128   // normal type index. Just call getTypeIndex.
2129   switch (Ty->getTag()) {
2130   case dwarf::DW_TAG_class_type:
2131   case dwarf::DW_TAG_structure_type:
2132   case dwarf::DW_TAG_union_type:
2133     break;
2134   default:
2135     return getTypeIndex(Ty);
2136   }
2137 
2138   // Check if we've already translated the complete record type.  Lowering a
2139   // complete type should never trigger lowering another complete type, so we
2140   // can reuse the hash table lookup result.
2141   const auto *CTy = cast<DICompositeType>(Ty);
2142   auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
2143   if (!InsertResult.second)
2144     return InsertResult.first->second;
2145 
2146   TypeLoweringScope S(*this);
2147 
2148   // Make sure the forward declaration is emitted first. It's unclear if this
2149   // is necessary, but MSVC does it, and we should follow suit until we can show
2150   // otherwise.
2151   TypeIndex FwdDeclTI = getTypeIndex(CTy);
2152 
2153   // Just use the forward decl if we don't have complete type info. This might
2154   // happen if the frontend is using modules and expects the complete definition
2155   // to be emitted elsewhere.
2156   if (CTy->isForwardDecl())
2157     return FwdDeclTI;
2158 
2159   TypeIndex TI;
2160   switch (CTy->getTag()) {
2161   case dwarf::DW_TAG_class_type:
2162   case dwarf::DW_TAG_structure_type:
2163     TI = lowerCompleteTypeClass(CTy);
2164     break;
2165   case dwarf::DW_TAG_union_type:
2166     TI = lowerCompleteTypeUnion(CTy);
2167     break;
2168   default:
2169     llvm_unreachable("not a record");
2170   }
2171 
2172   InsertResult.first->second = TI;
2173   return TI;
2174 }
2175 
2176 /// Emit all the deferred complete record types. Try to do this in FIFO order,
2177 /// and do this until fixpoint, as each complete record type typically
2178 /// references
2179 /// many other record types.
2180 void CodeViewDebug::emitDeferredCompleteTypes() {
2181   SmallVector<const DICompositeType *, 4> TypesToEmit;
2182   while (!DeferredCompleteTypes.empty()) {
2183     std::swap(DeferredCompleteTypes, TypesToEmit);
2184     for (const DICompositeType *RecordTy : TypesToEmit)
2185       getCompleteTypeIndex(RecordTy);
2186     TypesToEmit.clear();
2187   }
2188 }
2189 
2190 void CodeViewDebug::emitLocalVariableList(ArrayRef<LocalVariable> Locals) {
2191   // Get the sorted list of parameters and emit them first.
2192   SmallVector<const LocalVariable *, 6> Params;
2193   for (const LocalVariable &L : Locals)
2194     if (L.DIVar->isParameter())
2195       Params.push_back(&L);
2196   std::sort(Params.begin(), Params.end(),
2197             [](const LocalVariable *L, const LocalVariable *R) {
2198               return L->DIVar->getArg() < R->DIVar->getArg();
2199             });
2200   for (const LocalVariable *L : Params)
2201     emitLocalVariable(*L);
2202 
2203   // Next emit all non-parameters in the order that we found them.
2204   for (const LocalVariable &L : Locals)
2205     if (!L.DIVar->isParameter())
2206       emitLocalVariable(L);
2207 }
2208 
2209 void CodeViewDebug::emitLocalVariable(const LocalVariable &Var) {
2210   // LocalSym record, see SymbolRecord.h for more info.
2211   MCSymbol *LocalBegin = MMI->getContext().createTempSymbol(),
2212            *LocalEnd = MMI->getContext().createTempSymbol();
2213   OS.AddComment("Record length");
2214   OS.emitAbsoluteSymbolDiff(LocalEnd, LocalBegin, 2);
2215   OS.EmitLabel(LocalBegin);
2216 
2217   OS.AddComment("Record kind: S_LOCAL");
2218   OS.EmitIntValue(unsigned(SymbolKind::S_LOCAL), 2);
2219 
2220   LocalSymFlags Flags = LocalSymFlags::None;
2221   if (Var.DIVar->isParameter())
2222     Flags |= LocalSymFlags::IsParameter;
2223   if (Var.DefRanges.empty())
2224     Flags |= LocalSymFlags::IsOptimizedOut;
2225 
2226   OS.AddComment("TypeIndex");
2227   TypeIndex TI = Var.UseReferenceType
2228                      ? getTypeIndexForReferenceTo(Var.DIVar->getType())
2229                      : getCompleteTypeIndex(Var.DIVar->getType());
2230   OS.EmitIntValue(TI.getIndex(), 4);
2231   OS.AddComment("Flags");
2232   OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
2233   // Truncate the name so we won't overflow the record length field.
2234   emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
2235   OS.EmitLabel(LocalEnd);
2236 
2237   // Calculate the on disk prefix of the appropriate def range record. The
2238   // records and on disk formats are described in SymbolRecords.h. BytePrefix
2239   // should be big enough to hold all forms without memory allocation.
2240   SmallString<20> BytePrefix;
2241   for (const LocalVarDefRange &DefRange : Var.DefRanges) {
2242     BytePrefix.clear();
2243     if (DefRange.InMemory) {
2244       uint16_t RegRelFlags = 0;
2245       if (DefRange.IsSubfield) {
2246         RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
2247                       (DefRange.StructOffset
2248                        << DefRangeRegisterRelSym::OffsetInParentShift);
2249       }
2250       DefRangeRegisterRelSym Sym(S_DEFRANGE_REGISTER_REL);
2251       Sym.Hdr.Register = DefRange.CVRegister;
2252       Sym.Hdr.Flags = RegRelFlags;
2253       Sym.Hdr.BasePointerOffset = DefRange.DataOffset;
2254       ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER_REL);
2255       BytePrefix +=
2256           StringRef(reinterpret_cast<const char *>(&SymKind), sizeof(SymKind));
2257       BytePrefix +=
2258           StringRef(reinterpret_cast<const char *>(&Sym.Hdr), sizeof(Sym.Hdr));
2259     } else {
2260       assert(DefRange.DataOffset == 0 && "unexpected offset into register");
2261       if (DefRange.IsSubfield) {
2262         // Unclear what matters here.
2263         DefRangeSubfieldRegisterSym Sym(S_DEFRANGE_SUBFIELD_REGISTER);
2264         Sym.Hdr.Register = DefRange.CVRegister;
2265         Sym.Hdr.MayHaveNoName = 0;
2266         Sym.Hdr.OffsetInParent = DefRange.StructOffset;
2267 
2268         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_SUBFIELD_REGISTER);
2269         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2270                                 sizeof(SymKind));
2271         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2272                                 sizeof(Sym.Hdr));
2273       } else {
2274         // Unclear what matters here.
2275         DefRangeRegisterSym Sym(S_DEFRANGE_REGISTER);
2276         Sym.Hdr.Register = DefRange.CVRegister;
2277         Sym.Hdr.MayHaveNoName = 0;
2278         ulittle16_t SymKind = ulittle16_t(S_DEFRANGE_REGISTER);
2279         BytePrefix += StringRef(reinterpret_cast<const char *>(&SymKind),
2280                                 sizeof(SymKind));
2281         BytePrefix += StringRef(reinterpret_cast<const char *>(&Sym.Hdr),
2282                                 sizeof(Sym.Hdr));
2283       }
2284     }
2285     OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
2286   }
2287 }
2288 
2289 void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
2290   const Function &GV = MF->getFunction();
2291   assert(FnDebugInfo.count(&GV));
2292   assert(CurFn == &FnDebugInfo[&GV]);
2293 
2294   collectVariableInfo(GV.getSubprogram());
2295 
2296   // Don't emit anything if we don't have any line tables.
2297   if (!CurFn->HaveLineInfo) {
2298     FnDebugInfo.erase(&GV);
2299     CurFn = nullptr;
2300     return;
2301   }
2302 
2303   CurFn->Annotations = MF->getCodeViewAnnotations();
2304 
2305   CurFn->End = Asm->getFunctionEnd();
2306 
2307   CurFn = nullptr;
2308 }
2309 
2310 void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
2311   DebugHandlerBase::beginInstruction(MI);
2312 
2313   // Ignore DBG_VALUE locations and function prologue.
2314   if (!Asm || !CurFn || MI->isDebugValue() ||
2315       MI->getFlag(MachineInstr::FrameSetup))
2316     return;
2317 
2318   // If the first instruction of a new MBB has no location, find the first
2319   // instruction with a location and use that.
2320   DebugLoc DL = MI->getDebugLoc();
2321   if (!DL && MI->getParent() != PrevInstBB) {
2322     for (const auto &NextMI : *MI->getParent()) {
2323       if (NextMI.isDebugValue())
2324         continue;
2325       DL = NextMI.getDebugLoc();
2326       if (DL)
2327         break;
2328     }
2329   }
2330   PrevInstBB = MI->getParent();
2331 
2332   // If we still don't have a debug location, don't record a location.
2333   if (!DL)
2334     return;
2335 
2336   maybeRecordLocation(DL, Asm->MF);
2337 }
2338 
2339 MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
2340   MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
2341            *EndLabel = MMI->getContext().createTempSymbol();
2342   OS.EmitIntValue(unsigned(Kind), 4);
2343   OS.AddComment("Subsection size");
2344   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
2345   OS.EmitLabel(BeginLabel);
2346   return EndLabel;
2347 }
2348 
2349 void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
2350   OS.EmitLabel(EndLabel);
2351   // Every subsection must be aligned to a 4-byte boundary.
2352   OS.EmitValueToAlignment(4);
2353 }
2354 
2355 void CodeViewDebug::emitDebugInfoForUDTs(
2356     ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
2357   for (const auto &UDT : UDTs) {
2358     const DIType *T = UDT.second;
2359     assert(shouldEmitUdt(T));
2360 
2361     MCSymbol *UDTRecordBegin = MMI->getContext().createTempSymbol(),
2362              *UDTRecordEnd = MMI->getContext().createTempSymbol();
2363     OS.AddComment("Record length");
2364     OS.emitAbsoluteSymbolDiff(UDTRecordEnd, UDTRecordBegin, 2);
2365     OS.EmitLabel(UDTRecordBegin);
2366 
2367     OS.AddComment("Record kind: S_UDT");
2368     OS.EmitIntValue(unsigned(SymbolKind::S_UDT), 2);
2369 
2370     OS.AddComment("Type");
2371     OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
2372 
2373     emitNullTerminatedSymbolName(OS, UDT.first);
2374     OS.EmitLabel(UDTRecordEnd);
2375   }
2376 }
2377 
2378 void CodeViewDebug::emitDebugInfoForGlobals() {
2379   DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
2380       GlobalMap;
2381   for (const GlobalVariable &GV : MMI->getModule()->globals()) {
2382     SmallVector<DIGlobalVariableExpression *, 1> GVEs;
2383     GV.getDebugInfo(GVEs);
2384     for (const auto *GVE : GVEs)
2385       GlobalMap[GVE] = &GV;
2386   }
2387 
2388   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2389   for (const MDNode *Node : CUs->operands()) {
2390     const auto *CU = cast<DICompileUnit>(Node);
2391 
2392     // First, emit all globals that are not in a comdat in a single symbol
2393     // substream. MSVC doesn't like it if the substream is empty, so only open
2394     // it if we have at least one global to emit.
2395     switchToDebugSectionForSymbol(nullptr);
2396     MCSymbol *EndLabel = nullptr;
2397     for (const auto *GVE : CU->getGlobalVariables()) {
2398       if (const auto *GV = GlobalMap.lookup(GVE))
2399         if (!GV->hasComdat() && !GV->isDeclarationForLinker()) {
2400           if (!EndLabel) {
2401             OS.AddComment("Symbol subsection for globals");
2402             EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2403           }
2404           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2405           emitDebugInfoForGlobal(GVE->getVariable(), GV, Asm->getSymbol(GV));
2406         }
2407     }
2408     if (EndLabel)
2409       endCVSubsection(EndLabel);
2410 
2411     // Second, emit each global that is in a comdat into its own .debug$S
2412     // section along with its own symbol substream.
2413     for (const auto *GVE : CU->getGlobalVariables()) {
2414       if (const auto *GV = GlobalMap.lookup(GVE)) {
2415         if (GV->hasComdat()) {
2416           MCSymbol *GVSym = Asm->getSymbol(GV);
2417           OS.AddComment("Symbol subsection for " +
2418                         Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
2419           switchToDebugSectionForSymbol(GVSym);
2420           EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
2421           // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
2422           emitDebugInfoForGlobal(GVE->getVariable(), GV, GVSym);
2423           endCVSubsection(EndLabel);
2424         }
2425       }
2426     }
2427   }
2428 }
2429 
2430 void CodeViewDebug::emitDebugInfoForRetainedTypes() {
2431   NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
2432   for (const MDNode *Node : CUs->operands()) {
2433     for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
2434       if (DIType *RT = dyn_cast<DIType>(Ty)) {
2435         getTypeIndex(RT);
2436         // FIXME: Add to global/local DTU list.
2437       }
2438     }
2439   }
2440 }
2441 
2442 void CodeViewDebug::emitDebugInfoForGlobal(const DIGlobalVariable *DIGV,
2443                                            const GlobalVariable *GV,
2444                                            MCSymbol *GVSym) {
2445   // DataSym record, see SymbolRecord.h for more info.
2446   // FIXME: Thread local data, etc
2447   MCSymbol *DataBegin = MMI->getContext().createTempSymbol(),
2448            *DataEnd = MMI->getContext().createTempSymbol();
2449   OS.AddComment("Record length");
2450   OS.emitAbsoluteSymbolDiff(DataEnd, DataBegin, 2);
2451   OS.EmitLabel(DataBegin);
2452   if (DIGV->isLocalToUnit()) {
2453     if (GV->isThreadLocal()) {
2454       OS.AddComment("Record kind: S_LTHREAD32");
2455       OS.EmitIntValue(unsigned(SymbolKind::S_LTHREAD32), 2);
2456     } else {
2457       OS.AddComment("Record kind: S_LDATA32");
2458       OS.EmitIntValue(unsigned(SymbolKind::S_LDATA32), 2);
2459     }
2460   } else {
2461     if (GV->isThreadLocal()) {
2462       OS.AddComment("Record kind: S_GTHREAD32");
2463       OS.EmitIntValue(unsigned(SymbolKind::S_GTHREAD32), 2);
2464     } else {
2465       OS.AddComment("Record kind: S_GDATA32");
2466       OS.EmitIntValue(unsigned(SymbolKind::S_GDATA32), 2);
2467     }
2468   }
2469   OS.AddComment("Type");
2470   OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
2471   OS.AddComment("DataOffset");
2472   OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
2473   OS.AddComment("Segment");
2474   OS.EmitCOFFSectionIndex(GVSym);
2475   OS.AddComment("Name");
2476   emitNullTerminatedSymbolName(OS, DIGV->getName());
2477   OS.EmitLabel(DataEnd);
2478 }
2479