Skip to content

Migrate from UnsafePointer<Void> to UnsafeRawPointer. #3724

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 10 commits into from
Jul 26, 2016
8 changes: 4 additions & 4 deletions benchmark/utils/DriverUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,9 @@ func internalMedian(_ inputs: [UInt64]) -> UInt64 {
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER

@_silgen_name("swift_leaks_startTrackingObjects")
func startTrackingObjects(_: UnsafeMutablePointer<Void>) -> ()
func startTrackingObjects(_: UnsafeMutableRawPointer) -> ()
@_silgen_name("swift_leaks_stopTrackingObjects")
func stopTrackingObjects(_: UnsafeMutablePointer<Void>) -> Int
func stopTrackingObjects(_: UnsafeMutableRawPointer) -> Int

#endif

Expand All @@ -235,14 +235,14 @@ class SampleRunner {
// Start the timer.
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
var str = name
startTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
startTrackingObjects(UnsafeMutableRawPointer(str._core.startASCII))
#endif
let start_ticks = mach_absolute_time()
fn(Int(num_iters))
// Stop the timer.
let end_ticks = mach_absolute_time()
#if SWIFT_RUNTIME_ENABLE_LEAK_CHECKER
stopTrackingObjects(UnsafeMutablePointer<Void>(str._core.startASCII))
stopTrackingObjects(UnsafeMutableRawPointer(str._core.startASCII))
#endif

// Compute the spent time and the scaling factor.
Expand Down
10 changes: 5 additions & 5 deletions docs/proposals/CPointerInteropLanguageModel.rst
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ accept any of the following:
array, and lifetime-extended for the duration of the callee.

As a special case, when a function is declared as taking an
``UnsafeMutablePointer<Void>`` argument, it can accept the same operands as
``UnsafeMutableRawPointer`` argument, it can accept the same operands as
``UnsafeMutablePointer<T>`` for any type T.

So if you have a function declared::
Expand All @@ -80,7 +80,7 @@ You can call it as any of::

And if you have a function declared::

func bar(_ x: UnsafeMutablePointer<Void>)
func bar(_ x: UnsafeMutableRawPointer)

You can call it as any of::

Expand Down Expand Up @@ -139,7 +139,7 @@ accept any of the following:
array, and lifetime-extended for the duration of the callee.

As a special case, when a function is declared as taking an
``UnsafePointer<Void>`` argument, it can accept the same operands as
``UnsafeRawPointer`` argument, it can accept the same operands as
``UnsafePointer<T>`` for any type ``T``. Pointers to certain integer
types can furthermore interoperate with strings; see `Strings`_ below.

Expand All @@ -158,7 +158,7 @@ You can call it as any of::

And if you have a function declared::

func zang(_ x: UnsafePointer<Void>)
func zang(_ x: UnsafeRawPointer)

You can call it as any of::

Expand All @@ -175,7 +175,7 @@ You can call it as any of::
zang(ints)

A type checker limitation prevents array literals from being passed directly
to ``UnsafePointer<Void>`` arguments without type annotation. As a
to ``UnsafeRawPointer`` arguments without type annotation. As a
workaround, you can bind the array literal to a constant, as above, or
specify the array type with ``as``::

Expand Down
15 changes: 4 additions & 11 deletions lib/AST/Module.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -371,23 +371,16 @@ VarDecl *Module::getDSOHandle() {
if (DSOHandle)
return DSOHandle;

auto unsafeMutablePtr = getASTContext().getUnsafeMutablePointerDecl();
if (!unsafeMutablePtr)
auto unsafeMutableRawPtr = getASTContext().getUnsafeMutableRawPointerDecl();
if (!unsafeMutableRawPtr)
return nullptr;

Type arg;
auto &ctx = getASTContext();
if (auto voidDecl = ctx.getVoidDecl()) {
arg = voidDecl->getDeclaredInterfaceType();
} else {
arg = TupleType::getEmpty(ctx);
}

Type type = BoundGenericType::get(unsafeMutablePtr, Type(), { arg });
auto handleVar = new (ctx) VarDecl(/*IsStatic=*/false, /*IsLet=*/false,
SourceLoc(),
ctx.getIdentifier("__dso_handle"),
type, Files[0]);
unsafeMutableRawPtr->getDeclaredType(),
Files[0]);
handleVar->setImplicit(true);
handleVar->getAttrs().add(
new (ctx) SILGenNameAttr("__dso_handle", /*Implicit=*/true));
Expand Down
17 changes: 14 additions & 3 deletions lib/ClangImporter/ImportType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,7 @@ namespace {

ImportResult VisitPointerType(const clang::PointerType *type) {
auto pointeeQualType = type->getPointeeType();
auto quals = pointeeQualType.getQualifiers();

// Special case for NSZone*, which has its own Swift wrapper.
if (const clang::RecordType *pointee =
Expand All @@ -303,7 +304,19 @@ namespace {
return {wrapperTy, ImportHint::OtherPointer};
}
}


// Import 'void*' as 'UnsafeMutableRawPointer' and 'const void*' as
// 'UnsafeRawPointer'. This is Swift's version of an untyped pointer. Note
// that 'Unsafe[Mutable]Pointer<T>' implicitly converts to
// 'Unsafe[Mutable]RawPointer' for interoperability.
if (pointeeQualType->isVoidType()) {
return {
(quals.hasConst() ? Impl.SwiftContext.getUnsafeRawPointerDecl()
: Impl.SwiftContext.getUnsafeMutableRawPointerDecl())
->getDeclaredType(),
ImportHint::OtherPointer};
}

// All other C pointers to concrete types map to
// UnsafeMutablePointer<T> or OpaquePointer (FIXME:, except in
// parameter position under the pre-
Expand Down Expand Up @@ -336,8 +349,6 @@ namespace {
};
}

auto quals = pointeeQualType.getQualifiers();

if (quals.hasConst()) {
return {Impl.getNamedSwiftTypeSpecialization(Impl.getStdlibModule(),
"UnsafePointer",
Expand Down
2 changes: 1 addition & 1 deletion lib/IDE/CodeCompletion.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4656,7 +4656,7 @@ static void addExprKeywords(CodeCompletionResultSink &Sink) {
// Same: Swift.IntegerLiteralType.
AddKeyword("#line", "Int", CodeCompletionKeywordKind::pound_line);
AddKeyword("#column", "Int", CodeCompletionKeywordKind::pound_column);
AddKeyword("#dsohandle", "UnsafeMutablePointer<Void>", CodeCompletionKeywordKind::pound_dsohandle);
AddKeyword("#dsohandle", "UnsafeMutableRawPointer", CodeCompletionKeywordKind::pound_dsohandle);
}

static void addAnyTypeKeyword(CodeCompletionResultSink &Sink) {
Expand Down
2 changes: 2 additions & 0 deletions lib/PrintAsObjC/PrintAsObjC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,8 @@ class ObjCPrinter : private DeclVisitor<ObjCPrinter>,
MAP(Bool, "BOOL", false);

MAP(OpaquePointer, "void *", true);
MAP(UnsafeRawPointer, "void const *", true);
MAP(UnsafeMutableRawPointer, "void *", true);

Identifier ID_ObjectiveC = ctx.Id_ObjectiveC;
specialNames[{ID_ObjectiveC, ctx.getIdentifier("ObjCBool")}]
Expand Down
2 changes: 1 addition & 1 deletion lib/Sema/CSGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1227,7 +1227,7 @@ namespace {
return visitLiteralExpr(expr);

case MagicIdentifierLiteralExpr::DSOHandle: {
// #dsohandle has type UnsafeMutablePointer<Void>.
// #dsohandle has type UnsafeMutableRawPointer.
auto &tc = CS.getTypeChecker();
if (tc.requirePointerArgumentIntrinsics(expr->getLoc()))
return nullptr;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ internal class PthreadBlockContext {
/// Execute the block, and return an `UnsafeMutablePointer` to memory
/// allocated with `UnsafeMutablePointer.alloc` containing the result of the
/// block.
func run() -> UnsafeMutablePointer<Void> { fatalError("abstract") }
func run() -> UnsafeMutableRawPointer { fatalError("abstract") }
}

internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext {
Expand All @@ -40,17 +40,17 @@ internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext {
super.init()
}

override func run() -> UnsafeMutablePointer<Void> {
override func run() -> UnsafeMutableRawPointer {
let result = UnsafeMutablePointer<Result>.allocate(capacity: 1)
result.initialize(to: block(arg))
return UnsafeMutablePointer(result)
return UnsafeMutableRawPointer(result)
}
}

/// Entry point for `pthread_create` that invokes a block context.
internal func invokeBlockContext(
_ contextAsVoidPointer: UnsafeMutablePointer<Void>?
) -> UnsafeMutablePointer<Void>! {
_ contextAsVoidPointer: UnsafeMutableRawPointer?
) -> UnsafeMutableRawPointer! {
// The context is passed in +1; we're responsible for releasing it.
let context = Unmanaged<PthreadBlockContext>
.fromOpaque(contextAsVoidPointer!)
Expand Down Expand Up @@ -95,12 +95,14 @@ public func _stdlib_pthread_join<Result>(
_ thread: pthread_t,
_ resultType: Result.Type
) -> (CInt, Result?) {
var threadResultPtr: UnsafeMutablePointer<Void>? = nil
let result = pthread_join(thread, &threadResultPtr)
var threadResultRawPtr: UnsafeMutableRawPointer? = nil
let result = pthread_join(thread, &threadResultRawPtr)
if result == 0 {
let threadResult = UnsafeMutablePointer<Result>(threadResultPtr!).pointee
threadResultPtr!.deinitialize()
threadResultPtr!.deallocate(capacity: 1)
let threadResultPtr = threadResultRawPtr!.assumingMemoryBound(
to: Result.self)
let threadResult = threadResultPtr.pointee
threadResultPtr.deinitialize()
threadResultPtr.deallocate(capacity: 1)
return (result, threadResult)
} else {
return (result, nil)
Expand Down
12 changes: 6 additions & 6 deletions stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public enum InstanceKind : UInt8 {
/// Represents a section in a loaded image in this process.
internal struct Section {
/// The absolute start address of the section's data in this address space.
let startAddress: UnsafePointer<Void>
let startAddress: UnsafeRawPointer

/// The size of the section in bytes.
let size: UInt
Expand Down Expand Up @@ -211,7 +211,7 @@ internal func sendBytes() {
let count = Int(readUInt())
debugLog("Parent requested \(count) bytes from \(address)")
var totalBytesWritten = 0
var pointer = unsafeBitCast(address, to: UnsafeMutablePointer<Void>.self)
var pointer = unsafeBitCast(address, to: UnsafeMutableRawPointer.self)
while totalBytesWritten < count {
let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout))
fflush(stdout)
Expand All @@ -228,7 +228,7 @@ internal func sendSymbolAddress() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let name = readLine()!
name.withCString {
let handle = unsafeBitCast(Int(-2), to: UnsafeMutablePointer<Void>.self)
let handle = unsafeBitCast(Int(-2), to: UnsafeMutableRawPointer.self)
let symbol = dlsym(handle, $0)
let symbolAddress = unsafeBitCast(symbol, to: UInt.self)
sendValue(symbolAddress)
Expand All @@ -247,7 +247,7 @@ internal func sendStringLength() {
/// Send the size of this architecture's pointer type.
internal func sendPointerSize() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let pointerSize = UInt8(sizeof(UnsafePointer<Void>.self))
let pointerSize = UInt8(sizeof(UnsafeRawPointer.self))
sendValue(pointerSize)
}

Expand Down Expand Up @@ -412,8 +412,8 @@ struct ThickFunction3 {
}

struct ThickFunctionParts {
var function: UnsafePointer<Void>
var context: Optional<UnsafePointer<Void>>
var function: UnsafeRawPointer
var context: Optional<UnsafeRawPointer>
}

/// Reflect a closure context. The given function must be a Swift-native
Expand Down
8 changes: 4 additions & 4 deletions stdlib/public/Platform/Platform.swift
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ internal func _swift_Platform_fcntl(
internal func _swift_Platform_fcntlPtr(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutablePointer<Void>
_ ptr: UnsafeMutableRawPointer
) -> Int32

public func fcntl(
Expand All @@ -240,7 +240,7 @@ public func fcntl(
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutablePointer<Void>
_ ptr: UnsafeMutableRawPointer
) -> Int32 {
return _swift_Platform_fcntlPtr(fd, cmd, ptr)
}
Expand Down Expand Up @@ -313,7 +313,7 @@ internal func _swift_Platform_ioctl(
internal func _swift_Platform_ioctlPtr(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutablePointer<Void>
_ ptr: UnsafeMutableRawPointer
) -> CInt

public func ioctl(
Expand All @@ -327,7 +327,7 @@ public func ioctl(
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutablePointer<Void>
_ ptr: UnsafeMutableRawPointer
) -> CInt {
return _swift_Platform_ioctlPtr(fd, request, ptr)
}
Expand Down
26 changes: 16 additions & 10 deletions stdlib/public/SDK/CoreAudio/CoreAudio.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,23 @@

extension UnsafeBufferPointer {
/// Initialize an `UnsafeBufferPointer<Element>` from an `AudioBuffer`.
/// Binds the the buffer's memory type to `Element`.
public init(_ audioBuffer: AudioBuffer) {
self.init(
start: UnsafePointer<Element>(audioBuffer.mData),
count: Int(audioBuffer.mDataByteSize) / strideof(Element.self))
let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self)
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}

extension UnsafeMutableBufferPointer {
/// Initialize an `UnsafeMutableBufferPointer<Element>` from an
/// `AudioBuffer`.
public init(_ audioBuffer: AudioBuffer) {
self.init(
start: UnsafeMutablePointer<Element>(audioBuffer.mData),
count: Int(audioBuffer.mDataByteSize) / strideof(Element.self))
let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self)
let elementPtr = audioBuffer.mData?.bindMemory(
to: Element.self, capacity: count)
self.init(start: elementPtr, count: count)
}
}

Expand All @@ -39,7 +42,7 @@ extension AudioBuffer {
numberOfChannels: Int
) {
self.mNumberChannels = UInt32(numberOfChannels)
self.mData = UnsafeMutablePointer<Void>(typedBuffer.baseAddress)
self.mData = UnsafeMutableRawPointer(typedBuffer.baseAddress)
self.mDataByteSize = UInt32(typedBuffer.count * strideof(Element.self))
}
}
Expand Down Expand Up @@ -68,8 +71,10 @@ extension AudioBufferList {
_precondition(ablMemory != nil,
"failed to allocate memory for an AudioBufferList")

let abl = UnsafeMutableAudioBufferListPointer(
UnsafeMutablePointer<AudioBufferList>(ablMemory!))
let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1)
(ablMemory! + strideof(AudioBufferList.self)).bindMemory(
to: AudioBuffer.self, capacity: maximumBuffers)
let abl = UnsafeMutableAudioBufferListPointer(listPtr)
abl.count = maximumBuffers
return abl
}
Expand Down Expand Up @@ -108,7 +113,8 @@ public struct UnsafeMutableAudioBufferListPointer {
// AudioBufferList has one AudioBuffer in a "flexible array member".
// Position the pointer after that, and skip one AudioBuffer back. This
// brings us to the start of AudioBuffer array.
return UnsafeMutablePointer<AudioBuffer>(unsafeMutablePointer + 1) - 1
let rawPtr = UnsafeMutableRawPointer(unsafeMutablePointer + 1)
return rawPtr.assumingMemoryBound(to: AudioBuffer.self) - 1
}

// FIXME: the properties 'unsafePointer' and 'unsafeMutablePointer' should be
Expand Down
Loading