Skip to content

[Constant Evaluator] Add support for evaluating checked_cast_br instruction and store_borrow. #28899

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions include/swift/AST/DiagnosticsSIL.def
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,11 @@ NOTE(constexpr_untracked_sil_value_use_found, none,
NOTE(constexpr_untracked_sil_value_used_here, none,
"untracked variable used %select{here|by this call}0", (bool))

NOTE(constexpr_unevaluable_cast_found, none,
"encountered an unevaluable cast", ())
NOTE(constexpr_unevaluable_cast_used_here, none,
"unevaluable cast encountered %select{here|by this call}0", (bool))

NOTE(constexpr_unresolvable_witness_call, none,
"encountered unresolvable witness method call: '%0'", (StringRef))
NOTE(constexpr_no_witness_table_entry, none, "cannot find witness table entry "
Expand Down
4 changes: 4 additions & 0 deletions include/swift/SIL/SILConstants.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ class UnknownReason {
/// the interpreter.
UntrackedSILValue,

/// Encountered a checked cast operation whose result cannot be evaluated
/// to a constant.
UnknownCastResult,

/// Attempted to find a concrete protocol conformance for a witness method
/// and failed.
UnknownWitnessMethodConformance,
Expand Down
7 changes: 7 additions & 0 deletions lib/SIL/SILConstants.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1000,6 +1000,13 @@ void SymbolicValue::emitUnknownDiagnosticNotes(SILLocation fallbackLoc) {
diagnose(ctx, triggerLoc, diag::constexpr_untracked_sil_value_used_here,
triggerLocSkipsInternalLocs);
return;
case UnknownReason::UnknownCastResult: {
diagnose(ctx, diagLoc, diag::constexpr_unevaluable_cast_found);
if (emitTriggerLocInDiag)
diagnose(ctx, triggerLoc, diag::constexpr_unevaluable_cast_used_here,
triggerLocSkipsInternalLocs);
return;
}
case UnknownReason::UnknownWitnessMethodConformance: {
SmallString<8> witnessMethodName;
getWitnessMethodName(dyn_cast<WitnessMethodInst>(unknownNode),
Expand Down
49 changes: 47 additions & 2 deletions lib/SILOptimizer/Utils/ConstExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
#define DEBUG_TYPE "ConstExpr"
#include "swift/SILOptimizer/Utils/ConstExpr.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/NullablePtr.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/Demangling/Demangle.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILConstants.h"
Expand Down Expand Up @@ -1684,7 +1685,7 @@ ConstExprFunctionState::evaluateFlowSensitive(SILInstruction *inst) {
if (auto apply = dyn_cast<ApplyInst>(inst))
return computeCallResult(apply);

if (isa<StoreInst>(inst)) {
if (isa<StoreInst>(inst) || isa<StoreBorrowInst>(inst)) {
auto stored = getConstantValue(inst->getOperand(0));
if (!stored.isConstant())
return stored;
Expand Down Expand Up @@ -1837,6 +1838,50 @@ ConstExprFunctionState::evaluateInstructionAndGetNext(
return {caseBB->begin(), None};
}

if (isa<CheckedCastBranchInst>(inst)) {
CheckedCastBranchInst *checkedCastInst =
dyn_cast<CheckedCastBranchInst>(inst);
SymbolicValue value = getConstantValue(checkedCastInst->getOperand());
if (!value.isConstant())
return {None, value};

// Determine success or failure of this cast.
CanType sourceType;
if (value.getKind() == SymbolicValue::Array) {
sourceType = value.getArrayType()->getCanonicalType();
} else {
// Here, the source type cannot be an address-only type as this is
// not a CheckedCastBranchAddr inst. Therefore, it has to be a struct
// type or String or Metatype. Since the types of aggregates are not
// tracked, we recover it from the declared type of the source operand
// and generic parameter subsitutions in the interpreter state.
sourceType = substituteGenericParamsAndSimpify(
checkedCastInst->getSourceFormalType());
}
CanType targetType = substituteGenericParamsAndSimpify(
checkedCastInst->getTargetFormalType());
DynamicCastFeasibility castResult = classifyDynamicCast(
inst->getModule().getSwiftModule(), sourceType, targetType);
if (castResult == DynamicCastFeasibility::MaySucceed) {
return {None,
getUnknown(evaluator, inst, UnknownReason::UnknownCastResult)};
}
// Determine the basic block to jump to.
SILBasicBlock *resultBB =
(castResult == DynamicCastFeasibility::WillSucceed)
? checkedCastInst->getSuccessBB()
: checkedCastInst->getFailureBB();
// Set up the arguments of the basic block, if any.
if (resultBB->getNumArguments() == 0)
return {resultBB->begin(), None};
// There should be at most one argument to the basic block, which is the
// casted value with the right type, or the input value if the cast fails,
// and inst is in OSSA.
assert(resultBB->getNumArguments() == 1);
setValue(resultBB->getArgument(0), value);
return {resultBB->begin(), None};
}

LLVM_DEBUG(llvm::dbgs() << "ConstExpr: Unknown Branch Instruction: " << *inst
<< "\n");

Expand Down
19 changes: 19 additions & 0 deletions test/SILOptimizer/constant_evaluable_subset_test.swift
Original file line number Diff line number Diff line change
Expand Up @@ -892,3 +892,22 @@ func testArrayOfClosures(_ byte: @escaping () -> Int) -> [(Int) -> Int] {
func interpretArrayOfClosures() -> [(Int) -> Int] {
return testArrayOfClosures({ 10 })
}

// Test checked casts.

// CHECK-LABEL: @testMetaTypeCast
// CHECK-NOT: error:
@_semantics("constant_evaluable")
func testMetaTypeCast<T>(_ x: T.Type) -> Bool {
return (x is Int.Type)
}

@_semantics("test_driver")
func interpretMetaTypeCast() -> Bool {
return testMetaTypeCast(Int.self)
}

// FIXME: this cast is not found to be false by the classifyDynamicCast utility.
func interpretMetaTypeCast2() -> Bool {
return testMetaTypeCast(((Int) -> Int).self)
}
28 changes: 28 additions & 0 deletions test/SILOptimizer/constant_evaluator_test.sil
Original file line number Diff line number Diff line change
Expand Up @@ -1475,3 +1475,31 @@ bb0:
return %3 : $@callee_guaranteed () -> Int64
} // CHECK: Returns closure: target: closure4 captures
// CHECK-NEXT: values:

// Tests for checked cast instruction.

sil [ossa] @testMetatypeCast : $@convention(thin) <T> (@thick T.Type) -> Builtin.Int1 {
bb0(%0 : $@thick T.Type):
checked_cast_br %0 : $@thick T.Type to Int64.Type, bb1, bb2

bb1(%3 : $@thick Int64.Type):
%4 = metatype $@thin Int64.Type
%5 = integer_literal $Builtin.Int1, -1
br bb3(%5 : $Builtin.Int1)

bb2(%7 : $@thick T.Type):
%8 = integer_literal $Builtin.Int1, 0
br bb3(%8 : $Builtin.Int1)

bb3(%10 : $Builtin.Int1):
return %10 : $Builtin.Int1
}

// CHECK-LABEL: @interpretMetatypeCast
sil [ossa] @interpretMetatypeCast : $@convention(thin) () -> Builtin.Int1 {
bb0:
%1 = metatype $@thick Int64.Type
%2 = function_ref @testMetatypeCast : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Builtin.Int1
%3 = apply %2<Int64>(%1) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Builtin.Int1
return %3 : $Builtin.Int1
} // CHECK: Returns int: -1