Commit Graph

37 Commits

Author SHA1 Message Date
Daniil Kovalev
1e403ecf5c [AutoDiff] Support custom derivatives for @_alwaysEmitIntoClient functions (#78908)
Consider an `@_alwaysEmitIntoClient` function and a custom derivative
defined
for it. Previously, such a combination resulted different errors under
different
circumstances.

Sometimes, there were linker errors due to missing derivative function
symbol -
these occurred when we tried to find the derivative in a module, while
it
should have been emitted into client's code (and it did not happen).

Sometimes, there were SIL verification failures like this:

```
SIL verification failed: internal/private function cannot be serialized or serializable: !F->isAnySerialized() || embedded
```

Linkage and serialization options for the derivative were not handled
properly,
and, instead of PublicNonABI linkage, we had Private one which is
unsupported
for serialization - but we need to serialize `@_alwaysEmitIntoClient`
functions
so the client's code is able to see them.

This patch resolves the issue and adds proper handling of custom
derivatives
of `@_alwaysEmitIntoClient` functions. Note that either both the
function and
its custom derivative or none of them should have
`@_alwaysEmitIntoClient`
attribute, mismatch in this attribute is not supported.

The following cases are handled (assume that in each case client's code
uses
the derivative).

1. Both the function and its derivative are defined in a single file in
   one module.

2. Both the function and its derivative are defined in different files
which
   are compiled to a single module.

3. The function is defined in one module, its derivative is defined in
another
   module.

4. The function and the derivative are defined as members of a protocol
extension in two separate modules - one for the function and one for the
   derivative. A struct conforming the protocol is defined in the third
   module.

5. The function and the derivative are defined as members of a struct
extension in two separate modules - one for the function and one for the
   derivative.

The changes allow to define derivatives for methods of `SIMD`.

Fixes #54445
<!--
If this pull request is targeting a release branch, please fill out the
following form:

https://github.com/swiftlang/.github/blob/main/PULL_REQUEST_TEMPLATE/release.md?plain=1

Otherwise, replace this comment with a description of your changes and
rationale. Provide links to external references/discussions if
appropriate.
If this pull request resolves any GitHub issues, link them like so:

  Resolves <link to issue>, resolves <link to another issue>.

For more information about linking a pull request to an issue, see:

https://docs.github.com/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue
-->

<!--
Before merging this pull request, you must run the Swift continuous
integration tests.
For information about triggering CI builds via @swift-ci, see:

https://github.com/apple/swift/blob/main/docs/ContinuousIntegration.md#swift-ci

Thank you for your contribution to Swift!
-->
2025-05-25 09:47:15 -04:00
Erik Eckstein
8e874cd2b2 SIL: add better support for specialized witness tables.
Store specialize witness tables in a separate lookup table in the module. This allows that for a normal conformance there can exist the original _and_ a specialized witness table.
Also, add a boolean property `isSpecialized` to `WitnessTable` which indicates whether the witness table is specialized or not.
2025-04-18 06:58:34 +02:00
Erik Eckstein
14ff3ea05f SILLinker: de-serialize Executor witness tables for the xExecutorRef builtins
Fixes unresolved symbol linker errors in embedded mode.
rdar://148538336
2025-04-04 14:32:48 +02:00
Erik Eckstein
e68882e8a3 SILLinker: make sure to de-serialize base protocol witness tables in embedded mode
Fixes unresolved symbol linker errors or compiler crashes
rdar://148538336
2025-04-04 14:32:48 +02:00
Kuba Mracek
9a293ed29a [embedded] Link in @_used declarations from other modules in SILLinker 2025-03-20 15:52:15 -07:00
Erik Eckstein
cc308c97cf embedded: make sure to generate witness tables which are imported from other modules
In embedded swift all the code is generated in the top-level module.
De-serialized witness tables for class existentials must be code-gen'd and therefore made non-external.

Fixes an unresolved symbol linker error.
rdar://142561676
2025-01-13 14:08:35 +01:00
Erik Eckstein
67b8c08ef1 SILLinker: convert an assert to a compiler error message
Having a wrong linkage can happen if the user "re-defines" an existing function with a wrong linkage, e.g. using `@_cdecl`.
2025-01-08 11:00:27 +01:00
Erik Eckstein
5502373018 SIL: rename AssociatedTypeProtocolWitness -> AssociatedConformanceWitness in SILWitnessTable
To be consistent with the naming convention in the AST
2024-10-02 07:10:30 +02:00
Kuba (Brecka) Mracek
24af84d8b9 Merge pull request #76753 from kubamracek/embedded-existential-deserialize
[embedded] Force deserialization of wtables when needed to support class-bound existentials
2024-09-28 01:19:22 -07:00
Kuba Mracek
151e587ef1 [embedded] Force deserialization of wtables when needed to support class-bound existentials 2024-09-27 10:49:25 -07:00
Erik Eckstein
2950e4521e SIL: representation for specialized witness tables
The main change here is to associate a witness table with a `ProtocolConformance` instead of a `RootProtocolConformance`.
A `ProtocolConformance` is the base class and can be a `RootProtocolConformance` or a `SpecializedProtocolConformance`.
2024-09-25 19:32:08 +02:00
Erik Eckstein
718ea4b018 replace require with the new ASSERT macro 2024-06-25 10:45:55 +02:00
Tim Kientzle
1098054291 Merge branch 'main' into tbkka-assertions2 2024-06-18 17:52:00 -07:00
Ellie Shin
534c35b08b [PackageCMO] Optimize witness thunks.
- Keep witness thunk linkage private for a package protocol member in SILGen.
- Optimize private/hidden functions during Package CMO; if they don't contain
references that have private/hidden symbols, serialize them and set the linkage
to shared. For unserialized witness thunks, set the linkage to package, so the
witness table itself can be serialized.
- Update witness table and vtable serialization.

Resolves rdar://129976582
2024-06-17 13:06:46 -07:00
Erik Eckstein
532535faad SIL: enable some SIL linkage related asserts in release builds
To catch wrong linkage bugs with a release-built compiler

related to rdar://129318806
2024-06-14 11:55:14 +02:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Ellie Shin
af9e5e6378 Merge branch 'main' into elsh/pcmo-fixes 2024-06-04 11:41:35 -07:00
Ellie Shin
5a0c73c45f Add isPackageCMOEnabled check for MethodInst and KeyPathInst.
Update lambda in table serialization.
Add more tests.
2024-06-03 23:39:04 -07:00
Ellie Shin
4ecfc96578 [SIL][PackageCMO] Allow optimizing [serialized_for_pkg] functions during SIL
inlining, generic/closure specialization, and devirtualization optimization passes.

SILFunction::canBeInlinedIntoCaller now exlicitly requires a caller's SerializedKind_t arg.
isAnySerialized() is added as a convenience function that checks if [serialized] or [serialized_for_pkg].

Resolves rdar://128704752
2024-05-27 23:05:56 -07:00
Ellie Shin
5ccc4cd394 SIL function can be serialized with different kinds: [serialized] or
[serialized_for_package] if Package CMO is enabled. The latter kind
allows a function to be serialized even if it contains loadable types,
if Package CMO is enabled. Renamed IsSerialized_t as SerializedKind_t.

The tri-state serialization kind requires validating inlinability
depending on the serialization kinds of callee vs caller; e.g. if the
callee is [serialized_for_package], the caller must be _not_ [serialized].
Renamed `hasValidLinkageForFragileInline` as `canBeInlinedIntoCaller`
that takes in its caller's SerializedKind as an argument. Another argument
`assumeFragileCaller` is also added to ensure that the calle sites of
this function know the caller is serialized unless it's called for SIL
inlining optimization passes.

The [serialized_for_package] attribute is allowed for SIL function, global var,
v-table, and witness-table.

Resolves rdar://128406520
2024-05-23 15:53:02 -07:00
Kuba Mracek
1bf38aa780 [embedded] Relax assert in SILLinkerVisitor::maybeAddFunctionToWorklist to allow external forward-declarations even in regular Swift, add tests 2024-04-09 11:36:37 -07:00
Kuba Mracek
757e4e56b0 [embedded] In -assert-config Debug, print errors in assertions, preconditions, fatalErrors 2024-04-09 11:36:21 -07:00
Erik Eckstein
4017501a4c re-instate: embedded: allow dead function elimination for de-serialized functions
This re-instates commit cc9e53bb08 with a fix for LLDB (rdar://124228107)

rdar://123772098
2024-03-11 15:38:00 +01:00
Michael Buch
8957f8186a Revert "embedded: allow dead function elimination for de-serialized functions" 2024-03-07 16:48:04 +00:00
Erik Eckstein
cc9e53bb08 embedded: allow dead function elimination for de-serialized functions
In embedded swift all de-serialized get public linkage because all the code is generated in the top-level module.
This change moves the point where we make de-serialized functions public to the end of the pipeline.
This allows dead function elimination to remove unused de-serialized functions.
For some stdlib functions (actually one: the Double initializer for a builtin integer) is essential, because codegen for embedded produces an unresolved symbol.

rdar://123772098
2024-03-06 20:51:09 +01:00
Doug Gregor
97ea19d191 Introduce a builtin and API for getting the local actor from a distributed one
When an actual instance of a distributed actor is on the local node, it is
has the capabilities of `Actor`. This isn't expressible directly in the type
system, because not all `DistributedActor`s are `Actor`s, nor is the
opposite true.

Instead, provide an API `DistributedActor.asLocalActor` that can only
be executed when the distributed actor is known to be local (because
this API is not itself `distributed`), and produces an existential
`any Actor` referencing that actor. The resulting existential value
carries with it a special witness table that adapts any type
conforming to the DistributedActor protocol into a type that conforms
to the Actor protocol. It is "as if" one had written something like this:

    extension DistributedActor: Actor { }

which, of course, is not permitted in the language. Nonetheless, we
lovingly craft such a witness table:

* The "type" being extended is represented as an extension context,
rather than as a type context. This hasn't been done before, all Swift
runtimes support it uniformly.

* A special witness is provided in the Distributed library to implement
the `Actor.unownedExecutor` operation. This witness back-deploys to the
Swift version were distributed actors were introduced (5.7). On Swift
5.9 runtimes (and newer), it will use
`DistributedActor.unownedExecutor` to support custom executors.

* The conformance of `Self: DistributedActor` is represented as a
conditional requirement, which gets satisfied by the witness table
that makes the type a `DistributedActor`. This makes the special
witness work.

* The witness table is *not* visible via any of the normal runtime
lookup tables, because doing so would allow any
`DistributedActor`-conforming type to conform to `Actor`, which would
break the safety model.

* The witness table is emitted on demand in any client that needs it.
In back-deployment configurations, there may be several witness tables
for the same concrete distributed actor conforming to `Actor`.
However, this duplication can only be observed under fairly extreme
circumstances (where one is opening the returned existential and
instantiating generic types with the distributed actor type as an
`Actor`, then performing dynamic type equivalence checks), and will
not be present with a new Swift runtime.

All of these tricks together mean that we need no runtime changes, and
`asLocalActor` back-deploys as far as distributed actors, allowing it's
use in `#isolation` and the async for...in loop.
2024-01-22 17:27:31 -08:00
Erik Eckstein
4d2fe9690a SIL linker: delay function verification to end of linking
The SIL linker de-serializes functions. Immediately after de-serialization some `[serialized]` flags of referenced functions may not be set correctly, yet.
This is fixed by the linker. But it also means that the SIL is only valid after the linker has finished processing all functions.

Fixes a SIL verifier error.
2023-12-01 16:09:30 +01:00
Kuba Mracek
57c26360f6 [embedded] When linking SIL vtables, also link superclass vtables 2023-10-13 21:23:34 -07:00
Kuba Mracek
4709bdcca6 [embedded] Deserialize and import global variables in embedded Swift mode 2023-09-24 17:34:03 -07:00
Kuba Mracek
25eb997a28 [embedded] Add basics of module serialization, importing and validation in embedded Swift.
- Add a flag to the serialized module (IsEmbeddedSwiftModule)
- Check on import that the mode matches (don't allow importing non-embedded module in embedded mode and vice versa)
- Drop TBD support, it's not expected to work in embedded Swift for now
- Drop auto-linking backdeploy libraries, it's not expected to backdeploy embedded Swift for now
- Drop prespecializations, not expected to work in embedded Swift for now
- Use CMO to serialize everything when emitting an embedded Swift module
- Change SILLinker to deserialize/import everything when importing an embedded Swift module
- Add an IR test for importing modules
- Add a deserialization validation test
2023-09-06 20:06:36 -07:00
Allan Shortlidge
40eb1422bb IRGen/SIL: Fix IR linkage computation for inlined function references from modules imported @_weakLinked.
Include the parent `ModuleDecl` when serializing a `SILFunction` so that it is available on deserialized functions even though the full `DeclContext` is not present. With the parent module always available we can reliably compute whether the `SILFunction` comes from a module that was imported `@_weakLinked`.

Serialize the `DeclContext` member of `SILFunction` so that it can be used to look up the module that a function belongs to in order to compute weak import status.

Resolves rdar://98521248
2022-08-19 09:56:45 -07:00
Doug Gregor
fdbeb45320 SIL linker: don't try to synthesize witness tables for marker protocols.
We never have them, we never need them, and we'll crash if there were
one for a conformance of a non-nominal type to such a protocol.

Fixes rdar://91126885 .
2022-03-31 21:48:29 -07:00
Erik Eckstein
6a020f8f15 Stabilize and simplify SIL linkage and serialization
The main point of this change is to make sure that a shared function always has a body: both, in the optimizer pipeline and in the swiftmodule file.
This is important because the compiler always needs to emit code for a shared function. Shared functions cannot be referenced from outside the module.
In several corner cases we missed to maintain this invariant which resulted in unresolved-symbol linker errors.

As side-effect of this change we can drop the shared_external SIL linkage and the IsSerializable flag, which simplifies the serialization and linkage concept.
2022-03-09 15:28:05 +01:00
Arnold Schwaighofer
9f2b6a4ebb Reuse _ContiguousArrayStorage<AnyObject> metadata for any class or objc generic type
Reduces the number of _ContiguousArrayStorage metadata.

In order to support constant time bridging we do need to set the correct
metadata when we bridge to Objective-C. This is so that the type check
succeeds when bridging back from Objective-C to reuse the storage
instance rather than bridging the elements.

To support dynamically setting the `_ContiguousArrayStorage` element
type i needed to add support for optimizing `alloc_ref_dynamic`
throughout the optimizer.

Possible future improvements:
* Use different metadata such that we can disambiguate native Swift
  classes during destruction -- allowing native release rather then unknown
  release usage.
* Optimize the newly added semantic function
  getContiguousArrayStorageType

rdar://86171143
2022-02-16 07:55:34 -08:00
Erik Eckstein
542a378436 SIL: add FunctionRefInst::getReferencedFunction()
If we know that we have a FunctionRefInst (and not another variant of FunctionRefBaseInst), we know that getting the referenced function will not be null (in contrast to FunctionRefBaseInst::getReferencedFunctionOrNull).

NFC
2021-02-09 19:56:43 +01:00
David Zarzycki
e077b6ffd9 [SIL] NFC: Make SILVTable follow C++ and LLVM best practices
1) Convert the `Entry` type to a class with getters/setters
2) Use llvm::TrailingObjects
3) Use llvm::PointerIntPair
2020-06-11 07:51:42 -04:00
Michael Gottesman
e1a19e4173 [sil] Split library into subfolders, while still building as a single library still.
Specifically, I split it into 3 initial categories: IR, Utils, Verifier. I just
did this quickly, we can always split it more later if we want.

I followed the model that we use in SILOptimizer: ./lib/SIL/CMakeLists.txt vends
 a macro (sil_register_sources) to the sub-folders that register the sources of
 the subdirectory with a global state variable that ./lib/SIL/CMakeLists.txt
 defines. Then after including those subdirs, the parent cmake declares the SIL
 library. So the output is the same, but we have the flexibility of having
 subdirectories to categorize source files.
2020-03-30 11:01:00 -07:00