File: InstructionUtils.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (1368 lines) | stat: -rw-r--r-- 50,992 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
//===--- InstructionUtils.cpp - Utilities for SIL instructions ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-inst-utils"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/MemAccessUtils.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/Basic/STLExtras.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/Projection.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILVisitor.h"

#include "clang/AST/DeclObjC.h"

using namespace swift;

SILValue swift::lookThroughOwnershipInsts(SILValue v) {
  while (true) {
    switch (v->getKind()) {
    default:
      return v;
    case ValueKind::MoveValueInst:
    case ValueKind::CopyValueInst:
    case ValueKind::BeginBorrowInst:
      v = cast<SingleValueInstruction>(v)->getOperand(0);
    }
  }
}

bool swift::visitNonOwnershipUses(SILValue value,
                                  function_ref<bool(Operand *)> visitor) {
  // All ownership insts have a single operand, so a recursive walk is
  // sufficient and cannot revisit operands.
  for (Operand *use : value->getUses()) {
    auto *user = use->getUser();
    switch (user->getKind()) {
    default:
      if (!visitor(use))
        return false;

      break;
    case SILInstructionKind::MoveValueInst:
    case SILInstructionKind::CopyValueInst:
    case SILInstructionKind::BeginBorrowInst:
      if (!visitNonOwnershipUses(cast<SingleValueInstruction>(user), visitor))
        return false;

      break;
    }
  }
  return true;
}

SILValue swift::lookThroughCopyValueInsts(SILValue val) {
  while (auto *cvi =
             dyn_cast_or_null<CopyValueInst>(val->getDefiningInstruction())) {
    val = cvi->getOperand();
  }
  return val;
}

/// Strip off casts/indexing insts/address projections from V until there is
/// nothing left to strip.
///
/// FIXME: Why don't we strip projections after stripping indexes?
SILValue swift::getUnderlyingObject(SILValue v) {
  while (true) {
    SILValue v2 = stripCasts(v);
    v2 = stripAddressProjections(v2);
    v2 = stripIndexingInsts(v2);
    v2 = lookThroughOwnershipInsts(v2);
    if (auto *ecm = dyn_cast<EndCOWMutationInst>(v2)) {
      v2 = ecm->getOperand();
    } else if (auto *eir = dyn_cast<EndInitLetRefInst>(v2)) {
      v2 = eir->getOperand();
    } else if (auto *mvr = dyn_cast<MultipleValueInstructionResult>(v2)) {
      if (auto *bci = dyn_cast<BeginCOWMutationInst>(mvr->getParent()))
        v2 = bci->getOperand();
    }
    if (v2 == v)
      return v2;
    v = v2;
  }
}

/// Return the underlying SILValue after stripping off identity SILArguments if
/// we belong to a BB with one predecessor.
SILValue swift::stripSinglePredecessorArgs(SILValue V) {
  while (true) {
    auto *A = dyn_cast<SILArgument>(V);
    if (!A)
      return V;
    
    SILBasicBlock *BB = A->getParent();
    
    // First try and grab the single predecessor of our parent BB. If we don't
    // have one, bail.
    SILBasicBlock *Pred = BB->getSinglePredecessorBlock();
    if (!Pred)
      return V;
    
    // Then grab the terminator of Pred...
    TermInst *PredTI = Pred->getTerminator();
    
    // And attempt to find our matching argument.
    //
    // *NOTE* We can only strip things here if we know that there is no semantic
    // change in terms of upcasts/downcasts/enum extraction since this is used
    // by other routines here. This means that we can only look through
    // cond_br/br.
    //
    // For instance, routines that use stripUpcasts() do not want to strip off a
    // downcast that results from checked_cast_br.
    if (auto *BI = dyn_cast<BranchInst>(PredTI)) {
      V = BI->getArg(A->getIndex());
      continue;
    }
    
    if (auto *CBI = dyn_cast<CondBranchInst>(PredTI)) {
      if (SILValue Arg = CBI->getArgForDestBB(BB, A)) {
        V = Arg;
        continue;
      }
    }
    
    return V;
  }
}

SILValue swift::stripCastsWithoutMarkDependence(SILValue v) {
  while (true) {
    v = stripSinglePredecessorArgs(v);
    if (isa<MarkDependenceInst>(v))
      return v;

    if (auto *svi = dyn_cast<SingleValueInstruction>(v)) {
      if (isIdentityPreservingRefCast(svi) ||
          isa<UncheckedTrivialBitCastInst>(v) || isa<BeginAccessInst>(v) ||
          isa<EndInitLetRefInst>(v) || isa<EndCOWMutationInst>(v)) {
        v = svi->getOperand(0);
        continue;
      }
    }
    return v;
  }
}

SILValue swift::stripCasts(SILValue v) {
  while (true) {
    v = stripSinglePredecessorArgs(v);
    if (auto *svi = dyn_cast<SingleValueInstruction>(v)) {
      if (isIdentityPreservingRefCast(svi) ||
          isa<UncheckedTrivialBitCastInst>(v) || isa<MarkDependenceInst>(v) ||
          isa<BeginAccessInst>(v)) {
        v = cast<SingleValueInstruction>(v)->getOperand(0);
        continue;
      }
    }
    SILValue v2 = lookThroughOwnershipInsts(v);
    if (v2 != v) {
      v = v2;
      continue;
    }
    return v;
  }
}

SILValue swift::stripUpCasts(SILValue v) {
  assert(v->getType().isClassOrClassMetatype() &&
         "Expected class or class metatype!");
  
  v = stripSinglePredecessorArgs(v);
  
  while (true) {
    if (auto *ui = dyn_cast<UpcastInst>(v)) {
      v = ui->getOperand();
      continue;
    }

    SILValue v2 = stripSinglePredecessorArgs(v);
    v2 = lookThroughOwnershipInsts(v2);
    if (v2 == v) {
      return v2;
    }
    v = v2;
  }
}

SILValue swift::stripClassCasts(SILValue v) {
  while (true) {
    if (auto *ui = dyn_cast<UpcastInst>(v)) {
      v = ui->getOperand();
      continue;
    }
    
    if (auto *ucci = dyn_cast<UnconditionalCheckedCastInst>(v)) {
      v = ucci->getOperand();
      continue;
    }

    SILValue v2 = lookThroughOwnershipInsts(v);
    if (v2 != v) {
      v = v2;
      continue;
    }

    return v;
  }
}

SILValue swift::stripAddressProjections(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);
    if (!Projection::isAddressProjection(V))
      return V;
    V = cast<SingleValueInstruction>(V)->getOperand(0);
  }
}

SILValue swift::lookThroughAddressToAddressProjections(SILValue v) {
  while (true) {
    v = stripSinglePredecessorArgs(v);
    if (!Projection::isAddressToAddressProjection(v))
      return v;
    v = cast<SingleValueInstruction>(v)->getOperand(0);
  }
}

SILValue swift::stripValueProjections(SILValue V) {
  while (true) {
    V = stripSinglePredecessorArgs(V);
    if (!Projection::isObjectProjection(V))
      return V;
    V = cast<SingleValueInstruction>(V)->getOperand(0);
  }
}

SILValue swift::stripIndexingInsts(SILValue V) {
  while (true) {
    if (!isa<IndexingInst>(V))
      return V;
    V = cast<IndexingInst>(V)->getBase();
  }
}

SILValue swift::stripExpectIntrinsic(SILValue V) {
  auto *BI = dyn_cast<BuiltinInst>(V);
  if (!BI)
    return V;
  if (BI->getIntrinsicInfo().ID != llvm::Intrinsic::expect)
    return V;
  return BI->getArguments()[0];
}

SILValue swift::stripBorrow(SILValue V) {
  if (auto *BBI = dyn_cast<BeginBorrowInst>(V))
    return BBI->getOperand();
  return V;
}

// All instructions handled here must propagate their first operand into their
// single result.
//
// This is guaranteed to handle all function-type conversions: ThinToThick,
// ConvertFunction, and ConvertEscapeToNoEscapeInst.
SingleValueInstruction *swift::getSingleValueCopyOrCast(SILInstruction *I) {
  if (auto convert = ConversionOperation(I))
    return *convert;

  switch (I->getKind()) {
  default:
    return nullptr;
  case SILInstructionKind::CopyValueInst:
  case SILInstructionKind::CopyBlockInst:
  case SILInstructionKind::CopyBlockWithoutEscapingInst:
  case SILInstructionKind::BeginBorrowInst:
  case SILInstructionKind::BeginAccessInst:
  case SILInstructionKind::MarkDependenceInst:
  case SILInstructionKind::MoveValueInst:
    return cast<SingleValueInstruction>(I);
  }
}

bool swift::isBeginScopeMarker(SILInstruction *user) {
  switch (user->getKind()) {
  default:
    return false;
  case SILInstructionKind::BeginAccessInst:
  case SILInstructionKind::BeginBorrowInst:
    return true;
  }
}

bool swift::isEndOfScopeMarker(SILInstruction *user) {
  switch (user->getKind()) {
  default:
    return false;
  case SILInstructionKind::EndAccessInst:
  case SILInstructionKind::EndBorrowInst:
    return true;
  }
}

bool swift::isIncidentalUse(SILInstruction *user) {
  return isEndOfScopeMarker(user) || user->isDebugInstruction() ||
         isa<FixLifetimeInst>(user) || isa<EndLifetimeInst>(user);
}

bool swift::onlyAffectsRefCount(SILInstruction *user) {
  switch (user->getKind()) {
  default:
    return false;
  case SILInstructionKind::CopyValueInst:
  case SILInstructionKind::DestroyValueInst:
  case SILInstructionKind::AutoreleaseValueInst:
  case SILInstructionKind::ReleaseValueInst:
  case SILInstructionKind::RetainValueInst:
  case SILInstructionKind::StrongReleaseInst:
  case SILInstructionKind::StrongRetainInst:
  case SILInstructionKind::UnmanagedAutoreleaseValueInst:
#define UNCHECKED_REF_STORAGE(Name, ...)                                       \
  case SILInstructionKind::Name##RetainValueInst:                              \
  case SILInstructionKind::Name##ReleaseValueInst:                             \
  case SILInstructionKind::StrongCopy##Name##ValueInst:
#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \
  case SILInstructionKind::Name##RetainInst:                                   \
  case SILInstructionKind::Name##ReleaseInst:                                  \
  case SILInstructionKind::StrongRetain##Name##Inst:                           \
  case SILInstructionKind::StrongCopy##Name##ValueInst:
#include "swift/AST/ReferenceStorage.def"
    return true;
  }
}

bool swift::mayCheckRefCount(SILInstruction *User) {
  return isa<IsUniqueInst>(User) || isa<IsEscapingClosureInst>(User) ||
         isa<BeginCOWMutationInst>(User);
}

bool swift::isSanitizerInstrumentation(SILInstruction *Instruction) {
  auto *BI = dyn_cast<BuiltinInst>(Instruction);
  if (!BI)
    return false;

  Identifier Name = BI->getName();
  if (Name == BI->getModule().getASTContext().getIdentifier("tsanInoutAccess"))
    return true;

  return false;
}

// Instrumentation instructions should not affect the correctness of the
// program. That is, they should not affect the observable program state.
// The constant evaluator relies on this property to skip instructions.
bool swift::isInstrumentation(SILInstruction *Instruction) {
  if (isSanitizerInstrumentation(Instruction))
    return true;

  if (isa<IncrementProfilerCounterInst>(Instruction))
    return true;

  return false;
}

SILValue swift::isPartialApplyOfReabstractionThunk(PartialApplyInst *PAI) {
  // A partial_apply of a reabstraction thunk either has a single capture
  // (a function) or two captures (function and dynamic Self type).
  if (PAI->getNumArguments() != 1 &&
      PAI->getNumArguments() != 2)
    return SILValue();

  auto *Fun = PAI->getReferencedFunctionOrNull();
  if (!Fun)
    return SILValue();

  // Make sure we have a reabstraction thunk.
  if (Fun->isThunk() != IsReabstractionThunk)
    return SILValue();

  // The argument should be a closure.
  auto Arg = PAI->getArgument(0);
  if (!Arg->getType().is<SILFunctionType>() ||
      (!Arg->getType().isReferenceCounted(PAI->getFunction()->getModule()) &&
       Arg->getType().getAs<SILFunctionType>()->getRepresentation() !=
           SILFunctionType::Representation::Thick))
    return SILValue();

  // Look through copies.
  if (auto copy = dyn_cast<CopyValueInst>(Arg)) {
    Arg = copy->getOperand();
  }

  return Arg;
}

bool swift::onlyUsedByAssignByWrapper(PartialApplyInst *PAI) {
  bool usedByAssignByWrapper = false;
  for (Operand *Op : PAI->getUses()) {
    SILInstruction *User = Op->getUser();
    if (isa<AssignByWrapperInst>(User) && Op->getOperandNumber() >= 2) {
      usedByAssignByWrapper = true;
      continue;
    }
    if (isa<DestroyValueInst>(User))
      continue;
    return false;
  }
  return usedByAssignByWrapper;
}

bool swift::onlyUsedByAssignOrInit(PartialApplyInst *PAI) {
  bool usedByAssignOrInit = false;
  for (Operand *Op : PAI->getUses()) {
    SILInstruction *user = Op->getUser();
    if (isa<AssignOrInitInst>(user)) {
      usedByAssignOrInit = true;
      continue;
    }

    if (isa<DestroyValueInst>(user)) {
      continue;
    }

    return false;
  }

  return usedByAssignOrInit;
}

static RuntimeEffect metadataEffect(SILType ty) {
  ClassDecl *cl = ty.getClassOrBoundGenericClass();
  if (cl && !cl->hasKnownSwiftImplementation())
    return RuntimeEffect::MetaData | RuntimeEffect::ObjectiveC;
  return RuntimeEffect::MetaData;
}

RuntimeEffect swift::getRuntimeEffect(SILInstruction *inst, SILType &impactType) {
  auto ifNonTrivial = [&](SILType type, RuntimeEffect effect) -> RuntimeEffect {
    // Nonescaping closures are modeled with ownership to track borrows, but
    // copying and destroying them has no actual runtime effect since they
    // are trivial after lowering.
    if (auto sft = type.getAs<SILFunctionType>()) {
      if (sft->isTrivialNoEscape()) {
        return RuntimeEffect::NoEffect;
      }
    }
    return effect;
  };

  switch (inst->getKind()) {
  case SILInstructionKind::TailAddrInst:
  case SILInstructionKind::IndexRawPointerInst:
  case SILInstructionKind::FunctionRefInst:
  case SILInstructionKind::DynamicFunctionRefInst:
  case SILInstructionKind::PreviousDynamicFunctionRefInst:
  case SILInstructionKind::GlobalAddrInst:
  case SILInstructionKind::BaseAddrForOffsetInst:
  case SILInstructionKind::IntegerLiteralInst:
  case SILInstructionKind::FloatLiteralInst:
  case SILInstructionKind::StringLiteralInst:
  case SILInstructionKind::ClassMethodInst:
  case SILInstructionKind::ObjCMethodInst:
  case SILInstructionKind::ObjCSuperMethodInst:
  case SILInstructionKind::UpcastInst:
  case SILInstructionKind::AddressToPointerInst:
  case SILInstructionKind::PointerToAddressInst:
  case SILInstructionKind::UncheckedRefCastInst:
  case SILInstructionKind::UncheckedAddrCastInst:
  case SILInstructionKind::UncheckedTrivialBitCastInst:
  case SILInstructionKind::UncheckedBitwiseCastInst:
  case SILInstructionKind::UncheckedValueCastInst:
  case SILInstructionKind::RefToRawPointerInst:
  case SILInstructionKind::RawPointerToRefInst:
#define LOADABLE_REF_STORAGE(Name, ...)                                        \
  case SILInstructionKind::RefTo##Name##Inst:                                  \
  case SILInstructionKind::Name##ToRefInst:
#include "swift/AST/ReferenceStorage.def"
#undef LOADABLE_REF_STORAGE_HELPER
  case SILInstructionKind::ConvertFunctionInst:
  case SILInstructionKind::ConvertEscapeToNoEscapeInst:
  case SILInstructionKind::RefToBridgeObjectInst:
  case SILInstructionKind::BridgeObjectToRefInst:
  case SILInstructionKind::BridgeObjectToWordInst:
  case SILInstructionKind::ThinToThickFunctionInst:
  case SILInstructionKind::ThickToObjCMetatypeInst:
  case SILInstructionKind::MoveOnlyWrapperToCopyableAddrInst:
  case SILInstructionKind::MoveOnlyWrapperToCopyableBoxInst:
  case SILInstructionKind::CopyableToMoveOnlyWrapperAddrInst:
  case SILInstructionKind::ObjCMetatypeToObjectInst:
  case SILInstructionKind::ObjCExistentialMetatypeToObjectInst:
  case SILInstructionKind::ClassifyBridgeObjectInst:
  case SILInstructionKind::ValueToBridgeObjectInst:
  case SILInstructionKind::MarkDependenceInst:
  case SILInstructionKind::MoveValueInst:
  case SILInstructionKind::DropDeinitInst:
  case SILInstructionKind::MarkUnresolvedNonCopyableValueInst:
  case SILInstructionKind::MarkUnresolvedReferenceBindingInst:
  case SILInstructionKind::CopyableToMoveOnlyWrapperValueInst:
  case SILInstructionKind::MoveOnlyWrapperToCopyableValueInst:
  case SILInstructionKind::UncheckedOwnershipConversionInst:
  case SILInstructionKind::LoadInst:
  case SILInstructionKind::LoadBorrowInst:
  case SILInstructionKind::BeginBorrowInst:
  case SILInstructionKind::StoreBorrowInst:
  case SILInstructionKind::MarkUninitializedInst:
  case SILInstructionKind::ProjectExistentialBoxInst:
  case SILInstructionKind::ObjCProtocolInst:
  case SILInstructionKind::ObjectInst:
  case SILInstructionKind::VectorInst:
  case SILInstructionKind::TupleInst:
  case SILInstructionKind::TupleExtractInst:
  case SILInstructionKind::StructInst:
  case SILInstructionKind::StructExtractInst:
  case SILInstructionKind::RefElementAddrInst:
  case SILInstructionKind::EnumInst:
  case SILInstructionKind::UncheckedEnumDataInst:
  case SILInstructionKind::InitEnumDataAddrInst:
  case SILInstructionKind::UncheckedTakeEnumDataAddrInst:
  case SILInstructionKind::SelectEnumInst:
  case SILInstructionKind::SelectEnumAddrInst:
  case SILInstructionKind::ProjectBlockStorageInst:
  case SILInstructionKind::UnreachableInst:
  case SILInstructionKind::ReturnInst:
  case SILInstructionKind::ThrowInst:
  case SILInstructionKind::ThrowAddrInst:
  case SILInstructionKind::YieldInst:
  case SILInstructionKind::UnwindInst:
  case SILInstructionKind::BranchInst:
  case SILInstructionKind::CondBranchInst:
  case SILInstructionKind::SwitchValueInst:
  case SILInstructionKind::SwitchEnumInst:
  case SILInstructionKind::DeallocStackInst:
  case SILInstructionKind::DeallocStackRefInst:
  case SILInstructionKind::DeallocPackInst:
  // This instruction just destroys stack allocations where metadata pointers
  // have been stored.
  case SILInstructionKind::DeallocPackMetadataInst:
  case SILInstructionKind::AutoreleaseValueInst:
  case SILInstructionKind::BindMemoryInst:
  case SILInstructionKind::RebindMemoryInst:
  case SILInstructionKind::FixLifetimeInst:
  case SILInstructionKind::EndBorrowInst:
  case SILInstructionKind::AssignInst:
  case SILInstructionKind::AssignByWrapperInst:
  case SILInstructionKind::AssignOrInitInst:
  case SILInstructionKind::MarkFunctionEscapeInst:
  case SILInstructionKind::EndLifetimeInst:
  case SILInstructionKind::EndApplyInst:
  case SILInstructionKind::AbortApplyInst:
  case SILInstructionKind::CondFailInst:
  case SILInstructionKind::DestructureStructInst:
  case SILInstructionKind::DestructureTupleInst:
  case SILInstructionKind::DifferentiableFunctionInst:
  case SILInstructionKind::DifferentiableFunctionExtractInst:
  case SILInstructionKind::LinearFunctionInst:
  case SILInstructionKind::LinearFunctionExtractInst:
  case SILInstructionKind::DifferentiabilityWitnessFunctionInst:
  case SILInstructionKind::IncrementProfilerCounterInst:
  case SILInstructionKind::EndCOWMutationInst:
  case SILInstructionKind::HasSymbolInst:
  case SILInstructionKind::DynamicPackIndexInst:
  case SILInstructionKind::PackPackIndexInst:
  case SILInstructionKind::ScalarPackIndexInst:
  case SILInstructionKind::PackElementGetInst:
  case SILInstructionKind::PackElementSetInst:
  case SILInstructionKind::PackLengthInst:
  case SILInstructionKind::DebugStepInst:
  case SILInstructionKind::FunctionExtractIsolationInst:
    return RuntimeEffect::NoEffect;
      
  case SILInstructionKind::OpenExistentialMetatypeInst:
  case SILInstructionKind::OpenExistentialBoxInst:
  case SILInstructionKind::OpenExistentialValueInst:
  case SILInstructionKind::OpenExistentialBoxValueInst:
    return RuntimeEffect::Existential;

  case SILInstructionKind::DebugValueInst:
    // Ignore runtime calls of debug_value
    return RuntimeEffect::NoEffect;
  case SILInstructionKind::SpecifyTestInst:
    // Ignore runtime calls of test-only instructions
    return RuntimeEffect::NoEffect;

  case SILInstructionKind::GetAsyncContinuationInst:
  case SILInstructionKind::GetAsyncContinuationAddrInst:
  case SILInstructionKind::AwaitAsyncContinuationInst:
  case SILInstructionKind::HopToExecutorInst:
  case SILInstructionKind::ExtractExecutorInst:
    return RuntimeEffect::Concurrency;

  case SILInstructionKind::KeyPathInst:
    return RuntimeEffect::Allocating | RuntimeEffect::Releasing |
           RuntimeEffect::MetaData;

  case SILInstructionKind::TuplePackExtractInst:
  case SILInstructionKind::TuplePackElementAddrInst:
    return RuntimeEffect::MetaData;

  case SILInstructionKind::SwitchEnumAddrInst:
  case SILInstructionKind::InjectEnumAddrInst:
  case SILInstructionKind::TupleElementAddrInst:
  case SILInstructionKind::StructElementAddrInst:
  case SILInstructionKind::IndexAddrInst:
    // TODO: hasArchetype() ?
    if (!inst->getOperand(0)->getType().isFixedABI(*inst->getFunction())) {
      impactType = inst->getOperand(0)->getType();
      return RuntimeEffect::MetaData;
    }
    return RuntimeEffect::NoEffect;

  case SILInstructionKind::RefTailAddrInst:
    if (!cast<RefTailAddrInst>(inst)->getTailType().isLoadable(*inst->getFunction())) {
      impactType = cast<RefTailAddrInst>(inst)->getTailType();
      return RuntimeEffect::MetaData;
    }
    return RuntimeEffect::NoEffect;

  case SILInstructionKind::BeginAccessInst:
    if (cast<BeginAccessInst>(inst)->getEnforcement() ==
        SILAccessEnforcement::Dynamic)
      return RuntimeEffect::ExclusivityChecking;
    return RuntimeEffect::NoEffect;
  case SILInstructionKind::EndAccessInst:
    if (cast<EndAccessInst>(inst)->getBeginAccess()->getEnforcement() ==
        SILAccessEnforcement::Dynamic)
      return RuntimeEffect::ExclusivityChecking;
    return RuntimeEffect::NoEffect;
  case SILInstructionKind::BeginUnpairedAccessInst:
    if (cast<BeginUnpairedAccessInst>(inst)->getEnforcement() ==
        SILAccessEnforcement::Dynamic)
      return RuntimeEffect::ExclusivityChecking;
    return RuntimeEffect::NoEffect;
  case SILInstructionKind::EndUnpairedAccessInst:
    if (cast<EndUnpairedAccessInst>(inst)->getEnforcement() ==
        SILAccessEnforcement::Dynamic)
      return RuntimeEffect::ExclusivityChecking;
    return RuntimeEffect::NoEffect;

  case SILInstructionKind::InitExistentialAddrInst:
  case SILInstructionKind::InitExistentialValueInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::Allocating | RuntimeEffect::Releasing |
           RuntimeEffect::MetaData | RuntimeEffect::Existential;

  case SILInstructionKind::InitExistentialRefInst:
  case SILInstructionKind::InitExistentialMetatypeInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::MetaData | RuntimeEffect::Existential;
  case SILInstructionKind::ObjCToThickMetatypeInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::MetaData;

  case SILInstructionKind::OpenPackElementInst:
    // We do potentially have to build type metadata as part of this
    // instruction (if we have to materialize a concrete pack).
    // The interface doesn't let us be specific about what metadata,
    // though.
    impactType = SILType();
    return RuntimeEffect::MetaData;

  case SILInstructionKind::OpenExistentialAddrInst:
    if (cast<OpenExistentialAddrInst>(inst)->getAccessKind() ==
        OpenedExistentialAccess::Mutable)
      return RuntimeEffect::Allocating | RuntimeEffect::Existential;
    return RuntimeEffect::Existential;

  case SILInstructionKind::OpenExistentialRefInst: {
    SILType opType = cast<OpenExistentialRefInst>(inst)->getOperand()->getType();
    impactType = opType;
    if (opType.getASTType()->isObjCExistentialType()) {
      return RuntimeEffect::MetaData | RuntimeEffect::Existential;
    }
    return RuntimeEffect::MetaData | RuntimeEffect::Existential;
    // TODO: should be Existential
    //return RuntimeEffect::Existential;
  }

  case SILInstructionKind::UnconditionalCheckedCastInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::Casting | metadataEffect(impactType) |
           metadataEffect(cast<SingleValueInstruction>(inst)->getType());
  case SILInstructionKind::UnconditionalCheckedCastAddrInst:
  case SILInstructionKind::CheckedCastAddrBranchInst:
  case SILInstructionKind::UncheckedRefCastAddrInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::Casting | metadataEffect(impactType) |
           metadataEffect(inst->getOperand(1)->getType());
  case SILInstructionKind::CheckedCastBranchInst:
    impactType = inst->getOperand(0)->getType();
    return RuntimeEffect::Casting | metadataEffect(impactType) |
      metadataEffect(cast<CheckedCastBranchInst>(inst)->getTargetLoweredType());

  case SILInstructionKind::AllocPackInst:
    // Just conservatively assume this has metadata impact.
    return RuntimeEffect::MetaData;
  case SILInstructionKind::AllocPackMetadataInst:
    // Currently this instruction has no effect but in the fullness of time it
    // will have a metadata effect.
    return RuntimeEffect::MetaData;

  case SILInstructionKind::AllocStackInst:
  case SILInstructionKind::AllocVectorInst:
  case SILInstructionKind::ProjectBoxInst:
    if (!cast<SingleValueInstruction>(inst)->getType().
          isLoadable(*inst->getFunction())) {
      impactType = cast<SingleValueInstruction>(inst)->getType();
      return RuntimeEffect::MetaData;
    }
    return RuntimeEffect::NoEffect;

  case SILInstructionKind::AllocGlobalInst: {
    SILType glTy = cast<AllocGlobalInst>(inst)->getReferencedGlobal()->
                      getLoweredType();
    if (glTy.isLoadable(*inst->getFunction()))
      return RuntimeEffect::NoEffect;
    if (glTy.hasOpaqueArchetype()) {
      impactType = glTy;
      return RuntimeEffect::Allocating | RuntimeEffect::MetaData;
    }
    return RuntimeEffect::Allocating;
  }
  case SILInstructionKind::AllocExistentialBoxInst:
    impactType = cast<SingleValueInstruction>(inst)->getType();
    return RuntimeEffect::Allocating | RuntimeEffect::MetaData |
           RuntimeEffect::Releasing | RuntimeEffect::Existential;
  case SILInstructionKind::AllocBoxInst:
  case SILInstructionKind::AllocRefInst:
  case SILInstructionKind::AllocRefDynamicInst:
    impactType = cast<SingleValueInstruction>(inst)->getType();
    return RuntimeEffect::Allocating | RuntimeEffect::MetaData |
           // TODO: why Releasing?
           RuntimeEffect::Releasing;

  case SILInstructionKind::DeallocRefInst:
  case SILInstructionKind::DeallocPartialRefInst:
  case SILInstructionKind::DeallocBoxInst:
  case SILInstructionKind::DeallocExistentialBoxInst:
  case SILInstructionKind::DeinitExistentialAddrInst:
  case SILInstructionKind::DeinitExistentialValueInst:
    return RuntimeEffect::Deallocating;

  case SILInstructionKind::CopyAddrInst: {
    auto *ca = cast<CopyAddrInst>(inst);
    if (ca->getSrc()->getType().isTrivial(ca->getFunction()))
      return RuntimeEffect::NoEffect;
    impactType = ca->getSrc()->getType();
    if (!ca->isInitializationOfDest())
      return RuntimeEffect::MetaData | RuntimeEffect::Releasing;
    if (!ca->isTakeOfSrc())
      return RuntimeEffect::MetaData | RuntimeEffect::RefCounting;
    return RuntimeEffect::MetaData;
  }
  case SILInstructionKind::TupleAddrConstructorInst: {
    auto *ca = cast<TupleAddrConstructorInst>(inst);
    impactType = ca->getDest()->getType();
    if (!ca->isInitializationOfDest())
      return RuntimeEffect::MetaData | RuntimeEffect::Releasing;
    return RuntimeEffect::MetaData;
  }
  case SILInstructionKind::ExplicitCopyAddrInst: {
    auto *ca = cast<ExplicitCopyAddrInst>(inst);
    impactType = ca->getSrc()->getType();
    if (!ca->isInitializationOfDest())
      return RuntimeEffect::MetaData | RuntimeEffect::Releasing;
    if (!ca->isTakeOfSrc())
      return RuntimeEffect::MetaData | RuntimeEffect::RefCounting;
    return RuntimeEffect::MetaData;
  }
  // Equivalent to a copy_addr [init]
  case SILInstructionKind::MarkUnresolvedMoveAddrInst: {
    return RuntimeEffect::MetaData | RuntimeEffect::RefCounting;
  }

  case SILInstructionKind::StoreInst:
    switch (cast<StoreInst>(inst)->getOwnershipQualifier()) {
      case StoreOwnershipQualifier::Unqualified:
      case StoreOwnershipQualifier::Trivial:
      case StoreOwnershipQualifier::Init:
        return RuntimeEffect::NoEffect;
      case StoreOwnershipQualifier::Assign:
        return RuntimeEffect::Releasing;
    }

  case SILInstructionKind::DestroyAddrInst:
    impactType = inst->getOperand(0)->getType();
    if (impactType.isTrivial(*inst->getFunction()))
      return RuntimeEffect::NoEffect;
    if (!impactType.isLoadable(*inst->getFunction()))
      return RuntimeEffect::Releasing | RuntimeEffect::MetaData;
    return RuntimeEffect::Releasing;

  case SILInstructionKind::ValueMetatypeInst:
  case SILInstructionKind::MetatypeInst: {
    auto metaTy = cast<SingleValueInstruction>(inst)->getType().castTo<MetatypeType>();
    if (metaTy->getRepresentation() != MetatypeRepresentation::Thin) {
      Type instTy = metaTy->getInstanceType();
      if (instTy->isLegalSILType())
        impactType = SILType::getPrimitiveObjectType(CanType(instTy));
      if (auto selfType = instTy->getAs<DynamicSelfType>())
        instTy = selfType->getSelfType();
      auto *cl = instTy->getClassOrBoundGenericClass();
      bool isForeign = cl && (cl->getObjectModel() == ReferenceCounting::ObjC ||
                              cl->isForeign());
      if (isForeign || instTy->isAnyObject())
        return RuntimeEffect::MetaData | RuntimeEffect::ObjectiveC;
      return RuntimeEffect::MetaData;
    }
    return RuntimeEffect::NoEffect;
  }

  case SILInstructionKind::ExistentialMetatypeInst: {
    SILType opType = cast<ExistentialMetatypeInst>(inst)->getOperand()->getType();
    impactType = opType;
    switch (opType.getPreferredExistentialRepresentation()) {
    case ExistentialRepresentation::Metatype:
    case ExistentialRepresentation::Boxed:
    case ExistentialRepresentation::Opaque:
      return RuntimeEffect::MetaData;
    case ExistentialRepresentation::Class: {
      if (opType.isAnyObject()) {
        if (inst->getModule().getASTContext().LangOpts.EnableObjCInterop) {
          return RuntimeEffect::MetaData | RuntimeEffect::Existential |
                 RuntimeEffect::ObjectiveC;
        } else {
          return RuntimeEffect::MetaData | RuntimeEffect::Existential;
        }
      }
      auto *cl = opType.getClassOrBoundGenericClass();
      bool usesObjCModel =
          cl && cl->getObjectModel() == ReferenceCounting::ObjC;
      if (usesObjCModel)
        return RuntimeEffect::MetaData | RuntimeEffect::ObjectiveC |
               RuntimeEffect::Existential;
      return RuntimeEffect::MetaData | RuntimeEffect::Existential;
    }
    case ExistentialRepresentation::None:
      return RuntimeEffect::NoEffect;
    }
    llvm_unreachable("Bad existential representation");
  }
  case SILInstructionKind::StrongRetainInst:
  case SILInstructionKind::UnmanagedRetainValueInst:
  case SILInstructionKind::RetainValueAddrInst:
  case SILInstructionKind::RetainValueInst:
  case SILInstructionKind::BeginCOWMutationInst:
  case SILInstructionKind::CopyValueInst:
  case SILInstructionKind::ExplicitCopyValueInst:
  case SILInstructionKind::BeginDeallocRefInst:
  case SILInstructionKind::EndInitLetRefInst:
  case SILInstructionKind::IsUniqueInst:
  case SILInstructionKind::IsEscapingClosureInst:
  case SILInstructionKind::CopyBlockInst:
  case SILInstructionKind::CopyBlockWithoutEscapingInst:
    return ifNonTrivial(inst->getOperand(0)->getType(),
                        RuntimeEffect::RefCounting);

  case SILInstructionKind::InitBlockStorageHeaderInst:
    return RuntimeEffect::Releasing;

  case SILInstructionKind::StrongReleaseInst:
  case SILInstructionKind::UnmanagedReleaseValueInst:
  case SILInstructionKind::UnmanagedAutoreleaseValueInst:
  case SILInstructionKind::ReleaseValueInst:
  case SILInstructionKind::ReleaseValueAddrInst:
  case SILInstructionKind::DestroyValueInst:
    impactType = inst->getOperand(0)->getType();
    if (impactType.isBlockPointerCompatible())
      return RuntimeEffect::ObjectiveC | RuntimeEffect::Releasing;
    if (impactType.isMoveOnly() &&
        !isa<DropDeinitInst>(lookThroughOwnershipInsts(inst->getOperand(0)))) {
      // Not de-virtualized value type deinits can require metatype in case the
      // deinit needs to be called via the value witness table.
      return RuntimeEffect::MetaData | RuntimeEffect::Releasing;
    }
    return ifNonTrivial(inst->getOperand(0)->getType(),
                        RuntimeEffect::Releasing);

#define ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)            \
  case SILInstructionKind::StrongRetain##Name##Inst:                           \
  case SILInstructionKind::Name##RetainInst:                                   \
    return RuntimeEffect::RefCounting;                                        \
  case SILInstructionKind::Name##ReleaseInst:                                  \
    return RuntimeEffect::Releasing;
#include "swift/AST/ReferenceStorage.def"
#undef ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE

  case SILInstructionKind::UnownedCopyValueInst:
  case SILInstructionKind::WeakCopyValueInst:
    return RuntimeEffect::RefCounting;
#define REF_STORAGE(Name, ...)                                                 \
  case SILInstructionKind::StrongCopy##Name##ValueInst:                        \
    return RuntimeEffect::RefCounting;
#include "swift/AST/ReferenceStorage.def"
#undef UNCHECKED_REF_STORAGE
#undef ALWAYS_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE

#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...)             \
  case SILInstructionKind::Store##Name##Inst:                                  \
    return RuntimeEffect::Releasing;
#include "swift/AST/ReferenceStorage.def"
#undef NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE

#define NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...)       \
  case SILInstructionKind::Load##Name##Inst:                                   \
    return RuntimeEffect::RefCounting;
#include "swift/AST/ReferenceStorage.def"
#undef NEVER_OR_SOMETIMES_LOADABLE_CHECKED_REF_STORAGE

  case SILInstructionKind::GlobalValueInst:
    return RuntimeEffect::Locking | RuntimeEffect::MetaData;

  case SILInstructionKind::DynamicMethodBranchInst:
    return RuntimeEffect::ObjectiveC;

  case SILInstructionKind::PartialApplyInst:
  case SILInstructionKind::ApplyInst:
  case SILInstructionKind::TryApplyInst:
  case SILInstructionKind::BeginApplyInst: {
    RuntimeEffect rt = RuntimeEffect::NoEffect;
    auto as = ApplySite(inst);

    switch (as.getSubstCalleeType()->getRepresentation()) {
    case SILFunctionTypeRepresentation::ObjCMethod:
      if (auto *callee = as.getCalleeFunction()) {
        if (auto *clangDecl = callee->getClangDecl()) {
          if (auto clangMethodDecl = dyn_cast<clang::ObjCMethodDecl>(clangDecl)) {
            if (clangMethodDecl->isDirectMethod()) {
              break;
            }
          }
        }
      }
      LLVM_FALLTHROUGH;
    case SILFunctionTypeRepresentation::Block:
      rt |= RuntimeEffect::ObjectiveC | RuntimeEffect::MetaData;
      break;
    case SILFunctionTypeRepresentation::WitnessMethod:
      rt |= RuntimeEffect::MetaData | RuntimeEffect::Existential;
      break;
    case SILFunctionTypeRepresentation::CFunctionPointer:
    case SILFunctionTypeRepresentation::CXXMethod:
    case SILFunctionTypeRepresentation::Thin:
    case SILFunctionTypeRepresentation::Method:
    case SILFunctionTypeRepresentation::Closure:
    case SILFunctionTypeRepresentation::Thick:
    case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
    case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
    case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
    case SILFunctionTypeRepresentation::KeyPathAccessorHash:
      break;
    }

    if (isa<BeginApplyInst>(inst))
      rt |= RuntimeEffect::Allocating;      

    if (auto *pa = dyn_cast<PartialApplyInst>(inst)) {
      if (pa->isOnStack()) {
        for (SILValue arg : pa->getArguments()) {
          if (!arg->getType().isTrivial(*pa->getFunction()))
            rt |= ifNonTrivial(arg->getType(), RuntimeEffect::RefCounting);
        }
      } else {
        rt |= RuntimeEffect::Allocating | RuntimeEffect::Releasing;
      }
    }

    if (!as.getSubstitutionMap().empty())
      rt |= RuntimeEffect::MetaData;
    if (auto *pa = dyn_cast<PartialApplyInst>(inst)) {
      if (!pa->isOnStack())
        rt |= RuntimeEffect::MetaData;
    }
    return rt;
  }
  case SILInstructionKind::WitnessMethodInst: {
    return RuntimeEffect::MetaData;
  }
  case SILInstructionKind::SuperMethodInst: {
    auto method = cast<SuperMethodInst>(inst)->getMember().getOverriddenVTableEntry();
    auto *classDecl = cast<ClassDecl>(method.getDecl()->getDeclContext());
    if (classDecl->hasResilientMetadata())
      return RuntimeEffect::MetaData;
    return RuntimeEffect::NoEffect;
  }

  case SILInstructionKind::BuiltinInst:
    switch (cast<BuiltinInst>(inst)->getBuiltinInfo().ID) {
    case BuiltinValueKind::Once:
    case BuiltinValueKind::OnceWithContext:
      return RuntimeEffect::Locking;
    case BuiltinValueKind::IsUnique:
      return RuntimeEffect::RefCounting;
    case BuiltinValueKind::IsOptionalType:
      return RuntimeEffect::Casting;
    case BuiltinValueKind::AllocRaw:
      return RuntimeEffect::Allocating;
    case BuiltinValueKind::DeallocRaw:
      return RuntimeEffect::Deallocating;
    case BuiltinValueKind::Fence:
    case BuiltinValueKind::CmpXChg:
    case BuiltinValueKind::AtomicLoad:
    case BuiltinValueKind::AtomicStore:
    case BuiltinValueKind::AtomicRMW:
      return RuntimeEffect::Locking;
    case BuiltinValueKind::DestroyArray:
      return RuntimeEffect::Releasing;
    case BuiltinValueKind::CopyArray:
      return RuntimeEffect::RefCounting;
    case BuiltinValueKind::AssignCopyArrayNoAlias:
    case BuiltinValueKind::AssignCopyArrayFrontToBack:
    case BuiltinValueKind::AssignCopyArrayBackToFront:
    case BuiltinValueKind::AssignTakeArray:
      return RuntimeEffect::RefCounting | RuntimeEffect::Deallocating;
    case BuiltinValueKind::BuildOrdinaryTaskExecutorRef:
    case BuiltinValueKind::BuildOrdinarySerialExecutorRef:
    case BuiltinValueKind::BuildComplexEqualitySerialExecutorRef:
    case BuiltinValueKind::BuildDefaultActorExecutorRef:
    case BuiltinValueKind::BuildMainActorExecutorRef:
    case BuiltinValueKind::StartAsyncLet:
    case BuiltinValueKind::StartAsyncLetWithLocalBuffer:
      return RuntimeEffect::MetaData;
    default:
      break;
    }
    return RuntimeEffect::NoEffect;
  }
}

/// Given a block used as a noescape function argument, attempt to find all
/// Swift closures that invoking the block will call. The StoredClosures may not
/// actually be partial_apply instructions. They may be copied, block arguments,
/// or conversions. The caller must continue searching up the use-def chain.
static SILValue findClosureStoredIntoBlock(SILValue V) {

  auto FnType = V->getType().castTo<SILFunctionType>();
  assert(FnType->getRepresentation() == SILFunctionTypeRepresentation::Block);
  (void)FnType;

  // Given a no escape block argument to a function,
  // pattern match to find the noescape closure that invoking the block
  // will call:
  //     %noescape_closure = ...
  //     %wae_Thunk = function_ref @$withoutActuallyEscapingThunk
  //     %sentinel =
  //       partial_apply [callee_guaranteed] %wae_thunk(%noescape_closure)
  //     %noescaped_wrapped = mark_dependence %sentinel on %noescape_closure
  //     %storage = alloc_stack
  //     %storage_address = project_block_storage %storage
  //     store %noescaped_wrapped to [init] %storage_address
  //     %block = init_block_storage_header %storage invoke %thunk
  //     %arg = copy_block %block

  InitBlockStorageHeaderInst *IBSHI = dyn_cast<InitBlockStorageHeaderInst>(V);
  if (!IBSHI)
    return nullptr;

  SILValue BlockStorage = IBSHI->getBlockStorage();
  auto *PBSI = BlockStorage->getSingleUserOfType<ProjectBlockStorageInst>();
  assert(PBSI && "Couldn't find block storage projection");

  auto *SI = PBSI->getSingleUserOfType<StoreInst>();
  assert(SI && "Couldn't find single store of function into block storage");

  auto *CV = dyn_cast<CopyValueInst>(SI->getSrc());
  if (!CV)
    return nullptr;
  auto *WrappedNoEscape = dyn_cast<MarkDependenceInst>(CV->getOperand());
  if (!WrappedNoEscape)
    return nullptr;
  auto Sentinel = dyn_cast<PartialApplyInst>(WrappedNoEscape->getValue());
  if (!Sentinel)
    return nullptr;
  auto NoEscapeClosure = isPartialApplyOfReabstractionThunk(Sentinel);
  if (WrappedNoEscape->getBase() != NoEscapeClosure)
    return nullptr;

  // This is the value of the closure to be invoked. To find the partial_apply
  // itself, the caller must search the use-def chain.
  return NoEscapeClosure;
}

/// Find all closures that may be propagated into the given function-type value.
///
/// Searches the use-def chain from the given value upward until a partial_apply
/// is reached. Populates `results` with the set of partial_apply instructions.
///
/// `funcVal` may be either a function type or an Optional function type. This
/// might be called on a directly applied value or on a call argument, which may
/// in turn be applied within the callee.
void swift::findClosuresForFunctionValue(
    SILValue funcVal, TinyPtrVector<PartialApplyInst *> &results) {

  SILType funcTy = funcVal->getType();
  // Handle `Optional<@convention(block) @noescape (_)->(_)>`
  if (auto optionalObjTy = funcTy.getOptionalObjectType())
    funcTy = optionalObjTy;
  assert(funcTy.is<SILFunctionType>());

  SmallVector<SILValue, 4> worklist;
  // Avoid exponential path exploration and prevent duplicate results.
  llvm::SmallDenseSet<SILValue, 8> visited;
  auto worklistInsert = [&](SILValue V) {
    if (visited.insert(V).second)
      worklist.push_back(V);
  };
  worklistInsert(funcVal);

  while (!worklist.empty()) {
    SILValue V = worklist.pop_back_val();

    if (auto *I = V->getDefiningInstruction()) {
      // Look through copies, borrows, and conversions.
      //
      // Handle copy_block and copy_block_without_actually_escaping before
      // calling findClosureStoredIntoBlock.
      if (SingleValueInstruction *SVI = getSingleValueCopyOrCast(I)) {
        worklistInsert(SVI->getOperand(0));
        continue;
      }
      // Look through `differentiable_function` operands, which are all
      // function-typed.
      if (auto *DFI = dyn_cast<DifferentiableFunctionInst>(I)) {
        for (auto &fn : DFI->getAllOperands())
          worklistInsert(fn.get());
        continue;
      }
    }
    // Look through Optionals.
    if (V->getType().getOptionalObjectType()) {
      auto *EI = dyn_cast<EnumInst>(V);
      if (EI && EI->hasOperand()) {
        worklistInsert(EI->getOperand());
      }
      // Ignore the .None case.
      continue;
    }
    // Look through Phis.
    //
    // This should be done before calling findClosureStoredIntoBlock.
    if (auto *arg = dyn_cast<SILPhiArgument>(V)) {
      SmallVector<std::pair<SILBasicBlock *, SILValue>, 2> blockArgs;
      arg->getIncomingPhiValues(blockArgs);
      for (auto &blockAndArg : blockArgs)
        worklistInsert(blockAndArg.second);

      continue;
    }
    // Look through ObjC closures.
    auto fnType = V->getType().getAs<SILFunctionType>();
    if (fnType
        && fnType->getRepresentation() == SILFunctionTypeRepresentation::Block) {
      if (SILValue storedClosure = findClosureStoredIntoBlock(V))
        worklistInsert(storedClosure);

      continue;
    }
    if (auto *PAI = dyn_cast<PartialApplyInst>(V)) {
      SILValue thunkArg = isPartialApplyOfReabstractionThunk(PAI);
      if (thunkArg) {
        // Handle reabstraction thunks recursively. This may reabstract over
        // @convention(block).
        worklistInsert(thunkArg);
        continue;
      }
      results.push_back(PAI);
      continue;
    }
    // Ignore other unrecognized values that feed this applied argument.
  }
}

bool PolymorphicBuiltinSpecializedOverloadInfo::init(
    SILFunction *fn, BuiltinValueKind builtinKind,
    ArrayRef<SILType> oldOperandTypes, SILType oldResultType) {
  assert(!isInitialized && "Expected uninitialized info");
  SWIFT_DEFER { isInitialized = true; };
  if (!isPolymorphicBuiltin(builtinKind))
    return false;

  // Ok, at this point we know that we have a true polymorphic builtin. See if
  // we have an overload for its current operand type.
  StringRef name = getBuiltinName(builtinKind);
  StringRef prefix = "generic_";
  assert(name.starts_with(prefix) &&
         "Invalid polymorphic builtin name! Prefix should be Generic$OP?!");
  SmallString<32> staticOverloadName;
  staticOverloadName.append(name.drop_front(prefix.size()));

  // If our first argument is an address, we know we have an indirect @out
  // parameter by convention since all of these polymorphic builtins today never
  // take indirect parameters without an indirect out result parameter. We stash
  // this information and validate that if we have an out param, that our result
  // is equal to the empty tuple type.
  if (oldOperandTypes[0].isAddress()) {
    if (oldResultType != fn->getModule().Types.getEmptyTupleType())
      return false;

    hasOutParam = true;
    SILType firstType = oldOperandTypes.front();

    // We only handle polymorphic builtins with trivial types today.
    if (!firstType.is<BuiltinType>() || !firstType.isTrivial(*fn)) {
      return false;
    }

    resultType = firstType.getObjectType();
    oldOperandTypes = oldOperandTypes.drop_front();
  } else {
    resultType = oldResultType;
  }

  // Then go through all of our values and bail if any after substitution are
  // not concrete builtin types. Otherwise, stash each of them in the argTypes
  // array as objects. We will convert them as appropriate.
  for (SILType ty : oldOperandTypes) {
    // If after specialization, we do not have a trivial builtin type, bail.
    if (!ty.is<BuiltinType>() || !ty.isTrivial(*fn)) {
      return false;
    }

    // Otherwise, we have an object builtin type ready to go.
    argTypes.push_back(ty.getObjectType());
  }

  // Ok, we have all builtin types. Infer the underlying polymorphic builtin
  // name form our first argument.
  CanBuiltinType builtinType = argTypes.front().getAs<BuiltinType>();
  SmallString<32> builtinTypeNameStorage;
  StringRef typeName = builtinType->getTypeName(builtinTypeNameStorage, false);
  staticOverloadName.append("_");
  staticOverloadName.append(typeName);

  auto &ctx = fn->getASTContext();
  staticOverloadIdentifier = ctx.getIdentifier(staticOverloadName);

  // Ok, we have our overload identifier. Grab the builtin info from the
  // cache. If we did not actually found a valid builtin value kind for our
  // overload, then we do not have a static overload for the passed in types, so
  // return false.
  builtinInfo = &fn->getModule().getBuiltinInfo(staticOverloadIdentifier);
  return true;
}

bool PolymorphicBuiltinSpecializedOverloadInfo::init(BuiltinInst *bi) {
  assert(!isInitialized && "Can not init twice?!");
  SWIFT_DEFER { isInitialized = true; };

  // First quickly make sure we have a /real/ BuiltinValueKind, not an intrinsic
  // or None.
  auto kind = bi->getBuiltinKind();
  if (!kind)
    return false;

  SmallVector<SILType, 8> oldOperandTypes;
  copy(bi->getOperandTypes(), std::back_inserter(oldOperandTypes));
  assert(bi->getNumResults() == 1 &&
         "We expect a tuple here instead of real args");
  SILType oldResultType = bi->getResult(0)->getType();
  return init(bi->getFunction(), *kind, oldOperandTypes, oldResultType);
}

SILValue
swift::getStaticOverloadForSpecializedPolymorphicBuiltin(BuiltinInst *bi) {

  PolymorphicBuiltinSpecializedOverloadInfo info;
  if (!info.init(bi))
    return SILValue();

  SmallVector<SILValue, 8> rawArgsData;
  copy(bi->getOperandValues(), std::back_inserter(rawArgsData));

  SILValue result = bi->getResult(0);
  MutableArrayRef<SILValue> rawArgs = rawArgsData;

  if (info.hasOutParam) {
    result = rawArgs.front();
    rawArgs = rawArgs.drop_front();
  }

  assert(bi->getNumResults() == 1 &&
         "We assume that builtins have a single result today. If/when this "
         "changes, this code needs to be updated");

  SILBuilderWithScope builder(bi);

  // Ok, now we know that we can convert this to our specialized
  // builtin. Prepare the arguments for the specialized value, loading the
  // values if needed and storing the result into an out parameter if needed.
  //
  // NOTE: We only support polymorphic builtins with trivial types today, so we
  // use load/store trivial as a result.
  SmallVector<SILValue, 8> newArgs;
  for (SILValue arg : rawArgs) {
    if (arg->getType().isObject()) {
      newArgs.push_back(arg);
      continue;
    }

    SILValue load = builder.emitLoadValueOperation(
        bi->getLoc(), arg, LoadOwnershipQualifier::Trivial);
    newArgs.push_back(load);
  }

  BuiltinInst *newBI =
      builder.createBuiltin(bi->getLoc(), info.staticOverloadIdentifier,
                            info.resultType, {}, newArgs);

  // If we have an out parameter initialize it now.
  if (info.hasOutParam) {
    builder.emitStoreValueOperation(newBI->getLoc(), newBI->getResult(0),
                                    result, StoreOwnershipQualifier::Trivial);
  }

  return newBI;
}

//===----------------------------------------------------------------------===//
//                          Exploded Tuple Visitors
//===----------------------------------------------------------------------===//

bool swift::visitExplodedTupleType(SILType inputType,
                                   llvm::function_ref<bool(SILType)> callback) {
  auto tupType = inputType.getAs<TupleType>();
  if (!tupType || tupType.containsPackExpansionType()) {
    return callback(inputType);
  }

  for (auto elt : tupType->getElementTypes()) {
    auto eltSILTy = SILType::getPrimitiveType(elt->getCanonicalType(),
                                              inputType.getCategory());
    if (!visitExplodedTupleType(eltSILTy, callback))
      return false;
  }

  return true;
}

bool swift::visitExplodedTupleValue(
    SILValue inputValue,
    llvm::function_ref<SILValue(SILValue, std::optional<unsigned>)> callback) {
  SILType inputType = inputValue->getType();
  auto tupType = inputType.getAs<TupleType>();
  if (!tupType || tupType.containsPackExpansionType()) {
    return callback(inputValue, {});
  }

  for (auto eltIndex : range(tupType->getNumElements())) {
    auto elt = callback(inputValue, eltIndex);
    if (!visitExplodedTupleValue(elt, callback))
      return false;
  }

  return true;
}