diff --git a/benchmark/single-source/BitCount.swift b/benchmark/single-source/BitCount.swift index f2bc50d2a9b68..fd15a5d37d44d 100644 --- a/benchmark/single-source/BitCount.swift +++ b/benchmark/single-source/BitCount.swift @@ -17,7 +17,7 @@ import Foundation import TestsUtils func countBitSet(_ num: Int) -> Int { - let bits = sizeof(Int.self) * 8 + let bits = MemoryLayout.size * 8 var cnt: Int = 0 var mask: Int = 1 for _ in 0...bits { diff --git a/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift b/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift index 3401dc72a0769..40541fc00e331 100644 --- a/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift +++ b/stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift @@ -116,7 +116,7 @@ public func spawnChild(_ args: [String]) // If execve() encountered an error, we write the errno encountered to the // parent write pipe. - let errnoSize = sizeof(errno.dynamicType) + let errnoSize = MemoryLayout._ofInstance(errno).size var execveErrno = errno let writtenBytes = withUnsafePointer(to: &execveErrno) { write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize) diff --git a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift index 72d322c2a4615..dd9056f59b30c 100644 --- a/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift +++ b/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift @@ -42,7 +42,7 @@ public var _stdlib_FD_SETSIZE: CInt { public struct _stdlib_fd_set { var _data: [UInt] static var _wordBits: Int { - return sizeof(UInt.self) * 8 + return MemoryLayout.size * 8 } public init() { diff --git a/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift b/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift index 040aa18724e43..2e3211ec0a94f 100644 --- a/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift +++ b/stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift @@ -157,21 +157,21 @@ internal func sendAddress(of instance: AnyObject) { debugLog("BEGIN \(#function)") defer { debugLog("END \(#function)") } var address = Unmanaged.passUnretained(instance).toOpaque() - sendBytes(from: &address, count: sizeof(UInt.self)) + sendBytes(from: &address, count: MemoryLayout.size) } /// Send the `value`'s bits to the parent. internal func sendValue(_ value: T) { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } var value = value - sendBytes(from: &value, count: sizeof(T.self)) + sendBytes(from: &value, count: MemoryLayout.size) } /// Read a word-sized unsigned integer from the parent. internal func readUInt() -> UInt { debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") } var value: UInt = 0 - fread(&value, sizeof(UInt.self), 1, stdin) + fread(&value, MemoryLayout.size, 1, stdin) return value } @@ -184,7 +184,7 @@ internal func sendReflectionInfos() { var numInfos = infos.count debugLog("\(numInfos) reflection info bundles.") precondition(numInfos >= 1) - sendBytes(from: &numInfos, count: sizeof(UInt.self)) + sendBytes(from: &numInfos, count: MemoryLayout.size) for info in infos { debugLog("Sending info for \(info.imageName)") for section in info { @@ -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(UnsafeRawPointer.self)) + let pointerSize = UInt8(MemoryLayout.size) sendValue(pointerSize) } @@ -357,11 +357,11 @@ public func reflect(object: AnyObject) { /// an Any existential. public func reflect(any: T) { let any: Any = any - let anyPointer = UnsafeMutablePointer.allocate(capacity: sizeof(Any.self)) + let anyPointer = UnsafeMutablePointer.allocate(capacity: MemoryLayout.size) anyPointer.initialize(to: any) let anyPointerValue = unsafeBitCast(anyPointer, to: UInt.self) reflect(instanceAddress: anyPointerValue, kind: .Existential) - anyPointer.deallocate(capacity: sizeof(Any.self)) + anyPointer.deallocate(capacity: MemoryLayout.size) } // Reflect an `Error`, a.k.a. an "error existential". @@ -421,7 +421,7 @@ struct ThickFunctionParts { /// @convention(thick) function value. public func reflect(function: () -> ()) { let fn = UnsafeMutablePointer.allocate( - capacity: sizeof(ThickFunction0.self)) + capacity: MemoryLayout.size) fn.initialize(to: ThickFunction0(function: function)) let parts = unsafeBitCast(fn, to: UnsafePointer.self) @@ -429,7 +429,7 @@ public func reflect(function: () -> ()) { reflect(instanceAddress: contextPointer, kind: .Object) - fn.deallocate(capacity: sizeof(ThickFunction0.self)) + fn.deallocate(capacity: MemoryLayout.size) } /// Reflect a closure context. The given function must be a Swift-native @@ -437,7 +437,7 @@ public func reflect(function: () -> ()) { public func reflect(function: (Int) -> ()) { let fn = UnsafeMutablePointer.allocate( - capacity: sizeof(ThickFunction1.self)) + capacity: MemoryLayout.size) fn.initialize(to: ThickFunction1(function: function)) let parts = unsafeBitCast(fn, to: UnsafePointer.self) @@ -445,14 +445,14 @@ public func reflect(function: (Int) -> ()) { reflect(instanceAddress: contextPointer, kind: .Object) - fn.deallocate(capacity: sizeof(ThickFunction1.self)) + fn.deallocate(capacity: MemoryLayout.size) } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: (Int, String) -> ()) { let fn = UnsafeMutablePointer.allocate( - capacity: sizeof(ThickFunction2.self)) + capacity: MemoryLayout.size) fn.initialize(to: ThickFunction2(function: function)) let parts = unsafeBitCast(fn, to: UnsafePointer.self) @@ -460,14 +460,14 @@ public func reflect(function: (Int, String) -> ()) { reflect(instanceAddress: contextPointer, kind: .Object) - fn.deallocate(capacity: sizeof(ThickFunction2.self)) + fn.deallocate(capacity: MemoryLayout.size) } /// Reflect a closure context. The given function must be a Swift-native /// @convention(thick) function value. public func reflect(function: (Int, String, AnyObject?) -> ()) { let fn = UnsafeMutablePointer.allocate( - capacity: sizeof(ThickFunction3.self)) + capacity: MemoryLayout.size) fn.initialize(to: ThickFunction3(function: function)) let parts = unsafeBitCast(fn, to: UnsafePointer.self) @@ -475,7 +475,7 @@ public func reflect(function: (Int, String, AnyObject?) -> ()) { reflect(instanceAddress: contextPointer, kind: .Object) - fn.deallocate(capacity: sizeof(ThickFunction3.self)) + fn.deallocate(capacity: MemoryLayout.size) } /// Call this function to indicate to the parent that there are diff --git a/stdlib/public/SDK/CoreAudio/CoreAudio.swift b/stdlib/public/SDK/CoreAudio/CoreAudio.swift index f6fa11e922239..b1d4c675636f6 100644 --- a/stdlib/public/SDK/CoreAudio/CoreAudio.swift +++ b/stdlib/public/SDK/CoreAudio/CoreAudio.swift @@ -16,7 +16,7 @@ extension UnsafeBufferPointer { /// Initialize an `UnsafeBufferPointer` from an `AudioBuffer`. /// Binds the the buffer's memory type to `Element`. public init(_ audioBuffer: AudioBuffer) { - let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self) + let count = Int(audioBuffer.mDataByteSize) / MemoryLayout.stride let elementPtr = audioBuffer.mData?.bindMemory( to: Element.self, capacity: count) self.init(start: elementPtr, count: count) @@ -27,7 +27,7 @@ extension UnsafeMutableBufferPointer { /// Initialize an `UnsafeMutableBufferPointer` from an /// `AudioBuffer`. public init(_ audioBuffer: AudioBuffer) { - let count = Int(audioBuffer.mDataByteSize) / strideof(Element.self) + let count = Int(audioBuffer.mDataByteSize) / MemoryLayout.stride let elementPtr = audioBuffer.mData?.bindMemory( to: Element.self, capacity: count) self.init(start: elementPtr, count: count) @@ -43,7 +43,7 @@ extension AudioBuffer { ) { self.mNumberChannels = UInt32(numberOfChannels) self.mData = UnsafeMutableRawPointer(typedBuffer.baseAddress) - self.mDataByteSize = UInt32(typedBuffer.count * strideof(Element.self)) + self.mDataByteSize = UInt32(typedBuffer.count * MemoryLayout.stride) } } @@ -53,8 +53,8 @@ extension AudioBufferList { public static func sizeInBytes(maximumBuffers: Int) -> Int { _precondition(maximumBuffers >= 1, "AudioBufferList should contain at least one AudioBuffer") - return sizeof(AudioBufferList.self) + - (maximumBuffers - 1) * strideof(AudioBuffer.self) + return MemoryLayout.size + + (maximumBuffers - 1) * MemoryLayout.stride } /// Allocate an `AudioBufferList` with a capacity for the specified number of @@ -72,7 +72,7 @@ extension AudioBufferList { "failed to allocate memory for an AudioBufferList") let listPtr = ablMemory!.bindMemory(to: AudioBufferList.self, capacity: 1) - (ablMemory! + strideof(AudioBufferList.self)).bindMemory( + (ablMemory! + MemoryLayout.stride).bindMemory( to: AudioBuffer.self, capacity: maximumBuffers) let abl = UnsafeMutableAudioBufferListPointer(listPtr) abl.count = maximumBuffers diff --git a/stdlib/public/SDK/Dispatch/Data.swift b/stdlib/public/SDK/Dispatch/Data.swift index 3557d3b15c0f5..fa6ce91f2da52 100644 --- a/stdlib/public/SDK/Dispatch/Data.swift +++ b/stdlib/public/SDK/Dispatch/Data.swift @@ -76,7 +76,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { var size = 0 let data = __dispatch_data_create_map(__wrapped, &ptr, &size) let contentPtr = ptr!.bindMemory( - to: ContentType.self, capacity: size / strideof(ContentType.self)) + to: ContentType.self, capacity: size / MemoryLayout.stride) defer { _fixLifetime(data) } return try body(contentPtr) } @@ -114,8 +114,8 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append(_ buffer : UnsafeBufferPointer) { - buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * strideof(SourceType.self)) { - self.append($0, count: buffer.count * sizeof(SourceType.self)) + buffer.baseAddress!.withMemoryRebound(to: UInt8.self, capacity: buffer.count * MemoryLayout.stride) { + self.append($0, count: buffer.count * MemoryLayout.stride) } } @@ -149,7 +149,7 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { /// Copy the contents of the data into a buffer. /// - /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `sizeof(DestinationType) * buffer.count` then the first N bytes will be copied into the buffer. + /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout.size * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. @@ -167,9 +167,9 @@ public struct DispatchData : RandomAccessCollection, _ObjectiveCBridgeable { precondition(r.endIndex >= 0) precondition(r.endIndex <= cnt, "The range is outside the bounds of the data") - copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * sizeof(DestinationType.self), r.count)) + copyRange = r.startIndex..<(r.startIndex + Swift.min(buffer.count * MemoryLayout.stride, r.count)) } else { - copyRange = 0...stride, cnt) } guard !copyRange.isEmpty else { return 0 } diff --git a/stdlib/public/SDK/Foundation/Data.swift b/stdlib/public/SDK/Foundation/Data.swift index 80ec49cb39ce7..a77841db3d0c5 100644 --- a/stdlib/public/SDK/Foundation/Data.swift +++ b/stdlib/public/SDK/Foundation/Data.swift @@ -137,14 +137,14 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init(buffer: UnsafeBufferPointer) { - _wrapped = _SwiftNSData(immutableObject: NSData(bytes: buffer.baseAddress, length: strideof(SourceType.self) * buffer.count)) + _wrapped = _SwiftNSData(immutableObject: NSData(bytes: buffer.baseAddress, length: MemoryLayout.stride * buffer.count)) } /// Initialize a `Data` with copied memory content. /// /// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`. public init(buffer: UnsafeMutableBufferPointer) { - _wrapped = _SwiftNSData(immutableObject: NSData(bytes: UnsafePointer(buffer.baseAddress), length: strideof(SourceType.self) * buffer.count)) + _wrapped = _SwiftNSData(immutableObject: NSData(bytes: UnsafePointer(buffer.baseAddress), length: MemoryLayout.stride * buffer.count)) } /// Initialize a `Data` with the contents of an Array. @@ -281,7 +281,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl public func withUnsafeBytes(_ body: @noescape (UnsafePointer) throws -> ResultType) rethrows -> ResultType { let bytes = _getUnsafeBytesPointer() defer { _fixLifetime(self)} - let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self)) + let contentPtr = bytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout.stride) return try body(contentPtr) } @@ -298,7 +298,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl public mutating func withUnsafeMutableBytes(_ body: @noescape (UnsafeMutablePointer) throws -> ResultType) rethrows -> ResultType { let mutableBytes = _getUnsafeMutableBytesPointer() defer { _fixLifetime(self)} - let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / strideof(ContentType.self)) + let contentPtr = mutableBytes.bindMemory(to: ContentType.self, capacity: count / MemoryLayout.stride) return try body(UnsafeMutablePointer(contentPtr)) } @@ -329,7 +329,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl /// Copy the contents of the data into a buffer. /// - /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `strideof(DestinationType) * buffer.count` then the first N bytes will be copied into the buffer. + /// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout.stride * buffer.count` then the first N bytes will be copied into the buffer. /// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called. /// - parameter buffer: A buffer to copy the data into. /// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied. @@ -347,9 +347,9 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl precondition(r.upperBound >= 0) precondition(r.upperBound <= cnt, "The range is outside the bounds of the data") - copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * strideof(DestinationType.self), r.count)) + copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout.stride, r.count)) } else { - copyRange = 0...stride, cnt) } guard !copyRange.isEmpty else { return 0 } @@ -458,7 +458,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl /// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`. public mutating func append(_ buffer : UnsafeBufferPointer) { _applyUnmanagedMutation { - $0.append(buffer.baseAddress!, length: buffer.count * strideof(SourceType.self)) + $0.append(buffer.baseAddress!, length: buffer.count * MemoryLayout.stride) } } @@ -502,7 +502,7 @@ public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessColl /// - parameter buffer: The replacement bytes. public mutating func replaceSubrange(_ subrange: Range, with buffer: UnsafeBufferPointer) { let nsRange = NSMakeRange(subrange.lowerBound, subrange.upperBound - subrange.lowerBound) - let bufferCount = buffer.count * strideof(SourceType.self) + let bufferCount = buffer.count * MemoryLayout.stride _applyUnmanagedMutation { $0.replaceBytes(in: nsRange, withBytes: buffer.baseAddress, length: bufferCount) diff --git a/stdlib/public/SDK/Foundation/DateInterval.swift b/stdlib/public/SDK/Foundation/DateInterval.swift index ec14353843fe2..90be751ba5936 100644 --- a/stdlib/public/SDK/Foundation/DateInterval.swift +++ b/stdlib/public/SDK/Foundation/DateInterval.swift @@ -157,7 +157,7 @@ public struct DateInterval : ReferenceConvertible, Comparable, Hashable { public var hashValue: Int { var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate)) return withUnsafeMutablePointer(to: &buf) { - return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer.self), CFIndex(sizeof(UInt.self) * 2))) + return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer.self), CFIndex(MemoryLayout.size * 2))) } } diff --git a/stdlib/public/SDK/Foundation/IndexPath.swift b/stdlib/public/SDK/Foundation/IndexPath.swift index a61ab67cff965..ec7507450cfa0 100644 --- a/stdlib/public/SDK/Foundation/IndexPath.swift +++ b/stdlib/public/SDK/Foundation/IndexPath.swift @@ -154,7 +154,7 @@ public struct IndexPath : ReferenceConvertible, Equatable, Hashable, MutableColl if count == 0 { _indexes = [] } else { - var ptr = malloc(count * sizeof(Element.self)) + var ptr = malloc(count * MemoryLayout.size) defer { free(ptr) } let elementPtr = ptr!.bindMemory(to: Element.self, capacity: count) diff --git a/stdlib/public/SDK/Foundation/UUID.swift b/stdlib/public/SDK/Foundation/UUID.swift index 63a109d440433..971d3b8ec7e4c 100644 --- a/stdlib/public/SDK/Foundation/UUID.swift +++ b/stdlib/public/SDK/Foundation/UUID.swift @@ -67,7 +67,7 @@ public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConv public var hashValue: Int { var localValue = uuid return withUnsafeMutablePointer(to: &localValue) { - return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer.self), CFIndex(sizeof(uuid_t.self)))) + return Int(bitPattern: CFHashBytes(unsafeBitCast($0, to: UnsafeMutablePointer.self), CFIndex(MemoryLayout.size))) } } diff --git a/stdlib/public/SDK/GLKit/GLKit.swift.gyb b/stdlib/public/SDK/GLKit/GLKit.swift.gyb index d5fbf9fe33729..c5962ead65bfe 100644 --- a/stdlib/public/SDK/GLKit/GLKit.swift.gyb +++ b/stdlib/public/SDK/GLKit/GLKit.swift.gyb @@ -35,7 +35,7 @@ vectorElementNames = [ public func _indexHomogeneousValue(_ aggregate: UnsafePointer, _ index: Int) -> T { return UnsafeRawPointer(aggregate).load( - fromByteOffset: index * strideof(T.self), as: T.self) + fromByteOffset: index * MemoryLayout.stride, as: T.self) } %{ diff --git a/stdlib/public/SDK/SceneKit/SceneKit.swift b/stdlib/public/SDK/SceneKit/SceneKit.swift index b2dca2f471c72..a626a3ff474ca 100644 --- a/stdlib/public/SDK/SceneKit/SceneKit.swift +++ b/stdlib/public/SDK/SceneKit/SceneKit.swift @@ -170,10 +170,10 @@ extension SCNGeometryElement { fatalError("Expected constant number of indices per primitive") } self.init( - data: Data(bytes: indices, count: indexCount * sizeof(IndexType.self)), + data: Data(bytes: indices, count: indexCount * MemoryLayout.stride), primitiveType: primitiveType, primitiveCount: primitiveCount, - bytesPerIndex: sizeof(IndexType.self)) + bytesPerIndex: MemoryLayout.stride) _fixLifetime(indices) } } diff --git a/stdlib/public/core/BridgeObjectiveC.swift b/stdlib/public/core/BridgeObjectiveC.swift index b292a0145c6e9..ff03fc3f01c52 100644 --- a/stdlib/public/core/BridgeObjectiveC.swift +++ b/stdlib/public/core/BridgeObjectiveC.swift @@ -546,8 +546,8 @@ internal struct _CocoaFastEnumerationStackBuf { _item14 = _item0 _item15 = _item0 - _sanityCheck(sizeofValue(self) >= - sizeof(Optional.self) * count) + _sanityCheck(MemoryLayout._ofInstance(self).size >= + MemoryLayout>.size * count) } } diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift index ad75068d2eb5e..7f32ec1a076ab 100644 --- a/stdlib/public/core/Builtin.swift +++ b/stdlib/public/core/Builtin.swift @@ -20,6 +20,7 @@ import SwiftShims /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(X.self)`, when `X` is a class type, is the /// same regardless of how many stored properties `X` has. +@available(*, deprecated, message: "use MemoryLayout.size instead.") @_transparent public func sizeof(_:T.Type) -> Int { return Int(Builtin.sizeof(T.self)) @@ -30,18 +31,21 @@ public func sizeof(_:T.Type) -> Int { /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(a)`, when `a` is a class instance, is the /// same regardless of how many stored properties `a` has. +@available(*, deprecated, message: "use MemoryLayout.size instead.") @_transparent public func sizeofValue(_:T) -> Int { return sizeof(T.self) } /// Returns the minimum memory alignment of `T`. +@available(*, deprecated, message: "use MemoryLayout.alignment instead.") @_transparent public func alignof(_:T.Type) -> Int { return Int(Builtin.alignof(T.self)) } /// Returns the minimum memory alignment of `T`. +@available(*, deprecated, message: "use MemoryLayout.alignment instead.") @_transparent public func alignofValue(_:T) -> Int { return alignof(T.self) @@ -49,6 +53,7 @@ public func alignofValue(_:T) -> Int { /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. +@available(*, deprecated, message: "use MemoryLayout.stride instead.") @_transparent public func strideof(_:T.Type) -> Int { return Int(Builtin.strideof_nonzero(T.self)) @@ -56,6 +61,7 @@ public func strideof(_:T.Type) -> Int { /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. +@available(*, deprecated, message: "use MemoryLayout.stride instead.") @_transparent public func strideofValue(_:T) -> Int { return strideof(T.self) @@ -100,7 +106,7 @@ internal func _roundUp( return UnsafeMutablePointer( bitPattern: _roundUpImpl( UInt(bitPattern: pointer), - toAlignment: alignof(DestinationType.self)) + toAlignment: MemoryLayout.alignment) ).unsafelyUnwrapped } @@ -119,7 +125,7 @@ func _canBeClass(_: T.Type) -> Int8 { /// @_transparent public func unsafeBitCast(_ x: T, to: U.Type) -> U { - _precondition(sizeof(T.self) == sizeof(U.self), + _precondition(MemoryLayout.size == MemoryLayout.size, "can't unsafeBitCast between types of different sizes") return Builtin.reinterpretCast(x) } @@ -249,8 +255,8 @@ public func unsafeDowncast(_ x: AnyObject, to: T.Type) -> T { public func _getUnsafePointerToStoredProperties(_ x: AnyObject) -> UnsafeMutableRawPointer { let storedPropertyOffset = _roundUp( - sizeof(_HeapObject.self), - toAlignment: alignof(Optional.self)) + MemoryLayout<_HeapObject>.size, + toAlignment: MemoryLayout>.alignment) return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) + storedPropertyOffset } diff --git a/stdlib/public/core/CMakeLists.txt b/stdlib/public/core/CMakeLists.txt index 7c883ad3ed306..c5a29fc16b2fd 100644 --- a/stdlib/public/core/CMakeLists.txt +++ b/stdlib/public/core/CMakeLists.txt @@ -77,6 +77,7 @@ set(SWIFTLIB_ESSENTIAL LifetimeManager.swift ManagedBuffer.swift Map.swift.gyb + MemoryLayout.swift Mirrors.swift.gyb Misc.swift MutableCollection.swift diff --git a/stdlib/public/core/Character.swift b/stdlib/public/core/Character.swift index 73afa5cc9f2a8..74fc63be01851 100644 --- a/stdlib/public/core/Character.swift +++ b/stdlib/public/core/Character.swift @@ -176,7 +176,7 @@ public struct Character : let (count, initialUTF8) = s._core._encodeSomeUTF8(from: 0) // Notice that the result of sizeof() is a small non-zero number and can't // overflow when multiplied by 8. - let bits = sizeofValue(initialUTF8) &* 8 &- 1 + let bits = MemoryLayout._ofInstance(initialUTF8).size &* 8 &- 1 if _fastPath( count == s._core.count && (initialUTF8 & (1 << numericCast(bits))) != 0) { _representation = .small(Builtin.trunc_Int64_Int63(initialUTF8._value)) diff --git a/stdlib/public/core/GroupInfo.json b/stdlib/public/core/GroupInfo.json index 127f2a335026a..5b8c398e90202 100644 --- a/stdlib/public/core/GroupInfo.json +++ b/stdlib/public/core/GroupInfo.json @@ -88,7 +88,8 @@ "BridgeStorage.swift", "Builtin.swift", "VarArgs.swift", - "CTypes.swift" + "CTypes.swift", + "MemoryLayout.swift" ], "Reflection": [ "Mirrors.swift", diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb index 5871b2ba3b295..3818421db7d25 100644 --- a/stdlib/public/core/HashedCollections.swift.gyb +++ b/stdlib/public/core/HashedCollections.swift.gyb @@ -280,14 +280,14 @@ internal struct _UnmanagedAnyObjectArray { internal subscript(i: Int) -> AnyObject { get { let unmanaged = value.load( - fromByteOffset: i * strideof(AnyObject.self), + fromByteOffset: i * MemoryLayout.stride, as: Unmanaged.self) return unmanaged.takeUnretainedValue() } nonmutating set(newValue) { let unmanaged = Unmanaged.passUnretained(newValue) value.storeBytes(of: unmanaged, - toByteOffset: i * strideof(AnyObject.self), + toByteOffset: i * MemoryLayout.stride, as: Unmanaged.self) } } @@ -2511,15 +2511,15 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : /// padding to align the start to word alignment. internal static func bytesForBitMap(capacity: Int) -> Int { let numWords = _UnsafeBitMap.sizeInWords(forSizeInBits: capacity) - return numWords * strideof(UInt.self) + alignof(UInt.self) + return numWords * MemoryLayout.stride + MemoryLayout.alignment } /// Returns the bytes necessary to store 'capacity' keys and padding to align /// the start to the alignment of the 'Key' type assuming a word aligned base /// address. internal static func bytesForKeys(capacity: Int) -> Int { - let padding = max(0, alignof(Key.self) - alignof(UInt.self)) - return strideof(Key.self) * capacity + padding + let padding = max(0, MemoryLayout.alignment - MemoryLayout.alignment) + return MemoryLayout.stride * capacity + padding } %if Self == 'Dictionary': @@ -2528,9 +2528,9 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : /// address aligned to the maximum of the alignment of the 'Key' type and the /// alignment of a word. internal static func bytesForValues(capacity: Int) -> Int { - let maxPrevAlignment = max(alignof(Key.self), alignof(UInt.self)) - let padding = max(0, alignof(Value.self) - maxPrevAlignment) - return strideof(Value.self) * capacity + padding + let maxPrevAlignment = max(MemoryLayout.alignment, MemoryLayout.alignment) + let padding = max(0, MemoryLayout.alignment - maxPrevAlignment) + return MemoryLayout.stride * capacity + padding } %end @@ -2582,7 +2582,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : let bitMapSizeInBytes = _unsafeMultiply( _UnsafeBitMap.sizeInWords(forSizeInBits: _body.capacity), - strideof(UInt.self)) + MemoryLayout.stride) let start = UnsafeMutableRawPointer(_initializedHashtableEntriesBitMapStorage) + bitMapSizeInBytes @@ -2592,7 +2592,7 @@ final internal class _Native${Self}StorageImpl<${TypeParameters}> : %if Self == 'Dictionary': // This API is unsafe and needs a `_fixLifetime` in the caller. internal var _values: UnsafeMutablePointer { - let keysSizeInBytes = _unsafeMultiply(_body.capacity, strideof(Key.self)) + let keysSizeInBytes = _unsafeMultiply(_body.capacity, MemoryLayout.stride) let start = UnsafeMutableRawPointer(_keys) + keysSizeInBytes return _roundUp(start, toAlignmentOf: Value.self) } diff --git a/stdlib/public/core/HeapBuffer.swift b/stdlib/public/core/HeapBuffer.swift index 5244a4b4275ea..5f1cfcea16e2d 100644 --- a/stdlib/public/core/HeapBuffer.swift +++ b/stdlib/public/core/HeapBuffer.swift @@ -72,21 +72,21 @@ struct _HeapBuffer : Equatable { internal static func _valueOffset() -> Int { return _roundUp( - sizeof(_HeapObject.self), - toAlignment: alignof(Value.self)) + MemoryLayout<_HeapObject>.size, + toAlignment: MemoryLayout.alignment) } internal static func _elementOffset() -> Int { return _roundUp( - _valueOffset() + sizeof(Value.self), - toAlignment: alignof(Element.self)) + _valueOffset() + MemoryLayout.size, + toAlignment: MemoryLayout.alignment) } internal static func _requiredAlignMask() -> Int { // We can't use max here because it can allocate an array. - let heapAlign = alignof(_HeapObject.self) &- 1 - let valueAlign = alignof(Value.self) &- 1 - let elementAlign = alignof(Element.self) &- 1 + let heapAlign = MemoryLayout<_HeapObject>.alignment &- 1 + let valueAlign = MemoryLayout.alignment &- 1 + let elementAlign = MemoryLayout.alignment &- 1 return (heapAlign < valueAlign ? (valueAlign < elementAlign ? elementAlign : valueAlign) : (heapAlign < elementAlign ? elementAlign : heapAlign)) @@ -123,7 +123,7 @@ struct _HeapBuffer : Equatable { /// Returns the actual number of `Elements` we can possibly store. internal func _capacity() -> Int { return (_allocatedSize() - _HeapBuffer._elementOffset()) - / strideof(Element.self) + / MemoryLayout.stride } internal init() { @@ -165,7 +165,7 @@ struct _HeapBuffer : Equatable { ) let totalSize = _HeapBuffer._elementOffset() + - capacity * strideof(Element.self) + capacity * MemoryLayout.stride let alignMask = _HeapBuffer._requiredAlignMask() let object: AnyObject = _swift_bufferAllocate( diff --git a/stdlib/public/core/ManagedBuffer.swift b/stdlib/public/core/ManagedBuffer.swift index 358d340221330..bbb1d4ab200e9 100644 --- a/stdlib/public/core/ManagedBuffer.swift +++ b/stdlib/public/core/ManagedBuffer.swift @@ -245,7 +245,7 @@ public struct ManagedBufferPointer : Equatable { /// idea to store this information in the "header" area when /// an instance is created. public var capacity: Int { - return (_capacityInBytes &- _My._elementOffset) / strideof(Element.self) + return (_capacityInBytes &- _My._elementOffset) / MemoryLayout.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored @@ -328,7 +328,7 @@ public struct ManagedBufferPointer : Equatable { "ManagedBufferPointer must have non-negative capacity") let totalSize = _My._elementOffset - + minimumCapacity * strideof(Element.self) + + minimumCapacity * MemoryLayout.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, @@ -352,11 +352,11 @@ public struct ManagedBufferPointer : Equatable { _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( - _class_getInstancePositiveExtentSize(bufferClass) == sizeof(_HeapObject.self) + _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( !creating && _class_getInstancePositiveExtentSize(bufferClass) - == _headerOffset + sizeof(Header.self)), + == _headerOffset + MemoryLayout
.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( @@ -369,11 +369,11 @@ public struct ManagedBufferPointer : Equatable { _ bufferClass: AnyClass, creating: Bool = false ) { _sanityCheck( - _class_getInstancePositiveExtentSize(bufferClass) == sizeof(_HeapObject.self) + _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( !creating && _class_getInstancePositiveExtentSize(bufferClass) - == _headerOffset + sizeof(Header.self)), + == _headerOffset + MemoryLayout
.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _sanityCheck( @@ -385,8 +385,8 @@ public struct ManagedBufferPointer : Equatable { /// The required alignment for allocations of this type, minus 1 internal static var _alignmentMask: Int { return max( - alignof(_HeapObject.self), - max(alignof(Header.self), alignof(Element.self))) &- 1 + MemoryLayout<_HeapObject>.alignment, + max(MemoryLayout
.alignment, MemoryLayout.alignment)) &- 1 } /// The actual number of bytes allocated for this object. @@ -403,8 +403,8 @@ public struct ManagedBufferPointer : Equatable { internal static var _headerOffset: Int { _onFastPath() return _roundUp( - sizeof(_HeapObject.self), - toAlignment: alignof(Header.self)) + MemoryLayout<_HeapObject>.size, + toAlignment: MemoryLayout
.alignment) } /// An **unmanaged** pointer to the storage for the `Header` @@ -429,8 +429,8 @@ public struct ManagedBufferPointer : Equatable { internal static var _elementOffset: Int { _onFastPath() return _roundUp( - _headerOffset + sizeof(Header.self), - toAlignment: alignof(Element.self)) + _headerOffset + MemoryLayout
.size, + toAlignment: MemoryLayout.alignment) } internal mutating func _isUniqueOrPinnedReference() -> Bool { diff --git a/stdlib/public/core/MemoryLayout.swift b/stdlib/public/core/MemoryLayout.swift new file mode 100644 index 0000000000000..a3cb8af54e845 --- /dev/null +++ b/stdlib/public/core/MemoryLayout.swift @@ -0,0 +1,52 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See http://swift.org/LICENSE.txt for license information +// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +/// Accesses the memory layout of `T` through its +/// `size`, `stride`, and `alignment` properties +public enum MemoryLayout { + + /// Returns the contiguous memory footprint of `T`. + /// + /// Does not include any dynamically-allocated or "remote" + /// storage. In particular, `MemoryLayout.size`, when + /// `T` is a class type, is the same regardless of how many + /// stored properties `T` has. + @_transparent + public static var size: Int { + return Int(Builtin.sizeof(T.self)) + } + + /// For instances of `T` in an `Array`, returns the number of + /// bytes from the start of one instance to the start of the + /// next. This is the same as the number of bytes moved when an + /// `UnsafePointer` is incremented. `T` may have a lower minimal + /// alignment that trades runtime performance for space + /// efficiency. The result is always positive. + @_transparent + public static var stride: Int { + return Int(Builtin.strideof_nonzero(T.self)) + } + + /// Returns the default memory alignment of `T`. + @_transparent + public static var alignment: Int { + return Int(Builtin.alignof(T.self)) + } +} + +extension MemoryLayout { + @_transparent + public // @testable + static func _ofInstance(_: @autoclosure () -> T) -> MemoryLayout.Type { + return MemoryLayout.self + } +} diff --git a/stdlib/public/core/Pointer.swift b/stdlib/public/core/Pointer.swift index 2c28762d2468a..44cabb17d482d 100644 --- a/stdlib/public/core/Pointer.swift +++ b/stdlib/public/core/Pointer.swift @@ -56,7 +56,7 @@ func _convertConstArrayToPointerArgument< if let addr = opaquePointer { validPointer = ToPointer(addr._rawValue) } else { - let lastAlignedValue = ~(alignof(FromElement.self) - 1) + let lastAlignedValue = ~(MemoryLayout.alignment - 1) let lastAlignedPointer = UnsafeRawPointer(bitPattern: lastAlignedValue)! validPointer = ToPointer(lastAlignedPointer._rawValue) } diff --git a/stdlib/public/core/Runtime.swift.gyb b/stdlib/public/core/Runtime.swift.gyb index 435d5b98cf807..ba46835631d6d 100644 --- a/stdlib/public/core/Runtime.swift.gyb +++ b/stdlib/public/core/Runtime.swift.gyb @@ -382,8 +382,8 @@ func _float${bits}ToString(_ value: Float${bits}, debug: Bool) -> String { } } - _sanityCheck(sizeof(_Buffer32.self) == 32) - _sanityCheck(sizeof(_Buffer72.self) == 72) + _sanityCheck(MemoryLayout<_Buffer32>.size == 32) + _sanityCheck(MemoryLayout<_Buffer72>.size == 72) var buffer = _Buffer32() return buffer.withBytes { (bufferPtr) in @@ -469,7 +469,7 @@ func _rawPointerToString(_ value: Builtin.RawPointer) -> String { radix: 16, uppercase: false ) - for _ in 0..<(2 * sizeof(UnsafeRawPointer.self) - result.utf16.count) { + for _ in 0..<(2 * MemoryLayout.size - result.utf16.count) { result = "0" + result } return "0x" + result diff --git a/stdlib/public/core/StringUTF8.swift b/stdlib/public/core/StringUTF8.swift index 8a9dd318a5f44..fa6faecc50524 100644 --- a/stdlib/public/core/StringUTF8.swift +++ b/stdlib/public/core/StringUTF8.swift @@ -38,7 +38,7 @@ extension _StringCore { if _fastPath(elementWidth == 1) { // How many UTF-16 code units might we use before we've filled up // our _UTF8Chunk with UTF-8 code units? - let utf16Count = Swift.min(sizeof(_UTF8Chunk.self), count - i) + let utf16Count = Swift.min(MemoryLayout<_UTF8Chunk>.size, count - i) var result: _UTF8Chunk = ~0 // Start with all bits set @@ -253,7 +253,7 @@ extension String { /// A Buffer value with the high byte set internal static var _bufferHiByte: Buffer { - return 0xFF << numericCast((sizeof(Buffer.self) &- 1) &* 8) + return 0xFF << numericCast((MemoryLayout.size &- 1) &* 8) } /// Consume a byte of the given buffer: shift out the low byte diff --git a/stdlib/public/core/SwiftNativeNSArray.swift b/stdlib/public/core/SwiftNativeNSArray.swift index 9ca385a1d90b2..4ca075906e328 100644 --- a/stdlib/public/core/SwiftNativeNSArray.swift +++ b/stdlib/public/core/SwiftNativeNSArray.swift @@ -87,7 +87,7 @@ extension _SwiftNativeNSArrayWithContiguousStorage : _NSArrayCore { // counting while correctly aliasing with all other pointer types. UnsafeMutableRawPointer(aBuffer).copyBytes( from: objects.baseAddress! + range.location, - count: range.length * strideof(AnyObject.self)) + count: range.length * MemoryLayout.stride) } } diff --git a/stdlib/public/core/Unicode.swift b/stdlib/public/core/Unicode.swift index 5fc1829030acc..a07d0ae667764 100644 --- a/stdlib/public/core/Unicode.swift +++ b/stdlib/public/core/Unicode.swift @@ -764,7 +764,7 @@ internal func _transcodeSomeUTF16AsUTF8( typealias _UTF8Chunk = _StringCore._UTF8Chunk let endIndex = input.endIndex - let utf8Max = sizeof(_UTF8Chunk.self) + let utf8Max = MemoryLayout<_UTF8Chunk>.size var result: _UTF8Chunk = 0 var utf8Count = 0 var nextIndex = startIndex @@ -839,7 +839,7 @@ internal func _transcodeSomeUTF16AsUTF8( nextIndex = input.index(nextIndex, offsetBy: utf16Length) } // FIXME: Annoying check, courtesy of - if utf8Count < sizeofValue(result) { + if utf8Count < MemoryLayout._ofInstance(result).size { result |= ~0 << numericCast(utf8Count * 8) } return (nextIndex, result) @@ -1021,11 +1021,11 @@ extension UTF16 { destination: UnsafeMutablePointer, count: Int ) { - if strideof(T.self) == strideof(U.self) { + if MemoryLayout.stride == MemoryLayout.stride { _memcpy( dest: UnsafeMutablePointer(destination), src: UnsafeMutablePointer(source), - size: UInt(count) * UInt(strideof(U.self))) + size: UInt(count) * UInt(MemoryLayout.stride)) } else { for i in 0.. /// contiguously in memory, presenting a collection interface to the /// underlying elements. /// -/// The pointer should be aligned to `alignof(Element.self)`. +/// The pointer should be aligned to `MemoryLayout.alignment`. public struct Unsafe${Mutable}BufferPointer : ${Mutable}Indexable, ${Mutable}Collection, RandomAccessCollection { diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb index a507bc58f7c8b..e4e7eaa459cbe 100644 --- a/stdlib/public/core/UnsafePointer.swift.gyb +++ b/stdlib/public/core/UnsafePointer.swift.gyb @@ -20,8 +20,8 @@ /// provides no automated memory management, and therefore must /// be handled with great care to ensure safety. /// -/// Instances must be aligned to `alignof(Pointee.self)`, i.e. -/// `(UnsafePointer(self) - nil) % alignof(Pointee.self) == 0` +/// Instances must be aligned to `MemoryLayout.alignment`, i.e. +/// `(UnsafePointer(self) - nil) % MemoryLayout.alignment == 0` /// /// The memory referenced by an instance can be in one of the following states: /// @@ -149,7 +149,7 @@ public struct ${Self} /// - Postcondition: The pointee is allocated, but not initialized. static public func allocate(capacity count: Int) -> UnsafeMutablePointer { - let size = strideof(Pointee.self) * count + let size = MemoryLayout.stride * count let rawPtr = Builtin.allocRaw(size._builtinWordValue, Builtin.alignof(Pointee.self)) Builtin.bindMemory(rawPtr, count._builtinWordValue, Pointee.self) @@ -163,7 +163,7 @@ public struct ${Self} /// /// - Postcondition: The memory has been deallocated. public func deallocate(capacity: Int) { - let size = strideof(Pointee.self) * capacity + let size = MemoryLayout.stride * capacity Builtin.deallocRaw( _rawValue, size._builtinWordValue, Builtin.alignof(Pointee.self)) } @@ -381,7 +381,7 @@ public struct ${Self} /// /// - Precondition: Type 'T' is layout compatible with type 'Pointee'. /// - /// - Precondition: The memory `self...stride` /// is bound to `Pointee`. public func withMemoryRebound(to: T.Type, capacity count: Int, _ body: @noescape (UnsafeMutablePointer) throws -> Result @@ -500,7 +500,7 @@ public func < (lhs: ${Self}, rhs: ${Self}) -> Bool { @_transparent public func + (lhs: ${Self}, rhs: Int) -> ${Self} { return ${Self}(Builtin.gep_Word( - lhs._rawValue, (rhs &* strideof(Pointee.self))._builtinWordValue)) + lhs._rawValue, (rhs &* MemoryLayout.stride)._builtinWordValue)) } @_transparent @@ -519,7 +519,7 @@ public func - (lhs: ${Self}, rhs: ${Self}) -> Int { return Int(Builtin.sub_Word(Builtin.ptrtoint_Word(lhs._rawValue), Builtin.ptrtoint_Word(rhs._rawValue))) - / strideof(Pointee.self) + / MemoryLayout.stride } @_transparent diff --git a/stdlib/public/core/UnsafeRawPointer.swift.gyb b/stdlib/public/core/UnsafeRawPointer.swift.gyb index 6da5250352d08..a35effd374081 100644 --- a/stdlib/public/core/UnsafeRawPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawPointer.swift.gyb @@ -168,7 +168,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// - Precondition: The memory is uninitialized. /// /// - Postcondition: The memory is bound to 'T' starting at `self` continuing - /// through `self` + `count` * `strideof(T.self)` + /// through `self` + `count` * `MemoryLayout.stride` /// /// - Warning: Binding memory to a type is potentially undefined if the /// memory is ever accessed as an unrelated type. @@ -225,10 +225,10 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { "UnsafeMutableRawPointer.initializeMemory: negative count") Builtin.bindMemory(_rawValue, count._builtinWordValue, type) - var nextPtr = self + index &* strideof(T.self) + var nextPtr = self + index &* MemoryLayout.stride for _ in 0...stride } return UnsafeMutablePointer(_rawValue) } @@ -242,20 +242,20 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// - Precondition: `count >= 0` /// /// - Precondition: The memory regions `source...stride` do not overlap. /// - /// - Precondition: The memory at `self...stride` /// is uninitialized, and the `T` values at `source...stride` /// is bound to type `T`. /// /// - Postcondition: The `T` values at `self...stride` and `source..( as type: T.Type, from source: UnsafePointer, count: Int @@ -264,7 +264,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { count >= 0, "UnsafeMutableRawPointer.initializeMemory with negative count") _debugPrecondition( - (UnsafeRawPointer(self + count * strideof(T.self)) + (UnsafeRawPointer(self + count * MemoryLayout.stride) <= UnsafeRawPointer(source)) || UnsafeRawPointer(source + count) <= UnsafeRawPointer(self), "UnsafeMutableRawPointer.initializeMemory overlapping range") @@ -285,13 +285,13 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// Returns an `UnsafeMutablePointer` this memory. /// /// - Precondition: The memory at `self...stride` is uninitialized. /// /// - Postcondition: The memory at `self...stride` is bound to type `T`. /// /// - Postcondition: The `T` values at `self...stride` are initialized. /// /// TODO: Optimize where `C` is a `ContiguousArrayBuffer`. @discardableResult @@ -314,14 +314,14 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// - Precondition: `count >= 0` /// /// - Precondition: The memory at `self...stride` is uninitialized and the `T` values at /// `source...stride` is bound to type `T`. /// /// - Postcondition: The `T` values at `self...stride` are initialized and the memory at /// `source..( @@ -368,7 +368,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// such that `T` is layout compatible with `U`. public func load(fromByteOffset offset: Int = 0, as type: T.Type) -> T { _debugPrecondition(0 == (UInt(bitPattern: self + offset) - & (UInt(alignof(T.self)) - 1)), + & (UInt(MemoryLayout.alignment) - 1)), "load from misaligned raw pointer") return Builtin.load((self + offset)._rawValue) @@ -409,7 +409,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { of value: T, toByteOffset offset: Int = 0, as: T.Type ) { _debugPrecondition(0 == (UInt(bitPattern: self + offset) - & (UInt(alignof(T.self)) - 1)), + & (UInt(MemoryLayout.alignment) - 1)), "storeBytes to misaligned raw pointer") var temp = value @@ -417,7 +417,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { let rawSrc = UnsafeMutableRawPointer(source)._rawValue // FIXME: to be replaced by _memcpy when conversions are implemented. Builtin.int_memcpy_RawPointer_RawPointer_Int64( - (self + offset)._rawValue, rawSrc, UInt64(sizeof(T.self))._value, + (self + offset)._rawValue, rawSrc, UInt64(MemoryLayout.size)._value, /*alignment:*/ Int32(0)._value, /*volatile:*/ false._value) } @@ -433,7 +433,7 @@ public struct Unsafe${Mutable}RawPointer : Strideable, Hashable, _Pointer { /// - Precondition: If the memory at `self...stride`. /// /// - Postcondition: The memory at `self.. CVaListPointer { public func _encodeBitsAsWords(_ x: T) -> [Int] { let result = [Int]( repeating: 0, - count: (sizeof(T.self) + sizeof(Int.self) - 1) / sizeof(Int.self)) + count: (MemoryLayout.size + MemoryLayout.size - 1) / MemoryLayout.size) _sanityCheck(result.count > 0) var tmp = x // FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy. _memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!), src: UnsafeMutablePointer(Builtin.addressof(&tmp)), - size: UInt(sizeof(T.self))) + size: UInt(MemoryLayout.size)) return result } @@ -144,7 +144,7 @@ extension Int64 : CVarArg, _CVarArgAligned { /// the value returned by `_cVarArgEncoding`. public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures - return alignofValue(self) + return MemoryLayout._ofInstance(self).alignment } } @@ -192,7 +192,7 @@ extension UInt64 : CVarArg, _CVarArgAligned { /// the value returned by `_cVarArgEncoding`. public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures - return alignofValue(self) + return MemoryLayout._ofInstance(self).alignment } } @@ -265,7 +265,7 @@ extension Float : _CVarArgPassedAsDouble, _CVarArgAligned { /// the value returned by `_cVarArgEncoding`. public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures - return alignofValue(Double(self)) + return MemoryLayout._ofInstance(Double(self)).alignment } } @@ -280,7 +280,7 @@ extension Double : _CVarArgPassedAsDouble, _CVarArgAligned { /// the value returned by `_cVarArgEncoding`. public var _cVarArgAlignment: Int { // FIXME: alignof differs from the ABI alignment on some architectures - return alignofValue(self) + return MemoryLayout._ofInstance(self).alignment } } @@ -298,7 +298,7 @@ final internal class _VaListBuilder { // differs from ABI alignment on some architectures. #if arch(arm) && !os(iOS) if let arg = arg as? _CVarArgAligned { - let alignmentInWords = arg._cVarArgAlignment / sizeof(Int.self) + let alignmentInWords = arg._cVarArgAlignment / MemoryLayout.size let misalignmentInWords = count % alignmentInWords if misalignmentInWords != 0 { let paddingInWords = alignmentInWords - misalignmentInWords @@ -349,7 +349,7 @@ final internal class _VaListBuilder { } func rawSizeAndAlignment(_ wordCount: Int) -> (Builtin.Word, Builtin.Word) { - return ((wordCount * strideof(Int.self))._builtinWordValue, + return ((wordCount * MemoryLayout.stride)._builtinWordValue, requiredAlignmentInBytes._builtinWordValue) } @@ -374,7 +374,7 @@ final internal class _VaListBuilder { } // FIXME: alignof differs from the ABI alignment on some architectures - let requiredAlignmentInBytes = alignof(Double.self) + let requiredAlignmentInBytes = MemoryLayout.alignment var count = 0 var allocated = 0 var storage: UnsafeMutablePointer? = nil @@ -390,7 +390,7 @@ final internal class _VaListBuilder { struct Header { var gp_offset = CUnsignedInt(0) - var fp_offset = CUnsignedInt(_x86_64CountGPRegisters * strideof(Int.self)) + var fp_offset = CUnsignedInt(_x86_64CountGPRegisters * MemoryLayout.stride) var overflow_arg_area: UnsafeMutablePointer? = nil var reg_save_area: UnsafeMutablePointer? = nil } diff --git a/test/1_stdlib/Character.swift b/test/1_stdlib/Character.swift index e61cf9e66bfac..c408c60a73c08 100644 --- a/test/1_stdlib/Character.swift +++ b/test/1_stdlib/Character.swift @@ -136,13 +136,13 @@ CharacterTests.test("literal") { CharacterTests.test("sizeof") { // FIXME: should be 8. - // sizeof(Character.self) is 9, should be 8 + // MemoryLayout.size is 9, should be 8 - let size1 = sizeof(Character.self) + let size1 = MemoryLayout.size expectTrue(size1 == 8 || size1 == 9) var a: Character = "a" - let size2 = sizeofValue(a) + let size2 = MemoryLayout._ofInstance(a).size expectTrue(size2 == 8 || size2 == 9) expectEqual(size1, size2) diff --git a/test/1_stdlib/Runtime.swift.gyb b/test/1_stdlib/Runtime.swift.gyb index 71a6c3b964a99..cde7a0fbb9b10 100644 --- a/test/1_stdlib/Runtime.swift.gyb +++ b/test/1_stdlib/Runtime.swift.gyb @@ -1483,9 +1483,9 @@ func computeCountLeadingZeroes(_ x: Int64) -> Int64 { BitTwiddlingTestSuite.test("_pointerSize") { #if arch(i386) || arch(arm) - expectEqual(4, sizeof(Optional.self)) + expectEqual(4, MemoryLayout>.size) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) - expectEqual(8, sizeof(Optional.self)) + expectEqual(8, MemoryLayout>.size) #else fatalError("implement") #endif diff --git a/test/1_stdlib/TestData.swift b/test/1_stdlib/TestData.swift index 5bf53f0982a26..d3aa71b9f07c8 100644 --- a/test/1_stdlib/TestData.swift +++ b/test/1_stdlib/TestData.swift @@ -458,19 +458,19 @@ class TestData : TestDataSuper { func testCopyBytes() { let c = 10 - let underlyingBuffer = malloc(c * strideof(UInt16.self))! + let underlyingBuffer = malloc(c * MemoryLayout.stride)! let u16Ptr = underlyingBuffer.bindMemory(to: UInt16.self, capacity: c) let buffer = UnsafeMutableBufferPointer(start: u16Ptr, count: c) buffer[0] = 0 buffer[1] = 0 - var data = Data(capacity: c * strideof(UInt16.self)) - data.resetBytes(in: 0...stride) + data.resetBytes(in: 0...stride) data[0] = 0xFF data[1] = 0xFF let copiedCount = data.copyBytes(to: buffer) - expectEqual(copiedCount, c * strideof(UInt16.self)) + expectEqual(copiedCount, c * MemoryLayout.stride) expectEqual(buffer[0], 0xFFFF) free(underlyingBuffer) @@ -481,7 +481,7 @@ class TestData : TestDataSuper { var data = a.withUnsafeBufferPointer { return Data(buffer: $0) } - let expectedSize = strideof(UInt8.self) * a.count + let expectedSize = MemoryLayout.stride * a.count expectEqual(expectedSize, data.count) let underlyingBuffer = unsafeBitCast(malloc(expectedSize - 1)!, to: UnsafeMutablePointer.self) @@ -505,7 +505,7 @@ class TestData : TestDataSuper { var data = a.withUnsafeBufferPointer { return Data(buffer: $0) } - let expectedSize = strideof(Int32.self) * a.count + let expectedSize = MemoryLayout.stride * a.count expectEqual(expectedSize, data.count) let underlyingBuffer = unsafeBitCast(malloc(expectedSize + 1)!, to: UnsafeMutablePointer.self) @@ -700,14 +700,14 @@ class TestData : TestDataSuper { return Data(buffer: $0) } - var expectedSize = strideof(Int32.self) * a.count + var expectedSize = MemoryLayout.stride * a.count expectEqual(expectedSize, data.count) [false, true].withUnsafeBufferPointer { data.append($0) } - expectedSize += strideof(Bool.self) * 2 + expectedSize += MemoryLayout.stride * 2 expectEqual(expectedSize, data.count) let underlyingBuffer = unsafeBitCast(malloc(expectedSize)!, to: UnsafeMutablePointer.self) @@ -810,7 +810,7 @@ class TestData : TestDataSuper { return Data(buffer: $0) } - expectEqual(data.count, strideof(MyStruct.self) * 3) + expectEqual(data.count, MemoryLayout.stride * 3) // append @@ -818,43 +818,43 @@ class TestData : TestDataSuper { data.append($0) } - expectEqual(data.count, strideof(MyStruct.self) * 6) + expectEqual(data.count, MemoryLayout.stride * 6) // copyBytes do { // equal size - let underlyingBuffer = malloc(6 * strideof(MyStruct.self))! + let underlyingBuffer = malloc(6 * MemoryLayout.stride)! defer { free(underlyingBuffer) } let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6) let buffer = UnsafeMutableBufferPointer(start: ptr, count: 6) let byteCount = data.copyBytes(to: buffer) - expectEqual(6 * strideof(MyStruct.self), byteCount) + expectEqual(6 * MemoryLayout.stride, byteCount) } do { // undersized - let underlyingBuffer = malloc(3 * strideof(MyStruct.self))! + let underlyingBuffer = malloc(3 * MemoryLayout.stride)! defer { free(underlyingBuffer) } let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 3) let buffer = UnsafeMutableBufferPointer(start: ptr, count: 3) let byteCount = data.copyBytes(to: buffer) - expectEqual(3 * strideof(MyStruct.self), byteCount) + expectEqual(3 * MemoryLayout.stride, byteCount) } do { // oversized - let underlyingBuffer = malloc(12 * strideof(MyStruct.self))! + let underlyingBuffer = malloc(12 * MemoryLayout.stride)! defer { free(underlyingBuffer) } let ptr = underlyingBuffer.bindMemory(to: MyStruct.self, capacity: 6) let buffer = UnsafeMutableBufferPointer(start: ptr, count: 6) let byteCount = data.copyBytes(to: buffer) - expectEqual(6 * strideof(MyStruct.self), byteCount) + expectEqual(6 * MemoryLayout.stride, byteCount) } } diff --git a/test/1_stdlib/UnsafeRawPointer.swift b/test/1_stdlib/UnsafeRawPointer.swift index 9ee370229b9fb..d2b33f0c03aff 100644 --- a/test/1_stdlib/UnsafeRawPointer.swift +++ b/test/1_stdlib/UnsafeRawPointer.swift @@ -16,11 +16,11 @@ class Missile { UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory") { Missile.missilesLaunched = 0 do { - let sizeInBytes = 3 * strideof(Missile.self) + let sizeInBytes = 3 * MemoryLayout.stride var p1 = UnsafeMutableRawPointer.allocate( - bytes: sizeInBytes, alignedTo: alignof(Missile.self)) + bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) defer { - p1.deallocate(bytes: sizeInBytes, alignedTo: alignof(Missile.self)) + p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) } var ptrM = p1.initializeMemory(as: Missile.self, to: Missile(1)) p1.initializeMemory(as: Missile.self, at: 1, count: 2, to: Missile(2)) @@ -29,9 +29,9 @@ UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory") { expectEqual(2, ptrM[2].number) var p2 = UnsafeMutableRawPointer.allocate( - bytes: sizeInBytes, alignedTo: alignof(Missile.self)) + bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) defer { - p2.deallocate(bytes: sizeInBytes, alignedTo: alignof(Missile.self)) + p2.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) } let ptrM2 = p2.moveInitializeMemory(as: Missile.self, from: ptrM, count: 3) defer { @@ -55,11 +55,11 @@ UnsafeMutableRawPointerExtraTestSuite.test("initializeMemory") { } UnsafeMutableRawPointerExtraTestSuite.test("bindMemory") { - let sizeInBytes = 3 * strideof(Int.self) + let sizeInBytes = 3 * MemoryLayout.stride var p1 = UnsafeMutableRawPointer.allocate( - bytes: sizeInBytes, alignedTo: alignof(Int.self)) + bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) defer { - p1.deallocate(bytes: sizeInBytes, alignedTo: alignof(Int.self)) + p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) } let ptrI = p1.bindMemory(to: Int.self, capacity: 3) ptrI.initialize(from: 1...3) @@ -72,33 +72,33 @@ UnsafeMutableRawPointerExtraTestSuite.test("bindMemory") { } UnsafeMutableRawPointerExtraTestSuite.test("load/store") { - let sizeInBytes = 3 * strideof(Int.self) + let sizeInBytes = 3 * MemoryLayout.stride var p1 = UnsafeMutableRawPointer.allocate( - bytes: sizeInBytes, alignedTo: alignof(Int.self)) + bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) defer { - p1.deallocate(bytes: sizeInBytes, alignedTo: alignof(Int.self)) + p1.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) } let ptrI = p1.initializeMemory(as: Int.self, from: 1...3) defer { ptrI.deinitialize(count: 3) } expectEqual(1, p1.load(as: Int.self)) - expectEqual(2, p1.load(fromByteOffset: strideof(Int.self), as: Int.self)) - expectEqual(3, p1.load(fromByteOffset: 2*strideof(Int.self), as: Int.self)) + expectEqual(2, p1.load(fromByteOffset: MemoryLayout.stride, as: Int.self)) + expectEqual(3, p1.load(fromByteOffset: 2*MemoryLayout.stride, as: Int.self)) p1.storeBytes(of: 4, as: Int.self) - p1.storeBytes(of: 5, toByteOffset: strideof(Int.self), as: Int.self) - p1.storeBytes(of: 6, toByteOffset: 2 * strideof(Int.self), as: Int.self) + p1.storeBytes(of: 5, toByteOffset: MemoryLayout.stride, as: Int.self) + p1.storeBytes(of: 6, toByteOffset: 2 * MemoryLayout.stride, as: Int.self) expectEqual(4, p1.load(as: Int.self)) - expectEqual(5, p1.load(fromByteOffset: strideof(Int.self), as: Int.self)) - expectEqual(6, p1.load(fromByteOffset: 2 * strideof(Int.self), as: Int.self)) + expectEqual(5, p1.load(fromByteOffset: MemoryLayout.stride, as: Int.self)) + expectEqual(6, p1.load(fromByteOffset: 2 * MemoryLayout.stride, as: Int.self)) } UnsafeMutableRawPointerExtraTestSuite.test("copyBytes") { - let sizeInBytes = 4 * strideof(Int.self) + let sizeInBytes = 4 * MemoryLayout.stride var rawPtr = UnsafeMutableRawPointer.allocate( - bytes: sizeInBytes, alignedTo: alignof(Int.self)) + bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) defer { - rawPtr.deallocate(bytes: sizeInBytes, alignedTo: alignof(Int.self)) + rawPtr.deallocate(bytes: sizeInBytes, alignedTo: MemoryLayout.alignment) } let ptrI = rawPtr.initializeMemory(as: Int.self, count: 4, to: 42) defer { @@ -108,8 +108,8 @@ UnsafeMutableRawPointerExtraTestSuite.test("copyBytes") { // Right overlap ptrI[0] = 1 ptrI[1] = 2 - (rawPtr + strideof(Int.self)).copyBytes( - from: roPtr, count: 2 * strideof(Int.self)) + (rawPtr + MemoryLayout.stride).copyBytes( + from: roPtr, count: 2 * MemoryLayout.stride) expectEqual(1, ptrI[1]) expectEqual(2, ptrI[2]) @@ -117,7 +117,7 @@ UnsafeMutableRawPointerExtraTestSuite.test("copyBytes") { ptrI[1] = 2 ptrI[2] = 3 rawPtr.copyBytes( - from: roPtr + strideof(Int.self), count: 2 * strideof(Int.self)) + from: roPtr + MemoryLayout.stride, count: 2 * MemoryLayout.stride) expectEqual(2, ptrI[0]) expectEqual(3, ptrI[1]) @@ -125,15 +125,15 @@ UnsafeMutableRawPointerExtraTestSuite.test("copyBytes") { ptrI[2] = 2 ptrI[3] = 3 rawPtr.copyBytes( - from: roPtr + 2 * strideof(Int.self), count: 2 * strideof(Int.self)) + from: roPtr + 2 * MemoryLayout.stride, count: 2 * MemoryLayout.stride) expectEqual(2, ptrI[0]) expectEqual(3, ptrI[1]) // Backwards ptrI[0] = 0 ptrI[1] = 1 - (rawPtr + 2 * strideof(Int.self)).copyBytes( - from: roPtr, count: 2 * strideof(Int.self)) + (rawPtr + 2 * MemoryLayout.stride).copyBytes( + from: roPtr, count: 2 * MemoryLayout.stride) expectEqual(0, ptrI[2]) expectEqual(1, ptrI[3]) } diff --git a/test/1_stdlib/simd.swift.gyb b/test/1_stdlib/simd.swift.gyb index b13f288308dad..d888adaeca914 100644 --- a/test/1_stdlib/simd.swift.gyb +++ b/test/1_stdlib/simd.swift.gyb @@ -59,35 +59,35 @@ var simdTestSuite = TestSuite("simd") simdTestSuite.test("sizes") { // C interop requires that vector be the right size. - expectEqual(8, sizeof(float2.self)) - expectEqual(16, sizeof(float3.self)) - expectEqual(16, sizeof(float4.self)) - expectEqual(8, sizeof(int2.self)) - expectEqual(16, sizeof(int3.self)) - expectEqual(16, sizeof(int4.self)) - expectEqual(16, sizeof(double2.self)) - expectEqual(32, sizeof(double3.self)) - expectEqual(32, sizeof(double4.self)) - - expectEqual(16, sizeof(float2x2.self)) - expectEqual(32, sizeof(float2x3.self)) - expectEqual(32, sizeof(float2x4.self)) - expectEqual(24, sizeof(float3x2.self)) - expectEqual(48, sizeof(float3x3.self)) - expectEqual(48, sizeof(float3x4.self)) - expectEqual(32, sizeof(float4x2.self)) - expectEqual(64, sizeof(float4x3.self)) - expectEqual(64, sizeof(float4x4.self)) - - expectEqual(32, sizeof(double2x2.self)) - expectEqual(64, sizeof(double2x3.self)) - expectEqual(64, sizeof(double2x4.self)) - expectEqual(48, sizeof(double3x2.self)) - expectEqual(96, sizeof(double3x3.self)) - expectEqual(96, sizeof(double3x4.self)) - expectEqual(64, sizeof(double4x2.self)) - expectEqual(128, sizeof(double4x3.self)) - expectEqual(128, sizeof(double4x4.self)) + expectEqual(8, MemoryLayout.size) + expectEqual(16, MemoryLayout.size) + expectEqual(16, MemoryLayout.size) + expectEqual(8, MemoryLayout.size) + expectEqual(16, MemoryLayout.size) + expectEqual(16, MemoryLayout.size) + expectEqual(16, MemoryLayout.size) + expectEqual(32, MemoryLayout.size) + expectEqual(32, MemoryLayout.size) + + expectEqual(16, MemoryLayout.size) + expectEqual(32, MemoryLayout.size) + expectEqual(32, MemoryLayout.size) + expectEqual(24, MemoryLayout.size) + expectEqual(48, MemoryLayout.size) + expectEqual(48, MemoryLayout.size) + expectEqual(32, MemoryLayout.size) + expectEqual(64, MemoryLayout.size) + expectEqual(64, MemoryLayout.size) + + expectEqual(32, MemoryLayout.size) + expectEqual(64, MemoryLayout.size) + expectEqual(64, MemoryLayout.size) + expectEqual(48, MemoryLayout.size) + expectEqual(96, MemoryLayout.size) + expectEqual(96, MemoryLayout.size) + expectEqual(64, MemoryLayout.size) + expectEqual(128, MemoryLayout.size) + expectEqual(128, MemoryLayout.size) } simdTestSuite.test("vector init") { diff --git a/test/Constraints/diagnostics.swift b/test/Constraints/diagnostics.swift index 0ba8807ca0e49..56d947328371c 100644 --- a/test/Constraints/diagnostics.swift +++ b/test/Constraints/diagnostics.swift @@ -834,7 +834,7 @@ func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {} func read() -> T? { var buffer : T let n = withUnsafePointer(to: &buffer) { (p) in - read2(UnsafePointer(p), maxLength: sizeof(T)) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}} + read2(UnsafePointer(p), maxLength: MemoryLayout.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}} } } diff --git a/test/Interpreter/SDK/Accelerate.swift b/test/Interpreter/SDK/Accelerate.swift index 8e5351b58ad22..416e9d5a298f3 100644 --- a/test/Interpreter/SDK/Accelerate.swift +++ b/test/Interpreter/SDK/Accelerate.swift @@ -10,7 +10,7 @@ extension vU1024: ExpressibleByIntegerLiteral, CustomStringConvertible, Equatabl public init(integerLiteral: Int) { var integerLiteral = integerLiteral self.init() - memcpy(&self, &integerLiteral, sizeof(Int.self)) + memcpy(&self, &integerLiteral, MemoryLayout.size) } init(_ int: Int) { @@ -37,7 +37,7 @@ extension Int { var u1024 = u1024 // NB: Doesn't overflow check self.init() - memcpy(&self, &u1024, sizeof(Int.self)) + memcpy(&self, &u1024, MemoryLayout.size) } } @@ -61,7 +61,7 @@ func quorem(_ x: vU1024, _ y: vU1024) -> (vU1024, vU1024) { public func ==(x: vU1024, y: vU1024) -> Bool { var x = x var y = y - return memcmp(&x, &y, sizeof(vU1024.self)) == 0 + return memcmp(&x, &y, MemoryLayout.size) == 0 } func factorial(_ x: Int) -> vU1024 { diff --git a/test/Interpreter/SDK/c_pointers.swift b/test/Interpreter/SDK/c_pointers.swift index 90a974275af31..3e577b35d54f1 100644 --- a/test/Interpreter/SDK/c_pointers.swift +++ b/test/Interpreter/SDK/c_pointers.swift @@ -44,10 +44,10 @@ print("<\(r) \(g) \(b) \(a)>") // CHECK-NEXT: <1.0 0.0 0.0 1.0> // FIXME: Array type annotation should not be required let data = NSData(bytes: [1.5, 2.25, 3.125] as [Double], - length: sizeof(Double.self) * 3) + length: MemoryLayout.size * 3) var fromData = [0.25, 0.25, 0.25] let notFromData = fromData -data.getBytes(&fromData, length: sizeof(Double.self) * 3) +data.getBytes(&fromData, length: MemoryLayout.size * 3) // CHECK-LABEL: Data is: print("Data is:") @@ -127,7 +127,7 @@ puts(s) // var unsorted = [3, 14, 15, 9, 2, 6, 5] -qsort(&unsorted, unsorted.count, sizeofValue(unsorted[0])) { a, b in +qsort(&unsorted, unsorted.count, MemoryLayout._ofInstance(unsorted[0]).size) { a, b in return Int32(a!.load(as: Int.self) - b!.load(as: Int.self)) } // CHECK-NEXT: [2, 3, 5, 6, 9, 14, 15] diff --git a/test/Interpreter/SDK/objc_cast.swift b/test/Interpreter/SDK/objc_cast.swift index 78d0bb981c04e..1e5f0fb2b4bd4 100644 --- a/test/Interpreter/SDK/objc_cast.swift +++ b/test/Interpreter/SDK/objc_cast.swift @@ -429,7 +429,7 @@ if let strArr = objImplicitOpt as? [String] { // CHECK: Numbers-as-doubles cast produces [3.9375, 2.71828, 0.0] obj = ([3.9375, 2.71828, 0] as [Double]) as AnyObject if let doubleArr = obj as? [Double] { - print(sizeof(Double.self)) + print(MemoryLayout.size) print("Numbers-as-doubles cast produces \(doubleArr)") } else { print("Numbers-as-doubles failed") @@ -437,7 +437,7 @@ if let doubleArr = obj as? [Double] { // CHECK: Numbers-as-floats cast produces [3.9375, 2.71828{{.*}}, 0.0] if let floatArr = obj as? [Float] { - print(sizeof(Float.self)) + print(MemoryLayout.size) print("Numbers-as-floats cast produces \(floatArr)") } else { print("Numbers-as-floats failed") diff --git a/test/Interpreter/builtin_bridge_object.swift b/test/Interpreter/builtin_bridge_object.swift index 427c90c51e2af..a993b02c4bcf6 100644 --- a/test/Interpreter/builtin_bridge_object.swift +++ b/test/Interpreter/builtin_bridge_object.swift @@ -179,8 +179,8 @@ func hitOptionalSpecifically(_ x: Builtin.BridgeObject?) { if true { // CHECK-NEXT: true - print(sizeof(Optional.self) - == sizeof(Builtin.BridgeObject.self)) + print(MemoryLayout>.size + == MemoryLayout.size) var bo: Builtin.BridgeObject? = nil diff --git a/test/Interpreter/enum.swift b/test/Interpreter/enum.swift index 67375a41103ea..8c511dc240142 100644 --- a/test/Interpreter/enum.swift +++ b/test/Interpreter/enum.swift @@ -440,7 +440,7 @@ struct OptionalTuple { } } func test_optional_generic_tuple(_ a: OptionalTuple) -> T { - print("optional pair is same size as pair: \(sizeofValue(a) == sizeof(T)*2)") + print("optional pair is same size as pair: \(MemoryLayout._ofInstance(a).size == MemoryLayout.size*2)") return a.value!.0 } print("Int result: \(test_optional_generic_tuple(OptionalTuple((5, 6))))") diff --git a/test/Interpreter/layout_reabstraction.swift b/test/Interpreter/layout_reabstraction.swift index 2b8cebab890a0..1772a0aaa8e2a 100644 --- a/test/Interpreter/layout_reabstraction.swift +++ b/test/Interpreter/layout_reabstraction.swift @@ -41,7 +41,7 @@ printMetatypeConditional(any, Q.self) // of the size of a type. @inline(never) func unspecializedSizeOf(_ t: T.Type) -> Int { - return sizeof(t) + return MemoryLayout.size } struct ContainsTrivialMetatype { @@ -54,12 +54,12 @@ struct ContainsTupleOfTrivialMetatype { } // CHECK-NEXT: 8 -print(sizeof(ContainsTrivialMetatype.self)) +print(MemoryLayout>.size) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTrivialMetatype.self)) // CHECK-NEXT: 8 -print(sizeof(ContainsTupleOfTrivialMetatype.self)) +print(MemoryLayout>.size) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTupleOfTrivialMetatype.self)) @@ -72,13 +72,13 @@ struct ContainsTupleOfFunctions { } // CHECK-NEXT: 2 -print(sizeof(ContainsTupleOfFunctions<()>.self) / sizeof(Int.self)) +print(MemoryLayout>.size / MemoryLayout.size) // CHECK-NEXT: 2 -print(unspecializedSizeOf(ContainsTupleOfFunctions<()>.self) / sizeof(Int.self)) +print(unspecializedSizeOf(ContainsTupleOfFunctions<()>.self) / MemoryLayout.size) // CHECK-NEXT: 3 -print(sizeof(ContainsTupleOfFunctions.self) / sizeof(Int.self)) +print(MemoryLayout>.size / MemoryLayout.size) // CHECK-NEXT: 3 -print(unspecializedSizeOf(ContainsTupleOfFunctions.self) / sizeof(Int.self)) +print(unspecializedSizeOf(ContainsTupleOfFunctions.self) / MemoryLayout.size) let x = ContainsTupleOfFunctions(x: (1, { $0 + 1 })) let y = ContainsTupleOfFunctions(x: ("foo", { $0 + "bar" })) diff --git a/test/SILOptimizer/devirt_protocol_method_invocations.swift b/test/SILOptimizer/devirt_protocol_method_invocations.swift index 14d50fdf10215..bf83a73a27d0a 100644 --- a/test/SILOptimizer/devirt_protocol_method_invocations.swift +++ b/test/SILOptimizer/devirt_protocol_method_invocations.swift @@ -162,7 +162,7 @@ protocol StaticP { static var size: Int { get } } struct HasStatic : StaticP { - static var size: Int { return sizeof(T.self) } + static var size: Int { return MemoryLayout.size } } public func testExMetatype() -> Int { let type: StaticP.Type = HasStatic.self diff --git a/validation-test/stdlib/Arrays.swift.gyb b/validation-test/stdlib/Arrays.swift.gyb index 102f841920d3b..1cbdf8d63fd9a 100644 --- a/validation-test/stdlib/Arrays.swift.gyb +++ b/validation-test/stdlib/Arrays.swift.gyb @@ -96,9 +96,9 @@ var ArrayTestSuite = TestSuite("Array") ArrayTestSuite.test("sizeof") { var a = [ 10, 20, 30 ] #if arch(i386) || arch(arm) - expectEqual(4, sizeofValue(a)) + expectEqual(4, MemoryLayout._ofInstance(a).size) #else - expectEqual(8, sizeofValue(a)) + expectEqual(8, MemoryLayout._ofInstance(a).size) #endif } diff --git a/validation-test/stdlib/CoreAudio.swift b/validation-test/stdlib/CoreAudio.swift index de7049dfcb00b..c063e2afe3cd3 100644 --- a/validation-test/stdlib/CoreAudio.swift +++ b/validation-test/stdlib/CoreAudio.swift @@ -106,9 +106,9 @@ CoreAudioTestSuite.test( } CoreAudioTestSuite.test("AudioBufferList.sizeInBytes(maximumBuffers: Int)") { - expectEqual(ablHeaderSize + strideof(AudioBuffer.self), + expectEqual(ablHeaderSize + MemoryLayout.stride, AudioBufferList.sizeInBytes(maximumBuffers: 1)) - expectEqual(ablHeaderSize + 16 * strideof(AudioBuffer.self), + expectEqual(ablHeaderSize + 16 * MemoryLayout.stride, AudioBufferList.sizeInBytes(maximumBuffers: 16)) } diff --git a/validation-test/stdlib/Dictionary.swift b/validation-test/stdlib/Dictionary.swift index db8e755e6cc2a..86565c1c90e5c 100644 --- a/validation-test/stdlib/Dictionary.swift +++ b/validation-test/stdlib/Dictionary.swift @@ -75,9 +75,9 @@ DictionaryTestSuite.test("AssociatedTypes") { DictionaryTestSuite.test("sizeof") { var dict = [1: "meow", 2: "meow"] #if arch(i386) || arch(arm) - expectEqual(4, sizeofValue(dict)) + expectEqual(4, MemoryLayout._ofInstance(dict).size) #else - expectEqual(8, sizeofValue(dict)) + expectEqual(8, MemoryLayout._ofInstance(dict).size) #endif } diff --git a/validation-test/stdlib/FixedPointArithmeticTraps.swift.gyb b/validation-test/stdlib/FixedPointArithmeticTraps.swift.gyb index 37fa7050a9a78..e25cf6733b413 100644 --- a/validation-test/stdlib/FixedPointArithmeticTraps.swift.gyb +++ b/validation-test/stdlib/FixedPointArithmeticTraps.swift.gyb @@ -258,7 +258,7 @@ FixedPointArithmeticTraps.test("${description}/${IntTy}/TypeSize") { a = get${IntTy}(a ${operation} get${IntTy}(0)) a = get${IntTy}(a ${operation} get${IntTy}(1)) - let shiftAmount = ${IntTy}(sizeof(${IntTy}.self) * 8) + let shiftAmount = ${IntTy}(MemoryLayout<${IntTy}>.size * 8) // Overflow in ${description}. expectCrashLater() @@ -271,7 +271,7 @@ FixedPointArithmeticTraps.test("${description}/${IntTy}/TypeSizePlusOne") { a = get${IntTy}(a ${operation} get${IntTy}(0)) - let shiftAmount = ${IntTy}(sizeof(${IntTy}.self) * 8 + 1) + let shiftAmount = ${IntTy}(MemoryLayout<${IntTy}>.size * 8 + 1) // Overflow in ${description}. expectCrashLater() diff --git a/validation-test/stdlib/NSNumberBridging.swift.gyb b/validation-test/stdlib/NSNumberBridging.swift.gyb index 52db31d7bc3b8..52f538bd51d16 100644 --- a/validation-test/stdlib/NSNumberBridging.swift.gyb +++ b/validation-test/stdlib/NSNumberBridging.swift.gyb @@ -137,7 +137,7 @@ extension ${Self} { func toNSNumberByteArray() -> [UInt8] { var v = self var result: [UInt8] = [] - for _ in 0...size { result.append(UInt8(v & 0xff)) v = v >> 8 } @@ -151,7 +151,7 @@ extension ${Self} { func toNSNumberByteArray() -> [UInt8] { var v = self.bitPattern var result: [UInt8] = [] - for _ in 0..> 8 } diff --git a/validation-test/stdlib/OpenCLSDKOverlay.swift b/validation-test/stdlib/OpenCLSDKOverlay.swift index 48c3571ed6231..d38631448a7fc 100644 --- a/validation-test/stdlib/OpenCLSDKOverlay.swift +++ b/validation-test/stdlib/OpenCLSDKOverlay.swift @@ -168,15 +168,15 @@ tests.test("clSetKernelArgsListAPPLE") { // Create the input and output arrays in device memory for our calculation // - guard var input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), sizeof(Float.self) * count, nil, nil), - var output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), sizeof(Float.self) * count, nil, nil) else { + guard var input = clCreateBuffer(context, cl_mem_flags(CL_MEM_READ_ONLY), MemoryLayout.size * count, nil, nil), + var output = clCreateBuffer(context, cl_mem_flags(CL_MEM_WRITE_ONLY), MemoryLayout.size * count, nil, nil) else { print("Error: Failed to allocate device memory!") exit(1) } // Write our data set into the input array in device memory // - err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, data, 0, nil, nil) + err = clEnqueueWriteBuffer(commands, input, cl_bool(CL_TRUE), 0, MemoryLayout.size * count, data, 0, nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to write to source array!") @@ -192,9 +192,9 @@ tests.test("clSetKernelArgsListAPPLE") { countPtr in clSetKernelArgsListAPPLE( kernel!, 3, - 0, sizeof(cl_mem.self), inputPtr, - 1, sizeof(cl_mem.self), outputPtr, - 2, sizeofValue(count), countPtr) + 0, MemoryLayout.size, inputPtr, + 1, MemoryLayout.size, outputPtr, + 2, MemoryLayout._ofInstance(count).size, countPtr) } } } @@ -208,7 +208,7 @@ tests.test("clSetKernelArgsListAPPLE") { // Get the maximum work group size for executing the kernel on the device // - err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), sizeofValue(local), &local, nil) + err = clGetKernelWorkGroupInfo(kernel, device_id, cl_kernel_work_group_info(CL_KERNEL_WORK_GROUP_SIZE), MemoryLayout._ofInstance(local).size, &local, nil) if (err != CL_SUCCESS) { print("Error: Failed to retrieve kernel work group info! \(err)") @@ -232,7 +232,7 @@ tests.test("clSetKernelArgsListAPPLE") { // Read back the results from the device to verify the output // - err = clEnqueueReadBuffer(commands, output, cl_bool(CL_TRUE), 0, sizeof(Float.self) * count, &results, cl_uint(0), nil, nil) + err = clEnqueueReadBuffer(commands, output, cl_bool(CL_TRUE), 0, MemoryLayout.size * count, &results, cl_uint(0), nil, nil) if (err != CL_SUCCESS) { print("Error: Failed to read output array! \(err)") diff --git a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb index 18773002127c4..07cd5c2c291ab 100644 --- a/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb +++ b/validation-test/stdlib/Prototypes/PersistentVector.swift.gyb @@ -61,9 +61,9 @@ pointer to a child node. Define `ChildNodeOrKey` to be a type that is an unsafe union of `Key` and `UnsafePointer`: - sizeof(ChildNodeOrKey) = max(sizeof(UnsafePointer), sizeof(Key)) - alignof(ChildNodeOrKey) = max(alignof(UnsafePointer), alignof(Key)) - strideof(ChildNodeOrKey) = max(strideof(UnsafePointer), strideof(Key)) + MemoryLayout.size = max(MemoryLayout.size, MemoryLayout.size) + MemoryLayout.alignment = max(MemoryLayout.alignment, MemoryLayout.alignment) + MemoryLayout.stride = max(MemoryLayout.stride, MemoryLayout.stride) Memory layout: @@ -275,20 +275,20 @@ struct _PVSparseVectorNodePointer typealias _Self = _PVSparseVectorNodePointer static var _referenceCountSize: Int { - return sizeof(Int.self) + return MemoryLayout.size } static var _referenceCountAlignment: Int { - return alignof(Int.self) + return MemoryLayout.alignment } static var _referenceCountOffset: Int { return 0 } static var _childNodePopulationBitmapSize: Int { - return sizeof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.size } static var _childNodePopulationBitmapAlignment: Int { - return alignof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.alignment } static var _childNodePopulationBitmapOffset: Int { let padding = @@ -297,10 +297,10 @@ struct _PVSparseVectorNodePointer } static var _keyPopulationBitmapSize: Int { - return sizeof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.size } static var _keyPopulationBitmapAlignment: Int { - return alignof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.alignment } static var _keyPopulationBitmapOffset: Int { let padding = @@ -310,10 +310,10 @@ struct _PVSparseVectorNodePointer } static func _childNodeVectorSize(layout: _PVSparseVectorNodeLayoutParameters) -> Int { - return strideof(UnsafePointer.self) * layout.childNodeCount + return MemoryLayout>.stride * layout.childNodeCount } static var _childNodeVectorAlignment: Int { - return alignof(UnsafePointer.self) + return MemoryLayout>.alignment } static var _childNodeVectorOffset: Int { let padding = @@ -322,10 +322,10 @@ struct _PVSparseVectorNodePointer } static func _keyVectorSize(layout: _PVSparseVectorNodeLayoutParameters) -> Int { - return strideof(Key.self) * layout.keyCount + return MemoryLayout.stride * layout.keyCount } static var _keyVectorAlignment: Int { - return alignof(Key.self) + return MemoryLayout.alignment } static func _keyVectorOffset(layout: _PVSparseVectorNodeLayoutParameters) -> Int { let padding = @@ -334,10 +334,10 @@ struct _PVSparseVectorNodePointer } static func _valueVectorSize(layout: _PVSparseVectorNodeLayoutParameters) -> Int { - return strideof(Value.self) * layout.keyCount + return MemoryLayout.stride * layout.keyCount } static var _valueVectorAlignment: Int { - return alignof(Value.self) + return MemoryLayout.alignment } static func _valueVectorOffset(layout: _PVSparseVectorNodeLayoutParameters) -> Int { let padding = @@ -942,30 +942,30 @@ struct _PVArrayNodePointer static var _childNodeOrKeyStride: Int { return max( - strideof(UnsafePointer.self), - strideof(Key.self)) + MemoryLayout>.stride, + MemoryLayout.stride) } static var _childNodeOrKeyAlignment: Int { return max( - alignof(UnsafePointer.self), - alignof(Key.self)) + MemoryLayout>.alignment, + MemoryLayout.alignment) } static var _referenceCountSize: Int { - return sizeof(Int.self) + return MemoryLayout.size } static var _referenceCountAlignment: Int { - return alignof(Int.self) + return MemoryLayout.alignment } static var _referenceCountOffset: Int { return 0 } static var _childNodePopulationBitmapSize: Int { - return sizeof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.size } static var _childNodePopulationBitmapAlignment: Int { - return alignof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.alignment } static var _childNodePopulationBitmapOffset: Int { let padding = max( @@ -975,10 +975,10 @@ struct _PVArrayNodePointer } static var _keyPopulationBitmapSize: Int { - return sizeof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.size } static var _keyPopulationBitmapAlignment: Int { - return alignof(_Int32Bitmap.self) + return MemoryLayout<_Int32Bitmap>.alignment } static var _keyPopulationBitmapOffset: Int { let padding = max( @@ -1002,10 +1002,10 @@ struct _PVArrayNodePointer } static var _valueArraySize: Int { - return strideof(Value.self) * 32 + return MemoryLayout.stride * 32 } static var _valueArrayAlignment: Int { - return alignof(Value.self) + return MemoryLayout.alignment } static var _valueArrayOffset: Int { let padding = @@ -1182,20 +1182,20 @@ struct _PVCollisionNodePointer typealias _Self = _PVCollisionNodePointer static var _referenceCountSize: Int { - return sizeof(Int.self) + return MemoryLayout.size } static var _referenceCountAlignment: Int { - return alignof(Int.self) + return MemoryLayout.alignment } static var _referenceCountOffset: Int { return 0 } static var _countSize: Int { - return sizeof(Int.self) + return MemoryLayout.size } static var _countAlignment: Int { - return alignof(Int.self) + return MemoryLayout.alignment } static var _countOffset: Int { let padding = max( @@ -1205,10 +1205,10 @@ struct _PVCollisionNodePointer } static func _keyArraySize(layout: _PVCollisionNodePointerLayoutParameters) -> Int { - return strideof(Key.self) * layout.keyCount + return MemoryLayout.stride * layout.keyCount } static var _keyArrayAlignment: Int { - return alignof(Key.self) + return MemoryLayout.alignment } static var _keyArrayOffset: Int { let padding = @@ -1217,10 +1217,10 @@ struct _PVCollisionNodePointer } static func _valueArraySize(layout: _PVCollisionNodePointerLayoutParameters) -> Int { - return strideof(Value.self) * layout.keyCount + return MemoryLayout.stride * layout.keyCount } static var _valueArrayAlignment: Int { - return alignof(Value.self) + return MemoryLayout.alignment } static func _valueArrayOffset(layout: _PVCollisionNodePointerLayoutParameters) -> Int { let padding = @@ -1880,14 +1880,14 @@ var PersistentVectorTests = TestSuite("PersistentVector") PersistentVectorTests.test("sizeof") { expectEqual( - sizeof(UnsafePointer.self), - sizeof(_PVSparseVectorNodePointer>.self)) + MemoryLayout>.size, + MemoryLayout<_PVSparseVectorNodePointer>>.size) expectEqual( - sizeof(UnsafePointer.self), - sizeof(_PVArrayNodePointer>.self)) + MemoryLayout>.size, + MemoryLayout<_PVArrayNodePointer>>.size) expectEqual( - sizeof(UnsafePointer.self), - sizeof(_PVAnyNodePointer>.self)) + MemoryLayout>.size, + MemoryLayout<_PVAnyNodePointer>>.size) } %{ diff --git a/validation-test/stdlib/SceneKit.swift b/validation-test/stdlib/SceneKit.swift index c71d21fc41ba7..f828482f728f7 100644 --- a/validation-test/stdlib/SceneKit.swift +++ b/validation-test/stdlib/SceneKit.swift @@ -20,7 +20,7 @@ func bytesFromNSData(_ data: NSData) -> [UInt8] { func floatsFromNSData(_ data: NSData) -> [Float] { let floatPtr = data.bytes.bindMemory(to: Float.self, capacity: data.length) - return Array(UnsafeBufferPointer(start: floatPtr, count: data.length / sizeof(Float))) + return Array(UnsafeBufferPointer(start: floatPtr, count: data.length / MemoryLayout.size)) } if #available(iOS 8.0, *) { @@ -140,7 +140,7 @@ if #available(iOS 8.0, *) { expectEqual(source.vectorCount, 2) expectEqual(source.componentsPerVector, 3) - expectEqual(source.bytesPerComponent, sizeof(Float)) + expectEqual(source.bytesPerComponent, MemoryLayout.size) let positions = floatsFromNSData(source.data as NSData) expectEqual(positions[2], 3) expectEqual(positions[4], 5) @@ -154,7 +154,7 @@ if #available(iOS 8.0, *) { expectEqual(source.vectorCount, 2) expectEqual(source.componentsPerVector, 3) - expectEqual(source.bytesPerComponent, sizeof(Float)) + expectEqual(source.bytesPerComponent, MemoryLayout.size) let normals = floatsFromNSData(source.data as NSData) expectEqual(normals[2], 3) expectEqual(normals[4], 5) diff --git a/validation-test/stdlib/Set.swift b/validation-test/stdlib/Set.swift index 1a211ab44fc0b..a11752348eebb 100644 --- a/validation-test/stdlib/Set.swift +++ b/validation-test/stdlib/Set.swift @@ -328,9 +328,9 @@ SetTestSuite.test("AssociatedTypes") { SetTestSuite.test("sizeof") { var s = Set(["Hello", "world"]) #if arch(i386) || arch(arm) - expectEqual(4, sizeofValue(s)) + expectEqual(4, MemoryLayout._ofInstance(s).size) #else - expectEqual(8, sizeofValue(s)) + expectEqual(8, MemoryLayout._ofInstance(s).size) #endif } diff --git a/validation-test/stdlib/String.swift b/validation-test/stdlib/String.swift index 954d4291dd308..59526d9edca8c 100644 --- a/validation-test/stdlib/String.swift +++ b/validation-test/stdlib/String.swift @@ -45,7 +45,7 @@ extension String { var StringTests = TestSuite("StringTests") StringTests.test("sizeof") { - expectEqual(3 * sizeof(Int.self), sizeof(String.self)) + expectEqual(3 * MemoryLayout.size, MemoryLayout.size) } StringTests.test("AssociatedTypes-UTF8View") { diff --git a/validation-test/stdlib/UnicodeUTFEncoders.swift b/validation-test/stdlib/UnicodeUTFEncoders.swift index 236ee97b5616f..39040d485b358 100644 --- a/validation-test/stdlib/UnicodeUTFEncoders.swift +++ b/validation-test/stdlib/UnicodeUTFEncoders.swift @@ -106,7 +106,7 @@ final class CodecTest { // Use Cocoa to encode the scalar nsEncode(scalar.value, Codec.encodingId(), &nsEncodeBuffer, &used) - let nsEncoded = nsEncodeBuffer[0..<(used/sizeof(CodeUnit.self))] + let nsEncoded = nsEncodeBuffer[0..<(used/MemoryLayout.size)] var encodeIndex = encodeBuffer.startIndex let encodeOutput: (CodeUnit) -> Void = { self.encodeBuffer[encodeIndex] = $0