Commit Graph

11645 Commits

Author SHA1 Message Date
Andrew Trick
b28cd59dfc [NFC] TypeLowering: add CustomDeinit.
Teach SIL type lowering to recursively track custom vs. default deinit status.

Determine whether each type recursively only has default deinitialization. This
includes any recursive deinitializers that may be invoked by releasing a
reference held by this type.

If a type only has default deinitialization, then the deinitializer cannot
have any semantically-visible side effects. It cannot write to any memory
2025-11-11 17:29:45 -08:00
Meghana Gupta
e2123e1b3b Merge pull request #85362 from meg-gupta/moreborrow
Add SIL verification for borrow and mutate accessors and some other minor fixes
2025-11-10 09:04:28 -08:00
Michael Gottesman
1bb65d8def Merge pull request #85165 from gottesmm/rdar153207557
[sil] Change SILIsolationInfo inference for classmethods to use SILDeclRef instead of using the AST directly.
2025-11-07 02:02:50 -08:00
eeckstein
552b665a9e Merge pull request #85334 from eeckstein/mandatory-destroy-hoisting
Optimizer: make destroy hoisting a mandatory pass
2025-11-07 06:45:03 +01:00
Michael Gottesman
a302d4e627 Merge pull request #85224 from gottesmm/pr-6cb303a9f5f15489fa44c26d00c70155a6d7cc97
[concurrency] Create builtins for invoking specific concurrency runtime functions.
2025-11-06 20:33:16 -08:00
Michael Gottesman
91444dd0bd Delete dead code. 2025-11-06 20:25:23 -08:00
Michael Gottesman
8016bf2332 [sil] Change SILIsolationInfo inference for classmethods to use SILDeclRef instead of using the AST directly.
We are creating/relying on a contract between the AST and SIL... that SILDeclRef
should accurately describe the method/accessor that a class_method is from. By
doing this we eliminate pattern matching on the AST which ties this code too
tightly to the AST and makes it brittle in the face of AST changes. This also
fixes an issue where we were not handling setters correctly.

I am doing this now since it is natural to fix it along side fixing the
ref_element_addr issue in the previous commit since they are effectively doing
the same thing.

rdar://153207557
2025-11-06 20:25:23 -08:00
Michael Gottesman
dfbe7c1e7a [rbi] Refactor out code for handling ref_element_addr so I can use it for class_methods as well.
The two pieces of code are fundamentally doing the same thing so I can reuse the
code. I am doing the refactoring as a separate change so that it is easier to
review.
2025-11-06 19:31:41 -08:00
Michael Gottesman
59e1474b52 Merge pull request #85164 from gottesmm/pr-39de26ee629693f844665c42d2bdff56838838a0
[rbi] When translating a Store, make sure to require src even if the value being stored is Sendable
2025-11-06 19:23:50 -08:00
Anton Korobeynikov
89a7663f1d [AutoDiff] Initial support for differentiation of throwing functions (#82653)
This adds initial support for differentiation of functions that may produce `Error` result. 

Essentially we wrap the pullback into `Optional` and emit a diamond-shape control flow pattern depending on whether the pullback value is available or not. VJP emission was modified to accommodate for this. In addition to this, some additional tricks are required as `try_apply` result is not available in the instruction parent block, it is available in normal successor basic block.

As a result we can now:
- differentiate an active `try_apply` result (that would be produced from `do ... try .. catch` constructions)
- `try_apply` when error result is unreachable (usually `try!` and similar source code constructs)
- Support (some) throwing functions with builtin differentiation operators. stdlib change will follow. Though we cannot support typed throws here (yet)
- Correctly propagate error types during currying around differentiable functions as well as type-checking for `@derivative(of:)` attribute, so we can register custom derivatives for functions producing error result
- Added custom derivative for `Optional.??` operator (note that support here is not yet complete as we cannot differentiate through autoclosures, so `x ?? y` works only if `y` is not active, e.g. a constant value).

Some fixes here and there
2025-11-06 13:12:43 -08:00
Erik Eckstein
04688a69ec Optimizer: Always respect deinit barriers when hoisting destroys.
Also for non-lexical lifetimes
2025-11-06 21:00:45 +01:00
Erik Eckstein
62786b01e2 Optimizer: add the mandatory destroy hoisting pass
It hoists `destroy_value` instructions for non-lexical values.

```
  %1 = some_ownedValue
  ...
  last_use(%1)
  ... // other instructions
  destroy_value %1
```
->
```
  %1 = some_ownedValue
  ...
  last_use(%1)
  destroy_value %1    // <- moved after the last use
  ... // other instructions
```

In contrast to non-mandatory optimization passes, this is the only pass which hoists destroys over deinit-barriers.
This ensures consistent behavior in -Onone and optimized builds.
2025-11-06 21:00:44 +01:00
Meghana Gupta
ff486b742e Update MoveOnlyAddressCheckerUtils for mutate accessors 2025-11-06 10:55:44 -08:00
Michael Gottesman
f0a4571fdd [rbi] Ensure that we properly handle nonisolated(nonsending) for forward declared vars.
rdar://164042741
2025-11-05 13:01:08 -08:00
Michael Gottesman
df6a05c103 [rbi] When translating a Store, make sure to require src even if the value being stored is Sendable
This is important to ensure that we require the base of src if the src is
non-Sendable (e.x.: a non-Sendable box).

rdar://163322459
https://github.com/swiftlang/swift/issues/85107
2025-11-05 13:01:03 -08:00
Michael Gottesman
97b0e2ebae [concurrency] Create builtins for invoking specific concurrency runtime functions.
Specifically:

1. swift_task_addCancellationHandler
2. swift_task_removeCancellationHandler
3. swift_task_addPriorityEscalationHandler
4. swift_task_removePriorityEscalationHandler
5. swift_task_localValuePush
6. swift_task_localValuePop

rdar://109850951
2025-11-05 11:03:44 -08:00
John McCall
13937fdb4e Merge pull request #84528 from rjmccall/async-let-runtime-realism
Model async let begin/finish as builtins in SIL
2025-11-05 10:24:46 -08:00
John McCall
ba47e23f51 Merge pull request #84688 from rjmccall/stack-nesting-2
Rewrite `StackNesting` to use a single-pass algorithm
2025-11-03 20:47:16 -08:00
John McCall
a7d7970e29 Turn finishAsyncLet into a builtin.
This is necessary because we need to model its stack-allocation
behavior, although I'm not yet doing that in this patch because
StackNesting first needs to be taught to not try to move the
deallocation.

I'm not convinced that `async let` *should* be doing a stack allocation,
but it undoubtedly *is* doing a stack allocation, and until we have an
alternative to that, we will need to model it properly.
2025-11-03 16:33:40 -08:00
John McCall
cd67912a50 Remove the deprecated and unused endAsyncLet builtin. 2025-11-03 13:45:18 -08:00
John McCall
1d95fe14de Remove the deprecated and unused startAsyncLet builtin 2025-11-03 13:44:58 -08:00
John McCall
b0df998572 Fix ClosureLifetimeFixup to insert code after all paired endAsyncLetLifetimes 2025-11-03 13:44:18 -08:00
John McCall
8d231d20c6 Rewrite StackNesting to be a non-iterative single-pass algorithm.
The previous algorithm was doing an iterative forward data flow analysis
followed by a reverse data flow analysis. I suspect the history here is that
it was a reverse analysis, and that didn't really work for infinite loops,
and so complexity accumulated.

The new algorithm is quite straightforward and relies on the allocations
being properly jointly post-dominated, just not nested. We simply walk
forward through the blocks in consistent-with-dominance order, maintaining
the stack of active allocations and deferring deallocations that are
improperly nested until we deallocate the allocations above it. The only
real subtlety is that we have to delay walking into dead-end regions until
we've seen all of the edges into them, so that we can know whether we have
a coherent stack state in them. If the state is incoherent, we need to
remove any deallocations of previous allocations because we cannot talk
correctly about what's on top of the stack.

The reason I'm doing this, besides it just being a simpler and hopefully
faster algorithm, is that modeling some of the uses of the async stack
allocator properly requires builtins that cannot just be semantically
reordered. That should be somewhat easier to handle with the new approach,
although really (1) we should not have runtime functions that need this and
(2) we're going to need a conservatively-correct solution that's different
from this anyway because hoisting allocations is *also* limited in its own
way.

I've attached a rather pedantic proof of the correctness of the algorithm.

The thing that concerns me most about the rewritten pass is that it isn't
actually validating joint post-dominance on input, so if you give it bad
input, it might be a little mystifying to debug the verifier failures.
2025-11-03 11:51:17 -08:00
Aidan Hall
0b342ded1c Merge pull request #85237 from aidan-hall/dedup-erase
DebugUtils: Remove eraseFromParentWithDebugInsts
2025-11-03 14:46:18 +00:00
Doug Gregor
ba507ab822 Merge pull request #85203 from DougGregor/clang-decl-asmname 2025-11-01 20:46:50 -07:00
Michael Gottesman
760a6fa776 Merge pull request #82427 from gottesmm/pr-9d8b2e21000560a9c3a3b0143c3fb3b22a0ca75a
[rbi] Remove code that caused us to misidentify certain captured parameters as sending.
2025-10-31 20:28:59 -07:00
Aidan Hall
b353bb302f DebugUtils: Remove eraseFromParentWithDebugInsts
There is another near-identical function in DebugOptUtils.h that can be used
everywhere this function is used, and offers more flexibility in its callback
interface.
2025-10-31 13:47:22 +00:00
Aidan Hall
8632e58825 Create Pack Specialisation pass 2025-10-30 14:28:16 +00:00
Doug Gregor
0ac8a83051 Use correct IR name for AutoDiff mangling 2025-10-29 19:35:57 -07:00
Doug Gregor
f267f62f65 [SILGen] Consistently use SIL asmname for foreign function/variable references
Whenever we have a reference to a foreign function/variable in SIL, use
a mangled name at the SIL level with the C name in the asmname
attribute. The expands the use of asmname to three kinds of cases that
it hadn't been used in yet:

* Declarations imported from C headers/modules
* @_cdecl @implementation of C headers/modules
* @_cdecl functions in general

Some code within the SIL pipeline makes assumptions that the C names of
various runtime functions are reflected at the SIL level. For example,
the linking of Embedded Swift runtime functions is done by-name, and
some of those names refer to C functions (like `swift_retain`) and
others refer to Swift functions that use `@_silgen_name` (like
`swift_getDefaultExecutor`). Extend the serialized module format to
include a table that maps from the asmname of functions/variables over
to their mangled names, so we can look up functions by asmname if we
want. These tables could also be used for checking for declarations
that conflict on their asmname in the future. Right now, we leave it
up to LLVM or the linker to do the checking.

`@_silgen_name` is not affected by these changes, nor should it be:
that hidden feature is specifically meant to affect the name at the
SIL level.

The vast majority of test changes are SIL tests where we had expected
to see the C/C++/Objective-C names in the tests for references to
foreign entities, and now we see Swift mangled names (ending in To).
The SIL declarations themselves will have a corresponding asmname.

Notably, the IRGen tests have *not* changed, because we generally the
same IR as before. It's only the modeling at the SIL lever that has
changed.

Another part of rdar://137014448.
2025-10-29 19:35:55 -07:00
Aidan Hall
c7af4c584e Bridging: APIs for PackSpecialization pass 2025-10-26 13:44:34 +00:00
Kavon Farvardin
03d61ed75a Merge pull request #85090 from kavon/manual-ownership/usability-fixes-6
ManualOwnership: provide ability to apply to entire compilation unit
2025-10-25 00:15:03 -07:00
nate-chandler
b4777083b0 Merge pull request #85128 from nate-chandler/rdar162922634
[CastOptimizer] Use TypeConverter to lower type.
2025-10-24 23:47:03 -07:00
Anton Korobeynikov
186f88bead [AutoDiff] Fix two issues related with emission of differentiability witnesses (#80983)
1. When differentiable nested function (closure) is specialized by capture promotion pass ensure we generate a differentiability witness for the specialized function as well. Ensure the original witness is removed if the original function becomes dead. 
2. Differentiability witnesses for a function could originate either from its `@differentiable` attribute or from explicit `@derivative(of:)` attribute on the derivative. In the latter case the derivative itself might not be emitted, while original function is (e.g. original function is `@inlineable`, but derivative is `@usableFromInline`). Previously both cases were handled only when function body was emitted. As a result we missed witness in the aforementioned case. Ensure the
differentiability witness originating from `@derivative(of:)` is emitted even if we're not going to emit body of the derivative.

Fixes #59135
2025-10-24 20:02:08 -07:00
Kavon Farvardin
6b858b411c ManualOwnership: introduce 'DynamicExclusivity'
We can add warnings about dynamic exclusivity
checks that may happen on an access, with
explainers about why they happen for safety.
2025-10-24 16:59:44 -07:00
Nate Chandler
41a7d7cab9 [CastOptimizer] Use TypeConverter to lower type, 2 2025-10-24 15:34:35 -07:00
Nate Chandler
ef6bd64e7f [CastOptimizer] Use TypeConverter to lower type.
rdar://162922634
2025-10-24 15:34:09 -07:00
Kuba (Brecka) Mracek
eb23d3bc0a Merge pull request #85074 from kubamracek/section
SE-0492: Stabilize @_section/@_used into @section/@used
2025-10-24 12:29:48 -07:00
Joe Groff
b219d4089c Merge pull request #85077 from jckarter/moveonly-after-definit-cleanup
DI: Place cleanups for partially-initialized non-`Copyable` values on the `mark_unresolved_noncopyable` marker.
2025-10-24 07:33:30 -07:00
Kavon Farvardin
38c61d7dd6 Merge pull request #85054 from kavon/opaque-values/fixes-3
OpaqueValues: add support for property wrappers
2025-10-23 22:18:54 -07:00
Michael Gottesman
4946256c61 Merge pull request #85064 from gottesmm/pr-a4b0eaddab3318c277ebf3a9080a8bcfc79a3ba6
[rbi] Prefer field specific isolation over nominal type isolation when inferring isolation.
2025-10-23 18:17:51 -07:00
Kavon Farvardin
19bd65c89b OpaqueValues: add support for property wrappers
resolves rdar://163071245
2025-10-23 16:31:01 -07:00
Joe Groff
ff627e5392 DI: Place cleanups for partially-initialized non-Copyable values on the mark_unresolved_noncopyable marker.
This ensures that move checking sees the cleanups when determining a value's lifetime and doesn't
try to insert its own cleanup leading to a double destroy. Fixes #85063 | rdar://163194098.
2025-10-23 13:11:19 -07:00
Meghana Gupta
6734d4a4e6 Disable GenericSpecializer for @guaranteed results 2025-10-23 05:19:15 -07:00
Meghana Gupta
01680de084 Fixup ownership of borrow accessor results
SILGen may produce a borrow accessor result from within a local borrow scope. Such as:

```
  %ld = load_borrow %self
  %fwd = unchecked_ownership %ld
  %ex = struct_extract %fwd, #Struct.storedProperty
  end_borrow %ld
  return %ex
```

This is illegal OSSA, since the return uses a value outside it's borrow scope.

Add a new SILGenCleanup transform, to turn this into valid OSSA:

```
  %ld = load_borrow %self
  %ex = struct_extract %ld, #Struct.storedProperty
  return_borrow %ex from_scopes %ld
```
2025-10-23 05:19:11 -07:00
Meghana Gupta
1dc5c9611c Intoduce unchecked_ownership instruction in raw SIL
This instruction can be used to disable ownership verification on it's result and
will be allowed only in raw SIL.

Sometimes SILGen can produce invalid ownership SSA, that cannot be resolved until
mandatory passes run. We have a few ways to piecewise disable verification.
With unchecked_ownership instruction we can provide a uniform way to disable ownership
verification for a value.
2025-10-23 05:19:08 -07:00
Meghana Gupta
a3aed17d63 Disable inlining borrow accessors with return_borrow instruction 2025-10-23 05:19:06 -07:00
Meghana Gupta
e116df3628 Introduce return_borrow instruction 2025-10-23 05:18:59 -07:00
Kuba Mracek
adeb40f261 SE-0492: Stabilize @_section/@_used into @section/@used
Removes the underscored prefixes from the @_section and @_used attributes, making them public as @section and @used respectively. The SymbolLinkageMarkers experimental feature has been removed as these attributes are now part of the standard language. Implemented expression syntactic checking rules per SE-0492.

Major parts:
- Renamed @_section to @section and @_used to @used
- Removed the SymbolLinkageMarkers experimental feature
- Added parsing support for the old underscored names with deprecation warnings
- Updated all tests and examples to use the new attribute names
- Added syntactic validation for @section to align with SE-0492 (reusing the legality checker by @artemcm)
- Changed @DebugDescription macro to explicitly use a tuple type instead of type inferring it, to comply with the expression syntax rules
- Added a testcase for the various allowed and disallowed syntactic forms, `test/ConstValues/SectionSyntactic.swift`.
2025-10-22 16:05:39 -07:00
Michael Gottesman
c14e4b0376 [rbi] Prefer field specific isolation over nominal type isolation when inferring isolation.
Specifically given a nominal type like the following:

```swift
@MainActor
struct Foo {
  @CustomActor var ns: NonSendableKlass
}
```

the isolation for ns should be CustomActor not MainActor.

rdar://160603379
2025-10-22 09:33:44 -07:00