Commit Graph

353 Commits

Author SHA1 Message Date
Allan Shortlidge
b1d20697fa SILGen: Stub unavailable @objc interop functions and thunks.
Part of rdar://107388493
2023-05-03 15:19:32 -07:00
Andrew Trick
7f916bafd9 SILGen - verify incomplete OSSA lifetimes
Use DeadEndBlocks to ignore missing end-borrows and destroys.

Allow SILGen to be as sloppy as it wants with OSSA cleanups.
2023-03-01 21:41:46 -08:00
John McCall
d25a8aec8b Add explicit lowering for value packs and pack expansions.
- SILPackType carries whether the elements are stored directly
  in the pack, which we're not currently using in the lowering,
  but it's probably something we'll want in the final ABI.
  Having this also makes it clear that we're doing the right
  thing with substitution and element lowering.  I also toyed
  with making this a scalar type, which made it necessary in
  various places, although eventually I pulled back to the
  design where we always use packs as addresses.

- Pack boundaries are a core ABI concept, so the lowering has
  to wrap parameter pack expansions up as packs.  There are huge
  unimplemented holes here where the abstraction pattern will
  need to tell us how many elements to gather into the pack,
  but a naive approach is good enough to get things off the
  ground.

- Pack conventions are related to the existing parameter and
  result conventions, but they're different on enough grounds
  that they deserve to be separated.
2023-01-29 03:29:06 -05:00
Nate Chandler
927758f123 [OpaqueValues] Build objc thunk args with fn conv.
Used the function convention to determine whether a SILParameterInfo is
indirect when emitting objc thunk arguments.
2023-01-04 18:17:54 -08:00
Pavel Yaskevich
3fb69b3c3c [SIL] SILFunction: Add runtime accessible function attribute
This attribute indicates that the given SILFunction has to be
added to "accessible functions" section and could be looked up
at runtime using a special API.
2022-12-20 09:33:44 -08:00
Nate Chandler
8d8577e5b0 [SIL] Removed Indirect_In_Constant convention.
It is no different from @in.

Continue parse @in_constant in textual and serialized SIL, but just as
an alias for @in.
2022-12-09 21:54:00 -08:00
Joe Groff
deab4cbf21 Merge pull request #62183 from ellishg/objc-direct-constructor
Allow Swift to call objc_direct constructors
2022-12-08 15:13:21 -08:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01:00
Ellis Hoag
693a049fe4 Allow Swift to call objc_direct constructors 2022-11-17 17:05:45 -08:00
Josh Soref
9a6bf46c0f Spelling silgen
* actually
* arbitrary
* cargo-culted
* clazz
* constrained
* continuation
* coordinator
* coroutine
* derivative
* destroyer
* given
* have
* imported
* initialization
* items
* necessarily
* occurring
* omitting
* overridden
* parameter
* possible
* predecessor
* preparation
* resilience
* should
* struct
* that
* the
* throwing
* unexpectedly
* uniqueness
* using
* value
* villain

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-11-09 21:44:17 -05:00
Puyan Lotfi
84a69c4143 [C++-Interop] Import const &T function parameters as @in_guaranteed
When passing value types as a const-ref to a C++ API, ensure that the
caller is tasked with handling the lifetime of the instance passed in.
2022-09-12 16:27:27 -04:00
Meghana Gupta
196994fc11 Fix store_borrow generation in SILGen
This change ensures all store_borrows are ended with an end_borrow, and uses of the store_borrow
destination are all in the enclosing store_borrow scope and via the store_borrow return address.

Fix tests to reflect new store_borrow pattern
2022-08-16 15:08:22 -07:00
John McCall
5519749ade [NFC] Collect protocol decls, not type, in ExistentialLayout
Another thing that will be necessary for correctness with
compositions of parameterized protocols.
2022-04-11 22:15:16 -04:00
Doug Gregor
9343446312 Eliminate undefined behavior where we call next on a past-the-end iterator.
Speculative fix for rdar://90735823.
2022-03-24 10:29:03 -07:00
Robert Widmann
ab44a07045 Convert DeclContext Parameters to their Associated Generic Signatures Instead 2022-03-07 22:54:23 -08:00
Robert Widmann
d6186c9cfb Add a DeclContext Parameter to Opened Archetype Construction
This ensures that opened archetypes always inherit any outer generic parameters from the context in which they reside. This matters because class bounds may bind generic parameters from these outer contexts, and without the outer context you can wind up with ill-formed generic environments like

<τ_0_0, where τ_0_0 : C<T>, τ_0_0 : P>

Where T is otherwise unbound because there is no entry for it among the generic parameters of the environment's associated generic signature.
2022-03-07 22:54:22 -08:00
Joe Groff
48a5089f18 SILGen: Handle objc async bridging when there is a combination of Any and other results.
Generalize the logic here to work with more than one indirect result, or a
combination of indirect result(s) and direct result(s). Fixes rdar://88949633.
2022-02-23 16:29:45 -08:00
John McCall
716f4b9e2f Hop to the generic executor in non-actor-isolated async functions.
Async functions are now expected to set ExpectedExecutor in their
prologue (and, generally, immediately hop to it).  I updated the
prologue code for a bunch of function emission, most of which was
uninteresting.  Top-level code was not returning to the main
executor, which is now fixed; fortunately, we weren't assuming
that we were on the main executor yet.

We had some code that only kicked in when an ExpectedExecutor
wasn't set which made us capture the current executor before
a hop and then return to it later.  This code has been removed;
there's no situation in which save-and-return is the semantically
correct thing to do given the possibility of hop optimization.
I suspect it could also have led to crashes if the current
executor is being kept alive only because it's currently running
code.  If we ever add async functions that are supposed to inherit
their caller's executor, we should have the caller pass the right
executor down to it.

This is the first half of SE-0338; the second, sendability
enforcement, is much more complicated, and Doug has volunteered
to do it.

Fixes rdar://79284465, as well as some tests that were XFAILed
on Windows.
2022-01-27 01:53:19 -05:00
Holly Borla
6cee193fc0 [Type System] When explicit existential types are enabled, wrap Error
in ExistentialType for the type of error values.
2022-01-13 19:30:44 -08:00
Pavel Yaskevich
4860f90fd7 [SIL] Add new flag to SILFunction - IsDistributed
Determines whether given SILFunction represents a distributed
method or its thunk.
2021-12-17 10:52:52 -08:00
Andrew Trick
8f53a927b0 SILGen OSSA support for switch_enum/checked_cast_br, related cleanup
Use APIs for creating terminator results that handle forwarding
ownership consistently.

Add ManagedValue::forForwardedRValue(SILValue) to handle cleanups
consistently based on ownership forwarding.

Add SILGenBuilder::createForwardedTermResult(SILType type) for
creating termator results with the correct ownership and cleanups.

Add SILGenBuilder::createTermResult(SILType type, ValueOwnershipKind
ownership) that handles cleanup based on terminator result ownership.

Add SILGenBuilder::createOptionalSomeResult(SwitchEnumInst) so a lot
of code doesn't need to deal with unwrapping Optional types,
terminator results, and ownership rules.

Replace the existing "phi" APIs with a single
SILGenBuilder::createPhi(SILType, ValueOwnershipKind) that handles
cleanup based on phi ownership.

Phis and terminator results are fundamentally different and need to be handled differently everywhere. Remove the confusion where terminator results were generated with a "phi argument" API.
2021-09-07 22:50:46 -07:00
Konrad `ktoso` Malawski
4f2c2f0a31 [Distributed] move emitDistributedThunk to SILGenDDistributed 2021-08-12 14:04:49 +09:00
Nate Chandler
6eb4f2ca8a [SILGen] Handled transforming Bridged? -> Swift.
Previously, the function emitCBridgedToNativeValue handled three
situations around optionals:
- Bridged?, Native?
- Bridged, Native?
- Bridged, Native

Here, handling for the fourth case
- Bridged?, Native
is added.

To enable this, the number of Optional wrappings that the bridged type
has that the native type does not is passed in to the function.  Then,
in the portions of the function where actual transformations are done,
the values are unwrapped an appropriate number of times.  Mostly that
means force unwrapping N times before doing the transformation.  In the
case of types that conform to _ObjectiveCBridgeable, however, it means
force unwrapping the value N-1 times after doing the transformation
because _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC
performs one layer of unwrapping itself.

rdar://81590807
2021-08-09 19:02:27 -07:00
nate-chandler
8345174bae Merge pull request #38370 from nate-chandler/rdar79383990
[SILGen] Used formal type when bridging completion handler arguments.
2021-07-26 10:57:49 -07:00
Nate Chandler
4cb8453d6a [SILGen] Used formal type when bridging continuation arguments.
Address a FIXME where lowered types rather than formal types were used
when converting from objc to native types which resulted in a failure to
convert block types.
2021-07-24 14:25:26 -07:00
Kavon Farvardin
8af69fb182 SILGen: do not emit hop_to_executor in some objc thunks
An @objc async thunk does not need to perform a
hop_to_executor if the native method the thunk is
wrapping is async, since the native method will do
its own hop.

This redundant hop was causing a crash in SILGen
with async actor-instance isolated @objc methods
declared in an actor, because SILGen was not
prepared to add the hop to  to `self` within
the @objc thunk.

resolves rdar://80130628
2021-07-22 17:08:48 -07:00
Konrad `ktoso` Malawski
3e77eaca10 [Distributed] DA deinit must resign address from the transport 2021-07-01 15:39:55 +09:00
Joe Groff
e39dca4dbf SILGen: Hop to the executor for actor-constrained methods in their @objc async thunks.
If a Swift async method is actor-constrained, then when it's projected into ObjC, it should still
run its task on the correct actor, along with the completion handler that ObjC passes into it.
Fixes rdar://76415650.
2021-06-15 12:09:47 -07:00
Konrad `ktoso` Malawski
3dcb0c230e [Distributed] implement _remote as dynamic functions 2021-06-04 18:06:27 +09:00
Konrad `ktoso` Malawski
6008b32789 [Distributed] initial distributed support, fixed availability (#37650)
* [Distributed] Initial distributed checking

* [Distributed] initial types shapes and conform to DistributedActor

* [Distributed] Require Codable params and return types

* [Distributed] initial synthesis of fields and constructors

* [Distributed] Field and initializer synthesis

* [Distributed] Codable requirement on distributed funcs; also handle <T: Codable>

* [Distributed] handle generic type params which are Codable in dist func

[Distributed] conformsToProtocol after all

* [Distributed] Implement remote flag on actors

* Implement remote flag on actors

* add test

* actor initializer that sets remote flag

[Distributed] conformances getting there

* [Distributed] dont require async throws; cleanup compile tests

* [Distributed] do not synthesize default implicit init, only our special ones

* [Distributed] properly synth inits and properties; mark actorTransport as _distributedActorIndependent

Also:

- do not synthesize default init() initializer for dist actor

* [Distributed] init(transport:) designated and typechecking

* [Distributed] dist actor initializers MUST delegate to local-init

* [Distributed] check if any ctors in delegation call init(transport:)

* [Distributed] check init(transport:) delegation through many inits; ban invoking init(resolve:using:) explicitly

* [Distributed] disable IRGen test for now

* [Distributed] Rebase cleanups

* [Concurrent] transport and address are concurrent value

* [Distributed] introduce -enable-experimental-distributed flag

* rebase adjustments again

* rebase again...

* [Distributed] distributed functions are implicitly async+throws outside the actor

* [Distributed] implicitly throwing and async distributed funcs

* remove printlns

* add more checks to implicit function test

* [Distributed] resolve initializer now marks the isRemote actor flag

* [Distributed] distributedActor_destroy invoked instead, rather than before normal

* [Distributed] Generate distributed thunk for actors

* [distributed] typechecking for _remote_ functions existing, add tests for remote funcs

* adding one XFAIL'ed task & actor lifetime test

The `executor_deinit1` test fails 100% of the time
(from what I've seen) so I thought we could track
and see when/if someone happens to fix this bug.

Also, added extra coverage for #36298 via `executor_deinit2`

* Fix a memory issue with actors in the runtime system, by @phausler

* add new test that now passes because of patch by @phausler

See previous commit in this PR.
Test is based on one from rdar://74281361

* fix all tests that require the _remote_ function stubs

* Do not infer @actorIndependent onto `let` decls

* REVERT_ME: remove some tests that hacky workarounds will fail

* another flaky test, help build toolchain

* [Distributed] experimental distributed implies experimental concurrency

* [Distributed] Allow distributed function that are not marked async or throws

* [Distributed] make attrs SIMPLE to get serialization generated

* [Distributed] ActorAddress must be Hashable

* [Distributed] Implement transport.actorReady call in local init

* cleanup after rebase

* [Distributed] add availability attributes to all distributed actor code

* cleanup - this fixed some things

* fixing up

* fixing up

* [Distributed] introduce new Distributed module

* [Distributed] diagnose when missing 'import _Distributed'

* [Distributed] make all tests import the module

* more docs on address

* [Distributed] fixup merge issues

* cleanup: remove unnecessary code for now SIMPLE attribute

* fix: fix getActorIsolationOfContext

* [Distributed] cmake: depend on _concurrency module

* fixing tests...

* Revert "another flaky test, help build toolchain"

This reverts commit 83ae6654dd.

* remove xfail

* clenup some IR and SIL tests

* cleanup

* [Distributed] fix cmake test and ScanDependencies/can_import_with_map.swift

* [Distributed] fix flags/build tests

* cleanup: use isDistributed wherever possible

* [Distributed] don't import Dispatch in tests

* dont link distributed in stdlib unittest

* trying always append distributed module

* cleanups

* [Distributed] move all tests to Distributed/ directory

* [lit] try to fix lit test discovery

* [Distributed] update tests after diagnostics for implicit async changed

* [Distributed] Disable remote func tests on Windows for now

* Review cleanups

* [Distributed] fix typo, fixes Concurrency/actor_isolation_objc.swift

* [Distributed] attributes are DistributedOnly (only)

* cleanup

* [Distributed] cleanup: rely on DistributedOnly for guarding the keyword

* Update include/swift/AST/ActorIsolation.h

Co-authored-by: Doug Gregor <dgregor@apple.com>

* introduce isAnyThunk, minor cleanup

* wip

* [Distributed] move some type checking to TypeCheckDistributed.cpp

* [TypeCheckAttr] remove extra debug info

* [Distributed/AutoDiff] fix SILDeclRef creation which caused AutoDiff issue

* cleanups

* [lit] remove json import from lit test suite, not needed after all

* [Distributed] distributed functions only in DistributedActor protocols

* [Distributed] fix flag overlap & build setting

* [Distributed] Simplify noteIsolatedActorMember to not take bool distributed param

* [Distributed] make __isRemote not public

* [Distributed] Fix availability and remove actor class tests

* [actorIndependent] do not apply actorIndependent implicitly to values where it would be illegal to apply

* [Distributed] disable tests until issue fixed

Co-authored-by: Dario Rexin <drexin@apple.com>
Co-authored-by: Kavon Farvardin <kfarvardin@apple.com>
Co-authored-by: Doug Gregor <dgregor@apple.com>
2021-05-28 07:22:03 +09:00
Joe Groff
92f56e7ec8 Allow conversions from actor-bound sync function type to unbound async function type.
For `async` function types, an actor constraint can be enforced by the callee by hopping executors,
unlike with `sync` functions, so doesn't need to influence the outward type of the function.

rdar://76248452
2021-05-21 14:17:50 -07:00
Joe Groff
acac14e757 SILGen: Copy the block before detaching a task for async methods called from ObjC.
The block needs to survive long enough for the task to get scheduled. Fixes rdar://76871310.
2021-05-03 15:31:22 -07:00
Richard Wei
fb66de6126 Unify mangling operators for async, @Sendable, @differentiable and @noDerivative.
Repurpose mangling operator `Y` as an umbrella operator that covers new attributes on function types. Free up operators `J`, `j`, and `k`.

```
async ::= 'Ya'                             // 'async' annotation on function types
sendable ::= 'Yb'                          // @Sendable on function types
throws ::= 'K'                             // 'throws' annotation on function types
differentiable ::= 'Yjf'                   // @differentiable(_forward) on function type
differentiable ::= 'Yjr'                   // @differentiable(reverse) on function type
differentiable ::= 'Yjd'                   // @differentiable on function type
differentiable ::= 'Yjl'                   // @differentiable(_linear) on function type
```

Resolves rdar://76299796.
2021-04-07 17:49:10 -07:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Joe Groff
fb199df1c7 SILGen: Support overriding/conforming to ObjC APIs with async error flag arguments. 2021-02-23 08:56:44 -08:00
Erik Eckstein
ec64f2a255 SILLocation: replace CleanupLocation::get(loc) with CleanupLocation(loc)
No need to have a static get function - the constructor can be used directly.
NFC
2021-01-29 20:28:21 +01:00
Erik Eckstein
462e58d3cb SILLocation: a big refactoring and reducing its size from 3 to 2 words
My goal was to reduce the size of SILLocation. It now contains only of a storage union, which is basically a pointer and a bitfield containing the Kind, StorageKind and flags. By far, most locations are only single pointers to an AST node. For the few cases where more data needs to be stored, this data is allocated separately: with the SILModule's bump pointer allocator.

While working on this, I couldn't resist to do a major refactoring to simplify the code:

* removed unused stuff
* The term "DebugLoc" was used for 3 completely different things:
    - for `struct SILLocation::DebugLoc` -> renamed it to `FilePosition`
    - for `hasDebugLoc()`/`getDebugSourceLoc()` -> renamed it to `hasASTNodeForDebugging()`/`getSourceLocForDebugging()`
    - for `class SILDebugLocation` -> kept it as it is (though, `SILScopedLocation` would be a better name, IMO)
* made SILLocation more "functional", i.e. replaced some setters with corresponding constructors
* replaced the hand-written bitfield `KindData` with C bitfields
* updated and improved comments
2021-01-29 20:28:21 +01:00
Joe Groff
0b0264cbdc SILGen: Implement native-to-foreign thunks for async interfaces with nullable completion handlers.
If the ObjC interface is passed a null completion handler, just discard the result of the native async call after it
finishes.
2020-12-15 17:21:35 -08:00
Joe Groff
291b75fcc4 Merge pull request #34953 from jckarter/async-native-to-foreign-thunk
[WIP] SILGen: Implement native-to-foreign thunks for async methods.
2020-12-09 17:00:36 -08:00
Joe Groff
5087e411c2 SILGen: Implement native-to-foreign thunks for async methods.
Bridging an async Swift method back to an ObjC completion-handler-based API requires
that the ObjC thunk spawn a task on which to execute the Swift async API and pass
its results back on to the completion handler.
2020-12-08 10:04:40 -08:00
Kavon Farvardin
60fa93f131 emit hop_to_executor before & sometimes after implicitly-async calls
implicitly-async calls are calls to synchronous
actor-isolated functions. Synchronous functions
cannot perform hop_to_executor, so implicitly
async calls have the convention that the caller
is responsible for switching to the right
executor prior to entering the actor-isolated
callee.

It follows naturally that the caller must then
switch back to the appropriate executor after
the implicitly-async call completed.

Now, if the caller is not isolated to a
_specific_ actor, then we are (currently)
_not_ emitting a hop to go back to the
caller's executor, because that caller's
executor is unspecified (and currently not
accessable in SIL). This behavior may change
in the future; tracked in rdar://71905765
2020-12-07 17:40:17 -08:00
Joe Groff
81b8cdcfd2 SILGen: Update emitForeignToNativeThunk to handle async methods.
So if we use an ObjC imported as async to conform to a Swift protocol, delegate a Swift subclass initializer, etc.,
we generate the conversion thunk to the Swift calling convention for the imported API.
2020-11-18 17:13:20 -08:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Joe Groff
096828e5ab Merge pull request #34358 from jckarter/imported-async-type-lowering
Type lowering and SILGen for imported ObjC async decls.
2020-10-29 08:46:16 -07:00
Slava Pestov
51c1fa9e08 SILGen: Fix assertion failure when emitting foreign-to-native thunk for a method with inout 'self'
We import a C function taking a non-const pointer 'self' parameter
as a mutating method.

The getParameterTypes() helper method in SILGenBridging.cpp would
assert upon encountering the inout 'self' parameter, even though
emitForeignToNativeThunk() would still emit correct code as long
as the 'self' type was not bridged.

Relax the assertion a bit to hopefully still catch bugs where
other parameters are unexpectedly 'inout', but allow it on 'self',
and add a test.

Fixes <rdar://problem/70346482>.
2020-10-27 13:45:54 -04:00
Joe Groff
7ab9e87b68 SILGen: Stub out support for invoking foreign async methods.
Allow SILGen to not crash when invoking foreign async methods by emitting
`undef` for the completion callback going into the call, and for the
results that would be channeled back through awaiting the continuation.
2020-10-27 10:22:32 -07:00
Varun Gandhi
5e9bf1f7c6 [SIL] Store ClangTypeInfo in SILFunctionType.
This patch includes a large number of changes to make sure that:
1. When ExtInfo values are created, we store a ClangTypeInfo if applicable.
2. We reduce dependence on storing SIL representations in ASTExtInfo values.
3. Reduce places where we sloppily create ASTExtInfo values which should
   store a Clang type but don't. In certain places, this is unavoidable;
   see [NOTE: ExtInfo-Clang-type-invariant].

Ideally, we would check that the appropriate SILExtInfo does always store
a ClangTypeInfo. However, the presence of the HasClangFunctionTypes option
means that we would need to condition that assertion based on a dynamic check.
Plumbing the setting down to SILExtInfoBuilder's checkInvariants would be too
much work. So we weaken the check for now; we should strengthen it once we
"turn on" HasClangFunctionTypes and remove the dynamic feature switch.
2020-09-16 10:34:42 -07:00
Varun Gandhi
eeec16f143 [NFC] Remove redundant ExtInfo parameter for getBridgedFunctionType.
At all call-sites, the extInfo passed as the third argument is computed directly
from the second argument, so we compute it directly in getBridgedFunctionType.
2020-08-27 13:14:05 -07:00
Nate Chandler
94b5f76654 Revert "[SIL] Add SILFunctionType flag for async."
This reverts commit 9b8828848d.
2020-08-25 13:37:26 -07:00
Nate Chandler
9b8828848d [SIL] Add SILFunctionType flag for async. 2020-08-19 11:29:58 -07:00