forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILGenFunction.h
1578 lines (1321 loc) · 67.6 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 - 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
//
//===----------------------------------------------------------------------===//
#ifndef SILGENFUNCTION_H
#define SILGENFUNCTION_H
#include "SILGen.h"
#include "JumpDest.h"
#include "swift/AST/AnyFunctionRef.h"
#include "llvm/ADT/PointerIntPair.h"
#include "swift/SIL/SILBuilder.h"
namespace swift {
namespace Lowering {
class ArgumentSource;
class Condition;
class ConsumableManagedValue;
class Initialization;
class LogicalPathComponent;
class LValue;
class ManagedValue;
class RValue;
class TemporaryInitialization;
/// How a method is dispatched.
enum class MethodDispatch {
// The method implementation can be referenced statically.
Static,
// The method implementation uses class_method dispatch.
Class,
};
/// Internal context information for the SILGenFunction visitor.
///
/// In general, emission methods which take an SGFContext indicate
/// that they've initialized the emit-into buffer (if they have) by
/// returning a "isInContext()" ManagedValue of whatever type. Callers who
/// propagate down an SGFContext that might have a emit-into buffer must be
/// aware of this.
///
/// Clients of emission routines that take an SGFContext can also specify that
/// they are ok getting back an RValue at +0 instead of requiring it to be at
/// +1. The client is then responsible for checking the ManagedValue to see if
/// it got back a ManagedValue at +0 or +1.
class SGFContext {
enum DesiredTransfer {
PlusOne,
ImmediatePlusZero,
GuaranteedPlusZero,
};
llvm::PointerIntPair<Initialization *, 2, DesiredTransfer> state;
public:
SGFContext() = default;
enum AllowImmediatePlusZero_t {
/// The client is okay with getting a +0 value and plans to use it
/// immediately.
///
/// For example, in this context, it would be okay to return +0
/// even for a load from a mutable variable, because the only way
/// the value could be invalidated before it's used is a race
/// condition.
AllowImmediatePlusZero
};
enum AllowGuaranteedPlusZero_t {
/// The client is okay with getting a +0 value as long as it's
/// guaranteed to last at least as long as the current evaluation.
/// (For expression evaluation, this generally means at least
/// until the end of the current statement.)
///
/// For example, in this context, it would be okay to return +0
/// for a reference to a local 'let' because that will last until
/// the 'let' goes out of scope. However, it would not be okay to
/// return +0 for a load from a mutable 'var', because that could
/// be mutated before the end of the statement.
AllowGuaranteedPlusZero
};
/// Creates an emitInto context that will store the result of the visited expr
/// into the given Initialization.
explicit SGFContext(Initialization *emitInto) : state(emitInto, PlusOne) {
}
/*implicit*/
SGFContext(AllowImmediatePlusZero_t) : state(nullptr, ImmediatePlusZero) {
}
/*implicit*/
SGFContext(AllowGuaranteedPlusZero_t) : state(nullptr, GuaranteedPlusZero) {
}
/// Returns a pointer to the Initialization that the current expression should
/// store its result to, or null if the expression should allocate temporary
/// storage for its result.
Initialization *getEmitInto() const {
return state.getPointer();
}
/// Return true if a ManagedValue producer is allowed to return at
/// +0, given that it cannot guarantee that the value will be valid
/// until the end of the current evaluation.
bool isImmediatePlusZeroOk() const {
return state.getInt() == ImmediatePlusZero;
}
/// Return true if a ManagedValue producer is allowed to return at
/// +0 if it can guarantee that the value will be valid until the
/// end of the current evaluation.
bool isGuaranteedPlusZeroOk() const {
// Either ImmediatePlusZero or GuaranteedPlusZero is fine.
return state.getInt() >= ImmediatePlusZero;
}
/// Get a context for a sub-expression given that arbitrary side
/// effects may follow the subevaluation.
SGFContext withFollowingSideEffects() const {
SGFContext copy = *this;
if (copy.state.getInt() == ImmediatePlusZero) {
copy.state.setInt(GuaranteedPlusZero);
}
return copy;
}
/// Get a context for a sub-expression where we plan to project out
/// a value. The Initialization is not okay to propagate down, but
/// the +0/+1-ness is.
SGFContext withFollowingProjection() const {
SGFContext copy;
copy.state.setInt(state.getInt());
return copy;
}
};
enum class ApplyOptions : unsigned {
/// No special treatment is required.
None = 0,
/// Suppress the error-handling edge out of the call. This should
/// be used carefully; it's used to implement features like 'rethrows'.
DoesNotThrow = 0x1,
};
inline ApplyOptions operator|(ApplyOptions lhs, ApplyOptions rhs) {
return ApplyOptions(unsigned(lhs) | unsigned(rhs));
}
inline ApplyOptions &operator|=(ApplyOptions &lhs, ApplyOptions rhs) {
return (lhs = (lhs | rhs));
}
inline bool operator&(ApplyOptions lhs, ApplyOptions rhs) {
return ((unsigned(lhs) & unsigned(rhs)) != 0);
}
inline ApplyOptions operator-(ApplyOptions lhs, ApplyOptions rhs) {
return ApplyOptions(unsigned(lhs) & ~unsigned(rhs));
}
inline ApplyOptions &operator-=(ApplyOptions &lhs, ApplyOptions rhs) {
return (lhs = (lhs - rhs));
}
class PatternMatchContext;
struct LValueWriteback;
/// 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,
};
/// A subclass of SILBuilder that tracks used protocol conformances.
class SILGenBuilder : public SILBuilder {
SILGenModule &SGM;
public:
SILGenBuilder(SILGenFunction &gen);
SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB);
SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB,
SmallVectorImpl<SILInstruction *> *insertedInsts);
SILGenBuilder(SILGenFunction &gen, SILBasicBlock *insertBB,
SILInstruction *insertInst);
SILGenBuilder(SILGenFunction &gen, SILFunction::iterator insertBB)
: SILGenBuilder(gen, &*insertBB) {}
SILGenBuilder(SILGenFunction &gen, SILFunction::iterator insertBB,
SmallVectorImpl<SILInstruction *> *insertedInsts)
: SILGenBuilder(gen, &*insertBB, insertedInsts) {}
SILGenBuilder(SILGenFunction &gen, SILFunction::iterator insertBB,
SILInstruction *insertInst)
: SILGenBuilder(gen, &*insertBB, insertInst) {}
SILGenBuilder(SILGenFunction &gen, SILFunction::iterator insertBB,
SILBasicBlock::iterator insertInst)
: SILGenBuilder(gen, &*insertBB, &*insertInst) {}
// Metatype instructions use the conformances necessary to instantiate the
// type.
MetatypeInst *createMetatype(SILLocation Loc, SILType Metatype);
// Generic pply instructions use the conformances necessary to form the call.
using SILBuilder::createApply;
ApplyInst *createApply(SILLocation Loc, SILValue Fn,
SILType SubstFnTy,
SILType Result,
ArrayRef<Substitution> Subs,
ArrayRef<SILValue> Args);
TryApplyInst *createTryApply(SILLocation loc, SILValue fn,
SILType substFnTy,
ArrayRef<Substitution> subs,
ArrayRef<SILValue> args,
SILBasicBlock *normalBB,
SILBasicBlock *errorBB);
PartialApplyInst *createPartialApply(SILLocation Loc, SILValue Fn,
SILType SubstFnTy,
ArrayRef<Substitution> Subs,
ArrayRef<SILValue> Args,
SILType ClosureTy);
BuiltinInst *createBuiltin(SILLocation Loc, Identifier Name,
SILType ResultTy, ArrayRef<Substitution> Subs,
ArrayRef<SILValue> Args);
// Existential containers use the conformances needed by the existential
// box.
InitExistentialAddrInst *
createInitExistentialAddr(SILLocation Loc,
SILValue Existential,
CanType FormalConcreteType,
SILType LoweredConcreteType,
ArrayRef<ProtocolConformance*> Conformances);
InitExistentialMetatypeInst *
createInitExistentialMetatype(SILLocation loc, SILValue metatype,
SILType existentialType,
ArrayRef<ProtocolConformance*> conformances);
InitExistentialRefInst *
createInitExistentialRef(SILLocation Loc, SILType ExistentialType,
CanType FormalConcreteType,
SILValue Concrete,
ArrayRef<ProtocolConformance*> Conformances);
AllocExistentialBoxInst *createAllocExistentialBox(SILLocation Loc,
SILType ExistentialType,
CanType ConcreteType,
SILType ConcreteLoweredType,
ArrayRef<ProtocolConformance *> Conformances);
};
/// 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 name of the function currently being emitted, as presented to user
/// code by __FUNCTION__.
DeclName MagicFunctionName;
std::string MagicFunctionString;
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().)
SILBasicBlock *StartOfPostmatter = nullptr;
/// 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 is non-null, the current insertion block
/// should be ordered before that.
///
/// If the current function section is Postmatter, StartOfPostmatter
/// is non-null 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;
/// \brief Does this function require a non-void direct return?
bool NeedsReturn = false;
/// \brief Is emission currently within a formal modification?
bool InWritebackScope = false;
/// \brief Is emission currently within an inout conversion?
bool InInOutConversionScope = false;
/// B - The SILGenBuilder used to construct the SILFunction. It is
/// what maintains the notion of the current block being emitted
/// into.
SILGenBuilder B;
/// IndirectReturnAddress - For a function with an indirect return, holds a
/// value representing the address to initialize with the return value. Null
/// for a function that returns by value.
SILValue IndirectReturnAddress;
struct BreakContinueDest {
LabeledStmt *Target;
JumpDest BreakDest;
JumpDest ContinueDest;
};
std::vector<BreakContinueDest> BreakContinueDestStack;
std::vector<PatternMatchContext*> SwitchStack;
/// Keep track of our current nested scope.
std::vector<SILDebugScope*> DebugScopeStack;
/// 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 and takes a BB argument of the exception type.
JumpDest ThrowDest = JumpDest::invalid();
/// \brief The SIL location corresponding to the AST node being processed.
SILLocation CurrentSILLoc;
/// Cleanups - This records information about the currently active cleanups.
CleanupManager Cleanups;
/// The stack of pending writebacks.
std::vector<LValueWriteback> *WritebackStack = 0;
std::vector<LValueWriteback> &getWritebackStack();
/// freeWritebackStack - Just deletes WritebackStack. Out of line to avoid
/// having to put the definition of LValueWriteback in this header.
void freeWritebackStack();
/// VarLoc - representation of an emitted local variable or constant. There
/// are three scenarios here:
///
/// 1) This could be a simple "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.
///
/// Generally, code shouldn't be written to enumerate these three 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).
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;
static VarLoc get(SILValue value, SILValue box = SILValue()) {
VarLoc Result;
Result.value = value;
Result.box = box;
return Result;
}
};
/// 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;
/// 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 consumed next time it is referenced.
WillConsumeSelf,
// 'self' has been consumed.
DidConsumeSelf,
};
SelfInitDelegationStates SelfInitDelegationState = NormalSelf;
/// The metatype argument to an allocating constructor, if we're emitting one.
SILValue AllocatorMetatype;
/// True if 'return' without an operand or falling off the end of the current
/// function is valid.
bool allowsVoidReturn() const {
return ReturnDest.getBlock()->bbarg_empty();
}
/// This location, when set, is used as an override location for magic
/// identifier expansion (e.g. __FILE__). This allows default argument
/// expansion to report the location of the call, instead of the location
/// of the original expr.
Optional<SourceLoc> overrideLocationForMagicIdentifiers;
/// Emit code to increment a counter for profiling.
void emitProfilerIncrement(ASTNode N) {
if (SGM.Profiler)
SGM.Profiler->emitCounterIncrement(B, N);
}
SILGenFunction(SILGenModule &SGM, SILFunction &F);
~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; }
SILGenBuilder &getBuilder() { return B; }
const TypeLowering &getTypeLowering(AbstractionPattern orig, Type subst,
unsigned uncurryLevel = 0) {
return SGM.Types.getTypeLowering(orig, subst, uncurryLevel);
}
const TypeLowering &getTypeLowering(Type t, unsigned uncurryLevel = 0) {
return SGM.Types.getTypeLowering(t, uncurryLevel);
}
SILType getLoweredType(AbstractionPattern orig, Type subst,
unsigned uncurryLevel = 0) {
return SGM.Types.getLoweredType(orig, subst, uncurryLevel);
}
SILType getLoweredType(Type t, unsigned uncurryLevel = 0) {
return SGM.Types.getLoweredType(t, uncurryLevel);
}
SILType getLoweredLoadableType(Type t, unsigned uncurryLevel = 0) {
return SGM.Types.getLoweredLoadableType(t, uncurryLevel);
}
const TypeLowering &getTypeLowering(SILType type) {
return SGM.Types.getTypeLowering(type);
}
SILConstantInfo getConstantInfo(SILDeclRef constant) {
return SGM.Types.getConstantInfo(constant);
}
SourceManager &getSourceManager() { return SGM.M.getASTContext().SourceMgr; }
/// Push a new debug scope and set its parent pointer.
void enterDebugScope(SILLocation Loc) {
auto *Parent =
DebugScopeStack.size() ? DebugScopeStack.back() : F.getDebugScope();
auto *DS = new (SGM.M) SILDebugScope(Loc, getFunction(), Parent);
DebugScopeStack.push_back(DS);
B.setCurrentDebugScope(DS);
}
/// Return to the previous debug scope.
void leaveDebugScope() {
DebugScopeStack.pop_back();
if (DebugScopeStack.size())
B.setCurrentDebugScope(DebugScopeStack.back());
// Don't reset the debug scope after leaving the outermost scope,
// because the debugger is not expecting the function epilogue to
// be in a different scope.
}
//===--------------------------------------------------------------------===//
// Entry points for codegen
//===--------------------------------------------------------------------===//
/// \brief Generates code for a FuncDecl.
void emitFunction(FuncDecl *fd);
/// \brief 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 class.
void emitArtificialTopLevel(ClassDecl *mainClass);
/// Generates code for a class deallocating destructor. This
/// calls the destroying destructor and then deallocates 'self'.
void emitDeallocatingDestructor(DestructorDecl *dd);
/// 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
/// allocating entry point. This allocates the new 'self' value, passes it to
/// the initializer entry point, then returns the initialized 'self'.
void emitClassConstructorAllocator(ConstructorDecl *ctor);
/// Generates code for a class constructor's
/// initializing entry point. This takes 'self' and the constructor arguments
/// as parameters and executes the constructor body to initialize 'self'.
void emitClassConstructorInitializer(ConstructorDecl *ctor);
/// Generates code to initialize instance variables from their
/// initializers.
///
/// \param selfDecl The 'self' declaration within the current function.
/// \param nominal The type whose members are being initialized.
void emitMemberInitializers(VarDecl *selfDecl, NominalTypeDecl *nominal);
/// Emit a method that initializes the ivars of a class.
void emitIVarInitializer(SILDeclRef ivarInitializer);
/// Emit a method that destroys the ivars of a class.
void emitIVarDestroyer(SILDeclRef ivarDestroyer);
/// Generates code to destroy the instance variables of a class.
///
/// \param selfValue The 'self' value.
/// \param cd The class declaration whose members are being destroyed.
void emitClassMemberDestruction(SILValue selfValue, ClassDecl *cd,
CleanupLocation cleanupLoc);
/// Generates code for a curry thunk from one uncurry level
/// of a function to another.
void emitCurryThunk(ValueDecl *fd,
SILDeclRef fromLevel, SILDeclRef toLevel);
/// Generates a thunk from a foreign function to the native Swift convention.
void emitForeignToNativeThunk(SILDeclRef thunk);
/// Generates a thunk from a native function to the conventions.
void emitNativeToForeignThunk(SILDeclRef thunk);
// Generate a nullary function that returns the given value.
void emitGeneratorFunction(SILDeclRef function, Expr *value);
/// Generate an ObjC-compatible destructor (-dealloc).
void emitObjCDestructor(SILDeclRef dtor);
ManagedValue emitGlobalVariableRef(SILLocation loc, VarDecl *var);
/// Generate a lazy global initializer.
void emitLazyGlobalInitializer(PatternBindingDecl *binding,
unsigned pbdEntry);
/// Generate a global accessor, using the given initializer token and
/// function
void emitGlobalAccessor(VarDecl *global,
SILGlobalVariable *onceToken,
SILFunction *onceFunc);
void emitGlobalGetter(VarDecl *global,
SILGlobalVariable *onceToken,
SILFunction *onceFunc);
/// Generate a protocol witness entry point, invoking 'witness' at the
/// abstraction level of 'requirement'.
void emitProtocolWitness(ProtocolConformance *conformance,
SILDeclRef requirement,
SILDeclRef witness,
ArrayRef<Substitution> witnessSubs,
IsFreeFunctionWitness_t isFree);
/// Convert a block to a native function with a thunk.
ManagedValue emitBlockToFunc(SILLocation loc,
ManagedValue block,
CanSILFunctionType funcTy);
/// Convert a native function to a block with a thunk.
ManagedValue emitFuncToBlock(SILLocation loc,
ManagedValue block,
CanSILFunctionType funcTy);
/// Thunk with the signature of a base class method calling a derived class
/// method.
///
/// \param inputOrigType Abstraction pattern of base class method
/// \param inputSubstType Formal AST type of base class method
/// \param outputSubstType Formal AST type of derived class method
void emitVTableThunk(SILDeclRef derived,
AbstractionPattern inputOrigType,
CanAnyFunctionType inputSubstType,
CanAnyFunctionType outputSubstType);
//===--------------------------------------------------------------------===//
// Control flow
//===--------------------------------------------------------------------===//
/// emitCondition - Emit a boolean expression as a control-flow condition.
///
/// \param E - The expression to be evaluated as a condition.
/// \param hasFalseCode - true if the false branch doesn't just lead
/// to the fallthrough.
/// \param invertValue - true if this routine should invert the value before
/// testing true/false.
/// \param contArgs - the types of the arguments to the continuation BB.
/// Matching argument values must be passed to exitTrue and exitFalse
/// of the resulting Condition object.
Condition emitCondition(Expr *E,
bool hasFalseCode = true, bool invertValue = false,
ArrayRef<SILType> contArgs = {});
Condition emitCondition(SILValue V, SILLocation Loc,
bool hasFalseCode = true, bool invertValue = false,
ArrayRef<SILType> contArgs = {});
/// Create a new basic block.
///
/// The block can be explicitly placed after a particular block.
/// Otherwise, if the current insertion point is valid, it will be
/// placed immediately after it. Otherwise, it will be placed at the
/// end of the current function section.
///
/// Because basic blocks are generally constructed with an insertion
/// point active, users should be aware that this behavior leads to
/// an emergent LIFO ordering: if code generation requires multiple
/// blocks, the second block created will be positioned before the
/// first block. (This is clearly desirable behavior when blocks
/// are created by different emissions; it's just a little
/// counter-intuitive within a single emission.)
SILBasicBlock *createBasicBlock(SILBasicBlock *afterBB = nullptr);
/// Create a new basic block at the end of the given function
/// section.
SILBasicBlock *createBasicBlock(FunctionSection section);
/// Erase a basic block that was speculatively created and turned
/// out to be unneeded.
///
/// This should be called instead of eraseFromParent() in order to
/// keep SILGen's internal bookkeeping consistent.
///
/// The block should be empty and have no predecessors.
void eraseBasicBlock(SILBasicBlock *block);
//===--------------------------------------------------------------------===//
// Memory management
//===--------------------------------------------------------------------===//
/// emitProlog - Generates prolog code to allocate and clean up mutable
/// storage for closure captures and local arguments.
void emitProlog(AnyFunctionRef TheClosure, ArrayRef<Pattern*> paramPatterns,
Type resultType);
/// returns the number of variables in paramPatterns.
unsigned emitProlog(ArrayRef<Pattern*> paramPatterns,
Type resultType, DeclContext *DeclCtx);
/// Create SILArguments in the entry block that bind all the values
/// of the given pattern suitably for being forwarded.
void bindParametersForForwarding(Pattern *paramPattern,
SmallVectorImpl<SILValue> ¶meters);
/// \brief Create (but do not emit) the epilog branch, and save the
/// current cleanups depth as the destination for return statement branches.
///
/// \param returnType If non-null, the epilog block will be created with an
/// argument of this type to receive the return value for
/// the function.
/// \param isThrowing If true, create an error epilog block.
/// \param L The SILLocation which should be accosocated with
/// cleanup instructions.
void prepareEpilog(Type returnType, bool isThrowing, CleanupLocation L);
void prepareRethrowEpilog(CleanupLocation l);
/// \brief Branch to and emit the epilog basic block. This will fuse
/// the epilog to the current basic block if the epilog bb has no predecessor.
/// The insertion point will be moved into the epilog block if it is
/// reachable.
///
/// \param TopLevelLoc The location of the top level AST node for which we are
/// constructing the epilog, such as a AbstractClosureExpr.
/// \returns None if the epilog block is unreachable. Otherwise, returns
/// the epilog block's return value argument, or a null SILValue if
/// the epilog doesn't take a return value. Also returns the location
/// of the return instrcution if the epilog block is supposed to host
/// the ReturnLocation (This happens in case the predecessor block is
/// merged with the epilog block.)
std::pair<Optional<SILValue>, SILLocation>
emitEpilogBB(SILLocation TopLevelLoc);
/// \brief Emits a standard epilog which runs top-level cleanups then returns
/// the function return value, if any. This can be customized by clients, who
/// set UsesCustomEpilog to true, and optionally inject their own code into
/// the epilog block before calling this. If they do this, their code is run
/// before the top-level cleanups, and the epilog block to continue is
/// returned as the insertion point of this function. They must provide the
/// final exit sequence for the block as well.
///
/// \param TopLevelLoc The location of the top-level expression during whose
/// evaluation the epilog is being produced, for example, the
/// AbstractClosureExpr.
/// \param UsesCustomEpilog True if the client wants to manage its own epilog
/// logic.
SILLocation emitEpilog(SILLocation TopLevelLoc,bool UsesCustomEpilog = false);
/// \brief Emits the standard rethrow epilog using a Swift error result.
void emitRethrowEpilog(SILLocation topLevelLoc);
/// emitSelfDecl - Emit a SILArgument for 'self', register it in varlocs, set
/// up debug info, etc. This returns the 'self' value.
SILValue emitSelfDecl(VarDecl *selfDecl);
/// Emits a temporary allocation that will be deallocated automatically at the
/// end of the current scope. Returns the address of the allocation.
SILValue emitTemporaryAllocation(SILLocation loc, SILType ty);
/// Prepares a buffer to receive the result of an expression, either using the
/// 'emit into' initialization buffer if available, or allocating a temporary
/// allocation if not.
///
/// The caller should call manageBufferForExprResult at the instant
/// that the buffer has been initialized.
SILValue getBufferForExprResult(SILLocation loc, SILType ty, SGFContext C);
/// Flag that the buffer for an expression result has been properly
/// initialized.
///
/// Returns an empty value if the buffer was taken from the context.
ManagedValue manageBufferForExprResult(SILValue buffer,
const TypeLowering &bufferTL,
SGFContext C);
//===--------------------------------------------------------------------===//
// Type conversions for expr emission and thunks
//===--------------------------------------------------------------------===//
ManagedValue emitInjectOptional(SILLocation loc,
ManagedValue v,
CanType inputFormalType,
CanType substFormalType,
const TypeLowering &expectedTL,
SGFContext ctxt);
/// Initialize a memory location with an optional value.
///
/// \param loc The location to use for the resulting optional.
/// \param value The value to inject into an optional.
/// \param dest The uninitialized memory in which to store the result value.
/// \param optTL Type lowering information for the optional to create.
void emitInjectOptionalValueInto(SILLocation loc,
ArgumentSource &&value,
SILValue dest,
const TypeLowering &optTL);
/// Initialize a memory location with an optional "nothing"
/// value.
///
/// \param loc The location to use for the resulting optional.
/// \param dest The uninitialized memory in which to store the result value.
/// \param optTL Type lowering information for the optional to create.
void emitInjectOptionalNothingInto(SILLocation loc,
SILValue dest,
const TypeLowering &optTL);
/// Return a value for an optional ".None" of the specified type. This only
/// works for loadable enum types.
SILValue getOptionalNoneValue(SILLocation loc, const TypeLowering &optTL);
/// Return a value for an optional ".Some(x)" of the specified type. This only
/// works for loadable enum types.
ManagedValue getOptionalSomeValue(SILLocation loc, ManagedValue value,
const TypeLowering &optTL);
/// \brief Emit a call to the library intrinsic _doesOptionalHaveValue.
///
/// The result is a Builtin.Int1.
SILValue emitDoesOptionalHaveValue(SILLocation loc, SILValue addrOrValue);
/// \brief Emit a call to the library intrinsic _preconditionOptionalHasValue.
void emitPreconditionOptionalHasValue(SILLocation loc, SILValue addr);
/// \brief Emit a call to the library intrinsic _getOptionalValue
/// given the address of the optional, which checks that an optional contains
/// some value and either returns the value or traps if there is none.
ManagedValue emitCheckedGetOptionalValueFrom(SILLocation loc,
ManagedValue addr,
const TypeLowering &optTL,
SGFContext C);
/// \brief Extract the value from an optional, which must be known to contain
/// a value.
ManagedValue emitUncheckedGetOptionalValueFrom(SILLocation loc,
ManagedValue addrOrValue,
const TypeLowering &optTL,
SGFContext C = SGFContext());
typedef std::function<ManagedValue(SILGenFunction &gen,
SILLocation loc,
ManagedValue input,
SILType loweredResultTy)> ValueTransform;
/// Emit a transformation on the value of an optional type.
ManagedValue emitOptionalToOptional(SILLocation loc,
ManagedValue input,
SILType loweredResultTy,
const ValueTransform &transform);
ManagedValue emitClassMetatypeToObject(SILLocation loc,
ManagedValue v,
SILType resultTy);
ManagedValue emitExistentialMetatypeToObject(SILLocation loc,
ManagedValue v,
SILType resultTy);
ManagedValue emitProtocolMetatypeToObject(SILLocation loc,
CanType inputTy,
SILType resultTy);
/// OpenedArchetypes - Mappings of opened archetypes back to the
/// instruction which opened them.
llvm::DenseMap<CanType, SILValue> ArchetypeOpenings;
SILValue getArchetypeOpeningSite(CanArchetypeType archetype) const {
auto it = ArchetypeOpenings.find(archetype);
assert(it != ArchetypeOpenings.end() &&
"opened archetype was not registered with SILGenFunction");
return it->second;
}
void setArchetypeOpeningSite(CanArchetypeType archetype, SILValue site) {
ArchetypeOpenings.insert({archetype, site});
}
struct OpaqueValueState {
SILValue value;
bool isConsumable;
bool hasBeenConsumed;
void destroy(SILGenFunction &gen, SILLocation loc);
};
ManagedValue manageOpaqueValue(OpaqueValueState &entry,
SILLocation loc,
SGFContext C);
/// Open up the given existential value and project its payload.
///
/// \param existentialValue The existential value.
/// \param openedArchetype The opened existential archetype.
/// \param loweredOpenedType The lowered type of the projection, which in
/// practice will be the openedArchetype, possibly wrapped in a metatype.
SILGenFunction::OpaqueValueState
emitOpenExistential(SILLocation loc,
ManagedValue existentialValue,
CanArchetypeType openedArchetype,
SILType loweredOpenedType);
/// \brief Wrap the given value in an existential container.
///
/// \param concreteFormalType AST type of value.
/// \param concreteTL Type lowering of value.
/// \param existentialTL Type lowering of existential type.
/// \param F Function reference to emit the existential contents with the
/// given context.
ManagedValue emitExistentialErasure(
SILLocation loc,
CanType concreteFormalType,
const TypeLowering &concreteTL,
const TypeLowering &existentialTL,
const ArrayRef<ProtocolConformance *> &conformances,
SGFContext C,
llvm::function_ref<ManagedValue (SGFContext)> F);
//===--------------------------------------------------------------------===//
// Recursive entry points
//===--------------------------------------------------------------------===//
using ASTVisitorType::visit;
//===--------------------------------------------------------------------===//
// Statements
//===--------------------------------------------------------------------===//
void visit(Stmt *S) = delete;
void emitStmt(Stmt *S);
void emitBreakOutOf(SILLocation loc, Stmt *S);
void emitCatchDispatch(DoCatchStmt *S, ManagedValue exn,
ArrayRef<CatchStmt*> clauses,
JumpDest catchFallthroughDest);
/// Emit code for the throw expr. If \p emitWillThrow is set then emit a
/// call to swift_willThrow, that will allow the debugger to place a
/// breakpoint on throw sites.
void emitThrow(SILLocation loc, ManagedValue exn, bool emitWillThrow = false);
//===--------------------------------------------------------------------===//
// Patterns
//===--------------------------------------------------------------------===//
SILValue emitOSVersionRangeCheck(SILLocation loc, const VersionRange &range);
void emitStmtCondition(StmtCondition Cond, JumpDest FailDest,
SILLocation loc);
void emitConditionalPBD(PatternBindingDecl *PBD, SILBasicBlock *FailBB);
void emitSwitchStmt(SwitchStmt *S);
void emitSwitchFallthrough(FallthroughStmt *S);
//===--------------------------------------------------------------------===//
// Expressions
//===--------------------------------------------------------------------===//
RValue visit(Expr *E) = delete;
/// Generate SIL for the given expression, storing the final result into the
/// specified Initialization buffer(s). This avoids an allocation and copy if
/// the result would be allocated into temporary memory normally.
void emitExprInto(Expr *E, Initialization *I);
/// Emit the given expression as an r-value.
RValue emitRValue(Expr *E, SGFContext C = SGFContext());
/// Emit the given expression as an r-value that follows the
/// abstraction patterns of the original type.
ManagedValue emitRValueAsOrig(Expr *E, AbstractionPattern origPattern,
const TypeLowering &origTL,
SGFContext C = SGFContext());
/// Emit the given expression, ignoring its result.
void emitIgnoredExpr(Expr *E);
/// Emit the given expression as an r-value, then (if it is a tuple), combine
/// it together into a single ManagedValue.
ManagedValue emitRValueAsSingleValue(Expr *E, SGFContext C = SGFContext());
/// Emit 'undef' in a particular formal type.
ManagedValue emitUndef(SILLocation loc, Type type);
ManagedValue emitUndef(SILLocation loc, SILType type);
std::pair<ManagedValue, SILValue>
emitUninitializedArrayAllocation(Type ArrayTy,
SILValue Length,
SILLocation Loc);
CleanupHandle enterDeallocateUninitializedArrayCleanup(SILValue array);
void emitUninitializedArrayDeallocation(SILLocation loc, SILValue array);
SILValue emitConversionToSemanticRValue(SILLocation loc, SILValue value,
const TypeLowering &valueTL);
/// Emit the empty tuple value by emitting
SILValue emitEmptyTuple(SILLocation loc);
/// "Emit" an RValue representing an empty tuple.
RValue emitEmptyTupleRValue(SILLocation loc, SGFContext C);
/// Returns a reference to a constant in global context. For local func decls
/// this returns the function constant with unapplied closure context.
SILValue emitGlobalFunctionRef(SILLocation loc, SILDeclRef constant) {
return emitGlobalFunctionRef(loc, constant, getConstantInfo(constant));
}
SILValue emitGlobalFunctionRef(SILLocation loc, SILDeclRef constant,
SILConstantInfo constantInfo);
/// Returns a reference to a function value that dynamically dispatches
/// the function in a runtime-modifiable way.
SILValue emitDynamicMethodRef(SILLocation loc, SILDeclRef constant,
SILConstantInfo constantInfo);