-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathConstExpr.cpp
2366 lines (2067 loc) · 94.7 KB
/
ConstExpr.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
//===--- ConstExpr.cpp - Constant expression evaluator -------------------===//
//
// 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 "ConstExpr"
#include "swift/SILOptimizer/Utils/ConstExpr.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/Demangling/Demangle.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/InstructionUtils.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILConstants.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/TerminatorUtils.h"
#include "swift/SILOptimizer/Utils/Devirtualize.h"
#include "swift/Serialization/SerializedSILLoader.h"
#include "llvm/ADT/PointerEmbeddedInt.h"
#include "llvm/Support/TrailingObjects.h"
using namespace swift;
static std::optional<SymbolicValue>
evaluateAndCacheCall(SILFunction &fn, SubstitutionMap substitutionMap,
ArrayRef<SymbolicValue> arguments, SymbolicValue &result,
unsigned &numInstEvaluated, ConstExprEvaluator &evaluator);
// TODO: ConstantTracker in the performance inliner and the
// ConstantFolding.h/cpp files should be subsumed by this, as this is a more
// general framework.
enum class WellKnownFunction {
// Array.init()
ArrayInitEmpty,
// Array._allocateUninitializedArray
AllocateUninitializedArray,
// Array._endMutation
EndArrayMutation,
// _finalizeUninitializedArray
FinalizeUninitializedArray,
// Array.append(_:)
ArrayAppendElement,
// String.init()
StringInitEmpty,
// String.init(_builtinStringLiteral:utf8CodeUnitCount:isASCII:)
StringMakeUTF8,
// static String.append (_: String, _: inout String)
StringAppend,
// static String.== infix(_: String)
StringEquals,
// String.percentEscapedString.getter
StringEscapePercent,
// BinaryInteger.description.getter
BinaryIntegerDescription,
// _assertionFailure(_: StaticString, _: StaticString, file: StaticString,...)
AssertionFailure,
// A function taking one argument that prints the symbolic value of the
// argument during constant evaluation. This must only be used for debugging.
DebugPrint
};
static std::optional<WellKnownFunction> classifyFunction(SILFunction *fn) {
if (fn->hasSemanticsAttr(semantics::ARRAY_INIT_EMPTY))
return WellKnownFunction::ArrayInitEmpty;
if (fn->hasSemanticsAttr(semantics::ARRAY_UNINITIALIZED_INTRINSIC))
return WellKnownFunction::AllocateUninitializedArray;
if (fn->hasSemanticsAttr(semantics::ARRAY_END_MUTATION))
return WellKnownFunction::EndArrayMutation;
if (fn->hasSemanticsAttr(semantics::ARRAY_FINALIZE_INTRINSIC))
return WellKnownFunction::FinalizeUninitializedArray;
if (fn->hasSemanticsAttr(semantics::ARRAY_APPEND_ELEMENT))
return WellKnownFunction::ArrayAppendElement;
if (fn->hasSemanticsAttr(semantics::STRING_INIT_EMPTY))
return WellKnownFunction::StringInitEmpty;
// There are two string initializers in the standard library with the
// semantics "string.makeUTF8". They are identical from the perspective of
// the interpreter. One of those functions is probably redundant and not used.
if (fn->hasSemanticsAttr(semantics::STRING_MAKE_UTF8))
return WellKnownFunction::StringMakeUTF8;
if (fn->hasSemanticsAttr(semantics::STRING_APPEND))
return WellKnownFunction::StringAppend;
if (fn->hasSemanticsAttr(semantics::STRING_EQUALS))
return WellKnownFunction::StringEquals;
if (fn->hasSemanticsAttr(semantics::STRING_ESCAPE_PERCENT_GET))
return WellKnownFunction::StringEscapePercent;
if (fn->hasSemanticsAttr(semantics::BINARY_INTEGER_DESCRIPTION))
return WellKnownFunction::BinaryIntegerDescription;
if (fn->hasSemanticsAttrThatStartsWith("programtermination_point"))
return WellKnownFunction::AssertionFailure;
// A call to a function with the following semantics annotation will be
// considered as a DebugPrint operation. The evaluator will print the value
// of the single argument passed to this function call to the standard error.
// This functionality must be used only for debugging the evaluator.
if (fn->hasSemanticsAttrThatStartsWith("constant_evaluator_debug_print"))
return WellKnownFunction::DebugPrint;
return std::nullopt;
}
static bool isReadOnlyFunction(WellKnownFunction function) {
switch (function) {
case WellKnownFunction::ArrayInitEmpty:
case WellKnownFunction::AllocateUninitializedArray:
case WellKnownFunction::StringInitEmpty:
case WellKnownFunction::StringMakeUTF8:
case WellKnownFunction::StringEquals:
case WellKnownFunction::StringEscapePercent:
case WellKnownFunction::BinaryIntegerDescription:
return true;
case WellKnownFunction::EndArrayMutation:
case WellKnownFunction::FinalizeUninitializedArray:
case WellKnownFunction::ArrayAppendElement:
case WellKnownFunction::StringAppend:
case WellKnownFunction::AssertionFailure:
case WellKnownFunction::DebugPrint:
return false;
}
}
/// Helper function for creating UnknownReason without a payload.
static SymbolicValue getUnknown(ConstExprEvaluator &evaluator, SILNode *node,
UnknownReason::UnknownKind kind) {
return evaluator.getUnknown(node, UnknownReason::create(kind));
}
//===----------------------------------------------------------------------===//
// ConstExprFunctionState implementation.
//===----------------------------------------------------------------------===//
namespace swift {
/// This type represents the state of computed values within a function
/// as evaluation happens. A separate instance of this is made for each
/// callee in a call chain to represent the constant values given the set of
/// formal parameters that callee was invoked with.
class ConstExprFunctionState {
/// This is the evaluator that is computing this function state. We use it to
/// allocate space for values and to query the call stack.
ConstExprEvaluator &evaluator;
/// If we are analyzing the body of a constexpr function, this is the
/// function. This is null for the top-level expression.
SILFunction *fn;
/// If we have a function being analyzed, this is the substitutionMap for
/// the call to it.
/// substitutionMap specifies a mapping from all of the protocol and type
/// requirements in the generic signature down to concrete conformances and
/// concrete types.
SubstitutionMap substitutionMap;
/// This keeps track of the number of instructions we've evaluated. If this
/// goes beyond the execution cap, then we start returning unknown values.
unsigned &numInstEvaluated;
/// This is a state of previously analyzed values, maintained and filled in
/// by getConstantValue. This does not hold the memory referred to by SIL
/// addresses.
llvm::DenseMap<SILValue, SymbolicValue> calculatedValues;
/// If a SILValue is not bound to a SymbolicValue in the calculatedValues,
/// try to compute it recursively by visiting its defining instruction.
bool recursivelyComputeValueIfNotInState = false;
public:
ConstExprFunctionState(ConstExprEvaluator &evaluator, SILFunction *fn,
SubstitutionMap substitutionMap,
unsigned &numInstEvaluated,
bool enableTopLevelEvaluation)
: evaluator(evaluator), fn(fn), substitutionMap(substitutionMap),
numInstEvaluated(numInstEvaluated),
recursivelyComputeValueIfNotInState(enableTopLevelEvaluation) {
assert((!fn || !enableTopLevelEvaluation) &&
"top-level evaluation must be disabled when evaluating a function"
" body step by step");
}
/// Pretty print the state to stderr.
void dump() const {
llvm::errs() << "[ConstExprState: \n";
llvm::errs() << " Caller: " << (fn ? fn->getName() : "null") << "\n";
llvm::errs() << " evaluatedInstrCount: " << numInstEvaluated << "\n";
llvm::errs() << " SubstMap: \n";
substitutionMap.dump(llvm::errs(), SubstitutionMap::DumpStyle::Full, 6);
llvm::errs() << "\n calculatedValues: ";
for (auto kv : calculatedValues) {
llvm::errs() << " " << kv.first << " --> " << kv.second << "\n";
}
}
void setValue(SILValue value, SymbolicValue symVal) {
calculatedValues.insert({value, symVal});
}
/// Return the symbolic value for a SILValue if it is bound in the interpreter
/// state. If not, return None.
std::optional<SymbolicValue> lookupValue(SILValue value) {
auto it = calculatedValues.find(value);
if (it != calculatedValues.end())
return it->second;
return std::nullopt;
}
/// Invariant: Before the call, `calculatedValues` must not contain `addr`
/// as a key.
SymbolicValue createMemoryObject(SILValue addr, SymbolicValue initialValue) {
assert(!calculatedValues.count(addr));
Type valueType =
substituteGenericParamsAndSimplify(addr->getType().getASTType());
auto *memObject = SymbolicValueMemoryObject::create(
valueType, initialValue, evaluator.getAllocator());
auto result = SymbolicValue::getAddress(memObject);
setValue(addr, result);
return result;
}
/// Return the SymbolicValue for the specified SIL value. If the SIL value is
/// not in \c calculatedValues, try computing the SymbolicValue recursively
/// if \c recursivelyComputeValueIfNotInState flag is set.
SymbolicValue getConstantValue(SILValue value);
/// Evaluate the specified instruction in a flow sensitive way, for use by
/// the constexpr function evaluator. This does not handle control flow
/// statements.
std::optional<SymbolicValue> evaluateFlowSensitive(SILInstruction *inst);
/// Evaluate a branch or non-branch instruction and if the evaluation was
/// successful, return the next instruction from where the evaluation must
/// continue.
/// \param instI basic-block iterator pointing to the instruction to evaluate.
/// \param visitedBlocks basic blocks already visited during evaluation.
/// This is used to detect loops.
/// \returns a pair where the first and second elements are defined as
/// follows:
/// If the evaluation of the instruction is successful, the first element
/// is the iterator to the next instruction from the where the evaluation
/// must continue. Otherwise, it is None.
///
/// Second element is None, if the evaluation is successful.
/// Otherwise, is an unknown symbolic value that contains the error.
std::pair<std::optional<SILBasicBlock::iterator>,
std::optional<SymbolicValue>>
evaluateInstructionAndGetNext(
SILBasicBlock::iterator instI,
SmallPtrSetImpl<SILBasicBlock *> &visitedBlocks);
Type substituteGenericParamsAndSimplify(Type ty);
CanType substituteGenericParamsAndSimplify(CanType ty) {
return substituteGenericParamsAndSimplify(Type(ty))->getCanonicalType();
}
SymbolicValue computeConstantValue(SILValue value);
SymbolicValue computeConstantValueBuiltin(BuiltinInst *inst);
std::optional<SymbolicValue> computeCallResult(ApplyInst *apply);
std::optional<SymbolicValue> computeOpaqueCallResult(ApplyInst *apply,
SILFunction *callee);
std::optional<SymbolicValue>
computeWellKnownCallResult(ApplyInst *apply, WellKnownFunction callee);
/// Evaluate a closure creation instruction which is either a partial_apply
/// instruction or a thin_to_think_function instruction. On success, this
/// function will bind the \c closureInst parameter to its symbolic value.
/// On failure, it returns the unknown symbolic value that captures the error.
std::optional<SymbolicValue>
evaluateClosureCreation(SingleValueInstruction *closureInst);
SymbolicValue getSingleWriterAddressValue(SILValue addr);
SymbolicValue getConstAddrAndLoadResult(SILValue addr);
SymbolicValue loadAddrValue(SILValue addr, SymbolicValue addrVal);
std::optional<SymbolicValue> computeFSStore(SymbolicValue storedCst,
SILValue dest);
private:
std::optional<SymbolicValue> initializeAddressFromSingleWriter(SILValue addr);
};
} // namespace swift
/// Simplify the specified type based on knowledge of substitutions if we have
/// any.
Type ConstExprFunctionState::substituteGenericParamsAndSimplify(Type ty) {
return substitutionMap.empty() ? ty : ty.subst(substitutionMap);
}
/// Const-evaluate `value`, which must not have been computed.
SymbolicValue ConstExprFunctionState::computeConstantValue(SILValue value) {
assert(!calculatedValues.count(value));
// If this a trivial constant instruction that we can handle, then fold it
// immediately.
if (auto *ili = dyn_cast<IntegerLiteralInst>(value))
return SymbolicValue::getInteger(ili->getValue(), evaluator.getAllocator());
if (auto *sli = dyn_cast<StringLiteralInst>(value))
return SymbolicValue::getString(sli->getValue(), evaluator.getAllocator());
if (auto *fri = dyn_cast<FunctionRefInst>(value))
return SymbolicValue::getFunction(fri->getReferencedFunction());
// If we have a reference to a metatype, constant fold any substitutable
// types.
if (auto *mti = dyn_cast<MetatypeInst>(value)) {
auto metatype = mti->getType().castTo<MetatypeType>();
auto type = substituteGenericParamsAndSimplify(metatype->getInstanceType())
->getCanonicalType();
return SymbolicValue::getMetatype(type);
}
if (auto *tei = dyn_cast<TupleExtractInst>(value)) {
auto val = getConstantValue(tei->getOperand());
if (!val.isConstant())
return val;
return val.getAggregateMembers()[tei->getFieldIndex()];
}
// If this is a struct extract from a fragile type, then we can return the
// element being extracted.
if (auto *sei = dyn_cast<StructExtractInst>(value)) {
auto aggValue = sei->getOperand();
auto val = getConstantValue(aggValue);
if (!val.isConstant()) {
return val;
}
assert(val.getKind() == SymbolicValue::Aggregate);
return val.getAggregateMembers()[sei->getFieldIndex()];
}
// If this is an unchecked_enum_data from a fragile type, then we can return
// the enum case value.
if (auto *uedi = dyn_cast<UncheckedEnumDataInst>(value)) {
auto aggValue = uedi->getOperand();
auto val = getConstantValue(aggValue);
if (val.isConstant()) {
assert(val.getKind() == SymbolicValue::EnumWithPayload);
return val.getEnumPayloadValue();
}
// Not a const.
return val;
}
// If this is a destructure_result, then we can return the element being
// extracted.
if (isaResultOf<DestructureStructInst>(value) ||
isaResultOf<DestructureTupleInst>(value)) {
auto *result = cast<MultipleValueInstructionResult>(value);
SILValue aggValue = result->getParent()->getOperand(0);
auto val = getConstantValue(aggValue);
if (val.isConstant()) {
assert(val.getKind() == SymbolicValue::Aggregate);
return val.getAggregateMembers()[result->getIndex()];
}
// Not a const.
return val;
}
// TODO: If this is a single element struct, we can avoid creating an
// aggregate to reduce # allocations. This is extra silly in the case of zero
// element tuples.
if (isa<StructInst>(value) || isa<TupleInst>(value)) {
auto *inst = cast<SingleValueInstruction>(value);
SmallVector<SymbolicValue, 4> elts;
for (unsigned i = 0, e = inst->getNumOperands(); i != e; ++i) {
auto val = getConstantValue(inst->getOperand(i));
if (!val.isConstant() && !val.isUnknownDueToUnevaluatedInstructions())
return val;
// Unknown values due to unevaluated instructions can be assigned to
// struct properties as they are not indicative of a fatal error or
// trap.
elts.push_back(val);
}
CanType structType = value->getType().getASTType();
return SymbolicValue::getAggregate(
elts, substituteGenericParamsAndSimplify(structType),
evaluator.getAllocator());
}
// If this is a struct or tuple element addressor, compute a more derived
// address.
if (isa<StructElementAddrInst>(value) || isa<TupleElementAddrInst>(value)) {
auto inst = cast<SingleValueInstruction>(value);
auto baseAddr = getConstantValue(inst->getOperand(0));
if (!baseAddr.isConstant())
return baseAddr;
SmallVector<unsigned, 4> accessPath;
auto *memObject = baseAddr.getAddressValue(accessPath);
// Add our index onto the next of the list.
unsigned index;
if (auto sea = dyn_cast<StructElementAddrInst>(inst))
index = sea->getFieldIndex();
else
index = cast<TupleElementAddrInst>(inst)->getFieldIndex();
accessPath.push_back(index);
return SymbolicValue::getAddress(memObject, accessPath,
evaluator.getAllocator());
}
// If this is a load, then we either have computed the value of the memory
// already (when analyzing the body of a function in a flow-sensitive
// fashion), or this is the indirect result of a call. Either way, we ask for
// the value of the pointer. In the former case, this will be the latest
// value of the memory. In the latter case, the call must be the only
// store to the address so that the memory object can be computed by
// recursively processing the allocation and call instructions in a
// demand-driven fashion.
if (auto li = dyn_cast<LoadInst>(value))
return getConstAddrAndLoadResult(li->getOperand());
// Try to resolve a witness method against our known conformances.
if (auto *wmi = dyn_cast<WitnessMethodInst>(value)) {
auto conf = substitutionMap.lookupConformance(
wmi->getLookupType()->mapTypeOutOfContext()->getCanonicalType(),
wmi->getConformance().getRequirement());
if (conf.isInvalid())
return getUnknown(evaluator, value,
UnknownReason::UnknownWitnessMethodConformance);
auto &module = wmi->getModule();
SILFunction *fn =
module.lookUpFunctionInWitnessTable(conf, wmi->getMember(), wmi->isSpecialized(),
SILModule::LinkingMode::LinkAll).first;
// If we were able to resolve it, then we can proceed.
if (fn)
return SymbolicValue::getFunction(fn);
LLVM_DEBUG(llvm::dbgs()
<< "ConstExpr Unresolved witness: " << *value << "\n");
return getUnknown(evaluator, value, UnknownReason::NoWitnesTableEntry);
}
if (auto *builtin = dyn_cast<BuiltinInst>(value))
return computeConstantValueBuiltin(builtin);
if (auto *enumVal = dyn_cast<EnumInst>(value)) {
if (!enumVal->hasOperand())
return SymbolicValue::getEnum(enumVal->getElement());
auto payload = getConstantValue(enumVal->getOperand());
if (!payload.isConstant())
return payload;
return SymbolicValue::getEnumWithPayload(enumVal->getElement(), payload,
evaluator.getAllocator());
}
// This one returns the address of its enum payload.
if (auto *dai = dyn_cast<UncheckedTakeEnumDataAddrInst>(value)) {
auto enumVal = getConstAddrAndLoadResult(dai->getOperand());
if (!enumVal.isConstant())
return enumVal;
return createMemoryObject(value, enumVal.getEnumPayloadValue());
}
if (isa<SelectEnumInst>(value) || isa<SelectEnumAddrInst>(value)) {
auto selectInst = SelectEnumOperation(value->getDefiningInstruction());
SILValue enumOperand = selectInst.getEnumOperand();
SymbolicValue enumValue = isa<SelectEnumInst>(value)
? getConstantValue(enumOperand)
: getConstAddrAndLoadResult(enumOperand);
if (!enumValue.isConstant())
return enumValue;
assert(enumValue.getKind() == SymbolicValue::Enum ||
enumValue.getKind() == SymbolicValue::EnumWithPayload);
SILValue resultOperand = selectInst.getCaseResult(enumValue.getEnumValue());
return getConstantValue(resultOperand);
}
// This instruction is a marker that returns its first operand.
if (auto *bai = dyn_cast<BeginAccessInst>(value))
return getConstantValue(bai->getOperand());
// Look through copy_value, begin_borrow, and move_value since the
// interpreter doesn't model these memory management instructions.
if (isa<CopyValueInst>(value) || isa<BeginBorrowInst>(value) ||
isa<MoveValueInst>(value))
return getConstantValue(cast<SingleValueInstruction>(value)->getOperand(0));
// Builtin.RawPointer and addresses have the same representation.
if (auto *p2ai = dyn_cast<PointerToAddressInst>(value))
return getConstantValue(p2ai->getOperand());
// Indexing a pointer moves the deepest index of the access path it represents
// within a memory object. For example, if a pointer p represents the access
// path [1, 2] within a memory object, p + 1 represents [1, 3]
if (auto *ia = dyn_cast<IndexAddrInst>(value)) {
auto index = getConstantValue(ia->getOperand(1));
if (!index.isConstant())
return index;
auto basePtr = getConstantValue(ia->getOperand(0));
if (basePtr.getKind() != SymbolicValue::Address)
return basePtr;
SmallVector<unsigned, 4> accessPath;
auto *memObject = basePtr.getAddressValue(accessPath);
assert(!accessPath.empty() && "Can't index a non-indexed address");
accessPath.back() += index.getIntegerValue().getLimitedValue();
return SymbolicValue::getAddress(memObject, accessPath,
evaluator.getAllocator());
}
// `convert_function` instructions that only change substitutions can be
// looked through to the original function.
//
// TODO: Certain covariant or otherwise ABI-compatible conversions should
// be handled as well.
if (auto cf = dyn_cast<ConvertFunctionInst>(value)) {
if (cf->onlyConvertsSubstitutions() || cf->onlyConvertsSendable()) {
return getConstantValue(cf->getOperand());
}
}
if (auto *convertEscapeInst = dyn_cast<ConvertEscapeToNoEscapeInst>(value))
return getConstantValue(convertEscapeInst->getOperand());
if (auto *mdi = dyn_cast<MarkDependenceInst>(value))
return getConstantValue(mdi->getValue());
LLVM_DEBUG(llvm::dbgs() << "ConstExpr Unknown simple: " << *value << "\n");
// Otherwise, we don't know how to handle this.
auto unknownReason = isa<SingleValueInstruction>(value)
? UnknownReason::UnsupportedInstruction
: UnknownReason::Default;
return getUnknown(evaluator, value, unknownReason);
}
SymbolicValue
ConstExprFunctionState::computeConstantValueBuiltin(BuiltinInst *inst) {
const BuiltinInfo &builtin = inst->getBuiltinInfo();
// Constant builtins.
if (inst->getNumOperands() == 0) {
switch (builtin.ID) {
default:
break;
case BuiltinValueKind::AssertConf:
return SymbolicValue::getInteger(evaluator.getAssertConfig(), 32);
}
}
// Handle various cases in groups.
auto invalidOperandValue = [&]() -> SymbolicValue {
return getUnknown(evaluator, SILValue(inst),
UnknownReason::InvalidOperandValue);
};
// Unary operations.
if (inst->getNumOperands() == 1) {
auto operand = getConstantValue(inst->getOperand(0));
// TODO: Could add a "value used here" sort of diagnostic.
if (!operand.isConstant())
return operand;
// Implement support for s_to_s_checked_trunc_Int2048_Int64 and other
// checking integer truncates. These produce a tuple of the result value
// and an overflow bit.
//
// TODO: We can/should diagnose statically detectable integer overflow
// errors and subsume the ConstantFolding.cpp mandatory SIL pass.
auto IntCheckedTruncFn = [&](bool srcSigned,
bool dstSigned) -> SymbolicValue {
if (operand.getKind() != SymbolicValue::Integer)
return invalidOperandValue();
APInt operandVal = operand.getIntegerValue();
uint32_t srcBitWidth = operandVal.getBitWidth();
auto dstBitWidth =
builtin.Types[1]->castTo<BuiltinIntegerType>()->getGreatestWidth();
// Note that the if the source type is a Builtin.IntLiteral, operandVal
// could have fewer bits than the destination bit width and may only
// require a sign extension.
APInt result = operandVal.sextOrTrunc(dstBitWidth);
// Determine if there is a overflow.
if (operandVal.getBitWidth() > dstBitWidth) {
// Re-extend the value back to its source and check for loss of value.
APInt reextended =
dstSigned ? result.sext(srcBitWidth) : result.zext(srcBitWidth);
bool overflowed = (operandVal != reextended);
if (!srcSigned && dstSigned)
overflowed |= result.isSignBitSet();
if (overflowed)
return getUnknown(evaluator, SILValue(inst), UnknownReason::Overflow);
}
auto &allocator = evaluator.getAllocator();
// Build the Symbolic value result for our truncated value.
return SymbolicValue::getAggregate(
{SymbolicValue::getInteger(result, allocator),
SymbolicValue::getInteger(APInt(1, false), allocator)},
inst->getType().getASTType(), allocator);
};
switch (builtin.ID) {
default:
break;
case BuiltinValueKind::SToSCheckedTrunc:
return IntCheckedTruncFn(true, true);
case BuiltinValueKind::UToSCheckedTrunc:
return IntCheckedTruncFn(false, true);
case BuiltinValueKind::SToUCheckedTrunc:
return IntCheckedTruncFn(true, false);
case BuiltinValueKind::UToUCheckedTrunc:
return IntCheckedTruncFn(false, false);
case BuiltinValueKind::Trunc:
case BuiltinValueKind::TruncOrBitCast:
case BuiltinValueKind::ZExt:
case BuiltinValueKind::ZExtOrBitCast:
case BuiltinValueKind::SExt:
case BuiltinValueKind::SExtOrBitCast: {
if (operand.getKind() != SymbolicValue::Integer)
return invalidOperandValue();
unsigned destBitWidth =
inst->getType().castTo<BuiltinIntegerType>()->getGreatestWidth();
APInt result = operand.getIntegerValue();
if (result.getBitWidth() != destBitWidth) {
switch (builtin.ID) {
default:
assert(0 && "Unknown case");
case BuiltinValueKind::Trunc:
case BuiltinValueKind::TruncOrBitCast:
result = result.trunc(destBitWidth);
break;
case BuiltinValueKind::ZExt:
case BuiltinValueKind::ZExtOrBitCast:
result = result.zext(destBitWidth);
break;
case BuiltinValueKind::SExt:
case BuiltinValueKind::SExtOrBitCast:
result = result.sext(destBitWidth);
break;
}
}
return SymbolicValue::getInteger(result, evaluator.getAllocator());
}
// The two following builtins are supported only for string constants. This
// is because this builtin is used by StaticString which is used in
// preconditions and assertion failures. Supporting this enables the
// evaluator to handle assertion/precondition failures.
case BuiltinValueKind::PtrToInt:
case BuiltinValueKind::IntToPtr: {
if (operand.getKind() != SymbolicValue::String) {
return getUnknown(evaluator, SILValue(inst),
UnknownReason::UnsupportedInstruction);
}
return operand;
}
}
}
// Binary operations.
if (inst->getNumOperands() == 2) {
auto operand0 = getConstantValue(inst->getOperand(0));
auto operand1 = getConstantValue(inst->getOperand(1));
if (!operand0.isConstant())
return operand0;
if (!operand1.isConstant())
return operand1;
auto constFoldIntCompare =
[&](const std::function<bool(const APInt &, const APInt &)> &fn)
-> SymbolicValue {
if (operand0.getKind() != SymbolicValue::Integer ||
operand1.getKind() != SymbolicValue::Integer)
return invalidOperandValue();
auto result = fn(operand0.getIntegerValue(), operand1.getIntegerValue());
return SymbolicValue::getInteger(APInt(1, result),
evaluator.getAllocator());
};
#define REQUIRE_KIND(KIND) \
if (operand0.getKind() != SymbolicValue::KIND || \
operand1.getKind() != SymbolicValue::KIND) \
return invalidOperandValue();
switch (builtin.ID) {
default:
break;
#define INT_BINOP(OPCODE, EXPR) \
case BuiltinValueKind::OPCODE: { \
REQUIRE_KIND(Integer) \
auto l = operand0.getIntegerValue(), r = operand1.getIntegerValue(); \
return SymbolicValue::getInteger((EXPR), evaluator.getAllocator()); \
}
INT_BINOP(Add, l + r)
INT_BINOP(And, l & r)
INT_BINOP(AShr, l.ashr(r))
INT_BINOP(LShr, l.lshr(r))
INT_BINOP(Or, l | r)
INT_BINOP(Mul, l * r)
INT_BINOP(SDiv, l.sdiv(r))
INT_BINOP(Shl, l << r)
INT_BINOP(SRem, l.srem(r))
INT_BINOP(Sub, l - r)
INT_BINOP(UDiv, l.udiv(r))
INT_BINOP(URem, l.urem(r))
INT_BINOP(Xor, l ^ r)
#undef INT_BINOP
#define INT_COMPARE(OPCODE, EXPR) \
case BuiltinValueKind::OPCODE: \
REQUIRE_KIND(Integer) \
return constFoldIntCompare( \
[&](const APInt &l, const APInt &r) -> bool { return (EXPR); })
INT_COMPARE(ICMP_EQ, l == r);
INT_COMPARE(ICMP_NE, l != r);
INT_COMPARE(ICMP_SLT, l.slt(r));
INT_COMPARE(ICMP_SGT, l.sgt(r));
INT_COMPARE(ICMP_SLE, l.sle(r));
INT_COMPARE(ICMP_SGE, l.sge(r));
INT_COMPARE(ICMP_ULT, l.ult(r));
INT_COMPARE(ICMP_UGT, l.ugt(r));
INT_COMPARE(ICMP_ULE, l.ule(r));
INT_COMPARE(ICMP_UGE, l.uge(r));
#undef INT_COMPARE
#undef REQUIRE_KIND
case BuiltinValueKind::Expect:
return operand0;
}
}
// Three operand builtins.
if (inst->getNumOperands() == 3) {
auto operand0 = getConstantValue(inst->getOperand(0));
auto operand1 = getConstantValue(inst->getOperand(1));
auto operand2 = getConstantValue(inst->getOperand(2));
if (!operand0.isConstant())
return operand0;
if (!operand1.isConstant())
return operand1;
if (!operand2.isConstant())
return operand2;
// Overflowing integer operations like sadd_with_overflow take three
// operands: the last one is a "should report overflow" bit.
auto constFoldIntOverflow =
[&](const std::function<APInt(const APInt &, const APInt &, bool &)>
&fn) -> SymbolicValue {
if (operand0.getKind() != SymbolicValue::Integer ||
operand1.getKind() != SymbolicValue::Integer ||
operand2.getKind() != SymbolicValue::Integer)
return invalidOperandValue();
auto l = operand0.getIntegerValue(), r = operand1.getIntegerValue();
bool overflowed = false;
auto result = fn(l, r, overflowed);
// Return a statically diagnosed overflow if the operation is supposed to
// trap on overflow.
if (overflowed && !operand2.getIntegerValue().isZero())
return getUnknown(evaluator, SILValue(inst), UnknownReason::Overflow);
auto &allocator = evaluator.getAllocator();
// Build the Symbolic value result for our normal and overflow bit.
return SymbolicValue::getAggregate(
{SymbolicValue::getInteger(result, allocator),
SymbolicValue::getInteger(APInt(1, overflowed), allocator)},
inst->getType().getASTType(), allocator);
};
switch (builtin.ID) {
default:
break;
#define INT_OVERFLOW(OPCODE, METHOD) \
case BuiltinValueKind::OPCODE: \
return constFoldIntOverflow( \
[&](const APInt &l, const APInt &r, bool &overflowed) -> APInt { \
return l.METHOD(r, overflowed); \
})
INT_OVERFLOW(SAddOver, sadd_ov);
INT_OVERFLOW(UAddOver, uadd_ov);
INT_OVERFLOW(SSubOver, ssub_ov);
INT_OVERFLOW(USubOver, usub_ov);
INT_OVERFLOW(SMulOver, smul_ov);
INT_OVERFLOW(UMulOver, umul_ov);
#undef INT_OVERFLOW
}
}
LLVM_DEBUG(llvm::dbgs() << "ConstExpr Unknown Builtin: " << *inst << "\n");
// Otherwise, we don't know how to handle this builtin.
return getUnknown(evaluator, SILValue(inst),
UnknownReason::UnsupportedInstruction);
}
// Handle calls to opaque callees, either by handling them and returning None or
// by returning with a Unknown indicating a failure.
std::optional<SymbolicValue>
ConstExprFunctionState::computeOpaqueCallResult(ApplyInst *apply,
SILFunction *callee) {
LLVM_DEBUG(llvm::dbgs() << "ConstExpr Opaque Callee: " << *callee << "\n");
return evaluator.getUnknown(
apply,
UnknownReason::createCalleeImplementationUnknown(callee));
}
/// Given a symbolic value representing an instance of StaticString, look into
/// the aggregate and extract the static string value stored inside it.
static std::optional<StringRef>
extractStaticStringValue(SymbolicValue staticString) {
if (staticString.getKind() != SymbolicValue::Aggregate)
return std::nullopt;
ArrayRef<SymbolicValue> staticStringProps =
staticString.getAggregateMembers();
if (staticStringProps.empty() ||
staticStringProps[0].getKind() != SymbolicValue::String)
return std::nullopt;
return staticStringProps[0].getStringValue();
}
static std::optional<StringRef>
extractStringOrStaticStringValue(SymbolicValue stringValue) {
if (stringValue.getKind() == SymbolicValue::String)
return stringValue.getStringValue();
return extractStaticStringValue(stringValue);
}
/// If the specified type is a Swift.Array of some element type, then return the
/// element type. Otherwise, return a null Type.
static Type getArrayElementType(Type ty) {
if (auto bgst = ty->getAs<BoundGenericStructType>())
if (bgst->isArray())
return bgst->getGenericArgs()[0];
return Type();
}
/// Check if the given type \p ty is a stdlib integer type and if so return
/// whether the type is signed. Returns \c None if \p ty is not a stdlib integer
/// type, \c true if it is a signed integer type and \c false if it is an
/// unsigned integer type.
static std::optional<bool> getSignIfStdlibIntegerType(Type ty) {
if (ty->isInt() || ty->isInt8() || ty->isInt16() || ty->isInt32() ||
ty->isInt64()) {
return true;
}
if (ty->isUInt() || ty->isUInt8() || ty->isUInt16() || ty->isUInt32() ||
ty->isUInt64()) {
return false;
}
return std::nullopt;
}
/// Given a call to a well known function, collect its arguments as constants,
/// fold it, and return None. If any of the arguments are not constants, marks
/// the call's results as Unknown, and return an Unknown with information about
/// the error.
std::optional<SymbolicValue>
ConstExprFunctionState::computeWellKnownCallResult(ApplyInst *apply,
WellKnownFunction callee) {
auto conventions = apply->getSubstCalleeConv();
switch (callee) {
case WellKnownFunction::AssertionFailure: {
SmallString<4> message;
for (unsigned i = 0, e = apply->getNumArguments(); i < e; ++i) {
SILValue argument = apply->getArgument(i);
SymbolicValue argValue = getConstantValue(argument);
std::optional<StringRef> stringOpt =
extractStringOrStaticStringValue(argValue);
// The first argument is a prefix that specifies the kind of failure
// this is.
if (i == 0) {
if (stringOpt) {
message += stringOpt.value();
} else {
// Use a generic prefix here, as the actual prefix is not a constant.
message += "assertion failed";
}
continue;
}
if (stringOpt) {
message += ": ";
message += stringOpt.value();
}
}
return evaluator.getUnknown(
apply,
UnknownReason::createTrap(message, evaluator.getAllocator()));
}
case WellKnownFunction::ArrayInitEmpty: { // Array.init()
assert(conventions.getNumDirectSILResults() == 1 &&
conventions.getNumIndirectSILResults() == 0 &&
"unexpected Array.init() signature");
auto typeValue = getConstantValue(apply->getOperand(1));
if (typeValue.getKind() != SymbolicValue::Metatype) {
return typeValue.isConstant()
? getUnknown(evaluator, apply,
UnknownReason::InvalidOperandValue)
: typeValue;
}
Type arrayType = typeValue.getMetatypeValue();
// Create an empty SymbolicArrayStorage and then create a SymbolicArray
// using it.
SymbolicValue arrayStorage = SymbolicValue::getSymbolicArrayStorage(
{}, getArrayElementType(arrayType)->getCanonicalType(),
evaluator.getAllocator());
auto arrayVal = SymbolicValue::getArray(arrayType, arrayStorage,
evaluator.getAllocator());
setValue(apply, arrayVal);
return std::nullopt;
}
case WellKnownFunction::AllocateUninitializedArray: {
// This function has this signature:
// func _allocateUninitializedArray<Element>(_ builtinCount: Builtin.Word)
// -> (Array<Element>, Builtin.RawPointer)
assert(conventions.getNumParameters() == 1 &&
conventions.getNumDirectSILResults() == 2 &&
conventions.getNumIndirectSILResults() == 0 &&
"unexpected _allocateUninitializedArray signature");
// Figure out the allocation size.
auto numElementsSV = getConstantValue(apply->getOperand(1));
if (!numElementsSV.isConstant())
return numElementsSV;
unsigned numElements = numElementsSV.getIntegerValue().getLimitedValue();
// Allocating uninitialized arrays is supported only in flow-sensitive mode.
// TODO: the top-level mode in the interpreter should be phased out.
if (recursivelyComputeValueIfNotInState)
return getUnknown(evaluator, apply, UnknownReason::Default);
SmallVector<SymbolicValue, 8> elementConstants;
// Set array elements to uninitialized state. Subsequent stores through
// their addresses will initialize the elements.
elementConstants.assign(numElements, SymbolicValue::getUninitMemory());
Type resultType =
substituteGenericParamsAndSimplify(apply->getType().getASTType());
assert(resultType->is<TupleType>());
Type arrayType = resultType->castTo<TupleType>()->getElementType(0);
Type arrayEltType = getArrayElementType(arrayType);
assert(arrayEltType && "Couldn't understand Swift.Array type?");
// Create a SymbolicArrayStorage with \c elements and then create a
// SymbolicArray using it.
SymbolicValueAllocator &allocator = evaluator.getAllocator();
SymbolicValue arrayStorage = SymbolicValue::getSymbolicArrayStorage(
elementConstants, arrayEltType->getCanonicalType(), allocator);
SymbolicValue array =
SymbolicValue::getArray(arrayType, arrayStorage, allocator);
// Construct return value for this call, which is a pair consisting of the
// address of the first element of the array and the array.
SymbolicValue storageAddress = array.getAddressOfArrayElement(allocator, 0);
setValue(apply, SymbolicValue::getAggregate({array, storageAddress},
resultType, allocator));
return std::nullopt;
}
case WellKnownFunction::EndArrayMutation: {
// This function has the following signature in SIL:
// (@inout Array<Element>) -> ()
assert(conventions.getNumParameters() == 1 &&
conventions.getNumDirectSILResults() == 0 &&
conventions.getNumIndirectSILResults() == 0 &&
"unexpected Array._endMutation() signature");
// _endMutation is a no-op.
return std::nullopt;
}
case WellKnownFunction::FinalizeUninitializedArray: {
// This function has the following signature in SIL:
// (Array<Element>) -> Array<Element>
assert(conventions.getNumParameters() == 1 &&
conventions.getNumDirectSILResults() == 1 &&
conventions.getNumIndirectSILResults() == 0 &&
"unexpected _finalizeUninitializedArray() signature");
auto result = getConstantValue(apply->getOperand(1));