forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Verifier.cpp
3177 lines (2770 loc) · 134 KB
/
Verifier.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
//===--- Verifier.cpp - Verification of Swift SIL Code --------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "silverifier"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILVTable.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Module.h"
#include "swift/AST/Types.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Basic/Range.h"
#include "llvm/Support/Debug.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
using Lowering::AbstractionPattern;
// This flag is used only to check that sil-combine can properly
// remove any code after unreachable, thus bringing SIL into
// its canonical form which may get temporarily broken during
// intermediate transformations.
static llvm::cl::opt<bool> SkipUnreachableMustBeLastErrors(
"verify-skip-unreachable-must-be-last",
llvm::cl::init(false));
// The verifier is basically all assertions, so don't compile it with NDEBUG to
// prevent release builds from triggering spurious unused variable warnings.
#ifndef NDEBUG
/// Returns true if A is an opened existential type, Self, or is equal to an
/// archetype in F's nested archetype list.
///
/// FIXME: Once Self has been removed in favor of opened existential types
/// everywhere, remove support for self.
static bool isArchetypeValidInFunction(ArchetypeType *A, SILFunction *F) {
// The only two cases where an archetype is always legal in a function is if
// it is self or if it is from an opened existential type. Currently, Self is
// being migrated away from in favor of opened existential types, so we should
// remove the special case here for Self when that process is completed.
//
// *NOTE* Associated types of self are not valid here.
if (!A->getOpenedExistentialType().isNull() || A->getSelfProtocol())
return true;
// Ok, we have an archetype, make sure it is in the nested archetypes of our
// caller.
for (auto Iter : F->getContextGenericParams()->getAllNestedArchetypes())
if (A->isEqual(&*Iter))
return true;
return A->getIsRecursive();
}
namespace {
/// Metaprogramming-friendly base class.
template <class Impl>
class SILVerifierBase : public SILVisitor<Impl> {
public:
// visitCLASS calls visitPARENT and checkCLASS.
// checkCLASS does nothing by default.
#define VALUE(CLASS, PARENT) \
void visit##CLASS(CLASS *I) { \
static_cast<Impl*>(this)->visit##PARENT(I); \
static_cast<Impl*>(this)->check##CLASS(I); \
} \
void check##CLASS(CLASS *I) {}
#include "swift/SIL/SILNodes.def"
void visitValueBase(ValueBase *V) {
static_cast<Impl*>(this)->checkValueBase(V);
}
void checkValueBase(ValueBase *V) {}
};
} // end anonymous namespace
namespace {
/// The SIL verifier walks over a SIL function / basic block / instruction,
/// checking and enforcing its invariants.
class SILVerifier : public SILVerifierBase<SILVerifier> {
Module *M;
const SILFunction &F;
Lowering::TypeConverter &TC;
const SILInstruction *CurInstruction = nullptr;
DominanceInfo *Dominance = nullptr;
SILVerifier(const SILVerifier&) = delete;
void operator=(const SILVerifier&) = delete;
public:
void _require(bool condition, const Twine &complaint,
const std::function<void()> &extraContext = nullptr) {
if (condition) return;
llvm::dbgs() << "SIL verification failed: " << complaint << "\n";
if (extraContext) extraContext();
if (CurInstruction) {
llvm::dbgs() << "Verifying instruction:\n";
CurInstruction->printInContext(llvm::dbgs());
llvm::dbgs() << "In function:\n";
F.print(llvm::dbgs());
} else {
llvm::dbgs() << "In function:\n";
F.print(llvm::dbgs());
}
abort();
}
#define require(condition, complaint) \
_require(bool(condition), complaint ": " #condition)
template <class T> typename CanTypeWrapperTraits<T>::type
_requireObjectType(SILType type, const Twine &valueDescription,
const char *typeName) {
_require(type.isObject(), valueDescription + " must be an object");
auto result = type.getAs<T>();
_require(bool(result), valueDescription + " must have type " + typeName);
return result;
}
template <class T> typename CanTypeWrapperTraits<T>::type
_requireObjectType(SILValue value, const Twine &valueDescription,
const char *typeName) {
return _requireObjectType<T>(value.getType(), valueDescription, typeName);
}
#define requireObjectType(type, value, valueDescription) \
_requireObjectType<type>(value, valueDescription, #type)
template <class T>
typename CanTypeWrapperTraits<T>::type
_forbidObjectType(SILType type, const Twine &valueDescription,
const char *typeName) {
_require(type.isObject(), valueDescription + " must be an object");
auto result = type.getAs<T>();
_require(!bool(result),
valueDescription + " must not have type " + typeName);
return result;
}
template <class T>
typename CanTypeWrapperTraits<T>::type
_forbidObjectType(SILValue value, const Twine &valueDescription,
const char *typeName) {
return _forbidObjectType<T>(value.getType(), valueDescription, typeName);
}
#define forbidObjectType(type, value, valueDescription) \
_forbidObjectType<type>(value, valueDescription, #type)
// Require that the operand is a non-optional, non-unowned reference-counted
// type.
void requireReferenceValue(SILValue value, const Twine &valueDescription) {
require(value.getType().isObject(), valueDescription +" must be an object");
require(value.getType().isReferenceCounted(F.getModule()),
valueDescription + " must have reference semantics");
forbidObjectType(UnownedStorageType, value, valueDescription);
}
// Require that the operand is a reference-counted type, or an Optional
// thereof.
void requireReferenceOrOptionalReferenceValue(SILValue value,
const Twine &valueDescription) {
require(value.getType().isObject(), valueDescription +" must be an object");
auto objectTy = value.getType();
OptionalTypeKind otk;
if (auto optObjTy = objectTy.getAnyOptionalObjectType(F.getModule(), otk)) {
objectTy = optObjTy;
}
require(objectTy.isReferenceCounted(F.getModule()),
valueDescription + " must have reference semantics");
}
// Require that the operand is a type that supports reference storage
// modifiers.
void requireReferenceStorageCapableValue(SILValue value,
const Twine &valueDescription) {
requireReferenceOrOptionalReferenceValue(value, valueDescription);
require(!value.getType().is<SILFunctionType>(),
valueDescription + " cannot apply to a function type");
}
// Require that the operand is a reference-counted type, or potentially an
// optional thereof.
void requireRetainablePointerValue(SILValue value,
const Twine &valueDescription) {
require(value.getType().isObject(), valueDescription +" must be an object");
require(value.getType().hasRetainablePointerRepresentation(),
valueDescription + " must have retainable pointer representation");
}
/// Assert that two types are equal.
void requireSameType(SILType type1, SILType type2, const Twine &complaint) {
_require(type1 == type2, complaint, [&] {
llvm::dbgs() << " " << type1 << "\n " << type2 << '\n';
});
}
/// Require two function types to be ABI-compatible.
void requireABICompatibleFunctionTypes(CanSILFunctionType type1,
CanSILFunctionType type2,
const Twine &what) {
auto complain = [=](const char *msg) -> std::function<void()> {
return [=]{
llvm::dbgs() << " " << msg << '\n'
<< " " << type1 << "\n " << type2 << '\n';
};
};
auto complainBy = [=](std::function<void()> msg) -> std::function<void()> {
return [=]{
msg();
llvm::dbgs() << '\n';
llvm::dbgs() << " " << type1 << "\n " << type2 << '\n';
};
};
// The calling convention and function representation can't be changed.
_require(type1->getRepresentation() == type2->getRepresentation(), what,
complain("Different function representations"));
// TODO: We should compare generic signatures. Class and witness methods
// allow variance in "self"-fulfilled parameters; other functions must
// match exactly.
auto signature1 = type1->getGenericSignature();
auto signature2 = type2->getGenericSignature();
auto getAnyOptionalObjectTypeInContext = [&](CanGenericSignature sig,
SILType type) {
Lowering::GenericContextScope context(F.getModule().Types, sig);
OptionalTypeKind _;
return type.getAnyOptionalObjectType(F.getModule(), _);
};
// TODO: More sophisticated param and return ABI compatibility rules could
// diverge.
std::function<bool (SILType, SILType)>
areABICompatibleParamsOrReturns = [&](SILType a, SILType b) -> bool {
// Address parameters are all ABI-compatible, though the referenced
// values may not be. Assume whoever's doing this knows what they're
// doing.
if (a.isAddress() && b.isAddress())
return true;
// Addresses aren't compatible with values.
// TODO: An exception for pointerish types?
else if (a.isAddress() || b.isAddress())
return false;
// Tuples are ABI compatible if their elements are.
// TODO: Should destructure recursively.
SmallVector<CanType, 1> aElements, bElements;
if (auto tup = a.getAs<TupleType>()) {
auto types = tup.getElementTypes();
aElements.append(types.begin(), types.end());
} else {
aElements.push_back(a.getSwiftRValueType());
}
if (auto tup = b.getAs<TupleType>()) {
auto types = tup.getElementTypes();
bElements.append(types.begin(), types.end());
} else {
bElements.push_back(b.getSwiftRValueType());
}
if (aElements.size() != bElements.size())
return false;
for (unsigned i : indices(aElements)) {
auto aa = SILType::getPrimitiveObjectType(aElements[i]),
bb = SILType::getPrimitiveObjectType(bElements[i]);
// Equivalent types are always ABI-compatible.
if (aa == bb)
continue;
// FIXME: If one or both types are dependent, we can't accurately assess
// whether they're ABI-compatible without a generic context. We can
// do a better job here when dependent types are related to their
// generic signatures.
if (aa.hasTypeParameter() || bb.hasTypeParameter())
continue;
// Bridgeable object types are interchangeable.
if (aa.isBridgeableObjectType() && bb.isBridgeableObjectType())
continue;
// Optional and IUO are interchangeable if their elements are.
auto aObject = getAnyOptionalObjectTypeInContext(signature1, aa);
auto bObject = getAnyOptionalObjectTypeInContext(signature2, bb);
if (aObject && bObject
&& areABICompatibleParamsOrReturns(aObject, bObject))
continue;
// Optional objects are ABI-interchangeable with non-optionals;
// None is represented by a null pointer.
if (aObject && aObject.isBridgeableObjectType()
&& bb.isBridgeableObjectType())
continue;
if (bObject && bObject.isBridgeableObjectType()
&& aa.isBridgeableObjectType())
continue;
// Optional thick metatypes are ABI-interchangeable with non-optionals
// too.
if (aObject)
if (auto aObjMeta = aObject.getAs<MetatypeType>())
if (auto bMeta = bb.getAs<MetatypeType>())
if (aObjMeta->getRepresentation() == bMeta->getRepresentation()
&& bMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
if (bObject)
if (auto aMeta = aa.getAs<MetatypeType>())
if (auto bObjMeta = bObject.getAs<MetatypeType>())
if (aMeta->getRepresentation() == bObjMeta->getRepresentation()
&& aMeta->getRepresentation() != MetatypeRepresentation::Thin)
continue;
// Function types are interchangeable if they're also ABI-compatible.
if (auto aFunc = aa.getAs<SILFunctionType>())
if (auto bFunc = bb.getAs<SILFunctionType>()) {
// FIXME
requireABICompatibleFunctionTypes(aFunc, bFunc, what);
return true;
}
// Metatypes are interchangeable with metatypes with the same
// representation.
if (auto aMeta = aa.getAs<MetatypeType>())
if (auto bMeta = bb.getAs<MetatypeType>())
if (aMeta->getRepresentation() == bMeta->getRepresentation())
continue;
// Other types must match exactly.
return false;
}
return true;
};
// Check the return value.
auto result1 = type1->getResult();
auto result2 = type2->getResult();
_require(result1.getConvention() == result2.getConvention(), what,
complain("Different return value conventions"));
_require(areABICompatibleParamsOrReturns(result1.getSILType(),
result2.getSILType()), what,
complain("ABI-incompatible return values"));
// Our error result conventions are designed to be ABI compatible
// with functions lacking error results. Just make sure that the
// actual conventions match up.
if (type1->hasErrorResult() && type2->hasErrorResult()) {
auto error1 = type1->getErrorResult();
auto error2 = type2->getErrorResult();
_require(error1.getConvention() == error2.getConvention(), what,
complain("Different error result conventions"));
_require(areABICompatibleParamsOrReturns(error1.getSILType(),
error2.getSILType()), what,
complain("ABI-incompatible error results"));
}
// Check the parameters.
// TODO: Could allow known-empty types to be inserted or removed, but SIL
// doesn't know what empty types are yet.
_require(type1->getParameters().size() == type2->getParameters().size(),
what, complain("different number of parameters"));
for (unsigned i : indices(type1->getParameters())) {
auto param1 = type1->getParameters()[i];
auto param2 = type2->getParameters()[i];
_require(param1.getConvention() == param2.getConvention(), what,
complainBy([=] {
llvm::dbgs() << "Different conventions for parameter " << i;
}));
_require(areABICompatibleParamsOrReturns(param1.getSILType(),
param2.getSILType()), what,
complainBy([=] {
llvm::dbgs() << "ABI-incompatible types for parameter " << i;
}));
}
}
void requireSameFunctionComponents(CanSILFunctionType type1,
CanSILFunctionType type2,
const Twine &what) {
require(type1->getResult() == type2->getResult(),
"result types of " + what + " do not match");
require(type1->getParameters().size() ==
type2->getParameters().size(),
"inputs of " + what + " do not match in count");
for (auto i : indices(type1->getParameters())) {
require(type1->getParameters()[i] ==
type2->getParameters()[i],
"input " + Twine(i) + " of " + what + " do not match");
}
}
SILVerifier(const SILFunction &F)
: M(F.getModule().getSwiftModule()), F(F), TC(F.getModule().Types),
Dominance(nullptr) {
if (F.isExternalDeclaration())
return;
// Check to make sure that all blocks are well formed. If not, the
// SILVerifier object will explode trying to compute dominance info.
for (auto &BB : F) {
require(!BB.empty(), "Basic blocks cannot be empty");
require(isa<TermInst>(BB.back()),
"Basic blocks must end with a terminator instruction");
}
Dominance = new DominanceInfo(const_cast<SILFunction*>(&F));
auto *DebugScope = F.getDebugScope();
require(DebugScope, "All SIL functions must have a debug scope");
require(DebugScope && DebugScope->SILFn == &F,
"Scope of SIL function points to different function");
}
~SILVerifier() {
if (Dominance)
delete Dominance;
}
void visitSILArgument(SILArgument *arg) {
checkLegalTypes(arg->getFunction(), arg);
}
void visitSILInstruction(SILInstruction *I) {
CurInstruction = I;
checkSILInstruction(I);
// Check the SILLLocation attached to the instruction.
checkInstructionsSILLocation(I);
checkLegalTypes(I->getFunction(), I);
}
void checkSILInstruction(SILInstruction *I) {
const SILBasicBlock *BB = I->getParent();
require(BB, "Instruction with null parent");
require(I->getFunction(), "Instruction not in function");
// Check that non-terminators look ok.
if (!isa<TermInst>(I)) {
require(!BB->empty(), "Can't be in a parent block if it is empty");
require(&*BB->rbegin() != I,
"Non-terminators cannot be the last in a block");
} else {
// Skip the check for UnreachableInst, if explicitly asked to do so.
if (!isa<UnreachableInst>(I) || !SkipUnreachableMustBeLastErrors)
require(&*BB->rbegin() == I,
"Terminator must be the last in block");
}
// Verify that all of our uses are in this function.
for (Operand *use : I->getUses()) {
auto user = use->getUser();
require(user, "instruction user is null?");
require(isa<SILInstruction>(user),
"instruction used by non-instruction");
auto userI = cast<SILInstruction>(user);
require(userI->getParent(),
"instruction used by unparented instruction");
require(userI->getFunction() == &F,
"instruction used by instruction in different function");
auto operands = userI->getAllOperands();
require(operands.begin() <= use && use <= operands.end(),
"use doesn't actually belong to instruction it claims to");
}
// Verify some basis structural stuff about an instruction's operands.
for (auto &operand : I->getAllOperands()) {
require(operand.get().isValid(), "instruction has null operand");
if (auto *valueI = dyn_cast<SILInstruction>(operand.get())) {
require(valueI->getParent(),
"instruction uses value of unparented instruction");
require(valueI->getFunction() == &F,
"instruction uses value of instruction from another function");
require(Dominance->properlyDominates(valueI, I),
"instruction isn't dominated by its operand");
}
if (auto *valueBBA = dyn_cast<SILArgument>(operand.get())) {
require(valueBBA->getParent(),
"instruction uses value of unparented instruction");
require(valueBBA->getFunction() == &F,
"bb argument value from another function");
require(Dominance->dominates(valueBBA->getParent(), I->getParent()),
"instruction isn't dominated by its bb argument operand");
}
require(operand.getUser() == I,
"instruction's operand's owner isn't the instruction");
require(isInValueUses(&operand), "operand value isn't used by operand");
// Make sure that if operand is generic that its primary archetypes match
// the function context.
checkLegalTypes(I->getFunction(), operand.get().getDef());
}
}
/// Return the SIL function of a SILDebugScope's ancestor.
static SILFunction *getFunction(const SILDebugScope *DS) {
if (DS->InlinedCallSite)
return getFunction(DS->InlinedCallSite);
if (DS->Parent)
return getFunction(DS->Parent);
return DS->SILFn;
}
void checkInstructionsSILLocation(SILInstruction *I) {
// Check the debug scope.
auto *DS = I->getDebugScope();
if (DS && !maybeScopeless(*I)) {
require(DS, "instruction has a location, but no scope");
require(getFunction(DS) == I->getFunction(),
"parent scope of instruction points to a different function");
}
require(!DS || DS->InlinedCallSite || DS->SILFn == I->getFunction(),
"scope of a non-inlined instruction points to different function");
// Check the location kind.
SILLocation L = I->getLoc();
SILLocation::LocationKind LocKind = L.getKind();
ValueKind InstKind = I->getKind();
// Regular locations and SIL file locations are allowed on all instructions.
if (LocKind == SILLocation::RegularKind ||
LocKind == SILLocation::SILFileKind)
return;
if (LocKind == SILLocation::CleanupKind ||
LocKind == SILLocation::InlinedKind)
require(InstKind != ValueKind::ReturnInst ||
InstKind != ValueKind::AutoreleaseReturnInst,
"cleanup and inlined locations are not allowed on return instructions");
if (LocKind == SILLocation::ReturnKind ||
LocKind == SILLocation::ImplicitReturnKind)
require(InstKind == ValueKind::BranchInst ||
InstKind == ValueKind::ReturnInst ||
InstKind == ValueKind::AutoreleaseReturnInst ||
InstKind == ValueKind::UnreachableInst,
"return locations are only allowed on branch and return instructions");
if (LocKind == SILLocation::ArtificialUnreachableKind)
require(InstKind == ValueKind::UnreachableInst,
"artificial locations are only allowed on Unreachable instructions");
}
/// Check that the types of this value producer are all legal in the function
/// context in which it exists.
void checkLegalTypes(SILFunction *F, ValueBase *value) {
for (auto type : value->getTypes()) {
checkLegalType(F, type);
}
}
/// Check that the given type is a legal SIL value.
void checkLegalType(SILFunction *F, SILType type) {
auto rvalueType = type.getSwiftRValueType();
require(!isa<LValueType>(rvalueType),
"l-value types are not legal in SIL");
require(!isa<AnyFunctionType>(rvalueType),
"AST function types are not legal in SIL");
rvalueType.visit([&](Type t) {
auto *A = dyn_cast<ArchetypeType>(t.getPointer());
if (!A)
return;
require(isArchetypeValidInFunction(A, F),
"Operand is of an ArchetypeType that does not exist in the "
"Caller's generic param list.");
});
}
/// Check that this operand appears in the use-chain of the value it uses.
static bool isInValueUses(const Operand *operand) {
for (auto use : operand->get()->getUses())
if (use == operand)
return true;
return false;
}
/// \return True if all of the users of the AllocStack instruction \p ASI are
/// inside the same basic block.
static bool isSingleBlockUsage(AllocStackInst *ASI, DominanceInfo *Dominance){
SILBasicBlock *BB = ASI->getParent();
for (auto UI = ASI->use_begin(), E = ASI->use_end(); UI != E; ++UI)
if (UI->getUser()->getParent() != BB &&
Dominance->isReachableFromEntry(UI->getUser()->getParent()))
return false;
return true;
}
void checkAllocStackInst(AllocStackInst *AI) {
require(AI->getContainerResult().getType().isLocalStorage(),
"first result of alloc_stack must be local storage");
require(AI->getAddressResult().getType().isAddress(),
"second result of alloc_stack must be an address type");
require(AI->getContainerResult().getType().getSwiftRValueType()
== AI->getElementType().getSwiftRValueType(),
"container storage must be for allocated type");
// Scan the parent block of AI and check that the users of AI inside this
// block are inside the lifetime of the allocated memory.
SILBasicBlock *SBB = AI->getParent();
bool Allocated = true;
for (auto Inst = AI->getIterator(), E = SBB->end(); Inst != E; ++Inst) {
if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
if (LI->getOperand().getDef() == AI)
require(Allocated, "AllocStack used by Load outside its lifetime");
if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
if (SI->getDest().getDef() == AI)
require(Allocated, "AllocStack used by Store outside its lifetime");
if (DeallocStackInst *DSI = dyn_cast<DeallocStackInst>(Inst))
if (DSI->getOperand() == AI)
Allocated = false;
}
// If the AllocStackInst is also deallocated inside the allocation block
// then make sure that all the users are inside that block.
if (!Allocated) {
require(isSingleBlockUsage(AI, Dominance),
"AllocStack has users in other basic blocks after allocation");
}
}
void checkAllocRefInst(AllocRefInst *AI) {
requireReferenceValue(AI, "Result of alloc_ref");
}
void checkAllocRefDynamicInst(AllocRefDynamicInst *ARDI) {
requireReferenceValue(ARDI, "Result of alloc_ref_dynamic");
require(ARDI->getOperand().getType().is<AnyMetatypeType>(),
"operand of alloc_ref_dynamic must be of metatype type");
auto metaTy = ARDI->getOperand().getType().castTo<AnyMetatypeType>();
require(metaTy->hasRepresentation(),
"operand of alloc_ref_dynamic must have a metatype representation");
if (ARDI->isObjC()) {
require(metaTy->getRepresentation() == MetatypeRepresentation::ObjC,
"alloc_ref_dynamic @objc requires operand of ObjC metatype");
} else {
require(metaTy->getRepresentation() == MetatypeRepresentation::Thick,
"alloc_ref_dynamic requires operand of thick metatype");
}
}
/// Check the substitutions passed to an apply or partial_apply.
CanSILFunctionType checkApplySubstitutions(ArrayRef<Substitution> subs,
SILType calleeTy) {
auto fnTy = requireObjectType(SILFunctionType, calleeTy, "callee operand");
// If there are substitutions, verify them and apply them to the callee.
if (subs.empty()) {
require(!fnTy->isPolymorphic(),
"callee of apply without substitutions must not be polymorphic");
return fnTy;
}
require(fnTy->isPolymorphic(),
"callee of apply with substitutions must be polymorphic");
// Apply the substitutions.
return fnTy->substGenericArgs(F.getModule(), M, subs);
}
void checkFullApplySite(FullApplySite site) {
// If we have a substitution whose replacement type is an archetype, make
// sure that the replacement archetype is in the context generic params of
// the caller function.
// For each substitution Sub in AI...
for (auto &Sub : site.getSubstitutions()) {
// If Sub's replacement is not an archetype type or is from an opened
// existential type, skip it...
auto *A = Sub.getReplacement()->getAs<ArchetypeType>();
if (!A)
continue;
require(isArchetypeValidInFunction(A, site.getInstruction()->getFunction()),
"Archetype to be substituted must be valid in function.");
}
// Then make sure that we have a type that can be substituted for the
// callee.
auto substTy = checkApplySubstitutions(site.getSubstitutions(),
site.getCallee().getType());
require(site.getOrigCalleeType()->getRepresentation() ==
site.getSubstCalleeType()->getRepresentation(),
"calling convention difference between types");
require(!site.getSubstCalleeType()->isPolymorphic(),
"substituted callee type should not be generic");
requireSameType(SILType::getPrimitiveObjectType(substTy),
SILType::getPrimitiveObjectType(site.getSubstCalleeType()),
"substituted callee type does not match substitutions");
// Check that the arguments and result match.
require(site.getArguments().size() ==
substTy->getParameters().size(),
"apply doesn't have right number of arguments for function");
for (size_t i = 0, size = site.getArguments().size(); i < size; ++i) {
requireSameType(site.getArguments()[i].getType(),
substTy->getParameters()[i].getSILType(),
"operand of 'apply' doesn't match function input type");
}
}
void checkApplyInst(ApplyInst *AI) {
checkFullApplySite(AI);
auto substTy = AI->getSubstCalleeType();
require(AI->getType() == substTy->getResult().getSILType(),
"type of apply instruction doesn't match function result type");
if (AI->isNonThrowing()) {
require(substTy->hasErrorResult(),
"nothrow flag used for callee without error result");
} else {
require(!substTy->hasErrorResult(),
"apply instruction cannot call function with error result");
}
// Check that if the apply is of a noreturn callee, make sure that an
// unreachable is the next instruction.
if (AI->getModule().getStage() == SILStage::Raw ||
!AI->getCallee().getType().getAs<SILFunctionType>()->isNoReturn())
return;
require(isa<UnreachableInst>(std::next(SILBasicBlock::iterator(AI))),
"No return apply without an unreachable as a next instruction.");
}
void checkTryApplyInst(TryApplyInst *AI) {
checkFullApplySite(AI);
auto substTy = AI->getSubstCalleeType();
auto normalBB = AI->getNormalBB();
require(normalBB->bbarg_size() == 1,
"normal destination of try_apply must take one argument");
requireSameType((*normalBB->bbarg_begin())->getType(),
substTy->getResult().getSILType(),
"normal destination of try_apply must take argument "
"of normal result type");
auto errorBB = AI->getErrorBB();
require(substTy->hasErrorResult(),
"try_apply must call function with error result");
require(errorBB->bbarg_size() == 1,
"error destination of try_apply must take one argument");
requireSameType((*errorBB->bbarg_begin())->getType(),
substTy->getErrorResult().getSILType(),
"error destination of try_apply must take argument "
"of error result type");
}
void verifyLLVMIntrinsic(BuiltinInst *BI, llvm::Intrinsic::ID ID) {
// Certain llvm instrinsic require constant values as their operands.
// Consequently, these must not be phi nodes (aka. basic block arguments).
switch (ID) {
default:
break;
case llvm::Intrinsic::ctlz: // llvm.ctlz
case llvm::Intrinsic::cttz: // llvm.cttz
break;
case llvm::Intrinsic::memcpy:
case llvm::Intrinsic::memmove:
case llvm::Intrinsic::memset:
require(!isa<SILArgument>(BI->getArguments()[3]),
"alignment argument of memory intrinsics must be an integer "
"literal");
require(!isa<SILArgument>(BI->getArguments()[4]),
"isvolatile argument of memory intrinsics must be an integer "
"literal");
break;
case llvm::Intrinsic::lifetime_start:
case llvm::Intrinsic::lifetime_end:
case llvm::Intrinsic::invariant_start:
require(!isa<SILArgument>(BI->getArguments()[0]),
"size argument of memory use markers must be an integer literal");
break;
case llvm::Intrinsic::invariant_end:
require(!isa<SILArgument>(BI->getArguments()[1]),
"llvm.invariant.end parameter #2 must be an integer literal");
break;
}
}
void checkPartialApplyInst(PartialApplyInst *PAI) {
auto resultInfo = requireObjectType(SILFunctionType, PAI,
"result of partial_apply");
verifySILFunctionType(resultInfo);
require(resultInfo->getExtInfo().hasContext(),
"result of closure cannot have a thin function type");
// If we have a substitution whose replacement type is an archetype, make
// sure that the replacement archetype is in the context generic params of
// the caller function.
// For each substitution Sub in AI...
for (auto &Sub : PAI->getSubstitutions()) {
// If Sub's replacement is not an archetype type or is from an opened
// existential type, skip it...
Sub.getReplacement().visit([&](Type t) {
auto *A = t->getAs<ArchetypeType>();
if (!A)
return;
require(isArchetypeValidInFunction(A, PAI->getFunction()),
"Archetype to be substituted must be valid in function.");
});
}
auto substTy = checkApplySubstitutions(PAI->getSubstitutions(),
PAI->getCallee().getType());
require(!PAI->getSubstCalleeType()->isPolymorphic(),
"substituted callee type should not be generic");
requireSameType(SILType::getPrimitiveObjectType(substTy),
SILType::getPrimitiveObjectType(PAI->getSubstCalleeType()),
"substituted callee type does not match substitutions");
// The arguments must match the suffix of the original function's input
// types.
require(PAI->getArguments().size() +
resultInfo->getParameters().size()
== substTy->getParameters().size(),
"result of partial_apply should take as many inputs as were not "
"applied by the instruction");
unsigned offset =
substTy->getParameters().size() - PAI->getArguments().size();
for (unsigned i = 0, size = PAI->getArguments().size(); i < size; ++i) {
require(PAI->getArguments()[i].getType()
== substTy->getParameters()[i + offset].getSILType(),
"applied argument types do not match suffix of function type's "
"inputs");
}
// The arguments to the result function type must match the prefix of the
// original function's input types.
for (unsigned i = 0, size = resultInfo->getParameters().size();
i < size; ++i) {
require(resultInfo->getParameters()[i] ==
substTy->getParameters()[i],
"inputs to result function type do not match unapplied inputs "
"of original function");
}
// The "returns inner pointer" convention doesn't survive through a partial
// application, since the thunk takes responsibility for lifetime-extending
// 'self'.
auto expectedResult = substTy->getResult();
if (expectedResult.getConvention() == ResultConvention::UnownedInnerPointer)
{
expectedResult = SILResultInfo(expectedResult.getType(),
ResultConvention::Unowned);
require(resultInfo->getResult() == expectedResult,
"result type of result function type for partially applied "
"@unowned_inner_pointer function should have @unowned convention");
} else {
require(resultInfo->getResult() == expectedResult,
"result type of result function type does not match original "
"function");
}
}
void checkBuiltinInst(BuiltinInst *BI) {
// Check for special constraints on llvm intrinsics.
if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::not_intrinsic)
verifyLLVMIntrinsic(BI, BI->getIntrinsicInfo().ID);
}
bool isValidLinkageForFragileRef(SILLinkage linkage) {
switch (linkage) {
case SILLinkage::Private:
case SILLinkage::PrivateExternal:
case SILLinkage::Hidden:
case SILLinkage::HiddenExternal:
return false;
case SILLinkage::Shared:
case SILLinkage::SharedExternal:
// This handles some kind of generated functions, like constructors
// of clang imported types.
// TODO: check why those functions are not fragile anyway and make
// a less conservative check here.
return true;
case SILLinkage::Public:
case SILLinkage::PublicExternal:
return true;
}
}
void checkFunctionRefInst(FunctionRefInst *FRI) {
auto fnType = requireObjectType(SILFunctionType, FRI,
"result of function_ref");
require(!fnType->getExtInfo().hasContext(),
"function_ref should have a context-free function result");
if (F.isFragile()) {
SILFunction *RefF = FRI->getReferencedFunction();
require(RefF->isFragile()
|| isValidLinkageForFragileRef(RefF->getLinkage())
|| RefF->isExternalDeclaration(),
"function_ref inside fragile function cannot "
"reference a private or hidden symbol");
}
verifySILFunctionType(fnType);
}
void checkGlobalAddrInst(GlobalAddrInst *GAI) {
require(GAI->getType().isAddress(),
"global_addr must have an address result type");
require(GAI->getType().getObjectType() ==
GAI->getReferencedGlobal()->getLoweredType(),
"global_addr must be the address type of the variable it "
"references");
if (F.isFragile()) {
SILGlobalVariable *RefG = GAI->getReferencedGlobal();
require(RefG->isFragile()
|| isValidLinkageForFragileRef(RefG->getLinkage()),
"global_addr inside fragile function cannot "
"reference a private or hidden symbol");
}
}
void checkIntegerLiteralInst(IntegerLiteralInst *ILI) {
require(ILI->getType().is<BuiltinIntegerType>(),
"invalid integer literal type");
}
void checkLoadInst(LoadInst *LI) {
require(LI->getType().isObject(), "Result of load must be an object");
require(LI->getOperand().getType().isAddress(),
"Load operand must be an address");
require(LI->getOperand().getType().getObjectType() == LI->getType(),
"Load operand type and result type mismatch");
}
void checkStoreInst(StoreInst *SI) {
require(SI->getSrc().getType().isObject(),
"Can't store from an address source");
require(SI->getDest().getType().isAddress(),
"Must store to an address dest");
require(SI->getDest().getType().getObjectType() == SI->getSrc().getType(),
"Store operand type and dest type mismatch");
}
void checkAssignInst(AssignInst *AI) {
SILValue Src = AI->getSrc(), Dest = AI->getDest();
require(AI->getModule().getStage() == SILStage::Raw,
"assign instruction can only exist in raw SIL");
require(Src.getType().isObject(), "Can't assign from an address source");
require(Dest.getType().isAddress(), "Must store to an address dest");
require(Dest.getType().getObjectType() == Src.getType(),
"Store operand type and dest type mismatch");
}
void checkLoadWeakInst(LoadWeakInst *LWI) {
require(LWI->getType().isObject(), "Result of load must be an object");
require(LWI->getType().getSwiftType()->getAnyOptionalObjectType(),
"Result of weak load must be an optional");
auto PointerType = LWI->getOperand().getType();
auto PointerRVType = PointerType.getSwiftRValueType();
require(PointerType.isAddress() &&
PointerRVType->is<WeakStorageType>(),
"load_weak operand must be an weak address");
require(PointerRVType->getReferenceStorageReferent()->getCanonicalType() ==
LWI->getType().getSwiftType(),
"Load operand type and result type mismatch");
}
void checkStoreWeakInst(StoreWeakInst *SWI) {
require(SWI->getSrc().getType().isObject(),
"Can't store from an address source");
require(SWI->getSrc().getType().getSwiftType()->getAnyOptionalObjectType(),
"store_weak must be of an optional value");
auto PointerType = SWI->getDest().getType();
auto PointerRVType = PointerType.getSwiftRValueType();
require(PointerType.isAddress() &&
PointerRVType->is<WeakStorageType>(),