-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSILGenLValue.cpp
1335 lines (1125 loc) · 50.3 KB
/
SILGenLValue.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
//===--- SILGenLValue.cpp - Constructs logical lvalues for SILGen ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Emission of l-value expressions and basic operations on them.
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "LValue.h"
#include "RValue.h"
#include "Scope.h"
#include "Initialization.h"
#include "swift/AST/AST.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/Support/raw_ostream.h"
#include "ASTVisitor.h"
using namespace swift;
using namespace Lowering;
//===----------------------------------------------------------------------===//
/// A pending writeback.
namespace swift {
namespace Lowering {
/// Materialize - Represents a temporary allocation.
struct LLVM_LIBRARY_VISIBILITY Materialize {
/// The address of the allocation.
SILValue address;
/// The cleanup to dispose of the value before deallocating the buffer.
/// This cleanup can be killed by calling the consume method.
CleanupHandle valueCleanup;
/// Load and claim ownership of the value in the buffer. Does not deallocate
/// the buffer.
ManagedValue claim(SILGenFunction &gen, SILLocation loc);
};
struct LLVM_LIBRARY_VISIBILITY LValueWriteback {
SILLocation loc;
std::unique_ptr<LogicalPathComponent> component;
ManagedValue base;
Materialize temp;
~LValueWriteback() {}
LValueWriteback(LValueWriteback&&) = default;
LValueWriteback &operator=(LValueWriteback&&) = default;
LValueWriteback() = default;
LValueWriteback(SILLocation loc, std::unique_ptr<LogicalPathComponent> &&comp,
ManagedValue base, Materialize temp)
: loc(loc), component(std::move(comp)), base(base), temp(temp) {
}
};
}
}
std::vector<LValueWriteback> &SILGenFunction::getWritebackStack() {
if (!WritebackStack)
WritebackStack = new std::vector<LValueWriteback>();
return *WritebackStack;
}
void SILGenFunction::freeWritebackStack() {
delete WritebackStack;
}
Materialize SILGenFunction::emitMaterialize(SILLocation loc, ManagedValue v) {
// Address-only values are already materialized.
if (v.getType().isAddress()) {
assert(v.getType().isAddressOnly(SGM.M) && "can't materialize an l-value");
return Materialize{v.getValue(), v.getCleanup()};
}
assert(!v.isLValue() && "materializing a non-address-only lvalue?!");
auto &lowering = getTypeLowering(v.getType().getSwiftType());
// We don't use getBufferForExprResult here because the result of a
// materialization is *not* the value, but an address of the value.
SILValue tmpMem = emitTemporaryAllocation(loc, v.getType());
v.forwardInto(*this, loc, tmpMem);
CleanupHandle valueCleanup = CleanupHandle::invalid();
if (!lowering.isTrivial())
valueCleanup = enterDestroyCleanup(tmpMem);
return Materialize{tmpMem, valueCleanup};
}
//===----------------------------------------------------------------------===//
static CanType getSubstFormalRValueType(Expr *expr) {
return expr->getType()->getRValueType()->getCanonicalType();
}
static AbstractionPattern getOrigFormalRValueType(Type formalStorageType) {
auto type = formalStorageType->getCanonicalType();
if (auto ref = dyn_cast<ReferenceStorageType>(type)) {
type = ref.getReferentType();
if (isa<WeakStorageType>(ref))
type = OptionalType::get(type)->getCanonicalType();
}
return AbstractionPattern(type);
}
/// Return the LValueTypeData for the formal type of a declaration
/// that needs no substitutions.
static LValueTypeData getUnsubstitutedTypeData(SILGenFunction &gen,
CanType formalRValueType) {
return {
AbstractionPattern(formalRValueType),
formalRValueType,
gen.getLoweredType(formalRValueType),
};
}
static LValueTypeData getMemberTypeData(SILGenFunction &gen,
Type memberStorageType,
Expr *lvalueExpr) {
auto origFormalType = getOrigFormalRValueType(memberStorageType);
auto substFormalType = getSubstFormalRValueType(lvalueExpr);
return {
origFormalType,
substFormalType,
gen.getLoweredType(origFormalType, substFormalType)
};
}
/// SILGenLValue - An ASTVisitor for building logical lvalues.
class LLVM_LIBRARY_VISIBILITY SILGenLValue
: public Lowering::ExprVisitor<SILGenLValue, LValue>
{
public:
SILGenFunction &gen;
SILGenLValue(SILGenFunction &gen) : gen(gen) {}
LValue visitRec(Expr *e);
/// Dummy handler to log unimplemented nodes.
LValue visitExpr(Expr *e);
// Nodes that form the root of lvalue paths
LValue visitDeclRefExpr(DeclRefExpr *e);
// Nodes that make up components of lvalue paths
LValue visitMemberRefExpr(MemberRefExpr *e);
LValue visitSubscriptExpr(SubscriptExpr *e);
LValue visitTupleElementExpr(TupleElementExpr *e);
LValue visitLValueConversionExpr(LValueConversionExpr *e);
// Expressions that wrap lvalues
LValue visitInOutExpr(InOutExpr *e);
LValue visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *e);
};
SILValue LogicalPathComponent::getMaterialized(SILGenFunction &gen,
SILLocation loc,
ManagedValue base) const {
// If the writeback is disabled, just emit a load into a temporary memory
// location.
if (!gen.InWritebackScope) {
ManagedValue value = get(gen, loc, base, SGFContext());
return gen.emitMaterialize(loc, value).address;
}
// Otherwise, we need to emit a get and set. The get operation will consume
// the base's +1, so copy the base for the setter.
ManagedValue getterBase = base;
if (base && base.hasCleanup())
getterBase = base.copy(gen, loc);
ManagedValue value = get(gen, loc, getterBase, SGFContext());
Materialize temp = gen.emitMaterialize(loc, value);
gen.getWritebackStack().emplace_back(loc, clone(gen, loc), base, temp);
return temp.address;
}
ManagedValue Materialize::claim(SILGenFunction &gen, SILLocation loc) {
auto &addressTL = gen.getTypeLowering(address.getType());
if (addressTL.isAddressOnly()) {
// We can use the temporary as an address-only rvalue directly.
return ManagedValue(address, valueCleanup);
}
// A materialized temporary is always its own type-of-rvalue because
// we did a semantic load to produce it in the first place.
if (valueCleanup.isValid())
gen.Cleanups.setCleanupState(valueCleanup, CleanupState::Dead);
return gen.emitLoad(loc, address, addressTL, SGFContext(), IsTake);
}
WritebackScope::WritebackScope(SILGenFunction &g)
: gen(&g), wasInWritebackScope(g.InWritebackScope),
savedDepth(g.getWritebackStack().size())
{
// If we're in an inout conversion scope, disable nested writeback scopes.
if (g.InInOutConversionScope) {
gen = nullptr;
return;
}
g.InWritebackScope = true;
}
WritebackScope::~WritebackScope() {
if (!gen)
return;
gen->InWritebackScope = wasInWritebackScope;
auto i = gen->getWritebackStack().end(),
deepest = gen->getWritebackStack().begin() + savedDepth;
while (i-- > deepest) {
ManagedValue mv = i->temp.claim(*gen, i->loc);
auto formalTy = i->component->getSubstFormalType();
i->component->set(*gen, i->loc, RValue(*gen, i->loc, formalTy, mv),
i->base);
}
gen->getWritebackStack().erase(deepest, gen->getWritebackStack().end());
}
WritebackScope::WritebackScope(WritebackScope &&o)
: gen(o.gen),
wasInWritebackScope(o.wasInWritebackScope),
savedDepth(o.savedDepth)
{
o.gen = nullptr;
}
WritebackScope &WritebackScope::operator=(WritebackScope &&o) {
gen = o.gen;
wasInWritebackScope = o.wasInWritebackScope;
savedDepth = o.savedDepth;
o.gen = nullptr;
return *this;
}
InOutConversionScope::InOutConversionScope(SILGenFunction &gen)
: gen(gen)
{
assert(gen.InWritebackScope
&& "inout conversions should happen in writeback scopes");
assert(!gen.InInOutConversionScope
&& "inout conversions should not be nested");
gen.InInOutConversionScope = true;
}
InOutConversionScope::~InOutConversionScope() {
assert(gen.InInOutConversionScope && "already exited conversion scope?!");
gen.InInOutConversionScope = false;
}
void PathComponent::_anchor() {}
void PhysicalPathComponent::_anchor() {}
void LogicalPathComponent::_anchor() {}
/// Return the LValueTypeData for a value whose type is its own
/// lowering.
static LValueTypeData getValueTypeData(SILValue value) {
assert(value.getType().isObject() ||
value.getType().getSwiftRValueType()->isExistentialType() ||
value.getType().getSwiftRValueType()->is<ArchetypeType>());
return {
AbstractionPattern(value.getType().getSwiftRValueType()),
value.getType().getSwiftRValueType(),
value.getType()
};
}
namespace {
class RefElementComponent : public PhysicalPathComponent {
VarDecl *Field;
SILType SubstFieldType;
public:
RefElementComponent(VarDecl *field, SILType substFieldType,
LValueTypeData typeData)
: PhysicalPathComponent(typeData),
Field(field), SubstFieldType(substFieldType) {}
ManagedValue offset(SILGenFunction &gen, SILLocation loc, ManagedValue base)
const override
{
assert(base.getType().isObject() &&
"base for ref element component must be an object");
assert(base.getType().hasReferenceSemantics() &&
"base for ref element component must be a reference type");
auto Res = gen.B.createRefElementAddr(loc, base.getValue(), Field,
SubstFieldType);
return ManagedValue::forLValue(Res);
}
};
class TupleElementComponent : public PhysicalPathComponent {
unsigned ElementIndex;
public:
TupleElementComponent(unsigned elementIndex, LValueTypeData typeData)
: PhysicalPathComponent(typeData), ElementIndex(elementIndex) {}
ManagedValue offset(SILGenFunction &gen, SILLocation loc,
ManagedValue base) const override {
assert(base && "invalid value for element base");
auto Res = gen.B.createTupleElementAddr(loc, base.getUnmanagedValue(),
ElementIndex,
getTypeOfRValue().getAddressType());
return ManagedValue::forLValue(Res);
}
};
class StructElementComponent : public PhysicalPathComponent {
VarDecl *Field;
SILType SubstFieldType;
public:
StructElementComponent(VarDecl *field, SILType substFieldType,
LValueTypeData typeData)
: PhysicalPathComponent(typeData),
Field(field), SubstFieldType(substFieldType) {}
ManagedValue offset(SILGenFunction &gen, SILLocation loc,
ManagedValue base) const override {
assert(base && "invalid value for element base");
auto Res = gen.B.createStructElementAddr(loc, base.getUnmanagedValue(),
Field, SubstFieldType);
return ManagedValue::forLValue(Res);
}
};
class ValueComponent : public PhysicalPathComponent {
ManagedValue Value;
public:
ValueComponent(ManagedValue value, LValueTypeData typeData) :
PhysicalPathComponent(typeData),
Value(value) {
}
ManagedValue offset(SILGenFunction &gen, SILLocation loc,
ManagedValue base) const override {
assert(!base && "value component must be root of lvalue path");
return Value;
}
};
class GetterSetterComponent : public LogicalPathComponent {
// The VarDecl or SubscriptDecl being get/set.
AbstractStorageDecl *decl;
bool IsSuper;
std::vector<Substitution> substitutions;
Expr *subscriptIndexExpr;
mutable RValue origSubscripts;
struct AccessorArgs {
RValueSource base;
RValue subscripts;
};
/// Returns a tuple of RValues holding the accessor value, base (retained if
/// necessary), and subscript arguments, in that order.
AccessorArgs
prepareAccessorArgs(SILGenFunction &gen, SILLocation loc,
ManagedValue base, AbstractFunctionDecl *funcDecl) const
{
AccessorArgs result;
if (base)
result.base = gen.prepareAccessorBaseArg(loc, base, funcDecl);
if (subscriptIndexExpr) {
if (!origSubscripts)
origSubscripts = gen.emitRValue(subscriptIndexExpr);
// TODO: use the subscript expression as the source if we're
// only using this l-value once.
result.subscripts = origSubscripts.copy(gen, loc);
}
return result;
}
public:
GetterSetterComponent(AbstractStorageDecl *decl,
bool isSuper,
ArrayRef<Substitution> substitutions,
LValueTypeData typeData,
Expr *subscriptIndexExpr = nullptr)
: LogicalPathComponent(typeData),
decl(decl),
IsSuper(isSuper),
substitutions(substitutions.begin(), substitutions.end()),
subscriptIndexExpr(subscriptIndexExpr)
{
}
GetterSetterComponent(const GetterSetterComponent &copied,
SILGenFunction &gen,
SILLocation loc)
: LogicalPathComponent(copied.getTypeData()),
decl(copied.decl),
IsSuper(copied.IsSuper),
substitutions(copied.substitutions),
subscriptIndexExpr(copied.subscriptIndexExpr),
origSubscripts(copied.origSubscripts.copy(gen, loc))
{
}
void set(SILGenFunction &gen, SILLocation loc,
RValue &&value, ManagedValue base) const override {
// Pass in just the setter.
auto args = prepareAccessorArgs(gen, loc, base, decl->getSetter());
return gen.emitSetAccessor(loc, decl, substitutions,
std::move(args.base), IsSuper,
std::move(args.subscripts),
std::move(value));
}
ManagedValue get(SILGenFunction &gen, SILLocation loc,
ManagedValue base, SGFContext c) const override {
auto args = prepareAccessorArgs(gen, loc, base, decl->getGetter());
return gen.emitGetAccessor(loc, decl, substitutions,
std::move(args.base), IsSuper,
std::move(args.subscripts), c);
}
std::unique_ptr<LogicalPathComponent>
clone(SILGenFunction &gen, SILLocation loc) const override {
LogicalPathComponent *clone = new GetterSetterComponent(*this, gen, loc);
return std::unique_ptr<LogicalPathComponent>(clone);
}
};
/// Convert an lvalue to a different type through a pair of conversion
/// functions.
class LValueConversionComponent : public LogicalPathComponent {
LValueConversionExpr *Conversion;
public:
LValueConversionComponent(LValueConversionExpr *E,
LValueTypeData typeData)
: LogicalPathComponent(typeData),
Conversion(E)
{}
ManagedValue get(SILGenFunction &gen, SILLocation loc,
ManagedValue orig, SGFContext c) const override {
// Load the original value.
ManagedValue origVal = gen.emitLoad(loc, orig.getValue(),
gen.getTypeLowering(orig.getType()),
SGFContext(),
IsNotTake);
// Apply the "from" conversion.
auto origTy = Conversion->getSubExpr()->getType()
->getLValueOrInOutObjectType()
->getCanonicalType();
return gen.emitApplyConversionFunction(loc,
Conversion->getFromConversionFn(),
Conversion->getType()->getLValueOrInOutObjectType(),
RValue(gen, loc, origTy, origVal));
}
void set(SILGenFunction &gen, SILLocation loc,
RValue &&value, ManagedValue origAddr) const override {
// Apply the "to" conversion.
ManagedValue convertedVal = gen.emitApplyConversionFunction(loc,
Conversion->getToConversionFn(),
Conversion->getSubExpr()->getType()->getLValueOrInOutObjectType(),
std::move(value));
// Store back to the original value.
convertedVal.assignInto(gen, loc, origAddr.getValue());
}
std::unique_ptr<LogicalPathComponent>
clone(SILGenFunction &gen, SILLocation loc) const override {
LogicalPathComponent *clone
= new LValueConversionComponent(Conversion, getTypeData());
return std::unique_ptr<LogicalPathComponent>(clone);
}
};
/// Remap an lvalue referencing a generic type to an lvalue of its substituted
/// type in a concrete context.
class OrigToSubstComponent : public LogicalPathComponent {
AbstractionPattern origType;
CanType substType;
public:
OrigToSubstComponent(SILGenFunction &gen,
AbstractionPattern origType, CanType substType)
: LogicalPathComponent(getUnsubstitutedTypeData(gen, substType)),
origType(origType), substType(substType)
{}
void set(SILGenFunction &gen, SILLocation loc,
RValue &&value, ManagedValue base) const override {
// Map the value to the original abstraction level.
ManagedValue mv = std::move(value).getAsSingleValue(gen, loc);
mv = gen.emitSubstToOrigValue(loc, mv, origType, substType);
// Store to the base.
mv.assignInto(gen, loc, base.getValue());
}
ManagedValue get(SILGenFunction &gen, SILLocation loc,
ManagedValue base, SGFContext c) const override {
// Load the original value.
ManagedValue baseVal = gen.emitLoad(loc, base.getValue(),
gen.getTypeLowering(base.getType()),
SGFContext(),
IsNotTake);
// Map the base value to its substituted representation.
return gen.emitOrigToSubstValue(loc, baseVal,
origType, substType, c);
}
std::unique_ptr<LogicalPathComponent>
clone(SILGenFunction &gen, SILLocation loc) const override {
LogicalPathComponent *clone
= new OrigToSubstComponent(gen, origType, substType);
return std::unique_ptr<LogicalPathComponent>(clone);
}
};
}
LValue SILGenFunction::emitLValue(Expr *e) {
LValue r = SILGenLValue(*this).visit(e);
// If the final component is physical with an abstraction change, introduce a
// reabstraction component.
if (r.isLastComponentPhysical()
&& getTypeLowering(r.getSubstFormalType()).getLoweredType()
!= r.getTypeOfRValue()) {
r.add<OrigToSubstComponent>(*this, r.getOrigFormalType(),
r.getSubstFormalType());
}
return r;
}
LValue SILGenLValue::visitRec(Expr *e) {
// Non-lvalue types (references, values, metatypes, etc) form the root of a
// logical l-value.
if (!e->getType()->is<LValueType>() && !e->getType()->is<InOutType>()) {
// Calls through protocols can be done with +0 rvalues. This allows us to
// avoid materializing copies of existentials.
SGFContext Ctx;
if (e->getType()->isExistentialType() || e->getType()->is<ArchetypeType>())
Ctx = SGFContext::AllowPlusZero;
ManagedValue rv = gen.emitRValueAsSingleValue(e, Ctx);
auto typeData = getValueTypeData(rv.getValue());
LValue lv;
lv.add<ValueComponent>(rv, typeData);
return lv;
}
return visit(e);
}
LValue SILGenLValue::visitExpr(Expr *e) {
e->dump(llvm::errs());
llvm_unreachable("unimplemented lvalue expr");
}
static LValue emitLValueForNonMemberVarDecl(SILGenFunction &gen,
SILLocation loc, VarDecl *var,
CanType formalRValueType,
bool isDirectPropertyAccess) {
LValue lv;
auto typeData = getUnsubstitutedTypeData(gen, formalRValueType);
// If it's a computed variable, push a reference to the getter and setter.
if (var->hasAccessorFunctions() && !isDirectPropertyAccess) {
ArrayRef<Substitution> substitutions;
if (auto genericParams
= gen.SGM.Types.getEffectiveGenericParamsForContext(
var->getDeclContext()))
substitutions = gen.buildForwardingSubstitutions(genericParams);
lv.add<GetterSetterComponent>(var, /*isSuper=*/false, substitutions,
typeData);
} else {
// If it's a physical value (e.g. a local variable in memory), push its
// address.
auto address = gen.emitLValueForDecl(loc, var, isDirectPropertyAccess);
assert(address.isLValue() &&
"physical lvalue decl ref must evaluate to an address");
lv.add<ValueComponent>(address, typeData);
}
return std::move(lv);
}
LValue SILGenLValue::visitDeclRefExpr(DeclRefExpr *e) {
// The only non-member decl that can be an lvalue is VarDecl.
return emitLValueForNonMemberVarDecl(gen, e, cast<VarDecl>(e->getDecl()),
getSubstFormalRValueType(e),
e->isDirectPropertyAccess());
}
LValue SILGenLValue::visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *e){
// If it is convenient to avoid loading the base, don't bother loading it.
gen.emitRValue(e->getLHS(), SGFContext::AllowPlusZero);
return visitRec(e->getRHS());
}
LValue SILGenLValue::visitMemberRefExpr(MemberRefExpr *e) {
LValue lv = visitRec(e->getBase());
// MemberRefExpr can refer to type and function members, but the only case
// that can be an lvalue is a VarDecl.
VarDecl *var = cast<VarDecl>(e->getMember().getDecl());
LValueTypeData typeData = getMemberTypeData(gen, var->getType(), e);
// Use the property accessors if the variable has accessors and this isn't a
// direct access to underlying storage.
if (var->hasAccessorFunctions() && !e->isDirectPropertyAccess()) {
lv.add<GetterSetterComponent>(var, e->isSuper(),
e->getMember().getSubstitutions(), typeData);
return std::move(lv);
}
// Otherwise, the lvalue access is performed with a fragile element reference.
// Find the substituted storage type.
SILType varStorageType =
gen.SGM.Types.getSubstitutedStorageType(var, e->getType());
// For static variables, emit a reference to the global variable backing
// them.
// FIXME: This has to be dynamically looked up for classes, and
// dynamically instantiated for generics.
if (var->isStatic()) {
auto baseMeta = e->getBase()->getType()->castTo<MetatypeType>()
->getInstanceType();
(void)baseMeta;
assert(!baseMeta->is<BoundGenericType>() &&
"generic static stored properties not implemented");
assert((baseMeta->getStructOrBoundGenericStruct() ||
baseMeta->getEnumOrBoundGenericEnum()) &&
"static stored properties for classes/protocols not implemented");
return emitLValueForNonMemberVarDecl(gen, e, var,
getSubstFormalRValueType(e),
e->isDirectPropertyAccess());
}
// For member variables, this access is done w.r.t. a base computation that
// was already emitted. This member is accessed off of it.
if (!e->getBase()->getType()->is<LValueType>()) {
assert(e->getBase()->getType()->hasReferenceSemantics());
lv.add<RefElementComponent>(var, varStorageType, typeData);
} else {
lv.add<StructElementComponent>(var, varStorageType, typeData);
}
return std::move(lv);
}
LValue SILGenLValue::visitSubscriptExpr(SubscriptExpr *e) {
auto decl = cast<SubscriptDecl>(e->getDecl().getDecl());
auto typeData = getMemberTypeData(gen, decl->getElementType(), e);
LValue lv = visitRec(e->getBase());
lv.add<GetterSetterComponent>(decl, e->isSuper(),
e->getDecl().getSubstitutions(),
typeData, e->getIndex());
return std::move(lv);
}
LValue SILGenLValue::visitTupleElementExpr(TupleElementExpr *e) {
unsigned index = e->getFieldNumber();
LValue lv = visitRec(e->getBase());
auto baseTypeData = lv.getTypeData();
LValueTypeData typeData = {
baseTypeData.OrigFormalType.getTupleElementType(index),
cast<TupleType>(baseTypeData.SubstFormalType).getElementType(index),
baseTypeData.TypeOfRValue.getTupleElementType(index)
};
lv.add<TupleElementComponent>(index, typeData);
return std::move(lv);
}
LValue SILGenLValue::visitLValueConversionExpr(LValueConversionExpr *e) {
LValue lv = visitRec(e->getSubExpr());
LValueTypeData typeData = getMemberTypeData(gen,
e->getType()->getLValueOrInOutObjectType(),
e);
lv.add<LValueConversionComponent>(e, typeData);
return std::move(lv);
}
LValue SILGenLValue::visitInOutExpr(InOutExpr *e) {
return visitRec(e->getSubExpr());
}
LValue SILGenFunction::emitDirectIVarLValue(SILLocation loc, ManagedValue base,
VarDecl *ivar) {
SILGenLValue sgl(*this);
LValue lv;
auto baseType = base.getType().getSwiftRValueType();
// Refer to 'self' as the base of the lvalue.
lv.add<ValueComponent>(base, getUnsubstitutedTypeData(*this, baseType));
auto origFormalType = getOrigFormalRValueType(ivar->getType());
auto substFormalType = ivar->getType()->getCanonicalType();
LValueTypeData typeData = { origFormalType, substFormalType,
getLoweredType(origFormalType, substFormalType) };
// Find the substituted storage type.
SILType varStorageType =
SGM.Types.getSubstitutedStorageType(ivar, LValueType::get(ivar->getType()));
if (baseType->hasReferenceSemantics())
lv.add<RefElementComponent>(ivar, varStorageType, typeData);
else
lv.add<StructElementComponent>(ivar, varStorageType, typeData);
return std::move(lv);
}
/// Load an r-value out of the given address.
///
/// \param rvalueTL - the type lowering for the type-of-rvalue
/// of the address
ManagedValue SILGenFunction::emitLoad(SILLocation loc, SILValue addr,
const TypeLowering &rvalueTL,
SGFContext C, IsTake_t isTake) {
// Get the lowering for the address type. We can avoid a re-lookup
// in the very common case of this being equivalent to the r-value
// type.
auto &addrTL =
(addr.getType() == rvalueTL.getLoweredType().getAddressType()
? rvalueTL : getTypeLowering(addr.getType()));
if (rvalueTL.isAddressOnly()) {
// If the client is cool with a +0 rvalue, the decl has an address-only
// type, and there are no conversions, then we can return this as a +0
// address RValue.
if (C.isPlusZeroOk() && rvalueTL.getLoweredType() ==addrTL.getLoweredType())
return ManagedValue::forUnmanaged(addr);
// Copy the address-only value.
SILValue copy = getBufferForExprResult(loc, rvalueTL.getLoweredType(), C);
emitSemanticLoadInto(loc, addr, addrTL, copy, rvalueTL,
isTake, IsInitialization);
return emitManagedRValueWithCleanup(copy, rvalueTL);
}
// Load the loadable value, and retain it if we aren't taking it.
SILValue loadedV = emitSemanticLoad(loc, addr, addrTL, rvalueTL, isTake);
return emitManagedRValueWithCleanup(loadedV, rvalueTL);
}
static void emitUnloweredStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue value, SILValue addr,
IsInitialization_t isInit) {
if (isInit)
B.createStore(loc, value, addr);
else
B.createAssign(loc, value, addr);
}
#ifndef NDEBUG
static bool hasDifferentTypeOfRValue(const TypeLowering &srcTL) {
return srcTL.getLoweredType().is<ReferenceStorageType>();
}
#endif
static Substitution getSimpleSubstitution(GenericParamList &generics,
CanType typeArg) {
assert(generics.getParams().size() == 1);
auto typeParamDecl = generics.getParams()[0].getAsTypeParam();
return Substitution{typeParamDecl->getArchetype(), typeArg, {}};
}
/// Create the correct substitution for calling the given function at
/// the given type.
static Substitution getSimpleSubstitution(FuncDecl *fn, CanType typeArg) {
auto polyFnType =
cast<PolymorphicFunctionType>(fn->getType()->getCanonicalType());
return getSimpleSubstitution(polyFnType->getGenericParams(), typeArg);
}
static CanType getOptionalValueType(SILType optType,
OptionalTypeKind &optionalKind) {
auto generic = cast<BoundGenericType>(optType.getSwiftRValueType());
optionalKind = generic->getDecl()->classifyAsOptionalType();
assert(optionalKind);
return generic.getGenericArgs()[0];
}
/// Emit code to convert the given possibly-null reference value into
/// a value of the corresponding optional type.
static SILValue emitRefToOptional(SILGenFunction &gen, SILLocation loc,
SILValue ref, const TypeLowering &optTL) {
// TODO: we should probably emit this as a call to a helper function
// that does this, because (1) this is a lot of code and (2) it's
// dumb to redundantly emit and optimize it.
auto isNullBB = gen.createBasicBlock();
auto isNonNullBB = gen.createBasicBlock();
auto contBB = gen.createBasicBlock();
SILValue resultAddr =
gen.emitTemporaryAllocation(loc, optTL.getLoweredType());
CanType refType = ref.getType().getSwiftRValueType();
assert(refType.hasReferenceSemantics());
// Ask whether the value is null.
auto isNonNull = gen.B.createIsNonnull(loc, ref);
gen.B.createCondBranch(loc, isNonNull, isNonNullBB, isNullBB);
// If it's non-null, use _injectValueIntoOptional.
gen.B.emitBlock(isNonNullBB);
{
FullExpr scope(gen.Cleanups, CleanupLocation::getCleanupLocation(loc));
RValueSource value(loc, RValue(ManagedValue::forUnmanaged(ref), refType));
gen.emitInjectOptionalValueInto(loc, std::move(value), resultAddr, optTL);
}
gen.B.createBranch(loc, contBB);
// If it's null, use _injectNothingIntoOptional.
gen.B.emitBlock(isNullBB);
gen.emitInjectOptionalNothingInto(loc, resultAddr, optTL);
gen.B.createBranch(loc, contBB);
// Continue.
gen.B.emitBlock(contBB);
auto result = gen.B.createLoad(loc, resultAddr);
return result;
}
/// Emit code to convert the givenvalue of optional type into a
/// possibly-null reference value.
static SILValue emitOptionalToRef(SILGenFunction &gen, SILLocation loc,
SILValue opt, const TypeLowering &optTL,
SILType refType) {
// TODO: we should probably emit this as a call to a helper function
// that does this, because (1) this is a lot of code and (2) it's
// dumb to redundantly emit and optimize it.
auto isNotPresentBB = gen.createBasicBlock();
auto isPresentBB = gen.createBasicBlock();
auto contBB = gen.createBasicBlock();
auto optType = opt.getType();
assert(optType == optTL.getLoweredType());
// This assertion might be unreasonable in the short term.
assert(!optType.isAddress() &&
"Optional<T> is address-only for reference type T?");
assert(!refType.isAddress());
assert(refType.hasReferenceSemantics());
// Make an argument on contBB.
auto result = new (gen.SGM.M) SILArgument(refType, contBB);
// Materialize the optional value so we can pass it inout to
// _doesOptionalHaveValue. Really, we just want to pass it +0.
auto allocation = gen.B.createAllocStack(loc, optType);
// Note that our SIL-generation patterns here assume that these
// library intrinsic functions won't throw.
auto optAddr = allocation->getAddressResult();
gen.B.createStore(loc, opt, optAddr);
// Ask whether the value is present.
auto isPresent = gen.emitDoesOptionalHaveValue(loc, optAddr);
gen.B.createCondBranch(loc, isPresent, isPresentBB, isNotPresentBB);
// If it's present, use _getOptionalValue.
gen.B.emitBlock(isPresentBB);
SILValue refValue;
{
FullExpr scope(gen.Cleanups, CleanupLocation::getCleanupLocation(loc));
auto managedOptAddr = ManagedValue::forUnmanaged(optAddr);
refValue = gen.emitGetOptionalValueFrom(loc, managedOptAddr, optTL,
SGFContext()).forward(gen);
assert(refValue.getType().isObject());
}
gen.B.createBranch(loc, contBB, refValue);
// If it's not present, just create a null value.
gen.B.emitBlock(isNotPresentBB);
// %1 = integer_literal $Builtin.Word, 0
auto WordTy = SILType::getBuiltinWordType(gen.getASTContext());
SILValue null = gen.B.createIntegerLiteral(loc, WordTy, 0);
// %2 = builtin_function_ref "inttoptr_Word" : $@thin (Word) -> RawPointer
auto bfrInfo = SILFunctionType::ExtInfo(AbstractCC::Freestanding,
/*thin*/ true,
/*noreturn*/ false,
/*autoclosure*/ false,
/*block*/ false);
SILParameterInfo Param(WordTy.getSwiftRValueType(),
ParameterConvention::Direct_Unowned);
SILResultInfo Result(gen.getASTContext().TheRawPointerType,
ResultConvention::Unowned);
auto bfrFnType = SILFunctionType::get(nullptr, bfrInfo,
ParameterConvention::Direct_Owned,
Param, Result,
gen.getASTContext());
auto bfr = gen.B.createBuiltinFunctionRef(loc, "inttoptr_Word",
SILType::getPrimitiveObjectType(bfrFnType));
// %3 = apply %2(%1) : $@thin (Builtin.Word) -> Builtin.RawPointer
null = gen.B.createApply(loc, bfr, null);
null = gen.B.createRawPointerToRef(loc, null, refType);
gen.B.emitReleaseValueOperation(loc, opt); // destroy the nothing value
gen.B.createBranch(loc, contBB, null);
// Continue.
gen.B.emitBlock(contBB);
gen.B.createDeallocStack(CleanupLocation::getCleanupLocation(loc),
allocation->getContainerResult());
return result;
}
void SILGenFunction::emitInjectOptionalValueInto(SILLocation loc,
RValueSource &&value,
SILValue dest,
const TypeLowering &optTL) {
SILType optType = optTL.getLoweredType();
OptionalTypeKind optionalKind;
CanType valueType = getOptionalValueType(optType, optionalKind);
FuncDecl *fn =
getASTContext().getInjectValueIntoOptionalDecl(nullptr, optionalKind);
Substitution sub = getSimpleSubstitution(fn, valueType);
// Materialize the r-value into a temporary.
FullExpr scope(Cleanups, CleanupLocation::getCleanupLocation(loc));
auto valueAddr = std::move(value).materialize(*this,
AbstractionPattern(CanType(sub.Archetype)));
TemporaryInitialization emitInto(dest, CleanupHandle::invalid());
auto result = emitApplyOfLibraryIntrinsic(loc, fn, sub, valueAddr,
SGFContext(&emitInto));
assert(result.isInContext() && "didn't emit directly into buffer?");
(void)result;
}
void SILGenFunction::emitInjectOptionalNothingInto(SILLocation loc,
SILValue dest,
const TypeLowering &optTL) {
SILType optType = optTL.getLoweredType();
OptionalTypeKind optionalKind;
CanType valueType = getOptionalValueType(optType, optionalKind);
FuncDecl *fn =
getASTContext().getInjectNothingIntoOptionalDecl(nullptr, optionalKind);
Substitution sub = getSimpleSubstitution(fn, valueType);
TemporaryInitialization emitInto(dest, CleanupHandle::invalid());
auto result = emitApplyOfLibraryIntrinsic(loc, fn, sub, {},
SGFContext(&emitInto));
assert(result.isInContext() && "didn't emit directly into buffer?");
(void)result;
}
SILValue SILGenFunction::emitDoesOptionalHaveValue(SILLocation loc,
SILValue addr) {
SILType optType = addr.getType().getObjectType();
OptionalTypeKind optionalKind;
CanType valueType = getOptionalValueType(optType, optionalKind);
FuncDecl *fn =
getASTContext().getDoesOptionalHaveValueDecl(nullptr, optionalKind);
Substitution sub = getSimpleSubstitution(fn, valueType);
// The argument to _doesOptionalHaveValue is passed by reference.
return emitApplyOfLibraryIntrinsic(loc, fn, sub,
ManagedValue::forUnmanaged(addr),
SGFContext())
.getUnmanagedValue();
}