Commit Graph

1561 Commits

Author SHA1 Message Date
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
6fe77328cc Merge pull request #82796 from atrick/local-deadend
Improve LocalVariableUtils.gatherKnownLifetimeUses; dead ends
2025-07-04 12:50:24 -07:00
Pavel Yaskevich
5195e899ee Merge pull request #82792 from xedin/rdar-154719565-workaround-with-disfavored
[SwiftCompilerSources] Disfavor overload of `==` that takes `StringRef`
2025-07-04 09:32:10 -07:00
eeckstein
f5fae2dcd9 Merge pull request #82766 from eeckstein/fix-metatype-in-mpo
MandatoryPerformanceOptimizations: don't specialize vtables for thin class metatype instructions
2025-07-04 11:52:04 +02:00
Andrew Trick
239255b8bc 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)
2025-07-03 21:30:37 -07:00
Pavel Yaskevich
e3a5477bf9 [SwiftCompilerSources] Disfavor overload of == that takes StringRef
This overload is disfavored to make sure that it's only used for cases
that don't involve literals, for that `==(StringRef, StaticString) -> Bool`
is preferred. Otherwise these overloads are going to be ambiguous
because both `StringRef`, `StaticString` conform to `ExpressibleByStringLiteral`.

Consider the following example:

```swift
func test(lhs: StringRef) {
  lhs == "<<test>>"
}
```

The type-checker used to pick `==(StringRef, StringRef)` overload in this
case because it has homogenous parameter types but this is no longer the
case because this behavior was too aggressive and led to sub-optimal choices
by completely skipping other viable overloads.

Since `StaticString` already represents literals it's better to use
a standard library type and reserve the `(StringRef, StringRef)`
overload to when the literals are not involved.

Resolves: rdar://154719565
2025-07-03 16:57:28 -07:00
Erik Eckstein
2b8c63dcd3 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-03 16:21:21 +02:00
Erik Eckstein
63da299622 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-03 12:47:34 +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
Erik Eckstein
1343dc562d SILBridging: remove OptionalBridgedSILDebugVariable
This didn't work because the BridgedSILDebugVariable destructor was called even in the "none" case.

Fixes a compiler crash
rdar://154689481
2025-07-01 10:31:30 +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
da484f3146 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 10:01:42 +02: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
934aad80f0 Merge pull request #82408 from atrick/fix-immortal
Fix lifetime dependence diagnostics on Void types.
2025-06-23 09:05:59 -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
Andrew Trick
bcc4a78c42 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)
2025-06-23 00:19:21 -07:00
Andrew Trick
a8da66a82e Fix MarkDependenceInst.simplify()
Do not eliminate a mark_dependence on a begin_apply scope even though the token
has a trivial type.

Ideally, token would have a non-trivial Builtin type to avoid special cases.
2025-06-22 23:25:26 -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
f70177ca13 SIL: fix typo in comment in Function.swift 2025-06-20 08:15:03 +02:00
Erik Eckstein
fc8f264d56 SIL: add some instruction APIs
* some APIs for `MarkUnresolvedNonCopyableValueInst`
* `AllocBoxInst.hasDynamicLifetime`
2025-06-20 08:15:03 +02:00
Erik Eckstein
2259fe6972 SIL: add some instruction creation functions in Builder 2025-06-20 08:15:03 +02:00
Erik Eckstein
c19aa69940 SIL: implement Function.isSerialized and Function.isAnySerialized with serializedKind
No need for bridging functions
2025-06-20 08:15:02 +02:00
Erik Eckstein
c482b09878 SIL: let Builder.createAllocStack specify a debugVariable 2025-06-20 08:15:02 +02:00
Erik Eckstein
28dd6f7064 Optimizer: improve the SpecializationCloner
* add `cloneFunctionBody` without an `entryBlockArguments` argument
* remove the `swift::ClosureSpecializationCloner` from the bridging code and replace it with a more general `SpecializationCloner`
2025-06-20 08:15:02 +02:00
Erik Eckstein
7deec66ffe Optimizer: add two utilities in OptUtils.swift
* `MultipleValueInstruction.replace(with:)`
* `eraseIfDead(functions:)`
2025-06-20 08:15:01 +02:00
Erik Eckstein
9bd85c6723 SIL: add some Function APIs
* `isReferencedInModule`
* `shouldOptimize`
2025-06-20 08:15:01 +02:00
Erik Eckstein
d8e4e501f6 Optimizer: add some SIL modification APIs to Context
* `insertFunctionArgument`
* `BeginAccessInst.set(accessKind:)`
* `erase(function:)`
2025-06-20 08:15:01 +02:00
Erik Eckstein
de28cf04cc Optimizer: add Context. mangle(withBoxToStackPromotedArguments) 2025-06-20 08:15:01 +02:00
Erik Eckstein
bc7024edfe Optimizer: fix ModulePassContext.mangle(withDeadArguments:)
If mangled the wrong argument indices.
2025-06-20 08:15:00 +02:00
Erik Eckstein
5b9c206059 Optimizer: remove don't use locationOfNextNonMetaInstruction for getting Builder locations from instructions
This does not work in some situations.
2025-06-20 08:15:00 +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
f83fb1b14a Optimizer: add FunctionWorklist and CrossFunctionValueWorklist
Originally, `FunctionWorklist` was a private utility in MandatoryPerformanceOptimizations.
Moved this to `Worklist.swift` to make it generally available.
Also, simplify the `pop()` function which changes the popping order - therefore some test changes were necessary.
2025-06-20 08:14:59 +02:00
Erik Eckstein
40363d87c4 Optimizer: fix the InstructionRange utility for control flow graphs with unreachable blocks
`InstructionRange.contains` did yield a wrong result if the range ended in the begin-block and another instruction was inserted in an unreachable block.
2025-06-20 08:14:59 +02:00
Erik Eckstein
1f304e5609 SIL: improve APIs for Box types
* move `isBox` from `SIL.Type` to `TypeProperties` to make it also available for AST types
* add `BoxFieldsArray.isMutable(fieldIndex:)`
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
Erik Eckstein
d025e9f7a5 SIL: add var Argument.decl: ValueDecl? 2025-06-20 08:14:58 +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
eeckstein
2237d8615e Merge pull request #82142 from eeckstein/mandatory-perf-opt
MandatoryPerformanceOptimizations: some refactoring
2025-06-10 17:45:17 +02:00
Hamish Knight
4b2af07ec6 Merge pull request #82118 from hamishknight/excode
[cmake] Remove remaining `XCODE` checks
2025-06-10 16:01:56 +01:00
Erik Eckstein
8d73f881e8 SIL: let getNominalFields return nil for a struct with unreferenceable storage
Like C bitfields.
Fixes a crash in the InitializeStaticGlobals pass in case a global having a C struct type with bitfield is initialized statically.
2025-06-10 10:55:40 +02:00
Erik Eckstein
f0b3ec05b4 MandatoryPerformanceOptimizations: some refactoring
NFC
2025-06-10 08:10:42 +02:00
Hamish Knight
8f4fbe3d9a [cmake] Remove remaining XCODE checks
I missed these when ripping out support for CMake Xcode project
generation.
2025-06-09 22:16:12 +01:00
eeckstein
a40a7be694 Merge pull request #82090 from valeriyvan/typos
Fix some typos in SwiftCompilerSources/Sources
2025-06-09 13:23:04 +02:00
Valeriy Van
761bee9d09 Fix typo in func replaceOpenedArchetypeInSubstituations -> replaceOpenedArchetypeInSubstitutions 2025-06-08 11:30:04 +03:00