Skip to content

IRGen: Unwrap one-element tuple metadata in emitDynamicTupleTypeMetadataRef() [5.9] #65560

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
4 changes: 2 additions & 2 deletions lib/IRGen/GenPack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -899,11 +899,11 @@ llvm::Value *irgen::emitTypeMetadataPackElementRef(
wtables.push_back(wtable);
}
}
metadataPhi->addIncoming(metadata, materialize);
metadataPhi->addIncoming(metadata, IGF.Builder.GetInsertBlock());
for (auto i : indices(wtables)) {
auto *wtable = wtables[i];
auto *wtablePhi = wtablePhis[i];
wtablePhi->addIncoming(wtable, materialize);
wtablePhi->addIncoming(wtable, IGF.Builder.GetInsertBlock());
}
IGF.Builder.CreateBr(exit);
// }} Finished emitting emit_i.
Expand Down
61 changes: 59 additions & 2 deletions lib/IRGen/GenTuple.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -562,9 +562,66 @@ Address irgen::projectTupleElementAddressByDynamicIndex(IRGenFunction &IGF,
SILType elementType) {
auto *metadata = IGF.emitTypeMetadataRefForLayout(tupleType);

llvm::Value *offset = loadTupleOffsetFromMetadata(IGF, metadata, index);

llvm::BasicBlock *trueBB = nullptr, *falseBB = nullptr, *restBB = nullptr;
llvm::BasicBlock *unwrappedBB = nullptr;
llvm::Value *unwrappedOffset = nullptr;

auto loweredTupleType = tupleType.castTo<TupleType>();
if (loweredTupleType->getNumScalarElements() <= 1) {
ConditionalDominanceScope scope(IGF);

// Test if the runtime length of the pack type is exactly 1.
CanPackType packType = loweredTupleType.getInducedPackType();
auto *shapeExpression = IGF.emitPackShapeExpression(packType);

auto *one = llvm::ConstantInt::get(IGF.IGM.SizeTy, 1);
auto *isOne = IGF.Builder.CreateICmpEQ(shapeExpression, one);

trueBB = IGF.createBasicBlock("vanishing-tuple");
falseBB = IGF.createBasicBlock("actual-tuple");

IGF.Builder.CreateCondBr(isOne, trueBB, falseBB);

IGF.Builder.emitBlock(trueBB);

// If the length is 1, the offset is just zero.
unwrappedBB = IGF.Builder.GetInsertBlock();
unwrappedOffset = llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0);

restBB = IGF.createBasicBlock("tuple-rest");
IGF.Builder.CreateBr(restBB);

IGF.Builder.emitBlock(falseBB);
}

llvm::Value *tupleOffset = nullptr;
llvm::BasicBlock *tupleBB = nullptr;

{
ConditionalDominanceScope scope(IGF);
tupleOffset = loadTupleOffsetFromMetadata(IGF, metadata, index);

tupleBB = IGF.Builder.GetInsertBlock();
}

// Control flow join with the one-element case.
llvm::Value *result = nullptr;
if (unwrappedOffset != nullptr) {
IGF.Builder.CreateBr(restBB);
IGF.Builder.emitBlock(restBB);

auto *phi = IGF.Builder.CreatePHI(IGF.IGM.Int32Ty, 2);
phi->addIncoming(unwrappedOffset, unwrappedBB);
phi->addIncoming(tupleOffset, tupleBB);

result = phi;
} else {
result = tupleOffset;
}

auto *gep =
IGF.emitByteOffsetGEP(tuple.getAddress(), offset, IGF.IGM.OpaqueTy);
IGF.emitByteOffsetGEP(tuple.getAddress(), result, IGF.IGM.OpaqueTy);
auto elementAddress = Address(gep, IGF.IGM.OpaqueTy,
IGF.IGM.getPointerAlignment());
return IGF.Builder.CreateElementBitCast(elementAddress,
Expand Down
119 changes: 95 additions & 24 deletions lib/IRGen/MetadataRequest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1170,41 +1170,112 @@ static llvm::Constant *emitEmptyTupleTypeMetadataRef(IRGenModule &IGM) {
IGM.FullExistentialTypeMetadataStructTy, fullMetadata, indices);
}

/// Emit metadata for a tuple type containing one or more pack expansions, eg
/// (T, repeat each U, v: V, repeat each W).
static MetadataResponse emitDynamicTupleTypeMetadataRef(IRGenFunction &IGF,
CanTupleType type,
DynamicMetadataRequest request) {
SmallVector<CanType, 2> types;
types.append(type.getElementTypes().begin(),
type.getElementTypes().end());

CanPackType packType = CanPackType::get(IGF.IGM.Context, types);
CanPackType packType = type.getInducedPackType();

// Begin by computing the number of elements in the tuple type.
auto *shapeExpression = IGF.emitPackShapeExpression(packType);
auto addr = emitTypeMetadataPack(IGF, packType, MetadataState::Abstract);
llvm::BasicBlock *trueBB = nullptr, *falseBB = nullptr, *restBB = nullptr;
llvm::BasicBlock *unwrappedBB = nullptr;
llvm::Value *unwrapped = nullptr;

auto *pointerToFirst = IGF.Builder.CreatePointerCast(
addr.getAddressPointer(), IGF.IGM.TypeMetadataPtrPtrTy);
// A tuple type containing zero or one non-pack-expansions might contain
// exactly one element after substitution, in which case the tuple
// "vanishes" and gets unwrapped. This behavior is implemented in both
// compile-time type substitution, and runtime type metadata instantiation,
// ensuring consistent behavior.
if (type->getNumScalarElements() <= 1) {
ConditionalDominanceScope scope(IGF);

llvm::Value *args[] = {
request.get(IGF),
shapeExpression,
pointerToFirst,
getTupleLabelsString(IGF.IGM, type),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
// Test if the runtime length of the pack type is exactly 1.
auto *one = llvm::ConstantInt::get(IGF.IGM.SizeTy, 1);
auto *isOne = IGF.Builder.CreateICmpEQ(shapeExpression, one);

auto call = IGF.Builder.CreateCall(
IGF.IGM.getGetTupleMetadataFunctionPointer(), args);
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotThrow();
trueBB = IGF.createBasicBlock("vanishing-tuple");
falseBB = IGF.createBasicBlock("actual-tuple");

Optional<unsigned> elementCount = 0;
if (auto *constant = dyn_cast<llvm::ConstantInt>(shapeExpression))
elementCount = constant->getValue().getZExtValue();
IGF.Builder.CreateCondBr(isOne, trueBB, falseBB);

cleanupTypeMetadataPack(IGF, addr, elementCount);
IGF.Builder.emitBlock(trueBB);

return MetadataResponse::handle(IGF, request, call);
// If the length is 1, directly emit the metadata for the first pack element.
ArrayRef<ProtocolConformanceRef> conformances;
llvm::SmallVector<llvm::Value *, 2> wtables;

auto *index = llvm::ConstantInt::get(IGF.IGM.SizeTy, 0);
auto *value = emitTypeMetadataPackElementRef(
IGF, packType, conformances, index, request, wtables);

// FIXME: Should emitTypeMetadataPackElementRef() preserve the dynamic state?
auto response = MetadataResponse::forBounded(
value, request.getStaticLowerBoundOnResponseState());
response.ensureDynamicState(IGF);

unwrapped = response.combine(IGF);
unwrappedBB = IGF.Builder.GetInsertBlock();

assert(wtables.empty());

restBB = IGF.createBasicBlock("tuple-rest");
IGF.Builder.CreateBr(restBB);

IGF.Builder.emitBlock(falseBB);
}

llvm::CallInst *call = nullptr;

{
ConditionalDominanceScope scope(IGF);

// Otherwise, we know that either statically or dynamically, we have more than
// one element. Emit the pack.
auto addr = emitTypeMetadataPack(IGF, packType, MetadataState::Abstract);

auto *pointerToFirst = IGF.Builder.CreatePointerCast(
addr.getAddressPointer(), IGF.IGM.TypeMetadataPtrPtrTy);

// Call swift_getTupleMetadata().
llvm::Value *args[] = {
request.get(IGF),
shapeExpression,
pointerToFirst,
getTupleLabelsString(IGF.IGM, type),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};

call = IGF.Builder.CreateCall(
IGF.IGM.getGetTupleMetadataFunctionPointer(), args);
call->setCallingConv(IGF.IGM.SwiftCC);
call->setDoesNotThrow();

// Clean up the pack.
Optional<unsigned> elementCount = 0;
if (auto *constant = dyn_cast<llvm::ConstantInt>(shapeExpression))
elementCount = constant->getValue().getZExtValue();

cleanupTypeMetadataPack(IGF, addr, elementCount);
}

// Control flow join with the one-element case.
llvm::Value *result = nullptr;
if (unwrapped != nullptr) {
IGF.Builder.CreateBr(restBB);
IGF.Builder.emitBlock(restBB);

auto *phi = IGF.Builder.CreatePHI(IGF.IGM.TypeMetadataResponseTy, 2);
phi->addIncoming(unwrapped, unwrappedBB);
phi->addIncoming(call, call->getParent());

result = phi;
} else {
result = call;
}

return MetadataResponse::handle(IGF, request, result);
}

static MetadataResponse emitTupleTypeMetadataRef(IRGenFunction &IGF,
Expand Down
45 changes: 45 additions & 0 deletions test/IRGen/variadic_vanishing_tuple.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize

public func takesMetatype<T>(_: T.Type) {}

public func makeTuple<each T>(_ t: repeat each T) {
takesMetatype((repeat each T).self)
}

// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc void @"$s24variadic_vanishing_tuple9makeTupleyyxxQpRvzlF"(%swift.opaque** noalias nocapture %0, {{i32|i64}} %1, %swift.type** %"each T")
// CHECK: [[CMP:%.*]] = icmp eq [[INT]] %1, 1
// CHECK: br i1 [[CMP]], label %vanishing-tuple, label %actual-tuple

// CHECK: vanishing-tuple:
// CHECK: [[PACK_ADDR:%.*]] = ptrtoint %swift.type** %"each T" to [[INT]]
// CHECK: [[PACK_ADDR_MASKED:%.*]] = and [[INT]] [[PACK_ADDR]], -2
// CHECK: [[PACK_PTR:%.*]] = inttoptr [[INT]] [[PACK_ADDR_MASKED]] to %swift.type**
// CHECK: [[ELT_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[PACK_PTR]], [[INT]] 0
// CHECK: [[ELT:%.*]] = load %swift.type*, %swift.type** [[ELT_PTR]]
// CHECK: [[RESULT:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[ELT]], 0
// CHECK: [[RESULT2:%.*]] = insertvalue %swift.metadata_response [[RESULT]], [[INT]] 0, 1
// CHECK: br label %tuple-rest

// CHECK: actual-tuple:
// CHECK: [[PACK:%.*]] = alloca %swift.type*, [[INT]] %1
// CHECK: br label %pack-expansion-check

// CHECK: pack-expansion-check:
// CHECK: br i1 {{%.*}}, label %pack-expansion-loop, label %pack-expansion-rest

// CHECK: pack-expansion-loop:
// CHECK: br label %pack-expansion-check

// CHECK: pack-expansion-rest:
// CHECK: [[TUPLE:%.*]] = call swiftcc %swift.metadata_response @swift_getTupleTypeMetadata([[INT]] 0, [[INT]] %1, %swift.type** [[PACK:%.*]], i8* null, i8** null)
// CHECK: br label %tuple-rest

// CHECK: tuple-rest:
// CHECK: [[PHI:%.*]] = phi %swift.metadata_response [ [[RESULT2]], %vanishing-tuple ], [ [[TUPLE]], %pack-expansion-rest ]
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[PHI]], 0
// CHECK: call swiftcc void @"$s24variadic_vanishing_tuple13takesMetatypeyyxmlF"(%swift.type* [[METADATA]], %swift.type* [[METADATA]])
// CHECK: ret void

public func makeTuple2<each T, each U, each V: Hashable>(t: repeat each T, u: repeat each U, v: repeat each V) {
takesMetatype((repeat each T, repeat Array<each U>, repeat Set<each V>).self)
}
19 changes: 7 additions & 12 deletions test/Interpreter/variadic_generic_tuples.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
// RUN: %target-run-simple-swift

// FIXME: Fix the optimizer
// REQUIRES: swift_test_mode_optimize_none

// REQUIRES: executable_test

import StdlibUnittest
Expand All @@ -18,8 +15,8 @@ func makeTuple<each T>(_: repeat (each T).Type) -> Any.Type {
tuples.test("makeTuple") {
expectEqual("()", _typeName(makeTuple()))

// FIXME: This should unwrap the one-element tuple!
expectEqual("(Swift.Array<Swift.Int>)", _typeName(makeTuple(Int.self)))
// Note that we unwrap the one-element tuple!
expectEqual("Swift.Array<Swift.Int>", _typeName(makeTuple(Int.self)))

expectEqual("(Swift.Array<Swift.Int>, Swift.Array<Swift.String>)", _typeName(makeTuple(Int.self, String.self)))
expectEqual("(Swift.Array<Swift.Int>, Swift.Array<Swift.String>, Swift.Array<Swift.Float>)", _typeName(makeTuple(Int.self, String.self, Float.self)))
Expand All @@ -30,8 +27,8 @@ func makeTuple2<each T>(_: repeat (each T).Type) -> Any.Type {
}

tuples.test("makeTuple2") {
// FIXME: This should unwrap the one-element tuple!
expectEqual("(Swift.Int)", _typeName(makeTuple2()))
// Note that we unwrap the one-element tuple!
expectEqual("Swift.Int", _typeName(makeTuple2()))

expectEqual("(Swift.Int, Swift.Array<Swift.Bool>)", _typeName(makeTuple2(Bool.self)))
expectEqual("(Swift.Int, Swift.Array<Swift.Bool>, Swift.Array<Swift.Character>)", _typeName(makeTuple2(Bool.self, Character.self)))
Expand All @@ -45,11 +42,9 @@ func makeTuple3<each T, each U>(t: repeat (each T).Type, u: repeat (each U).Type
tuples.test("makeTuple3") {
expectEqual("()", _typeName(makeTuple3()))

// FIXME: This should unwrap the one-element tuple!
expectEqual("(Swift.Int)", _typeName(makeTuple3(t: Int.self)))

// FIXME: This should unwrap the one-element tuple!
expectEqual("(Swift.Int)", _typeName(makeTuple3(u: Int.self)))
// Note that we unwrap the one-element tuple!
expectEqual("Swift.Int", _typeName(makeTuple3(t: Int.self)))
expectEqual("Swift.Int", _typeName(makeTuple3(u: Int.self)))

expectEqual("(Swift.Int, Swift.Float)", _typeName(makeTuple3(t: Int.self, u: Float.self)))
}
Expand Down