Commit Graph

1457 Commits

Author SHA1 Message Date
Andrew Trick
ed158ffdcb [NFC] LifetimeDependence computeAddressRange comments and test case
(cherry picked from commit ac9a5b6d164b3824fdfcbf638af8724ec6e2751c)
2025-10-03 20:50:02 -07:00
Andrew Trick
6039ca2240 LifetimeDependenceDiagnostics: extend temp alloc to unreachable.
When a non-Escapable value depends on the address of a trivial value, we use a
special computeAddressableRange analysis to compute the trivial value's
scope. Extend that analysis to include unreachable paths.

Fixes this pattern:

    inlineStorage.span.withUnsafeBytes

where inlineStorage is a trivial type defined in the user module. This
does not reproduce directly with InlineArray, but it is a problem for
user modules that have their own trivial wrapper around an InlineArray.

Fixes rdar://161630684 (Incorrect diagnostic: lifetime-dependent value escapes its scope)

(cherry picked from commit 98b7d5906cffa0cf7a481ba47a6acd746e388ac9)
2025-10-03 20:50:02 -07:00
Andrew Trick
57a3acf412 Comment LifetimeDependenceScopeFixup. Explain unreachable paths.
(cherry picked from commit 72ea350a9d38227dec3908521730552fe50a1909)
2025-10-03 20:50:02 -07:00
Erik Eckstein
00f83dd85b fix handling of large indices in SmallProjectionPath
* Fix the right shift operator which didn't work if the number of bits is exactly 64
* Detect overflow when combining indices

Such large indices usually don't appear in real code, except in internal String operations where (potentially large) integer values are treated as pointers.

Fixes a compiler crash
https://github.com/swiftlang/swift/issues/84372
rdar://160863199
2025-09-23 07:35:33 +02:00
Andrew Trick
d2dea322e2 Fix computeAddressableRange, test, and comment.
Address review feedback from the previous commit.

(cherry picked from commit 712d39a624)
2025-09-10 21:32:56 -07:00
Andrew Trick
4f0dfc13ea LifetimeDependenceScopeFixup: extend temporary stack allocations
When the source of a lifetime dependency is a stack-allocated address, extend
the stack allocation to cover all dependent uses.

This avoids miscompilations for "addressable" dependencies which arise in code
built with -enable-experimental-feature AddressableTypes or
AddressableParameters. It is always an error for SILGen to emit the alloc_stack
in such cases. Nonetheless, we want to handle these unexpected cases gracefully
in SIL as a diagnostic error rather than allowing a miscompile.

Fixes rdar://159680262 ([nonescapable] diagnose dependence on a
temporary copy of a global array)

(cherry picked from commit 7dfd1057111425d3902b1b17cd2129c94f974027)
2025-09-10 21:32:56 -07:00
Andrew Trick
45a98a7209 LifetimeDependenceDiagnostics: check for on-stack trivial copies
Add a diagnostic to catch addressable dependencies on a trivial values that have
been copied to a temporary stack location. SILGen should never copy the source
of an addressable dependency to a temporary stack location, but this diagnostic
catches such compiler bugs rather than allowing miscompilation.

Fixes rdar://159680262 ([nonescapable] diagnose dependence on a temporary copy
of a global array)
2025-09-10 21:32:55 -07:00
Andrew Trick
b9c0292e33 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)

(cherry picked from commit 288cef1532)
2025-09-10 21:32:55 -07:00
Andrew Trick
cb438befb0 [NFC] Rename a variable for clarity.
(cherry picked from commit b3e169be5e)
2025-09-10 21:32:55 -07:00
Erik Eckstein
77a2954751 Optimizer: fix handling of dependent existential archetypes in alloc_stack and apply simplification
When replacing an opened existential type with the concrete type, we didn't consider that the existential archetype can also be a "dependent" type of the root archetype.
For now, just bail in this case. In future we can support dependent archetypes as well.

Fixes a compiler crash.
rdar://158594365
2025-08-27 17:14:51 +02:00
Erik Eckstein
9dfe54075a AST: add Type.interfaceTypeOfArchetype and some related APIs 2025-08-27 16:52:28 +02:00
Erik Eckstein
0f485b6efc Swift AST: add some Type APIs 2025-08-27 16:52:19 +02:00
Andrew Trick
d03fd679b8 Merge pull request #82797 from atrick/62-local-deadend
[6.2] Improve LocalVariableUtils.gatherKnownLifetimeUses; dead ends
2025-07-07 08:17:15 -07:00
eeckstein
8e96e1a0fc Merge pull request #82800 from eeckstein/fix-metatype-in-mpo-6.2
[6.2] MandatoryPerformanceOptimizations: don't specialize vtables for thin class metatype instructions
2025-07-07 16:05:22 +02:00
eeckstein
092441e60a Merge pull request #82799 from eeckstein/fix-escape-utils-6.2
[6.2] EscapeUtils: consider that a pointer argument can escape a function call
2025-07-07 16:04:57 +02:00
Erik Eckstein
972fde7e70 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 20:37:45 +02:00
Erik Eckstein
33c91065b7 Optimizer: add var insertedPhis in SSAUpdater 2025-07-04 20:37:45 +02:00
Erik Eckstein
6c36196fa3 MandatoryPerformanceOptimizations: don't specialize vtables for thin class metatype instructions
Fixes a wrong compiler error for imported C++ classes with custom reference counting.
rdar://154947835
2025-07-04 12:07:18 +02:00
Erik Eckstein
fc7c9931b3 EscapeUtils: consider that a pointer argument can escape a function call
Unlike addresses of indirect arguments, a pointer argument (e.g. `UnsafePointer`) can escape a function call.
For example, it can be returned.

Fixes a miscompile
rdar://154124497
2025-07-04 11:56:03 +02:00
Andrew Trick
9f7bf2a507 Improve LocalVariableUtils.gatherKnownLifetimeUses; dead ends
Add a fake use for dead-end blocks. This allows gatherKnownLifetimeUses to be
used for local liveness by considering an "unreachable" instruction to generate
liveness. This is important when liveness is used as a boundary within which
access scopes may be extended. Otherwise, we are unable to extend access scopes
into dead-end blocks.

Fixes rdar://154406790 (Lifetime-dependent variable 'X' escapes its
scope but only if actor/class is final)

(cherry picked from commit 239255b8bc)
2025-07-03 21:34:25 -07:00
Andrew Trick
9b66d7c7d3 Merge pull request #82603 from atrick/62-local-switch
[6.2] Fix LocalVariableUtils switch_enum_addr.
2025-06-30 10:22:03 -07:00
Andrew Trick
43193b6a4d 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)

(cherry picked from commit fe9c0dd735)
2025-06-28 09:30:55 -07:00
Erik Eckstein
8758b557fa MandatoryPerformanceOptimization: don't recursive into referenced functions if they are not called
Fixes a false compiler error when referencing a function from a global with a section attribute.

rdar://154332540
2025-06-27 16:09:53 +02:00
Andrew Trick
2c98863499 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)

(cherry picked from commit 7c5d4b8b6d)

--- CCC ---

Explanation: Fix MutableSpan exclusive access to unsafe pointers This
fix enables exclusive access to a MutableSpan created from an
UnsafeMutablePointer.

Scope: Affects users of MutableSpan when initializing them from an unsafe pointer.

Radar/SR Issue: rdar://153745332 (Swift allows constructing two
MutableSpans to the same underlying pointer)

main PR: https://github.com/swiftlang/swift/pull/82450

Risk: Low. This only affects users of an API that requires lifetime
dependence. Without using an experimental feature, this only applies
to the initializers of Mutable[Raw]Span.

Testing: Added source-level unit tests

Reviewer: TBD
2025-06-24 00:18:29 -07:00
Andrew Trick
3dd1fb2518 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.

(cherry picked from commit 36d2b5bee4)
2025-06-24 00:11:47 -07:00
Andrew Trick
04cb1a3c1e Fix lifetime diagnotics on an empty tuple.
Consider an empty tuple to be a value introducer rather than a forwarding
instruction.

Fixes rdar://153978086 ([nonescapable] compiler crash with dependency on an
expression)

(cherry picked from commit bcc4a78c42)
2025-06-24 00:11:46 -07:00
Andrew Trick
9bcc3f41dc 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)

(cherry picked from commit 5b5f370ce1)
2025-06-17 09:59:14 -07:00
Meghana Gupta
d5b82a3b7c [6.2] Fix an inliner crash when inlining begin_apply with scoped lifetime dependence 2025-06-13 14:18:29 -07:00
eeckstein
9df721761c Merge pull request #82141 from eeckstein/fix-mpo2-6.2
[6.2] MandatoryPerformanceOptimizations: only set the `[perf_constraint]` flag for callees of performance constraint functions
2025-06-11 06:51:40 +02:00
Erik Eckstein
779434ac08 MandatoryPerformanceOptimizations: only set the [perf_constraint] flag for callees of performance constraint functions
It used to also set it for functions which are referenced from a global with a const/section attribute - even if not performance attribute was present in the whole module. This is unnecessary and can lead to worse code generation.

rdar://152665294
2025-06-10 11:31:03 +02:00
Andrew Trick
0116dc0ff9 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)

(cherry picked from commit 227f8028e8)
2025-06-05 20:24:18 -07:00
Andrew Trick
3691eedab9 [NFC] LifetimeDependence: fix internal debug output
(cherry picked from commit 95f7a12c98)
2025-06-05 20:24:18 -07:00
Andrew Trick
0d5351bfcc Merge pull request #81993 from atrick/62-fix-lifedep-indirect-closure
[6.2] LifetimeDependenceDiagnostics: diagnose indirect closure results.
2025-06-05 01:20:41 -07:00
Pavel Yaskevich
608a37ad04 Merge pull request #81997 from xedin/using-for-default-isolation-in-file-context-6.2
[6.2][AST/Sema] SE-0478: Implement using declaration under an experimental flag
2025-06-05 00:44:21 -07:00
Pavel Yaskevich
c38cf0f985 [CompilerSources] Register using declaration
(cherry picked from commit 202907d0f6)
2025-06-04 13:16:55 -07:00
Andrew Trick
fb2a6ee9a8 LifetimeDependenceDiagnostics: fix source loc for implicit variables
Diagnostics on an indirect result ($return_value) did not report a source
location.

(cherry picked from commit c030b78c7d)
2025-06-04 12:03:35 -07:00
Andrew Trick
b862300097 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)

(cherry picked from commit 1d09c06ab1)
2025-06-04 12:03:35 -07:00
Erik Eckstein
890de1ac28 MandatoryPerformanceOptimizations: make sure to handle de-serialized vtable methods
When de-serializing a function and this function allocates a class, the methods of the de-serialized vtable must be handled, too.

Fixes an IRGen crash
rdar://152311945
2025-06-04 12:22:58 +02:00
Erik Eckstein
7eb123ff29 Swift SIL: Fix argument conventions for functions which have both, a direct and indirect result.
The function convention for the first argument is not identified as indirect-out.
This lets alias analysis assume that the memory pointed to by argument 0 cannot be written by the called function.

The problem is that subscripting a LazyFilterCollection (with the base index, e.g. `Int`) does not work as expected, because it returns the nth element of the base collection!
The fix is to implement the subscript "manually".

Fixes a mis-compile.
rdar://152160748
2025-05-30 12:40:44 +02:00
eeckstein
826bc76a71 Merge pull request #81736 from eeckstein/fix-mda-6.2
[6.2] SIL: define `mark_dependence_addr` to read and write to its address operand
2025-05-24 15:29:07 +02:00
Erik Eckstein
30e138c48b SIL: define mark_dependence_addr to read and write to its address operand
This prevents simplification and SILCombine passes to remove (alive) `mark_dependence_addr`.
The instruction is conceptually equivalent to
```
  %v = load %addr
  %d = mark_dependence %v on %base
  store %d to %addr
```

Therefore the address operand has to be defined as writing to the address.
2025-05-23 07:53:14 +02:00
Erik Eckstein
f69793cc5f DeadStoreElimination: don't assume that the operand of an dealloc_stack is an alloc_stack.
It can also be a `partial_apply`.
Fixes a compiler crash
https://github.com/swiftlang/swift/issues/81698
rdar://151822502
2025-05-23 06:48:45 +02:00
eeckstein
11b77bfe3c Merge pull request #81328 from eeckstein/copy-block-opt2-6.2
[6.2] Optimizer: support partial_apply of thunks in the `copy_block` simplification
2025-05-07 01:19:57 +02:00
Meghana Gupta
65cda30e54 Merge pull request #81298 from meg-gupta/fixwarncp
[6.2] Fix newly introduced warnings in LifetimeDependenceScopeFixup
2025-05-06 09:03:38 -07:00
Erik Eckstein
cc92319c3d Optimizer: support partial_apply of thunks in the copy_block simplification.
If the block is passed to another function - either as closure argument or as closure capture - it's "converted" to a swift closure with the help of a thunk. The thunk just calls the block.
If this is done with a non-escaping partial_apply, the block does not escape.

rdar://149095630
2025-05-06 17:57:37 +02:00
Erik Eckstein
2f34dae56f Swift SIL: add Builder.createUncheckedOwnershipConversion 2025-05-06 17:57:37 +02:00
Meghana Gupta
f9f709b7c3 Fix newly introduced warnings in LifetimeDependenceScopeFixup 2025-05-05 11:26:38 -07:00
Erik Eckstein
7e212a8580 embedded: avoid false error "Deinit of non-copyable type not visible in the current module" in SourceKit
As SourceKit explicitly disables WMO, silence the diagnostic in this case (but leave it enabled for explicit non-WMO builds otherwise).

rdar://150596807
2025-05-05 19:11:46 +02:00
Zachary 'Clack' Cole
f3380efa9d Merge pull request #81240 from clackary/cherrypick/ossa-partial-apply-80662
[6.2 🍒] Fix ownership issues with sequences of partial_apply's in AutoDiff closure specialization pass
2025-05-02 13:20:34 -06:00
Andrew Trick
6f05d80161 LifetimeDependenceDefUseAddressWalker: avoid infinite recursion.
This utility is used by DependentAddressUseDefWalker which now conservatively
follows all possible uses. This could result in the same address being reached
multiple times during a def-use walk. Ensure that we don't infinitely recurse.

There is no small test case for this, but the fix is trivial and standard
practice for such walkers, and this is hit quickly in real usage, so there is no
danger of it regressing.

Fixes rdar://150403948 ([nonescapable] Infinite recursion compiler crash in
lifetime dependence checking)

(cherry picked from commit 4512927d2b)
2025-05-01 17:10:59 -07:00