-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenStmt.cpp
1693 lines (1441 loc) · 62.6 KB
/
SILGenStmt.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
//===--- SILGenStmt.cpp - Implements Lowering of ASTs -> SIL for Stmts ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "ArgumentScope.h"
#include "ArgumentSource.h"
#include "Condition.h"
#include "Conversion.h"
#include "ExecutorBreadcrumb.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "SILGen.h"
#include "Scope.h"
#include "SwitchEnumBuilder.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/ProfileCounter.h"
#include "swift/SIL/BasicBlockUtils.h"
#include "swift/SIL/AbstractionPatternGenerators.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILProfiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace Lowering;
template<typename...T, typename...U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
U &&...args) {
Context.Diags.diagnose(loc,
diag, std::forward<U>(args)...);
}
SILBasicBlock *SILGenFunction::createBasicBlockAfter(SILBasicBlock *afterBB) {
assert(afterBB);
return F.createBasicBlockAfter(afterBB);
}
SILBasicBlock *SILGenFunction::createBasicBlockBefore(SILBasicBlock *beforeBB) {
assert(beforeBB);
return F.createBasicBlockBefore(beforeBB);
}
SILBasicBlock *SILGenFunction::createBasicBlock() {
// If we have a current insertion point, insert there.
if (B.hasValidInsertionPoint()) {
return F.createBasicBlockAfter(B.getInsertionBB());
// Otherwise, insert at the end of the current section.
} else {
return createBasicBlock(CurFunctionSection);
}
}
SILBasicBlock *SILGenFunction::createBasicBlock(llvm::StringRef debugName) {
auto block = createBasicBlock();
block->setDebugName(debugName);
return block;
}
SILBasicBlock *SILGenFunction::createBasicBlock(FunctionSection section) {
switch (section) {
case FunctionSection::Ordinary: {
// The end of the ordinary section is just the end of the function
// unless postmatter blocks exist.
if (StartOfPostmatter != F.end()) {
return F.createBasicBlockBefore(&*StartOfPostmatter);
} else {
return F.createBasicBlock();
}
}
case FunctionSection::Postmatter: {
// The end of the postmatter section is always the end of the function.
// Register the new block as the start of the postmatter if needed.
SILBasicBlock *newBB = F.createBasicBlock();
if (StartOfPostmatter == F.end())
StartOfPostmatter = newBB->getIterator();
return newBB;
}
}
llvm_unreachable("bad function section");
}
SILBasicBlock *
SILGenFunction::createBasicBlockAndBranch(SILLocation loc,
SILBasicBlock *destBB) {
auto *newBB = createBasicBlock();
SILGenBuilder(B, newBB).createBranch(loc, destBB);
return newBB;
}
void SILGenFunction::eraseBasicBlock(SILBasicBlock *block) {
assert(block->pred_empty() && "erasing block with predecessors");
assert(block->empty() && "erasing block with content");
SILFunction::iterator blockIt = block->getIterator();
if (blockIt == StartOfPostmatter) {
StartOfPostmatter = next_or_end(blockIt, F.end());
}
block->eraseFromParent();
}
// Merge blocks during a single traversal of the block list. Only unconditional
// branch edges are visited. Consequently, this takes only as much time as a
// linked list traversal and requires no additional storage.
//
// For each block, check if it can be merged with its successor. Place the
// merged block at the successor position in the block list.
//
// Typically, the successor occurs later in the list. This is most efficient
// because merging moves instructions from the successor to the
// predecessor. This way, instructions will only be moved once. Furthermore, the
// merged block will be visited again to determine if it can be merged with it's
// successor, and so on, so no edges are skipped.
//
// In rare cases, the predecessor is merged with its earlier successor, which has
// already been visited. If the successor can also be merged, then it has
// already happened, and there is no need to revisit the merged block.
void SILGenFunction::mergeCleanupBlocks() {
for (auto bbPos = F.begin(), bbEnd = F.end(), nextPos = bbPos; bbPos != bbEnd;
bbPos = nextPos) {
// A forward iterator referring to the next unprocessed block in the block
// list. If blocks are merged and moved, then this will be updated.
nextPos = std::next(bbPos);
// Consider the current block as the predecessor.
auto *predBB = &*bbPos;
auto *BI = dyn_cast<BranchInst>(predBB->getTerminator());
if (!BI)
continue;
// predBB has an unconditional branch to succBB. If succBB has no other
// predecessors, then merge the blocks.
auto *succBB = BI->getDestBB();
if (!succBB->getSinglePredecessorBlock())
continue;
// Before merging, establish iterators that won't be invalidated by erasing
// succBB. Use a reverse iterator to remember the position before a block.
//
// Remember the block before the current successor as a position for placing
// the merged block.
auto beforeSucc = std::next(SILFunction::reverse_iterator(succBB));
// Remember the position before the current predecessor to avoid skipping
// blocks or revisiting blocks unnecessarily.
auto beforePred = std::next(SILFunction::reverse_iterator(predBB));
// Since succBB will be erased, move before it.
if (beforePred == SILFunction::reverse_iterator(succBB))
++beforePred;
// Merge `predBB` with `succBB`. This erases `succBB`.
mergeBasicBlockWithSingleSuccessor(predBB, succBB);
// If predBB is first in the list, then it must be the entry block which
// cannot be moved.
if (beforePred != F.rend()) {
// Move the merged block into the successor position. (If the blocks are
// not already adjacent, then the first is typically the trampoline.)
assert(beforeSucc != F.rend()
&& "entry block cannot have a predecessor.");
F.moveBlockAfter(predBB, &*beforeSucc);
}
// If after moving predBB there are no more blocks to process, then break.
if (beforePred == F.rbegin())
break;
// Update the loop iterator to the next unprocessed block.
nextPos = SILFunction::iterator(&*std::prev(beforePred));
}
}
//===----------------------------------------------------------------------===//
// SILGenFunction emitStmt implementation
//===----------------------------------------------------------------------===//
namespace {
class StmtEmitter : public Lowering::ASTVisitor<StmtEmitter> {
SILGenFunction &SGF;
public:
StmtEmitter(SILGenFunction &sgf) : SGF(sgf) {}
#define STMT(ID, BASE) void visit##ID##Stmt(ID##Stmt *S);
#include "swift/AST/StmtNodes.def"
ASTContext &getASTContext() { return SGF.getASTContext(); }
SILBasicBlock *createBasicBlock() { return SGF.createBasicBlock(); }
JumpDest createJumpDest(Stmt *cleanupLoc) {
return JumpDest(SGF.createBasicBlock(),
SGF.getCleanupsDepth(),
CleanupLocation(cleanupLoc));
}
JumpDest createThrowDest(Stmt *cleanupLoc, ThrownErrorInfo errorInfo) {
return JumpDest(SGF.createBasicBlock(FunctionSection::Postmatter),
SGF.getCleanupsDepth(),
CleanupLocation(cleanupLoc),
errorInfo);
}
};
} // end anonymous namespace
void SILGenFunction::emitStmt(Stmt *S) {
StmtEmitter(*this).visit(S);
}
/// getOrEraseBlock - If there are branches to the specified JumpDest,
/// return the block, otherwise return NULL. The JumpDest must be valid.
static SILBasicBlock *getOrEraseBlock(SILGenFunction &SGF, JumpDest &dest) {
SILBasicBlock *BB = dest.takeBlock();
if (BB->pred_empty()) {
// If the block is unused, we don't need it; just delete it.
SGF.eraseBasicBlock(BB);
return nullptr;
}
return BB;
}
/// emitOrDeleteBlock - If there are branches to the specified JumpDest,
/// emit it per emitBlock. If there aren't, then just delete the block - it
/// turns out to have not been needed.
static void emitOrDeleteBlock(SILGenFunction &SGF, JumpDest &dest,
SILLocation BranchLoc) {
// If we ever add a single-use optimization here (to just continue
// the predecessor instead of branching to a separate block), we'll
// need to update visitDoCatchStmt so that code like:
// try { throw x } catch _ { }
// doesn't leave us emitting the rest of the function in the
// postmatter section.
SILBasicBlock *BB = getOrEraseBlock(SGF, dest);
if (BB != nullptr)
SGF.B.emitBlock(BB, BranchLoc);
}
Condition SILGenFunction::emitCondition(Expr *E, bool invertValue,
ArrayRef<SILType> contArgs,
ProfileCounter NumTrueTaken,
ProfileCounter NumFalseTaken) {
assert(B.hasValidInsertionPoint() &&
"emitting condition at unreachable point");
// Sema forces conditions to have Bool type, which guarantees this.
SILValue V;
{
FullExpr Scope(Cleanups, CleanupLocation(E));
V = emitRValue(E).forwardAsSingleValue(*this, E);
}
auto i1Value = emitUnwrapIntegerResult(E, V);
return emitCondition(i1Value, E, invertValue, contArgs, NumTrueTaken,
NumFalseTaken);
}
Condition SILGenFunction::emitCondition(SILValue V, SILLocation Loc,
bool invertValue,
ArrayRef<SILType> contArgs,
ProfileCounter NumTrueTaken,
ProfileCounter NumFalseTaken) {
assert(B.hasValidInsertionPoint() &&
"emitting condition at unreachable point");
SILBasicBlock *ContBB = createBasicBlock();
for (SILType argTy : contArgs) {
ContBB->createPhiArgument(argTy, OwnershipKind::Owned);
}
SILBasicBlock *FalseBB = createBasicBlock();
SILBasicBlock *TrueBB = createBasicBlock();
if (invertValue)
B.createCondBranch(Loc, V, FalseBB, TrueBB, NumFalseTaken, NumTrueTaken);
else
B.createCondBranch(Loc, V, TrueBB, FalseBB, NumTrueTaken, NumFalseTaken);
return Condition(TrueBB, FalseBB, ContBB, Loc);
}
void StmtEmitter::visitBraceStmt(BraceStmt *S) {
// Enter a new scope.
LexicalScope BraceScope(SGF, CleanupLocation(S));
// This is a workaround until the FIXME in SILGenFunction::getOrCreateScope
// has been addressed. Property wrappers create incorrect source locations.
DebugScope DbgScope(SGF, S);
// Keep in sync with DiagnosticsSIL.def.
const unsigned ReturnStmtType = 0;
const unsigned BreakStmtType = 1;
const unsigned ContinueStmtType = 2;
const unsigned ThrowStmtType = 3;
const unsigned UnknownStmtType = 4;
unsigned StmtType = UnknownStmtType;
// Emit local auxiliary declarations.
if (!SGF.LocalAuxiliaryDecls.empty()) {
for (auto *var : SGF.LocalAuxiliaryDecls) {
if (auto *patternBinding = var->getParentPatternBinding())
SGF.visit(patternBinding);
SGF.visit(var);
}
SGF.LocalAuxiliaryDecls.clear();
}
bool didDiagnoseUnreachableElements = false;
for (auto &ESD : S->getElements()) {
if (auto D = ESD.dyn_cast<Decl*>()) {
// Hoisted declarations are emitted at the top level by emitSourceFile().
if (D->isHoisted())
continue;
// PatternBindingBecls represent local variable bindings that execute
// as part of the function's execution.
if (!isa<PatternBindingDecl>(D) && !isa<VarDecl>(D)) {
// Other decls define entities that may be used by the program, such as
// local function declarations. So handle them here, before checking for
// reachability, and then continue looping.
SGF.visit(D);
continue;
}
}
// If we ever reach an unreachable point, stop emitting statements and issue
// an unreachable code diagnostic.
if (!SGF.B.hasValidInsertionPoint()) {
// If this is an implicit statement or expression, just skip over it,
// don't emit a diagnostic here.
if (auto *S = ESD.dyn_cast<Stmt*>()) {
// Return statement in a single-expression closure or function is
// implicit, but the result isn't. So, skip over return statements
// that are implicit and either have no results or the result is
// implicit. Otherwise, don't so we can emit unreachable code
// diagnostics.
if (S->isImplicit() && isa<ReturnStmt>(S)) {
auto returnStmt = cast<ReturnStmt>(S);
if (!returnStmt->hasResult()) {
continue;
}
if (returnStmt->getResult()->isImplicit()) {
continue;
}
}
if (S->isImplicit() && !isa<ReturnStmt>(S)) {
continue;
}
} else if (auto *E = ESD.dyn_cast<Expr*>()) {
if (E->isImplicit()) {
// Some expressions, like `OptionalEvaluationExpr` and
// `OpenExistentialExpr`, are implicit but may contain non-implicit
// children that should be diagnosed as unreachable. Check
// descendants here to see if there is anything to diagnose.
bool hasDiagnosableDescendant = false;
E->forEachChildExpr([&](auto *childExpr) -> Expr * {
if (!childExpr->isImplicit())
hasDiagnosableDescendant = true;
return hasDiagnosableDescendant ? nullptr : childExpr;
});
// If there's nothing to diagnose, ignore this expression.
if (!hasDiagnosableDescendant)
continue;
}
} else if (auto D = ESD.dyn_cast<Decl*>()) {
// Local declarations aren't unreachable - only their usages can be. To
// that end, we only care about pattern bindings since their
// initializer expressions can be unreachable.
if (!isa<PatternBindingDecl>(D))
continue;
}
if (didDiagnoseUnreachableElements)
continue;
didDiagnoseUnreachableElements = true;
if (StmtType != UnknownStmtType) {
diagnose(getASTContext(), ESD.getStartLoc(),
diag::unreachable_code_after_stmt, StmtType);
} else {
diagnose(getASTContext(), ESD.getStartLoc(),
diag::unreachable_code);
if (!S->getElements().empty()) {
for (auto *arg : SGF.getFunction().getArguments()) {
auto argTy = arg->getType().getASTType();
if (argTy->isStructurallyUninhabited()) {
// Use the interface type in this diagnostic because the SIL type
// unpacks tuples. But, the SIL type being exploded means it
// points directly at the offending tuple element type and we can
// use that to point the user at problematic component(s).
auto argIFaceTy = arg->getDecl()->getInterfaceType();
diagnose(getASTContext(), S->getStartLoc(),
diag::unreachable_code_uninhabited_param_note,
arg->getDecl()->getBaseName().userFacingName(),
argIFaceTy,
argIFaceTy->is<EnumType>(),
argTy);
break;
}
}
}
}
continue;
}
// Process children.
if (auto *S = ESD.dyn_cast<Stmt*>()) {
visit(S);
if (isa<ReturnStmt>(S))
StmtType = ReturnStmtType;
if (isa<BreakStmt>(S))
StmtType = BreakStmtType;
if (isa<ContinueStmt>(S))
StmtType = ContinueStmtType;
if (isa<ThrowStmt>(S))
StmtType = ThrowStmtType;
} else if (auto *E = ESD.dyn_cast<Expr*>()) {
SGF.emitIgnoredExpr(E);
} else {
auto *D = ESD.get<Decl*>();
assert((isa<PatternBindingDecl>(D) || isa<VarDecl>(D)) &&
"other decls should be handled before the reachability check");
SGF.visit(D);
}
}
}
namespace {
class StoreResultInitialization : public Initialization {
SILValue &Storage;
SmallVectorImpl<CleanupHandle> &Cleanups;
public:
StoreResultInitialization(SILValue &storage,
SmallVectorImpl<CleanupHandle> &cleanups)
: Storage(storage), Cleanups(cleanups) {}
void copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) override {
Storage = value.getValue();
auto cleanup = value.getCleanup();
if (cleanup.isValid()) Cleanups.push_back(cleanup);
}
};
} // end anonymous namespace
static void wrapInSubstToOrigInitialization(SILGenFunction &SGF,
InitializationPtr &init,
AbstractionPattern origType,
CanType substType,
SILType expectedTy) {
auto loweredSubstTy = SGF.getLoweredRValueType(substType);
if (expectedTy.getASTType() != loweredSubstTy) {
auto conversion =
Conversion::getSubstToOrig(origType, substType,
SILType::getPrimitiveObjectType(loweredSubstTy),
expectedTy);
auto convertingInit = new ConvertingInitialization(conversion,
std::move(init));
init.reset(convertingInit);
}
}
static InitializationPtr
createIndirectResultInit(SILGenFunction &SGF, SILValue addr,
SmallVectorImpl<CleanupHandle> &cleanups) {
// Create an initialization which will initialize it.
auto &resultTL = SGF.getTypeLowering(addr->getType());
auto temporary = SGF.useBufferAsTemporary(addr, resultTL);
// Remember the cleanup that will be activated.
auto cleanup = temporary->getInitializedCleanup();
if (cleanup.isValid())
cleanups.push_back(cleanup);
return InitializationPtr(temporary.release());
}
static InitializationPtr
createIndirectResultInit(SILGenFunction &SGF, SILValue addr,
AbstractionPattern origType,
CanType substType,
SmallVectorImpl<CleanupHandle> &cleanups) {
auto init = createIndirectResultInit(SGF, addr, cleanups);
wrapInSubstToOrigInitialization(SGF, init, origType, substType,
addr->getType());
return init;
}
static void
preparePackResultInit(SILGenFunction &SGF, SILLocation loc,
AbstractionPattern origExpansionType,
CanTupleEltTypeArrayRef resultEltTypes,
SILArgument *packAddr,
SmallVectorImpl<CleanupHandle> &cleanups,
SmallVectorImpl<InitializationPtr> &inits) {
auto loweredPackType = packAddr->getType().castTo<SILPackType>();
assert(loweredPackType->getNumElements() == resultEltTypes.size() &&
"mismatched pack components; possible missing substitutions on orig type?");
// If the pack expanded to nothing, there shouldn't be any initializers
// for it in our context.
if (resultEltTypes.empty()) {
return;
}
auto origPatternType = origExpansionType.getPackExpansionPatternType();
// Induce a formal pack type from the slice of the tuple elements.
CanPackType formalPackType =
CanPackType::get(SGF.getASTContext(), resultEltTypes);
for (auto componentIndex : indices(resultEltTypes)) {
auto resultComponentType = formalPackType.getElementType(componentIndex);
auto loweredComponentType = loweredPackType->getElementType(componentIndex);
assert(isa<PackExpansionType>(loweredComponentType)
== isa<PackExpansionType>(resultComponentType) &&
"need expansions in similar places");
// If we have a pack expansion, the initializer had better be a
// pack expansion expression, and we'll generate a loop for it.
// Preserve enough information to do this properly.
if (isa<PackExpansionType>(resultComponentType)) {
auto resultPatternType =
cast<PackExpansionType>(resultComponentType).getPatternType();
auto expectedPatternTy = SILType::getPrimitiveAddressType(
cast<PackExpansionType>(loweredComponentType).getPatternType());
auto init = PackExpansionInitialization::create(SGF, packAddr,
formalPackType,
componentIndex);
// Remember the cleanup for destroying all of the expansion elements.
auto expansionCleanup = init->getExpansionCleanup();
if (expansionCleanup.isValid())
cleanups.push_back(expansionCleanup);
inits.emplace_back(init.release());
wrapInSubstToOrigInitialization(SGF, inits.back(), origPatternType,
resultPatternType,
expectedPatternTy);
// Otherwise, we should be able to just project out the pack
// address and set up a nomal indirect result into it.
} else {
auto packIndex =
SGF.B.createScalarPackIndex(loc, componentIndex, formalPackType);
auto eltAddr =
SGF.B.createPackElementGet(loc, packIndex, packAddr,
SILType::getPrimitiveAddressType(loweredComponentType));
inits.push_back(createIndirectResultInit(SGF, eltAddr,
origPatternType,
resultComponentType,
cleanups));
}
}
}
static InitializationPtr
prepareIndirectResultInit(SILGenFunction &SGF, SILLocation loc,
CanSILFunctionType fnTypeForResults,
AbstractionPattern origResultType,
CanType resultType,
ArrayRef<SILResultInfo> &allResults,
MutableArrayRef<SILValue> &directResults,
ArrayRef<SILArgument*> &indirectResultAddrs,
SmallVectorImpl<CleanupHandle> &cleanups) {
// Recursively decompose tuple abstraction patterns.
if (origResultType.isTuple()) {
// Normally, we build a compound initialization for the tuple. But
// the initialization we build should match the substituted type,
// so if the tuple in the abstraction pattern vanishes under variadic
// substitution, we actually just want to return the initializer
// for the surviving component.
TupleInitialization *tupleInit = nullptr;
SmallVector<InitializationPtr, 1> singletonEltInit;
bool vanishes = origResultType.doesTupleVanish();
if (!vanishes) {
auto resultTupleType = cast<TupleType>(resultType);
tupleInit = new TupleInitialization(resultTupleType);
tupleInit->SubInitializations.reserve(
cast<TupleType>(resultType)->getNumElements());
}
// The list of element initializers to build into.
auto &eltInits = (vanishes
? static_cast<SmallVectorImpl<InitializationPtr> &>(singletonEltInit)
: tupleInit->SubInitializations);
origResultType.forEachTupleElement(resultType,
[&](TupleElementGenerator &elt) {
if (!elt.isOrigPackExpansion()) {
auto eltInit = prepareIndirectResultInit(SGF, loc, fnTypeForResults,
elt.getOrigType(),
elt.getSubstTypes()[0],
allResults,
directResults,
indirectResultAddrs,
cleanups);
eltInits.push_back(std::move(eltInit));
} else {
assert(allResults[0].isPack());
assert(SGF.silConv.isSILIndirect(allResults[0]));
allResults = allResults.slice(1);
auto packAddr = indirectResultAddrs[0];
indirectResultAddrs = indirectResultAddrs.slice(1);
preparePackResultInit(SGF, loc, elt.getOrigType(), elt.getSubstTypes(),
packAddr, cleanups, eltInits);
}
});
if (vanishes) {
assert(singletonEltInit.size() == 1);
return std::move(singletonEltInit.front());
}
assert(tupleInit);
assert(eltInits.size() == cast<TupleType>(resultType)->getNumElements());
return InitializationPtr(tupleInit);
}
// Okay, pull the next result off the list of results.
auto result = allResults[0];
allResults = allResults.slice(1);
// If it's indirect, we should be emitting into an argument.
InitializationPtr init;
if (SGF.silConv.isSILIndirect(result)) {
// Pull off the next indirect result argument.
SILValue addr = indirectResultAddrs.front();
indirectResultAddrs = indirectResultAddrs.slice(1);
init = createIndirectResultInit(SGF, addr, origResultType, resultType,
cleanups);
} else {
// Otherwise, make an Initialization that stores the value in the
// next element of the directResults array.
auto storeInit = new StoreResultInitialization(directResults[0], cleanups);
directResults = directResults.slice(1);
init = InitializationPtr(storeInit);
SILType expectedResultTy =
SGF.getSILTypeInContext(result, fnTypeForResults);
wrapInSubstToOrigInitialization(SGF, init, origResultType, resultType,
expectedResultTy);
}
return init;
}
/// Prepare an Initialization that will initialize the result of the
/// current function.
///
/// \param directResultsBuffer - will be filled with the direct
/// components of the result
/// \param cleanups - will be filled (after initialization completes)
/// with all the active cleanups managing the result values
std::unique_ptr<Initialization>
SILGenFunction::prepareIndirectResultInit(
SILLocation loc,
AbstractionPattern origResultType,
CanType formalResultType,
SmallVectorImpl<SILValue> &directResultsBuffer,
SmallVectorImpl<CleanupHandle> &cleanups) {
auto fnConv = F.getConventions();
// Make space in the direct-results array for all the entries we need.
directResultsBuffer.append(fnConv.getNumDirectSILResults(), SILValue());
ArrayRef<SILResultInfo> allResults = fnConv.funcTy->getResults();
MutableArrayRef<SILValue> directResults = directResultsBuffer;
ArrayRef<SILArgument*> indirectResultAddrs = F.getIndirectResults();
auto init = ::prepareIndirectResultInit(*this, loc,
fnConv.funcTy,
origResultType,
formalResultType, allResults,
directResults, indirectResultAddrs,
cleanups);
assert(allResults.empty());
assert(directResults.empty());
assert(indirectResultAddrs.empty());
return init;
}
void SILGenFunction::emitReturnExpr(SILLocation branchLoc,
Expr *ret) {
SmallVector<SILValue, 4> directResults;
auto retTy = ret->getType()->getCanonicalType();
AbstractionPattern origRetTy = TypeContext
? TypeContext->OrigType.getFunctionResultType()
: AbstractionPattern(retTy);
if (F.getConventions().hasIndirectSILResults()) {
// Indirect return of an address-only value.
FullExpr scope(Cleanups, CleanupLocation(ret));
// Build an initialization which recursively destructures the tuple.
SmallVector<CleanupHandle, 4> resultCleanups;
InitializationPtr resultInit =
prepareIndirectResultInit(ret, origRetTy,
ret->getType()->getCanonicalType(),
directResults, resultCleanups);
// Emit the result expression into the initialization.
emitExprInto(ret, resultInit.get());
// Deactivate all the cleanups for the result values.
for (auto cleanup : resultCleanups) {
Cleanups.forwardCleanup(cleanup);
}
} else {
// SILValue return.
FullExpr scope(Cleanups, CleanupLocation(ret));
// Does the return context require reabstraction?
RValue RV;
auto loweredRetTy = getLoweredType(retTy);
auto loweredResultTy = getLoweredType(origRetTy, retTy);
if (loweredResultTy != loweredRetTy) {
auto conversion = Conversion::getSubstToOrig(origRetTy, retTy,
loweredRetTy, loweredResultTy);
RV = RValue(*this, ret, emitConvertedRValue(ret, conversion));
} else {
RV = emitRValue(ret);
}
std::move(RV)
.ensurePlusOne(*this, CleanupLocation(ret))
.forwardAll(*this, directResults);
}
Cleanups.emitBranchAndCleanups(ReturnDest, branchLoc, directResults);
}
void StmtEmitter::visitReturnStmt(ReturnStmt *S) {
SILLocation Loc = S->isImplicit() ?
(SILLocation)ImplicitReturnLocation(S) :
(SILLocation)ReturnLocation(S);
SILValue ArgV;
if (!S->hasResult())
// Void return.
SGF.Cleanups.emitBranchAndCleanups(SGF.ReturnDest, Loc);
else if (S->getResult()->getType()->isUninhabited())
// Never return.
SGF.emitIgnoredExpr(S->getResult());
else
SGF.emitReturnExpr(Loc, S->getResult());
}
void StmtEmitter::visitThrowStmt(ThrowStmt *S) {
if (SGF.getASTContext().LangOpts.ThrowsAsTraps) {
SGF.B.createUnconditionalFail(S, "throw turned into a trap");
SGF.B.createUnreachable(S);
return;
}
ManagedValue exn = SGF.emitRValueAsSingleValue(S->getSubExpr());
SGF.emitThrow(S, exn, /* emit a call to willThrow */ true);
}
void StmtEmitter::visitDiscardStmt(DiscardStmt *S) {
// A 'discard' simply triggers the memberwise, consuming destruction of 'self'.
ManagedValue selfValue = SGF.emitRValueAsSingleValue(S->getSubExpr());
CleanupLocation loc(S);
// \c fn could only be null if the type checker failed to call its 'set', or
// we somehow got to SILGen when errors were emitted!
auto *fn = S->getInnermostMethodContext();
if (!fn)
llvm_unreachable("internal compiler error with discard statement");
auto *nominal = fn->getDeclContext()->getSelfNominalTypeDecl();
assert(nominal);
// Check if the nominal's contents are trivial. This is a temporary
// restriction until we get discard implemented the way we want.
for (auto *varDecl : nominal->getStoredProperties()) {
assert(varDecl->hasStorage());
auto varType = varDecl->getTypeInContext();
auto &varTypeLowering = SGF.getTypeLowering(varType);
if (!varTypeLowering.isTrivial()) {
diagnose(getASTContext(),
S->getStartLoc(),
diag::discard_nontrivial_storage,
nominal->getDeclaredInterfaceType());
// emit a note pointing out the problematic storage type
if (auto varLoc = varDecl->getLoc()) {
diagnose(getASTContext(),
varLoc,
diag::discard_nontrivial_storage_note,
varType);
} else {
diagnose(getASTContext(),
nominal->getLoc(),
diag::discard_nontrivial_implicit_storage_note,
nominal->getDeclaredInterfaceType(),
varType);
}
break; // only one diagnostic is needed per discard
}
}
SGF.emitMoveOnlyMemberDestruction(selfValue.forward(SGF), nominal, loc);
}
void StmtEmitter::visitYieldStmt(YieldStmt *S) {
SmallVector<ArgumentSource, 4> sources;
SmallVector<AbstractionPattern, 4> origTypes;
for (auto yield : S->getYields()) {
sources.emplace_back(yield);
origTypes.emplace_back(yield->getType());
}
FullExpr fullExpr(SGF.Cleanups, CleanupLocation(S));
SGF.emitYield(S, sources, origTypes, SGF.CoroutineUnwindDest);
}
void StmtEmitter::visitThenStmt(ThenStmt *S) {
auto *E = S->getResult();
// Retrieve the initialization for the parent SingleValueStmtExpr. If we don't
// have an init, we don't care about the result, emit an ignored expr. This is
// the case if e.g the result is being converted to Void.
if (auto init = SGF.getSingleValueStmtInit(E)) {
SGF.emitExprInto(E, init.get());
} else {
SGF.emitIgnoredExpr(E);
}
}
void StmtEmitter::visitPoundAssertStmt(PoundAssertStmt *stmt) {
SILValue condition;
{
FullExpr scope(SGF.Cleanups, CleanupLocation(stmt));
condition =
SGF.emitRValueAsSingleValue(stmt->getCondition()).getUnmanagedValue();
}
// Extract the i1 from the Bool struct.
auto i1Value = SGF.emitUnwrapIntegerResult(stmt, condition);
SILValue message = SGF.B.createStringLiteral(
stmt, stmt->getMessage(), StringLiteralInst::Encoding::UTF8);
auto resultType = SGF.getASTContext().TheEmptyTupleType;
SGF.B.createBuiltin(
stmt, SGF.getASTContext().getIdentifier("poundAssert"),
SGF.getLoweredType(resultType), {}, {i1Value, message});
}
namespace {
// This is a little cleanup that ensures that there are no jumps out of a
// defer body. The cleanup is only active and installed when emitting the
// body of a defer, and it is disabled at the end. If it ever needs to be
// emitted, it crashes the compiler because Sema missed something.
class DeferEscapeCheckerCleanup : public Cleanup {
SourceLoc deferLoc;
public:
DeferEscapeCheckerCleanup(SourceLoc deferLoc) : deferLoc(deferLoc) {}
void emit(SILGenFunction &SGF, CleanupLocation l, ForUnwind_t forUnwind) override {
assert(false && "Sema didn't catch exit out of a defer?");
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "DeferEscapeCheckerCleanup\n"
<< "State: " << getState() << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
class DeferCleanup : public Cleanup {
SourceLoc deferLoc;
Expr *call;
public:
DeferCleanup(SourceLoc deferLoc, Expr *call)
: deferLoc(deferLoc), call(call) {}
void emit(SILGenFunction &SGF, CleanupLocation l, ForUnwind_t forUnwind) override {
SGF.Cleanups.pushCleanup<DeferEscapeCheckerCleanup>(deferLoc);
auto TheCleanup = SGF.Cleanups.getTopCleanup();
SGF.emitIgnoredExpr(call);
if (SGF.B.hasValidInsertionPoint())
SGF.Cleanups.setCleanupState(TheCleanup, CleanupState::Dead);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "DeferCleanup\n"
<< "State: " << getState() << "\n";
#endif
}
};
} // end anonymous namespace
void StmtEmitter::visitDeferStmt(DeferStmt *S) {
// Emit the closure for the defer, along with its binding.
// If the defer is at the top-level code, insert 'mark_escape_inst'
// to the top-level code to check initialization of any captured globals.
FuncDecl *deferDecl = S->getTempDecl();
auto *Ctx = deferDecl->getDeclContext();
if (isa<TopLevelCodeDecl>(Ctx) && SGF.isEmittingTopLevelCode()) {
auto Captures = deferDecl->getCaptureInfo();
SGF.emitMarkFunctionEscapeForTopLevelCodeGlobals(S, std::move(Captures));
}
SGF.visitFuncDecl(deferDecl);
// Register a cleanup to invoke the closure on any exit paths.
SGF.Cleanups.pushCleanup<DeferCleanup>(S->getDeferLoc(), S->getCallExpr());
}
void StmtEmitter::visitIfStmt(IfStmt *S) {
Scope condBufferScope(SGF.Cleanups, S);
// Create a continuation block.
JumpDest contDest = createJumpDest(S->getThenStmt());
auto contBB = contDest.getBlock();
// Set the destinations for any 'break' and 'continue' statements inside the
// body. Note that "continue" is not valid out of a labeled 'if'.
SGF.BreakContinueDestStack.push_back(
{ S, contDest, JumpDest(CleanupLocation(S)) });
// Set up the block for the false case. If there is an 'else' block, we make
// a new one, otherwise it is our continue block.
JumpDest falseDest = contDest;
if (S->getElseStmt())
falseDest = createJumpDest(S);
// Emit the condition, along with the "then" part of the if properly guarded
// by the condition and a jump to ContBB. If the condition fails, jump to
// the CondFalseBB.
{
// Enter a scope for any bound pattern variables.
LexicalScope trueScope(SGF, S);
auto NumTrueTaken = SGF.loadProfilerCount(S->getThenStmt());
auto NumFalseTaken = ProfileCounter();
if (auto *Else = S->getElseStmt())
NumFalseTaken = SGF.loadProfilerCount(Else);
SGF.emitStmtCondition(S->getCond(), falseDest, S, NumTrueTaken,
NumFalseTaken);
// In the success path, emit the 'then' part if the if.
SGF.emitProfilerIncrement(S->getThenStmt());
SGF.emitStmt(S->getThenStmt());
// Finish the "true part" by cleaning up any temporaries and jumping to the
// continuation block.
if (SGF.B.hasValidInsertionPoint()) {
RegularLocation L(S->getThenStmt());
L.pointToEnd();
SGF.Cleanups.emitBranchAndCleanups(contDest, L);
}
}
// If there is 'else' logic, then emit it.
if (S->getElseStmt()) {
SGF.B.emitBlock(falseDest.getBlock());
visit(S->getElseStmt());
if (SGF.B.hasValidInsertionPoint()) {
RegularLocation L(S->getElseStmt());
L.pointToEnd();
SGF.B.createBranch(L, contBB);
}
}
// If the continuation block was used, emit it now, otherwise remove it.
if (contBB->pred_empty()) {
SGF.eraseBasicBlock(contBB);
} else {
RegularLocation L(S->getThenStmt());
L.pointToEnd();