forked from apple/swift
/
SILInstructions.cpp
2961 lines (2617 loc) · 122 KB
/
SILInstructions.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
//===--- SILInstructions.cpp - Instructions for SIL code ------------------===//
//
// 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 defines the high-level SILInstruction classes used for SIL code.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Expr.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/AssertImplements.h"
#include "swift/Basic/Unicode.h"
#include "swift/Basic/type_traits.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILCloner.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILVisitor.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/ErrorHandling.h"
using namespace swift;
using namespace Lowering;
/// Allocate an instruction that inherits from llvm::TrailingObjects<>.
template <class Inst, class... TrailingTypes, class... CountTypes>
static void *allocateTrailingInst(SILFunction &F, CountTypes... counts) {
return F.getModule().allocateInst(
Inst::template totalSizeToAlloc<TrailingTypes...>(counts...),
alignof(Inst));
}
// Collect used open archetypes from a given type into the \p openedArchetypes.
// \p openedArchetypes is being used as a set. We don't use a real set type here
// for performance reasons.
static void
collectDependentTypeInfo(CanType Ty,
SmallVectorImpl<CanArchetypeType> &openedArchetypes,
bool &hasDynamicSelf) {
if (!Ty)
return;
if (Ty->hasDynamicSelfType())
hasDynamicSelf = true;
if (!Ty->hasOpenedExistential())
return;
Ty.visit([&](CanType t) {
if (t->isOpenedExistential()) {
// Add this opened archetype if it was not seen yet.
// We don't use a set here, because the number of open archetypes
// is usually very small and using a real set may introduce too
// much overhead.
auto archetypeTy = cast<ArchetypeType>(t);
if (std::find(openedArchetypes.begin(), openedArchetypes.end(),
archetypeTy) == openedArchetypes.end())
openedArchetypes.push_back(archetypeTy);
}
});
}
// Takes a set of open archetypes as input and produces a set of
// references to open archetype definitions.
static void buildTypeDependentOperands(
SmallVectorImpl<CanArchetypeType> &OpenedArchetypes,
bool hasDynamicSelf,
SmallVectorImpl<SILValue> &TypeDependentOperands, SILFunction &F) {
for (auto archetype : OpenedArchetypes) {
SILValue def = F.getModule().getOpenedArchetypeDef(archetype, &F);
assert(def->getFunction() == &F &&
"def of opened archetype is in wrong function");
TypeDependentOperands.push_back(def);
}
if (hasDynamicSelf)
TypeDependentOperands.push_back(F.getDynamicSelfMetadata());
}
// Collects all opened archetypes from a type and a substitutions list and form
// a corresponding list of opened archetype operands.
// We need to know the number of opened archetypes to estimate
// the number of opened archetype operands for the instruction
// being formed, because we need to reserve enough memory
// for these operands.
static void collectTypeDependentOperands(
SmallVectorImpl<SILValue> &TypeDependentOperands,
SILFunction &F,
CanType Ty,
SubstitutionMap subs = { }) {
SmallVector<CanArchetypeType, 4> openedArchetypes;
bool hasDynamicSelf = false;
collectDependentTypeInfo(Ty, openedArchetypes, hasDynamicSelf);
for (Type replacement : subs.getReplacementTypes()) {
// Substitutions in SIL should really be canonical.
auto ReplTy = replacement->getCanonicalType();
collectDependentTypeInfo(ReplTy, openedArchetypes, hasDynamicSelf);
}
buildTypeDependentOperands(openedArchetypes, hasDynamicSelf,
TypeDependentOperands, F);
}
//===----------------------------------------------------------------------===//
// SILInstruction Subclasses
//===----------------------------------------------------------------------===//
template <typename INST>
static void *allocateDebugVarCarryingInst(SILModule &M,
Optional<SILDebugVariable> Var,
ArrayRef<SILValue> Operands = {}) {
return M.allocateInst(
sizeof(INST) + (Var ? Var->Name.size() : 0) +
(Var && Var->Type ? sizeof(SILType) : 0) +
(Var && Var->Loc ? sizeof(SILLocation) : 0) +
(Var && Var->Scope ? sizeof(const SILDebugScope *) : 0) +
sizeof(SILDIExprElement) * (Var ? Var->DIExpr.getNumElements() : 0) +
sizeof(Operand) * Operands.size(),
alignof(INST));
}
TailAllocatedDebugVariable::TailAllocatedDebugVariable(
Optional<SILDebugVariable> Var, char *buf, SILType *AuxVarType,
SILLocation *DeclLoc, const SILDebugScope **DeclScope,
SILDIExprElement *DIExprOps) {
if (!Var) {
Bits.RawValue = 0;
return;
}
Bits.Data.HasValue = true;
Bits.Data.Constant = Var->Constant;
Bits.Data.ArgNo = Var->ArgNo;
Bits.Data.Implicit = Var->Implicit;
Bits.Data.NameLength = Var->Name.size();
assert(Bits.Data.ArgNo == Var->ArgNo && "Truncation");
assert(Bits.Data.NameLength == Var->Name.size() && "Truncation");
memcpy(buf, Var->Name.data(), Bits.Data.NameLength);
if (AuxVarType && Var->Type)
*AuxVarType = *Var->Type;
if (DeclLoc && Var->Loc)
*DeclLoc = *Var->Loc;
if (DeclScope && Var->Scope)
*DeclScope = Var->Scope;
if (DIExprOps) {
llvm::ArrayRef<SILDIExprElement> Ops(Var->DIExpr.Elements);
memcpy(DIExprOps, Ops.data(), sizeof(SILDIExprElement) * Ops.size());
}
}
StringRef TailAllocatedDebugVariable::getName(const char *buf) const {
if (Bits.Data.NameLength)
return StringRef(buf, Bits.Data.NameLength);
return StringRef();
}
Optional<SILDebugVariable>
SILDebugVariable::createFromAllocation(const AllocationInst *AI) {
Optional<SILDebugVariable> VarInfo;
if (const auto *ASI = dyn_cast_or_null<AllocStackInst>(AI))
VarInfo = ASI->getVarInfo();
// TODO: Support AllocBoxInst
if (!VarInfo)
return VarInfo;
// Copy everything but the DIExpr
VarInfo->DIExpr.clear();
// Coalesce the debug loc attached on AI into VarInfo
SILType Type = AI->getType();
SILLocation InstLoc = AI->getLoc();
const SILDebugScope *InstDS = AI->getDebugScope();
if (!VarInfo->Type)
VarInfo->Type = Type;
if (!VarInfo->Loc)
VarInfo->Loc = InstLoc;
if (!VarInfo->Scope)
VarInfo->Scope = InstDS;
return VarInfo;
}
AllocStackInst::AllocStackInst(SILDebugLocation Loc, SILType elementType,
ArrayRef<SILValue> TypeDependentOperands,
SILFunction &F, Optional<SILDebugVariable> Var,
bool hasDynamicLifetime, bool isLexical)
: InstructionBase(Loc, elementType.getAddressType()),
SILDebugVariableSupplement(Var ? Var->DIExpr.getNumElements() : 0,
Var ? Var->Type.hasValue() : false,
Var ? Var->Loc.hasValue() : false,
Var ? Var->Scope != nullptr : false),
dynamicLifetime(hasDynamicLifetime), lexical(isLexical) {
SILNode::Bits.AllocStackInst.NumOperands =
TypeDependentOperands.size();
assert(SILNode::Bits.AllocStackInst.NumOperands ==
TypeDependentOperands.size() && "Truncation");
SILNode::Bits.AllocStackInst.VarInfo =
TailAllocatedDebugVariable(Var, getTrailingObjects<char>(),
getTrailingObjects<SILType>(),
getTrailingObjects<SILLocation>(),
getTrailingObjects<const SILDebugScope *>(),
getTrailingObjects<SILDIExprElement>())
.getRawValue();
if (auto *VD = Loc.getLocation().getAsASTNode<VarDecl>()) {
TailAllocatedDebugVariable DbgVar(SILNode::Bits.AllocStackInst.VarInfo);
DbgVar.setImplicit(VD->isImplicit() || DbgVar.isImplicit());
SILNode::Bits.AllocStackInst.VarInfo = DbgVar.getRawValue();
}
TrailingOperandsList::InitOperandsList(getAllOperands().begin(), this,
TypeDependentOperands);
}
AllocStackInst *AllocStackInst::create(SILDebugLocation Loc,
SILType elementType, SILFunction &F,
Optional<SILDebugVariable> Var,
bool hasDynamicLifetime,
bool isLexical) {
SmallVector<SILValue, 8> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, F,
elementType.getASTType());
void *Buffer = allocateDebugVarCarryingInst<AllocStackInst>(
F.getModule(), Var, TypeDependentOperands);
return ::new (Buffer) AllocStackInst(Loc, elementType, TypeDependentOperands,
F, Var, hasDynamicLifetime, isLexical);
}
VarDecl *AllocationInst::getDecl() const {
return getLoc().getAsASTNode<VarDecl>();
}
DeallocStackInst *AllocStackInst::getSingleDeallocStack() const {
DeallocStackInst *Dealloc = nullptr;
for (auto *U : getUses()) {
if (auto DS = dyn_cast<DeallocStackInst>(U->getUser())) {
if (Dealloc == nullptr) {
Dealloc = DS;
continue;
}
// Already saw a dealloc_stack.
return nullptr;
}
}
return Dealloc;
}
AllocRefInstBase::AllocRefInstBase(SILInstructionKind Kind,
SILDebugLocation Loc,
SILType ObjectType,
bool objc, bool canBeOnStack,
ArrayRef<SILType> ElementTypes)
: AllocationInst(Kind, Loc, ObjectType) {
SILNode::Bits.AllocRefInstBase.ObjC = objc;
SILNode::Bits.AllocRefInstBase.OnStack = canBeOnStack;
SILNode::Bits.AllocRefInstBase.NumTailTypes = ElementTypes.size();
assert(SILNode::Bits.AllocRefInstBase.NumTailTypes ==
ElementTypes.size() && "Truncation");
assert(!objc || ElementTypes.empty());
}
AllocRefInst *AllocRefInst::create(SILDebugLocation Loc, SILFunction &F,
SILType ObjectType,
bool objc, bool canBeOnStack,
ArrayRef<SILType> ElementTypes,
ArrayRef<SILValue> ElementCountOperands) {
assert(ElementTypes.size() == ElementCountOperands.size());
assert(!objc || ElementTypes.empty());
SmallVector<SILValue, 8> AllOperands(ElementCountOperands.begin(),
ElementCountOperands.end());
for (SILType ElemType : ElementTypes) {
collectTypeDependentOperands(AllOperands, F, ElemType.getASTType());
}
collectTypeDependentOperands(AllOperands, F, ObjectType.getASTType());
auto Size = totalSizeToAlloc<swift::Operand, SILType>(AllOperands.size(),
ElementTypes.size());
auto Buffer = F.getModule().allocateInst(Size, alignof(AllocRefInst));
return ::new (Buffer) AllocRefInst(Loc, F, ObjectType, objc, canBeOnStack,
ElementTypes, AllOperands);
}
AllocRefDynamicInst *
AllocRefDynamicInst::create(SILDebugLocation DebugLoc, SILFunction &F,
SILValue metatypeOperand, SILType ty, bool objc,
ArrayRef<SILType> ElementTypes,
ArrayRef<SILValue> ElementCountOperands) {
SmallVector<SILValue, 8> AllOperands(ElementCountOperands.begin(),
ElementCountOperands.end());
AllOperands.push_back(metatypeOperand);
collectTypeDependentOperands(AllOperands, F, ty.getASTType());
for (SILType ElemType : ElementTypes) {
collectTypeDependentOperands(AllOperands, F, ElemType.getASTType());
}
auto Size = totalSizeToAlloc<swift::Operand, SILType>(AllOperands.size(),
ElementTypes.size());
auto Buffer = F.getModule().allocateInst(Size, alignof(AllocRefDynamicInst));
return ::new (Buffer)
AllocRefDynamicInst(DebugLoc, ty, objc, ElementTypes, AllOperands);
}
AllocBoxInst::AllocBoxInst(SILDebugLocation Loc, CanSILBoxType BoxType,
ArrayRef<SILValue> TypeDependentOperands,
SILFunction &F, Optional<SILDebugVariable> Var,
bool hasDynamicLifetime)
: InstructionBaseWithTrailingOperands(TypeDependentOperands, Loc,
SILType::getPrimitiveObjectType(BoxType)),
VarInfo(Var, getTrailingObjects<char>()),
dynamicLifetime(hasDynamicLifetime) {
}
AllocBoxInst *AllocBoxInst::create(SILDebugLocation Loc,
CanSILBoxType BoxType,
SILFunction &F,
Optional<SILDebugVariable> Var,
bool hasDynamicLifetime) {
SmallVector<SILValue, 8> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, F, BoxType);
auto Sz = totalSizeToAlloc<swift::Operand, char>(TypeDependentOperands.size(),
Var ? Var->Name.size() : 0);
auto Buf = F.getModule().allocateInst(Sz, alignof(AllocBoxInst));
return ::new (Buf) AllocBoxInst(Loc, BoxType, TypeDependentOperands, F, Var,
hasDynamicLifetime);
}
SILType AllocBoxInst::getAddressType() const {
return getSILBoxFieldType(TypeExpansionContext(*this->getFunction()),
getBoxType(), getModule().Types, 0)
.getAddressType();
}
DebugValueInst::DebugValueInst(SILDebugLocation DebugLoc, SILValue Operand,
SILDebugVariable Var, bool poisonRefs)
: UnaryInstructionBase(DebugLoc, Operand),
SILDebugVariableSupplement(Var.DIExpr.getNumElements(),
Var.Type.hasValue(), Var.Loc.hasValue(),
Var.Scope),
VarInfo(Var, getTrailingObjects<char>(), getTrailingObjects<SILType>(),
getTrailingObjects<SILLocation>(),
getTrailingObjects<const SILDebugScope *>(),
getTrailingObjects<SILDIExprElement>()) {
if (auto *VD = DebugLoc.getLocation().getAsASTNode<VarDecl>())
VarInfo.setImplicit(VD->isImplicit() || VarInfo.isImplicit());
setPoisonRefs(poisonRefs);
}
DebugValueInst *DebugValueInst::create(SILDebugLocation DebugLoc,
SILValue Operand, SILModule &M,
SILDebugVariable Var, bool poisonRefs) {
void *buf = allocateDebugVarCarryingInst<DebugValueInst>(M, Var);
return ::new (buf) DebugValueInst(DebugLoc, Operand, Var, poisonRefs);
}
DebugValueInst *DebugValueInst::createAddr(SILDebugLocation DebugLoc,
SILValue Operand, SILModule &M,
SILDebugVariable Var) {
// For alloc_stack, debug_value is used to annotate the associated
// memory location, so we shouldn't attach op_deref.
if (!isa<AllocStackInst>(Operand))
Var.DIExpr.prependElements(
{SILDIExprElement::createOperator(SILDIExprOperator::Dereference)});
void *buf = allocateDebugVarCarryingInst<DebugValueInst>(M, Var);
return ::new (buf) DebugValueInst(DebugLoc, Operand, Var,
/*poisonRefs=*/false);
}
bool DebugValueInst::exprStartsWithDeref() const {
if (!NumDIExprOperands)
return false;
llvm::ArrayRef<SILDIExprElement> DIExprElements(
getTrailingObjects<SILDIExprElement>(), NumDIExprOperands);
return DIExprElements.front().getAsOperator()
== SILDIExprOperator::Dereference;
}
VarDecl *DebugValueInst::getDecl() const {
return getLoc().getAsASTNode<VarDecl>();
}
AllocExistentialBoxInst *AllocExistentialBoxInst::create(
SILDebugLocation Loc, SILType ExistentialType, CanType ConcreteType,
ArrayRef<ProtocolConformanceRef> Conformances,
SILFunction *F) {
SmallVector<SILValue, 8> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, *F, ConcreteType);
SILModule &Mod = F->getModule();
auto Size = totalSizeToAlloc<swift::Operand>(TypeDependentOperands.size());
auto Buffer = Mod.allocateInst(Size, alignof(AllocExistentialBoxInst));
return ::new (Buffer) AllocExistentialBoxInst(Loc,
ExistentialType,
ConcreteType,
Conformances,
TypeDependentOperands,
F);
}
AllocValueBufferInst::AllocValueBufferInst(
SILDebugLocation DebugLoc, SILType valueType, SILValue operand,
ArrayRef<SILValue> TypeDependentOperands)
: UnaryInstructionWithTypeDependentOperandsBase(DebugLoc, operand,
TypeDependentOperands,
valueType.getAddressType()) {}
AllocValueBufferInst *
AllocValueBufferInst::create(SILDebugLocation DebugLoc, SILType valueType,
SILValue operand, SILFunction &F) {
SmallVector<SILValue, 8> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, F, valueType.getASTType());
void *Buffer = F.getModule().allocateInst(
sizeof(AllocValueBufferInst) +
sizeof(Operand) * (TypeDependentOperands.size() + 1),
alignof(AllocValueBufferInst));
return ::new (Buffer) AllocValueBufferInst(DebugLoc, valueType, operand,
TypeDependentOperands);
}
BuiltinInst *BuiltinInst::create(SILDebugLocation Loc, Identifier Name,
SILType ReturnType,
SubstitutionMap Substitutions,
ArrayRef<SILValue> Args,
SILModule &M) {
auto Size = totalSizeToAlloc<swift::Operand>(Args.size());
auto Buffer = M.allocateInst(Size, alignof(BuiltinInst));
return ::new (Buffer) BuiltinInst(Loc, Name, ReturnType, Substitutions,
Args);
}
BuiltinInst::BuiltinInst(SILDebugLocation Loc, Identifier Name,
SILType ReturnType, SubstitutionMap Subs,
ArrayRef<SILValue> Args)
: InstructionBaseWithTrailingOperands(Args, Loc, ReturnType), Name(Name),
Substitutions(Subs) {
}
InitBlockStorageHeaderInst *
InitBlockStorageHeaderInst::create(SILFunction &F,
SILDebugLocation DebugLoc, SILValue BlockStorage,
SILValue InvokeFunction, SILType BlockType,
SubstitutionMap Subs) {
void *Buffer = F.getModule().allocateInst(
sizeof(InitBlockStorageHeaderInst),
alignof(InitBlockStorageHeaderInst));
return ::new (Buffer) InitBlockStorageHeaderInst(DebugLoc, BlockStorage,
InvokeFunction, BlockType,
Subs);
}
ApplyInst::ApplyInst(SILDebugLocation Loc, SILValue Callee,
SILType SubstCalleeTy, SILType Result,
SubstitutionMap Subs,
ArrayRef<SILValue> Args,
ArrayRef<SILValue> TypeDependentOperands,
ApplyOptions options,
const GenericSpecializationInformation *SpecializationInfo)
: InstructionBase(Loc, Callee, SubstCalleeTy, Subs, Args,
TypeDependentOperands, SpecializationInfo, Result) {
setApplyOptions(options);
assert(!SubstCalleeTy.castTo<SILFunctionType>()->isCoroutine());
}
ApplyInst *
ApplyInst::create(SILDebugLocation Loc, SILValue Callee, SubstitutionMap Subs,
ArrayRef<SILValue> Args, ApplyOptions Options,
Optional<SILModuleConventions> ModuleConventions,
SILFunction &F,
const GenericSpecializationInformation *SpecializationInfo) {
SILType SubstCalleeSILTy = Callee->getType().substGenericArgs(
F.getModule(), Subs, F.getTypeExpansionContext());
auto SubstCalleeTy = SubstCalleeSILTy.getAs<SILFunctionType>();
SILFunctionConventions Conv(SubstCalleeTy,
ModuleConventions.hasValue()
? ModuleConventions.getValue()
: SILModuleConventions(F.getModule()));
SILType Result = Conv.getSILResultType(F.getTypeExpansionContext());
SmallVector<SILValue, 32> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, F,
SubstCalleeSILTy.getASTType(), Subs);
void *Buffer =
allocateTrailingInst<ApplyInst, Operand>(
F, getNumAllOperands(Args, TypeDependentOperands));
return ::new(Buffer) ApplyInst(Loc, Callee, SubstCalleeSILTy,
Result, Subs, Args,
TypeDependentOperands,
Options,
SpecializationInfo);
}
BeginApplyInst::BeginApplyInst(SILDebugLocation loc, SILValue callee,
SILType substCalleeTy,
ArrayRef<SILType> allResultTypes,
ArrayRef<ValueOwnershipKind> allResultOwnerships,
SubstitutionMap subs,
ArrayRef<SILValue> args,
ArrayRef<SILValue> typeDependentOperands,
ApplyOptions options,
const GenericSpecializationInformation *specializationInfo)
: InstructionBase(loc, callee, substCalleeTy, subs, args,
typeDependentOperands, specializationInfo),
MultipleValueInstructionTrailingObjects(this, allResultTypes,
allResultOwnerships) {
setApplyOptions(options);
assert(substCalleeTy.castTo<SILFunctionType>()->isCoroutine());
}
BeginApplyInst *
BeginApplyInst::create(SILDebugLocation loc, SILValue callee,
SubstitutionMap subs, ArrayRef<SILValue> args,
ApplyOptions options,
Optional<SILModuleConventions> moduleConventions,
SILFunction &F,
const GenericSpecializationInformation *specializationInfo) {
SILType substCalleeSILType = callee->getType().substGenericArgs(
F.getModule(), subs, F.getTypeExpansionContext());
auto substCalleeType = substCalleeSILType.castTo<SILFunctionType>();
SILFunctionConventions conv(substCalleeType,
moduleConventions.hasValue()
? moduleConventions.getValue()
: SILModuleConventions(F.getModule()));
SmallVector<SILType, 8> resultTypes;
SmallVector<ValueOwnershipKind, 8> resultOwnerships;
for (auto &yield : substCalleeType->getYields()) {
auto yieldType = conv.getSILType(yield, F.getTypeExpansionContext());
auto convention = SILArgumentConvention(yield.getConvention());
resultTypes.push_back(yieldType);
resultOwnerships.push_back(
ValueOwnershipKind(F, yieldType, convention));
}
resultTypes.push_back(SILType::getSILTokenType(F.getASTContext()));
// The begin_apply token represents the borrow scope of all owned and
// guaranteed call arguments. Although SILToken is (currently) trivially
// typed, it must have guaranteed ownership so end_apply and abort_apply will
// be recognized as lifetime-ending uses.
resultOwnerships.push_back(OwnershipKind::Guaranteed);
SmallVector<SILValue, 32> typeDependentOperands;
collectTypeDependentOperands(typeDependentOperands, F, substCalleeType, subs);
void *buffer =
allocateTrailingInst<BeginApplyInst, Operand, MultipleValueInstruction*,
MultipleValueInstructionResult>(
F, getNumAllOperands(args, typeDependentOperands),
1, resultTypes.size());
return ::new(buffer) BeginApplyInst(loc, callee, substCalleeSILType,
resultTypes, resultOwnerships, subs,
args, typeDependentOperands,
options, specializationInfo);
}
void BeginApplyInst::getCoroutineEndPoints(
SmallVectorImpl<EndApplyInst *> &endApplyInsts,
SmallVectorImpl<AbortApplyInst *> &abortApplyInsts) const {
for (auto *tokenUse : getTokenResult()->getUses()) {
auto *user = tokenUse->getUser();
if (auto *end = dyn_cast<EndApplyInst>(user)) {
endApplyInsts.push_back(end);
continue;
}
abortApplyInsts.push_back(cast<AbortApplyInst>(user));
}
}
void BeginApplyInst::getCoroutineEndPoints(
SmallVectorImpl<Operand *> &endApplyInsts,
SmallVectorImpl<Operand *> &abortApplyInsts) const {
for (auto *tokenUse : getTokenResult()->getUses()) {
auto *user = tokenUse->getUser();
if (isa<EndApplyInst>(user)) {
endApplyInsts.push_back(tokenUse);
continue;
}
assert(isa<AbortApplyInst>(user));
abortApplyInsts.push_back(tokenUse);
}
}
bool swift::doesApplyCalleeHaveSemantics(SILValue callee, StringRef semantics) {
if (auto *FRI = dyn_cast<FunctionRefBaseInst>(callee))
if (auto *F = FRI->getReferencedFunctionOrNull())
return F->hasSemanticsAttr(semantics);
return false;
}
PartialApplyInst::PartialApplyInst(
SILDebugLocation Loc, SILValue Callee, SILType SubstCalleeTy,
SubstitutionMap Subs, ArrayRef<SILValue> Args,
ArrayRef<SILValue> TypeDependentOperands, SILType ClosureType,
const GenericSpecializationInformation *SpecializationInfo)
// FIXME: the callee should have a lowered SIL function type, and
// PartialApplyInst
// should derive the type of its result by partially applying the callee's
// type.
: InstructionBase(Loc, Callee, SubstCalleeTy, Subs, Args,
TypeDependentOperands, SpecializationInfo, ClosureType) {}
PartialApplyInst *PartialApplyInst::create(
SILDebugLocation Loc, SILValue Callee, ArrayRef<SILValue> Args,
SubstitutionMap Subs, ParameterConvention CalleeConvention, SILFunction &F,
const GenericSpecializationInformation *SpecializationInfo,
OnStackKind onStack) {
SILType SubstCalleeTy = Callee->getType().substGenericArgs(
F.getModule(), Subs, F.getTypeExpansionContext());
SILType ClosureType = SILBuilder::getPartialApplyResultType(
F.getTypeExpansionContext(), SubstCalleeTy, Args.size(), F.getModule(), {},
CalleeConvention, onStack);
SmallVector<SILValue, 32> TypeDependentOperands;
collectTypeDependentOperands(TypeDependentOperands, F,
SubstCalleeTy.getASTType(), Subs);
void *Buffer =
allocateTrailingInst<PartialApplyInst, Operand>(
F, getNumAllOperands(Args, TypeDependentOperands));
return ::new(Buffer) PartialApplyInst(Loc, Callee, SubstCalleeTy,
Subs, Args,
TypeDependentOperands, ClosureType,
SpecializationInfo);
}
TryApplyInstBase::TryApplyInstBase(SILInstructionKind kind,
SILDebugLocation loc,
SILBasicBlock *normalBB,
SILBasicBlock *errorBB)
: TermInst(kind, loc), DestBBs{{{this, normalBB}, {this, errorBB}}} {}
TryApplyInst::TryApplyInst(
SILDebugLocation Loc, SILValue callee, SILType substCalleeTy,
SubstitutionMap subs, ArrayRef<SILValue> args,
ArrayRef<SILValue> TypeDependentOperands, SILBasicBlock *normalBB,
SILBasicBlock *errorBB,
ApplyOptions options,
const GenericSpecializationInformation *SpecializationInfo)
: InstructionBase(Loc, callee, substCalleeTy, subs, args,
TypeDependentOperands, SpecializationInfo, normalBB,
errorBB) {
setApplyOptions(options);
}
TryApplyInst *TryApplyInst::create(
SILDebugLocation loc, SILValue callee, SubstitutionMap subs,
ArrayRef<SILValue> args, SILBasicBlock *normalBB, SILBasicBlock *errorBB,
ApplyOptions options,
SILFunction &F,
const GenericSpecializationInformation *specializationInfo) {
SILType substCalleeTy = callee->getType().substGenericArgs(
F.getModule(), subs, F.getTypeExpansionContext());
SmallVector<SILValue, 32> typeDependentOperands;
collectTypeDependentOperands(typeDependentOperands, F,
substCalleeTy.getASTType(),
subs);
void *buffer =
allocateTrailingInst<TryApplyInst, Operand>(
F, getNumAllOperands(args, typeDependentOperands));
return ::new (buffer) TryApplyInst(loc, callee, substCalleeTy, subs, args,
typeDependentOperands,
normalBB, errorBB, options,
specializationInfo);
}
SILType DifferentiableFunctionInst::getDifferentiableFunctionType(
SILValue OriginalFunction, IndexSubset *ParameterIndices,
IndexSubset *ResultIndices) {
assert(!ResultIndices->isEmpty());
auto fnTy = OriginalFunction->getType().castTo<SILFunctionType>();
auto diffTy = fnTy->getWithDifferentiability(DifferentiabilityKind::Reverse,
ParameterIndices, ResultIndices);
return SILType::getPrimitiveObjectType(diffTy);
}
ValueOwnershipKind DifferentiableFunctionInst::getMergedOwnershipKind(
SILValue OriginalFunction, ArrayRef<SILValue> DerivativeFunctions) {
if (DerivativeFunctions.empty())
return OriginalFunction.getOwnershipKind();
return mergeSILValueOwnership(
{OriginalFunction, DerivativeFunctions[0], DerivativeFunctions[1]});
}
DifferentiableFunctionInst::DifferentiableFunctionInst(
SILDebugLocation Loc, IndexSubset *ParameterIndices,
IndexSubset *ResultIndices, SILValue OriginalFunction,
ArrayRef<SILValue> DerivativeFunctions,
ValueOwnershipKind forwardingOwnershipKind)
: InstructionBaseWithTrailingOperands(
OriginalFunction, DerivativeFunctions, Loc,
getDifferentiableFunctionType(OriginalFunction, ParameterIndices,
ResultIndices),
forwardingOwnershipKind),
ParameterIndices(ParameterIndices), ResultIndices(ResultIndices),
HasDerivativeFunctions(!DerivativeFunctions.empty()) {
assert(DerivativeFunctions.empty() || DerivativeFunctions.size() == 2);
}
DifferentiableFunctionInst *DifferentiableFunctionInst::create(
SILModule &Module, SILDebugLocation Loc, IndexSubset *ParameterIndices,
IndexSubset *ResultIndices, SILValue OriginalFunction,
Optional<std::pair<SILValue, SILValue>> VJPAndJVPFunctions,
ValueOwnershipKind forwardingOwnershipKind) {
auto derivativeFunctions =
VJPAndJVPFunctions.hasValue()
? ArrayRef<SILValue>(
reinterpret_cast<SILValue *>(VJPAndJVPFunctions.getPointer()),
2)
: ArrayRef<SILValue>();
size_t size = totalSizeToAlloc<Operand>(1 + derivativeFunctions.size());
void *buffer = Module.allocateInst(size, alignof(DifferentiableFunctionInst));
return ::new (buffer) DifferentiableFunctionInst(
Loc, ParameterIndices, ResultIndices, OriginalFunction,
derivativeFunctions, forwardingOwnershipKind);
}
SILType LinearFunctionInst::getLinearFunctionType(
SILValue OriginalFunction, IndexSubset *ParameterIndices) {
auto fnTy = OriginalFunction->getType().castTo<SILFunctionType>();
auto *resultIndices =
IndexSubset::get(fnTy->getASTContext(), /*capacity*/ 1, /*indices*/ {0});
auto diffTy = fnTy->getWithDifferentiability(DifferentiabilityKind::Linear,
ParameterIndices, resultIndices);
return SILType::getPrimitiveObjectType(diffTy);
}
LinearFunctionInst::LinearFunctionInst(
SILDebugLocation Loc, IndexSubset *ParameterIndices,
SILValue OriginalFunction, Optional<SILValue> TransposeFunction,
ValueOwnershipKind forwardingOwnershipKind)
: InstructionBaseWithTrailingOperands(
OriginalFunction,
TransposeFunction.hasValue()
? ArrayRef<SILValue>(TransposeFunction.getPointer(), 1)
: ArrayRef<SILValue>(),
Loc, getLinearFunctionType(OriginalFunction, ParameterIndices),
forwardingOwnershipKind),
ParameterIndices(ParameterIndices),
HasTransposeFunction(TransposeFunction.hasValue()) {}
LinearFunctionInst *LinearFunctionInst::create(
SILModule &Module, SILDebugLocation Loc, IndexSubset *ParameterIndices,
SILValue OriginalFunction, Optional<SILValue> TransposeFunction,
ValueOwnershipKind forwardingOwnershipKind) {
size_t size = totalSizeToAlloc<Operand>(TransposeFunction.hasValue() ? 2 : 1);
void *buffer = Module.allocateInst(size, alignof(DifferentiableFunctionInst));
return ::new (buffer)
LinearFunctionInst(Loc, ParameterIndices, OriginalFunction,
TransposeFunction, forwardingOwnershipKind);
}
SILType DifferentiableFunctionExtractInst::getExtracteeType(
SILValue function, NormalDifferentiableFunctionTypeComponent extractee,
SILModule &module) {
auto fnTy = function->getType().castTo<SILFunctionType>();
// TODO: Ban 'Normal' and 'Forward'.
assert(
fnTy->getDifferentiabilityKind() == DifferentiabilityKind::Reverse ||
fnTy->getDifferentiabilityKind() == DifferentiabilityKind::Normal ||
fnTy->getDifferentiabilityKind() == DifferentiabilityKind::Forward);
auto originalFnTy = fnTy->getWithoutDifferentiability();
auto kindOpt = extractee.getAsDerivativeFunctionKind();
if (!kindOpt) {
assert(extractee == NormalDifferentiableFunctionTypeComponent::Original);
return SILType::getPrimitiveObjectType(originalFnTy);
}
auto resultFnTy = originalFnTy->getAutoDiffDerivativeFunctionType(
fnTy->getDifferentiabilityParameterIndices(),
fnTy->getDifferentiabilityResultIndices(), *kindOpt, module.Types,
LookUpConformanceInModule(module.getSwiftModule()));
return SILType::getPrimitiveObjectType(resultFnTy);
}
DifferentiableFunctionExtractInst::DifferentiableFunctionExtractInst(
SILModule &module, SILDebugLocation debugLoc,
NormalDifferentiableFunctionTypeComponent extractee, SILValue function,
ValueOwnershipKind forwardingOwnershipKind, Optional<SILType> extracteeType)
: UnaryInstructionBase(debugLoc, function,
extracteeType
? *extracteeType
: getExtracteeType(function, extractee, module),
forwardingOwnershipKind),
Extractee(extractee), HasExplicitExtracteeType(extracteeType.hasValue()) {
}
SILType LinearFunctionExtractInst::
getExtracteeType(
SILValue function, LinearDifferentiableFunctionTypeComponent extractee,
SILModule &module) {
auto fnTy = function->getType().castTo<SILFunctionType>();
assert(fnTy->getDifferentiabilityKind() == DifferentiabilityKind::Linear);
auto originalFnTy = fnTy->getWithoutDifferentiability();
switch (extractee) {
case LinearDifferentiableFunctionTypeComponent::Original:
return SILType::getPrimitiveObjectType(originalFnTy);
case LinearDifferentiableFunctionTypeComponent::Transpose:
auto transposeFnTy = originalFnTy->getAutoDiffTransposeFunctionType(
fnTy->getDifferentiabilityParameterIndices(), module.Types,
LookUpConformanceInModule(module.getSwiftModule()));
return SILType::getPrimitiveObjectType(transposeFnTy);
}
llvm_unreachable("invalid extractee");
}
LinearFunctionExtractInst::LinearFunctionExtractInst(
SILModule &module, SILDebugLocation debugLoc,
LinearDifferentiableFunctionTypeComponent extractee, SILValue function,
ValueOwnershipKind forwardingOwnershipKind)
: UnaryInstructionBase(debugLoc, function,
getExtracteeType(function, extractee, module),
forwardingOwnershipKind),
extractee(extractee) {}
SILType DifferentiabilityWitnessFunctionInst::getDifferentiabilityWitnessType(
SILModule &module, DifferentiabilityWitnessFunctionKind witnessKind,
SILDifferentiabilityWitness *witness) {
auto fnTy = witness->getOriginalFunction()->getLoweredFunctionType();
auto witnessCanGenSig = witness->getDerivativeGenericSignature().getCanonicalSignature();
auto *parameterIndices = witness->getParameterIndices();
auto *resultIndices = witness->getResultIndices();
if (auto derivativeKind = witnessKind.getAsDerivativeFunctionKind()) {
bool isReabstractionThunk =
witness->getOriginalFunction()->isThunk() == IsReabstractionThunk;
auto diffFnTy = fnTy->getAutoDiffDerivativeFunctionType(
parameterIndices, resultIndices, *derivativeKind, module.Types,
LookUpConformanceInModule(module.getSwiftModule()), witnessCanGenSig,
isReabstractionThunk);
return SILType::getPrimitiveObjectType(diffFnTy);
}
assert(witnessKind == DifferentiabilityWitnessFunctionKind::Transpose);
auto transposeFnTy = fnTy->getAutoDiffTransposeFunctionType(
parameterIndices, module.Types,
LookUpConformanceInModule(module.getSwiftModule()), witnessCanGenSig);
return SILType::getPrimitiveObjectType(transposeFnTy);
}
DifferentiabilityWitnessFunctionInst::DifferentiabilityWitnessFunctionInst(
SILModule &module, SILDebugLocation debugLoc,
DifferentiabilityWitnessFunctionKind witnessKind,
SILDifferentiabilityWitness *witness, Optional<SILType> functionType)
: InstructionBase(debugLoc, functionType
? *functionType
: getDifferentiabilityWitnessType(
module, witnessKind, witness)),
witnessKind(witnessKind), witness(witness),
hasExplicitFunctionType(functionType) {
assert(witness && "Differentiability witness must not be null");
#ifndef NDEBUG
if (functionType.hasValue()) {
assert(module.getStage() == SILStage::Lowered &&
"Explicit type is valid only in lowered SIL");
}
#endif
}
FunctionRefBaseInst::FunctionRefBaseInst(SILInstructionKind Kind,
SILDebugLocation DebugLoc,
SILFunction *F,
TypeExpansionContext context)
: LiteralInst(Kind, DebugLoc, F->getLoweredTypeInContext(context)), f(F) {
F->incrementRefCount();
}
void FunctionRefBaseInst::dropReferencedFunction() {
if (auto *Function = getInitiallyReferencedFunction())
Function->decrementRefCount();
f = nullptr;
}
FunctionRefBaseInst::~FunctionRefBaseInst() {
if (getInitiallyReferencedFunction())
getInitiallyReferencedFunction()->decrementRefCount();
}
FunctionRefInst::FunctionRefInst(SILDebugLocation Loc, SILFunction *F,
TypeExpansionContext context)
: FunctionRefBaseInst(SILInstructionKind::FunctionRefInst, Loc, F,
context) {
assert(!F->isDynamicallyReplaceable());
}
DynamicFunctionRefInst::DynamicFunctionRefInst(SILDebugLocation Loc,
SILFunction *F,
TypeExpansionContext context)
: FunctionRefBaseInst(SILInstructionKind::DynamicFunctionRefInst, Loc, F,
context) {
assert(F->isDynamicallyReplaceable());
}
PreviousDynamicFunctionRefInst::PreviousDynamicFunctionRefInst(
SILDebugLocation Loc, SILFunction *F, TypeExpansionContext context)
: FunctionRefBaseInst(SILInstructionKind::PreviousDynamicFunctionRefInst,
Loc, F, context) {
assert(!F->isDynamicallyReplaceable());
}
AllocGlobalInst::AllocGlobalInst(SILDebugLocation Loc,
SILGlobalVariable *Global)
: InstructionBase(Loc),
Global(Global) {}
GlobalAddrInst::GlobalAddrInst(SILDebugLocation DebugLoc,
SILGlobalVariable *Global,
TypeExpansionContext context)
: InstructionBase(DebugLoc,
Global->getLoweredTypeInContext(context).getAddressType(),
Global) {}
GlobalValueInst::GlobalValueInst(SILDebugLocation DebugLoc,
SILGlobalVariable *Global,
TypeExpansionContext context)
: InstructionBase(DebugLoc,
Global->getLoweredTypeInContext(context).getObjectType(),
Global) {}
const IntrinsicInfo &BuiltinInst::getIntrinsicInfo() const {
return getModule().getIntrinsicInfo(getName());
}
const BuiltinInfo &BuiltinInst::getBuiltinInfo() const {
return getModule().getBuiltinInfo(getName());
}
static unsigned getWordsForBitWidth(unsigned bits) {
return ((bits + llvm::APInt::APINT_BITS_PER_WORD - 1)
/ llvm::APInt::APINT_BITS_PER_WORD);
}
template<typename INST>
static void *allocateLiteralInstWithTextSize(SILModule &M, unsigned length) {
return M.allocateInst(sizeof(INST) + length, alignof(INST));
}
template<typename INST>
static void *allocateLiteralInstWithBitSize(SILModule &M, unsigned bits) {
unsigned words = getWordsForBitWidth(bits);
return M.allocateInst(
sizeof(INST) + sizeof(llvm::APInt::WordType)*words, alignof(INST));
}
IntegerLiteralInst::IntegerLiteralInst(SILDebugLocation Loc, SILType Ty,
const llvm::APInt &Value)
: InstructionBase(Loc, Ty) {
SILNode::Bits.IntegerLiteralInst.numBits = Value.getBitWidth();
std::uninitialized_copy_n(Value.getRawData(), Value.getNumWords(),
getTrailingObjects<llvm::APInt::WordType>());
}
IntegerLiteralInst *IntegerLiteralInst::create(SILDebugLocation Loc,
SILType Ty, const APInt &Value,
SILModule &M) {
#ifndef NDEBUG
if (auto intTy = Ty.getAs<BuiltinIntegerType>()) {
assert(intTy->getGreatestWidth() == Value.getBitWidth() &&
"IntegerLiteralInst APInt value's bit width doesn't match type");
} else {
assert(Ty.is<BuiltinIntegerLiteralType>());
assert(Value.getBitWidth() == Value.getMinSignedBits());
}
#endif
void *buf = allocateLiteralInstWithBitSize<IntegerLiteralInst>(M,
Value.getBitWidth());
return ::new (buf) IntegerLiteralInst(Loc, Ty, Value);
}
static APInt getAPInt(AnyBuiltinIntegerType *anyIntTy, intmax_t value) {
// If we're forming a fixed-width type, build using the greatest width.
if (auto intTy = dyn_cast<BuiltinIntegerType>(anyIntTy))
return APInt(intTy->getGreatestWidth(), value);
// Otherwise, build using the size of the type and then truncate to the
// minimum width necessary.
APInt result(8 * sizeof(value), value, /*signed*/ true);
result = result.trunc(result.getMinSignedBits());
return result;
}
IntegerLiteralInst *IntegerLiteralInst::create(SILDebugLocation Loc,
SILType Ty, intmax_t Value,
SILModule &M) {
auto intTy = Ty.castTo<AnyBuiltinIntegerType>();
return create(Loc, Ty, getAPInt(intTy, Value), M);
}
static SILType getGreatestIntegerType(Type type, SILModule &M) {
if (auto intTy = type->getAs<BuiltinIntegerType>()) {
return SILType::getBuiltinIntegerType(intTy->getGreatestWidth(),
M.getASTContext());
} else {
assert(type->is<BuiltinIntegerLiteralType>());
return SILType::getBuiltinIntegerLiteralType(M.getASTContext());