-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenCall.cpp
6999 lines (6116 loc) · 265 KB
/
GenCall.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
//===--- GenCall.cpp - Swift IR Generation for Function Calls -------------===//
//
// 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 generation for function signature lowering
// in Swift. This includes creating the IR type, collecting IR attributes,
// performing calls, and supporting prologue and epilogue emission.
//
//===----------------------------------------------------------------------===//
#include "swift/ABI/Coro.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/Basic/Assertions.h"
#include "swift/IRGen/Linking.h"
#include "swift/Runtime/Config.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Sema/Sema.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalPtrAuthInfo.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/Support/Compiler.h"
#include <optional>
#include "CallEmission.h"
#include "EntryPointArgumentEmission.h"
#include "Explosion.h"
#include "GenCall.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenKeyPath.h"
#include "GenObjC.h"
#include "GenPointerAuth.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "IRGenMangler.h"
#include "LoadableTypeInfo.h"
#include "NativeConventionSchema.h"
#include "Signature.h"
#include "StructLayout.h"
using namespace swift;
using namespace irgen;
static Size getYieldOnceCoroutineBufferSize(IRGenModule &IGM) {
return NumWords_YieldOnceBuffer * IGM.getPointerSize();
}
static Alignment getYieldOnceCoroutineBufferAlignment(IRGenModule &IGM) {
return IGM.getPointerAlignment();
}
static Size getYieldManyCoroutineBufferSize(IRGenModule &IGM) {
return NumWords_YieldManyBuffer * IGM.getPointerSize();
}
static Alignment getYieldManyCoroutineBufferAlignment(IRGenModule &IGM) {
return IGM.getPointerAlignment();
}
static std::optional<Size> getCoroutineContextSize(IRGenModule &IGM,
CanSILFunctionType fnType) {
switch (fnType->getCoroutineKind()) {
case SILCoroutineKind::None:
llvm_unreachable("expand a coroutine");
case SILCoroutineKind::YieldOnce2:
return std::nullopt;
case SILCoroutineKind::YieldOnce:
return getYieldOnceCoroutineBufferSize(IGM);
case SILCoroutineKind::YieldMany:
return getYieldManyCoroutineBufferSize(IGM);
}
llvm_unreachable("bad kind");
}
AsyncContextLayout irgen::getAsyncContextLayout(IRGenModule &IGM,
SILFunction *function) {
SubstitutionMap forwardingSubstitutionMap =
function->getForwardingSubstitutionMap();
CanSILFunctionType originalType = function->getLoweredFunctionType();
CanSILFunctionType substitutedType = originalType->substGenericArgs(
IGM.getSILModule(), forwardingSubstitutionMap,
IGM.getMaximalTypeExpansionContext());
auto layout = getAsyncContextLayout(
IGM, originalType, substitutedType, forwardingSubstitutionMap);
return layout;
}
static Size getAsyncContextHeaderSize(IRGenModule &IGM) {
return 2 * IGM.getPointerSize();
}
AsyncContextLayout irgen::getAsyncContextLayout(
IRGenModule &IGM, CanSILFunctionType originalType,
CanSILFunctionType substitutedType, SubstitutionMap substitutionMap) {
// FIXME: everything about this type is way more complicated than it
// needs to be now that we no longer pass and return things in memory
// in the async context and therefore the layout is totally static.
SmallVector<const TypeInfo *, 4> typeInfos;
SmallVector<SILType, 4> valTypes;
// AsyncContext * __ptrauth_swift_async_context_parent Parent;
{
auto ty = SILType();
auto &ti = IGM.getSwiftContextPtrTypeInfo();
valTypes.push_back(ty);
typeInfos.push_back(&ti);
}
// TaskContinuationFunction * __ptrauth_swift_async_context_resume
// ResumeParent;
{
auto ty = SILType();
auto &ti = IGM.getTaskContinuationFunctionPtrTypeInfo();
valTypes.push_back(ty);
typeInfos.push_back(&ti);
}
return AsyncContextLayout(IGM, LayoutStrategy::Optimal, valTypes, typeInfos,
originalType, substitutedType, substitutionMap);
}
AsyncContextLayout::AsyncContextLayout(
IRGenModule &IGM, LayoutStrategy strategy, ArrayRef<SILType> fieldTypes,
ArrayRef<const TypeInfo *> fieldTypeInfos, CanSILFunctionType originalType,
CanSILFunctionType substitutedType, SubstitutionMap substitutionMap)
: StructLayout(IGM, /*type=*/std::nullopt, LayoutKind::NonHeapObject,
strategy, fieldTypeInfos, /*typeToFill*/ nullptr),
originalType(originalType), substitutedType(substitutedType),
substitutionMap(substitutionMap) {
assert(fieldTypeInfos.size() == fieldTypes.size() &&
"type infos don't match types");
assert(this->isFixedLayout());
assert(this->getSize() == getAsyncContextHeaderSize(IGM));
}
Alignment IRGenModule::getAsyncContextAlignment() const {
return Alignment(MaximumAlignment);
}
Alignment IRGenModule::getCoroStaticFrameAlignment() const {
return Alignment(MaximumAlignment);
}
std::optional<Size>
FunctionPointerKind::getStaticAsyncContextSize(IRGenModule &IGM) const {
if (!isSpecial())
return std::nullopt;
auto headerSize = getAsyncContextHeaderSize(IGM);
headerSize = headerSize.roundUpToAlignment(IGM.getPointerAlignment());
switch (getSpecialKind()) {
case SpecialKind::TaskFutureWaitThrowing:
case SpecialKind::TaskFutureWait:
case SpecialKind::AsyncLetWait:
case SpecialKind::AsyncLetWaitThrowing:
case SpecialKind::AsyncLetGet:
case SpecialKind::AsyncLetGetThrowing:
case SpecialKind::AsyncLetFinish:
case SpecialKind::TaskGroupWaitNext:
case SpecialKind::TaskGroupWaitAll:
case SpecialKind::DistributedExecuteTarget:
// The current guarantee for all of these functions is the same.
// See TaskFutureWaitAsyncContext.
//
// If you add a new special runtime function, it is highly recommended
// that you make calls to it allocate a little more memory than this!
// These frames being this small is very arguably a mistake.
return headerSize + 3 * IGM.getPointerSize();
case SpecialKind::KeyPathAccessor:
return std::nullopt;
}
llvm_unreachable("covered switch");
}
void IRGenFunction::setupAsync(unsigned asyncContextIndex) {
llvm::Value *c = CurFn->getArg(asyncContextIndex);
asyncContextLocation = createAlloca(c->getType(), IGM.getPointerAlignment());
IRBuilder builder(IGM.getLLVMContext(), IGM.DebugInfo != nullptr);
// Insert the stores after the coro.begin.
builder.SetInsertPoint(getEarliestInsertionPoint()->getParent(),
getEarliestInsertionPoint()->getIterator());
builder.CreateStore(c, asyncContextLocation);
}
std::optional<CoroAllocatorKind>
IRGenFunction::getDefaultCoroutineAllocatorKind() {
if (isCalleeAllocatedCoroutine()) {
// This is a yield_once_2 coroutine. It has no default kind.
return std::nullopt;
}
if (isAsync()) {
return CoroAllocatorKind::Async;
}
if (isCoroutine()) {
return CoroAllocatorKind::Malloc;
}
if (IGM.SwiftCoroCC != llvm::CallingConv::SwiftCoro) {
// If the swiftcorocc isn't available, fall back to malloc.
return CoroAllocatorKind::Malloc;
}
return CoroAllocatorKind::Stack;
}
llvm::Value *IRGenFunction::getAsyncTask() {
auto call = Builder.CreateCall(IGM.getGetCurrentTaskFunctionPointer(), {});
call->setDoesNotThrow();
call->setCallingConv(IGM.SwiftCC);
return call;
}
llvm::Value *IRGenFunction::getAsyncContext() {
assert(isAsync());
return Builder.CreateLoad(asyncContextLocation);
}
void IRGenFunction::storeCurrentAsyncContext(llvm::Value *context) {
context = Builder.CreateBitCast(context, IGM.SwiftContextPtrTy);
Builder.CreateStore(context, asyncContextLocation);
}
llvm::CallInst *IRGenFunction::emitSuspendAsyncCall(
unsigned asyncContextIndex, llvm::StructType *resultTy,
ArrayRef<llvm::Value *> args, bool restoreCurrentContext) {
auto *id = Builder.CreateIntrinsicCall(llvm::Intrinsic::coro_suspend_async,
{resultTy}, args);
if (restoreCurrentContext) {
// This is setup code after the split point. Don't associate any line
// numbers to it.
irgen::PrologueLocation LocRAII(IGM.DebugInfo.get(), Builder);
llvm::Value *calleeContext =
Builder.CreateExtractValue(id, asyncContextIndex);
calleeContext =
Builder.CreateBitOrPointerCast(calleeContext, IGM.Int8PtrTy);
llvm::Function *projectFn = cast<llvm::Function>(
(cast<llvm::Constant>(args[2])->stripPointerCasts()));
auto *fnTy = projectFn->getFunctionType();
llvm::Value *context =
Builder.CreateCallWithoutDbgLoc(fnTy, projectFn, {calleeContext});
storeCurrentAsyncContext(context);
}
return id;
}
llvm::Type *ExplosionSchema::getScalarResultType(IRGenModule &IGM) const {
if (size() == 0) {
return IGM.VoidTy;
} else if (size() == 1) {
return begin()->getScalarType();
} else {
SmallVector<llvm::Type*, 16> elts;
for (auto &elt : *this) elts.push_back(elt.getScalarType());
return llvm::StructType::get(IGM.getLLVMContext(), elts);
}
}
static void addDereferenceableAttributeToBuilder(IRGenModule &IGM,
llvm::AttrBuilder &b,
const TypeInfo &ti) {
// The addresses of empty values are undefined, so we can't safely mark them
// dereferenceable.
if (ti.isKnownEmpty(ResilienceExpansion::Maximal))
return;
// If we know the type to have a fixed nonempty size, then the pointer is
// dereferenceable to at least that size.
// TODO: Would be nice to have a "getMinimumKnownSize" on TypeInfo for
// dynamic-layout aggregates.
if (auto fixedTI = dyn_cast<FixedTypeInfo>(&ti)) {
b.addAttribute(
llvm::Attribute::getWithDereferenceableBytes(IGM.getLLVMContext(),
fixedTI->getFixedSize().getValue()));
}
}
static void addIndirectValueParameterAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
const TypeInfo &ti,
unsigned argIndex) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Value parameter pointers can't alias or be captured.
b.addAttribute(llvm::Attribute::NoAlias);
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (ti.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
// The parameter must reference dereferenceable memory of the type.
addDereferenceableAttributeToBuilder(IGM, b, ti);
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static void addPackParameterAttributes(IRGenModule &IGM,
SILType paramSILType,
llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Pack parameter pointers can't alias.
// Note: they are not marked `nocapture` as one
// pack parameter could be a value type (e.g. a C++ type)
// that captures its own pointer in itself.
b.addAttribute(llvm::Attribute::NoAlias);
// TODO: we could mark this dereferenceable when the pack has fixed
// components.
// TODO: add an alignment attribute
// TODO: add a nonnull attribute
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static void addInoutParameterAttributes(IRGenModule &IGM, SILType paramSILType,
llvm::AttributeList &attrs,
const TypeInfo &ti, unsigned argIndex,
bool aliasable) {
llvm::AttrBuilder b(IGM.getLLVMContext());
// Thanks to exclusivity checking, it is not possible to alias inouts except
// those that are inout_aliasable.
if (!aliasable && paramSILType.getASTType()->getAnyPointerElementType()) {
// To ward against issues with LLVM's alias analysis, for now, only add the
// attribute if it's a pointer being passed inout.
b.addAttribute(llvm::Attribute::NoAlias);
}
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (ti.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
// The inout must reference dereferenceable memory of the type.
addDereferenceableAttributeToBuilder(IGM, b, ti);
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static llvm::CallingConv::ID getFreestandingConvention(IRGenModule &IGM) {
// TODO: use a custom CC that returns three scalars efficiently
return IGM.SwiftCC;
}
/// Expand the requirements of the given abstract calling convention
/// into a "physical" calling convention.
llvm::CallingConv::ID
irgen::expandCallingConv(IRGenModule &IGM,
SILFunctionTypeRepresentation convention, bool isAsync,
bool isCalleeAllocatedCoro) {
switch (convention) {
case SILFunctionTypeRepresentation::CFunctionPointer:
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::Block:
return IGM.getOptions().PlatformCCallingConvention;
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
if (isCalleeAllocatedCoro)
return IGM.SwiftCoroCC;
if (isAsync)
return IGM.SwiftAsyncCC;
return getFreestandingConvention(IGM);
}
llvm_unreachable("bad calling convention!");
}
static void addIndirectResultAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
unsigned paramIndex, bool allowSRet,
llvm::Type *storageType,
const TypeInfo &typeInfo,
bool useInReg = false) {
llvm::AttrBuilder b(IGM.getLLVMContext());
b.addAttribute(llvm::Attribute::NoAlias);
// Bitwise takable value types are guaranteed not to capture
// a pointer into itself.
if (typeInfo.isBitwiseTakable(ResilienceExpansion::Maximal))
b.addAttribute(llvm::Attribute::NoCapture);
if (allowSRet) {
assert(storageType);
b.addStructRetAttr(storageType);
if (useInReg)
b.addAttribute(llvm::Attribute::InReg);
}
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), paramIndex, b);
}
// This function should only be called with directly returnable
// result and error types. Errors can only be returned directly if
// they consists solely of int and ptr values.
CombinedResultAndErrorType irgen::combineResultAndTypedErrorType(
const IRGenModule &IGM, const NativeConventionSchema &resultSchema,
const NativeConventionSchema &errorSchema) {
assert(!resultSchema.requiresIndirect());
assert(!errorSchema.shouldReturnTypedErrorIndirectly());
CombinedResultAndErrorType result;
SmallVector<llvm::Type *, 8> elts;
resultSchema.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
elts.push_back(type);
});
SmallVector<llvm::Type *, 8> errorElts;
errorSchema.enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
errorElts.push_back(type);
});
llvm::SmallVector<llvm::Type *, 4> combined;
auto resIt = elts.begin();
auto errorIt = errorElts.begin();
while (resIt < elts.end() && errorIt < errorElts.end()) {
auto *res = *resIt;
if (!res->isIntOrPtrTy()) {
combined.push_back(res);
++resIt;
continue;
}
auto *error = *errorIt;
assert(error->isIntOrPtrTy() &&
"Direct errors must only consist of int or ptr values");
result.errorValueMapping.push_back(combined.size());
if (res == error) {
combined.push_back(res);
} else {
auto maxSize = std::max(IGM.DataLayout.getTypeSizeInBits(res),
IGM.DataLayout.getTypeSizeInBits(error));
combined.push_back(llvm::IntegerType::get(IGM.getLLVMContext(), maxSize));
}
++resIt;
++errorIt;
}
while (resIt < elts.end()) {
combined.push_back(*resIt);
++resIt;
}
while (errorIt < errorElts.end()) {
result.errorValueMapping.push_back(combined.size());
combined.push_back(*errorIt);
++errorIt;
}
if (combined.empty()) {
result.combinedTy = llvm::Type::getVoidTy(IGM.getLLVMContext());
} else if (combined.size() == 1) {
result.combinedTy = combined[0];
} else {
result.combinedTy =
llvm::StructType::get(IGM.getLLVMContext(), combined, /*packed*/ false);
}
return result;
}
void IRGenModule::addSwiftAsyncContextAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
b.addAttribute(llvm::Attribute::SwiftAsync);
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void IRGenModule::addSwiftSelfAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
b.addAttribute(llvm::Attribute::SwiftSelf);
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void IRGenModule::addSwiftErrorAttributes(llvm::AttributeList &attrs,
unsigned argIndex) {
llvm::AttrBuilder b(getLLVMContext());
// Don't add the swifterror attribute on ABIs that don't pass it in a register.
// We create a shadow stack location of the swifterror parameter for the
// debugger on such platforms and so we can't mark the parameter with a
// swifterror attribute.
if (ShouldUseSwiftError)
b.addAttribute(llvm::Attribute::SwiftError);
// The error result should not be aliased, captured, or pointed at invalid
// addresses regardless.
b.addAttribute(llvm::Attribute::NoAlias);
b.addAttribute(llvm::Attribute::NoCapture);
b.addDereferenceableAttr(getPointerSize().getValue());
attrs = attrs.addParamAttributes(this->getLLVMContext(), argIndex, b);
}
void irgen::addByvalArgumentAttributes(IRGenModule &IGM,
llvm::AttributeList &attrs,
unsigned argIndex, Alignment align,
llvm::Type *storageType) {
llvm::AttrBuilder b(IGM.getLLVMContext());
b.addByValAttr(storageType);
b.addAttribute(llvm::Attribute::getWithAlignment(
IGM.getLLVMContext(), llvm::Align(align.getValue())));
attrs = attrs.addParamAttributes(IGM.getLLVMContext(), argIndex, b);
}
static llvm::Attribute::AttrKind attrKindForExtending(bool signExtend) {
if (signExtend)
return llvm::Attribute::SExt;
return llvm::Attribute::ZExt;
}
namespace swift {
namespace irgen {
namespace {
class SignatureExpansion {
IRGenModule &IGM;
CanSILFunctionType FnType;
bool forStaticCall = false; // Used for objc_method (direct call or not).
// Indicates this is a c++ constructor call.
const clang::CXXConstructorDecl *cxxCtorDecl = nullptr;
public:
SmallVector<llvm::Type*, 8> ParamIRTypes;
llvm::Type *ResultIRType = nullptr;
llvm::AttributeList Attrs;
ForeignFunctionInfo ForeignInfo;
CoroutineInfo CoroInfo;
bool CanUseSRet = true;
bool CanUseError = true;
bool CanUseSelf = true;
unsigned AsyncContextIdx;
unsigned AsyncResumeFunctionSwiftSelfIdx = 0;
FunctionPointerKind FnKind;
SignatureExpansion(IRGenModule &IGM, CanSILFunctionType fnType,
FunctionPointerKind fnKind, bool forStaticCall = false,
const clang::CXXConstructorDecl *cxxCtorDecl = nullptr)
: IGM(IGM), FnType(fnType), forStaticCall(forStaticCall),
cxxCtorDecl(cxxCtorDecl), FnKind(fnKind) {}
/// Expand the components of the primary entrypoint of the function type.
void expandFunctionType(
SignatureExpansionABIDetails *recordedABIDetails = nullptr);
/// Expand the components of the continuation entrypoint of the
/// function type.
void expandCoroutineContinuationType();
// Expand the components for the async continuation entrypoint of the
// function type (the function to be called on returning).
void expandAsyncReturnType();
// Expand the components for the async suspend call of the function type.
void expandAsyncAwaitType();
// Expand the components for the primary entrypoint of the async function
// type.
void expandAsyncEntryType();
Signature getSignature();
private:
const TypeInfo &expand(SILParameterInfo param);
llvm::Type *addIndirectResult(SILType resultType, bool useInReg = false);
SILFunctionConventions getSILFuncConventions() const {
return SILFunctionConventions(FnType, IGM.getSILModule());
}
unsigned getCurParamIndex() {
return ParamIRTypes.size();
}
bool claimSRet() {
bool result = CanUseSRet;
CanUseSRet = false;
return result;
}
bool claimSelf() {
auto Ret = CanUseSelf;
assert(CanUseSelf && "Multiple self parameters?!");
CanUseSelf = false;
return Ret;
}
bool claimError() {
auto Ret = CanUseError;
assert(CanUseError && "Multiple error parameters?!");
CanUseError = false;
return Ret;
}
/// Add a pointer to the given type as the next parameter.
void addPointerParameter(llvm::Type *storageType) {
ParamIRTypes.push_back(storageType->getPointerTo());
}
void addCoroutineContextParameter();
void addCoroutineAllocatorParameter();
void addAsyncParameters();
void expandResult(SignatureExpansionABIDetails *recordedABIDetails);
/// Returns the LLVM type pointer and its type info for
/// the direct result of this function. If the result is passed indirectly,
/// a void type is returned instead, with a \c null type info.
std::pair<llvm::Type *, const TypeInfo *> expandDirectResult();
std::pair<llvm::Type *, const TypeInfo *> expandDirectErrorType();
void expandIndirectResults();
void expandParameters(SignatureExpansionABIDetails *recordedABIDetails);
void expandKeyPathAccessorParameters();
void expandExternalSignatureTypes();
void expandCoroutineResult(bool forContinuation);
void expandCoroutineContinuationParameters();
void addIndirectThrowingResult();
llvm::Type *getErrorRegisterType();
};
} // end anonymous namespace
} // end namespace irgen
} // end namespace swift
llvm::Type *SignatureExpansion::addIndirectResult(SILType resultType,
bool useInReg) {
const TypeInfo &resultTI = IGM.getTypeInfo(resultType);
auto storageTy = resultTI.getStorageType();
addIndirectResultAttributes(IGM, Attrs, ParamIRTypes.size(), claimSRet(),
storageTy, resultTI, useInReg);
addPointerParameter(storageTy);
return IGM.VoidTy;
}
/// Expand all of the direct and indirect result types.
void SignatureExpansion::expandResult(
SignatureExpansionABIDetails *recordedABIDetails) {
if (FnType->isAsync()) {
// The result will be stored within the SwiftContext that is passed to async
// functions.
ResultIRType = IGM.VoidTy;
return;
}
if (FnType->isCoroutine()) {
// This should be easy enough to support if we need to: use the
// same algorithm but add the direct results to the results as if
// they were unioned in.
return expandCoroutineResult(/*for continuation*/ false);
}
auto fnConv = getSILFuncConventions();
// Disable the use of sret if we have multiple indirect results.
if (fnConv.getNumIndirectSILResults() > 1)
CanUseSRet = false;
// Ensure that no parameters were added before to correctly record their ABI
// details.
assert(ParamIRTypes.empty());
// Expand the direct result.
const TypeInfo *directResultTypeInfo;
std::tie(ResultIRType, directResultTypeInfo) = expandDirectResult();
if (!fnConv.hasIndirectSILResults() && !fnConv.hasIndirectSILErrorResults()) {
llvm::Type *directErrorType;
const TypeInfo *directErrorTypeInfo;
std::tie(directErrorType, directErrorTypeInfo) = expandDirectErrorType();
if ((directResultTypeInfo || ResultIRType->isVoidTy()) &&
directErrorTypeInfo) {
ResultIRType = directErrorType;
directResultTypeInfo = directErrorTypeInfo;
}
}
// Expand the indirect results.
expandIndirectResults();
// Record ABI details if asked.
if (!recordedABIDetails)
return;
if (directResultTypeInfo)
recordedABIDetails->directResult =
SignatureExpansionABIDetails::DirectResult{*directResultTypeInfo};
for (unsigned i = 0; i < ParamIRTypes.size(); ++i) {
bool hasSRet = Attrs.hasParamAttr(i, llvm::Attribute::StructRet);
recordedABIDetails->indirectResults.push_back(
SignatureExpansionABIDetails::IndirectResult{hasSRet});
}
}
void SignatureExpansion::expandIndirectResults() {
auto fnConv = getSILFuncConventions();
// Expand the indirect results.
for (auto indirectResultType :
fnConv.getIndirectSILResultTypes(IGM.getMaximalTypeExpansionContext())) {
auto storageTy = IGM.getStorageType(indirectResultType);
auto useSRet = claimSRet();
// We need to use opaque types or non fixed size storage types because llvm
// does type based analysis based on the type of sret arguments.
const TypeInfo &typeInfo = IGM.getTypeInfo(indirectResultType);
if (useSRet && !isa<FixedTypeInfo>(typeInfo)) {
storageTy = IGM.OpaqueTy;
}
addIndirectResultAttributes(IGM, Attrs, ParamIRTypes.size(), useSRet,
storageTy, typeInfo);
addPointerParameter(storageTy);
}
}
namespace {
class YieldSchema {
SILType YieldTy;
const TypeInfo &YieldTI;
std::optional<NativeConventionSchema> NativeSchema;
bool IsIndirect;
public:
YieldSchema(IRGenModule &IGM, SILFunctionConventions fnConv,
SILYieldInfo yield)
: YieldTy(
fnConv.getSILType(yield, IGM.getMaximalTypeExpansionContext())),
YieldTI(IGM.getTypeInfo(YieldTy)) {
if (isFormalIndirect()) {
IsIndirect = true;
} else {
NativeSchema.emplace(IGM, &YieldTI, /*result*/ true);
IsIndirect = NativeSchema->requiresIndirect();
}
}
SILType getSILType() const {
return YieldTy;
}
const TypeInfo &getTypeInfo() const {
return YieldTI;
}
/// Should the yielded value be yielded as a pointer?
bool isIndirect() const { return IsIndirect; }
/// Is the yielded value formally indirect?
bool isFormalIndirect() const { return YieldTy.isAddress(); }
llvm::PointerType *getIndirectPointerType() const {
assert(isIndirect());
return YieldTI.getStorageType()->getPointerTo();
}
const NativeConventionSchema &getDirectSchema() const {
assert(!isIndirect());
return *NativeSchema;
}
void enumerateDirectComponents(llvm::function_ref<void(llvm::Type*)> fn) {
getDirectSchema().enumerateComponents([&](clang::CharUnits begin,
clang::CharUnits end,
llvm::Type *componentTy) {
fn(componentTy);
});
}
};
}
void SignatureExpansion::expandCoroutineResult(bool forContinuation) {
// The return type may be different for the ramp function vs. the
// continuations.
if (forContinuation) {
switch (FnType->getCoroutineKind()) {
case SILCoroutineKind::None:
llvm_unreachable("should have been filtered out before here");
// Yield-once coroutines may optionaly return a value from the continuation.
case SILCoroutineKind::YieldOnce:
case SILCoroutineKind::YieldOnce2: {
// Ensure that no parameters were added before to correctly record their ABI
// details.
assert(ParamIRTypes.empty());
// Expand the direct result.
const TypeInfo *directResultTypeInfo;
std::tie(ResultIRType, directResultTypeInfo) = expandDirectResult();
return;
}
// Yield-many coroutines yield the same types from the continuation
// as they do from the ramp function.
case SILCoroutineKind::YieldMany:
assert(FnType->getNumResults() == 0 &&
"having both normal and yield results is currently unsupported");
break;
}
}
SmallVector<llvm::Type*, 8> components;
// The continuation pointer.
components.push_back(IGM.Int8PtrTy);
auto fnConv = getSILFuncConventions();
for (auto yield : FnType->getYields()) {
YieldSchema schema(IGM, fnConv, yield);
// If the individual value must be yielded indirectly, add a pointer.
if (schema.isIndirect()) {
components.push_back(schema.getIndirectPointerType());
continue;
}
// Otherwise, collect all the component types.
schema.enumerateDirectComponents([&](llvm::Type *type) {
components.push_back(type);
});
}
// Find the maximal sequence of the component types that we can
// convince the ABI to pass directly.
// When counting components, ignore the continuation pointer.
unsigned numDirectComponents = components.size() - 1;
SmallVector<llvm::Type*, 8> overflowTypes;
while (clang::CodeGen::swiftcall::
shouldPassIndirectly(IGM.ClangCodeGen->CGM(), components,
/*asReturnValue*/ true)) {
// If we added a pointer to the end of components, remove it.
if (!overflowTypes.empty()) components.pop_back();
// Remove the last component and add it as an overflow type.
overflowTypes.push_back(components.pop_back_val());
--numDirectComponents;
// Add a pointer to the end of components.
components.push_back(IGM.Int8PtrTy);
}
// We'd better have been able to pass at least two pointers.
assert(components.size() >= 2 || overflowTypes.empty());
CoroInfo.NumDirectYieldComponents = numDirectComponents;
// Replace the pointer type we added to components with the real
// pointer-to-overflow type.
if (!overflowTypes.empty()) {
std::reverse(overflowTypes.begin(), overflowTypes.end());
// TODO: should we use some sort of real layout here instead of
// trusting LLVM's?
CoroInfo.indirectResultsType =
llvm::StructType::get(IGM.getLLVMContext(), overflowTypes);
components.back() = CoroInfo.indirectResultsType->getPointerTo();
}
ResultIRType = components.size() == 1
? components.front()
: llvm::StructType::get(IGM.getLLVMContext(), components);
}
void SignatureExpansion::expandCoroutineContinuationParameters() {
// The coroutine context.
addCoroutineContextParameter();
if (FnType->isCalleeAllocatedCoroutine()) {
// Whether this is an unwind resumption.
ParamIRTypes.push_back(IGM.CoroAllocatorPtrTy);
} else {
// Whether this is an unwind resumption.
ParamIRTypes.push_back(IGM.Int1Ty);
}
}
void SignatureExpansion::addAsyncParameters() {
// using TaskContinuationFunction =
// SWIFT_CC(swift)
// void (SWIFT_ASYNC_CONTEXT AsyncContext *);
AsyncContextIdx = getCurParamIndex();
Attrs = Attrs.addParamAttribute(IGM.getLLVMContext(), AsyncContextIdx,
llvm::Attribute::SwiftAsync);
ParamIRTypes.push_back(IGM.SwiftContextPtrTy);
}
void SignatureExpansion::addCoroutineContextParameter() {
// Flag that the context is dereferenceable and unaliased.
auto contextSize = getCoroutineContextSize(IGM, FnType);
Attrs = Attrs.addDereferenceableParamAttr(
IGM.getLLVMContext(), getCurParamIndex(),
contextSize ? contextSize->getValue() : 0);
Attrs = Attrs.addParamAttribute(IGM.getLLVMContext(),
getCurParamIndex(),
llvm::Attribute::NoAlias);
ParamIRTypes.push_back(IGM.Int8PtrTy);
}
void SignatureExpansion::addCoroutineAllocatorParameter() {
ParamIRTypes.push_back(IGM.CoroAllocatorPtrTy);
}
NativeConventionSchema::NativeConventionSchema(IRGenModule &IGM,
const TypeInfo *ti,
bool IsResult)
: Lowering(IGM.ClangCodeGen->CGM()) {
if (auto *loadable = dyn_cast<LoadableTypeInfo>(ti)) {
// Lower the type according to the Swift ABI.
loadable->addToAggLowering(IGM, Lowering, Size(0));
Lowering.finish();
// Should we pass indirectly according to the ABI?
RequiresIndirect = Lowering.shouldPassIndirectly(IsResult);
} else {
Lowering.finish();
RequiresIndirect = true;
}
}
llvm::Type *NativeConventionSchema::getExpandedType(IRGenModule &IGM) const {
if (empty())
return IGM.VoidTy;
SmallVector<llvm::Type *, 8> elts;
enumerateComponents([&](clang::CharUnits offset, clang::CharUnits end,
llvm::Type *type) { elts.push_back(type); });
if (elts.size() == 1)
return elts[0];
auto &ctx = IGM.getLLVMContext();
return llvm::StructType::get(ctx, elts, /*packed*/ false);
}
std::pair<llvm::StructType *, llvm::StructType *>
NativeConventionSchema::getCoercionTypes(
IRGenModule &IGM, SmallVectorImpl<unsigned> &expandedTyIndicesMap) const {
auto &ctx = IGM.getLLVMContext();
if (empty()) {
auto type = llvm::StructType::get(ctx);
return {type, type};
}
clang::CharUnits lastEnd = clang::CharUnits::Zero();
llvm::SmallSet<unsigned, 8> overlappedWithSuccessor;
unsigned idx = 0;
// Mark overlapping ranges.
enumerateComponents(
[&](clang::CharUnits offset, clang::CharUnits end, llvm::Type *type) {
if (offset < lastEnd) {
overlappedWithSuccessor.insert(idx);
}
lastEnd = end;
++idx;
});
// Create the coercion struct with only the integer portion of overlapped
// components and non-overlapped components.
idx = 0;
lastEnd = clang::CharUnits::Zero();
SmallVector<llvm::Type *, 8> elts;
bool packed = false;
enumerateComponents(
[&](clang::CharUnits begin, clang::CharUnits end, llvm::Type *type) {
bool overlapped = overlappedWithSuccessor.count(idx) ||
(idx && overlappedWithSuccessor.count(idx - 1));
++idx;
if (overlapped && !isa<llvm::IntegerType>(type)) {
// keep the old lastEnd for padding.
return;
}
// Add padding (which may include padding for overlapped non-integer
// components).
if (begin != lastEnd) {
auto paddingSize = begin - lastEnd;
assert(!paddingSize.isNegative());