Skip to content

[NoncopyableGenerics] Basic end-to-end testing (without stdlib). #69591

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 8 commits into from
Nov 3, 2023
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 include/swift/Basic/LangOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
#define SWIFT_BASIC_LANGOPTIONS_H

#include "swift/Basic/Feature.h"
#include "swift/Basic/FixedBitSet.h"
#include "swift/Basic/FunctionBodySkipping.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/Version.h"
Expand All @@ -28,7 +29,6 @@
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
Expand Down Expand Up @@ -426,7 +426,7 @@ namespace swift {
bool EnableNewOperatorLookup = false;

/// The set of features that have been enabled.
llvm::SmallSet<Feature, 2> Features;
FixedBitSet<numFeatures(), Feature> Features;

/// Temporary flag to support LLDB's transition to using \c Features.
bool EnableBareSlashRegexLiterals = false;
Expand Down
4 changes: 0 additions & 4 deletions include/swift/SIL/SILType.h
Original file line number Diff line number Diff line change
Expand Up @@ -862,10 +862,6 @@ class SILType {
return getSILBoxFieldType(fn).isMoveOnly();
}

bool isBoxedNonCopyableType(const SILFunction &fn) const {
return isBoxedNonCopyableType(&fn);
}

bool isBoxedMoveOnlyWrappedType(const SILFunction *fn) const {
if (!this->is<SILBoxType>())
return false;
Expand Down
11 changes: 8 additions & 3 deletions lib/IRGen/GenReflection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ getTypeRefImpl(IRGenModule &IGM,
useFlatUnique = true;
break;

case MangledTypeRefRole::FieldMetadata:
case MangledTypeRefRole::FieldMetadata: {
// We want to keep fields of noncopyable type from being exposed to
// in-process runtime reflection libraries in older Swift runtimes, since
// they more than likely assume they can copy field values, and the language
Expand All @@ -391,11 +391,16 @@ getTypeRefImpl(IRGenModule &IGM,
// noncopyable, use a function to emit the type ref which will look for a
// signal from future runtimes whether they support noncopyable types before
// exposing their metadata to them.
if (type->isNoncopyable()) {
Type contextualTy = type;
if (sig)
contextualTy = sig.getGenericEnvironment()->mapTypeIntoContext(type);

if (contextualTy->isNoncopyable()) {
IGM.IRGen.noteUseOfTypeMetadata(type);
return getTypeRefByFunction(IGM, sig, type);
}
LLVM_FALLTHROUGH;
}
LLVM_FALLTHROUGH;

case MangledTypeRefRole::DefaultAssociatedTypeWitness:
case MangledTypeRefRole::Metadata:
Expand Down
5 changes: 3 additions & 2 deletions lib/SIL/IR/SILInstructions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -387,8 +387,9 @@ AllocBoxInst::AllocBoxInst(SILDebugLocation Loc, CanSILBoxType BoxType,
sharedUInt8().AllocBoxInst.reflection = reflection;

// If we have a noncopyable type, always set uses mvoeable value debug info.
usesMoveableValueDebugInfo |=
BoxType->getLayout()->getFields()[0].getObjectType().isMoveOnly();
auto fieldTy = getSILBoxFieldType(F.getTypeExpansionContext(), BoxType,
F.getModule().Types, 0);
usesMoveableValueDebugInfo |= fieldTy.isMoveOnly();

sharedUInt8().AllocBoxInst.usesMoveableValueDebugInfo =
usesMoveableValueDebugInfo;
Expand Down
28 changes: 25 additions & 3 deletions lib/SIL/IR/SILType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1044,10 +1044,20 @@ SILType::getSingletonAggregateFieldType(SILModule &M,
}

bool SILType::isMoveOnly() const {
// Nominal types are move-only if declared as such.
if (getASTType()->isNoncopyable())
// Legacy check.
if (!getASTContext().LangOpts.hasFeature(Feature::NoncopyableGenerics)) {
return getASTType()->isNoncopyable() || isMoveOnlyWrapped();
}

// Anything within the move-only wrapper is move-only.
if (isMoveOnlyWrapped())
return true;

auto ty = getASTType();

// All kinds of references are copyable.
if (isa<ReferenceStorageType>(ty))
return false;

// TODO: Nonescaping closures ought to be treated as move-only in SIL.
// They aren't marked move-only now, because the necessary move-only passes
Expand All @@ -1060,7 +1070,19 @@ bool SILType::isMoveOnly() const {
return fnTy->isTrivialNoEscape();
}
*/
return isMoveOnlyWrapped();
if (isa<SILFunctionType>(ty))
return false;

// Treat all other SIL-specific types as Copyable.
if (isa<SILBlockStorageType,
SILBoxType,
SILPackType,
SILTokenType>(ty)) {
return false;
}

// Finally, for other ordinary types, ask the AST type.
return ty->isNoncopyable();
}


Expand Down
2 changes: 1 addition & 1 deletion lib/SILOptimizer/Transforms/AllocBoxToStack.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1062,7 +1062,7 @@ specializeApplySite(SILOptFunctionBuilder &FuncBuilder, ApplySite Apply,
// boxes, convert them from having escaping to having non-escaping
// semantics.
for (unsigned index : PromotedCalleeArgIndices) {
if (F->getArgument(index)->getType().isBoxedNonCopyableType(*F)) {
if (F->getArgument(index)->getType().isBoxedNonCopyableType(F)) {
auto boxType = F->getArgument(index)->getType().castTo<SILBoxType>();
bool isMutable = boxType->getLayout()->getFields()[0].isMutable();
auto checkKind = isMutable ? MarkUnresolvedNonCopyableValueInst::
Expand Down
4 changes: 3 additions & 1 deletion lib/Sema/TypeCheckDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -944,7 +944,9 @@ bool HasNoncopyableAnnotationRequest::evaluate(Evaluator &evaluator, TypeDecl *d

// Handle the legacy '@_moveOnly' attribute
if (decl->getAttrs().hasAttribute<MoveOnlyAttr>()) {
assert(isa<StructDecl>(decl) || isa<EnumDecl>(decl));
assert(isa<StructDecl>(decl) || isa<EnumDecl>(decl)
|| (ctx.LangOpts.hasFeature(Feature::MoveOnlyClasses)
&& isa<ClassDecl>(decl)));
return true;
}

Expand Down
117 changes: 117 additions & 0 deletions test/Interpreter/moveonly_generics.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// RUN: %target-run-simple-swift(-Xfrontend -sil-verify-all -enable-experimental-feature NoncopyableGenerics)
// RUN: %target-run-simple-swift(-O -Xfrontend -sil-verify-all -enable-experimental-feature NoncopyableGenerics)

// REQUIRES: executable_test
// REQUIRES: asserts

// Needed due to limitations of autoclosures and noncopyable types.
func eagerAssert(_ b: Bool, _ line: Int = #line) {
guard b else { fatalError("assertion failure on line \(line)") }
}

///---------------------
/// MARK: a Swift x Haskell limited-edition stdlib
/// ---------------------



/// MARK: Ord aka 'Comparable'
protocol Ord: ~Copyable {
func compare(_ other: borrowing Self) -> Ordering
}

enum Ordering {
case LT
case EQ
case GT

static func compare<T: Comparable>(_ a: borrowing T, _ b: borrowing T) -> Ordering {
if (a < b) { return .LT }
if (a > b) { return .GT }
eagerAssert(a == b)
return .EQ
}
}

extension Ord {
static func <(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
return a.compare(b) == .LT
}
static func <=(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
return !(a > b)
}
static func >(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
return a.compare(b) == .GT
}
static func >=(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
return !(a < b)
}
static func ==(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
a.compare(b) == .EQ
}
static func !=(_ a: borrowing Self, _ b: borrowing Self) -> Bool {
!(a == b)
}
}

/// MARK: Maybe aka 'Optional'
enum Maybe<Val: ~Copyable>: ~Copyable {
case just(Val)
case none

// NOTE: a 'consuming' version of the unfortunately 'borrowing' map from the stdlib.
consuming func consumingMap<U: ~Copyable>(_ fn: (consuming Val) throws -> U) rethrows -> Maybe<U> {
// rdar://117638878 (MoveOnlyAddressChecker crashes with generic associated value in enum)
fatalError("need to fix rdar://117638878")
// return switch consume self {
// case let .just(val): .just(try fn(val))
// case .none: .none
// }
}
}

// NOTE: temporary
extension Maybe: Copyable where Val: Copyable {}


/// MARK: beginning of tests

struct FileDescriptor: ~Copyable, Ord {
let id: Int

func compare(_ other: borrowing FileDescriptor) -> Ordering {
return .compare(id, other.id)
}

deinit { print("calling deinit!") }
}

class Shared<T: ~Copyable> {
let value: T
init(_ val: consuming T) { self.value = val }
func borrow<V>(_ f: (borrowing T) throws -> V) rethrows -> V {
return try f(value)
}
}

defer { testOrd() }
func testOrd() {
let stderr = Shared(FileDescriptor(id: 1))
let stdout = Shared(FileDescriptor(id: 0))
stdout.borrow { out in
stderr.borrow { err in
eagerAssert(err > out)
eagerAssert(out < err)
eagerAssert(out != err)
}
}
}

defer { testMaybe() }
func testMaybe() {
let mayb = Maybe.just(FileDescriptor(id: 0));
switch consume mayb {
case let .just(fd): eagerAssert(fd.id == 0)
case .none: eagerAssert(false)
}
}
Loading