forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProjection.cpp
1545 lines (1335 loc) · 52.5 KB
/
Projection.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
//===--- Projection.cpp ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-projection"
#include "swift/SIL/Projection.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/SILUndef.h"
#include "llvm/ADT/None.h"
#include "llvm/Support/Debug.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Projection Static Asserts
//===----------------------------------------------------------------------===//
/// These are just for performance and verification. If one needs to make
/// changes that cause the asserts the fire, please update them. The purpose is
/// to prevent these predicates from changing values by mistake.
static_assert(std::is_standard_layout<Projection>::value,
"Expected projection to be a standard layout type");
//===----------------------------------------------------------------------===//
// Utility
//===----------------------------------------------------------------------===//
/// Extract an integer index from a SILValue.
///
/// Return true if IndexVal is a constant index representable as unsigned
/// int. We do not support symbolic projections yet, only 32-bit unsigned
/// integers.
bool swift::getIntegerIndex(SILValue IndexVal, unsigned &IndexConst) {
if (auto *IndexLiteral = dyn_cast<IntegerLiteralInst>(IndexVal)) {
APInt ConstInt = IndexLiteral->getValue();
// IntegerLiterals are signed.
if (ConstInt.isIntN(32) && ConstInt.isNonNegative()) {
IndexConst = (unsigned)ConstInt.getSExtValue();
return true;
}
}
return false;
}
//===----------------------------------------------------------------------===//
// Projection
//===----------------------------------------------------------------------===//
Projection::Projection(SILInstruction *I) : Value() {
if (!I)
return;
/// Initialize given the specific instruction type and verify with asserts
/// that we constructed it correctly.
switch (I->getKind()) {
// If we do not support this instruction kind, then just bail. Index will
// be None so the Projection will be invalid.
default:
return;
case ValueKind::StructElementAddrInst: {
auto *SEAI = cast<StructElementAddrInst>(I);
Value = ValueTy(ProjectionKind::Struct, SEAI->getFieldNo());
assert(getKind() == ProjectionKind::Struct);
assert(getIndex() == SEAI->getFieldNo());
assert(getType(SEAI->getOperand()->getType(), SEAI->getModule()) ==
SEAI->getType());
break;
}
case ValueKind::StructExtractInst: {
auto *SEI = cast<StructExtractInst>(I);
Value = ValueTy(ProjectionKind::Struct, SEI->getFieldNo());
assert(getKind() == ProjectionKind::Struct);
assert(getIndex() == SEI->getFieldNo());
assert(getType(SEI->getOperand()->getType(), SEI->getModule()) ==
SEI->getType());
break;
}
case ValueKind::RefElementAddrInst: {
auto *REAI = cast<RefElementAddrInst>(I);
Value = ValueTy(ProjectionKind::Class, REAI->getFieldNo());
assert(getKind() == ProjectionKind::Class);
assert(getIndex() == REAI->getFieldNo());
assert(getType(REAI->getOperand()->getType(), REAI->getModule()) ==
REAI->getType());
break;
}
case ValueKind::ProjectBoxInst: {
auto *PBI = cast<ProjectBoxInst>(I);
Value = ValueTy(ProjectionKind::Box, (unsigned)0);
assert(getKind() == ProjectionKind::Box);
assert(getIndex() == 0);
assert(getType(PBI->getOperand()->getType(), PBI->getModule()) ==
PBI->getType());
(void) PBI;
break;
}
case ValueKind::TupleExtractInst: {
auto *TEI = cast<TupleExtractInst>(I);
Value = ValueTy(ProjectionKind::Tuple, TEI->getFieldNo());
assert(getKind() == ProjectionKind::Tuple);
assert(getIndex() == TEI->getFieldNo());
assert(getType(TEI->getOperand()->getType(), TEI->getModule()) ==
TEI->getType());
break;
}
case ValueKind::TupleElementAddrInst: {
auto *TEAI = cast<TupleElementAddrInst>(I);
Value = ValueTy(ProjectionKind::Tuple, TEAI->getFieldNo());
assert(getKind() == ProjectionKind::Tuple);
assert(getIndex() == TEAI->getFieldNo());
assert(getType(TEAI->getOperand()->getType(), TEAI->getModule()) ==
TEAI->getType());
break;
}
case ValueKind::UncheckedEnumDataInst: {
auto *UEDI = cast<UncheckedEnumDataInst>(I);
Value = ValueTy(ProjectionKind::Enum, UEDI->getElementNo());
assert(getKind() == ProjectionKind::Enum);
assert(getIndex() == UEDI->getElementNo());
assert(getType(UEDI->getOperand()->getType(), UEDI->getModule()) ==
UEDI->getType());
break;
}
case ValueKind::UncheckedTakeEnumDataAddrInst: {
auto *UTEDAI = cast<UncheckedTakeEnumDataAddrInst>(I);
Value = ValueTy(ProjectionKind::Enum, UTEDAI->getElementNo());
assert(getKind() == ProjectionKind::Enum);
assert(getIndex() == UTEDAI->getElementNo());
assert(getType(UTEDAI->getOperand()->getType(), UTEDAI->getModule()) ==
UTEDAI->getType());
break;
}
case ValueKind::IndexAddrInst: {
// We can represent all integers provided here since getIntegerIndex only
// returns 32 bit values. When that changes, this code will need to be
// updated and a MaxLargeIndex will need to be used here. Currently we
// represent large Indexes using a 64 bit integer, so we don't need to mess
// with anything.
unsigned NewIndex = ~0;
auto *IAI = cast<IndexAddrInst>(I);
if (getIntegerIndex(IAI->getIndex(), NewIndex)) {
assert(NewIndex != unsigned(~0) && "NewIndex should have been changed "
"by getIntegerIndex?!");
Value = ValueTy(ProjectionKind::Index, NewIndex);
assert(getKind() == ProjectionKind::Index);
assert(getIndex() == NewIndex);
}
break;
}
case ValueKind::UpcastInst: {
auto *Ty = I->getType().getSwiftRValueType().getPointer();
assert(Ty->isCanonical());
Value = ValueTy(ProjectionKind::Upcast, Ty);
assert(getKind() == ProjectionKind::Upcast);
assert(getType(I->getOperand(0)->getType(), I->getModule()) ==
I->getType());
break;
}
case ValueKind::UncheckedRefCastInst: {
auto *Ty = I->getType().getSwiftRValueType().getPointer();
assert(Ty->isCanonical());
Value = ValueTy(ProjectionKind::RefCast, Ty);
assert(getKind() == ProjectionKind::RefCast);
assert(getType(I->getOperand(0)->getType(), I->getModule()) ==
I->getType());
break;
}
case ValueKind::UncheckedBitwiseCastInst:
case ValueKind::UncheckedAddrCastInst: {
auto *Ty = I->getType().getSwiftRValueType().getPointer();
assert(Ty->isCanonical());
Value = ValueTy(ProjectionKind::BitwiseCast, Ty);
assert(getKind() == ProjectionKind::BitwiseCast);
assert(getType(I->getOperand(0)->getType(), I->getModule()) ==
I->getType());
break;
}
}
}
NullablePtr<SILInstruction>
Projection::createObjectProjection(SILBuilder &B, SILLocation Loc,
SILValue Base) const {
SILType BaseTy = Base->getType();
// We can only create a value projection from an object.
if (!BaseTy.isObject())
return nullptr;
// Ok, we now know that the type of Base and the type represented by the base
// of this projection match and that this projection can be represented as
// value. Create the instruction if we can. Otherwise, return nullptr.
switch (getKind()) {
case ProjectionKind::Struct:
return B.createStructExtract(Loc, Base, getVarDecl(BaseTy));
case ProjectionKind::Tuple:
return B.createTupleExtract(Loc, Base, getIndex());
case ProjectionKind::Index:
return nullptr;
case ProjectionKind::Enum:
return B.createUncheckedEnumData(Loc, Base, getEnumElementDecl(BaseTy));
case ProjectionKind::Class:
return nullptr;
case ProjectionKind::Box:
return nullptr;
case ProjectionKind::Upcast:
return B.createUpcast(Loc, Base, getCastType(BaseTy));
case ProjectionKind::RefCast:
return B.createUncheckedRefCast(Loc, Base, getCastType(BaseTy));
case ProjectionKind::BitwiseCast:
return B.createUncheckedBitwiseCast(Loc, Base, getCastType(BaseTy));
}
}
NullablePtr<SILInstruction>
Projection::createAddressProjection(SILBuilder &B, SILLocation Loc,
SILValue Base) const {
SILType BaseTy = Base->getType();
// We can only create an address projection from an object, unless we have a
// class.
if (BaseTy.getClassOrBoundGenericClass() || !BaseTy.isAddress())
return nullptr;
// Ok, we now know that the type of Base and the type represented by the base
// of this projection match and that this projection can be represented as
// value. Create the instruction if we can. Otherwise, return nullptr.
switch (getKind()) {
case ProjectionKind::Struct:
return B.createStructElementAddr(Loc, Base, getVarDecl(BaseTy));
case ProjectionKind::Tuple:
return B.createTupleElementAddr(Loc, Base, getIndex());
case ProjectionKind::Index: {
auto IntLiteralTy =
SILType::getBuiltinIntegerType(64, B.getModule().getASTContext());
auto IntLiteralIndex =
B.createIntegerLiteral(Loc, IntLiteralTy, getIndex());
return B.createIndexAddr(Loc, Base, IntLiteralIndex);
}
case ProjectionKind::Enum:
return B.createUncheckedTakeEnumDataAddr(Loc, Base,
getEnumElementDecl(BaseTy));
case ProjectionKind::Class:
return B.createRefElementAddr(Loc, Base, getVarDecl(BaseTy));
case ProjectionKind::Box:
return B.createProjectBox(Loc, Base);
case ProjectionKind::Upcast:
return B.createUpcast(Loc, Base, getCastType(BaseTy));
case ProjectionKind::RefCast:
case ProjectionKind::BitwiseCast:
return B.createUncheckedAddrCast(Loc, Base, getCastType(BaseTy));
}
}
void Projection::getFirstLevelProjections(SILType Ty, SILModule &Mod,
llvm::SmallVectorImpl<Projection> &Out) {
if (auto *S = Ty.getStructOrBoundGenericStruct()) {
unsigned Count = 0;
for (auto *VDecl : S->getStoredProperties()) {
(void) VDecl;
Projection P(ProjectionKind::Struct, Count++);
DEBUG(ProjectionPath X(Ty);
assert(X.getMostDerivedType(Mod) == Ty);
X.append(P);
assert(X.getMostDerivedType(Mod) == Ty.getFieldType(VDecl, Mod));
X.verify(Mod););
Out.push_back(P);
}
return;
}
if (auto TT = Ty.getAs<TupleType>()) {
for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) {
Projection P(ProjectionKind::Tuple, i);
DEBUG(ProjectionPath X(Ty);
assert(X.getMostDerivedType(Mod) == Ty);
X.append(P);
assert(X.getMostDerivedType(Mod) == Ty.getTupleElementType(i));
X.verify(Mod););
Out.push_back(P);
}
return;
}
if (auto *C = Ty.getClassOrBoundGenericClass()) {
unsigned Count = 0;
for (auto *VDecl : C->getStoredProperties()) {
(void) VDecl;
Projection P(ProjectionKind::Class, Count++);
DEBUG(ProjectionPath X(Ty);
assert(X.getMostDerivedType(Mod) == Ty);
X.append(P);
assert(X.getMostDerivedType(Mod) == Ty.getFieldType(VDecl, Mod));
X.verify(Mod););
Out.push_back(P);
}
return;
}
if (auto Box = Ty.getAs<SILBoxType>()) {
Projection P(ProjectionKind::Box, (unsigned)0);
DEBUG(ProjectionPath X(Ty);
assert(X.getMostDerivedType(Mod) == Ty);
X.append(P);
assert(X.getMostDerivedType(Mod) == SILType::getPrimitiveAddressType(
Box->getBoxedType()));
X.verify(Mod););
(void) Box;
Out.push_back(P);
return;
}
}
//===----------------------------------------------------------------------===//
// Projection Path
//===----------------------------------------------------------------------===//
Optional<ProjectionPath> ProjectionPath::getProjectionPath(SILValue Start,
SILValue End) {
ProjectionPath P(Start->getType(), End->getType());
// If Start == End, there is a "trivial" projection path in between the
// two. This is represented by returning an empty ProjectionPath.
if (Start == End)
return std::move(P);
// Do not inspect the body of types with unreferenced types such as bitfields
// and unions. This is currently only associated with structs.
if (Start->getType().aggregateHasUnreferenceableStorage() ||
End->getType().aggregateHasUnreferenceableStorage())
return llvm::NoneType::None;
auto Iter = End;
while (Start != Iter) {
Projection AP(Iter);
if (!AP.isValid())
break;
P.Path.push_back(AP);
Iter = cast<SILInstruction>(*Iter).getOperand(0);
}
// Return None if we have an empty projection list or if Start == Iter.
// We do not worry about th implicit #0 in case of index_addr, as the
// ProjectionPath never allow paths to be compared as a list of indices.
// Only the encoded type+index pair will be compared.
if (P.empty() || Start != Iter)
return llvm::NoneType::None;
// Reverse to get a path from base to most-derived.
std::reverse(P.Path.begin(), P.Path.end());
// Otherwise, return P.
return std::move(P);
}
/// Returns true if the two paths have a non-empty symmetric difference.
///
/// This means that the two objects have the same base but access different
/// fields of the base object.
bool
ProjectionPath::hasNonEmptySymmetricDifference(const ProjectionPath &RHS) const{
// First make sure that both of our base types are the same.
if (BaseType != RHS.BaseType)
return false;
// Otherwise, we have a common base and perhaps some common subpath.
auto LHSIter = Path.begin();
auto RHSIter = RHS.Path.begin();
bool FoundDifferingProjections = false;
// For each index i until min path size...
unsigned i = 0;
for (unsigned e = std::min(size(), RHS.size()); i != e; ++i) {
// Grab the current projections.
const Projection &LHSProj = *LHSIter;
const Projection &RHSProj = *RHSIter;
// If we are accessing different fields of a common object, the two
// projection paths may have a non-empty symmetric difference. We check if
if (LHSProj != RHSProj) {
DEBUG(llvm::dbgs() << " Path different at index: " << i << '\n');
FoundDifferingProjections = true;
break;
}
// Continue if we are accessing the same field.
LHSIter++;
RHSIter++;
}
// All path elements are the same. The symmetric difference is empty.
if (!FoundDifferingProjections)
return false;
// We found differing projections, but we need to make sure that there are no
// casts in the symmetric difference. To be conservative, we only wish to
// allow for casts to appear in the common parts of projections.
for (unsigned li = i, e = size(); li != e; ++li) {
if (LHSIter->isAliasingCast())
return false;
LHSIter++;
}
for (unsigned ri = i, e = RHS.size(); ri != e; ++ri) {
if (RHSIter->isAliasingCast())
return false;
RHSIter++;
}
// If we don't have any casts in our symmetric difference (i.e. only typed
// GEPs), then we can say that these actually have a symmetric difference we
// can understand. The fundamental issue here is that since we do not have any
// notion of size, we cannot know the effect of a cast + gep on the final
// location that we are reaching.
return true;
}
/// TODO: Integrate has empty non-symmetric difference into here.
SubSeqRelation_t
ProjectionPath::computeSubSeqRelation(const ProjectionPath &RHS) const {
// Make sure that both base types are the same. Otherwise, we can not compare
// the projections as sequences.
if (BaseType != RHS.BaseType)
return SubSeqRelation_t::Unknown;
// If both paths are empty, return Equal.
if (empty() && RHS.empty())
return SubSeqRelation_t::Equal;
auto LHSIter = begin();
auto RHSIter = RHS.begin();
unsigned MinPathSize = std::min(size(), RHS.size());
// For each index i until min path size...
for (unsigned i = 0; i != MinPathSize; ++i) {
// Grab the current projections.
const Projection &LHSProj = *LHSIter;
const Projection &RHSProj = *RHSIter;
// If the two projections do not equal exactly, return Unrelated.
//
// TODO: If Index equals zero, then we know that the two lists have nothing
// in common and should return unrelated. If Index is greater than zero,
// then we know that the two projection paths have a common base but a
// non-empty symmetric difference. For now we just return Unrelated since I
// can not remember why I had the special check in the
// hasNonEmptySymmetricDifference code.
if (LHSProj != RHSProj)
return SubSeqRelation_t::Unknown;
// Otherwise increment reverse iterators.
LHSIter++;
RHSIter++;
}
// Ok, we now know that one of the paths is a subsequence of the other. If
// both size() and RHS.size() equal then we know that the entire sequences
// equal.
if (size() == RHS.size())
return SubSeqRelation_t::Equal;
// If MinPathSize == size(), then we know that LHS is a strict subsequence of
// RHS.
if (MinPathSize == size())
return SubSeqRelation_t::LHSStrictSubSeqOfRHS;
// Otherwise, we know that MinPathSize must be RHS.size() and RHS must be a
// strict subsequence of LHS. Assert to check this and return.
assert(MinPathSize == RHS.size() &&
"Since LHS and RHS don't equal and size() != MinPathSize, RHS.size() "
"must equal MinPathSize");
return SubSeqRelation_t::RHSStrictSubSeqOfLHS;
}
Optional<ProjectionPath>
ProjectionPath::removePrefix(const ProjectionPath &Path,
const ProjectionPath &Prefix) {
// We can only subtract paths that have the same base.
if (Path.BaseType != Prefix.BaseType)
return llvm::NoneType::None;
// If Prefix is greater than or equal to Path in size, Prefix can not be a
// prefix of Path. Return None.
unsigned PrefixSize = Prefix.size();
unsigned PathSize = Path.size();
if (PrefixSize >= PathSize)
return llvm::NoneType::None;
// First make sure that the prefix matches.
Optional<ProjectionPath> P = ProjectionPath(Path.BaseType);
for (unsigned i = 0; i < PrefixSize; i++) {
if (Path.Path[i] != Prefix.Path[i]) {
P.reset();
return P;
}
}
// Add the rest of Path to P and return P.
for (unsigned i = PrefixSize, e = PathSize; i != e; ++i) {
P->Path.push_back(Path.Path[i]);
}
return P;
}
raw_ostream &ProjectionPath::print(raw_ostream &os, SILModule &M) {
// Match how the memlocation print tests expect us to print projection paths.
//
// TODO: It sort of sucks having to print these bottom up computationally. We
// should really change the test so that prints out the path elements top
// down the path, rather than constructing all of these intermediate paths.
for (unsigned i : reversed(indices(Path))) {
SILType IterType = getDerivedType(i, M);
auto &IterProj = Path[i];
os << "Address Projection Type: ";
if (IterProj.isNominalKind()) {
auto *Decl = IterProj.getVarDecl(IterType);
IterType = IterProj.getType(IterType, M);
os << IterType.getAddressType() << "\n";
os << "Field Type: ";
Decl->print(os);
os << "\n";
continue;
}
if (IterProj.getKind() == ProjectionKind::Tuple) {
IterType = IterProj.getType(IterType, M);
os << IterType.getAddressType() << "\n";
os << "Index: ";
os << IterProj.getIndex() << "\n";
continue;
}
if (IterProj.getKind() == ProjectionKind::Box) {
os << "Box: ";
continue;
}
llvm_unreachable("Can not print this projection kind");
}
// Migrate the tests to this format eventually.
#if 0
os << "(Projection Path [";
SILType NextType = BaseType;
os << NextType;
for (const Projection &P : Path) {
os << ", ";
NextType = P.getType(NextType, M);
os << NextType;
}
os << "]";
#endif
return os;
}
raw_ostream &ProjectionPath::printProjections(raw_ostream &os, SILModule &M) const {
// Match how the memlocation print tests expect us to print projection paths.
//
// TODO: It sort of sucks having to print these bottom up computationally. We
// should really change the test so that prints out the path elements top
// down the path, rather than constructing all of these intermediate paths.
for (unsigned i : reversed(indices(Path))) {
auto &IterProj = Path[i];
if (IterProj.isNominalKind()) {
os << "Field Type: " << IterProj.getIndex() << "\n";
continue;
}
if (IterProj.getKind() == ProjectionKind::Tuple) {
os << "Index: " << IterProj.getIndex() << "\n";
continue;
}
llvm_unreachable("Can not print this projection kind");
}
return os;
}
void ProjectionPath::dump(SILModule &M) {
print(llvm::outs(), M);
llvm::outs() << "\n";
}
void ProjectionPath::dumpProjections(SILModule &M) const {
printProjections(llvm::outs(), M);
}
void ProjectionPath::verify(SILModule &M) {
#ifndef NDEBUG
SILType IterTy = getBaseType();
assert(IterTy);
for (auto &Proj : Path) {
IterTy = Proj.getType(IterTy, M);
assert(IterTy);
}
#endif
}
void
ProjectionPath::expandTypeIntoLeafProjectionPaths(SILType B, SILModule *Mod,
ProjectionPathList &Paths) {
// Perform a BFS to expand the given type into projectionpath each of
// which contains 1 field from the type.
llvm::SmallVector<ProjectionPath, 8> Worklist;
llvm::SmallVector<Projection, 8> Projections;
// Push an empty projection path to get started.
ProjectionPath P(B);
Worklist.push_back(P);
do {
// Get the next level projections based on current projection's type.
ProjectionPath PP = Worklist.pop_back_val();
// Get the current type to process.
SILType Ty = PP.getMostDerivedType(*Mod);
DEBUG(llvm::dbgs() << "Visiting type: " << Ty << "\n");
// Get the first level projection of the current type.
Projections.clear();
Projection::getFirstLevelProjections(Ty, *Mod, Projections);
// Reached the end of the projection tree, this field can not be expanded
// anymore.
if (Projections.empty()) {
DEBUG(llvm::dbgs() << " No projections. Finished projection list\n");
Paths.push_back(PP);
continue;
}
// If this is a class type, we also have reached the end of the type
// tree for this type.
//
// We do not push its next level projection into the worklist,
// if we do that, we could run into an infinite loop, e.g.
//
// class SelfLoop {
// var p : SelfLoop
// }
//
// struct XYZ {
// var x : Int
// var y : SelfLoop
// }
//
// The worklist would never be empty in this case !.
//
if (Ty.getClassOrBoundGenericClass()) {
DEBUG(llvm::dbgs() << " Found class. Finished projection list\n");
Paths.push_back(PP);
continue;
}
// Keep expanding the location.
for (auto &P : Projections) {
ProjectionPath X(B);
X.append(PP);
///assert(PP.getMostDerivedType(*Mod) == X.getMostDerivedType(*Mod));
X.append(P);
Worklist.push_back(X);
}
// Keep iterating if the worklist is not empty.
} while (!Worklist.empty());
}
bool ProjectionPath::
hasUncoveredNonTrivials(SILType B, SILModule *Mod, ProjectionPathSet &CPaths) {
llvm::SmallVector<ProjectionPath, 4> Worklist, Paths;
// Push an empty projection path to get started.
ProjectionPath P(B);
Worklist.push_back(P);
do {
// Get the next level projections based on current projection's type.
ProjectionPath PP = Worklist.pop_back_val();
// If this path is part of the covered path, then continue.
if (CPaths.find(PP) != CPaths.end())
continue;
// Get the current type to process.
SILType Ty = PP.getMostDerivedType(*Mod);
// Get the first level projection of the current type.
llvm::SmallVector<Projection, 4> Projections;
Projection::getFirstLevelProjections(Ty, *Mod, Projections);
// Reached the end of the projection tree, this field can not be expanded
// anymore.
if (Projections.empty()) {
Paths.push_back(PP);
continue;
}
// There is at least one projection path that leads to a type with
// reference semantics.
if (Ty.getClassOrBoundGenericClass()) {
Paths.push_back(PP);
continue;
}
// Keep expanding the location.
for (auto &P : Projections) {
ProjectionPath X(B);
X.append(PP);
assert(PP.getMostDerivedType(*Mod) == X.getMostDerivedType(*Mod));
X.append(P);
Worklist.push_back(X);
}
// Keep iterating if the worklist is not empty.
} while (!Worklist.empty());
// Check whether any path leads to a non-trivial type.
for (auto &X : Paths) {
if (!X.getMostDerivedType(*Mod).isTrivial(*Mod))
return true;
}
return false;
}
SILValue
ProjectionPath::
createExtract(SILValue Base, SILInstruction *Inst, bool IsVal) const {
// If we found a projection path, but there are no projections, then the two
// loads must be the same, return PrevLI.
if (Path.empty())
return Base;
// Ok, at this point we know that we can construct our aggregate projections
// from our list of address projections.
SILValue LastExtract = Base;
SILBuilder Builder(Inst);
Builder.setCurrentDebugScope(Inst->getFunction()->getDebugScope());
// We use an auto-generated SILLocation for now.
// TODO: make the sil location more precise.
SILLocation Loc = RegularLocation::getAutoGeneratedLocation();
// Construct the path!
for (auto PI = Path.begin(), PE = Path.end(); PI != PE; ++PI) {
if (IsVal) {
LastExtract =
PI->createObjectProjection(Builder, Loc, LastExtract).get();
continue;
}
LastExtract =
PI->createAddressProjection(Builder, Loc, LastExtract).get();
}
// Return the last extract we created.
return LastExtract;
}
bool
Projection::operator<(const Projection &Other) const {
// If we have a nominal kind...
if (isNominalKind()) {
// And Other is also nominal...
if (Other.isNominalKind()) {
// Just compare the value decl pointers.
return getIndex() < Other.getIndex();
}
// Otherwise if Other is not nominal, return true since we always sort
// decls before indices.
return true;
} else {
// If this is not a nominal kind and Other is nominal, return
// false. Nominal kinds are always sorted before non-nominal kinds.
if (Other.isNominalKind())
return false;
// Otherwise, we are both index projections. Compare the indices.
return getIndex() < Other.getIndex();
}
}
NullablePtr<SILInstruction>
Projection::
createAggFromFirstLevelProjections(SILBuilder &B, SILLocation Loc,
SILType BaseType,
llvm::SmallVectorImpl<SILValue> &Values) {
if (BaseType.getStructOrBoundGenericStruct()) {
return B.createStruct(Loc, BaseType, Values);
}
if (BaseType.is<TupleType>()) {
return B.createTuple(Loc, BaseType, Values);
}
return nullptr;
}
SILValue Projection::getOperandForAggregate(SILInstruction *I) const {
switch (getKind()) {
case ProjectionKind::Struct:
if (isa<StructInst>(I))
return I->getOperand(getIndex());
break;
case ProjectionKind::Tuple:
if (isa<TupleInst>(I))
return I->getOperand(getIndex());
break;
case ProjectionKind::Index:
break;
case ProjectionKind::Enum:
if (EnumInst *EI = dyn_cast<EnumInst>(I)) {
if (EI->getElement() == getEnumElementDecl(I->getType())) {
assert(EI->hasOperand() && "expected data operand");
return EI->getOperand();
}
}
break;
case ProjectionKind::Class:
case ProjectionKind::Box:
case ProjectionKind::Upcast:
case ProjectionKind::RefCast:
case ProjectionKind::BitwiseCast:
// There is no SIL instruction to create a class or box by aggregating
// values.
break;
}
return SILValue();
}
//===----------------------------------------------------------------------===//
// ProjectionTreeNode
//===----------------------------------------------------------------------===//
ProjectionTreeNode *
ProjectionTreeNode::getChildForProjection(ProjectionTree &Tree,
const Projection &P) {
for (unsigned Index : ChildProjections) {
ProjectionTreeNode *N = Tree.getNode(Index);
if (N->Proj && N->Proj.getValue() == P) {
return N;
}
}
return nullptr;
}
ProjectionTreeNode *
ProjectionTreeNode::getParent(ProjectionTree &Tree) {
if (!Parent)
return nullptr;
return Tree.getNode(Parent.getValue());
}
const ProjectionTreeNode *
ProjectionTreeNode::getParent(const ProjectionTree &Tree) const {
if (!Parent)
return nullptr;
return Tree.getNode(Parent.getValue());
}
NullablePtr<SILInstruction>
ProjectionTreeNode::
createProjection(SILBuilder &B, SILLocation Loc, SILValue Arg) const {
if (!Proj)
return nullptr;
return Proj->createProjection(B, Loc, Arg);
}
std::string
ProjectionTreeNode::getNameEncoding(const ProjectionTree &PT) const {
std::string Encoding;
const ProjectionTreeNode *Node = this;
while (Node) {
if (Node->isRoot())
break;
Encoding += std::to_string(Node->Proj->getIndex());
Node = Node->getParent(PT);
}
return Encoding;
}
void
ProjectionTreeNode::
processUsersOfValue(ProjectionTree &Tree,
llvm::SmallVectorImpl<ValueNodePair> &Worklist,
SILValue Value, LivenessKind Kind,
llvm::DenseSet<SILInstruction *> &Releases) {
DEBUG(llvm::dbgs() << " Looking at Users:\n");
// For all uses of V...
for (Operand *Op : getNonDebugUses(Value)) {
// Grab the User of V.
SILInstruction *User = Op->getUser();
DEBUG(llvm::dbgs() << " " << *User);
// First try to create a Projection for User.
auto P = Projection::Projection(User);
// If we fail to create a projection, add User as a user to this node and
// continue.
if (!P.isValid()) {
DEBUG(llvm::dbgs() << " Failed to create projection. Adding "
"to non projection user!\n");
// Is the user an epilogue release ?
if (Kind == IgnoreEpilogueReleases) {
bool EpilogueReleaseUser = !Releases.empty();
EpilogueReleaseUser &= Releases.find(User) != Releases.end();
if (EpilogueReleaseUser)
continue;
}
addNonProjectionUser(Op);
continue;
}
DEBUG(llvm::dbgs() << " Created projection.\n");
assert(User->hasValue() && "Projections should have a value");
// we have a projection to the next level children, create the next
// level children nodes lazily.
if (!Initialized)
createNextLevelChildren(Tree);
// Look up the Node for this projection add {User, ChildNode} to the
// worklist.
//
// *NOTE* This means that we will process ChildNode multiple times
// potentially with different projection users.
if (auto *ChildNode = getChildForProjection(Tree, P)) {
DEBUG(llvm::dbgs() << " Found child for projection: "
<< ChildNode->getType() << "\n");
SILValue V = SILValue(User);
Worklist.push_back({V, ChildNode});
} else {
DEBUG(llvm::dbgs() << " Did not find a child for projection!. "
"Adding to non projection user!\b");
// The only projection which we do not currently handle are enums since we
// may not know the correct case. This can be extended in the future.
// Is the user an epilogue release ?
if (Kind == IgnoreEpilogueReleases) {
bool EpilogueReleaseUser = !Releases.empty();
EpilogueReleaseUser &= Releases.find(User) != Releases.end();
if (EpilogueReleaseUser)
continue;
}
addNonProjectionUser(Op);
}
}
}
void
ProjectionTreeNode::
createNextLevelChildrenForStruct(ProjectionTree &Tree, StructDecl *SD) {
SILModule &Mod = Tree.getModule();
unsigned ChildIndex = 0;
SILType Ty = getType();
for (VarDecl *VD : SD->getStoredProperties()) {
assert(Tree.getNode(Index) == this && "Node is not mapped to itself?");
SILType NodeTy = Ty.getFieldType(VD, Mod);
auto *Node = Tree.createChildForStruct(this, NodeTy, VD, ChildIndex++);
DEBUG(llvm::dbgs() << " Creating child for: " << NodeTy << "\n");
DEBUG(llvm::dbgs() << " Projection: "
<< Node->getProjection().getValue().getIndex() << "\n");
ChildProjections.push_back(Node->getIndex());
assert(getChildForProjection(Tree, Node->getProjection().getValue()) == Node &&
"Child not matched to its projection in parent!");
assert(Node->getParent(Tree) == this && "Parent of Child is not Parent?!");
}
}
void
ProjectionTreeNode::
createNextLevelChildrenForTuple(ProjectionTree &Tree, TupleType *TT) {
SILType Ty = getType();
for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) {
assert(Tree.getNode(Index) == this && "Node is not mapped to itself?");
SILType NodeTy = Ty.getTupleElementType(i);
auto *Node = Tree.createChildForTuple(this, NodeTy, i);
DEBUG(llvm::dbgs() << " Creating child for: " << NodeTy << "\n");
DEBUG(llvm::dbgs() << " Projection: "
<< Node->getProjection().getValue().getIndex() << "\n");
ChildProjections.push_back(Node->getIndex());
assert(getChildForProjection(Tree, Node->getProjection().getValue()) == Node &&
"Child not matched to its projection in parent!");
assert(Node->getParent(Tree) == this && "Parent of Child is not Parent?!");
}
}