-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathIRGenDebugInfo.cpp
2523 lines (2223 loc) · 98.4 KB
/
IRGenDebugInfo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- IRGenDebugInfo.cpp - Debug Info Support --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR debug info generation for Swift.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "debug-info"
#include "IRGenDebugInfo.h"
#include "GenOpaque.h"
#include "GenType.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Expr.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/Pattern.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/Config/config.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
#ifndef NDEBUG
#include "swift/AST/ASTDemangler.h"
#endif
using namespace swift;
using namespace irgen;
llvm::cl::opt<bool> VerifyLineTable(
"verify-linetable", llvm::cl::init(false),
llvm::cl::desc(
"Verify that the debug locations within one scope are contiguous."));
namespace {
using TrackingDIRefMap =
llvm::DenseMap<const llvm::MDString *, llvm::TrackingMDNodeRef>;
class IRGenDebugInfoImpl : public IRGenDebugInfo {
friend class IRGenDebugInfoImpl;
const IRGenOptions &Opts;
ClangImporter &CI;
SourceManager &SM;
llvm::Module &M;
llvm::DIBuilder DBuilder;
IRGenModule &IGM;
const PathRemapper &DebugPrefixMap;
/// Various caches.
/// @{
llvm::DenseMap<const SILDebugScope *, llvm::TrackingMDNodeRef> ScopeCache;
llvm::DenseMap<const SILDebugScope *, llvm::TrackingMDNodeRef> InlinedAtCache;
llvm::DenseMap<const void *, SILLocation::DebugLoc> DebugLocCache;
llvm::DenseMap<TypeBase *, llvm::TrackingMDNodeRef> DITypeCache;
llvm::DenseMap<const void *, llvm::TrackingMDNodeRef> DIModuleCache;
llvm::StringMap<llvm::TrackingMDNodeRef> DIFileCache;
TrackingDIRefMap DIRefMap;
/// @}
/// A list of replaceable fwddecls that need to be RAUWed at the end.
std::vector<std::pair<TypeBase *, llvm::TrackingMDRef>> ReplaceMap;
/// The set of imported modules.
llvm::DenseSet<ModuleDecl *> ImportedModules;
llvm::BumpPtrAllocator DebugInfoNames;
/// The current working directory.
StringRef CWDName;
/// User-provided -D macro definitions.
SmallString<0> ConfigMacros;
/// The current compilation unit.
llvm::DICompileUnit *TheCU = nullptr;
/// The main file.
llvm::DIFile *MainFile = nullptr;
/// The current module.
llvm::DIModule *MainModule = nullptr;
/// Scope of SWIFT_ENTRY_POINT_FUNCTION.
llvm::DIScope *EntryPointFn = nullptr;
/// The artificial type decls for named archetypes.
llvm::StringMap<TypeAliasDecl *> MetadataTypeDeclCache;
/// Catch-all type for opaque internal types.
llvm::DIType *InternalType = nullptr;
/// The last location that was emitted.
SILLocation::DebugLoc LastDebugLoc;
/// The scope of that last location.
const SILDebugScope *LastScope = nullptr;
/// Used by pushLoc.
SmallVector<std::pair<SILLocation::DebugLoc, const SILDebugScope *>, 8>
LocationStack;
#ifndef NDEBUG
using UUSTuple = std::pair<std::pair<unsigned, unsigned>, StringRef>;
struct DebugLocKey : public UUSTuple {
DebugLocKey(SILLocation::DebugLoc DL)
: UUSTuple({{DL.Line, DL.Column}, DL.Filename}) {}
inline bool operator==(const SILLocation::DebugLoc &DL) const {
return first.first == DL.Line && first.second == DL.Column &&
second.equals(DL.Filename);
}
};
llvm::DenseSet<UUSTuple> PreviousLineEntries;
SILLocation::DebugLoc PreviousDebugLoc;
#endif
public:
IRGenDebugInfoImpl(const IRGenOptions &Opts, ClangImporter &CI,
IRGenModule &IGM, llvm::Module &M,
StringRef MainOutputFilenameForDebugInfo,
StringRef PrivateDiscriminator);
void finalize();
void setCurrentLoc(IRBuilder &Builder, const SILDebugScope *DS,
SILLocation Loc);
void addFailureMessageToCurrentLoc(IRBuilder &Builder, StringRef failureMsg);
void clearLoc(IRBuilder &Builder);
void pushLoc();
void popLoc();
void setInlinedTrapLocation(IRBuilder &Builder, const SILDebugScope *Scope);
void setEntryPointLoc(IRBuilder &Builder);
llvm::DIScope *getEntryPointFn();
llvm::DIScope *getOrCreateScope(const SILDebugScope *DS);
void emitImport(ImportDecl *D);
llvm::DISubprogram *emitFunction(const SILDebugScope *DS, llvm::Function *Fn,
SILFunctionTypeRepresentation Rep,
SILType Ty, DeclContext *DeclCtx = nullptr);
llvm::DISubprogram *emitFunction(SILFunction &SILFn, llvm::Function *Fn);
void emitArtificialFunction(IRBuilder &Builder, llvm::Function *Fn,
SILType SILTy);
void emitVariableDeclaration(IRBuilder &Builder,
ArrayRef<llvm::Value *> Storage,
DebugTypeInfo Ty, const SILDebugScope *DS,
ValueDecl *VarDecl, SILDebugVariable VarInfo,
IndirectionKind = DirectValue,
ArtificialKind = RealValue);
void emitDbgIntrinsic(IRBuilder &Builder, llvm::Value *Storage,
llvm::DILocalVariable *Var, llvm::DIExpression *Expr,
unsigned Line, unsigned Col, llvm::DILocalScope *Scope,
const SILDebugScope *DS);
void emitGlobalVariableDeclaration(llvm::GlobalVariable *Storage,
StringRef Name, StringRef LinkageName,
DebugTypeInfo DebugType,
bool IsLocalToUnit, bool InFixedBuffer,
Optional<SILLocation> Loc);
void emitTypeMetadata(IRGenFunction &IGF, llvm::Value *Metadata,
unsigned Depth, unsigned Index, StringRef Name);
/// Return the DIBuilder.
llvm::DIBuilder &getBuilder() { return DBuilder; }
/// Decode (and cache) a SourceLoc.
SILLocation::DebugLoc decodeSourceLoc(SourceLoc SL);
IRGenDebugInfoFormat getDebugInfoFormat() { return Opts.DebugInfoFormat; }
private:
static StringRef getFilenameFromDC(const DeclContext *DC) {
if (auto *LF = dyn_cast<LoadedFile>(DC))
return LF->getFilename();
if (auto *SF = dyn_cast<SourceFile>(DC))
return SF->getFilename();
if (auto *M = dyn_cast<ModuleDecl>(DC))
return M->getModuleFilename();
return {};
}
using DebugLoc = SILLocation::DebugLoc;
DebugLoc getDeserializedLoc(Pattern *) { return {}; }
DebugLoc getDeserializedLoc(Expr *) { return {}; }
DebugLoc getDeserializedLoc(Decl *D) {
DebugLoc L;
const DeclContext *DC = D->getDeclContext()->getModuleScopeContext();
StringRef Filename = getFilenameFromDC(DC);
if (!Filename.empty())
L.Filename = Filename;
return L;
}
/// Use the Swift SM to figure out the actual line/column of a SourceLoc.
template <typename WithLoc>
DebugLoc getSwiftDebugLoc(IRGenDebugInfo &DI, WithLoc *ASTNode, bool End) {
if (!ASTNode)
return {};
SourceLoc Loc = End ? ASTNode->getEndLoc() : ASTNode->getStartLoc();
if (Loc.isInvalid())
// This may be a deserialized or clang-imported decl. And modules
// don't come with SourceLocs right now. Get at least the name of
// the module.
return getDeserializedLoc(ASTNode);
return DI.decodeSourceLoc(Loc);
}
DebugLoc getDebugLoc(IRGenDebugInfo &DI, Pattern *P, bool End = false) {
return getSwiftDebugLoc(DI, P, End);
}
DebugLoc getDebugLoc(IRGenDebugInfo &DI, Expr *E, bool End = false) {
return getSwiftDebugLoc(DI, E, End);
}
DebugLoc getDebugLoc(IRGenDebugInfo &DI, Decl *D, bool End = false) {
DebugLoc L;
if (!D)
return L;
if (auto *ClangDecl = D->getClangDecl()) {
clang::SourceLocation ClangSrcLoc = ClangDecl->getBeginLoc();
clang::SourceManager &ClangSM =
CI.getClangASTContext().getSourceManager();
clang::PresumedLoc PresumedLoc = ClangSM.getPresumedLoc(ClangSrcLoc);
if (!PresumedLoc.isValid())
return L;
L.Line = PresumedLoc.getLine();
L.Column = PresumedLoc.getColumn();
L.Filename = PresumedLoc.getFilename();
return L;
}
return getSwiftDebugLoc(DI, D, End);
}
DebugLoc getStartLocation(Optional<SILLocation> OptLoc) {
if (!OptLoc)
return {};
return decodeSourceLoc(OptLoc->getStartSourceLoc());
}
DebugLoc sanitizeCodeViewDebugLoc(DebugLoc DLoc) {
if (Opts.DebugInfoFormat == IRGenDebugInfoFormat::CodeView)
// When WinDbg finds two locations with the same line but different
// columns, the user must select an address when they break on that
// line. Also, clang does not emit column locations in CodeView for C++.
DLoc.Column = 0;
return DLoc;
}
DebugLoc decodeDebugLoc(SILLocation Loc) {
if (Loc.isDebugInfoLoc())
return sanitizeCodeViewDebugLoc(Loc.getDebugInfoLoc());
return decodeSourceLoc(Loc.getDebugSourceLoc());
}
DebugLoc getDebugLocation(Optional<SILLocation> OptLoc) {
if (!OptLoc || (Opts.DebugInfoFormat != IRGenDebugInfoFormat::CodeView &&
OptLoc->isInPrologue()))
return {};
return decodeDebugLoc(*OptLoc);
}
/// Strdup a raw char array using the bump pointer.
StringRef BumpAllocatedString(const char *Data, size_t Length) {
char *Ptr = DebugInfoNames.Allocate<char>(Length + 1);
memcpy(Ptr, Data, Length);
*(Ptr + Length) = 0;
return StringRef(Ptr, Length);
}
/// Strdup S using the bump pointer.
StringRef BumpAllocatedString(std::string S) {
return BumpAllocatedString(S.c_str(), S.length());
}
/// Strdup StringRef S using the bump pointer.
StringRef BumpAllocatedString(StringRef S) {
return BumpAllocatedString(S.data(), S.size());
}
/// Return the size reported by a type.
static unsigned getSizeInBits(llvm::DIType *Ty) {
// Follow derived types until we reach a type that
// reports back a size.
while (isa<llvm::DIDerivedType>(Ty) && !Ty->getSizeInBits()) {
auto *DT = cast<llvm::DIDerivedType>(Ty);
Ty = DT->getBaseType();
if (!Ty)
return 0;
}
return Ty->getSizeInBits();
}
#ifndef NDEBUG
/// Return the size reported by the variable's type.
static unsigned getSizeInBits(const llvm::DILocalVariable *Var) {
llvm::DIType *Ty = Var->getType();
return getSizeInBits(Ty);
}
#endif
/// Determine whether this debug scope belongs to an explicit closure.
static bool isExplicitClosure(const SILFunction *SILFn) {
if (SILFn && SILFn->hasLocation())
if (Expr *E = SILFn->getLocation().getAsASTNode<Expr>())
if (isa<ClosureExpr>(E))
return true;
return false;
}
llvm::MDNode *createInlinedAt(const SILDebugScope *DS) {
auto *CS = DS->InlinedCallSite;
if (!CS)
return nullptr;
auto CachedInlinedAt = InlinedAtCache.find(CS);
if (CachedInlinedAt != InlinedAtCache.end())
return cast<llvm::MDNode>(CachedInlinedAt->second);
auto L = decodeDebugLoc(CS->Loc);
auto Scope = getOrCreateScope(CS->Parent.dyn_cast<const SILDebugScope *>());
// Pretend transparent functions don't exist.
if (!Scope)
return createInlinedAt(CS);
auto InlinedAt =
llvm::DebugLoc::get(L.Line, L.Column, Scope, createInlinedAt(CS));
InlinedAtCache.insert(
{CS, llvm::TrackingMDNodeRef(InlinedAt.getAsMDNode())});
return InlinedAt;
}
#ifndef NDEBUG
/// Perform a couple of sanity checks on scopes.
static bool parentScopesAreSane(const SILDebugScope *DS) {
auto *Parent = DS;
while ((Parent = Parent->Parent.dyn_cast<const SILDebugScope *>())) {
if (!DS->InlinedCallSite)
assert(!Parent->InlinedCallSite &&
"non-inlined scope has an inlined parent");
}
return true;
}
/// Assert that within one lexical block, each location is only visited once.
bool lineEntryIsSane(SILLocation::DebugLoc DL, const SILDebugScope *DS);
#endif
llvm::DIFile *getOrCreateFile(StringRef Filename) {
if (Filename.empty())
Filename = SILLocation::getCompilerGeneratedDebugLoc().Filename;
// Look in the cache first.
auto CachedFile = DIFileCache.find(Filename);
if (CachedFile != DIFileCache.end()) {
// Verify that the information still exists.
if (llvm::Metadata *V = CachedFile->second)
return cast<llvm::DIFile>(V);
}
// Detect the main file.
StringRef MainFileName = MainFile->getFilename();
if (MainFile && Filename.endswith(MainFileName)) {
SmallString<256> AbsThisFile, AbsMainFile;
AbsThisFile = Filename;
llvm::sys::fs::make_absolute(AbsThisFile);
if (llvm::sys::path::is_absolute(MainFileName))
AbsMainFile = MainFileName;
else
llvm::sys::path::append(AbsMainFile, MainFile->getDirectory(),
MainFileName);
if (AbsThisFile == DebugPrefixMap.remapPath(AbsMainFile)) {
DIFileCache[Filename] = llvm::TrackingMDNodeRef(MainFile);
return MainFile;
}
}
return createFile(Filename, None, None);
}
/// This is effectively \p clang::CGDebugInfo::createFile().
llvm::DIFile *
createFile(StringRef FileName,
Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
Optional<StringRef> Source) {
StringRef Dir;
StringRef File;
SmallString<128> DirBuf;
SmallString<128> FileBuf;
std::string RemappedFileString = DebugPrefixMap.remapPath(FileName);
SmallString<128> RemappedFile = StringRef(RemappedFileString);
llvm::sys::path::remove_dots(RemappedFile);
std::string CurDir = DebugPrefixMap.remapPath(Opts.DebugCompilationDir);
if (llvm::sys::path::is_absolute(RemappedFile)) {
// Strip the common prefix (if it is more than just "/") from current
// directory and FileName for a more space-efficient encoding.
auto FileIt = llvm::sys::path::begin(RemappedFile);
auto FileE = llvm::sys::path::end(RemappedFile);
auto CurDirIt = llvm::sys::path::begin(CurDir);
auto CurDirE = llvm::sys::path::end(CurDir);
for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
llvm::sys::path::append(DirBuf, *CurDirIt);
if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
// Don't strip the common prefix if it is only the root "/"
// since that would make LLVM diagnostic locations confusing.
Dir = {};
File = RemappedFile;
} else {
for (; FileIt != FileE; ++FileIt)
llvm::sys::path::append(FileBuf, *FileIt);
Dir = DirBuf;
File = FileBuf;
}
} else {
File = RemappedFile;
// Leave <compiler-generated> & friends as is, without directory.
if (!(File.startswith("<") && File.endswith(">")))
Dir = CurDir;
}
llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
DIFileCache[FileName].reset(F);
return F;
}
StringRef getName(const FuncDecl &FD) {
// Getters and Setters are anonymous functions, so we forge a name
// using its parent declaration.
if (auto accessor = dyn_cast<AccessorDecl>(&FD))
if (ValueDecl *VD = accessor->getStorage()) {
const char *Kind;
switch (accessor->getAccessorKind()) {
case AccessorKind::Get:
Kind = ".get";
break;
case AccessorKind::Set:
Kind = ".set";
break;
case AccessorKind::WillSet:
Kind = ".willset";
break;
case AccessorKind::DidSet:
Kind = ".didset";
break;
case AccessorKind::Address:
Kind = ".addressor";
break;
case AccessorKind::MutableAddress:
Kind = ".mutableAddressor";
break;
case AccessorKind::Read:
Kind = ".read";
break;
case AccessorKind::Modify:
Kind = ".modify";
break;
}
SmallVector<char, 64> Buf;
StringRef Name = (VD->getBaseName().userFacingName() +
Twine(Kind)).toStringRef(Buf);
return BumpAllocatedString(Name);
}
if (FD.hasName())
return FD.getName().str();
return StringRef();
}
StringRef getName(SILLocation L) {
if (L.isNull())
return StringRef();
if (FuncDecl *FD = L.getAsASTNode<FuncDecl>())
return getName(*FD);
if (L.isASTNode<ConstructorDecl>())
return "init";
if (L.isASTNode<DestructorDecl>())
return "deinit";
return StringRef();
}
static CanSILFunctionType getFunctionType(SILType SILTy) {
if (!SILTy)
return CanSILFunctionType();
auto FnTy = SILTy.getAs<SILFunctionType>();
if (!FnTy) {
LLVM_DEBUG(llvm::dbgs() << "Unexpected function type: ";
SILTy.print(llvm::dbgs());
llvm::dbgs() << "\n");
return CanSILFunctionType();
}
return FnTy;
}
llvm::DIScope *getOrCreateContext(DeclContext *DC) {
if (!DC)
return TheCU;
if (isa<FuncDecl>(DC))
if (auto *Decl = IGM.getSILModule().lookUpFunction(SILDeclRef(
cast<AbstractFunctionDecl>(DC), SILDeclRef::Kind::Func)))
return getOrCreateScope(Decl->getDebugScope());
switch (DC->getContextKind()) {
// The interesting cases are already handled above.
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::AbstractClosureExpr:
// We don't model these in DWARF.
case DeclContextKind::SerializedLocal:
case DeclContextKind::Initializer:
case DeclContextKind::ExtensionDecl:
case DeclContextKind::SubscriptDecl:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::TopLevelCodeDecl:
return getOrCreateContext(DC->getParent());
case DeclContextKind::Module:
return getOrCreateModule(
{ModuleDecl::AccessPathTy(), cast<ModuleDecl>(DC)});
case DeclContextKind::FileUnit:
// A module may contain multiple files.
return getOrCreateContext(DC->getParent());
case DeclContextKind::GenericTypeDecl: {
auto *NTD = cast<NominalTypeDecl>(DC);
auto *Ty = NTD->getDeclaredType().getPointer();
if (auto *DITy = getTypeOrNull(Ty))
return DITy;
// Create a Forward-declared type.
auto Loc = getDebugLoc(*this, NTD);
auto File = getOrCreateFile(Loc.Filename);
auto Line = Loc.Line;
auto FwdDecl = DBuilder.createReplaceableCompositeType(
llvm::dwarf::DW_TAG_structure_type, NTD->getName().str(),
getOrCreateContext(DC->getParent()), File, Line,
llvm::dwarf::DW_LANG_Swift, 0, 0);
ReplaceMap.emplace_back(
std::piecewise_construct, std::make_tuple(Ty),
std::make_tuple(static_cast<llvm::Metadata *>(FwdDecl)));
return FwdDecl;
}
}
return TheCU;
}
void createParameterType(llvm::SmallVectorImpl<llvm::Metadata *> &Parameters,
SILType type) {
auto RealType = type.getASTType();
auto DbgTy = DebugTypeInfo::getFromTypeInfo(RealType, IGM.getTypeInfo(type));
Parameters.push_back(getOrCreateType(DbgTy));
}
// This is different from SILFunctionType::getAllResultsType() in some subtle
// ways.
static SILType getResultTypeForDebugInfo(IRGenModule &IGM,
CanSILFunctionType fnTy) {
if (fnTy->getNumResults() == 1) {
return fnTy->getResults()[0].getSILStorageType(IGM.getSILModule(), fnTy);
} else if (!fnTy->getNumIndirectFormalResults()) {
return fnTy->getDirectFormalResultsType(IGM.getSILModule());
} else {
SmallVector<TupleTypeElt, 4> eltTys;
for (auto &result : fnTy->getResults()) {
eltTys.push_back(result.getReturnValueType(IGM.getSILModule(), fnTy));
}
return SILType::getPrimitiveAddressType(
CanType(TupleType::get(eltTys, fnTy->getASTContext())));
}
}
llvm::DITypeRefArray createParameterTypes(SILType SILTy) {
if (!SILTy)
return nullptr;
return createParameterTypes(SILTy.castTo<SILFunctionType>());
}
llvm::DITypeRefArray createParameterTypes(CanSILFunctionType FnTy) {
SmallVector<llvm::Metadata *, 16> Parameters;
GenericContextScope scope(IGM, FnTy->getInvocationGenericSignature());
// The function return type is the first element in the list.
createParameterType(Parameters, getResultTypeForDebugInfo(IGM, FnTy));
// Actually, the input type is either a single type or a tuple
// type. We currently represent a function with one n-tuple argument
// as an n-ary function.
for (auto Param : FnTy->getParameters())
createParameterType(Parameters, IGM.silConv.getSILType(Param, FnTy));
return DBuilder.getOrCreateTypeArray(Parameters);
}
/// FIXME: replace this condition with something more sane.
static bool isAllocatingConstructor(SILFunctionTypeRepresentation Rep,
DeclContext *DeclCtx) {
return Rep != SILFunctionTypeRepresentation::Method && DeclCtx &&
isa<ConstructorDecl>(DeclCtx);
}
llvm::DIModule *getOrCreateModule(const void *Key, llvm::DIScope *Parent,
StringRef Name, StringRef IncludePath,
uint64_t Signature = ~1ULL,
StringRef ASTFile = StringRef()) {
// Look in the cache first.
auto Val = DIModuleCache.find(Key);
if (Val != DIModuleCache.end())
return cast<llvm::DIModule>(Val->second);
std::string RemappedIncludePath = DebugPrefixMap.remapPath(IncludePath);
// For Clang modules / PCH, create a Skeleton CU pointing to the PCM/PCH.
if (!Opts.DisableClangModuleSkeletonCUs) {
bool CreateSkeletonCU = !ASTFile.empty();
bool IsRootModule = !Parent;
if (CreateSkeletonCU && IsRootModule) {
llvm::DIBuilder DIB(M);
DIB.createCompileUnit(IGM.ObjCInterop ? llvm::dwarf::DW_LANG_ObjC
: llvm::dwarf::DW_LANG_C99,
DIB.createFile(Name, RemappedIncludePath),
TheCU->getProducer(), true, StringRef(), 0,
ASTFile, llvm::DICompileUnit::FullDebug,
Signature);
DIB.finalize();
}
}
StringRef Sysroot = IGM.Context.SearchPathOpts.SDKPath;
llvm::DIModule *M =
DBuilder.createModule(Parent, Name, ConfigMacros, RemappedIncludePath,
Sysroot);
DIModuleCache.insert({Key, llvm::TrackingMDNodeRef(M)});
return M;
}
using ASTSourceDescriptor = clang::ExternalASTSource::ASTSourceDescriptor;
/// Create a DIModule from a clang module or PCH.
/// The clang::Module pointer is passed separately because the recursive case
/// needs to fudge the AST descriptor.
llvm::DIModule *getOrCreateModule(ASTSourceDescriptor Desc,
const clang::Module *ClangModule) {
// PCH files don't have a signature field in the control block,
// but LLVM detects skeleton CUs by looking for a non-zero DWO id.
// We use the lower 64 bits for debug info.
uint64_t Signature =
Desc.getSignature()
? (uint64_t)Desc.getSignature()[1] << 32 | Desc.getSignature()[0]
: ~1ULL;
// Handle Clang modules.
if (ClangModule) {
llvm::DIModule *Parent = nullptr;
if (ClangModule->Parent) {
// The loading of additional modules by Sema may trigger an out-of-date
// PCM rebuild in the Clang module dependencies of the additional
// module. A PCM rebuild causes the ModuleManager to unload previously
// loaded ASTFiles. For this reason we must use the cached ASTFile
// information here instead of the potentially dangling pointer to the
// ASTFile that is stored in the clang::Module object.
//
// Note: The implementation here assumes that all clang submodules
// belong to the same PCM file.
ASTSourceDescriptor ParentDescriptor(*ClangModule->Parent);
Parent = getOrCreateModule({ParentDescriptor.getModuleName(),
ParentDescriptor.getPath(),
Desc.getASTFile(), Desc.getSignature()},
ClangModule->Parent);
}
return getOrCreateModule(ClangModule, Parent, Desc.getModuleName(),
Desc.getPath(), Signature, Desc.getASTFile());
}
// Handle PCH.
return getOrCreateModule(Desc.getASTFile().bytes_begin(), nullptr,
Desc.getModuleName(), Desc.getPath(), Signature,
Desc.getASTFile());
};
static Optional<ASTSourceDescriptor> getClangModule(const ModuleDecl &M) {
for (auto *FU : M.getFiles())
if (auto *CMU = dyn_cast_or_null<ClangModuleUnit>(FU))
if (auto Desc = CMU->getASTSourceDescriptor())
return Desc;
return None;
}
llvm::DIModule *getOrCreateModule(ModuleDecl::ImportedModule IM) {
ModuleDecl *M = IM.second;
if (Optional<ASTSourceDescriptor> ModuleDesc = getClangModule(*M))
return getOrCreateModule(*ModuleDesc, ModuleDesc->getModuleOrNull());
StringRef Path = getFilenameFromDC(M);
StringRef Name = M->getName().str();
return getOrCreateModule(M, TheCU, Name, Path);
}
TypeAliasDecl *getMetadataType(StringRef ArchetypeName) {
TypeAliasDecl *&Entry = MetadataTypeDeclCache[ArchetypeName];
if (Entry)
return Entry;
SourceLoc NoLoc;
Entry = new (IGM.Context) TypeAliasDecl(
NoLoc, NoLoc, IGM.Context.getIdentifier(ArchetypeName), NoLoc,
/*genericparams*/ nullptr, IGM.Context.TheBuiltinModule);
Entry->setUnderlyingType(IGM.Context.TheRawPointerType);
return Entry;
}
/// Return the DIFile that is the ancestor of Scope.
llvm::DIFile *getFile(llvm::DIScope *Scope) {
while (!isa<llvm::DIFile>(Scope)) {
switch (Scope->getTag()) {
case llvm::dwarf::DW_TAG_lexical_block:
Scope = cast<llvm::DILexicalBlock>(Scope)->getScope();
break;
case llvm::dwarf::DW_TAG_subprogram:
Scope = cast<llvm::DISubprogram>(Scope)->getFile();
break;
default:
return MainFile;
}
if (Scope)
return MainFile;
}
return cast<llvm::DIFile>(Scope);
}
static Size getStorageSize(const llvm::DataLayout &DL,
ArrayRef<llvm::Value *> Storage) {
unsigned size = 0;
for (llvm::Value *Piece : Storage)
size += DL.getTypeSizeInBits(Piece->getType());
return Size(size);
}
StringRef getMangledName(DebugTypeInfo DbgTy) {
if (DbgTy.IsMetadataType)
return MetadataTypeDeclCache.find(DbgTy.getDecl()->getName().str())
->getKey();
Type Ty = DbgTy.getType();
if (!Ty->hasTypeParameter())
Ty = Ty->mapTypeOutOfContext();
// Strip off top level of type sugar (except for type aliases).
// We don't want Optional<T> and T? to get different debug types.
while (true) {
if (auto *ParenTy = dyn_cast<ParenType>(Ty.getPointer())) {
Ty = ParenTy->getUnderlyingType();
continue;
}
if (auto *SugarTy = dyn_cast<SyntaxSugarType>(Ty.getPointer())) {
Ty = SugarTy->getSinglyDesugaredType();
continue;
}
break;
}
// TODO: Eliminate substitutions in SILFunctionTypes for now.
// On platforms where the substitutions affect representation, we will need
// to preserve this info and teach type reconstruction about it.
Ty = Ty->replaceSubstitutedSILFunctionTypesWithUnsubstituted(IGM.getSILModule());
Mangle::ASTMangler Mangler;
std::string Result = Mangler.mangleTypeForDebugger(
Ty, nullptr);
if (!Opts.DisableRoundTripDebugTypes
// FIXME: implement type reconstruction for opaque types
&& !Ty->hasOpaqueArchetype()) {
// Make sure we can reconstruct mangled types for the debugger.
#ifndef NDEBUG
auto &Ctx = Ty->getASTContext();
Type Reconstructed = Demangle::getTypeForMangling(Ctx, Result);
if (!Reconstructed) {
llvm::errs() << "Failed to reconstruct type for " << Result << "\n";
llvm::errs() << "Original type:\n";
Ty->dump(llvm::errs());
abort();
} else if (!Reconstructed->isEqual(Ty)) {
llvm::errs() << "Incorrect reconstructed type for " << Result << "\n";
llvm::errs() << "Original type:\n";
Ty->dump(llvm::errs());
llvm::errs() << "Reconstructed type:\n";
Reconstructed->dump(llvm::errs());
abort();
}
#endif
}
return BumpAllocatedString(Result);
}
llvm::DIDerivedType *createMemberType(DebugTypeInfo DbgTy, StringRef Name,
unsigned &OffsetInBits,
llvm::DIScope *Scope,
llvm::DIFile *File,
llvm::DINode::DIFlags Flags) {
unsigned SizeOfByte = CI.getTargetInfo().getCharWidth();
auto *Ty = getOrCreateType(DbgTy);
auto *DITy = DBuilder.createMemberType(Scope, Name, File, 0,
SizeOfByte * DbgTy.size.getValue(),
0, OffsetInBits, Flags, Ty);
OffsetInBits += getSizeInBits(Ty);
OffsetInBits =
llvm::alignTo(OffsetInBits, SizeOfByte * DbgTy.align.getValue());
return DITy;
}
llvm::DINodeArray
getTupleElements(TupleType *TupleTy, llvm::DIScope *Scope, llvm::DIFile *File,
llvm::DINode::DIFlags Flags, unsigned &SizeInBits) {
SmallVector<llvm::Metadata *, 16> Elements;
unsigned OffsetInBits = 0;
auto genericSig = IGM.getCurGenericContext();
for (auto ElemTy : TupleTy->getElementTypes()) {
auto &elemTI = IGM.getTypeInfoForUnlowered(
AbstractionPattern(genericSig, ElemTy->getCanonicalType()), ElemTy);
auto DbgTy =
DebugTypeInfo::getFromTypeInfo(ElemTy, elemTI);
Elements.push_back(createMemberType(DbgTy, StringRef(), OffsetInBits,
Scope, File, Flags));
}
SizeInBits = OffsetInBits;
return DBuilder.getOrCreateArray(Elements);
}
llvm::DINodeArray getStructMembers(NominalTypeDecl *D, Type BaseTy,
llvm::DIScope *Scope, llvm::DIFile *File,
llvm::DINode::DIFlags Flags,
unsigned &SizeInBits) {
SmallVector<llvm::Metadata *, 16> Elements;
unsigned OffsetInBits = 0;
for (VarDecl *VD : D->getStoredProperties()) {
auto memberTy =
BaseTy->getTypeOfMember(IGM.getSwiftModule(), VD, nullptr);
auto DbgTy = DebugTypeInfo::getFromTypeInfo(
VD->getInterfaceType(),
IGM.getTypeInfoForUnlowered(
IGM.getSILTypes().getAbstractionPattern(VD), memberTy));
Elements.push_back(createMemberType(DbgTy, VD->getName().str(),
OffsetInBits, Scope, File, Flags));
}
if (OffsetInBits > SizeInBits)
SizeInBits = OffsetInBits;
return DBuilder.getOrCreateArray(Elements);
}
llvm::DICompositeType *
createStructType(DebugTypeInfo DbgTy, NominalTypeDecl *Decl, Type BaseTy,
llvm::DIScope *Scope, llvm::DIFile *File, unsigned Line,
unsigned SizeInBits, unsigned AlignInBits,
llvm::DINode::DIFlags Flags, llvm::DIType *DerivedFrom,
unsigned RuntimeLang, StringRef UniqueID) {
StringRef Name = Decl->getName().str();
// Forward declare this first because types may be recursive.
auto FwdDecl = llvm::TempDIType(DBuilder.createReplaceableCompositeType(
llvm::dwarf::DW_TAG_structure_type, Name, Scope, File, Line,
llvm::dwarf::DW_LANG_Swift, SizeInBits, 0, Flags, UniqueID));
#ifndef NDEBUG
if (UniqueID.empty())
assert(!Name.empty() &&
"no mangled name and no human readable name given");
else
assert((UniqueID.startswith("_T") ||
UniqueID.startswith(MANGLING_PREFIX_STR)) &&
"UID is not a mangled name");
#endif
auto TH = llvm::TrackingMDNodeRef(FwdDecl.get());
DITypeCache[DbgTy.getType()] = TH;
auto Members =
getStructMembers(Decl, BaseTy, Scope, File, Flags, SizeInBits);
auto DITy = DBuilder.createStructType(
Scope, Name, File, Line, SizeInBits, AlignInBits, Flags, DerivedFrom,
Members, RuntimeLang, nullptr, UniqueID);
DBuilder.replaceTemporary(std::move(FwdDecl), DITy);
return DITy;
}
llvm::DINodeArray getEnumElements(DebugTypeInfo DbgTy, EnumDecl *ED,
llvm::DIScope *Scope, llvm::DIFile *File,
llvm::DINode::DIFlags Flags) {
SmallVector<llvm::Metadata *, 16> Elements;
for (auto *ElemDecl : ED->getAllElements()) {
// FIXME <rdar://problem/14845818> Support enums.
// Swift Enums can be both like DWARF enums and discriminated unions.
DebugTypeInfo ElemDbgTy;
if (ED->hasRawType())
// An enum with a raw type (enum E : Int {}), similar to a
// DWARF enum.
//
// The storage occupied by the enum may be smaller than the
// one of the raw type as long as it is large enough to hold
// all enum values. Use the raw type for the debug type, but
// the storage size from the enum.
ElemDbgTy = DebugTypeInfo(ED->getRawType(), DbgTy.StorageType,
DbgTy.size, DbgTy.align, true, false);
else if (auto ArgTy = ElemDecl->getArgumentInterfaceType()) {
// A discriminated union. This should really be described as a
// DW_TAG_variant_type. For now only describing the data.
ArgTy = ElemDecl->getParentEnum()->mapTypeIntoContext(ArgTy);
auto &TI = IGM.getTypeInfoForUnlowered(ArgTy);
ElemDbgTy = DebugTypeInfo::getFromTypeInfo(ArgTy, TI);
} else {
// Discriminated union case without argument. Fallback to Int
// as the element type; there is no storage here.
Type IntTy = IGM.Context.getIntDecl()->getDeclaredType();
ElemDbgTy = DebugTypeInfo(IntTy, DbgTy.StorageType, Size(0),
Alignment(1), true, false);
}
unsigned Offset = 0;
auto MTy = createMemberType(ElemDbgTy, ElemDecl->getName().str(), Offset,
Scope, File, Flags);
Elements.push_back(MTy);
}
return DBuilder.getOrCreateArray(Elements);
}
llvm::DICompositeType *createEnumType(DebugTypeInfo DbgTy, EnumDecl *Decl,
StringRef MangledName,
llvm::DIScope *Scope,
llvm::DIFile *File, unsigned Line,
llvm::DINode::DIFlags Flags) {
unsigned SizeOfByte = CI.getTargetInfo().getCharWidth();
unsigned SizeInBits = DbgTy.size.getValue() * SizeOfByte;
// Default, since Swift doesn't allow specifying a custom alignment.
unsigned AlignInBits = 0;
// FIXME: Is DW_TAG_union_type the right thing here?
// Consider using a DW_TAG_variant_type instead.
auto FwdDecl = llvm::TempDIType(DBuilder.createReplaceableCompositeType(
llvm::dwarf::DW_TAG_union_type, MangledName, Scope, File, Line,
llvm::dwarf::DW_LANG_Swift, SizeInBits, AlignInBits, Flags,
MangledName));
auto TH = llvm::TrackingMDNodeRef(FwdDecl.get());
DITypeCache[DbgTy.getType()] = TH;
auto DITy = DBuilder.createUnionType(
Scope, Decl->getName().str(), File, Line, SizeInBits, AlignInBits,
Flags, getEnumElements(DbgTy, Decl, Scope, File, Flags),
llvm::dwarf::DW_LANG_Swift, MangledName);
DBuilder.replaceTemporary(std::move(FwdDecl), DITy);
return DITy;
}
llvm::DIType *getOrCreateDesugaredType(Type Ty, DebugTypeInfo DbgTy) {
DebugTypeInfo BlandDbgTy(Ty, DbgTy.StorageType, DbgTy.size, DbgTy.align,
DbgTy.DefaultAlignment, DbgTy.IsMetadataType);
return getOrCreateType(BlandDbgTy);
}
uint64_t getSizeOfBasicType(DebugTypeInfo DbgTy) {
uint64_t SizeOfByte = CI.getTargetInfo().getCharWidth();
uint64_t BitWidth = DbgTy.size.getValue() * SizeOfByte;
llvm::Type *StorageType = DbgTy.StorageType
? DbgTy.StorageType
: IGM.DataLayout.getSmallestLegalIntType(
IGM.getLLVMContext(), BitWidth);