Commit Graph

413 Commits

Author SHA1 Message Date
nate-chandler
9fe43836f6 Merge pull request #83907 from nate-chandler/rdar158149082
[AllocBoxToStack] Don't destroy in dead-ends.
2025-08-28 13:36:28 -07:00
Jakub Florek
07ac8b3478 Add new loop invariant code motion. 2025-08-28 21:00:33 +01:00
Jakub Florek
e3140e0ae0 Add new generalized cloner. 2025-08-28 20:57:57 +01:00
Erik Eckstein
8e33487471 DeinitDevirtualizer: de-virtualize deinits of builtin "destroyArray" 2025-08-28 08:05:28 +02:00
Nate Chandler
1eafced6a2 [AllocBoxToStack] Don't destroy in dead-ends.
It is valid to leak a value on paths into dead-end regions.
Specifically, it is valid to leak an `alloc_box`.  Thus, "final
releases" in dead-end regions may not destroy the box and consequently
may not release its contents.  Therefore it's invalid to lower such final
releases to `dealloc_stack`s, let alone `destroy_addr`s.  The in-general
invalidity of that transformation results in miscompiling whenever a box
is leaked and its projected address is used after such final releases.

Fix this by not treating final releases as boundary markers of the
`alloc_box` and not lowering them to `destroy_addr`s and
`dealloc_stack`s.

rdar://158149082
2025-08-27 17:03:48 -07:00
Nate Chandler
74528eef8c [NFC] OptUtils: Promote isInLoop to internal.
It will be used by both AllocBoxToStack in addition to StackPromotion
and for the same reason.
2025-08-27 17:03:47 -07:00
Nate Chandler
f94168c875 [AllocBoxToStack] Restore isDeadEnd check.
The rewrite was missing the intentional omission of `dealloc_stack`s
corresponding to `[dead_end]` `dealloc_box`es.  Add the necessary
bridging to get to parity with the original.

Without this check, `dealloc_box [dead_end]`s are promoted to
`dealloc_stack`s but the memory projected out of such `alloc_box`s need
not be valid.

rdar://159271158
2025-08-27 17:02:27 -07:00
Aidan Hall
53028abea9 Merge pull request #83665 from aidan-hall/fix-effects
ComputeSideEffects: compute properties even if function has an effect attribute
2025-08-27 10:34:53 +01:00
Daniil Kovalev
ae2b46e263 [AutoDiff][gardening] Auto-format ClosureSpecialization.swift (#83925)
Auto-formatting is done as a prerequisite for the ongoing series of
patches resolving #68944.
2025-08-27 06:12:47 +00:00
Aidan Hall
6a263f8ddb ComputeSideEffects: Compute for functions with effect attributes
After computing side effects, we also remove any global or argument effects that
are computed to happen, but are defined not to, based on the effect attribute.

This allows us to compute the deinit_barrier effect for such functions, fixing
the test case here: rdar://155870190

This supercedes #38324.
2025-08-22 11:42:09 +01:00
Doug Gregor
7a196ac3ba Merge pull request #83739 from DougGregor/embedded-weak-definitions-of-imports
[Embedded] Emit weak definitions for imported symbols
2025-08-17 20:25:02 -07:00
Doug Gregor
c91a4822d3 Serialize the "markedAsUsed" bit for SILGlobalVariable 2025-08-17 15:25:50 -07:00
Andrew Trick
288cef1532 LifetimeDependenceScopeFixup: extend store_borrow allocations
Extend temporary allocations (sink dealloc_stacks) initialized by a store_borrow
across lifetime dependent uses.

Fixes rdar://143159873 ([nonescapable] extend rvalue lifetimes when they are the source of a dependency)
2025-08-14 10:13:55 -07:00
Andrew Trick
b3e169be5e [NFC] Rename a variable for clarity. 2025-08-14 09:08:11 -07:00
Andrew Trick
eb1d5f484c [NFC] SwiftCompilerSources: add a correctly named filterUsers API
Rename existing filterUsers to filterUses.
2025-08-14 09:08:11 -07:00
Erik Eckstein
eaf38da903 InitializeStaticGlobals: support non-loadable enums
TODO: we don't support non-loadable enum cases with payload, yet, because IRGen support is missing.
2025-08-03 17:25:43 +02:00
Erik Eckstein
c849c7cdae InitializeStaticGlobals: support initializing globals with @_rawLayout types, like Atomic
Look through `@_rawLayout` projections, which "type casts" a raw-layout struct to it's content, which must match the like-type of the raw-layout, e.g.

```
@_rawLayout(like: T)
struct S {}

  %2 = builtin "addressOfRawLayout"<S>(%1 : $*S) : $Builtin.RawPointer
  %3 = pointer_to_address %2 to $*T
```
2025-08-03 17:25:43 +02:00
Erik Eckstein
41a6b8e257 SwiftCompilerSources: move SIL-related Context APIs from Optimizer to the SIL module 2025-07-28 14:19:11 +02:00
nate-chandler
d6b5c4fb99 Merge pull request #82798 from eeckstein/fix-let-property-lowering
LetPropertyLowering: remove redundant phis after ssa-update
2025-07-08 18:07:08 -07:00
Andrew Trick
14e0fe8d1f Merge branch 'main' into reassign-immortal 2025-07-08 08:20:18 -07:00
Daniil Kovalev
5528cf1cc4 [AutoDiff] Run AutoDiff closure spec pass for all VJPs (#81548)
Previously, AutoDiff closure specialization pass was triggered only on
VJPs containing single basic block. However, the pass logic allows
running on arbitrary VJPs. This PR enables the pass for all VJPs
unconditionally. So, if the pullback corresponding to multiple-BB VJP
accepts some closures directly as arguments, these closures might become
specialized by the pass. Closures passed via payload of branch tracing
enum are not specialized - this is subject for future changes.

The PR contains several commits.
1. The thing named "call site" in the code is partial_apply of pullback
corresponding to the VJP. This might appear only once, so we drop
support for multiple "call sites".
2. Enhance existing SILOptimizer tests for the pass.
3. Add validation-tests for single basic block case.
4. The change itself - delete check against single basic block.
5. Add validation-tests for multiple basic block case.
6. Add SILOptimizer tests for multiple basic block case.
2025-07-07 13:00:14 +00:00
Andrew Trick
ac94d7df1d Fix LifetimeDependenceDiagnostics: allow inout assignment to Void.
Bypess lifetime dependence diagnostics completely for immortal values. We did
not do this initially because we wanted to potentially consider a value with a missing
dependency to mean that it could not escape the current function. But now we use
`Void` as a stand-in for immortal values.

This is needed for reassigning a Span/MutableSpan to an empty, immortal
Span:

    func inoutToImmortal(_ s: inout RawSpan) {
      let tmp = RawSpan(_unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0))
      s = _overrideLifetime(tmp, borrowing: ())
    }

Fixes rdar://152572002 ([GH:#81976] Cannot reinitialize inout parameter of type
`MutableSpan<T>?`)
2025-07-07 00:16:49 -07:00
Erik Eckstein
81a4f7a84e LetPropertyLowering: remove redundant phis after ssa-update
This is needed after running the SSAUpdater, because the updater can insert unnecessary phis in the middle of the original liverange of a value.

Fixes an ownership error.
rdar://153229472
2025-07-04 11:10:27 +02:00
Erik Eckstein
80ed35b38d MandatoryAllocBoxToStack: also handle new specialized functions
Add new created specializations to the worklist so that those are optimized as well.

rdar://154686063, rdar://154713388
2025-07-02 19:10:47 +02:00
Andrew Trick
fe9c0dd735 Fix LocalVariableUtils switch_enum_addr.
switch_enum_addr was being treated like a store instruction, which killed
the local enum's liveness. This could result local variable analysis reporting a
shorter lifetime for the local.

This showed up as a missing exclusivity diagnostic because an access scope was
not fully extended across a dependent local variable of Optional type.

This prevents the following pattern from miscompiling. It should report an exclusivity violation:

  var mutableView = getOpaqueOptionalView(holder: &holder)!
  mutate(&holder)
  mutableView.modify()

Fixes rdar://151231236 ([~Escapable] Missing 'overlapping acceses' error when
called from client code, but exact same code produces error in same module)
2025-06-28 09:30:17 -07:00
Erik Eckstein
abbe0e8e95 TempLValueElimination: fix a stupid bug when combining copy_addr with a following destroy_addr
This peephole optimization also combined the instructions if the `destroy_addr` appears before the `copy_addr` in the same basic block.

https://github.com/swiftlang/swift/issues/82466
rdar://154236276
2025-06-25 08:09:55 +02:00
Andrew Trick
7c5d4b8b6d Fix MutableSpan exclusive access to unsafe pointers
This fix enables exclusive access to a MutableSpan created from an UnsafeMutablePointer.

The compiler has a special case that allows MutableSpan to depend on a mutable
pointer *without* extending that pointer's access scope. That lets us implement
standard library code like this:

    mutating public func extracting(droppingLast k: Int) -> Self {
      //...
      let newSpan = unsafe Self(_unchecked: _pointer, byteCount: newCount)
      return unsafe _overrideLifetime(newSpan, mutating: &self)

Refine this special case so that is does not apply to inout parameters where the
programmer has an expectation that the unsafe pointer is not copied when being
passed as an argument. Now, we safely get an exclusivity violation when creating
two mutable spans from the same pointer field:

    @lifetime(&self)
    mutating func getSpan() -> MutableSpan<T> {
      let span1 = makeMutableSpan(&self.pointer)
      let span2 = makeMutableSpan(&self.pointer) // ERROR: overlapping access
      return span1
    }

If we don't fix this now, it will likely be source breaking in the future.

Fixes rdar://153745332 (Swift allows constructing two MutableSpans to the same underlying pointer)
2025-06-24 00:10:06 -07:00
Andrew Trick
36d2b5bee4 Fix lifetime dependence diagnostics on Void types.
Allow a dependence on Void to be considered immortal. This is the ultimate
override in cases where no other code pattern is supported yet.
2025-06-23 00:33:57 -07:00
eeckstein
1d3895610e Merge pull request #82349 from eeckstein/alloc-box-to-stack
Optimizer: re-implement and improve the AllocBoxToStack pass
2025-06-21 07:28:18 +02:00
Erik Eckstein
6714a72256 Optimizer: re-implement and improve the AllocBoxToStack pass
This pass replaces `alloc_box` with `alloc_stack` if the box is not escaping.
The original implementation had some limitations. It could not handle cases of local functions which are called multiple times or even recursively, e.g.

```
public func foo() -> Int {
  var i = 1

  func localFunction() { i += 1 }

  localFunction()
  localFunction()
  return i
}

```

The new implementation (done in Swift) fixes this problem with a new algorithm.
It's not only more powerful, but also simpler: the new pass has less than half lines of code than the old pass.

The pass is invoked in the mandatory pipeline and later in the optimizer pipeline.
The new implementation provides a module-pass for the mandatory pipeline (whereas the "regular" pass is a function pass).
This is required because the mandatory pass needs to remove originals of specialized closures, which cannot be done from a function-pass.
In the old implementation this was done with a hack by adding a semantic attribute and deleting the function later in the pipeline.

I still kept the sources of the old pass for being able to bootstrap the compiler without a host compiler.

rdar://142756547
2025-06-20 08:15:04 +02:00
Erik Eckstein
63cb683cb7 SIL: improve some Location APIs
* rename `var autoGenerated` -> `var asAutoGenerated`
* add `var asCleanup`
* add `func withScope`
2025-06-20 08:15:00 +02:00
Erik Eckstein
4212c611e5 Optimizer: add Context.createSpecializedFunctionDeclaration
Originally this was a "private" utility for the ClosureSpecialization pass.
Now, make it a general utility which can be used for all kind of function specializations.
2025-06-20 08:15:00 +02:00
Erik Eckstein
57e08affcb SIL: add ApplySite.calleeArgument(of operand: Operand, in callee: Function)
This is a safer API than using
```
  let argIdx = applySite.calleeArgumentIndex(of: op)
  let arg = callee.arguments[argIdx]
```
because there is no potential misuse of the index.
2025-06-20 08:14:59 +02:00
Erik Eckstein
094b246874 SIL: FunctionArgument.copyFlags needs a MutatingContext argument
SIL may only be modified through a MutatingContext. Otherwise analysis notifications may get lost.
2025-06-20 08:14:59 +02:00
Anthony Latsis
722bc0f086 ASTBridging: Bridge swift::DiagID directly 2025-06-19 12:29:27 +01:00
Andrew Trick
5b5f370ce1 LifetimeDependenceScopeFixup: crash handling dead-end coroutine
When extending a coroutine, handle the end_borrow instruction used to end a
coroutine lifetime at a dead-end block.

Fixes rdar://153479358 (Compiler crash when force-unwrapping optional ~Copyable type)
2025-06-16 21:43:44 -07:00
Meghana Gupta
8396a6d8c0 Fix an inliner crash when inlining begin_apply with scoped lifetime dependence
LifetimeDependenceInsertion inserts mark_dependence on token result of a begin_apply
when it yields a lifetime dependent value. When such a begin_apply gets inlined,
the inliner can crash because of the remaining uses of the token result.

Fix this by inserting mark_dependence on parameter operands that are lifetime dependence sources
and deleting the mark_dependence on token results in the inliner.

Fixes rdar://151568816
2025-06-12 01:35:36 -07:00
Valeriy Van
dd2468cf58 Fix typo in local var 2025-06-08 11:27:30 +03:00
Valeriy Van
949c2bad67 Fix some typos in SwiftCompilerSources/Sources 2025-06-08 11:22:45 +03:00
eeckstein
a33ff9879a Merge pull request #81969 from eeckstein/temp-lvalue-elimination
Optimizer: improve TempLValueOpt
2025-06-06 15:30:29 +02:00
Andrew Trick
227f8028e8 LifetimeDependenceScopeFixup: handle yielded value copies.
When extending an access scope over a coroutines, instead of simply
considering the lifetime of the coroutine scope, recurse through all
uses of yielded values. They may be copyable, non-Escapable values
that depend on the coroutine operand.

Fixes rdar://152693622 (Extend coroutines over copied yields)
2025-06-05 20:21:40 -07:00
Andrew Trick
95f7a12c98 [NFC] LifetimeDependence: fix internal debug output 2025-06-05 20:09:06 -07:00
Erik Eckstein
2b9b2d243c Optimizer: improve TempLValueOpt
* re-implement the pass in swift
* support alloc_stack liveranges which span over multiple basic blocks
* support `load`-`store` pairs, copying from the alloc_stack (in addition to `copy_addr`)

Those improvements help to reduce temporary stack allocations, especially for InlineArrays.

rdar://151606382
2025-06-05 06:45:18 +02:00
Erik Eckstein
6428a7b50c Optimizer: move protocol CopyLikeInstruction from TempRValueElimination to OptUtils, so that other passes can use it as well 2025-06-05 06:45:18 +02:00
Andrew Trick
c030b78c7d LifetimeDependenceDiagnostics: fix source loc for implicit variables
Diagnostics on an indirect result ($return_value) did not report a source
location.
2025-06-04 11:41:15 -07:00
Andrew Trick
1d09c06ab1 LifetimeDependenceDiagnostics: diagnose indirect closure results.
Add support for diagnosing calls to closures that return a generic
non-Escapable result.

Closures do not yet model lifetime dependencies. The diagnostics have
a special case for handling nonescaple result with no lifetime
dependence, but it previously only handled direct results. This fix handles
cases like the following:

    func callIndirectClosure<T>(f: () -> NE<T>) -> NE<T> {
      f()
    }

Fixes rdar://134318846 ([nonescapable] diagnose function types with nonescapable results)
2025-06-04 11:40:42 -07:00
Andrew Trick
51090b62bb LifetimeDependenceInsertion: allow dependency on Builtin.addressof()
This mostly makes it easier to test dependency corner cases. The analysis still
doesn't recognize UnsafeRawPointer.init(), so regular users still need to use
_overrideLifetime.

Fixes rdar://137608270 ([borrows] Add Builtin.addressof() support
for @addressable arguments)
2025-05-29 10:27:03 -07:00
Erik Eckstein
198d4ab0bb Optimizer: run TempRValueElimination also at Onone
Introduce a new pass MandatoryTempRValueElimination, which works as the original TempRValueElimination, except that it does not remove any alloc_stack instruction which are associated with source variables.

Running this pass at Onone helps to reduce copies of large structs, e.g. InlineArrays or structs containing InlineArrays.
Copying large structs can be a performance problem, even at Onone.

rdar://151629149
2025-05-23 18:56:56 +02:00
Erik Eckstein
d10602ea28 SIL: improve and fix mark-dependence instruction APIs
* Move the mutating APIs into Context.swift, because SIL can only be mutated through a MutatingContext
* move the `baseOperand` and `base` properties from the instruction classes to the `MarkDependenceInstruction` protocol
* add `valueOrAddressOperand` and `valueOrAddress` in the `MarkDependenceInstruction` protocol
2025-05-23 18:53:57 +02:00
eeckstein
efa07a7557 Merge pull request #81702 from eeckstein/fix-test
InitializeStaticGlobals: handle `InlineArray.init(repeating:)` also for arm64_32
2025-05-23 00:55:20 +02:00