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