-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathPrintClangFunction.cpp
1712 lines (1594 loc) · 66.7 KB
/
PrintClangFunction.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
//===--- PrintClangFunction.cpp - Printer for C/C++ functions ---*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
#include "PrintClangFunction.h"
#include "ClangSyntaxPrinter.h"
#include "DeclAndTypePrinter.h"
#include "OutputLanguageMode.h"
#include "PrimitiveTypeMapping.h"
#include "PrintClangClassType.h"
#include "PrintClangValueType.h"
#include "SwiftToClangInteropContext.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SwiftNameTranslation.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/IRGen/IRABIDetailsProvider.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/STLExtras.h"
using namespace swift;
namespace {
// FIXME: RENAME.
enum class FunctionSignatureTypeUse { TypeReference, ParamType, ReturnType };
std::optional<PrimitiveTypeMapping::ClangTypeInfo>
getKnownTypeInfo(const TypeDecl *typeDecl, PrimitiveTypeMapping &typeMapping,
OutputLanguageMode languageMode) {
return languageMode == OutputLanguageMode::Cxx
? typeMapping.getKnownCxxTypeInfo(typeDecl)
: typeMapping.getKnownCTypeInfo(typeDecl);
}
bool isKnownType(Type t, PrimitiveTypeMapping &typeMapping,
OutputLanguageMode languageMode) {
if (auto *typeAliasType = dyn_cast<TypeAliasType>(t.getPointer())) {
auto aliasInfo =
getKnownTypeInfo(typeAliasType->getDecl(), typeMapping, languageMode);
if (aliasInfo != std::nullopt)
return true;
return isKnownType(typeAliasType->getSinglyDesugaredType(), typeMapping,
languageMode);
}
const TypeDecl *typeDecl;
auto *tPtr = t->isOptional() ? t->getOptionalObjectType()->getDesugaredType()
: t->getDesugaredType();
if (auto *bgt = dyn_cast<BoundGenericStructType>(tPtr)) {
return bgt->isUnsafePointer() || bgt->isUnsafeMutablePointer();
}
if (auto *structType = dyn_cast<StructType>(tPtr)) {
auto nullableInfo =
getKnownTypeInfo(structType->getDecl(), typeMapping, languageMode);
if (nullableInfo && nullableInfo->canBeNullable)
return true;
}
if (auto *classType = dyn_cast<ClassType>(tPtr)) {
return classType->getClassOrBoundGenericClass()->hasClangNode() &&
isa<clang::ObjCInterfaceDecl>(
classType->getClassOrBoundGenericClass()->getClangDecl());
}
if (auto *structDecl = t->getStructOrBoundGenericStruct())
typeDecl = structDecl;
else
return false;
return getKnownTypeInfo(typeDecl, typeMapping, languageMode) != std::nullopt;
}
bool isKnownCxxType(Type t, PrimitiveTypeMapping &typeMapping) {
return isKnownType(t, typeMapping, OutputLanguageMode::Cxx);
}
bool isKnownCType(Type t, PrimitiveTypeMapping &typeMapping) {
return isKnownType(t, typeMapping, OutputLanguageMode::ObjC);
}
struct CFunctionSignatureTypePrinterModifierDelegate {
/// Prefix the initially printed value type.
std::optional<llvm::function_ref<ClangValueTypePrinter::TypeUseKind(
ClangValueTypePrinter::TypeUseKind)>>
mapValueTypeUseKind = std::nullopt;
};
class ClangTypeHandler {
public:
ClangTypeHandler(const clang::Decl *typeDecl) : typeDecl(typeDecl) {}
bool isRepresentable() const {
// We can only return trivial types, or
// types that can be moved or copied.
if (auto *record = dyn_cast<clang::CXXRecordDecl>(typeDecl)) {
return record->isTrivial() || record->hasMoveConstructor() ||
record->hasCopyConstructorWithConstParam();
}
return false;
}
void printTypeName(raw_ostream &os) const {
ClangSyntaxPrinter(os).printClangTypeReference(typeDecl);
}
static void
printGenericReturnScaffold(raw_ostream &os, StringRef templateParamName,
llvm::function_ref<void(StringRef)> bodyOfReturn) {
printReturnScaffold(nullptr, os, templateParamName, templateParamName,
bodyOfReturn);
}
void printReturnScaffold(raw_ostream &os,
llvm::function_ref<void(StringRef)> bodyOfReturn) {
std::string fullQualifiedType;
std::string typeName;
{
llvm::raw_string_ostream typeNameOS(fullQualifiedType);
printTypeName(typeNameOS);
llvm::raw_string_ostream unqualTypeNameOS(typeName);
unqualTypeNameOS << cast<clang::NamedDecl>(typeDecl)->getName();
}
printReturnScaffold(typeDecl, os, fullQualifiedType, typeName,
bodyOfReturn);
}
private:
static void
printReturnScaffold(const clang::Decl *typeDecl, raw_ostream &os,
StringRef fullQualifiedType, StringRef typeName,
llvm::function_ref<void(StringRef)> bodyOfReturn) {
os << "alignas(alignof(" << fullQualifiedType << ")) char storage[sizeof("
<< fullQualifiedType << ")];\n";
os << "auto * _Nonnull storageObjectPtr = reinterpret_cast<"
<< fullQualifiedType << " *>(storage);\n";
bodyOfReturn("storage");
os << ";\n";
if (typeDecl && cast<clang::CXXRecordDecl>(typeDecl)->isTrivial()) {
// Trivial object can be just copied and not destroyed.
os << "return *storageObjectPtr;\n";
return;
}
// Force a `std::move` on the resulting object.
os << fullQualifiedType << " result(static_cast<" << fullQualifiedType
<< " &&>(*storageObjectPtr));\n";
os << "storageObjectPtr->~" << typeName << "();\n";
os << "return result;\n";
}
const clang::Decl *typeDecl;
};
// Prints types in the C function signature that corresponds to the
// native Swift function/method.
class CFunctionSignatureTypePrinter
: public TypeVisitor<CFunctionSignatureTypePrinter, ClangRepresentation,
std::optional<OptionalTypeKind>, bool>,
private ClangSyntaxPrinter {
public:
CFunctionSignatureTypePrinter(
raw_ostream &os, raw_ostream &cPrologueOS,
PrimitiveTypeMapping &typeMapping, OutputLanguageMode languageMode,
SwiftToClangInteropContext &interopContext,
CFunctionSignatureTypePrinterModifierDelegate modifiersDelegate,
const ModuleDecl *moduleContext, DeclAndTypePrinter &declPrinter,
FunctionSignatureTypeUse typeUseKind =
FunctionSignatureTypeUse::ParamType)
: ClangSyntaxPrinter(os), cPrologueOS(cPrologueOS),
typeMapping(typeMapping), interopContext(interopContext),
languageMode(languageMode), modifiersDelegate(modifiersDelegate),
moduleContext(moduleContext), declPrinter(declPrinter),
typeUseKind(typeUseKind) {}
void printInoutTypeModifier() {
os << (languageMode == swift::OutputLanguageMode::Cxx ? " &"
: " * _Nonnull");
}
bool printIfKnownSimpleType(const TypeDecl *typeDecl,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
auto knownTypeInfo = getKnownTypeInfo(typeDecl, typeMapping, languageMode);
if (!knownTypeInfo)
return false;
bool shouldPrintOptional = optionalKind && *optionalKind != OTK_None &&
!knownTypeInfo->canBeNullable;
if (!isInOutParam && shouldPrintOptional &&
typeUseKind == FunctionSignatureTypeUse::ParamType)
os << "const ";
printOptional(shouldPrintOptional ? optionalKind : std::nullopt, [&]() {
os << knownTypeInfo->name;
if (knownTypeInfo->canBeNullable) {
printNullability(optionalKind);
}
});
if (!isInOutParam && shouldPrintOptional &&
typeUseKind == FunctionSignatureTypeUse::ParamType)
os << '&';
if (isInOutParam)
printInoutTypeModifier();
return true;
}
void printOptional(std::optional<OptionalTypeKind> optionalKind,
llvm::function_ref<void()> body) {
if (!optionalKind || optionalKind == OTK_None)
return body();
printBaseName(moduleContext->getASTContext().getStdlibModule());
os << "::Optional<";
body();
os << '>';
}
ClangRepresentation visitType(TypeBase *Ty,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
assert(Ty->getDesugaredType() == Ty && "unhandled sugared type");
os << "/* ";
Ty->print(os);
os << " */";
return ClangRepresentation::unsupported;
}
ClangRepresentation
visitTupleType(TupleType *TT, std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
if (TT->getNumElements() > 0)
// FIXME: Handle non-void type.
return ClangRepresentation::unsupported;
// FIXME: how to support `()` parameters.
if (typeUseKind != FunctionSignatureTypeUse::ReturnType)
return ClangRepresentation::unsupported;
os << "void";
return ClangRepresentation::representable;
}
ClangRepresentation
visitTypeAliasType(TypeAliasType *aliasTy,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
const TypeAliasDecl *alias = aliasTy->getDecl();
if (printIfKnownSimpleType(alias, optionalKind, isInOutParam))
return ClangRepresentation::representable;
return visitSugarType(aliasTy, optionalKind, isInOutParam);
}
ClangRepresentation
visitSugarType(SugarType *sugarTy,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return visitPart(sugarTy->getSinglyDesugaredType(), optionalKind,
isInOutParam);
}
ClangRepresentation
visitClassType(ClassType *CT, std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
auto *cd = CT->getDecl();
if (cd->hasClangNode()) {
ClangSyntaxPrinter(os).printClangTypeReference(cd->getClangDecl());
os << " *"
<< (!optionalKind || *optionalKind == OTK_None ? "_Nonnull"
: "_Nullable");
if (isInOutParam) {
if (isa<clang::ObjCContainerDecl>(cd->getClangDecl()))
os << " __strong";
printInoutTypeModifier();
}
if (isa<clang::CXXRecordDecl>(cd->getClangDecl())) {
if (std::find_if(
cd->getClangDecl()->getAttrs().begin(),
cd->getClangDecl()->getAttrs().end(), [](clang::Attr *attr) {
if (auto *sa = dyn_cast<clang::SwiftAttrAttr>(attr)) {
llvm::StringRef value = sa->getAttribute();
if ((value.startswith("retain:") ||
value.startswith("release:")) &&
!value.endswith(":immortal"))
return true;
}
return false;
}) != cd->getClangDecl()->getAttrs().end()) {
// This is a shared FRT. Do not bridge it back to
// C++ as its ownership is not managed automatically
// in C++ yet.
return ClangRepresentation::unsupported;
}
}
// FIXME: Mark that this is only ObjC representable.
return ClangRepresentation::representable;
}
// FIXME: handle optionalKind.
if (languageMode != OutputLanguageMode::Cxx) {
os << "void * "
<< (!optionalKind || *optionalKind == OTK_None ? "_Nonnull"
: "_Nullable");
if (isInOutParam)
os << " * _Nonnull";
return ClangRepresentation::representable;
}
if (typeUseKind == FunctionSignatureTypeUse::ParamType && !isInOutParam)
os << "const ";
printOptional(optionalKind, [&]() {
ClangSyntaxPrinter(os).printBaseName(CT->getDecl());
});
if (typeUseKind == FunctionSignatureTypeUse::ParamType)
os << "&";
return ClangRepresentation::representable;
}
ClangRepresentation
visitEnumType(EnumType *ET, std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return visitValueType(ET, ET->getNominalOrBoundGenericNominal(),
optionalKind, isInOutParam);
}
ClangRepresentation
visitStructType(StructType *ST, std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return visitValueType(ST, ST->getNominalOrBoundGenericNominal(),
optionalKind, isInOutParam);
}
ClangRepresentation visitGenericArgs(ArrayRef<Type> genericArgs) {
if (genericArgs.empty())
return ClangRepresentation::representable;
os << '<';
llvm::SaveAndRestore<FunctionSignatureTypeUse> typeUseNormal(
typeUseKind, FunctionSignatureTypeUse::TypeReference);
decltype(modifiersDelegate) emptyModifiersDelegate;
llvm::SaveAndRestore<decltype(modifiersDelegate)> modReset(
modifiersDelegate, emptyModifiersDelegate);
ClangRepresentation result = ClangRepresentation::representable;
llvm::interleaveComma(genericArgs, os, [&](Type t) {
result.merge(visitPart(t, std::nullopt, false));
});
os << '>';
return result;
}
ClangRepresentation
visitValueType(TypeBase *type, const NominalTypeDecl *decl,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam, ArrayRef<Type> genericArgs = {}) {
assert(isa<StructDecl>(decl) || isa<EnumDecl>(decl));
// Handle known type names.
if (printIfKnownSimpleType(decl, optionalKind, isInOutParam))
return ClangRepresentation::representable;
if (!declPrinter.shouldInclude(decl))
return ClangRepresentation::unsupported; // FIXME: propagate why it's not
// exposed.
// Only C++ mode supports struct types.
if (languageMode != OutputLanguageMode::Cxx)
return ClangRepresentation::unsupported;
if (decl->hasClangNode()) {
ClangTypeHandler handler(decl->getClangDecl());
if (!handler.isRepresentable())
return ClangRepresentation::unsupported;
if (typeUseKind == FunctionSignatureTypeUse::ParamType &&
!isInOutParam)
os << "const ";
printOptional(optionalKind, [&]() { handler.printTypeName(os); });
if (typeUseKind == FunctionSignatureTypeUse::ParamType)
os << '&';
return ClangRepresentation::representable;
}
if (typeUseKind == FunctionSignatureTypeUse::ParamType) {
if (!isInOutParam) {
os << "const ";
}
ClangRepresentation result = ClangRepresentation::representable;
printOptional(optionalKind, [&]() {
ClangSyntaxPrinter(os).printPrimaryCxxTypeName(decl, moduleContext);
result = visitGenericArgs(genericArgs);
});
os << '&';
return result;
}
ClangRepresentation result = ClangRepresentation::representable;
printOptional(optionalKind, [&]() {
ClangValueTypePrinter printer(os, cPrologueOS, interopContext);
printer.printValueTypeReturnType(
decl, languageMode,
modifiersDelegate.mapValueTypeUseKind
? (*modifiersDelegate.mapValueTypeUseKind)(
ClangValueTypePrinter::TypeUseKind::CxxTypeName)
: ClangValueTypePrinter::TypeUseKind::CxxTypeName,
moduleContext);
result = visitGenericArgs(genericArgs);
});
return result;
}
std::optional<ClangRepresentation>
printIfKnownGenericStruct(const BoundGenericStructType *BGT,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
auto bgsTy = Type(const_cast<BoundGenericStructType *>(BGT));
bool isConst;
if (bgsTy->isUnsafePointer())
isConst = true;
else if (bgsTy->isUnsafeMutablePointer())
isConst = false;
else
return std::nullopt;
auto args = BGT->getGenericArgs();
assert(args.size() == 1);
llvm::SaveAndRestore<FunctionSignatureTypeUse> typeUseNormal(
typeUseKind, FunctionSignatureTypeUse::TypeReference);
// FIXME: We can definitely support pointers to known Clang types.
if (!isKnownCType(args.front(), typeMapping))
return ClangRepresentation(ClangRepresentation::unsupported);
auto partRepr = visitPart(args.front(), OTK_None, /*isInOutParam=*/false);
if (partRepr.isUnsupported())
return partRepr;
if (isConst)
os << " const";
os << " *";
printNullability(optionalKind);
if (isInOutParam)
printInoutTypeModifier();
return ClangRepresentation(ClangRepresentation::representable);
}
ClangRepresentation
visitBoundGenericStructType(BoundGenericStructType *BGT,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
if (auto result =
printIfKnownGenericStruct(BGT, optionalKind, isInOutParam))
return *result;
return visitValueType(BGT, BGT->getDecl(), optionalKind, isInOutParam,
BGT->getGenericArgs());
}
ClangRepresentation
visitBoundGenericEnumType(BoundGenericEnumType *BGT,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return visitValueType(BGT, BGT->getDecl(), optionalKind, isInOutParam,
BGT->getGenericArgs());
}
ClangRepresentation
visitGenericTypeParamType(GenericTypeParamType *genericTpt,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
bool isParam = typeUseKind == FunctionSignatureTypeUse::ParamType;
if (isParam && !isInOutParam)
os << "const ";
if (languageMode != OutputLanguageMode::Cxx) {
// Note: This can happen for UnsafeMutablePointer<T>.
if (typeUseKind != FunctionSignatureTypeUse::ParamType)
return ClangRepresentation::unsupported;
assert(typeUseKind == FunctionSignatureTypeUse::ParamType);
// Pass an opaque param in C mode.
os << "void * _Nonnull";
return ClangRepresentation::representable;
}
printOptional(optionalKind, [&]() {
ClangSyntaxPrinter(os).printGenericTypeParamTypeName(genericTpt);
});
// Pass a reference to the template type.
if (isParam)
os << '&';
return ClangRepresentation::representable;
}
ClangRepresentation
visitDynamicSelfType(DynamicSelfType *ds,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return visitPart(ds->getSelfType(), optionalKind, isInOutParam);
}
ClangRepresentation
visitMetatypeType(MetatypeType *mt,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
if (typeUseKind == FunctionSignatureTypeUse::TypeReference)
return visitPart(mt->getInstanceType(), optionalKind, isInOutParam);
return ClangRepresentation::unsupported;
}
ClangRepresentation visitPart(Type Ty,
std::optional<OptionalTypeKind> optionalKind,
bool isInOutParam) {
return TypeVisitor::visit(Ty, optionalKind, isInOutParam);
}
private:
raw_ostream &cPrologueOS;
PrimitiveTypeMapping &typeMapping;
SwiftToClangInteropContext &interopContext;
OutputLanguageMode languageMode;
CFunctionSignatureTypePrinterModifierDelegate modifiersDelegate;
const ModuleDecl *moduleContext;
DeclAndTypePrinter &declPrinter;
FunctionSignatureTypeUse typeUseKind;
};
} // end namespace
ClangRepresentation
DeclAndTypeClangFunctionPrinter::printClangFunctionReturnType(
Type ty, OptionalTypeKind optKind, ModuleDecl *moduleContext,
OutputLanguageMode outputLang) {
CFunctionSignatureTypePrinter typePrinter(
os, cPrologueOS, typeMapping, outputLang, interopContext,
CFunctionSignatureTypePrinterModifierDelegate(), moduleContext,
declPrinter, FunctionSignatureTypeUse::ReturnType);
// Param for indirect return cannot be marked as inout
return typePrinter.visit(ty, optKind, /*isInOutParam=*/false);
}
static void addABIRecordToTypeEncoding(llvm::raw_ostream &typeEncodingOS,
clang::CharUnits offset,
clang::CharUnits end, Type t,
PrimitiveTypeMapping &typeMapping) {
auto info =
typeMapping.getKnownCTypeInfo(t->getNominalOrBoundGenericNominal());
assert(info);
typeEncodingOS << '_';
for (char c : info->name) {
if (c == ' ')
typeEncodingOS << '_';
else if (c == '*')
typeEncodingOS << "ptr";
else
typeEncodingOS << c;
}
// Express the offset and end in terms of target word size.
// This ensures that tests are able to use the stub struct name in target
// independent manner.
auto emitUnit = [&](const clang::CharUnits &unit) {
typeEncodingOS << '_' << unit.getQuantity();
};
emitUnit(offset);
emitUnit(end);
}
template <class T>
static std::string encodeTypeInfo(const T &abiTypeInfo,
const ModuleDecl *moduleContext,
PrimitiveTypeMapping &typeMapping) {
std::string typeEncoding;
llvm::raw_string_ostream typeEncodingOS(typeEncoding);
ClangSyntaxPrinter(typeEncodingOS).printBaseName(moduleContext);
abiTypeInfo.enumerateRecordMembers(
[&](clang::CharUnits offset, clang::CharUnits end, Type t) {
addABIRecordToTypeEncoding(typeEncodingOS, offset, end, t, typeMapping);
});
return std::move(typeEncodingOS.str());
}
// Returns false if the given direct type is not yet supported because
// of its ABI.
template <class T>
static bool printDirectReturnOrParamCType(
const T &abiTypeInfo, Type valueType, const ModuleDecl *emittedModule,
raw_ostream &os, raw_ostream &cPrologueOS,
PrimitiveTypeMapping &typeMapping,
SwiftToClangInteropContext &interopContext,
llvm::function_ref<void()> prettifiedValuePrinter) {
const bool isResultType =
std::is_same<T, LoweredFunctionSignature::DirectResultType>::value;
StringRef stubTypeName =
isResultType ? "swift_interop_returnStub_" : "swift_interop_passStub_";
std::string typeEncoding;
llvm::raw_string_ostream typeEncodingOS(typeEncoding);
typeEncodingOS << stubTypeName;
ClangSyntaxPrinter(typeEncodingOS).printBaseName(emittedModule);
unsigned Count = 0;
clang::CharUnits lastOffset;
if (abiTypeInfo.enumerateRecordMembers([&](clang::CharUnits offset,
clang::CharUnits end, Type t) {
lastOffset = offset;
++Count;
addABIRecordToTypeEncoding(typeEncodingOS, offset, end, t, typeMapping);
}))
return false;
assert(Count > 0 && "missing return values");
// FIXME: is this "prettyfying" logic sound for multiple return values?
if (isKnownCType(valueType, typeMapping) ||
(Count == 1 && lastOffset.isZero() && !valueType->hasTypeParameter() &&
valueType->isAnyClassReferenceType())) {
prettifiedValuePrinter();
return true;
}
os << "struct " << typeEncodingOS.str();
llvm::SmallVector<std::pair<clang::CharUnits, clang::CharUnits>, 8> fields;
auto printStub = [&](raw_ostream &os, StringRef stubName) {
// Print out a C stub for this value type.
os << "// Stub struct to be used to pass/return values to/from Swift "
"functions.\n";
os << "struct " << stubName << " {\n";
abiTypeInfo.enumerateRecordMembers([&](clang::CharUnits offset,
clang::CharUnits end, Type t) {
auto info =
typeMapping.getKnownCTypeInfo(t->getNominalOrBoundGenericNominal());
os << " " << info->name;
if (info->canBeNullable)
os << " _Nullable";
os << " _" << (fields.size() + 1) << ";\n";
fields.push_back(std::make_pair(offset, end));
});
os << "};\n\n";
auto minimalStubName = stubName;
minimalStubName.consume_front(stubTypeName);
if (isResultType) {
// Emit a stub that returns a value directly from swiftcc function.
os << "static SWIFT_C_INLINE_THUNK void swift_interop_returnDirect_"
<< minimalStubName;
os << "(char * _Nonnull result, struct " << stubName << " value";
os << ") {\n";
for (size_t i = 0; i < fields.size(); ++i) {
os << " memcpy(result + " << fields[i].first.getQuantity() << ", "
<< "&value._" << (i + 1) << ", "
<< (fields[i].second - fields[i].first).getQuantity() << ");\n";
}
} else {
// Emit a stub that is used to pass value type directly to swiftcc
// function.
os << "static SWIFT_C_INLINE_THUNK struct " << stubName
<< " swift_interop_passDirect_" << minimalStubName;
os << "(const char * _Nonnull value) {\n";
os << " struct " << stubName << " result;\n";
for (size_t i = 0; i < fields.size(); ++i) {
os << " memcpy(&result._" << (i + 1) << ", value + "
<< fields[i].first.getQuantity() << ", "
<< (fields[i].second - fields[i].first).getQuantity() << ");\n";
}
os << " return result;\n";
}
os << "}\n\n";
};
interopContext.runIfStubForDeclNotEmitted(typeEncodingOS.str(), [&]() {
printStub(cPrologueOS, typeEncodingOS.str());
});
return true;
}
/// Make adjustments to the Swift parameter name in generated C++, to
/// avoid things like additional warnings.
static void renameCxxParameterIfNeeded(const AbstractFunctionDecl *FD,
std::string ¶mName) {
if (paramName.empty())
return;
const auto *enumDecl = FD->getDeclContext()->getSelfEnumDecl();
if (!enumDecl)
return;
// Rename a parameter in an enum method that shadows an existing case name,
// to avoid a -Wshadow warning in Clang.
for (const auto *Case : enumDecl->getAllElements()) {
if (Case->getNameStr() == paramName) {
paramName = (llvm::Twine(paramName) + "_").str();
return;
}
}
}
ClangRepresentation DeclAndTypeClangFunctionPrinter::printFunctionSignature(
const AbstractFunctionDecl *FD, const LoweredFunctionSignature &signature,
StringRef name, Type resultTy, FunctionSignatureKind kind,
FunctionSignatureModifiers modifiers) {
// Print any template and requires clauses for the
// C++ class context to which this C++ member will belong to.
if (const auto *typeDecl = modifiers.qualifierContext) {
assert(kind == FunctionSignatureKind::CxxInlineThunk);
ClangSyntaxPrinter(os).printNominalTypeOutsideMemberDeclTemplateSpecifiers(
typeDecl);
}
if (FD->isGeneric()) {
auto Signature = FD->getGenericSignature().getCanonicalSignature();
if (!cxx_translation::isExposableToCxx(Signature))
return ClangRepresentation::unsupported;
// Print the template and requires clauses for this function.
if (kind == FunctionSignatureKind::CxxInlineThunk)
ClangSyntaxPrinter(os).printGenericSignature(Signature);
}
auto emittedModule = FD->getModuleContext();
OutputLanguageMode outputLang = kind == FunctionSignatureKind::CFunctionProto
? OutputLanguageMode::ObjC
: OutputLanguageMode::Cxx;
// FIXME: Might need a PrintMultiPartType here.
auto print =
[&, this](Type ty, std::optional<OptionalTypeKind> optionalKind,
StringRef name, bool isInOutParam,
CFunctionSignatureTypePrinterModifierDelegate delegate = {})
-> ClangRepresentation {
// FIXME: add support for noescape and PrintMultiPartType,
// see DeclAndTypePrinter::print.
CFunctionSignatureTypePrinter typePrinter(
os, cPrologueOS, typeMapping, outputLang, interopContext, delegate,
emittedModule, declPrinter);
auto result = typePrinter.visit(ty, optionalKind, isInOutParam);
if (!name.empty()) {
os << ' ';
ClangSyntaxPrinter(os).printIdentifier(name);
}
return result;
};
// Print any modifiers before the signature.
if (modifiers.isStatic) {
assert(!modifiers.isConst);
os << "static ";
}
if (modifiers.isInline)
ClangSyntaxPrinter(os).printInlineForThunk();
ClangRepresentation resultingRepresentation =
ClangRepresentation::representable;
// Print out the return type.
if (FD->hasThrows() && outputLang == OutputLanguageMode::Cxx)
os << "swift::ThrowingResult<";
if (kind == FunctionSignatureKind::CFunctionProto) {
// First, verify that the C++ return type is representable.
{
OptionalTypeKind optKind;
Type objTy;
std::tie(objTy, optKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(FD, resultTy);
CFunctionSignatureTypePrinter typePrinter(
llvm::nulls(), llvm::nulls(), typeMapping, OutputLanguageMode::Cxx,
interopContext, CFunctionSignatureTypePrinterModifierDelegate(),
emittedModule, declPrinter, FunctionSignatureTypeUse::ReturnType);
if (resultingRepresentation
.merge(typePrinter.visit(objTy, optKind, /*isInOutParam=*/false))
.isUnsupported())
return resultingRepresentation;
}
auto directResultType = signature.getDirectResultType();
// FIXME: support direct + indirect results.
if (directResultType && signature.getNumIndirectResultValues() > 0)
return ClangRepresentation::unsupported;
// FIXME: support multiple indirect results.
if (signature.getNumIndirectResultValues() > 1)
return ClangRepresentation::unsupported;
if (!directResultType) {
os << "void";
} else {
if (!printDirectReturnOrParamCType(
*directResultType, resultTy, emittedModule, os, cPrologueOS,
typeMapping, interopContext, [&]() {
OptionalTypeKind retKind;
Type objTy;
std::tie(objTy, retKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(FD,
resultTy);
auto s = printClangFunctionReturnType(
objTy, retKind, emittedModule, outputLang);
assert(!s.isUnsupported());
}))
return ClangRepresentation::unsupported;
}
} else {
OptionalTypeKind retKind;
Type objTy;
std::tie(objTy, retKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(FD, resultTy);
if (resultingRepresentation
.merge(printClangFunctionReturnType(objTy, retKind, emittedModule,
outputLang))
.isUnsupported())
return resultingRepresentation;
}
if (FD->hasThrows() && outputLang == OutputLanguageMode::Cxx)
os << ">";
os << ' ';
if (const auto *typeDecl = modifiers.qualifierContext)
ClangSyntaxPrinter(os).printNominalTypeQualifier(
typeDecl, typeDecl->getModuleContext());
ClangSyntaxPrinter(os).printIdentifier(name);
os << '(';
bool HasParams = false;
if (kind == FunctionSignatureKind::CFunctionProto) {
// First, verify that the C++ param types are representable.
for (auto param : *FD->getParameters()) {
OptionalTypeKind optKind;
Type objTy;
std::tie(objTy, optKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(
FD, param->getInterfaceType());
CFunctionSignatureTypePrinter typePrinter(
llvm::nulls(), llvm::nulls(), typeMapping, OutputLanguageMode::Cxx,
interopContext, CFunctionSignatureTypePrinterModifierDelegate(),
emittedModule, declPrinter, FunctionSignatureTypeUse::ParamType);
if (resultingRepresentation
.merge(typePrinter.visit(objTy, optKind,
/*isInOutParam=*/param->isInOut()))
.isUnsupported())
return resultingRepresentation;
}
bool needsComma = false;
auto emitNewParam = [&]() {
if (needsComma)
os << ", ";
needsComma = true;
};
auto printParamName = [&](const ParamDecl ¶m) {
std::string paramName =
param.getName().empty() ? "" : param.getName().str().str();
if (param.isSelfParameter())
paramName = "_self";
if (!paramName.empty()) {
os << ' ';
ClangSyntaxPrinter(os).printIdentifier(paramName);
}
};
auto printParamCType = [&](const ParamDecl ¶m) {
OptionalTypeKind optionalKind;
Type ty;
std::tie(ty, optionalKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(
¶m, param.getInterfaceType());
CFunctionSignatureTypePrinter typePrinter(
os, cPrologueOS, typeMapping, outputLang, interopContext,
CFunctionSignatureTypePrinterModifierDelegate(), emittedModule,
declPrinter);
auto s = typePrinter.visit(ty, optionalKind, param.isInOut());
assert(!s.isUnsupported());
};
signature.visitParameterList(
[&](const LoweredFunctionSignature::IndirectResultValue
&indirectResult) {
emitNewParam();
if (indirectResult.hasSRet())
os << "SWIFT_INDIRECT_RESULT ";
// FIXME: it would be nice to print out the C struct type here.
os << "void * _Nonnull";
},
[&](const LoweredFunctionSignature::DirectParameter ¶m) {
emitNewParam();
printDirectReturnOrParamCType(
param, param.getParamDecl().getInterfaceType(), emittedModule, os,
cPrologueOS, typeMapping, interopContext,
[&]() { printParamCType(param.getParamDecl()); });
printParamName(param.getParamDecl());
},
[&](const LoweredFunctionSignature::IndirectParameter ¶m) {
emitNewParam();
if (param.getParamDecl().isSelfParameter())
os << "SWIFT_CONTEXT ";
bool isConst =
!param.getParamDecl().isInOut() &&
!(param.getParamDecl().isSelfParameter() &&
!param.getParamDecl().getInterfaceType()->hasTypeParameter() &&
param.getParamDecl()
.getInterfaceType()
->isAnyClassReferenceType());
if (isConst)
os << "const ";
if (isKnownCType(param.getParamDecl().getInterfaceType(),
typeMapping) ||
(!param.getParamDecl().getInterfaceType()->hasTypeParameter() &&
param.getParamDecl()
.getInterfaceType()
->isAnyClassReferenceType()))
printParamCType(param.getParamDecl());
else
os << "void * _Nonnull";
printParamName(param.getParamDecl());
},
[&](const LoweredFunctionSignature::GenericRequirementParameter
&genericRequirementParam) {
emitNewParam();
os << "void * _Nonnull ";
auto reqt = genericRequirementParam.getRequirement();
if (reqt.isAnyWitnessTable())
ClangSyntaxPrinter(os).printBaseName(reqt.getProtocol());
else
assert(reqt.isAnyMetadata());
},
[&](const LoweredFunctionSignature::MetadataSourceParameter
&metadataSrcParam) {
emitNewParam();
os << "void * _Nonnull ";
},
[&](const LoweredFunctionSignature::ContextParameter &) {
emitNewParam();
os << "SWIFT_CONTEXT void * _Nonnull _ctx";
},
[&](const LoweredFunctionSignature::ErrorResultValue &) {
emitNewParam();
os << "SWIFT_ERROR_RESULT void * _Nullable * _Nullable _error";
});
if (needsComma == false)
// Emit 'void' in an empty parameter list for C function declarations.
os << "void";
os << ')';
return resultingRepresentation;
}
// Print out the C++ parameter types.
auto params = FD->getParameters();
if (params->size()) {
if (HasParams)
os << ", ";
HasParams = true;
size_t paramIndex = 1;
llvm::interleaveComma(*params, os, [&](const ParamDecl *param) {
OptionalTypeKind argKind;
Type objTy;
std::tie(objTy, argKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(
param, param->getInterfaceType());
std::string paramName =
param->getName().empty() ? "" : param->getName().str().str();
renameCxxParameterIfNeeded(FD, paramName);
// Always emit a named parameter for the C++ inline thunk to ensure it
// can be referenced in the body.
if (kind == FunctionSignatureKind::CxxInlineThunk && paramName.empty()) {
llvm::raw_string_ostream os(paramName);
os << "_" << paramIndex;
}
resultingRepresentation.merge(
print(objTy, argKind, paramName, param->isInOut()));
++paramIndex;
});
if (resultingRepresentation.isUnsupported())
return resultingRepresentation;
}
os << ')';
if (modifiers.isConst)
os << " const";
if (modifiers.isNoexcept)
os << " noexcept";
if (modifiers.hasSymbolUSR)
ClangSyntaxPrinter(os).printSymbolUSRAttribute(
modifiers.symbolUSROverride ? modifiers.symbolUSROverride : FD);
return resultingRepresentation;
}
void DeclAndTypeClangFunctionPrinter::printTypeImplTypeSpecifier(
Type type, const ModuleDecl *moduleContext) {
CFunctionSignatureTypePrinterModifierDelegate delegate;
delegate.mapValueTypeUseKind = [](ClangValueTypePrinter::TypeUseKind kind) {
return ClangValueTypePrinter::TypeUseKind::CxxImplTypeName;
};
CFunctionSignatureTypePrinter typePrinter(
os, cPrologueOS, typeMapping, OutputLanguageMode::Cxx, interopContext,
delegate, moduleContext, declPrinter,
FunctionSignatureTypeUse::TypeReference);
auto result = typePrinter.visit(type, std::nullopt, /*isInOut=*/false);
assert(!result.isUnsupported());
}
void DeclAndTypeClangFunctionPrinter::printCxxToCFunctionParameterUse(
Type type, StringRef name, const ModuleDecl *moduleContext, bool isInOut,
bool isIndirect, std::string directTypeEncoding, bool forceSelf) {
auto namePrinter = [&]() { ClangSyntaxPrinter(os).printIdentifier(name); };
if (!isKnownCxxType(type, typeMapping) &&
!hasKnownOptionalNullableCxxMapping(type)) {
if (type->is<GenericTypeParamType>()) {
os << "swift::" << cxx_synthesis::getCxxImplNamespaceName()
<< "::getOpaquePointer(";
namePrinter();
os << ')';
return;
}
if (auto *classDecl = type->getClassOrBoundGenericClass()) {