Commit Graph

158 Commits

Author SHA1 Message Date
Adrian Prantl
99cf35cdce [SILOptimzer] Fix a crash caused by SILCombine mishandling inlined variables
This showed up on and off again on the source-compatibility testsuite project hummingbird.

The gist of the problem is that transformations may not rewrite the
type of an inlined instance of a variable without also createing a
deep copy of the inlined function with a different name (and e.g., a
specialization suffix). Otherwise the modified inlined variable will
cause an inconsistency when later compiler passes try to create the
abstract declaration of that inlined function as there would be
conflicting declarations for that variable.

Since SILDebugScope isn't yet available in the SwiftCompilerSources
this fix just drop these variables, but it would be absolutely
possible to preserve them by using the same mechanism that SILCloner
uses to create a deep copy of the inlined function scopes.

rdar://163167975
2025-11-07 17:06:33 -08:00
Erik Eckstein
610539a85f SIL: streamline Operand Sequence APIs
* remove `filterUsers(ofType:)`, because it's a duplication of `users(ofType:)`
* rename `filterUses(ofType:)` -> `filter(usersOfType:)`
* rename `ignoreUses(ofType:)` -> `ignore(usersOfType:)`
* rename `getSingleUser` -> `singleUser`
* implement `singleUse` with `Sequence.singleElement`
* implement `ignoreDebugUses` with `ignore(usersOfType:)`

This is a follow-up of eb1d5f484c.
2025-10-16 10:12:33 +02:00
Erik Eckstein
82bffd3b21 Simplification: fold tuple - copy_value - destructure_tuple sequences
We already do this for structs.
Also, refactor the simplification to share the logic between structs and tuples
2025-10-14 10:20:17 +02:00
Erik Eckstein
181b2f1f6d Optimizer: eliminate struct_extracts of an owned struct where the struct_extracts are inside a borrow scope
This is done by splitting the `begin_borrow` of the whole struct into individual borrows of the fields (for trivial fields no borrow is needed).
And then sinking the `struct` to it's consuming use(s).

```
  %3 = struct $S(%nonTrivialField, %trivialField)  // owned
  ...
  %4 = begin_borrow %3
  %5 = struct_extract %4, #S.nonTrivialField
  %6 = struct_extract %4, #S.trivialField
  use %5, %6
  end_borrow %4
  ...
  end_of_lifetime %3
```
->
```
  ...
  %5 = begin_borrow %nonTrivialField
  use %5, %trivialField
  end_borrow %5
  ...
  %3 = struct $S(%nonTrivialField, %trivialField)
  end_of_lifetime %3
```

This optimization is important for Array code where the Array buffer is constantly wrapped into structs and then extracted again to access the buffer.
2025-10-08 17:48:37 +02:00
Erik Eckstein
c3612bafb8 SIL: make var OperandArray.values available for all kind of operand sequences 2025-10-06 09:47:40 +02:00
Anthony Latsis
3d898f71e5 SwiftCompilerSources/SIL: More robust IntegerLiteralInst construction
ac619010e3 backfired when building the
stdlib on rebranch. This time the problem is reversed: we should be
interpreting an integer as unsigned where we no longer do, here:
8f7af45115/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift (L78).

Rather than treating integers as signed by default, make
`Builder.createIntegerLiteral` accept a generic `FixedWidthInteger`, and
manipulate the value based on the generic type argument's signedness.

This doesn't entirely define away unintentional sign extensions, but
makes this mistake of humouring the parameter type less likely.
2025-09-25 08:05:57 +01:00
Anthony Latsis
275deaf154 Merge pull request #84052 from swiftlang/jepa-main2
SwiftCompilerSources/SIL: Fix APInt assertion failure on rebranch
2025-09-24 17:39:04 +01:00
Anthony Latsis
ac619010e3 SwiftCompilerSources/SIL: Fix APInt assertion failure on rebranch
The assertion is hit through `TypeValueInst.simplify` when constructing
an integer literal instruction with a negative 64-bit `Swift.Int` and a
bit width of 32 (the target pointer bit width for arm64_32 watchOS).
This happens because we tell the `llvm::APInt` constructor to treat the
input integer as unsigned by default in `getAPInt`, and a negative
64-bit signed integer does not fit into 32 bits when interpreted as
unsigned.

Fix this by flipping the default signedness assumption for the Swift API
and introducing a convenience method for constructing a 1-bit integer
literal instruction, where the correct signedness assumption depends on
whether you want to use 1 or -1 for 'true'.

In the context of using an integer to construct an `llvm::APInt`, there
are 2 other cases where signedness matters that come to mind:
1. A non-decimal integer literal narrower than 64 bits, such as
   `0xABCD`, is used.
2. The desired bit width is >64, since `llvm::APInt` can either
   zero-extend or sign-extend the 64-bit integer it accepts.

Neither of these appear to be exercised in SwiftCompilerSources, and
if we ever do, the caller should be responsible for either (1)
appropriately extending the literal manually, e.g.
`Int(Int16(bitPattern: 0xABCD))`, or (2) passing along the appropriate
signedness.
2025-09-24 09:37:42 +01:00
Jakub Florek
38f28c1049 Reapply "Merge pull request #84045 from MAJKFL/new-sil-licm-pass-copy-ownership"
This reverts commit d2cd281d4c.
2025-09-19 16:06:35 +01:00
Jakub Florek
d2cd281d4c Revert "Merge pull request #84045 from MAJKFL/new-sil-licm-pass-copy-ownership"
This reverts commit a5c6156525, reversing
changes made to 2b6ea81b9e.
2025-09-17 15:52:48 +01:00
Jakub Florek
df24019195 Rename Cloner.cloneRecursivelyToGlobal. 2025-09-10 16:18:50 +01:00
Erik Eckstein
844217d58c Optimizer: replace explicit_copy_value and explicit_copy_addr with their non-explicit counterparts
The `explicit_copy_value` and `explicit_copy_addr` instructions are only used for non-copyable diagnostics in the mandatory pipeline.
After that we can replace them by their non-explicit counterparts so that optimizations (which only know of `copy_value` and `copy_addr`) can do their work.

rdar://159039552
2025-09-04 19:40:53 +02:00
Jakub Florek
e3140e0ae0 Add new generalized cloner. 2025-08-28 20:57:57 +01:00
Erik Eckstein
56521f0c3d 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-26 18:01:10 +02: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
41a6b8e257 SwiftCompilerSources: move SIL-related Context APIs from Optimizer to the SIL module 2025-07-28 14:19:11 +02:00
Erik Eckstein
5064297400 InstructionSimplification: simplify negated integer comparsions
Replaces a builtin "xor", which negates its operand comparison
```
  %3 = builtin "cmp_slt_Int64"(%1, %2) : $Builtin.Int1
  %4 = integer_literal $Builtin.Int1, -1
  %5 = builtin "xor_Int1"(%3, %4) : $Builtin.Int1
```
with the negated comparison
```
  %5 = builtin "cmp_ge_Int64"(%1, %2) : $Builtin.Int1
```

This makes LLVM's IPSCCP happy.

rdar://154950810
2025-07-18 07:43:51 +02:00
Erik Eckstein
12d9311b15 SILCombine: run builtin simplification as part of SILCombine
That means: make `BuiltinInst` conform to `SILCombineSimplifiable`, but still also run the legacy builtin simplification in SILCombine
2025-07-18 07:43:51 +02:00
Meghana Gupta
e317a603fc Add simplification for end_cow_mutation_addr
We insert end_cow_mutation_addr for lifetime dependent values dependent on mutable addresses.
end_cow_mutation_addr can be simplified to end_cow_mutation after other optimizations like inlining, specialization etc

This PR adds an instruction simplification to transform end_cow_mutation_addr to end_cow_mutation.
This can enable array optimizations which look for end_cow_mutation.
2025-07-14 13:46:13 -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
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
Valeriy Van
761bee9d09 Fix typo in func replaceOpenedArchetypeInSubstituations -> replaceOpenedArchetypeInSubstitutions 2025-06-08 11:30:04 +03:00
Valeriy Van
949c2bad67 Fix some typos in SwiftCompilerSources/Sources 2025-06-08 11:22:45 +03:00
Doug Gregor
bc4cf1236b [SIL] Generalize CastingIsolatedConformances to CheckedCastInstOptions
We are going to need to add more flags to the various checked cast
instructions. Generalize the CastingIsolatedConformances bit in all of
these SIL instructions to an "options" struct that's easier to extend.

Precursor to rdar://152335805.
2025-06-04 17:12:28 -07:00
Erik Eckstein
1a5ea19a85 SimplifyApply: don't do the raw-enum comparison optimization for custom RawRepresentable enums
Because we don't know what the custom `rawValue` can do.

Fixes a miscompile
rdar://152143111
2025-05-29 08:12:17 +02:00
Erik Eckstein
cac594fb86 Optimizer: peephole optimization for raw-value enum comparsions
Optimize (the very inefficient) RawRepresentable comparison function call to a simple compare of enum tags.
For example,
```
  enum E: String {
    case  a, b, c
  }
```
is compared by getting the raw values of both operands and doing a string compare.
This peephole optimizations replaces the call to such a comparison function with a direct compare of the enum tags, which boils down to a single integer comparison instruction.

rdar://151788987
2025-05-27 12:11:03 +02:00
Erik Eckstein
85228f2c75 Optimizer: do mark_dependence simplification at Onone
* re-implement the SILCombine peephole as a Swift instruction simplification
* run this simplification also in the OnoneSimplification pass
2025-05-23 18:53:57 +02:00
Erik Eckstein
9e70eb814c InitializeStaticGlobals: handle InlineArray.init(repeating:) also for arm64_32
This needs matching a different builtin for scalar conversion for the `index_addr` index.

Fixes a test failure on watchos
rdar://151761870
2025-05-22 15:33:27 +02:00
Erik Eckstein
47db3fcfbb Optimizer: move the getGlobalInitialization utility from OptUtils.swift to SimplifyLoad.swift
Because it's not used anywhere else anymore
2025-05-20 20:46:40 +02:00
Erik Eckstein
d7580e4919 Optimizer: move the Value.lookThroughTruncOrBitCast from SimplifyPointerToAddress.swift to OptUtils.swift 2025-05-20 20:46:33 +02:00
Erik Eckstein
140b883b9a SIL: let TypeValueInst.value return an optional Int
and don't require the client to check if it's an integer type.
Also, implement `var value` natively and without bridging.
2025-05-15 21:29:02 +02:00
Erik Eckstein
bc4310b0eb Optimizer: simplify unchecked_addr_cast for vectors
Reimplement the simplification in swift and add a new transformation:
```
  %1 = unchecked_addr_cast %0 : $*Builtin.FixedArray<N, Element> to $*Element
```
->
```
  %1 = vector_base_addr %0 : $*Builtin.FixedArray<N, Element>
```
2025-05-12 19:25:12 +02:00
Erik Eckstein
1fee4fe953 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-02 18:10:08 +02:00
Erik Eckstein
199eb1d6e7 Optimizer: remove redundant copy_block instructions
Removes a `copy_block` if its only uses, beside ownership instructions, are callees of function calls
```
  %2 = copy_block %0
  %3 = begin_borrow [lexical] %2
  %4 = apply %3() : $@convention(block) @noescape () -> ()
  end_borrow %3
  destroy_value %2
```
->
```
  %4 = apply %0() : $@convention(block) @noescape () -> ()
```

rdar://118521396
2025-04-15 11:02:39 +02:00
Erik Eckstein
f5ca12d42b Simplification: check for isolated conformances when simplifying metatype casts
rdar://147417762
2025-04-05 09:00:30 +02:00
Erik Eckstein
f8d6efd485 SimplifyAllocStack: bail if the address of the allocated existential escapes
This is not a problem if the alloc_stack already contains the opened existential.
Fixes a miscompile
rdar://148253142
2025-04-03 23:04:49 +02:00
Erik Eckstein
1100bf9bfb SimplifyAllocStack: rename a variable and update a comment
NFC
2025-04-03 06:58:00 +02:00
Erik Eckstein
ee18f8c168 Simplification: fix a crash in alloc_stack simplification
Handle the case that a type dependent operand is a dynamic-self argument and not an open-existential instruction.

rdar://148258964
2025-04-01 10:58:45 +02:00
Doug Gregor
e0b52cd20e [SIL] Extend checked-cast instructions with "prohibit isolated conformances" flag
When performing a dynamic cast to an existential type that satisfies
(Metatype)Sendable, it is unsafe to allow isolated conformances of any
kind to satisfy protocol requirements for the existential. Identify
these cases and mark the corresponding cast instructions with a new flag,
`[prohibit_isolated_conformances]` that will be used to indicate to the
runtime that isolated conformances need to be rejected.
2025-03-26 22:31:47 -07:00
Erik Eckstein
04ede105d6 Simplification: remove redundant array casts
Remove casts between arrays of the same type.

```
  %1 = function_ref @_arrayConditionalCast : (@guaranteed Array<Int>) -> @owned Optional<Array<Int>>
  %2 = apply %1(%0) : (@guaranteed Array<Int>) -> @owned Optional<Array<Int>>
```
->
```
  %1 = copy_value %0
  %2 = enum $Optional<Array<Int>>, #Optional.some!enumelt, %1
```

This can be a result of specialization, e.g.

```
func foo<T>(from: [T]) -> [Int]? {
  return from as? [Int]
}

func bar(a: [Int]) -> [Int]? {
  return foo(from: a)
}
```

rdar://139632757
2025-03-15 08:32:58 +01:00
Erik Eckstein
d31d82c6fe SIL: remove a workaround for a Windows 5.10 host compiler crash
https://github.com/apple/swift/issues/73253 should be fixed in 6.0, which is now used as host compiler.
2025-03-14 09:49:53 +01:00
Erik Eckstein
37455b6ab6 Optimizer: use formal types instead of SIL types for classifying dynamic casts.
Casts always work with formal rather than lowered types.
This fixes a potential bug when lowered types are different than formal types, like function types.
2025-03-14 09:45:27 +01:00
Erik Eckstein
d52f7d1619 AST/SIL: Refactor and simplify AST.Type, AST.CanonicalType and SIL.Type
* let `SIL.Type` conform to `TypeProperties` to share the implementation of common type properties between the AST types and `SIL.Type`
* call references to an `AST.Type` `rawType` (instead of just `type`)
* remove unneeded stuff
* add comments
2025-03-14 09:40:22 +01:00
Erik Eckstein
46035305aa Optimizer: improve simplification of alloc_stack
* Reimplement most of the logic in Swift as an Instruction simplification and remove the old code from SILCombine
* support more cases of existential archetype replacements:

For example:
```
  %0 = alloc_stack $any P
  %1 = init_existential_addr %0, $T
  use %1
```
is transformed to
```
  %0 = alloc_stack $T
  use %0
```

Also, if the alloc_stack is already an opened existential and the concrete type is known,
replace it as well:
```
  %0 = metatype $@thick T.Type
  %1 = init_existential_metatype %0, $@thick any P.Type
  %2 = open_existential_metatype %1 : $@thick any P.Type to $@thick (@opened("X", P) Self).Type
  ...
  %3 = alloc_stack $@opened("X", any P) Self
  use %3
```
is transformed to
```
  ...
  %3 = alloc_stack $T
  use %3
```
2025-03-07 15:59:34 +01:00
Erik Eckstein
5572c832e1 SILOptimizer: replace existential archetypes with concrete types in witness_method instructions 2025-03-07 15:59:34 +01:00
Erik Eckstein
71de3d90e0 Optimizer: replace existential archetypes with concrete types in apply instructions
If an apply uses an existential archetype (`@opened("...")`) and the concrete type is known, replace the existential archetype with the concrete type
  1. in the apply's substitution map
  2. in the arguments, e.g. by inserting address casts
For example:
```
  %5 = apply %1<@opend("...")>(%2) : <τ_0_0> (τ_0_0) -> ()
```
->
```
  %4 = unchecked_addr_cast %2 to $*ConcreteType
  %5 = apply %1<ConcreteType>(%4) : <τ_0_0> (τ_0_0) -> ()
```
2025-03-07 15:59:34 +01:00
Erik Eckstein
810064b7dc Cleanup and additions to AST and SIL Type/CanonicalType
* factor out common methods of AST Type/CanonicalType into a `TypeProperties` protocol.
* add more APIs to AST Type/CanoncialType.
* move `MetatypeRepresentation` from SIL.Type to AST.Type and implement it with a swift enum.
* let `Builder.createMetatype` get a CanonicalType as instance type, because the instance type must not be a lowered type.
2025-03-07 15:59:33 +01:00
Erik Eckstein
35097b5a71 Optimizer: simplify unconditional_checked_cast to existential metatypes.
Replace `unconditional_checked_cast` to an existential metatype with an `init_existential_metatype`, it the source is a conforming type.
Note that init_existential_metatype is better than unconditional_checked_cast because it does not need to do any runtime casting.
2025-03-07 15:59:33 +01:00
Erik Eckstein
57a236e671 InitializeStaticGlobals: support statically initializing globals which are or contain inline arrays
For example:

```
struct S {
  static let slab: Slab = [1, 2, 3, 4]
}
```

rdar://143005996
2025-02-12 22:37:49 +01:00
eeckstein
dff88f968b Merge pull request #79317 from eeckstein/remove-alloc-vector
Remove the experimental FixedArray
2025-02-12 17:03:06 +01:00