Commit Graph

115 Commits

Author SHA1 Message Date
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
eeckstein
b6639e1782 Merge pull request #79314 from eeckstein/fix-simplify-keypath
SimplifyKeyPath: insert the correct destroy operation for an operand of a removed keypath
2025-02-12 15:18:39 +01:00
Erik Eckstein
6407f9a0bd remove the allocVector builtin
It's not needed anymore, because the "FixedArray" experimental feature is replaced by inline-arrays.
2025-02-12 10:51:14 +01:00
Erik Eckstein
3f95ce9645 Optimizer: fix spelling of the Simplifiable protocol
Rename `Simplifyable` -> `Simplifiable`

NFC
2025-02-12 09:01:11 +01:00
Erik Eckstein
2962474b58 SimplifyKeyPath: insert the correct destroy operation for an operand of a removed keypath
If the operand is an address, we need to use `destroy_addr` and not `destroy_value`.

Fixes a compiler crash.
rdar://144662171
2025-02-12 08:35:23 +01:00
Arnold Schwaighofer
0fe3cf0096 SIL: Update formal source type in SimplifyRefCasts when possible
We use the formal source type do decide whether a checked_cast_br is
known to succeed/fail. If we don't update it we loose that optimization

That is:

```
  checked_cast_br AnyObject in %2 : X to X, bb1, bb2
```

Will not be simplified even though the operand and the destintation type
matches.
2025-01-29 09:07:21 -08:00
Erik Eckstein
9aff288be4 Optimizer: re-implement the pointer_to_address SILCombine peephole optimizations in swift
Which consists of
* removing redundant `address_to_pointer`-`pointer_to_address` pairs
* optimize `index_raw_pointer` of a manually computed stride to `index_addr`
* remove or increase the alignment based on a "assumeAlignment" builtin

This is a big code cleanup but also has some functional differences for the `address_to_pointer`-`pointer_to_address` pair removal:

* It's not done if the resulting SIL would result in a (detectable) use-after-dealloc_stack memory lifetime failure.
* It's not done if `copy_value`s must be inserted or borrow-scopes must be extended to comply with ownership rules (this was the task of the OwnershipRAUWHelper).

Inserting copies is bad anyway.
Extending borrow-scopes would only be required if the original lifetime of the pointer extends a borrow scope - which shouldn't happen in save code. Therefore this is a very rare case which is not worth handling.
2024-12-21 08:28:22 +01:00
Erik Eckstein
89353506f5 SimplifyBuiltin: support metatype and function types when optimizing Builtin.sizeof/alignof/strideof/destroyArray
Get the maximally abstracted lowered type instead of bailing if the ast type isn't equal to the lowered SIL type.
2024-12-19 20:53:46 +01:00
Erik Eckstein
4fdf16de1b SIL: add CanonicalType.canBeClass
And move the implementation of `SIL.Type.canBeClass` to the AST Type. The SIL Type just calls the AST Type implementation.
Also rename `SIL.Type.canonicalASTType` -> `SIL.Type.astType`.
2024-12-19 20:53:46 +01:00
Erik Eckstein
cd7c533d42 Optimizer: add SingleValueInstruction.replace(with:) and use it throughout the optimizer
It replaces all uses and then erases the instruction.
2024-12-19 20:53:45 +01:00
Erik Eckstein
1545e01ab5 SIL: Let SubstitutionMap.replacementTypes return AST types rather than optional SIL types.
This is what the C++ SubstitutionMap does. One has to use `Type.loweredType` to get from the AST type to the SIL type.
2024-12-19 20:53:45 +01:00
Erik Eckstein
bf496aa4f6 Optimizer: add simplification for fix_lifetime
Canonicalize a `fix_lifetime` from an address to a `load` + `fix_lifetime`:
```
   %1 = alloc_stack $T
   ...
   fix_lifetime %1
```
->
```
   %1 = alloc_stack $T
   ...
   %2 = load %1
   fix_lifetime %2
```

This transformation is done for `alloc_stack` and `store_borrow` (which always has an `alloc_stack` operand).
The benefit of this transformation is that it enables other optimizations, like mem2reg.

This peephole optimization was already done in SILCombine, but it didn't handle store_borrow.
A good opportunity to make an instruction simplification out of it.

This is part of fixing regressions when enabling OSSA modules:
rdar://140229560
2024-12-13 12:06:20 +01:00
Erik Eckstein
3e35df0983 Simplification: run begin_borrow simplification in SILCombine 2024-12-11 12:32:34 +01:00
Erik Eckstein
12626e39d5 Simplification: remove begin_borrow if the borrowed value is a thin_to_thick_function
`thin_to_thick_function` has "none" ownership and is compatible with guaranteed values.
Therefore the `begin_borrow` is not needed.
2024-12-11 12:32:33 +01:00
Erik Eckstein
6b38f2aab4 Optimizer: simplify load_borrow
* Remove dead `load_borrow` instructions (replaces the old peephole optimization in SILCombine)
* If the `load_borrow` is followed by a `copy_value`, combine both into a `load [copy]`
2024-12-11 12:32:33 +01:00
Erik Eckstein
73e36e2282 SimplifyDestructure: canonicalize destructure_tuple and destructure_struct for trivial tuples/structs
Replace destructure_tuple with tuple_extract instructions and destructure_struct with struct_extract instructions.
This canonicalization helps other optimizations to e.g. CSE tuple_extract/struct_extract.
2024-12-11 12:32:33 +01:00
Erik Eckstein
736d8d5e9c SimplifyLoad: fix removal of load operand instructions
Also consider that the (transitive) operand of a load can be a multi-value instruction, like begin_cow_mutation

rdar://140778782
2024-12-02 19:38:53 +01:00
Erik Eckstein
c25d915337 SimplifyLoad: remove a load from a global object, e.g. from an outlined array
Loading  array elements or the array's count/capacity can be replaced with the actual value if the array is a statically allocated global let-variable.
2024-11-28 09:40:12 +01:00
Erik Eckstein
99ef6f727d Optimizer: replace unchecked_enum_data simplification in SILCombine with the corresponding instruction simplification from SwiftCompilerSources
The optimization in SILCombine had a bug (which is already fixed in the instruction simplification).
2024-11-14 09:18:29 +01:00
Erik Eckstein
c97502374b Optimizer: add constant folding of classify_bridge_object
Constant fold `classify_bridge_object` to `(false, false)` if the operand is known to be a swift class.
2024-10-08 16:24:46 +02:00
Erik Eckstein
10782cf42b SwiftCompilerSources: introduce the AST module
As the optimizer uses more and more AST stuff, it's now time to create an "AST" module.
Initially it defines following AST datastructures:
* declarations: `Decl` + derived classes
* `Conformance`
* `SubstitutionMap`
* `Type` and `CanonicalType`

Some of those were already defined in the SIL module and are now moved to the AST module.
This change also cleans up a few things:
* proper definition of `NominalTypeDecl`-related APIs in `SIL.Type`
* rename `ProtocolConformance` to `Conformance`
* use `AST.Type`/`AST.CanonicalType` instead of `BridgedASTType` in SIL and the Optimizer
2024-10-02 07:10:29 +02:00
Erik Eckstein
f3a9b08e7a SwiftCompilerSources: bridged ProtocolConformance
And use that in some Builder APIs
2024-09-25 19:31:40 +02:00
Kuba (Brecka) Mracek
d3c5149714 Merge pull request #76658 from kubamracek/embedded-managed-buffer
[embedded] Add support for ManagedBuffer to Embedded Swift
2024-09-25 02:54:55 -07:00
Kuba Mracek
0b50c2155e Don't emit upcast to the same type in SimplifyAllocRefDynamic, add test, add comment 2024-09-24 08:48:51 -07:00
Kuba Mracek
df38313572 The metatype operand on AllocRefDynamicInst is not always at index 1, use getNumTailTypes() 2024-09-23 15:42:38 -07:00
Kuba Mracek
c7a5569c4f [embedded] Add support for ManagedBuffer to Embedded Swift
This makes ManagedBuffer available and usable in Embedded Swift, by:

- Removing an internal consistency check from ManagedBuffer that relies on metatypes.
- Making the .create() API transparent (to hoist the metatype to the callee).
- Adding a AllocRefDynamicInst simplification to convert `alloc_ref_dynamic` to `alloc_ref`, which removes a metatype use.
- Adding tests for the above.
2024-09-23 13:32:50 -07:00
Kuba (Brecka) Mracek
ecce6ac3a9 Merge pull request #76046 from kubamracek/fix-optimize-assert-config
Fix flipped 0/1 values in SimplifyBuiltin.optimizeAssertConfig
2024-09-18 14:18:19 -07:00
Alejandro Alonso
b35ac50d3c Optimize TypeValueInst in Swift 2024-09-04 15:13:48 -07:00
Kuba Mracek
50fa83b237 Fix flipped 0/1 values in SimplifyBuiltin.optimizeAssertConfig 2024-08-22 14:46:02 -07:00
Alexander Cyon
c18a24e499 [SwiftCompilerSources] Fix typos 2024-08-08 22:22:39 -07:00
Erik Eckstein
e3de408716 Simplification: remove builtin "destroyArray" with trivial element types 2024-08-01 13:38:39 +02:00
Erik Eckstein
f388361885 SimplifyBuiltin: fix a wrong constant folding of the is_same_metatype builtin for function types
We need to compare the not lowered types, because function types may differ in their original version but are equal in the lowered version, e.g.
```
  ((Int, Int) -> ())
  (((Int, Int)) -> ())
```

Fixes a miscompile
2024-07-29 17:33:42 +02:00
Erik Eckstein
04e0907ab0 SIL: rename Type.instanceTypeOfMetatype -> Type.loweredInstanceTypeOfMetatype
The same for SILType

It needs to be made clear that this is not the "original", but the lowered SIL type.

NFC
2024-07-29 17:33:36 +02:00
Ellie Shin
c3ded85c4f Update SILBridgedFunction APIs.
Add isAnySerialized() and canBeInlinedIntoCaller(SerializedKind).
2024-05-29 15:54:36 -07:00
Erik Eckstein
cd59a5e1d0 SimplifyCheckedCast: only simplify if source and destination address types match
Fixes a crash when creating a copy_addr with mismtaching types.
rdar://128195403
2024-05-17 15:07:40 +02:00
Erik Eckstein
af68435d90 Optimizer: support static initialization of global arrays
The buffer of global arrays could already be statically initialized.
The missing piece was the array itself, which is basically a reference to the array buffer.
For example:
```
var a = [1, 2, 3]
```
ends up in two statically initialized globals:
1. the array buffer, which contains the elements
2. the variable `a` which is a single reference (= pointer) of the array buffer

This optimization removes the need for lazy initialization of such variables.

rdar://127757554
2024-05-16 21:34:36 +02:00
Erik Eckstein
d9fc62e54a SimplifyKeyPath: remove dead keypath instructions also in non-OSSA
which means: handle of strong_release instructions
2024-05-16 09:32:08 +02:00
eeckstein
7bf193e764 SwiftCompilerSources: workaround a compiler crash on windows by disabling convert_function simplification 2024-04-29 10:52:25 +02:00
Kuba Mracek
33e89c0aad [embedded] Consider move_value/copy_value as removable for keypath optimization 2024-04-22 13:33:24 -07:00
nate-chandler
7bcedc91da Merge pull request #72992 from nate-chandler/simplify-tuple
[OnoneSimplify] Handle tuple(destructure_tuple()).
2024-04-12 09:09:36 -07:00
Nate Chandler
5004e93144 [OnoneSimplify] Handle tuple(destructure_tuple()). 2024-04-11 15:20:41 -07:00
Erik Eckstein
e14c1d1f62 SIL, Optimizer: update and handle borrowed-from instructions
Compute, update and handle borrowed-from instruction in various utilities and passes.
Also, used borrowed-from to simplify `gatherBorrowIntroducers` and `gatherEnclosingValues`.
Replace those utilities by `Value.getBorrowIntroducers` and `Value.getEnclosingValues`, which return a lazily computed Sequence of borrowed/enclosing values.
2024-04-10 13:38:10 +02:00
Kuba (Brecka) Mracek
89cd62604b Merge pull request #72472 from kubamracek/embedded-keypaths
[embedded] Compile-time (literal) KeyPaths for Embedded Swift
2024-03-25 10:58:51 -07:00
Kuba Mracek
796554f55d [embedded] Respect ownership in SimplifyKeyPath, emit destroy_value instructions for keypath operands 2024-03-21 17:54:05 -07:00