Commit Graph

57 Commits

Author SHA1 Message Date
Guillaume Lessard
940628a23a [stdlib] add newly-required unsafe annotations 2025-03-10 15:20:51 -07:00
Guillaume Lessard
7bbb8348e3 [stdlib] add span properties to array types 2025-03-10 08:51:56 -07:00
Doug Gregor
22eecacc35 Adopt unsafe annotations throughout the standard library 2025-02-26 14:28:01 -08:00
Hamish Knight
f1e4fb27de Revert "Add an overload of append(contentsOf:) on Array that takes a Collecti…"
This reverts commit b71f768128.
2024-12-17 16:23:16 +00:00
David Smith
b71f768128 Add an overload of append(contentsOf:) on Array that takes a Collection instead of a Sequence, and use it to accelerate wCSIA-compatible Sequences (#77487) 2024-12-13 23:11:35 -08:00
Doug Gregor
8760b7caad Consistently use @usableFromInline and remove redundant @inlinables 2024-08-16 13:03:07 -07:00
Doug Gregor
4d037ce6ef Adopt typed throws for withUnsafeMutableBufferPointer 2024-08-16 11:13:19 -07:00
Doug Gregor
5c07fd9502 Adopt typed throws in withUnsafeBufferPointer.
Part of rdar://131405937.
2024-08-16 11:13:18 -07:00
Kuba Mracek
829967436e [embedded] Simplify AnyObject/Builtin.NativeObject split in arrays by using a typealias 2023-09-16 13:21:46 -07:00
Kuba Mracek
ae2e903574 [embedded] Build an initial embedded Swift standard library
This isn't a "complete" port of the standard library for embedded Swift, but
something that should serve as a starting point for further iterations on the
stdlib.

- General CMake logic for building a library as ".swiftmodule only" (ONLY_SWIFTMODULE).
- CMake logic in stdlib/public/core/CMakeLists.txt to start building the embedded stdlib for a handful of hardcoded target triples.
- Lots of annotations throughout the standard library to make types, functions, protocols unavailable in embedded Swift (@_unavailableInEmbedded).
- Mainly this is about stdlib functionality that relies on existentials, type erasure, metatypes, reflection, string interpolations.
- We rely on function body removal of unavailable functions to eliminate the actual problematic SIL code (existentials).
- Many .swift files are not included in the compilation of embedded stdlib at all, to simplify the scope of the annotations.
- EmbeddedStubs.swift is used to stub out (as unavailable and fatalError'd) the missing functionality.
2023-09-16 12:38:46 -07:00
Lucy Satheesan
ff76106177 [stdlib] don't copy array contents on removeAll(keepingCapacity: true) 2023-05-24 07:52:39 -07:00
Erik Eckstein
5d43f75173 stdlib: force inlining of ContiguousArray.endIndex and ContiguousArray._getCount
This let the optimizer generate efficient code for generic array loops (note that generic functions are not inlined by default).
Note that the same change is not done for `Array` because this might increase code size due to Array's bridging code.

rdar://108746069
2023-05-03 15:07:37 +02:00
Nate Chandler
cda365ca8d [stdlib] Collection types are eagerMove.
Types that have "value semantics" should not have lexical lifetimes.
Value types are not expected to have custom deinits. Are not expected to
expose unsafe interior pointers. And cannot have weak references because
they are structs. Therefore, deinitialization barriers are irrelevant.

rdar://107076869
2023-03-30 11:04:47 -07:00
Karoy Lorentey
7cbadf2c8d [stdlib] _modify: Ensure cleanup is always executed
Cleanup code in _modify accessors will only run reliably if it is put in a defer statement.

(Statements that follow the `yield` aren’t executed if the yielded-to code throws an error.)
2022-09-06 21:15:58 -07:00
Erik Eckstein
97424b76f4 stdlib: Don't check for overflows when adding 1 to Array.count
That addition can not possibly overflow. If Array.count would be Int max, the allocation of the array buffer would have failed way before.
2021-11-29 09:41:05 +01:00
Doug Gregor
353daabf8d Replace UnsafeSendable with @unchecked Sendable in the standard library. 2021-11-12 07:56:10 -08:00
Kuba (Brecka) Mracek
404badb49a Introduce SWIFT_ENABLE_REFLECTION to turn on/off the support for Mirrors and reflection (#33617) 2021-09-08 13:08:13 -07:00
Karoy Lorentey
48fa06b7f9 [stdlib] ContiguousArray & ArraySlice: Stop swapping self in wUMBP
Implements https://github.com/apple/swift/pull/38867 for ContiguousArray and ArraySlice -- these have the same unnecessary swapping logic.
2021-08-16 14:27:24 -07:00
Doug Gregor
9579390024 [SE-0304] Rename ConcurrentValue to Sendable 2021-03-18 22:48:20 -07:00
Karoy Lorentey
0836707303 [stdlib] Deprecate MutableCollection._withUnsafeMutableBufferPointerIfSupported (#36003)
* [stdlib] Deprecate MutableCollection._withUnsafeMutableBufferPointerIfSupported

In Swift 5.0, [SE-0237] introduced the public `MutableCollection.withContiguousMutableStorageIfAvailable` method. It’s time we migrated off the old, underscored variant and deprecated it.

The default `MutableCollection.sort` and `.partition(by:)` implementations are currently calling this hidden method rather than the documented interface, preventing custom Collection implementations from achieving good performance, even if they have contiguous storage.

[SE-0237]: https://github.com/apple/swift-evolution/blob/master/proposals/0237-contiguous-collection.md

* [test] Update tests for stdlib behavior changes

* Update stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift

Co-authored-by: Nate Cook <natecook@apple.com>

* Update stdlib/private/StdlibCollectionUnittest/CheckMutableCollectionType.swift

Co-authored-by: Nate Cook <natecook@apple.com>

* Apply suggestions from code review

Co-authored-by: Nate Cook <natecook@apple.com>

* [test] LoggingMutableCollection: Fix logging targets

* [stdlib] Fix warning by restoring original workaround

Co-authored-by: Nate Cook <natecook@apple.com>
2021-02-26 11:32:27 -08:00
Doug Gregor
1a1f79c0de Introduce safety checkin for ConcurrentValue conformance.
Introduce checking of ConcurrentValue conformances:
- For structs, check that each stored property conforms to ConcurrentValue
- For enums, check that each associated value conforms to ConcurrentValue
- For classes, check that each stored property is immutable and conforms
  to ConcurrentValue

Because all of the stored properties / associated values need to be
visible for this check to work, limit ConcurrentValue conformances to
be in the same source file as the type definition.

This checking can be disabled by conforming to a new marker protocol,
UnsafeConcurrentValue, that refines ConcurrentValue.
UnsafeConcurrentValue otherwise his no specific meaning. This allows
both "I know what I'm doing" for types that manage concurrent access
themselves as well as enabling retroactive conformance, both of which
are fundamentally unsafe but also quite necessary.

The bulk of this change ended up being to the standard library, because
all conformances of standard library types to the ConcurrentValue
protocol needed to be sunk down into the standard library so they
would benefit from the checking above. There were numerous little
mistakes in the initial pass through the stsandard library types that
have now been corrected.
2021-02-04 03:45:09 -08:00
Matt Zanchelli
be13b470aa Fix typos
becuase -> because
preceeds -> precedes
initalizer -> initializer
intialize -> initialize
libary -> library
notfication -> notification
reciever -> receiver
collecton -> collection
exlcusive -> exclusive
techincal -> technical
compatability -> compatibility
setps -> steps
accomodate -> accommodate
brakcet -> bracket
fraciton -> fraction
programm -> program
concequently -> consequently
ecoding -> encoding
timeIntervalforSelfEnd -> timeIntervalForSelfEnd
2020-12-21 18:44:03 -05:00
Andrew Trick
3128eae3f0 Add NestedSemanticFunctionCheck diagnostic
to check for improperly nested '@_semantic' functions.

Add a missing @_semantics("array.init") in ArraySlice found by the
diagnostic.

Distinguish between array.init and array.init.empty.

Categorize the types of semantic functions by how they affect the
inliner and pass pipeline, and centralize this logic in
PerformanceInlinerUtils. The ultimate goal is to prevent inlining of
"Fundamental" @_semantics calls and @_effects calls until the late
pipeline where we can safely discard semantics. However, that requires
significant pipeline changes.

In the meantime, this change prevents the situation from getting worse
and makes the intention clear. However, it has no significant effect
on the pass pipeline and inliner.
2020-10-26 17:02:33 -07:00
Valeriy Van
cdba663d80 Fixes example snippets in Array.swift considering endianness 2020-09-29 02:00:24 +02:00
Erik Eckstein
71a642e51b stdlib, SIL optimizer: use the SIL copy-on-write representation in the Array types.
Use the new builtins for COW representation in Array, ContiguousArray and ArraySlice.
The basic idea is to strictly separate code which mutates an array buffer from code which reads from an array.
The concept is explained in more detail in docs/SIL.rst, section "Copy-on-Write Representation".

The main change is to use beginCOWMutation() instead of isUniquelyReferenced() and insert endCOWMutation() at the end of all mutating functions. Also, reading from the array buffer must be done differently, depending on if the buffer is in a mutable or immutable state.

All the required invariants are enforced by runtime checks - but only in an assert-build of the library: a bit in the buffer object side-table indicates if the buffer is mutable or not.

Along with the library changes, also two optimizations needed to be updated: COWArrayOpt and ObjectOutliner.
2020-06-08 15:02:22 +02:00
Erik Eckstein
68728dcb7d stdlib: move the new-buffer creation function from Array to ArrayBuffer
This has two advantages:
1. It does not force the Array in memory (to pass it as inout self to the non-inlinable _createNewBuffer).
2. The new _consumeAndCreateNew is annotated to consume self. This helps to reduce unnecessary retains/releases.

The change applies for Array and ContiguousArray.
2020-05-29 08:46:54 +02:00
Alex Martini
bc5f0153fa Match docs to current behavior.
Confirmed this change on using the swift-5.2-DEVELOPMENT-SNAPSHOT-2020-01-22-a
toolchain, Apple Swift version 5.2-dev (Swift d3f0448a4c).

Fixes rdar://problem/58717942
2020-03-05 11:17:55 -08:00
Erik Eckstein
dfc5b06819 stdlib: annotate Array's remove functions with semantic attributes.
All mutating Array functions must be annotated with semantics, because otherwise some high level optimizations get confused.
The semantic attributes prevent inlining those functions in high-level-sil.
This is need so that the optimizer sees that the Array is taken as inout and can reason that it's modified.

This restriction is not needed anymore when we’ll have COW representation in SIL.

rdar://problem/58478089
2020-01-10 17:09:47 +01:00
Erik Eckstein
60a0718922 stdlib: simplify Array/ContiguousArray's withUnsafeMutableBufferPointer and withUnsafeMutableBufferPointer
Again, to reduce code size
2020-01-09 16:17:38 +01:00
Erik Eckstein
bda8af0958 stdlib: simplify Array/ContiguousArray's append(contentsOf:)
Instead of calling ArrayBuffer's _arrayAppendSequence, inline the code. This saves some code size.
2020-01-09 16:17:38 +01:00
Erik Eckstein
88a9ebb9f8 stdlib: Don't request additional capacity in Array/ContiguousArray's remove.
Just copy the buffer if it's not unique.
This also implies that if there is a copy-on-write in remove, "shrink" the capacity of the new buffer to the required amount of elements (instead of copying the capacity of the original buffer).
2020-01-09 16:17:38 +01:00
Erik Eckstein
ea3b6a02af stdlib: rewrite Array/ContiguousArray logic for reserving capacity and creating a new buffer.
Share more code and avoid the large generic functions of ArrayProtocol.
The result is a significant code size win.
2020-01-09 16:17:38 +01:00
Julian Lettner
381dcc24fc [TSan] Do not report benign race on _swiftEmptyArrayStorage
A previous commit [1] identified and fixed a benign race on
`_swiftEmptyArrayStorage`.  Unfortunately, we have some code duplication
and the fix was not applied to all the necessary places.  Essentially,
we need to ensure that the "empty array storage" object that backs many
"array like types" is never written to.

I tried to improve the test to capture this, however, it is very
finicky.  Currently, it does not go red on my system even when I remove
the check to avoid the benign race in Release mode.

Relevant classes: Array, ArraySlice, ContiguousArray, ArrayBuffer,
ContiguousArrayBuffer, SliceBuffer.

[1] b9b4c789f3

rdar://55161564
2019-10-21 11:22:25 -07:00
Alex Martini
f040edaa85 Typo fix: of of -> of
rdar://problem/54218099
2019-08-21 10:40:18 -07:00
Ben Cohen
e9d4687e31 De-underscore @frozen, apply it to structs (#24185)
* De-underscore @frozen for enums

* Add @frozen for structs, deprecate @_fixed_layout for them

* Switch usage from _fixed_layout to frozen
2019-05-30 17:55:37 -07:00
Nate Cook
b6bb9d2f8c [stdlib] Make unsafe array initializer public (#23134)
[stdlib] Make unsafe array initializer public

This implements SE-0245. The public versions of this initializer call
into the existing, underscored version, which avoids the need for
availability constraints.
2019-03-23 13:18:10 -05:00
Andrew Trick
6d3397337d Fix performance of array initialization from a generic sequence.
This fixes a major perform bug involving array initialization from any
contiguously stored collection.	 This is not a recent regression. This fix
results in a 10,000X speedup (that's 4 zeros) for this code path:

func initializeFromSlice(_ a: [Int]) -> [Int] {
  return Array<Int>(a[...])
}

A benchmark is included.
2019-02-11 19:41:45 -08:00
Ben Cohen
ad50a39b12 [stdlib] Add withContiguous{Mutable}StorageIfAvailable (#21092)
* Add MutableCollection.withContiguousMutableStorageIfAvailable

* Add withContiguousMutableStorageIfAvailable impls

* Add tests on concrete types

* Add Sequence.withContiguousStorageIfAvailable

* Implement withContiguousStorageIfAvailable in concrete types
2018-12-07 10:01:18 -08:00
Ben Cohen
1673c12d78 [stdlib] Replace "sanityCheck" with "internalInvariant" (#20616)
* Replace "sanityCheck" with "internalInvariant"
2018-11-15 20:50:22 -08:00
Maxim Moiseev
cbf83ac04f [NFC][stdlib] Add FIXME markers to simplify audit 2018-11-14 11:58:42 -08:00
Slava Pestov
f6c2caf64b stdlib: Add @inlinable to @inline(__always) declarations
These should be audited since some might not actually need to be
@inlinable, but for now:

- Anything public and @inline(__always) is now also @inlinable
- Anything @usableFromInline and @inline(__always) is now @inlinable
2018-11-13 15:15:07 -05:00
Ben Cohen
9ce2143335 Additional ownership annotations 2018-10-03 19:10:22 -07:00
Ben Cohen
6cc6f4f182 Underscore @usableFromInlinable symbols (#19686) 2018-10-03 12:01:28 -07:00
Ben Cohen
098a8919c4 Remove redundant implementations of !=(Equatable,Equatable) 2018-09-25 15:24:23 -07:00
Ben Cohen
df995de0d6 [stdlib] Make KeyValuePairs fully inlinable (#19502)
* Move KVP into its own Swift file. Make it fully inlineable.

* Make _makeCollectionDescription an extension. Add KeyValue equivalent.
2018-09-24 17:46:32 -07:00
Ben Cohen
ae6f5dd604 [stdlib] Add consuming/owned annotations to Collection implementations (#19360)
* Add consuming/owned annotations to Collection implementations

* Update SILOptimizer tests

* Fix access_marker_verify test

* XFAIL reconstruct_type_from_mangled_name
2018-09-21 12:06:56 -07:00
Ben Cohen
b4a23adcf0 [stdlib] Update Array.subscript to use _modify (#19154)
* Switch Array to use subscript _modify

* Add _modify to ContiguousArray

* XFAIL linux failing test
2018-09-07 10:36:58 -07:00
Ben Cohen
dd2f3b4386 [stdlib] More inalienable auditing (#18925)
* Removing FIXME from methods also marked always/never

* Unavailable/deprecated things don't need inlining

* Trivial implementations

* Enum namespaces

* Unsafe performance of opaque/raw pointer

* Dump doesn't need to be fast

* Error paths shouldn't require inlining

* Consistency with surrounding code

* Lazy performance needs specialization
2018-08-23 18:52:21 -07:00
Erik Eckstein
6ba45473df Remove the pinning addressors
It was used for Array + related types.
With exclusivity checking the pinned addressors are not useful anymore.

rdar://problem/35401528
2018-08-23 12:47:56 -07:00
Nate Cook
3d7dfc232b [stdlib] Update complexity docs for seq/collection algorithms (#17254)
* [stdlib] Update complexity docs for seq/collection algorithms

This corrects and standardizes the complexity documentation for Sequence
and Collection methods. The use of constants is more consistent, with `n`
equal to the length of the target collection, `m` equal to the length of
a collection passed in as a parameter, and `k` equal to any other passed
or calculated constant.

* Apply notes from @brentdax about complexity nomenclature

* Change `n` to `distance` in `index(_:offsetBy:)`

* Use equivalency language more places; sync across array types

* Use k instead of n for parameter names

* Slight changes to index(_:offsetBy:) discussion.

* Update tests with new parameter names
2018-07-24 01:01:34 -05:00