Commit Graph

55 Commits

Author SHA1 Message Date
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
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
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
Rintaro Ishizaki
47f18d492e [ASTGen] Move regex literal parsing from SwiftCompilerSources to ASTGen
ASTGen always builds with the host Swift compiler, without requiring
bootstrapping, and is enabled in more places. Move the regex literal
parsing logic there so it is enabled in more host environments, and
makes use of CMake's Swift support. Enable all of the regex literal
tests when ASTGen is built, to ensure everything is working.

Remove the "AST" and "Parse" Swift modules from SwiftCompilerSources,
because they are no longer needed.
2023-11-16 10:59:23 -08:00
Erik Eckstein
e718bfe8ed Optimizer: reimplement simplifications for copy_value and destroy_value in swift
So that they can run in the OnoneSimplification pass
2023-10-27 10:47:07 +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
Nate Chandler
ae1f950315 [SwiftCompilerSources] Moved Test into Optimizer.
And changed the type of the context argument to FunctionPassContext.
2023-10-07 21:23:13 -07:00
Nate Chandler
dab8c146a6 [SwiftCompilerSources] Bridged in-IR testing.
Added the bridging types involved and the basic functionality.
2023-09-28 11:33:50 -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
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
4d20423e00 Optimizer: re-implement the RedundantLoadElimination pass in Swift
The new implementation has several benefits compared to the old C++ implementation:

* It is significantly simpler. It optimizes each load separately instead of all at once with bit-field based dataflow.
* It's using alias analysis more accurately which enables more loads to be optimized
* It avoids inserting additional copies in OSSA

The algorithm is a data flow analysis which starts at the original load and searches for preceding stores or loads by following the control flow in backward direction.
The preceding stores and loads provide the "available values" with which the original load can be replaced.
2023-07-21 07:19:56 +02:00
Erik Eckstein
baaf5565b0 Optimizer: reimplement DeadStoreElimination in swift
The old C++ pass didn't catch a few cases.
Also:
* The new pass is significantly simpler: it doesn't perform dataflow for _all_ memory locations at once using bitfields, but handles each store separately. (In both implementations there is a complexity limit in place to avoid quadratic complexity)
* The new pass works with OSSA
2023-07-05 21:33:25 +02:00
Erik Eckstein
55c8c433c0 SILOptimizer: add the StripObjectHeader optimization pass
It sets the `[bare]` attribute for `alloc_ref` and `global_value` instructions if their header (reference count and metatype) is not used throughout the lifetime of the object.
2023-06-29 06:57:05 +02:00
Erik Eckstein
50c23a1640 Optimizer: implement the SILCombine peephole optimizations for retain_value and release_value in Swift 2023-06-07 14:18:38 +02:00
Erik Eckstein
4284dc10d0 Optimizer: implement the ObjectOutliner pass in Swift 2023-05-22 15:34:26 +02:00
Erik Eckstein
f3851f7503 Optimizer: implement load simplification in Swift 2023-05-22 15:34:26 +02:00
Erik Eckstein
dc3cb18029 Swift Optimizer: add the MandatoryPerformanceOptimizations pass
As a replacement for the old MandatoryGenericSpecializer

The pass it not enabled yet in the pass pipeline
2023-05-11 08:11:44 +02:00
Erik Eckstein
92a17f8a01 Optimizer: extract the NamedReturnValueOptimization from CopyForwarding to a separate function pass
This allows to run the NamedReturnValueOptimization only late in the pipeline.
The optimization shouldn't be done before serialization, because it might prevent predictable memory optimizations in the caller after inlining.
2023-05-11 08:11:44 +02:00
Erik Eckstein
fa1ecff143 Swift Optimizer: rewrite the MemBehaviorDumper test pass in swift. 2023-05-09 08:25:09 +02:00
Erik Eckstein
960ca70def Swift Optimizer: add the module pass ReadOnlyGlobalVariables
It marks global `var` variables as `let` if they are never written.
2023-05-08 21:23:36 +02:00
Erik Eckstein
6d6b94e430 Swift Optimizer: add the InitializeStaticGlobals function pass
It converts a lazily initialized global to a statically initialized global variable.

When this pass runs on a global initializer `[global_init_once_fn]` it tries to create a static initializer for the initialized global.
```
  sil [global_init_once_fn] @globalinit {
    alloc_global @the_global
    %a = global_addr @the_global
    %i = some_const_initializer_insts
    store %i to %a
  }
```

The pass creates a static initializer for the global:
```
  sil_global @the_global = {
    %initval = some_const_initializer_insts
  }
```

and removes the allocation and store instructions from the initializer function:
```
  sil [global_init_once_fn] @globalinit {
    %a = global_addr @the_global
    %i = some_const_initializer_insts
  }
```

The initializer then becomes a side-effect free function which let's the builtin-simplification remove the `builtin "once"` which calls the initializer.
2023-05-08 21:23:36 +02:00
Erik Eckstein
7eb2cb82e4 Swift Optimizer: add a pass to cleanup debug_step instructions
If a `debug_step` has the same debug location as a previous or succeeding instruction it is removed.
It's just important that there is at least one instruction for a certain debug location so that single stepping on that location will work.
2023-02-09 06:50:05 +01:00
Erik Eckstein
67ed6cfff8 Swift Optimizer: add Simplification passes
Those passes are a framework for instruction simplifications (which are not yet included in this commit).
Comparable to SILCombine
2023-02-09 06:49:58 +01:00
Erik Eckstein
cc68bd98c9 Swift Optimizer: rework pass context types and instruction passes
* split the `PassContext` into multiple protocols and structs: `Context`, `MutatingContext`, `FunctionPassContext` and `SimplifyContext`
* change how instruction passes work: implement the `simplify` function in conformance to `SILCombineSimplifyable`
* add a mechanism to add a callback for inserted instructions
2023-01-16 15:11:34 +01:00
Erik Eckstein
beb46eb624 Use the new escape and side effects in alias analysis 2022-12-21 17:41:46 +01:00
Erik Eckstein
d4d1620f28 Swift SIL: rework Instruction and BasicBlock lists to support deleting instructions during iteration
Replace the generic `List` with the (non-generic) `InstructionList` and `BasicBlockList`.
The `InstructionList` is now a bit different than the `BasicBlockList` because it supports that instructions are deleted while iterating over the list.
Also add a test pass which tests instruction modification while iteration.
2022-12-12 19:08:57 +01:00
Nate Chandler
7ea336367d [NFC] Port isDeinitBarrier to Swift.
Added new C++-to-Swift callback for isDeinitBarrier.

And pass it CalleeAnalysis so it can depend on function effects.  For
now, the argument is ignored.  And, all callers just pass nullptr.

Promoted to API the mayAccessPointer component predicate of
isDeinitBarrier which needs to remain in C++.  That predicate will also
depends on function effects.  For that reason, it too is now passed a
BasicCalleeAnalysis and is moved into SILOptimizer.

Also, added more conservative versions of isDeinitBarrier and
maySynchronize which will never consider side-effects.
2022-10-18 21:23:22 -07:00
Erik Eckstein
741c6c38df Swift Optimizer: add the ComputeSideEffects pass.
Computes the side effects for a function, which consists of argument- and global effects.
This is similar to the ComputeEscapeEffects pass, just for side-effects.
2022-10-05 07:38:11 +02:00
Erik Eckstein
e1c65bd1d6 Swift Optimizer: rename the ComputeEffects pass to ComputeEscapeEffects 2022-10-05 07:38:11 +02:00
Erik Eckstein
81ac311c83 Swift Optimizer: add the DeadEndBlocks utility for finding dead-end blocks.
Dead-end blocks are blocks from which there is no path to the function exit (`return`, `throw` or unwind).
These are blocks which end with an unreachable instruction and blocks from which all paths end in "unreachable" blocks.
2022-10-05 07:37:41 +02:00
Erik Eckstein
b2b44c0d83 Swift Optimizer: add the StackProtection optimization
It decides which functions need stack protection.

It sets the `needStackProtection` flags on all function which contain stack-allocated values for which an buffer overflow could occur.

Within safe swift code there shouldn't be any buffer overflows.
But if the address of a stack variable is converted to an unsafe pointer, it's not in the control of the compiler anymore.
This means, if there is any `address_to_pointer` instruction for an `alloc_stack`, such a function is marked for stack protection.
Another case is `index_addr` for non-tail allocated memory.
This pattern appears if pointer arithmetic is done with unsafe pointers in swift code.

If the origin of an unsafe pointer can only be tracked to a function argument, the pass tries to find the root stack allocation for such an argument by doing an inter-procedural analysis.
If this is not possible, the fallback is to move the argument into a temporary `alloc_stack` and do the unsafe pointer operations on the temporary.

rdar://93677524
2022-09-08 08:42:25 +02:00
Erik Eckstein
a12e33e9e9 Swift Optimizer: add the FunctionUses utility
Provides a list of instructions, which reference a function.

A function "use" is an instruction in another (or the same) function which references the function.
In most cases those are `function_ref` instructions, but can also be e.g. `keypath` instructions.

'FunctionUses' performs an analysis of all functions in the module and collects instructions which reference other functions.
This utility can be used to do inter-procedural caller-analysis.
2022-08-24 17:55:02 +02:00
Erik Eckstein
87f2f41d51 Swift Optimizer: add infrastructure for module passes.
To add a module pass in `Passes.def` use the new `SWIFT_MODULE_PASS` macro.
On the swift side, create a `ModulePass`.
It’s run function receives a `ModulePassContext`, which provides access to all functions of a module.
But it doesn't provide any APIs to modify functions.
In order to modify a function, a module pass must use `ModulePassContext.transform(function:)`.
2022-08-24 17:55:02 +02:00
Erik Eckstein
c2ef10661a Swift Optimizer: move function passes which are only used for unit testing to their own TestPasses directory. 2022-08-24 17:54:46 +02:00
Anxhelo Xhebraj
7a20bc3ea6 Swift Optimizer: add AccessUtils
This set of utilities introduce concepts such as `AccessBase`,
`AccessPath` and `AccessStoragePath` useful to analyze memory accesses.
2022-08-12 09:42:13 -07:00
Egor Zhdan
0e2d438c5b [cxx-interop][SwiftCompilerSources] Use llvm::StringRef instead of BridgedStringRef
rdar://83361000
2022-07-21 16:32:16 +01:00
eeckstein
b3d9b873a9 Merge pull request #58888 from eeckstein/objc-string-opt
Optimizer: add the ObjCBridgingOptimization to optimize ObjectiveC bridging operations.
2022-06-09 06:48:36 +02:00
Erik Eckstein
ec3d9dd9c7 Optimizer: add the ObjCBridgingOptimization to optimize ObjectiveC bridging operations.
Removes redundant ObjectiveC <-> Swift bridging calls.
Basically, if a value is bridged from ObjectiveC to Swift an then back to ObjectiveC again, then just re-use the original ObjectiveC value.

Also in this commit: add an additional DCE pass before ownership elimination. It can cleanup dead code which is left behind by the ObjCBridgingOptimization.

rdar://89987440
2022-06-08 22:51:57 +02:00
Rintaro Ishizaki
9f4ce612a2 [SwiftCompilerModules] Link lib_InternalSwiftSyntaxParser to libswift
To use _RegexParser from SwiftSyntax.

* Create 'libswiftCompilerModules_SwiftSyntax.a' which is a subset of
  'libswiftCompilerModules.a'
* Link 'lib_InternalSwiftSyntaxParser' to
  'libswiftCompilerModules_SwiftSyntax.a'
* Factor out swift runtime linking logic in CMake so that dynamic
  libraries can link to Swift runtime, in addition to executables
* Link 'lib_InternalSwiftSyntaxParser' to swift runtime
2022-06-02 12:23:03 -07:00
Erik Eckstein
cad646b283 re-implement the StackPromotion pass in swift
It uses the new EscapeInfo.
2022-05-02 14:22:27 +02:00
Josh Soref
1b0aa6d7f1 Spelling swiftcompilersources (#42617)
* spelling: diagnose

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: diagnostic

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: intentionally

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: optimization

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: target

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

* spelling: unbalanced

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>

Co-authored-by: Josh Soref <jsoref@users.noreply.github.com>
2022-04-25 09:01:23 -07:00
Rintaro Ishizaki
d292a95296 [SwiftCompiler/Regex] Use bridged DiagnosticEngine for error reporting
This fixes:
 * An issue where the diagnostic messages were leaked
 * Diagnose at correct position inside the regex literal

To do this:
 * Introduce 'Parse' SwiftCompiler module that is a bridging layer
   between '_CompilerRegexParser' and C++ libParse
 * Move libswiftParseRegexLiteral and libswiftLexRegexLiteral to 'Parse'

Also this change makes 'SwiftCompilerSources/Package.swift' be configured
by CMake so it can actually be built with 'swift-build'.

rdar://92187284
2022-04-22 22:53:46 -07:00
Erik Eckstein
eea471fe99 add the ComputeEffects pass
The ComputeEffects pass derives escape information for function arguments and adds those effects in the function.
This needs a lot of changes in check-lines in the tests, because the effects are printed in SIL
2022-04-22 09:50:07 +02:00
Erik Eckstein
87ae9e3a73 add passes to dump the results of EscapeInfo
And add test files which uses the passes for verification of EscapeInfo
2022-04-22 09:50:07 +02:00
Saleem Abdulrasool
218ef587e6 Revert "Merge pull request #42242 from eeckstein/escapeinfo"
This reverts commit c05e064cd8, reversing
changes made to c1534d5af9.

This caused a regression on Windows.
2022-04-21 20:33:37 -07:00
Erik Eckstein
700412b39e add the ComputeEffects pass
The ComputeEffects pass derives escape information for function arguments and adds those effects in the function.
This needs a lot of changes in check-lines in the tests, because the effects are printed in SIL
2022-04-21 08:45:08 +02:00
Erik Eckstein
4d5987c469 add passes to dump the results of EscapeInfo
And add test files which uses the passes for verification of EscapeInfo
2022-04-21 08:45:08 +02:00
Richard Wei
6022128f47 Rename compiler _RegexParser module to _CompilerRegexParser.
Work around a build failure due to this module having the same name as the runtime _RegexParser module.
2022-04-09 20:45:25 -07:00
Richard Wei
dd7610f2d2 Rename _MatchingEngine module to _RegexParser (#42081)
As the _MatchingEngine module no longer contains the matching engine, this patch renames this module to describe its role more accurately. Because this module primarily contains the AST and the regex parsing logic, I propose we rename it to "_RegexParser".

Also renames the ExperimentalRegex module in SwiftCompilerSources to _RegexParser for consistency. This would prevent errors if sources in _RegexParser used qualified lookup with the module name.
2022-03-31 11:13:18 -07:00
Erik Eckstein
4824d6d940 Swift SIL: improve BasicBlockRange and InstructionRange and add tests
* add `BasicBlockRange.inclusiveRange`
* add `insert(contentsOf:)`
* add the RangeDumper pass to dump ranges for testing
* and add a test file
2022-03-30 14:45:58 +02:00