Commit Graph

173 Commits

Author SHA1 Message Date
Erik Eckstein b33ddf2df7 FunctionSignatureOptimization: fix wrong error type when creating a thunk
If the specialized function is generic, the optimization derived the wrong error type when creating a thunk for the specialized function.

Fixes a compiler crash
https://github.com/swiftlang/swift/issues/89617
rdar://178484080
2026-06-08 12:28:58 +02:00
Kavon Farvardin 21b2ebff12 Sema: infer inverses in opaque return types
Opaque return types are special type declarations that have it
own nested generic signature. Thus, given this:
```
  protocol P<A> { associatedtype A: ~Copyable }
  func f<T: ~Copyable>() -> some P<T> {}
```
The generic signature for f is <T where T Escapable>, and
for the opaque return type, its nested signature ends up as
```
  <X where X: P, X.A == T>
```
With SE-503, we will now also expand a default for the suppressed
primary associated type, so the signature after expansion becomes
```
  <X where X: P, X.A == T, X.A: Copyable>
```
It would be smarter to effectively have this rule
```
  X.A == T, T: ~Copyable
  ----------------------
     X.A: ~Copyable
```
where we infer the inverse on X.A to cancel-out the
expanded default X.A: Copyable. We already do this for
two in-scope type parameters, and it would be better if
we did it if one side was out-of-scope, but that would
be source-breaking to do in general.

In the case of opaque return types, the fact that
it has a nested generic signature seems more an
artifact of the implementation. There also is little
risk of source break, as the only kinds of same-type
requirements that can appear are from parameterized
protocol type.

The experimental suppressed associated types prior to
SE-503 wouldn't be broken by this change, as they do
not infer defaults that need suppression, and we only
filter-out requirements from defaults expansion, rather
than explicitly-written ones.

rdar://175500824
2026-05-04 14:49:34 -07:00
Kavon Farvardin 6651cb6389 NFC: refactor the applyInverses bool
There's a need for more control over how default requirements
for conformance to Copyable/Escapable are expanded, and
subsequently how inverses are applied or inferred to cancel-out
those defaults.

The pattern of `/*applyInverses*/BOOL` is insufficient, so this
is a refactoring to grow that into a proper type that carries
an option that can be used in some future scenario about inferring
inverses for opaque return types.
2026-04-29 16:56:00 -07:00
Pavel Yaskevich 60ea598e7f [SIL] Set actor isolation when constructing/initializing SILFunction
Prevents situations when actor isolation ends up not being set
un-intentionally i.e. when cloning, specializating, or creating
thunks.

The thunks get `unspecified` isolation at the moment.
2026-04-21 16:03:35 -07:00
Pavel Yaskevich 883d4ce45b [SIL] Drop optional from SILFunction::getActorIsolation
SIL functions should always have actor isolation set, otherwise
it could lead to wrong deductions in optimization passes like
`SendNonSendable` or `OptimizeHopToExecutor`.

This is a first step to move isolation assignment into
`SILFunction::create`.
2026-04-21 12:21:01 -07:00
Pavel Yaskevich 74dc9c5144 Merge pull request #88460 from xedin/rdar-173640702
[SILOptimizer] Make sure that cloning also transfers the actor isolation
2026-04-15 19:34:50 -07:00
Pavel Yaskevich f01d91f079 [SILOptimizer] Make sure that cloning also transfers the actor isolation
There are passes that rely on the isolation being present after
specialization and other optmizations i.e. `SendNonSendable` which
means the clones need to always preserve the isolation of the
original function.
2026-04-13 17:41:57 -07:00
Pavel Yaskevich 1f8c8e149e [SILOptimizer] Prevent function signature optimization from removing implicit leading isolation parameter
Doing so changes isolation because the invariant is that if
the function is `@caller_isolated` it should have an implicit
leading parameter.
2026-04-13 14:19:04 -07:00
Erik Eckstein 3d84ab5845 ExistentialSpecializer: complete lifetimes in the generated thunk if needed
If the thunk calls to a no-return function, it is ended with an `unreachable`. This may introduce incomplete lifetimes.

Fixes a compiler crash
rdar://169555460
2026-02-06 15:44:52 +01:00
Erik Eckstein 18063707b5 Optimizer: enable complete OSSA lifetimes throughout the pass pipeline
This new OSSA invariant simplifies many optimizations because they don't have to take care of the corner case of incomplete lifetimes in dead-end blocks.

The implementation basically consists of these changes:
* add the lifetime completion utility
* add a flag in SILFunction which tells optimization that they need to run the lifetime completion utility
* let all optimizations complete lifetimes if necessary
* enable the ownership verifier to check complete lifetimes
2026-01-22 17:41:48 +01:00
Erik Eckstein 0f0aa0c17b Optimizer: require that there are no unreachable blocks and infinite loops in OSSA
These two new invariants eliminate corner cases which caused bugs if optimization didn't handle them.
Also, it will significantly simplify lifetime completion.

The implementation basically consists of these changes:
* add a flag in SILFunction which tells optimization if they need to take care of infinite loops
* add a utility to break infinite loops
* let all optimizations remove unreachable blocks and break infinite loops if necessary
* add verification to check the new SIL invariants

The new `breakIfniniteLoops` utility breaks infinite loops in the control flow by inserting an "artificial" loop exit to a new dead-end block with an `unreachable`.
It inserts a `cond_br` with a `builtin "infinite_loop_true_condition"`:
```
bb0:
  br bb1
bb1:
  br bb1              // back-end branch
```
->
```
bb0:
  br bb1
bb1:
  %1 = builtin "infinite_loop_true_condition"() // always true, but the compiler doesn't know
  cond_br %1, bb2, bb3
bb2:                  // new back-end block
  br bb1
bb3:                  // new dead-end block
  unreachable
```
2026-01-22 17:41:23 +01:00
Slava Pestov 819738c83e AST: Rename mapTypeIntoContext() => mapTypeIntoEnvironment(), mapTypeOutOfContext() => mapTypeOutOfEnvironment() 2025-11-12 14:48:19 -05:00
Erik Eckstein 08804d8fa2 ExistentialTransform: fix a wrong result type of open_existential_addr
It needs to be the address type of the opened type and not the object type.
Unfortunately I don't have a test case for this fix.

Fixes a compiler crash
rdar://162149588
2025-10-15 19:25:02 +02:00
Arnold Schwaighofer 25a071efc8 Add experimental feature @inline(always)
The intent for `@inline(always)` is to act as an optimization control.
The user can rely on inlining to happen or the compiler will emit an error
message.

Because function values can be dynamic (closures, protocol/class lookup)
this guarantee can only be upheld for direct function references.

In cases where the optimizer can resolve dynamic function values the
attribute shall be respected.

rdar://148608854
2025-09-30 08:36:26 -07:00
Erik Eckstein bc244d1122 SIL: move the FunctionBuilderTy template argument from TypeSubstCloner to remapParentFunction 2025-09-04 08:15:44 +02:00
Slava Pestov ee440f3c91 AST: Remove MakeAbstractConformanceForGenericType
While the intent behind this functor was noble, it has grown in complexity
considerably over the years, and it seems to be nothing but a source of
crashes in practice. I don't want to deal with it anymore, so I've decided
to just subsume all usages with LookUpConformanceInModule instead.
2025-07-15 16:34:11 -04:00
Meghana Gupta 12f8153b4e Disable function signature optimization on functions with lifetime dependencies 2025-07-10 07:39:52 -07:00
Erik Eckstein 8cab792753 FunctionSignatureOptimization: don't convert indirect @in to @in_guaranteed if the argument is mutated
This fixes a verifier error because an `@in_guaranteed` argument must not be mutated.

https://github.com/swiftlang/swift/issues/81444
rdar://151147971
2025-05-13 18:53:31 +02:00
Ludwig Hollmann 39aa950660 Update file header comments for headers in lib. 2025-05-04 22:26:26 +02:00
Erik Eckstein d225c47d25 AST: rename OpenArchetypeType -> ExistentialArchetypeType
NFC
2025-03-11 20:21:46 +01:00
Meghana Gupta db89c6a753 Merge pull request #77933 from meg-gupta/fixexistential
Fix existential specializer for unowned ownership
2024-12-04 10:40:09 -08:00
Meghana Gupta d033fe8224 Fix existential specializer for unowned ownership 2024-12-03 12:19:52 -08:00
Kuba Mracek 6f4ae28520 [ASTMangler] Pass ASTContext to all instantiations of ASTMangler 2024-12-02 15:01:04 -08:00
Erik Eckstein 44cd8d71d5 SIL: remove some const from decl arguments in SILBasicBlock and SILArgument APIs
It's not needed and would just introduce some const_casts.
2024-10-02 07:10:28 +02:00
Alejandro Alonso 9906db37c7 Fix closures capturing value generics 2024-09-04 15:13:50 -07:00
Alejandro Alonso f4f60f4344 Remove Value requirement Add GenericTypeParamKind 2024-09-04 15:13:43 -07:00
Alejandro Alonso 75c2cbf593 Implement value generics
Some requirement machine work

Rename requirement to Value

Rename more things to Value

Fix integer checking for requirement

some docs and parser changes

Minor fixes
2024-09-04 15:13:25 -07:00
Slava Pestov ff308e9510 AST: Remove TypeBase::openAnyExistentialType() 2024-08-20 12:15:27 -04:00
Slava Pestov 0c2f28fd3d AST: Remove GenericSignature parameter from OpenedArchetypeType::get() 2024-08-20 12:15:27 -04:00
Erik Eckstein 65adc5a582 FunctionSignatureOpts: don't convert non-copyable owned -> guaranteed arguments
It's not safe to insert a compensating release_value at the call site.
This release_value calls the deinit which might have been already de-virtualized in the callee.
2024-08-12 08:54:22 +02:00
Slava Pestov 375363a473 AST: Move global conformance lookup entry points to ConformanceLookup.h 2024-08-08 23:35:58 -04:00
Slava Pestov fae01d9776 AST: Remove ModuleDecl parameter from more places 2024-07-06 12:05:46 -04:00
Tim Kientzle 1098054291 Merge branch 'main' into tbkka-assertions2 2024-06-18 17:52:00 -07:00
Akira Hatanaka d92f181ace Create two versions (for caller and callee) of the functions that answer questions about parameter convention (#74124)
Create two versions of the following functions:

isConsumedParameter
isGuaranteedParameter
SILParameterInfo::isConsumed
SILParameterInfo::isGuaranteed
SILArgumentConvention::isOwnedConvention
SILArgumentConvention::isGuaranteedConvention

These changes will be needed when we add a new convention for
non-trivial C++ types as the functions will return different answers
depending on whether they are called for the caller or the callee. This
commit doesn't change any functionality.
2024-06-18 09:06:09 -07: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
nate-chandler 5b027139d5 Merge pull request #73857 from nate-chandler/rdar125864434
[MoveOnly] Call borrowing methods on existentials.
2024-05-24 12:14:52 -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
Nate Chandler af72e9b909 [ExistentialSpecializer] Move-only must consume.
Bail on non-consuming existential values which are move-only.
Existential specialization requires creating a copy in such cases and
that's illegal for move-only values.
2024-05-23 12:26:43 -07:00
Slava Pestov a1462ef184 SIL: Promote removeDeadBlock() from SILOptimizer to a method on SILBasicBlock 2024-05-21 13:52:58 -04:00
Slava Pestov 7da488663c SILOptimizer: Use getNextDepth()/getMaxDepth() 2024-05-01 12:09:01 -04:00
Ben Barham 9779c18da3 Rename startswith to starts_with
LLVM is presumably moving towards `std::string_view` -
`StringRef::startswith` is deprecated on tip. `SmallString::startswith`
was just renamed there (maybe with some small deprecation inbetween, but
if so, we've missed it).

The `SmallString::startswith` references were moved to
`.str().starts_with()`, rather than adding the `starts_with` on
`stable/20230725` as we only had a few of them. Open to switching that
over if anyone feels strongly though.
2024-03-13 22:25:47 -07:00
Pavel Yaskevich f9ec3b1d7e Merge pull request #71796 from xedin/make-dist-new-requirements-conditionally-available
[Distributed] Make new protocol requirements conditionally available
2024-02-22 15:18:52 -08:00
Pavel Yaskevich 65d164a9c3 Revert "[SIL] Distributed: Remove logic related to ad-hoc requirements from SILFunction"
This reverts commit 1909b12370.
2024-02-21 13:29:47 -08:00
Ben Barham ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Pavel Yaskevich 1909b12370 [SIL] Distributed: Remove logic related to ad-hoc requirements from SILFunction
Ad-hoc requirements are now obsolete by making `remoteCall`,
`record{Argument, ReturnType}`, `decodeNextArgument` protocols
requirements and injecting witness tables for `SerializationRequirement`
conformances during IRGen.
2024-02-12 14:26:30 -08:00
Pavel Yaskevich a6a2a74c9b [SILOptimizer] Distributed: Suppress signature specialization for witnesses with ad-hoc serialization requirement 2024-02-12 14:26:30 -08:00
Slava Pestov af50d7e6b8 AST: Add allowInverses flag to AbstractGenericSignatureRequest 2024-02-05 18:43:06 -05:00
Kavon Farvardin 4eccbe136e [NFC] combine collectExistentialConformances
There are a bunch of static `collectExistentialConformances` copied
around Sema and SILGen that are almost the same, save for whether they
want to permit missing conformances and/or check conditional
conformances.

This commit requestifies and combines all but one of these functions
into a `ModuleDecl::collectExistentialConformances`. The motivation for
this clean-up is another place that will need this procedure.
2024-01-10 19:39:07 -08:00
Doug Gregor 9f890004dd [SIL] Disable optimizations that aren't ready for indirect error results 2023-11-08 13:10:25 -08:00
Yuta Saito c5314bd3af Centralize KeyPath accessor calling convention logic to IRGen
KeyPath's getter/setter/hash/equals functions have their own calling
convention, which receives generic arguments and embedded indices from a
given KeyPath argument buffer.
The convention was previously implemented by:
1. Accepting an argument buffer as an UnsafeRawPointer and casting it to
   indices tuple pointer in SIL.
2. Bind generic arguments info from the given argument buffer while emitting
   prologue in IRGen by creating a new forwarding thunk.

This 2-phase lowering approach was not ideal, as it blocked KeyPath
projection optimization [^1], and also required having a target arch
specific signature lowering logic in SIL-level [^2].

This patch centralizes the KeyPath accessor calling convention logic to
IRGen, by introducing `@convention(keypath_accessor_XXX)` convention in
SIL and lowering it in IRGen. This change unblocks the KeyPath projection
optimization while capturing subscript indices, and also makes it easier
to support WebAssembly target.

[^1]: https://github.com/apple/swift/pull/28799
[^2]: https://forums.swift.org/t/wasm-support/16087/21
2023-09-20 11:25:39 -07:00