Commit Graph

248 Commits

Author SHA1 Message Date
Andrew Trick
8c092911ef Add the LifetimeDependenceInsertion pass.
Insert mark_dependence [nonescaping] markers at every lifetime
introducer that produces a lifetime-dependent value.
2024-02-12 09:57:14 -08:00
Andrew Trick
274c47877f LifetimeDepenenceDiagnostics improvements
Better handling of @_unsafeNonescapableResult

Improve diagnostic clarity.
2024-02-12 09:57:14 -08:00
Andrew Trick
63413916a1 LifetimeDependenceDiagnostics; handle @_unsafeNonescapableResult. 2024-02-12 09:57:14 -08:00
Erik Eckstein
6493872ec5 BooleanLiteralFolding: remove dead blocks
Remove all dead blocks which are a result of constant folding condition branches
2024-02-02 11:45:38 +01:00
eeckstein
fb5228d453 Merge pull request #71267 from eeckstein/function-signature-opt
MandatoryPerformanceOptimizations: perform function signature optimization to remove metatype arguments
2024-02-01 07:53:36 +01:00
eeckstein
13201e03c3 Merge pull request #71275 from eeckstein/fix-object-outliner
ObjectOutliner: don't outline objects with tail allocations
2024-02-01 07:47:24 +01:00
Andrew Trick
3002513c4e [NFC] disable verbose lifetime diagnostics by default 2024-01-31 18:58:45 -08:00
Erik Eckstein
31f3102540 swift SIL: fix Function.isGeneric
It didn't work for functions in generic contexts, which don't add a generic parameter themselves
2024-01-31 17:16:18 +01:00
Erik Eckstein
eb626c2814 ObjectOutliner: don't outline objects with tail allocations
An object with tail allocated elements is in risk of being passed to malloc_size, which does not work for non-heap allocated objects.
Conservatively, disable objects with tail allocations.

rdar://121886093
2024-01-31 16:25:21 +01:00
Andrew Trick
ddceffaf3b LifetimeDependenceDiagnostics pass
Initial diagnostic pass to enforce ~Escapable types.
2024-01-30 11:45:55 -08:00
Erik Eckstein
6b046a14eb StackPromotion: prevent resilient classes from being stack promoted.
Usually resilient classes cannot be promoted anyway, because their initializers are not visible and let the object appear to escape.
But in some rare situations this check is needed.

rdar://121558570
2024-01-26 09:38:14 +01:00
eeckstein
6bf39cccd6 Merge pull request #70787 from eeckstein/boolean-literal-folding
Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass
2024-01-11 11:39:44 +01:00
Meghana Gupta
5d2454f3e3 Merge pull request #68180 from meg-gupta/lowerb4inline
Lower OwnershipModelEliminator to just before inlining
2024-01-10 13:53:34 -08:00
Erik Eckstein
c89df9ec98 Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass
Add a new mandatory BooleanLiteralFolding pass which constant folds conditional branches with boolean literals as operands.

```
  %1 = integer_literal -1
  %2 = apply %bool_init(%1)   // Bool.init(_builtinBooleanLiteral:)
  %3 = struct_extract %2, #Bool._value
  cond_br %3, bb1, bb2
```
->
```
  ...
  br bb1
```

This pass is intended to run before DefiniteInitialization, where mandatory inlining and constant folding didn't run, yet (which would perform this kind of optimization).
This optimization is required to let DefiniteInitialization handle boolean literals correctly.
For example in infinite loops:

```
   init() {
     while true {           // DI need to know that there is no loop exit from this while-statement
       if some_condition {
         member_field = init_value
         break
       }
     }
   }
```
2024-01-10 16:15:57 +01:00
Erik Eckstein
fa3a959524 ObjectOutliner: support outlining of classes in global let variables
```
  let c = SomeClass()
```

is turned into

```
  private let outlinedVariable = SomeClass()  // statically initialized and allocated in the data section
  let c = outlinedVariable
```

rdar://111021230
rdar://115502043

Also, make the ObjectOutliner work for OSSA. Though, it currently doesn't run in the OSSA pipeline.
2024-01-10 09:34:01 +01:00
Erik Eckstein
3229749257 SwiftCompilerSources: move some private utilities of passes into OptUtils
* `var Function.initializedGlobal`
* `func getGlobalInitialization`

and add `var CollectionLikeSequence.singleElement`
2024-01-10 09:34:01 +01:00
Erik Eckstein
bc99986cf9 SIL: add a dependency token operand to global_addr
Optionally, the dependency to the initialization of the global can be specified with a dependency token `depends_on <token>`.
This is usually a `builtin "once"` which calls the initializer for the global variable.
2024-01-10 09:33:58 +01:00
Meghana Gupta
df3468fd6c Follow up of #68180
Remove unnecessary cases
2024-01-05 13:20:52 -08:00
Andrew Trick
2128c21106 Migrate SwiftCompilerSources to FunctionConvention.
Layers:
- FunctionConvention: AST FunctionType: results, parameters
- ArgumentConventions: SIL function arguments
- ApplyOperandConventions: applied operands

The meaning of an integer index is determined by the collection
type. All the mapping between the various indices (results,
parameters, SIL argument, applied arguments) is restricted to the
collection type that owns that mapping. Remove the concept of a
"caller argument index".
2024-01-03 12:24:50 -08:00
Erik Eckstein
ae278058e6 Add an experimental pass to lower allocateVector builtins
By default it lowers the builtin to an `alloc_vector` with a paired `dealloc_stack`.
If the builtin appears in the initializer of a global variable and the vector elements are initialized,
a statically initialized global is created where the initializer is a `vector` instruction.
2023-12-09 18:49:58 +01:00
Erik Eckstein
ded20d3c11 SwiftCompilerSources: add Value.isValidGlobalInitValue and FullApplySite.isSemanticCall
`Value.isValidGlobalInitValue` was privately used by the ObjectOutliner. Make it a generally usable utility.
2023-12-09 18:49:58 +01:00
Erik Eckstein
2a54f98c62 SimplificationPasses: add @discardableResult to runSimplification
NFC
2023-12-09 18:48:50 +01:00
Meghana Gupta
86b651330b Revert "Merge pull request #69807 from apple/revert-69450-uninarrayfix"
This reverts commit cabb5e109f, reversing
changes made to 09688abb02.
2023-12-06 08:29:50 -08:00
Meghana Gupta
a228a8859a Handle unchecked_ref_cast in ObjectOutliner 2023-12-05 13:06:36 -08:00
Erik Eckstein
3ffd4fe552 LetPropertyLowering: handle store_borrow and re-borrows
Handling of re-borrows is only done for completeness. Currently they don't occur for root-selfs at this stage in SIL.
2023-11-27 16:20:47 +01:00
Erik Eckstein
96e57d62f6 Optimizer: de-virtualize deinits of non-copyable types
In regular swift this is a nice optimization. In embedded swift it's a requirement, because the compiler needs to be able to specialize generic deinits of non-copyable types.
The new de-virtualization utilities are called from two places:

* from the new DeinitDevirtualizer pass. It replaces the old MoveOnlyDeinitDevirtualization, which is very basic and does not fulfill the needs for embedded swift.

* from MandatoryPerformanceOptimizations for embedded swift
2023-11-27 09:21:34 +01:00
Erik Eckstein
b948ccf1ae SwiftCompilerSources: add more APIs to create new basic blocks
* rename `Context.splitBlock(at:)` -> `Context.splitBlock(before:)`
* add `Context.splitBlock(after:)`
* add `Context.createBlock(after:)`
2023-11-27 09:21:33 +01:00
Erik Eckstein
fc534e1c28 SwiftCompilerSources: better APIs for handling resilient nominal types
* add `NominalTypeDecl.isResilient`

* make the return type of `Type.getNominalFields` optional and return nil in case the nominal type is resilient.
This forces users of this API to think about what to do in case the nominal type is resilient.
2023-11-27 09:21:33 +01:00
Erik Eckstein
186f1b39e4 InitializeStaticGlobals: don't merge stores to non-copyable types
A transformation must not create a `struct` instruction with a non-copyable type because this would apply that a (potential) deinit would be called for that struct.
2023-11-27 09:21:32 +01:00
Erik Eckstein
bdde6d3ba0 initializeStaticGlobalsPass: don't crash if there was a preceding error
In case of a preceding error, there is no guarantee that the SIL is valid. Therefore just bail in this case.

rdar://118521842
2023-11-17 16:14:36 +01:00
Erik Eckstein
0509a056fb SwiftCompilerSources: improve APIs for UseList
Make filter APIs for UseList chainable by adding them to Sequence where Element == Operand

For example, it allows to write:
```
let singleUse = value.uses.ignoreDebugUses.ignoreUsers(ofType: EndAccessInst.self).singleUse
```

Also, add `UseList.getSingleUser(notOfType:)`
2023-11-13 20:18:07 +01:00
Mishal Shah
e8de333daf Revert "Add a mark_dependence while emitting SIL for uninitialized array allocation " 2023-11-12 09:43:13 -08:00
Erik Eckstein
2c84de3f4f Optimizer: add a few "lookThrough" utilities
* move `Value.lookThoughOwnershipInstructions` from the ObjCBridgingOptimization pass to OptUtils
* add `lookThroughBorrow` and `lookThroughCopy`
2023-11-09 18:34:53 +01:00
Meghana Gupta
25d1e53241 Handle mark_dependence in ObjectOutliner 2023-10-31 11:07:40 -07:00
Meghana Gupta
f707d8a7de ObjectOutliner: isValidUseOfObject(Instruction) -> isValidUseOfObject(Operand) 2023-10-31 11:07:40 -07:00
Erik Eckstein
bd022b4051 InitializeStaticGlobals: fix a SIL verifier crash
When merging stores in a global initializer, it's possible that the merged store is inserted at the wrong location, causing a SIL verifier error.
This is hard to reproduce, but can happen.
The merged store must be inserted _after_ all other stores. Instead it's inserted after the store of the last property. Now, if properties are _not_ initialized in the order they are declared, this problem can show up.

rdar://117189962
2023-10-19 20:29:30 +02:00
Erik Eckstein
54d254f100 Optimizer: better handling of the complexity budget in redundant-load-elimination and dead-store-elimination.
Instead of having a budget for each optimized load or store, provide a budget for the whole function.
Fixes a build time problem.

rdar://116877696
2023-10-16 14:44:34 +02:00
Erik Eckstein
2dbd6cc56b SwiftCompilerSources: rework bridging
Introduce two modes of bridging:
* inline mode: this is basically how it worked so far. Using full C++ interop which allows bridging functions to be inlined.
* pure mode: bridging functions are not inlined but compiled in a cpp file. This allows to reduce the C++ interop requirements to a minimum. No std/llvm/swift headers are imported.

This change requires a major refactoring of bridging sources. The implementation of bridging functions go to two separate files: SILBridgingImpl.h and OptimizerBridgingImpl.h.
Depending on the mode, those files are either included in the corresponding header files (inline mode), or included in the c++ file (pure mode).

The mode can be selected with the BRIDGING_MODE cmake variable. By default it is set to the inline mode (= existing behavior). The pure mode is only selected in certain configurations to work around C++ interop issues:
* In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255).
* On windows to workaround a build problem.
2023-10-09 09:52:52 +02:00
Ikko Eltociear Ashimine
680c6f3ae2 Fix typo in ComputeSideEffects.swift
mutliple -> multiple
2023-10-03 17:39:39 +09:00
Kuba (Brecka) Mracek
f4a0397407 Merge pull request #68883 from kubamracek/embedded-release-devirt
[embedded] Re-enable ReleaseDevirtualizer and teach it to look for specialized destructors
2023-10-02 13:15:03 -07:00
Kuba Mracek
28a3d583c8 [embedded] Re-enable ReleaseDevirtualizer and teach it to look for specialized destructors 2023-09-29 16:28:59 -07:00
Andrew Trick
a5d8aafb23 SwiftCompilerSources: Replace BlockArgument with Phi and TermResult.
All SILArgument types are "block arguments". There are three kinds:
1. Function arguments
2. Phis
3. Terminator results

In every situation where the source of the block argument matters, we
need to distinguish between these three. Accidentally failing to
handle one of the cases is an perpetual source of compiler
bugs. Attempting to handle both phis and terminator results uniformly
is *always* a bug, especially once OSSA has phi flags. Even when all
cases are handled correctly, the code that deals with data flow across
blocks is incomprehensible without giving each case a type. This
continues to be a massive waste of time literally every time I review
code that involves cross-block control flow.

Unfortunately, we don't have these C++ types yet (nothing big is
blocking that, it just wasn't done). That's manageable because we can
use wrapper types on the Swift side for now. Wrapper types don't
create any more complexity than protocols, but they do sacrifice some
usability in switch cases.

There is no reason for a BlockArgument type. First, a function
argument is a block argument just as much as any other. BlockArgument
provides no useful information beyond Argument. And it is nearly
always a mistake to care about whether a value is a function argument
and not care whether it is a phi or terminator result.
2023-09-27 18:47:46 -07:00
Kavon Farvardin
b688a1f4a1 [SILOpt] experimental async demotion pass
For chains of async functions where suspensions can be statically
proven to never be required, this pass removes all suspensions and
turns the functions into synchronous functions.

For example, this function does not actually require any suspensions,
once the correct executor is acquired upon initial entry:

```
func fib(_ n: Int) async -> Int {
  if n <= 1 { return n }
  return await fib(n-1) + fib(n-2)
}
```

So we can turn the above into this for better performance:

```
func fib() async -> Int {
  return fib_sync()
}

func fib_sync(_ n: Int) -> Int {
  if n <= 1 { return n }
  return fib(n-1) + fib(n-2)
}
```

while rewriting callers of `fib` to use the `sync` entry-point
when we can prove that it will be invoked on a compatible executor.

This pass is currently experimental and under development. Thus, it
is disabled by default and you must use
`-enable-experimental-async-demotion` to try it.
2023-09-21 12:21:02 -07:00
Erik Eckstein
614a635d5d StripObjectHeaders: make sure that a dealloc_ref comes from the original root allocation.
Fixes a miscompile
2023-09-19 15:10:30 +02:00
Erik Eckstein
5bc036661c SIL optimizer: add the LetPropertyLowering pass
It lowers let property accesses of classes.
Lowering consists of two tasks:

* In class initializers, insert `end_init_let_ref` instructions at places where all let-fields are initialized.
  This strictly separates the life-range of the class into a region where let fields are still written during
  initialization and a region where let fields are truly immutable.

* Add the `[immutable]` flag to all `ref_element_addr` instructions (for let-fields) which are in the "immutable"
  region. This includes the region after an inserted `end_init_let_ref` in an class initializer, but also all
  let-field accesses in other functions than the initializer and the destructor.

This pass should run after DefiniteInitialization but before RawSILInstLowering (because it relies on `mark_uninitialized` still present in the class initializer).
Note that it's not mandatory to run this pass. If it doesn't run, SIL is still correct.

Simplified example (after lowering):

  bb0(%0 : @owned C):                           // = self of the class initializer
    %1 = mark_uninitialized %0
    %2 = ref_element_addr %1, #C.l              // a let-field
    store %init_value to %2
    %3 = end_init_let_ref %1                    // inserted by lowering
    %4 = ref_element_addr [immutable] %3, #C.l  // set to immutable by lowering
    %5 = load %4
2023-09-19 15:10:30 +02:00
Erik Eckstein
f0b811c45f SIL: add the end_init_let_ref instruction
This instructions marks the point where all let-fields of a class are initialized.
This is important to ensure the correctness of ``ref_element_addr [immutable]`` for let-fields,
because in the initializer of a class, its let-fields are not immutable, yet.
2023-09-19 15:10:30 +02:00
Erik Eckstein
e5eb15dcbe Swift SIL: replace the set_deallocating instruction with begin_dealloc_ref
Codegen is the same, but `begin_dealloc_ref` consumes the operand and produces a new SSA value.
This cleanly splits the liferange to the region before and within the destructor of a class.
2023-09-19 15:10:30 +02:00
Erik Eckstein
d457368014 SIL Optimizer: move some projection path utilities from RedundantLoadElimination and AccessUtils into OptUtils
NFC
2023-09-19 15:10:30 +02:00
Manu
02b5fa2c8e Fix some typos in the codebase 2023-08-31 18:50:10 -03:00
Erik Eckstein
51cb7575ea RedundantLoadElimination: don't crash when loading a non-trivial enum which was stored as trivial non-payload case.
rdar://114648847
2023-08-31 09:16:17 +02:00