Skip to content

Fix the emission of open-existential-metatype l-values #9852

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
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
2 changes: 1 addition & 1 deletion lib/SILGen/LValue.h
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class PathComponent {
OwnershipKind, // weak pointer remapping
AutoreleasingWritebackKind, // autorelease pointer on set
WritebackPseudoKind, // a fake component to customize writeback
OpenClassExistentialKind, // opened class existential
OpenNonOpaqueExistentialKind, // opened class or metatype existential
// Translation LValue kinds (a subtype of logical)
OrigToSubstKind, // generic type substitution
SubstToOrigKind, // generic type substitution
Expand Down
4 changes: 4 additions & 0 deletions lib/SILGen/SILGenExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4011,10 +4011,14 @@ void SILGenFunction::emitOpenExistentialExprImpl(
// Create a writeback scope for the access to the existential lvalue.
writebackScope.emplace(*this);

Type formalRValueType =
E->getOpaqueValue()->getType()->getLValueOrInOutObjectType();

accessKind = E->getExistentialValue()->getLValueAccessKind();
auto lv = emitLValue(E->getExistentialValue(), accessKind);
lv = emitOpenExistentialLValue(E, std::move(lv),
CanArchetypeType(E->getOpenedArchetype()),
formalRValueType->getCanonicalType(),
accessKind);
auto addr = emitAddressOfLValue(E, std::move(lv), accessKind);
state = {addr, false, false};
Expand Down
1 change: 1 addition & 0 deletions lib/SILGen/SILGenFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -1304,6 +1304,7 @@ class LLVM_LIBRARY_VISIBILITY SILGenFunction
LValue emitOpenExistentialLValue(SILLocation loc,
LValue &&existentialLV,
CanArchetypeType openedArchetype,
CanType formalRValueType,
AccessKind accessKind);

RValue emitLoadOfLValue(SILLocation loc, LValue &&src, SGFContext C,
Expand Down
105 changes: 62 additions & 43 deletions lib/SILGen/SILGenLValue.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -627,16 +627,15 @@ namespace {
/// A physical path component which projects out an opened archetype
/// from an existential.
class OpenOpaqueExistentialComponent : public PhysicalPathComponent {
static LValueTypeData getOpenedArchetypeTypeData(CanArchetypeType type) {
return {
AbstractionPattern::getOpaque(), type,
SILType::getPrimitiveObjectType(type)
};
CanArchetypeType getOpenedArchetype() const {
return cast<ArchetypeType>(getSubstFormalType());
}
public:
OpenOpaqueExistentialComponent(CanArchetypeType openedArchetype)
: PhysicalPathComponent(getOpenedArchetypeTypeData(openedArchetype),
OpenOpaqueExistentialKind) {}
OpenOpaqueExistentialComponent(CanArchetypeType openedArchetype,
LValueTypeData typeData)
: PhysicalPathComponent(typeData, OpenOpaqueExistentialKind) {
assert(getOpenedArchetype() == openedArchetype);
}

ManagedValue offset(SILGenFunction &SGF, SILLocation loc, ManagedValue base,
AccessKind accessKind) && override {
Expand Down Expand Up @@ -665,8 +664,7 @@ namespace {
llvm_unreachable("Bad existential representation for address-only type");
}

SGF.setArchetypeOpeningSite(cast<ArchetypeType>(getSubstFormalType()),
addr);
SGF.setArchetypeOpeningSite(getOpenedArchetype(), addr);
return ManagedValue::forLValue(addr);
}

Expand All @@ -675,21 +673,17 @@ namespace {
}
};

/// A local path component for the payload of a class existential.
/// A local path component for the payload of a class or metatype existential.
///
/// TODO: Could be physical if we had a way to project out the
/// payload.
class OpenClassExistentialComponent : public LogicalPathComponent {
static LValueTypeData getOpenedArchetypeTypeData(CanArchetypeType type) {
return {
AbstractionPattern::getOpaque(), type,
SILType::getPrimitiveObjectType(type)
};
}
class OpenNonOpaqueExistentialComponent : public LogicalPathComponent {
CanArchetypeType OpenedArchetype;
public:
OpenClassExistentialComponent(CanArchetypeType openedArchetype)
: LogicalPathComponent(getOpenedArchetypeTypeData(openedArchetype),
OpenClassExistentialKind) {}
OpenNonOpaqueExistentialComponent(CanArchetypeType openedArchetype,
LValueTypeData typeData)
: LogicalPathComponent(typeData, OpenNonOpaqueExistentialKind),
OpenedArchetype(openedArchetype) {}

AccessKind getBaseAccessKind(SILGenFunction &SGF,
AccessKind kind) const override {
Expand All @@ -712,15 +706,23 @@ namespace {
auto result = SGF.emitLoad(loc, base.getValue(), TL,
SGFContext(), IsNotTake);

assert(refType.isExistentialType() &&
assert(refType.isAnyExistentialType() &&
"base for open existential component must be an existential");
assert(refType.getPreferredExistentialRepresentation(SGF.SGM.M)
== ExistentialRepresentation::Class);
auto ref = SGF.B.createOpenExistentialRef(
loc, result, getTypeOfRValue());
ManagedValue ref;
if (refType.is<ExistentialMetatypeType>()) {
assert(refType.getPreferredExistentialRepresentation(SGF.SGM.M)
== ExistentialRepresentation::Metatype);
ref = ManagedValue::forUnmanaged(
SGF.B.createOpenExistentialMetatype(loc,
result.getUnmanagedValue(),
getTypeOfRValue()));
} else {
assert(refType.getPreferredExistentialRepresentation(SGF.SGM.M)
== ExistentialRepresentation::Class);
ref = SGF.B.createOpenExistentialRef(loc, result, getTypeOfRValue());
}

SGF.setArchetypeOpeningSite(cast<ArchetypeType>(getSubstFormalType()),
ref.getValue());
SGF.setArchetypeOpeningSite(OpenedArchetype, ref.getValue());

return RValue(SGF, loc, getSubstFormalType(), ref);
}
Expand All @@ -730,15 +732,24 @@ namespace {
auto payload = std::move(value).forwardAsSingleValue(SGF, loc);

SmallVector<ProtocolConformanceRef, 2> conformances;
for (auto proto : cast<ArchetypeType>(getSubstFormalType())->getConformsTo())
for (auto proto : OpenedArchetype->getConformsTo())
conformances.push_back(ProtocolConformanceRef(proto));

auto ref = SGF.B.createInitExistentialRef(
loc,
base.getType().getObjectType(),
getSubstFormalType(),
payload,
SGF.getASTContext().AllocateCopy(conformances));
SILValue ref;
if (base.getType().is<ExistentialMetatypeType>()) {
ref = SGF.B.createInitExistentialMetatype(
loc,
payload,
base.getType().getObjectType(),
SGF.getASTContext().AllocateCopy(conformances));
} else {
ref = SGF.B.createInitExistentialRef(
loc,
base.getType().getObjectType(),
getSubstFormalType(),
payload,
SGF.getASTContext().AllocateCopy(conformances));
}

auto &TL = SGF.getTypeLowering(base.getType());
SGF.emitSemanticStore(loc, ref,
Expand All @@ -748,13 +759,13 @@ namespace {
std::unique_ptr<LogicalPathComponent>
clone(SILGenFunction &SGF, SILLocation loc) const override {
LogicalPathComponent *clone =
new OpenClassExistentialComponent(
cast<ArchetypeType>(getSubstFormalType()));
new OpenNonOpaqueExistentialComponent(OpenedArchetype, getTypeData());
return std::unique_ptr<LogicalPathComponent>(clone);
}

void print(raw_ostream &OS) const override {
OS << "OpenClassExistentialComponent(...)\n";
OS << "OpenNonOpaqueExistentialComponent(" << OpenedArchetype
<< ", ...)\n";
}
};

Expand Down Expand Up @@ -2072,6 +2083,7 @@ LValue SILGenLValue::visitOpaqueValueExpr(OpaqueValueExpr *e,
lv = SGF.emitOpenExistentialLValue(
opened, std::move(lv),
CanArchetypeType(opened->getOpenedArchetype()),
e->getType()->getLValueOrInOutObjectType()->getCanonicalType(),
accessKind);
return lv;
}
Expand Down Expand Up @@ -2977,23 +2989,30 @@ LValue
SILGenFunction::emitOpenExistentialLValue(SILLocation loc,
LValue &&lv,
CanArchetypeType openedArchetype,
CanType formalRValueType,
AccessKind accessKind) {
assert(!formalRValueType->isLValueType());
LValueTypeData typeData = {
AbstractionPattern::getOpaque(), formalRValueType,
getLoweredType(formalRValueType).getObjectType()
};

// Open up the existential.
auto rep = lv.getTypeOfRValue()
.getPreferredExistentialRepresentation(SGM.M);
switch (rep) {
case ExistentialRepresentation::Opaque:
case ExistentialRepresentation::Boxed: {
lv.add<OpenOpaqueExistentialComponent>(openedArchetype);
lv.add<OpenOpaqueExistentialComponent>(openedArchetype, typeData);
break;
}
case ExistentialRepresentation::Metatype:
case ExistentialRepresentation::Class: {
lv.add<OpenClassExistentialComponent>(openedArchetype);
lv.add<OpenNonOpaqueExistentialComponent>(openedArchetype, typeData);
break;
}
default:
llvm_unreachable("Cannot perform lvalue access of "
"non-opaque, non-class existential");
case ExistentialRepresentation::None:
llvm_unreachable("cannot open non-existential");
}

return std::move(lv);
Expand Down
19 changes: 19 additions & 0 deletions test/SILGen/existential_metatypes.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s | %FileCheck %s

struct Value {}

protocol P {
init()
static func staticMethod() -> Self
static var value: Value { get }
}

struct S: P {
init() {}
static func staticMethod() -> S { return S() }
static var value: Value { return Value() }
}

// CHECK-LABEL: sil hidden @_T021existential_metatypes0A8MetatypeyAA1P_pF
Expand Down Expand Up @@ -51,3 +55,18 @@ func existentialMetatypeUpcast1(_ x: PP.Type) -> P.Type {
func existentialMetatypeUpcast2(_ x: (P & Q).Type) -> P.Type {
return x
}

// rdar://32288618
// CHECK-LABEL: sil hidden @_T021existential_metatypes0A19MetatypeVarPropertyAA5ValueVyF : $@convention(thin) () -> Value
func existentialMetatypeVarProperty() -> Value {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @thick P.Type }
// CHECK: [[ADDR:%.*]] = project_box [[BOX]] : ${ var @thick P.Type }, 0
// CHECK: [[T0:%.*]] = metatype $@thick S.Type
// CHECK: [[T1:%.*]] = init_existential_metatype [[T0]]
// CHECK: store [[T1]] to [trivial] [[ADDR]] :
// CHECK: [[T0:%.*]] = begin_access [read] [unknown] [[ADDR]] :
// CHECK: [[T1:%.*]] = load [trivial] [[T0]]
// CHECK: open_existential_metatype [[T1]] :
var type: P.Type = S.self
return type.value
}
6 changes: 6 additions & 0 deletions test/SILOptimizer/devirt_protocol_method_invocations.swift
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ public func testExMetatype() -> Int {
return type.size
}

// rdar://32288618
public func testExMetatypeVar() -> Int {
var type: StaticP.Type = HasStatic<Int>.self
return type.size
}

// IRGen used to crash on the testPropagationOfConcreteTypeIntoExistential method.
// rdar://26286278

Expand Down