Coverage Report

Created: 2019-07-24 05:18

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