-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenFunction.h
3275 lines (2789 loc) · 143 KB
/
SILGenFunction.h
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
//===--- SILGenFunction.h - Function Specific AST lower context -*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SILGEN_SILGENFUNCTION_H
#define SWIFT_SILGEN_SILGENFUNCTION_H
#include "FormalEvaluation.h"
#include "Initialization.h"
#include "InitializeDistActorIdentity.h"
#include "JumpDest.h"
#include "RValue.h"
#include "SGFContext.h"
#include "SILGen.h"
#include "SILGenBuilder.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/NoDiscard.h"
#include "swift/Basic/ProfileCounter.h"
#include "swift/Basic/Statistic.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILType.h"
#include "llvm/ADT/PointerIntPair.h"
namespace swift {
class ParameterList;
class ProfileCounterRef;
namespace Lowering {
class ArgumentSource;
class Condition;
class Conversion;
class ConsumableManagedValue;
class LogicalPathComponent;
class LValue;
class ManagedValue;
class PreparedArguments;
class RValue;
class CalleeTypeInfo;
class ResultPlan;
using ResultPlanPtr = std::unique_ptr<ResultPlan>;
class ArgumentScope;
class Scope;
class ExecutorBreadcrumb;
struct LValueOptions {
bool IsNonAccessing = false;
bool TryAddressable = false;
/// Derive options for accessing the base of an l-value, given that
/// applying the derived component might touch the memory.
LValueOptions forComputedBaseLValue() const {
auto copy = *this;
// Assume we're going to access the base.
copy.IsNonAccessing = false;
return copy;
}
/// Derive options for accessing the base of an l-value, given that
/// applying the derived component will not touch the memory.
LValueOptions forProjectedBaseLValue() const {
auto copy = *this;
return copy;
}
LValueOptions withAddressable(bool addressable) const {
auto copy = *this;
copy.TryAddressable = addressable;
return copy;
}
};
class PatternMatchContext;
/// A formal section of the function. This is a SILGen-only concept,
/// meant to improve locality. It's only reflected in the generated
/// SIL implicitly.
enum class FunctionSection : bool {
/// The section of the function dedicated to ordinary control flow.
Ordinary,
/// The section of the function dedicated to error-handling and
/// similar things.
Postmatter,
};
/// Parameter to \c SILGenFunction::emitCaptures that indicates what the
/// capture parameters are being emitted for.
enum class CaptureEmission {
/// Captures are being emitted for immediate application to a local function.
ImmediateApplication,
/// Captures are being emitted for partial application to form a closure
/// value.
PartialApplication,
/// Captures are being emitted for partial application of a local property
/// wrapper setter for assign_by_wrapper. Captures are guaranteed to not
/// escape, because assign_by_wrapper will not use the setter if the captured
/// variable is not initialized.
AssignByWrapper,
};
/// Different ways in which an l-value can be emitted.
enum class SGFAccessKind : uint8_t {
/// The access is a read whose result will be ignored.
IgnoredRead,
/// The access is a read that would prefer the address of a borrowed value.
/// This should only be used when it is semantically acceptable to borrow
/// the value, not just because the caller would benefit from a borrowed
/// value. See shouldEmitSelfAsRValue in SILGenLValue.cpp.
///
/// The caller will be calling emitAddressOfLValue or emitLoadOfLValue
/// on the l-value. The latter may be less efficient than an access
/// would be if the l-value had been emitted with an owned-read kind.
BorrowedAddressRead,
/// The access is a read that would prefer a loaded borrowed value.
/// This should only be used when it is semantically acceptable to borrow
/// the value, not just because the caller would benefit from a borrowed
/// value. See shouldEmitSelfAsRValue in SILGenLValue.cpp.
///
/// There isn't yet a way to emit the access that takes advantage of this.
BorrowedObjectRead,
/// The access is a read that would prefer the address of an owned value.
///
/// The caller will be calling emitAddressOfLValue or emitLoadOfLValue
/// on the l-value.
OwnedAddressRead,
/// The access is a read that would prefer a loaded owned value.
///
/// The caller will be calling emitLoadOfLValue on the l-value.
OwnedObjectRead,
/// The access is an assignment (or maybe an initialization).
///
/// The caller will be calling emitAssignToLValue on the l-value.
Write,
/// The access is a read-modify-write.
///
/// The caller will be calling emitAddressOfLValue on the l-value.
ReadWrite,
/// The access is a consuming operation that would prefer a loaded address
/// value. The lvalue will subsequently be left in an uninitialized state.
///
/// The caller will be calling emitAddressOfLValue and then load from the
/// l-value.
OwnedAddressConsume,
/// The access is a consuming operation that would prefer a loaded owned
/// value. The lvalue will subsequently be left in an uninitialized state.
///
/// The caller will be calling emitAddressOfLValue and then load from the
/// l-value.
OwnedObjectConsume,
};
static inline bool isBorrowAccess(SGFAccessKind kind) {
switch (kind) {
case SGFAccessKind::IgnoredRead:
case SGFAccessKind::BorrowedAddressRead:
case SGFAccessKind::BorrowedObjectRead:
return true;
case SGFAccessKind::OwnedAddressRead:
case SGFAccessKind::OwnedObjectRead:
case SGFAccessKind::Write:
case SGFAccessKind::ReadWrite:
case SGFAccessKind::OwnedAddressConsume:
case SGFAccessKind::OwnedObjectConsume:
return false;
}
}
static inline bool isReadAccess(SGFAccessKind kind) {
return uint8_t(kind) <= uint8_t(SGFAccessKind::OwnedObjectRead);
}
static inline bool isConsumeAccess(SGFAccessKind kind) {
switch (kind) {
case SGFAccessKind::IgnoredRead:
case SGFAccessKind::BorrowedAddressRead:
case SGFAccessKind::BorrowedObjectRead:
case SGFAccessKind::OwnedAddressRead:
case SGFAccessKind::OwnedObjectRead:
case SGFAccessKind::Write:
case SGFAccessKind::ReadWrite:
return false;
case SGFAccessKind::OwnedAddressConsume:
case SGFAccessKind::OwnedObjectConsume:
return true;
}
}
/// Given a read access kind, does it require an owned result?
static inline bool isReadAccessResultOwned(SGFAccessKind kind) {
assert(isReadAccess(kind));
return uint8_t(kind) >= uint8_t(SGFAccessKind::OwnedAddressRead);
}
/// Given a read access kind, does it require an address result?
static inline bool isReadAccessResultAddress(SGFAccessKind kind) {
assert(isReadAccess(kind));
return kind == SGFAccessKind::BorrowedAddressRead ||
kind == SGFAccessKind::OwnedAddressRead;
}
/// Return an address-preferring version of the given access kind.
static inline SGFAccessKind getAddressAccessKind(SGFAccessKind kind) {
switch (kind) {
case SGFAccessKind::BorrowedObjectRead:
return SGFAccessKind::BorrowedAddressRead;
case SGFAccessKind::OwnedObjectRead:
return SGFAccessKind::OwnedAddressRead;
case SGFAccessKind::OwnedObjectConsume:
return SGFAccessKind::OwnedAddressConsume;
case SGFAccessKind::IgnoredRead:
case SGFAccessKind::BorrowedAddressRead:
case SGFAccessKind::OwnedAddressRead:
case SGFAccessKind::OwnedAddressConsume:
case SGFAccessKind::Write:
case SGFAccessKind::ReadWrite:
return kind;
}
llvm_unreachable("bad kind");
}
static inline AccessKind getFormalAccessKind(SGFAccessKind kind) {
switch (kind) {
case SGFAccessKind::IgnoredRead:
case SGFAccessKind::BorrowedAddressRead:
case SGFAccessKind::BorrowedObjectRead:
case SGFAccessKind::OwnedAddressRead:
case SGFAccessKind::OwnedObjectRead:
return AccessKind::Read;
case SGFAccessKind::Write:
return AccessKind::Write;
// TODO: Do we need our own AccessKind here?
case SGFAccessKind::OwnedAddressConsume:
case SGFAccessKind::OwnedObjectConsume:
case SGFAccessKind::ReadWrite:
return AccessKind::ReadWrite;
}
llvm_unreachable("bad kind");
}
/// Parameter to \c SILGenFunction::emitAddressOfLValue that indicates
/// what kind of instrumentation should be emitted when compiling under
/// Thread Sanitizer.
enum class TSanKind : bool {
None = 0,
/// Instrument the LValue access as an inout access.
InoutAccess
};
/// Represents an LValue opened for mutating access.
///
/// This is used by LogicalPathComponent::projectAsBase().
struct MaterializedLValue {
ManagedValue temporary;
// Only set if a callback is required
CanType origSelfType;
CanGenericSignature genericSig;
SILValue callback;
SILValue callbackStorage;
MaterializedLValue() {}
explicit MaterializedLValue(ManagedValue temporary)
: temporary(temporary) {}
MaterializedLValue(ManagedValue temporary,
CanType origSelfType,
CanGenericSignature genericSig,
SILValue callback,
SILValue callbackStorage)
: temporary(temporary),
origSelfType(origSelfType),
genericSig(genericSig),
callback(callback),
callbackStorage(callbackStorage) {}
};
/// The kind of operation under which we are querying a storage reference.
enum class StorageReferenceOperationKind {
Borrow,
Consume
};
/// SILGenFunction - an ASTVisitor for producing SIL from function bodies.
class LLVM_LIBRARY_VISIBILITY SILGenFunction
: public ASTVisitor<SILGenFunction>
{ // style violation because Xcode <rdar://problem/13065676>
public:
/// The SILGenModule this function belongs to.
SILGenModule &SGM;
/// The SILFunction being constructed.
SILFunction &F;
/// The SILModuleConventions for this SIL module.
SILModuleConventions silConv;
bool useLoweredAddresses() const { return silConv.useLoweredAddresses(); }
/// The DeclContext corresponding to the function currently being emitted.
DeclContext * const FunctionDC;
/// The name of the function currently being emitted, as presented to user
/// code by #function.
DeclName MagicFunctionName;
std::string MagicFunctionString;
/// The specialized type context in which the function is being emitted.
/// Only applies to closures.
std::optional<FunctionTypeInfo> TypeContext;
ASTContext &getASTContext() const { return SGM.M.getASTContext(); }
/// The first block in the postmatter section of the function, if
/// anything has been built there.
///
/// (This field must precede B because B's initializer calls
/// createBasicBlock().)
SILFunction::iterator StartOfPostmatter;
/// The current section of the function that we're emitting code in.
///
/// The postmatter section is a part of the function intended for
/// things like error-handling that don't need to be mixed into the
/// normal code sequence.
///
/// If the current function section is Ordinary, and
/// StartOfPostmatter does not point to the function end, the current
/// insertion block should be ordered before that.
///
/// If the current function section is Postmatter, StartOfPostmatter
/// does not point to the function end and the current insertion block is
/// ordered after that (inclusive).
///
/// (This field must precede B because B's initializer calls
/// createBasicBlock().)
FunctionSection CurFunctionSection = FunctionSection::Ordinary;
/// Does this function require a non-void direct return?
bool NeedsReturn = false;
/// Is emission currently within a formal modification?
bool isInFormalEvaluationScope() const {
return FormalEvalContext.isInFormalEvaluationScope();
}
/// Is emission currently within an inout conversion?
bool InInOutConversionScope = false;
/// The SILGenBuilder used to construct the SILFunction. It is what maintains
/// the notion of the current block being emitted into.
SILGenBuilder B;
struct BreakContinueDest {
LabeledStmt *Target;
JumpDest BreakDest;
JumpDest ContinueDest;
};
std::vector<BreakContinueDest> BreakContinueDestStack;
std::vector<PatternMatchContext*> SwitchStack;
/// Information for a parent SingleValueStmtExpr initialization.
struct SingleValueStmtInitialization {
/// The target expressions to be used for initialization.
SmallPtrSet<Expr *, 4> Exprs;
SILValue InitializationBuffer;
SingleValueStmtInitialization(SILValue buffer)
: InitializationBuffer(buffer) {}
};
/// A stack of active SingleValueStmtExpr initializations that may be
/// initialized by the branches of a statement.
std::vector<SingleValueStmtInitialization> SingleValueStmtInitStack;
SourceFile *SF;
SourceLoc LastSourceLoc;
using ASTScopeTy = ast_scope::ASTScopeImpl;
const ASTScopeTy *FnASTScope = nullptr;
using VarDeclScopeMapTy =
llvm::SmallDenseMap<ValueDecl *, const ASTScopeTy *, 8>;
/// The ASTScope each variable declaration belongs to.
VarDeclScopeMapTy VarDeclScopeMap;
/// Caches one SILDebugScope for each ASTScope.
llvm::SmallDenseMap<std::pair<const ASTScopeTy *, const SILDebugScope *>,
const SILDebugScope *, 16>
ScopeMap;
/// Caches one toplevel inline SILDebugScope for each macro BufferID.
llvm::SmallDenseMap<unsigned, const SILDebugScope *, 16> InlinedScopeMap;
/// The cleanup depth and BB for when the operand of a
/// BindOptionalExpr is a missing value.
SmallVector<JumpDest, 2> BindOptionalFailureDests;
/// The cleanup depth and epilog BB for "return" statements.
JumpDest ReturnDest = JumpDest::invalid();
/// The cleanup depth and epilog BB for "fail" statements.
JumpDest FailDest = JumpDest::invalid();
/// The destination for throws. The block will always be in the
/// postmatter. For a direct error return, it takes a BB argument
/// of the exception type.
JumpDest ThrowDest = JumpDest::invalid();
/// Support for typed throws.
SILArgument *IndirectErrorResult = nullptr;
/// The destination for coroutine unwinds. The block will always
/// be in the postmatter.
JumpDest CoroutineUnwindDest = JumpDest::invalid();
/// This records information about the currently active cleanups.
CleanupManager Cleanups;
/// The current context where formal evaluation cleanups are managed.
FormalEvaluationContext FormalEvalContext;
/// VarLoc - representation of an emitted local variable or constant. There
/// are four scenarios here:
///
/// 1) This could be a simple copyable "var" or "let" emitted into an
/// alloc_box. In this case, 'value' contains a pointer (it is always an
/// address) to the value, and 'box' contains a pointer to the retain
/// count for the box.
/// 2) This could be a simple non-address-only "let" represented directly. In
/// this case, 'value' is the value of the let and is never of address
/// type. 'box' is always nil.
/// 3) This could be an address-only "let" emitted into an alloc_stack, or
/// passed in from somewhere else that has guaranteed lifetime (e.g. an
/// incoming argument of 'in_guaranteed' convention). In this case,
/// 'value' is a pointer to the memory (and thus, its type is always an
/// address) and the 'box' is nil.
/// 4) This could be a noncopyable "var" or "let" emitted into an
/// alloc_box. In this case, 'value' is nil and the 'box' contains the box
/// itself. The user must always reproject from the box and insert an
/// access marker/must_must_check as appropriate.
///
/// Generally, code shouldn't be written to enumerate these four cases, it
/// should just handle the case of "box or not" or "address or not", depending
/// on what the code cares about.
struct VarLoc {
/// value - the value of the variable, or the address the variable is
/// stored at (if "value.getType().isAddress()" is true).
///
/// It may be invalid if we are supposed to lazily project out an address
/// from a box.
SILValue value;
/// box - This is the retainable box for something emitted to an alloc_box.
/// It may be invalid if no box was made for the value (e.g., because it was
/// an inout value, or constant emitted to an alloc_stack).
SILValue box;
/// What kind of access enforcement should be used to access the variable,
/// or `Unknown` if it's known to be immutable.
SILAccessEnforcement access;
/// A structure used for bookkeeping the on-demand formation and cleanup
/// of an addressable representation for an immutable value binding.
struct AddressableBuffer {
struct State {
// If the value needs to be reabstracted to provide an addressable
// representation, this SILValue owns the reabstracted representation.
SILValue reabstraction = SILValue();
// The stack allocation for the addressable representation.
SILValue allocStack = SILValue();
// The initiation of the in-memory borrow.
SILValue storeBorrow = SILValue();
State(SILValue reabstraction,
SILValue allocStack,
SILValue storeBorrow)
: reabstraction(reabstraction), allocStack(allocStack),
storeBorrow(storeBorrow)
{}
};
std::unique_ptr<State> state = nullptr;
// If the variable cleanup is triggered before the addressable
// representation is demanded, but the addressable representation
// gets demanded later, we save the insertion points where the
// representation would be cleaned up so we can backfill them.
llvm::SmallVector<SILInstruction*, 1> cleanupPoints;
AddressableBuffer() = default;
AddressableBuffer(AddressableBuffer &&other)
: state(std::move(other.state))
{
cleanupPoints.swap(other.cleanupPoints);
}
AddressableBuffer &operator=(AddressableBuffer &&other) {
state = std::move(other.state);
cleanupPoints.swap(other.cleanupPoints);
return *this;
}
~AddressableBuffer();
};
AddressableBuffer addressableBuffer;
VarLoc() = default;
VarLoc(SILValue value, SILAccessEnforcement access,
SILValue box = SILValue())
: value(value), box(box), access(access)
{}
};
/// VarLocs - Entries in this map are generated when a PatternBindingDecl is
/// emitted. The map is queried to produce the lvalue for a DeclRefExpr to
/// a local variable.
llvm::DenseMap<ValueDecl*, VarLoc> VarLocs;
// Represents an addressable buffer that has been allocated but not yet used.
struct PreparedAddressableBuffer {
SILInstruction *insertPoint = nullptr;
PreparedAddressableBuffer() = default;
PreparedAddressableBuffer(SILInstruction *insertPoint)
: insertPoint(insertPoint)
{}
PreparedAddressableBuffer(PreparedAddressableBuffer &&other)
: insertPoint(other.insertPoint)
{
other.insertPoint = nullptr;
}
PreparedAddressableBuffer &operator=(PreparedAddressableBuffer &&other) {
insertPoint = other.insertPoint;
other.insertPoint = nullptr;
return *this;
}
~PreparedAddressableBuffer() {
if (insertPoint) {
// Remove the insertion point if it went unused.
insertPoint->eraseFromParent();
}
}
};
llvm::DenseMap<VarDecl *, PreparedAddressableBuffer> AddressableBuffers;
/// Establish the scope for the addressable buffer that might be allocated
/// for a local variable binding.
///
/// This must be enclosed within the scope of the value binding for the
/// variable, and cover the scope in which the variable can be referenced.
void enterLocalVariableAddressableBufferScope(VarDecl *decl);
/// Get a stable address which is suitable for forming dependent pointers
/// if possible.
SILValue getLocalVariableAddressableBuffer(VarDecl *decl,
SILLocation loc,
ValueOwnership ownership);
/// The local auxiliary declarations for the parameters of this function that
/// need to be emitted inside the next brace statement.
llvm::SmallVector<VarDecl *, 2> LocalAuxiliaryDecls;
/// The mappings between instance properties referenced by this init
/// accessor (via initializes/accesses attributes) and and argument
/// declarations synthesized to access them in the body.
llvm::DenseMap<VarDecl *, ParamDecl *> InitAccessorArgumentMappings;
// Context information for tracking an `async let` child task.
struct AsyncLetChildTask {
SILValue asyncLet; // RawPointer to the async let state
SILValue resultBuf; // RawPointer to the result buffer
bool isThrowing; // true if task can throw
};
/// Mapping from each async let clause to the AsyncLet repr that contains the
/// AsyncTask that will produce the initializer value for that clause and a
/// Boolean value indicating whether the task can throw.
llvm::SmallDenseMap<std::pair<PatternBindingDecl *, unsigned>,
AsyncLetChildTask>
AsyncLetChildTasks;
/// Indicates whether this function is a distributed actor's designated
/// initializer, providing the needed clean-up to emit an identity
/// assignment after initializing the actorSystem property.
std::optional<InitializeDistActorIdentity> DistActorCtorContext;
/// When rebinding 'self' during an initializer delegation, we have to be
/// careful to preserve the object at 1 retain count during the delegation
/// because of assumptions in framework code. This enum tracks the state of
/// 'self' during the delegation.
enum SelfInitDelegationStates {
// 'self' is a normal variable.
NormalSelf,
/// 'self' needs to be shared borrowed next time self is used.
///
/// At this point we do not know if:
///
/// 1. 'self' is used at all. In such a case, the borrow scope for self will
/// end before the delegating init call and we will overwrite the value
/// in
/// the self box.
///
/// 2. If there is a consuming self use, will self be borrowed in an
/// exclusive manner or a shared manner. If we need to perform an
/// exclusive borrow, we will transition to WillExclusiveBorrowSelf in
/// SILGenApply.
WillSharedBorrowSelf,
/// 'self' needs to be exclusively borrowed next time self is used.
///
/// We only advance to this state in SILGenApply when we know that we are
/// going to be passing self to a delegating initializer that will consume
/// it. We will always evaluate self before any other uses of self in the
/// self.init call, so we know that we will never move from
/// WillExclusiveBorrowSelf to WillSharedBorrowSelf.
///
/// Once we are in this point, all other uses of self must be borrows until
/// we use self in the delegating init call. All of the borrow scopes /must/
/// end before the delegating init call.
WillExclusiveBorrowSelf,
/// 'self' was shared borrowed to compute the self argument of the
/// delegating init call.
///
/// This means that the delegating init uses a metatype or the like as its
/// self argument instead of 'self'. Thus we are able to perform a shared
/// borrow of self to compute that value and end the shared borrow scope
/// before the delegating initializer apply.
DidSharedBorrowSelf,
// 'self' was exclusively borrowed for the delegating init call. All further
// uses of self until the actual delegating init must be done via shared
// borrows that end strictly before the delegating init call.
DidExclusiveBorrowSelf,
};
SelfInitDelegationStates SelfInitDelegationState = NormalSelf;
ManagedValue InitDelegationSelf;
SILValue InitDelegationSelfBox;
std::optional<SILLocation> InitDelegationLoc;
ManagedValue SuperInitDelegationSelf;
RValue emitRValueForSelfInDelegationInit(SILLocation loc, CanType refType,
SILValue result, SGFContext C);
/// A version of emitRValueForSelfInDelegationInit that uses formal evaluation
/// operations instead of normal scoped operations.
RValue emitFormalEvaluationRValueForSelfInDelegationInit(SILLocation loc,
CanType refType,
SILValue addr,
SGFContext C);
/// The metatype argument to an allocating constructor, if we're emitting one.
SILValue AllocatorMetatype;
class ExpectedExecutorStorage {
static ValueBase *invalid() {
return reinterpret_cast<ValueBase*>(uintptr_t(0));
}
static ValueBase *unnecessary() {
return reinterpret_cast<ValueBase*>(uintptr_t(1));
}
static ValueBase *lazy() {
return reinterpret_cast<ValueBase*>(uintptr_t(2));
}
ValueBase *Value;
public:
ExpectedExecutorStorage() : Value(invalid()) {}
bool isValid() const { return Value != invalid(); }
bool isNecessary() const {
assert(isValid());
return Value != unnecessary();
}
void setUnnecessary() {
assert(Value == invalid());
Value = unnecessary();
}
bool isEager() const {
assert(Value != invalid() && Value != unnecessary());
return Value != lazy();
}
SILValue getEager() const {
assert(isEager());
return Value;
}
void set(SILValue value) {
assert(Value == invalid());
assert(value != nullptr);
Value = value;
}
void setLazy() {
assert(Value == invalid());
Value = lazy();
}
};
/// If set, the current function is an async function which is formally
/// isolated to the given executor, and hop_to_executor instructions must
/// be inserted at the begin of the function and after all suspension
/// points.
ExpectedExecutorStorage ExpectedExecutor;
struct ActivePackExpansion {
GenericEnvironment *OpenedElementEnv;
SILValue ExpansionIndex;
/// Mapping from temporary pack expressions to their values. These
/// are evaluated once, with their elements projected in a dynamic
/// pack loop.
llvm::SmallDenseMap<MaterializePackExpr *, SILValue>
MaterializedPacks;
ActivePackExpansion(GenericEnvironment *OpenedElementEnv)
: OpenedElementEnv(OpenedElementEnv) {}
};
/// The innermost active pack expansion.
ActivePackExpansion *InnermostPackExpansion = nullptr;
ActivePackExpansion *getInnermostPackExpansion() const {
assert(InnermostPackExpansion && "not inside a pack expansion!");
return InnermostPackExpansion;
}
/// True if 'return' without an operand or falling off the end of the current
/// function is valid.
bool allowsVoidReturn() const { return ReturnDest.getBlock()->args_empty(); }
/// Emit code to increment a counter for profiling.
void emitProfilerIncrement(ASTNode Node);
/// Emit code to increment a counter for profiling.
void emitProfilerIncrement(ProfileCounterRef Ref);
/// Load the profiled execution count corresponding to \p Node, if one is
/// available.
ProfileCounter loadProfilerCount(ASTNode Node) const;
/// Get the PGO node's parent.
std::optional<ASTNode> getPGOParent(ASTNode Node) const;
/// Tracer object for counting SIL (and other events) caused by this instance.
FrontendStatsTracer StatsTracer;
SILGenFunction(SILGenModule &SGM, SILFunction &F, DeclContext *DC,
bool IsEmittingTopLevelCode = false);
~SILGenFunction();
/// Return a stable reference to the current cleanup.
CleanupsDepth getCleanupsDepth() const {
return Cleanups.getCleanupsDepth();
}
CleanupHandle getTopCleanup() const {
return Cleanups.getTopCleanup();
}
SILFunction &getFunction() { return F; }
const SILFunction &getFunction() const { return F; }
SILModule &getModule() { return F.getModule(); }
SILGenBuilder &getBuilder() { return B; }
const SILOptions &getOptions() { return getModule().getOptions(); }
// Returns the type expansion context for types in this function.
TypeExpansionContext getTypeExpansionContext() const {
return TypeExpansionContext(getFunction());
}
const TypeLowering &getTypeLowering(AbstractionPattern orig, Type subst) {
return F.getTypeLowering(orig, subst);
}
const TypeLowering &getTypeLowering(Type t) {
return F.getTypeLowering(t);
}
CanSILFunctionType getSILFunctionType(TypeExpansionContext context,
AbstractionPattern orig,
CanFunctionType substFnType) {
return SGM.Types.getSILFunctionType(context, orig, substFnType);
}
SILType getLoweredType(AbstractionPattern orig,
Type subst) {
return F.getLoweredType(orig, subst);
}
SILType getLoweredType(Type t) {
return F.getLoweredType(t);
}
SILType getLoweredType(AbstractionPattern orig, Type subst,
SILValueCategory category) {
return SILType::getPrimitiveType(F.getLoweredRValueType(orig, subst),
category);
}
SILType getLoweredType(Type t, SILValueCategory category) {
return SILType::getPrimitiveType(F.getLoweredRValueType(t), category);
}
CanType getLoweredRValueType(AbstractionPattern orig,
Type subst) {
return F.getLoweredRValueType(orig, subst);
}
CanType getLoweredRValueType(Type t) {
return F.getLoweredRValueType(t);
}
SILType getLoweredTypeForFunctionArgument(Type t) {
auto typeForConv =
SGM.Types.getLoweredType(t, TypeExpansionContext::minimal());
return getLoweredType(t).getCategoryType(typeForConv.getCategory());
}
SILType getLoweredLoadableType(Type t) {
return F.getLoweredLoadableType(t);
}
const TypeLowering &getTypeLowering(SILType type) {
return F.getTypeLowering(type);
}
SILType getSILInterfaceType(SILParameterInfo param) const {
return silConv.getSILType(param, CanSILFunctionType(),
getTypeExpansionContext());
}
SILType getSILInterfaceType(SILResultInfo result) const {
return silConv.getSILType(result, CanSILFunctionType(),
getTypeExpansionContext());
}
SILType getSILType(SILParameterInfo param, CanSILFunctionType fnTy) const {
return silConv.getSILType(param, fnTy, getTypeExpansionContext());
}
SILType getSILType(SILResultInfo result, CanSILFunctionType fnTy) const {
return silConv.getSILType(result, fnTy, getTypeExpansionContext());
}
SILType getSILTypeInContext(SILResultInfo result, CanSILFunctionType fnTy) {
auto t = F.mapTypeIntoContext(getSILType(result, fnTy));
return getTypeLowering(t).getLoweredType().getCategoryType(t.getCategory());
}
SILType getSILTypeInContext(SILParameterInfo param, CanSILFunctionType fnTy) {
auto t = F.mapTypeIntoContext(getSILType(param, fnTy));
return getTypeLowering(t).getLoweredType().getCategoryType(t.getCategory());
}
const SILConstantInfo &getConstantInfo(TypeExpansionContext context,
SILDeclRef constant) {
return SGM.Types.getConstantInfo(context, constant);
}
/// Return the normal local type-lowering information for the given
/// formal function type without any special abstraction pattern applied.
/// This matches the type that `emitRValue` etc. are expected to produce
/// without any contextual overrides.
FunctionTypeInfo getFunctionTypeInfo(CanAnyFunctionType fnType);
/// A helper method that calls getFunctionTypeInfo that also marks global
/// actor isolated async closures that are not sendable as sendable.
FunctionTypeInfo getClosureTypeInfo(AbstractClosureExpr *expr);
bool isEmittingTopLevelCode() { return IsEmittingTopLevelCode; }
void stopEmittingTopLevelCode() { IsEmittingTopLevelCode = false; }
/// Can the generated code reference \c decl safely?
///
/// Checks that the module defining \c decl is as visible to clients as the
/// code referencing it, preventing an inlinable function to reference an
/// implementation-only dependency and similar. This applies similar checks
/// as the exportability checker does to source code for decls referenced by
/// generated code.
bool referenceAllowed(ValueDecl *decl);
std::optional<SILAccessEnforcement>
getStaticEnforcement(VarDecl *var = nullptr);
std::optional<SILAccessEnforcement>
getDynamicEnforcement(VarDecl *var = nullptr);
std::optional<SILAccessEnforcement>
getUnknownEnforcement(VarDecl *var = nullptr);
SourceManager &getSourceManager() { return SGM.M.getASTContext().SourceMgr; }
std::string getMagicFileIDString(SourceLoc loc);
StringRef getMagicFilePathString(SourceLoc loc);
StringRef getMagicFunctionString();
SILDebugLocation
getSILDebugLocation(SILBuilder &B, SILLocation Loc,
std::optional<SILLocation> CurDebugLocOverride,
bool ForMetaInstruction);
const SILDebugScope *getScopeOrNull(SILLocation Loc,
bool ForMetaInstruction = false);
private:
bool IsEmittingTopLevelCode;
const SILDebugScope *getOrCreateScope(SourceLoc SLoc);
const SILDebugScope *getMacroScope(SourceLoc SLoc);
const SILDebugScope *
getOrCreateScope(const ast_scope::ASTScopeImpl *ASTScope,
const SILDebugScope *FnScope,
const SILDebugScope *InlinedAt = nullptr);
public:
/// Enter the debug scope for \p Loc, creating it if necessary.
///
/// \param isBindingScope If true, this is a scope for the bindings introduced
/// by a let expression. This scope ends when the next innermost BraceStmt
/// ends.
void enterDebugScope(SILLocation Loc, bool isBindingScope = false);
/// Return to the previous debug scope.
void leaveDebugScope();
std::unique_ptr<Initialization>
prepareIndirectResultInit(SILLocation loc,
AbstractionPattern origResultType,
CanType formalResultType,
SmallVectorImpl<SILValue> &directResultsBuffer,
SmallVectorImpl<CleanupHandle> &cleanups);
/// Check to see if an initalization for a SingleValueStmtExpr is active, and
/// if the provided expression is for one of its branches. If so, returns the
/// initialization to use for the expression. Otherwise returns \c nullptr.
std::unique_ptr<Initialization> getSingleValueStmtInit(Expr *E);
//===--------------------------------------------------------------------===//
// Entry points for codegen
//===--------------------------------------------------------------------===//
/// Generates code for a FuncDecl.
void emitFunction(FuncDecl *fd);
/// Emits code for a ClosureExpr.
void emitClosure(AbstractClosureExpr *ce);
/// Generates code for a class destroying destructor. This
/// emits the body code from the DestructorDecl, calls the base class
/// destructor, then implicitly releases the elements of the class.
void emitDestroyingDestructor(DestructorDecl *dd);
/// Generates code for an artificial top-level function that starts an
/// application based on a main type and optionally a main type.
void emitArtificialTopLevel(Decl *mainDecl);
/// Generate code for calling the given main function.
void emitCallToMain(FuncDecl *mainDecl);
/// Generate code into @main for starting the async main on the main thread.
void emitAsyncMainThreadStart(SILDeclRef entryPoint);
/// Generates code for class/move only deallocating destructor. This calls the
/// destroying destructor and then deallocates 'self'.
void emitDeallocatingDestructor(DestructorDecl *dd, bool isIsolated);
/// Generates code for a class (isolated-)deallocating destructor. This
/// calls the destroying destructor and then deallocates 'self'.
void emitDeallocatingClassDestructor(DestructorDecl *dd, bool isIsolated);
/// Generates code for the deinit of the move only type and destroys all of
/// the fields.
void emitDeallocatingMoveOnlyDestructor(DestructorDecl *dd);
/// Generates code for a class deallocating destructor that switches executor
/// and calls isolated deallocating destuctor on the right executor.
void emitIsolatingDestructor(DestructorDecl *dd);
/// Whether we are inside a constructor whose hops are injected by
/// definite initialization.
bool isCtorWithHopsInjectedByDefiniteInit();
/// Generates code for a struct constructor.
/// This allocates the new 'self' value, emits the
/// body code, then returns the final initialized 'self'.
void emitValueConstructor(ConstructorDecl *ctor);
/// Generates code for an enum case constructor.
/// This allocates the new 'self' value, injects the enum case,
/// then returns the final initialized 'self'.
void emitEnumConstructor(EnumElementDecl *element);
/// Generates code for a class constructor's