forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mangle.cpp
1857 lines (1646 loc) · 64.3 KB
/
Mangle.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
//===--- Mangle.cpp - Swift Name Mangling --------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements declaration name mangling in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Mangle.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/Punycode.h"
#include "clang/Basic/CharInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace Mangle;
static bool isNonAscii(StringRef str) {
for (unsigned char c : str) {
if (c >= 0x80)
return true;
}
return false;
}
namespace {
/// A helpful little wrapper for a value that should be mangled
/// in a particular, compressed value.
class Index {
unsigned N;
public:
explicit Index(unsigned n) : N(n) {}
friend raw_ostream &operator<<(raw_ostream &out, Index n) {
if (n.N != 0) out << (n.N - 1);
return (out << '_');
}
};
}
/// Mangle a StringRef as an identifier into a buffer.
void Mangler::mangleIdentifier(StringRef str, OperatorFixity fixity,
bool isOperator) {
auto operatorKind = [=]() -> Demangle::OperatorKind {
if (!isOperator) return Demangle::OperatorKind::NotOperator;
switch (fixity) {
case OperatorFixity::NotOperator:return Demangle::OperatorKind::NotOperator;
case OperatorFixity::Prefix: return Demangle::OperatorKind::Prefix;
case OperatorFixity::Postfix: return Demangle::OperatorKind::Postfix;
case OperatorFixity::Infix: return Demangle::OperatorKind::Infix;
}
llvm_unreachable("invalid operator fixity");
}();
std::string buf;
Demangle::mangleIdentifier(str.data(), str.size(), operatorKind, buf,
UsePunycode);
Buffer << buf;
}
/// Mangle an identifier into the buffer.
void Mangler::mangleIdentifier(Identifier ident, OperatorFixity fixity) {
StringRef str = ident.str();
assert(!str.empty() && "mangling an empty identifier!");
return mangleIdentifier(str, fixity, ident.isOperator());
}
bool Mangler::tryMangleSubstitution(const void *ptr) {
auto ir = Substitutions.find(ptr);
if (ir == Substitutions.end()) return false;
// substitution ::= 'S' integer? '_'
unsigned index = ir->second;
Buffer << 'S';
if (index) Buffer << (index - 1);
Buffer << '_';
return true;
}
void Mangler::addSubstitution(const void *ptr) {
Substitutions.insert(std::make_pair(ptr, Substitutions.size()));
}
/// Mangle the context of the given declaration as a <context.
/// This is the top-level entrypoint for mangling <context>.
void Mangler::mangleContextOf(const ValueDecl *decl, BindGenerics shouldBind) {
auto clangDecl = decl->getClangDecl();
// Classes and protocols implemented in Objective-C have a special context
// mangling.
// known-context ::= 'So'
if (isa<ClassDecl>(decl) && clangDecl) {
assert(isa<clang::ObjCInterfaceDecl>(clangDecl) ||
isa<clang::TypedefDecl>(clangDecl));
Buffer << "So";
return;
}
if (isa<ProtocolDecl>(decl) && clangDecl) {
assert(isa<clang::ObjCProtocolDecl>(clangDecl));
Buffer << "So";
return;
}
// Declarations provided by a C module have a special context mangling.
// known-context ::= 'SC'
// Do a dance to avoid a layering dependency.
if (auto file = dyn_cast<FileUnit>(decl->getDeclContext())) {
if (file->getKind() == FileUnitKind::ClangModule) {
Buffer << "SC";
return;
}
}
// Just mangle the decl's DC.
mangleContext(decl->getDeclContext(), shouldBind);
}
namespace {
class FindFirstVariable :
public PatternVisitor<FindFirstVariable, VarDecl *> {
public:
VarDecl *visitNamedPattern(NamedPattern *P) {
return P->getDecl();
}
VarDecl *visitTuplePattern(TuplePattern *P) {
for (auto &elt : P->getElements()) {
VarDecl *var = visit(elt.getPattern());
if (var) return var;
}
return nullptr;
}
VarDecl *visitParenPattern(ParenPattern *P) {
return visit(P->getSubPattern());
}
VarDecl *visitVarPattern(VarPattern *P) {
return visit(P->getSubPattern());
}
VarDecl *visitTypedPattern(TypedPattern *P) {
return visit(P->getSubPattern());
}
VarDecl *visitAnyPattern(AnyPattern *P) {
return nullptr;
}
// Refutable patterns shouldn't ever come up.
#define REFUTABLE_PATTERN(ID, BASE) \
VarDecl *visit##ID##Pattern(ID##Pattern *P) { \
llvm_unreachable("shouldn't be visiting a refutable pattern here!"); \
}
#define PATTERN(ID, BASE)
#include "swift/AST/PatternNodes.def"
};
}
/// Find the first identifier bound by the given binding. This
/// assumes that field and global-variable bindings always bind at
/// least one name, which is probably a reasonable assumption but may
/// not be adequately enforced.
static VarDecl *findFirstVariable(PatternBindingDecl *binding) {
for (auto entry : binding->getPatternList()) {
auto var = FindFirstVariable().visit(entry.getPattern());
if (var) return var;
}
llvm_unreachable("pattern-binding bound no variables?");
}
CanGenericSignature Mangler::getCanonicalSignatureOrNull(GenericSignature *sig,
ModuleDecl &M) {
if (!sig)
return nullptr;
Mod = &M;
return sig->getCanonicalManglingSignature(M);
}
void Mangler::mangleContext(const DeclContext *ctx, BindGenerics shouldBind) {
switch (ctx->getContextKind()) {
case DeclContextKind::Module:
return mangleModule(cast<Module>(ctx));
case DeclContextKind::FileUnit:
assert(!isa<BuiltinUnit>(ctx) && "mangling member of builtin module!");
mangleContext(ctx->getParent(), shouldBind);
return;
case DeclContextKind::SerializedLocal: {
auto local = cast<SerializedLocalDeclContext>(ctx);
switch (local->getLocalDeclContextKind()) {
case LocalDeclContextKind::AbstractClosure:
mangleClosureEntity(cast<SerializedAbstractClosureExpr>(local),
ResilienceExpansion::Minimal, /*uncurry*/ 0);
return;
case LocalDeclContextKind::DefaultArgumentInitializer: {
auto argInit = cast<SerializedDefaultArgumentInitializer>(local);
mangleDefaultArgumentEntity(ctx->getParent(), argInit->getIndex());
return;
}
case LocalDeclContextKind::PatternBindingInitializer: {
auto patternInit = cast<SerializedPatternBindingInitializer>(local);
auto var = findFirstVariable(patternInit->getBinding());
mangleInitializerEntity(var);
return;
}
case LocalDeclContextKind::TopLevelCodeDecl:
return mangleContext(local->getParent(), shouldBind);
}
}
case DeclContextKind::NominalTypeDecl:
mangleNominalType(cast<NominalTypeDecl>(ctx), ResilienceExpansion::Minimal,
shouldBind);
return;
case DeclContextKind::ExtensionDecl: {
auto ExtD = cast<ExtensionDecl>(ctx);
auto ExtTy = ExtD->getExtendedType();
// Recover from erroneous extension.
if (ExtTy.isNull() || ExtTy->is<ErrorType>())
return mangleContext(ExtD->getDeclContext(), shouldBind);
auto decl = ExtTy->getAnyNominal();
assert(decl && "extension of non-nominal type?");
// Mangle the module name if:
// - the extension is defined in a different module from the actual nominal
// type decl,
// - the extension is constrained, or
// - the extension is to a protocol.
// FIXME: In a world where protocol extensions are dynamically dispatched,
// "extension is to a protocol" would no longer be a reason to use the
// extension mangling, because an extension method implementation could be
// resiliently moved into the original protocol itself.
if (ExtD->getParentModule() != decl->getParentModule()
|| ExtD->isConstrainedExtension()
|| ExtD->getDeclaredInterfaceType()->isExistentialType()) {
auto sig = ExtD->getGenericSignature();
// If the extension is constrained, mangle the generic signature that
// constrains it.
bool mangleSignature = sig && ExtD->isConstrainedExtension();
Buffer << (mangleSignature ? 'e' : 'E');
mangleModule(ExtD->getParentModule());
if (mangleSignature) {
Mod = ExtD->getModuleContext();
mangleGenericSignature(sig, ResilienceExpansion::Minimal);
}
}
mangleNominalType(decl, ResilienceExpansion::Minimal, shouldBind,
getCanonicalSignatureOrNull(ExtD->getGenericSignature(),
*ExtD->getParentModule()),
ExtD->getGenericParams());
return;
}
case DeclContextKind::AbstractClosureExpr:
return mangleClosureEntity(cast<AbstractClosureExpr>(ctx),
ResilienceExpansion::Minimal, /*uncurry*/ 0);
case DeclContextKind::AbstractFunctionDecl: {
auto fn = cast<AbstractFunctionDecl>(ctx);
// Constructors and destructors as contexts are always mangled
// using the non-(de)allocating variants.
if (auto ctor = dyn_cast<ConstructorDecl>(fn)) {
return mangleConstructorEntity(ctor, /*allocating*/ false,
ResilienceExpansion::Minimal,
/*uncurry*/ 0);
}
if (auto dtor = dyn_cast<DestructorDecl>(fn))
return mangleDestructorEntity(dtor, /*deallocating*/ false);
return mangleEntity(fn, ResilienceExpansion::Minimal, /*uncurry*/ 0);
}
case DeclContextKind::Initializer:
switch (cast<Initializer>(ctx)->getInitializerKind()) {
case InitializerKind::DefaultArgument: {
auto argInit = cast<DefaultArgumentInitializer>(ctx);
mangleDefaultArgumentEntity(ctx->getParent(),
argInit->getIndex());
return;
}
case InitializerKind::PatternBinding: {
auto patternInit = cast<PatternBindingInitializer>(ctx);
auto var = findFirstVariable(patternInit->getBinding());
mangleInitializerEntity(var);
return;
}
}
llvm_unreachable("bad initializer kind");
case DeclContextKind::TopLevelCodeDecl:
// Mangle the containing module context.
return mangleContext(ctx->getParent(), shouldBind);
}
llvm_unreachable("bad decl context");
}
void Mangler::mangleModule(const Module *module) {
assert(!module->getParent() && "cannot mangle nested modules!");
// Try the special 'swift' substitution.
// context ::= known-module
// known-module ::= 's'
if (module->isStdlibModule()) {
Buffer << "s";
return;
}
// context ::= substitution
if (tryMangleSubstitution(module)) return;
// context ::= identifier
mangleIdentifier(module->getName());
addSubstitution(module);
}
/// Bind the generic parameters from the given list and its parents.
void Mangler::bindGenericParameters(CanGenericSignature sig,
const GenericParamList *genericParams) {
if (sig)
CurGenericSignature = sig;
assert(genericParams);
SmallVector<const GenericParamList *, 2> paramLists;
// Determine the depth our parameter list is at. We don't actually need to
// emit the outer parameters because they should have been emitted as part of
// the outer context.
assert(ArchetypesDepth == genericParams->getDepth());
ArchetypesDepth++;
unsigned index = 0;
for (auto archetype : genericParams->getPrimaryArchetypes()) {
// Remember the current depth and level.
ArchetypeInfo info;
info.Depth = ArchetypesDepth;
info.Index = index++;
assert(!Archetypes.count(archetype) ||
(Archetypes[archetype].Depth == info.Depth &&
Archetypes[archetype].Index == info.Index));
Archetypes.insert(std::make_pair(archetype, info));
}
}
static OperatorFixity getDeclFixity(const ValueDecl *decl) {
if (!decl->getName().isOperator())
return OperatorFixity::NotOperator;
switch (decl->getAttrs().getUnaryOperatorKind()) {
case UnaryOperatorKind::Prefix: return OperatorFixity::Prefix;
case UnaryOperatorKind::Postfix: return OperatorFixity::Postfix;
case UnaryOperatorKind::None: return OperatorFixity::Infix;
}
llvm_unreachable("bad UnaryOperatorKind");
}
void Mangler::mangleDeclName(const ValueDecl *decl) {
if (decl->getDeclContext()->isLocalContext()) {
// Mangle local declarations with a numeric discriminator.
// decl-name ::= 'L' index identifier
Buffer << 'L' << Index(decl->getLocalDiscriminator());
// Fall through to mangle the <identifier>.
} else if (decl->hasAccessibility() &&
decl->getFormalAccess() == Accessibility::Private) {
// Mangle non-local private declarations with a textual discriminator
// based on their enclosing file.
// decl-name ::= 'P' identifier identifier
// Don't bother to use the private discriminator if the enclosing context
// is also private.
auto isWithinPrivateNominal = [](const Decl *D) -> bool {
const DeclContext *DC = D->getDeclContext();
if (!DC->isTypeContext()) {
assert((DC->isModuleScopeContext() || DC->isLocalContext()) &&
"do we need a private discriminator for this context?");
return false;
}
auto nominal = dyn_cast<NominalTypeDecl>(DC);
if (!nominal)
nominal = cast<ExtensionDecl>(DC)->getExtendedType()->getAnyNominal();
return nominal->getFormalAccess() == Accessibility::Private;
};
if (!isWithinPrivateNominal(decl)) {
// The first <identifier> is a discriminator string unique to the decl's
// original source file.
auto topLevelContext = decl->getDeclContext()->getModuleScopeContext();
auto fileUnit = cast<FileUnit>(topLevelContext);
Identifier discriminator =
fileUnit->getDiscriminatorForPrivateValue(decl);
assert(!discriminator.empty());
assert(!isNonAscii(discriminator.str()) &&
"discriminator contains non-ASCII characters");
(void) isNonAscii;
assert(!clang::isDigit(discriminator.str().front()) &&
"not a valid identifier");
Buffer << 'P';
mangleIdentifier(discriminator);
}
// Fall through to mangle the name.
}
// decl-name ::= identifier
mangleIdentifier(decl->getName(), getDeclFixity(decl));
}
static void bindAllGenericParameters(Mangler &mangler,
CanGenericSignature sig,
GenericParamList *generics) {
if (!generics) {
mangler.resetArchetypesDepth();
return;
}
bindAllGenericParameters(mangler, nullptr, generics->getOuterParameters());
mangler.bindGenericParameters(sig, generics);
}
void Mangler::mangleTypeForDebugger(Type Ty, const DeclContext *DC) {
assert(DWARFMangling && "DWARFMangling expected whn mangling for debugger");
// Polymorphic function types carry their own generic parameters and
// manglePolymorphicType will bind them.
bool BindGenericParams = Ty->getKind() != TypeKind::PolymorphicFunction;
Buffer << "_Tt";
// Move up to the innermost generic context.
while (DC && !DC->isInnermostContextGeneric()) DC = DC->getParent();
if (DC && BindGenericParams)
bindAllGenericParameters(*this,
getCanonicalSignatureOrNull(
DC->getGenericSignatureOfContext(),
*DC->getParentModule()),
DC->getGenericParamsOfContext());
DeclCtx = DC;
mangleType(Ty, ResilienceExpansion::Minimal, /*uncurry*/ 0);
}
void Mangler::mangleDeclTypeForDebugger(const ValueDecl *decl) {
assert(DWARFMangling && "DWARFMangling expected");
Buffer << "_Tt";
typedef std::pair<bool, BindGenerics> result_t;
struct ClassifyDecl : swift::DeclVisitor<ClassifyDecl, result_t> {
/// TypeAliasDecls need to be mangled.
result_t visitTypeAliasDecl(TypeDecl *D) {
llvm_unreachable("filtered out above");
}
/// Other TypeDecls don't need their types mangled in.
result_t visitTypeDecl(TypeDecl *D) {
return { false, BindGenerics::None };
}
/// Function-like declarations do, but they should have
/// polymorphic type and therefore don't need specific binding.
result_t visitFuncDecl(FuncDecl *D) {
if (D->getDeclContext()->isTypeContext())
return { true, BindGenerics::Enclosing };
else
return { true, BindGenerics::All };
}
result_t visitConstructorDecl(ConstructorDecl *D) {
return { true, BindGenerics::Enclosing };
}
result_t visitDestructorDecl(DestructorDecl *D) {
return { true, BindGenerics::Enclosing };
}
result_t visitEnumElementDecl(EnumElementDecl *D) {
return { true, BindGenerics::Enclosing };
}
/// All other values need to have contextual archetypes bound.
result_t visitVarDecl(VarDecl *D) {
return { true, BindGenerics::All };
}
result_t visitParamDecl(ParamDecl *D) {
return { true, BindGenerics::All };
}
result_t visitSubscriptDecl(SubscriptDecl *D) {
return { true, BindGenerics::All };
}
/// Make sure we have a case for every ValueDecl.
result_t visitValueDecl(ValueDecl *D) = delete;
/// Everything else should be unreachable here.
result_t visitDecl(Decl *D) {
llvm_unreachable("not a ValueDecl");
}
};
auto result = ClassifyDecl().visit(const_cast<ValueDecl *>(decl));
if (!result.first) return;
// Find the innermost generic context and stash it in DeclCtx.
// Also track whether DC is just a type ancestor of the decl.
DeclContext *DC = decl->getDeclContext();
bool isNonTypeDC = false;
while (DC && !DC->isInnermostContextGeneric()) {
if (!isNonTypeDC) isNonTypeDC = !DC->isTypeContext();
DC = DC->getParent();
}
DeclCtx = DC;
// Bind the generic parameters from that.
if (DC) {
// But if the generics come from a type container, they may be
// accounted for in the decl's type; skip them if so.
if (result.second == BindGenerics::Enclosing && !isNonTypeDC) {
while (DC->isTypeContext())
DC = DC->getParent();
}
bindAllGenericParameters(*this,
getCanonicalSignatureOrNull(
DC->getGenericSignatureOfContext(),
*DC->getParentModule()),
DC->getGenericParamsOfContext());
}
mangleDeclType(decl, ResilienceExpansion::Minimal, /*uncurry*/ 0);
}
/// Is this declaration a method for mangling purposes? If so, we'll leave the
/// Self type out of its mangling.
static bool isMethodDecl(const Decl *decl) {
return isa<AbstractFunctionDecl>(decl)
&& (isa<NominalTypeDecl>(decl->getDeclContext())
|| isa<ExtensionDecl>(decl->getDeclContext()));
}
static bool genericParamIsBelowDepth(Type type, unsigned methodDepth) {
if (auto gp = type->getAs<GenericTypeParamType>()) {
return gp->getDepth() >= methodDepth;
}
if (auto dm = type->getAs<DependentMemberType>()) {
return genericParamIsBelowDepth(dm->getBase(), methodDepth);
}
// Non-dependent types in a same-type requirement don't affect whether we
// mangle the requirement.
return false;
}
Type Mangler::getDeclTypeForMangling(const ValueDecl *decl,
ArrayRef<GenericTypeParamType *> &genericParams,
unsigned &initialParamDepth,
ArrayRef<Requirement> &requirements,
SmallVectorImpl<Requirement> &requirementsBuf) {
auto &C = decl->getASTContext();
if (!decl->hasType())
return ErrorType::get(C);
Type type = decl->getInterfaceType();
initialParamDepth = 0;
CanGenericSignature sig;
if (auto gft = type->getAs<GenericFunctionType>()) {
assert(Mod);
sig = gft->getGenericSignature()->getCanonicalManglingSignature(*Mod);
CurGenericSignature = sig;
genericParams = sig->getGenericParams();
requirements = sig->getRequirements();
type = FunctionType::get(gft->getInput(), gft->getResult(),
gft->getExtInfo());
} else {
genericParams = {};
requirements = {};
}
// Shed the 'self' type and generic requirements from method manglings.
if (C.LangOpts.DisableSelfTypeMangling
&& isMethodDecl(decl)
&& type && !type->is<ErrorType>()) {
// Drop the Self argument clause from the type.
type = type->castTo<AnyFunctionType>()->getResult();
// Drop generic parameters and requirements from the method's context.
if (auto parentGenericSig =
decl->getDeclContext()->getGenericSignatureOfContext()) {
// The method's depth starts below the depth of the context.
if (!parentGenericSig->getGenericParams().empty())
initialParamDepth =
parentGenericSig->getGenericParams().back()->getDepth()+1;
while (!genericParams.empty()) {
if (genericParams.front()->getDepth() >= initialParamDepth)
break;
genericParams = genericParams.slice(1);
}
requirementsBuf.clear();
for (auto &reqt : sig->getRequirements()) {
switch (reqt.getKind()) {
case RequirementKind::WitnessMarker:
// Not needed for mangling.
continue;
case RequirementKind::Conformance:
// We don't need the requirement if the constrained type is above the
// method depth.
if (!genericParamIsBelowDepth(reqt.getFirstType(), initialParamDepth))
continue;
break;
case RequirementKind::SameType:
// We don't need the requirement if both types are above the method
// depth, or non-dependent.
if (!genericParamIsBelowDepth(reqt.getFirstType(),initialParamDepth)&&
!genericParamIsBelowDepth(reqt.getSecondType(),initialParamDepth))
continue;
break;
}
// If we fell through the switch, mangle the requirement.
requirementsBuf.push_back(reqt);
}
requirements = requirementsBuf;
}
}
return type;
}
void Mangler::mangleDeclType(const ValueDecl *decl,
ResilienceExpansion explosion,
unsigned uncurryLevel) {
ArrayRef<GenericTypeParamType *> genericParams;
unsigned initialParamDepth;
ArrayRef<Requirement> requirements;
SmallVector<Requirement, 4> requirementsBuf;
Mod = decl->getModuleContext();
Type type = getDeclTypeForMangling(decl,
genericParams, initialParamDepth,
requirements, requirementsBuf);
// Mangle the generic signature, if any.
if (!genericParams.empty() || !requirements.empty()) {
Buffer << 'u';
mangleGenericSignatureParts(genericParams, initialParamDepth,
requirements, explosion);
}
mangleType(type->getCanonicalType(), explosion, uncurryLevel);
// Bind the declaration's generic context for nested decls.
if (decl->getInterfaceType()
&& !decl->getInterfaceType()->is<ErrorType>()) {
if (const auto context = dyn_cast<DeclContext>(decl)) {
if (auto params = context->getGenericParamsOfContext()) {
bindAllGenericParameters(*this, nullptr, params);
}
}
}
}
void Mangler::mangleConstrainedType(CanType type,
ResilienceExpansion expansion) {
// The type constrained by a generic requirement should always be a
// generic parameter or associated type thereof. Assuming this lets us save
// an introducer character in the common case when a generic parameter is
// constrained.
assert(isa<DependentMemberType>(type) || isa<GenericTypeParamType>(type));
if (auto gp = dyn_cast<GenericTypeParamType>(type)) {
mangleGenericParamIndex(gp);
return;
}
mangleType(type, expansion, 0);
}
void Mangler::mangleGenericSignatureParts(
ArrayRef<GenericTypeParamType*> params,
unsigned initialParamDepth,
ArrayRef<Requirement> requirements,
ResilienceExpansion expansion) {
// Mangle the number of parameters.
unsigned depth = 0;
unsigned count = 0;
// Since it's unlikely (but not impossible) to have zero generic parameters
// at a depth, encode indexes starting from 1, and use a special mangling
// for zero.
auto mangleGenericParamCount = [&](unsigned depth, unsigned count) {
if (depth < initialParamDepth)
return;
if (count == 0)
Buffer << 'z';
else
Buffer << Index(count - 1);
};
// As a special case, mangle nothing if there's a single generic parameter
// at the initial depth.
if (params.size() == 1 && params[0]->getDepth() == initialParamDepth)
goto mangle_requirements;
for (auto param : params) {
if (param->getDepth() != depth) {
assert(param->getDepth() > depth && "generic params not ordered");
while (depth < param->getDepth()) {
mangleGenericParamCount(depth, count);
++depth;
count = 0;
}
}
assert(param->getIndex() == count && "generic params not ordered");
++count;
}
mangleGenericParamCount(depth, count);
mangle_requirements:
bool didMangleRequirement = false;
// Mangle the requirements.
for (auto &reqt : requirements) {
switch (reqt.getKind()) {
case RequirementKind::WitnessMarker:
break;
case RequirementKind::Conformance: {
if (!didMangleRequirement) {
Buffer << 'R';
didMangleRequirement = true;
}
SmallVector<ProtocolDecl *, 2> protocols;
if (reqt.getSecondType()->isExistentialType(protocols)
&& protocols.size() == 1) {
// Protocol constraints are the common case, so mangle them more
// efficiently.
// TODO: We could golf this a little more by assuming the first type
// is a dependent type.
mangleConstrainedType(reqt.getFirstType()->getCanonicalType(),
expansion);
mangleProtocolName(protocols[0]);
break;
}
mangleConstrainedType(reqt.getFirstType()->getCanonicalType(), expansion);
mangleType(reqt.getSecondType()->getCanonicalType(), expansion, 0);
break;
}
case RequirementKind::SameType:
if (!didMangleRequirement) {
Buffer << 'R';
didMangleRequirement = true;
}
mangleConstrainedType(reqt.getFirstType()->getCanonicalType(), expansion);
Buffer << 'z';
mangleType(reqt.getSecondType()->getCanonicalType(), expansion, 0);
break;
}
}
// Mark end of requirements.
Buffer << 'r';
}
void Mangler::mangleGenericSignature(const GenericSignature *sig,
ResilienceExpansion expansion) {
assert(Mod);
auto canSig = sig->getCanonicalManglingSignature(*Mod);
CurGenericSignature = canSig;
mangleGenericSignatureParts(canSig->getGenericParams(), 0,
canSig->getRequirements(),
expansion);
}
static void mangleMetatypeRepresentation(raw_ostream &Buffer,
MetatypeRepresentation Rep) {
switch (Rep) {
case MetatypeRepresentation::Thin:
Buffer << 't';
break;
case MetatypeRepresentation::Thick:
Buffer << 'T';
break;
case MetatypeRepresentation::ObjC:
Buffer << 'o';
}
}
void Mangler::mangleGenericParamIndex(GenericTypeParamType *paramTy) {
if (paramTy->getDepth() > 0) {
Buffer << 'd';
Buffer << Index(paramTy->getDepth() - 1);
Buffer << Index(paramTy->getIndex());
return;
}
if (paramTy->getIndex() == 0) {
Buffer << 'x';
return;
}
Buffer << Index(paramTy->getIndex() - 1);
}
void Mangler::mangleAssociatedTypeName(DependentMemberType *dmt,
bool canAbbreviate) {
auto assocTy = dmt->getAssocType();
if (tryMangleSubstitution(assocTy))
return;
// If the base type is known to have a single protocol conformance
// in the current generic context, then we don't need to disambiguate the
// associated type name by protocol.
// FIXME: We ought to be able to get to the generic signature from a
// dependent type, but can't yet. Shouldn't need this side channel.
if (!canAbbreviate || !CurGenericSignature || !Mod
|| CurGenericSignature->getConformsTo(dmt->getBase(), *Mod).size() > 1) {
Buffer << 'P';
mangleProtocolName(assocTy->getProtocol());
}
mangleIdentifier(assocTy->getName());
addSubstitution(assocTy);
}
/// Mangle a type into the buffer.
///
/// Type manglings should never start with [0-9dz_] or end with [0-9].
///
/// <type> ::= A <natural> <type> # fixed-sized arrays
/// <type> ::= Bb # Builtin.UnsafeValueBuffer
/// <type> ::= Bf <natural> _ # Builtin.Float
/// <type> ::= Bi <natural> _ # Builtin.Integer
/// <type> ::= BO # Builtin.UnknownObject
/// <type> ::= Bo # Builtin.NativeObject
/// <type> ::= Bb # Builtin.BridgeObject
/// <type> ::= Bp # Builtin.RawPointer
/// <type> ::= Bv <natural> <type> # Builtin.Vector
/// <type> ::= C <decl> # class (substitutable)
/// <type> ::= D <type> # dynamic Self return
/// <type> ::= ERR # Error type
/// <type> ::= 'a' <context> <identifier> # Type alias (DWARF only)
/// <type> ::= F <type> <type> # function type
/// <type> ::= f <type> <type> # uncurried function type
/// <type> ::= G <type> <type>+ _ # bound generic type
/// <type> ::= O <decl> # enum (substitutable)
/// <type> ::= M <type> # metatype
/// <type> ::= P <protocol-list> _ # protocol composition
/// <type> ::= PM <type> # existential metatype
/// <type> ::= Q <index> # archetype with depth=0, index=N
/// <type> ::= Qd <index> <index> # archetype with depth=M+1, index=N
/// <type> ::= 'Qq' index context # archetype+context (DWARF only)
///
/// <type> ::= R <type> # inout
/// <type> ::= T <tuple-element>* _ # tuple
/// <type> ::= U <generic-parameter>+ _ <type>
/// <type> ::= V <decl> # struct (substitutable)
/// <type> ::= Xo <type> # unowned reference type
/// <type> ::= Xw <type> # weak reference type
/// <type> ::= XF <impl-function-type> # SIL function type
///
/// <index> ::= _ # 0
/// <index> ::= <natural> _ # N+1
///
/// <tuple-element> ::= <identifier>? <type>
void Mangler::mangleType(Type type, ResilienceExpansion explosion,
unsigned uncurryLevel) {
assert((DWARFMangling || type->isCanonical()) &&
"expecting canonical types when not mangling for the debugger");
TypeBase *tybase = type.getPointer();
switch (type->getKind()) {
case TypeKind::TypeVariable:
llvm_unreachable("mangling type variable");
case TypeKind::Module:
llvm_unreachable("Cannot mangle module type yet");
case TypeKind::Error:
case TypeKind::Unresolved:
Buffer << "ERR";
return;
// We don't care about these types being a bit verbose because we
// don't expect them to come up that often in API names.
case TypeKind::BuiltinFloat:
switch (cast<BuiltinFloatType>(tybase)->getFPKind()) {
case BuiltinFloatType::IEEE16: Buffer << "Bf16_"; return;
case BuiltinFloatType::IEEE32: Buffer << "Bf32_"; return;
case BuiltinFloatType::IEEE64: Buffer << "Bf64_"; return;
case BuiltinFloatType::IEEE80: Buffer << "Bf80_"; return;
case BuiltinFloatType::IEEE128: Buffer << "Bf128_"; return;
case BuiltinFloatType::PPC128: llvm_unreachable("ppc128 not supported");
}
llvm_unreachable("bad floating-point kind");
case TypeKind::BuiltinInteger: {
auto width = cast<BuiltinIntegerType>(tybase)->getWidth();
if (width.isFixedWidth())
Buffer << "Bi" << width.getFixedWidth() << '_';
else if (width.isPointerWidth())
Buffer << "Bw";
else
llvm_unreachable("impossible width value");
return;
}
case TypeKind::BuiltinRawPointer:
Buffer << "Bp";
return;
case TypeKind::BuiltinNativeObject:
Buffer << "Bo";
return;
case TypeKind::BuiltinBridgeObject:
Buffer << "Bb";
return;
case TypeKind::BuiltinUnknownObject:
Buffer << "BO";
return;
case TypeKind::BuiltinUnsafeValueBuffer:
Buffer << "BB";
return;
case TypeKind::BuiltinVector:
Buffer << "Bv" << cast<BuiltinVectorType>(tybase)->getNumElements();
mangleType(cast<BuiltinVectorType>(tybase)->getElementType(), explosion,
uncurryLevel);
return;
case TypeKind::NameAlias: {
assert(DWARFMangling && "sugared types are only legal for the debugger");
auto NameAliasTy = cast<NameAliasType>(tybase);
TypeAliasDecl *decl = NameAliasTy->getDecl();
if (decl->getModuleContext() == decl->getASTContext().TheBuiltinModule)
// It's not possible to mangle the context of the builtin module.
return mangleType(decl->getUnderlyingType(), explosion, uncurryLevel);
Buffer << "a";
// For the DWARF output we want to mangle the type alias + context,
// unless the type alias references a builtin type.
ContextStack context(*this);
while (DeclCtx && !DeclCtx->isInnermostContextGeneric())
DeclCtx = DeclCtx->getParent();
mangleContextOf(decl, BindGenerics::None);
mangleIdentifier(decl->getName());
return;
}
case TypeKind::Paren:
return mangleSugaredType<ParenType>(type);
case TypeKind::AssociatedType:
return mangleSugaredType<AssociatedTypeType>(type);
case TypeKind::Substituted:
return mangleSugaredType<SubstitutedType>(type);
case TypeKind::ArraySlice: /* fallthrough */
case TypeKind::Optional:
return mangleSugaredType<SyntaxSugarType>(type);
case TypeKind::Dictionary:
return mangleSugaredType<DictionaryType>(type);
case TypeKind::ImplicitlyUnwrappedOptional: {
assert(DWARFMangling && "sugared types are only legal for the debugger");
auto *IUO = cast<ImplicitlyUnwrappedOptionalType>(tybase);
auto implDecl = tybase->getASTContext().getImplicitlyUnwrappedOptionalDecl();
auto GenTy = BoundGenericType::get(implDecl, Type(), IUO->getBaseType());
return mangleType(GenTy, ResilienceExpansion::Minimal, 0);
}
case TypeKind::ExistentialMetatype: {
ExistentialMetatypeType *EMT = cast<ExistentialMetatypeType>(tybase);
if (EMT->hasRepresentation()) {
Buffer << 'X' << 'P' << 'M';
mangleMetatypeRepresentation(Buffer, EMT->getRepresentation());
} else {
Buffer << 'P' << 'M';
}
return mangleType(EMT->getInstanceType(),
ResilienceExpansion::Minimal, 0);
}
case TypeKind::Metatype: {
MetatypeType *MT = cast<MetatypeType>(tybase);