Commit Graph

362 Commits

Author SHA1 Message Date
Erik Eckstein
d25b1ed834 Optimizer: Replace the MandatoryCombine pass with a Simplification pass, which is implemented in Swift
The Swift Simplification pass can do more than the old MandatoryCombine pass: simplification of more instruction types and dead code elimination.
The result is a better -Onone performance while still keeping debug info consistent.

Currently following code patterns are simplified:
* `struct` -> `struct_extract`
* `enum` -> `unchecked_enum_data`
* `partial_apply` -> `apply`
* `br` to a 1:1 related block
* `cond_br` with a constant condition
* `isConcrete` and `is_same_metadata` builtins

More simplifications can be added in the future.

rdar://96708429
rdar://104562580
2023-02-09 06:50:05 +01:00
Michael Gottesman
a624fece3e [move-only] Move MoveOnlyObjectChecker /before/ MoveOnlyAddressChecker in the pass pipeline and move post checker verification into the MoveOnlyAddressChecker.
The reason why I am doing this is that:

1. There are sometimes copy_value on move only values loaded from memory that
the MoveOnlyAddressChecker needs to eliminate.

2. Previously, the move only address checker did not rewrite copy_value ->
explicit_copy_value if it failed in diagnostics (it did handle load [copy] and
copy_addr though). This could then cause the copy_value elimination verification
in the MoveOnlyObjectChecker to then fail. So this suggested that I needed to
move the verification from the object checkt to the address checker.

3. If we run the verification in the address checker, then the object checker
(which previously ran before the address checker) naturally needed to run
/before/ the address checker.
2023-02-08 13:29:39 -08:00
Michael Gottesman
48546fd6d3 [move-only] Move BorrowToDestructureTransform back into the Object Checker rather than as a separate pass.
The reason that I am doing this is I discovered that we emit worse quality
diagnostics since if we emit an error while running the borrow to destructure
transform, we want to do a complete cleanup to be safe (e.x.: converting
copy_value -> explicit_copy_value). This causes the object checker to then not
emit any additional diagnostics for other variables that were not impacted by
the BorrowToDestructureTransform, reducing the quality of diagnostics in a
significant way that isn't needed.
2023-01-31 15:24:17 -08:00
Michael Gottesman
c9ce3a9722 Merge pull request #63270 from gottesmm/pr-58e55bb70e30107d86e3c437c972c9f0adbce7b4
[move-only] Rather than calling the borrow to destructure transform from the MoveOnlyObjectChecker, make its own pass.
2023-01-27 17:18:21 -08:00
Michael Gottesman
96140ddfe9 [move-only] Rather than calling the borrow to destructure transform from the MoveOnlyObjectChecker, make its own pass.
This is a cleaner separation of concerns. The reason why I did not do this
originally is that I thought I would need to reuse this functionality in the
address checker, but this issue actually does not come up there since we project
the address and then load instead of load and then project.
2023-01-27 14:23:53 -08:00
Michael Gottesman
3a538282ff [consume-operator] Rename checker passes to have ConsumeOperator in the name to reduce confusion with MoveChecking passes.
Just trying to eliminate potential confusion.
2023-01-27 13:46:32 -08:00
Joe Groff
9eefc2ec65 Merge pull request #61772 from jckarter/move-passes-after-closure-lifetime-fixup
SIL: Perform move-only diag passes after ClosureLifetimeFixup.
2022-10-28 10:26:36 -07:00
Joe Groff
394e6e42d7 SIL: Perform move-only diag passes after ClosureLifetimeFixup.
ClosureLifetimeFixup finalizes the lifetimes of nonescaping closures,
which allows us to analyze their captures as borrows and permit move-
only types to be captured by them.
2022-10-27 13:46:34 -07:00
Michael Gottesman
50163aad3b Make the option sil-stop-optzns-before-lowering-ownership work at -Onone.
Just wanted to look at -Onone codegen before ownership was lowered and realized
that this optimization did not work at -Onone.
2022-10-24 19:09:20 -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
Josh Soref
730b16c569 Spelling siloptimizer
* access
* accessed
* accesses
* accessor
* acquiring
* across
* activated
* additive
* address
* addresses'
* aggregated
* analysis
* and
* appropriately
* archetype
* argument
* associated
* availability
* barriers
* because
* been
* beginning
* belongs
* beneficial
* blocks
* borrow
* builtin
* cannot
* canonical
* canonicalize
* clazz
* cleanup
* coalesceable
* coalesced
* comparisons
* completely
* component
* computed
* concrete
* conjunction
* conservatively
* constituent
* construct
* consuming
* containing
* covered
* creates
* critical
* dataflow
* declaration
* defined
* defining
* definition
* deinitialization
* deliberately
* dependencies
* dependent
* deserialized
* destroy
* deterministic
* deterministically
* devirtualizes
* diagnostic
* diagnostics
* differentiation
* disable
* discipline
* dominate
* dominates
* don't
* element
* eliminate
* eliminating
* elimination
* embedded
* encounter
* epilogue
* epsilon
* escape
* escaping
* essential
* evaluating
* evaluation
* evaluator
* executing
* existential
* existentials
* explicit
* expression
* extended
* extension
* extract
* for
* from
* function
* generic
* guarantee
* guaranteed
* happened
* heuristic
* however
* identifiable
* immediately
* implementation
* improper
* include
* infinite
* initialize
* initialized
* initializer
* inside
* instruction
* interference
* interferes
* interleaved
* internal
* intersection
* intractable
* intrinsic
* invalidates
* irreducible
* irrelevant
* language
* lifetime
* literal
* looks
* materialize
* meaning
* mergeable
* might
* mimics
* modification
* modifies
* multiple
* mutating
* necessarily
* necessary
* needsmultiplecopies
* nonetheless
* nothing
* occurred
* occurs
* optimization
* optimizing
* original
* outside
* overflow
* overlapping
* overridden
* owned
* ownership
* parallel
* parameter
* paths
* patterns
* pipeline
* plottable
* possible
* potentially
* practically
* preamble
* precede
* preceding
* predecessor
* preferable
* preparation
* probably
* projection
* properties
* property
* protocol
* reabstraction
* reachable
* recognized
* recursive
* recursively
* redundant
* reentrancy
* referenced
* registry
* reinitialization
* reload
* represent
* requires
* response
* responsible
* retrieving
* returned
* returning
* returns
* rewriting
* rewritten
* sample
* scenarios
* scope
* should
* sideeffects
* similar
* simplify
* simplifycfg
* somewhat
* spaghetti
* specialization
* specializations
* specialized
* specially
* statistically
* substitute
* substitution
* succeeds
* successful
* successfully
* successor
* superfluous
* surprisingly
* suspension
* swift
* targeted
* that
* that our
* the
* therefore
* this
* those
* threshold
* through
* transform
* transformation
* truncated
* ultimate
* unchecked
* uninitialized
* unlikely
* unmanaged
* unoptimized key
* updataflow
* usefulness
* utilities
* villain
* whenever
* writes

Signed-off-by: Josh Soref <jsoref@users.noreply.github.com>
2022-10-03 18:31:33 -04:00
Michael Gottesman
b1738c63c7 [move-only] Implement MoveOnlyDeinitInsertion that converts destroy_value of known deinit move only types to call the deinit directly.
NOTE: If one does not define a deinit on a move only type, if a destroy_value
lasts until IRGen time we will assert since I haven't implemented support in
IRGen for the destroy value witness for move only types. That being said, just
creating a deinit by adding to such a type:

```
deinit {}
```

is pretty low overhead for the experiments we want to use this for.
2022-09-20 15:19:31 -07:00
Michael Gottesman
0a16cc362a [move-only] Implement an initial version of the move only address checker.
Some notes:

1. I added support for both loadable/address only types.

2. These tests are based off of porting the move only object tests for inout,
vars, mutating self, etc.

3. I did not include already written tests for address only types in this
specific merge since I need to change us to borrow move only var like types.
Without that, we get a lot of spurious error msgs and the burden of writing that
is not worth it. So instead in a forthcoming commit where I fix that issue in
SILGen, I will commit the corresponding address only tests for this work.

4. I did not include support for trivial types in this. I am going to do
object/address for that at the same time.
2022-09-11 18:57:32 -07: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
Michael Gottesman
dca78695f0 [move-only] Move the non-trivial move only type eliminator to the end of the guaranteed pipeline.
Still being careful with it. With time I want to move it back to IRGen.
2022-09-05 20:41:45 -07:00
Michael Gottesman
9d92d40060 [move-only] Move most move only passes earlier in the pass pipeline before Mandatory Inlining, right after DI. 2022-09-05 20:41:44 -07:00
Michael Gottesman
4dc6e6ecc4 [move-keyword] Remove old implementation.
By using the keyword instead of the function, we actually get a much simpler
implementation since we avoid all of the machinery of SILGenApply. Given that we
are going down that path, I am removing the old builtin implementation since it
is dead code.

The reason why I am removing this now is that in a subsequent commit, I want to
move all of the ownership checking passes to run /before/ mandatory inlining. I
originally placed the passes after mandatory inlining since the function version
of the move keyword was transparent and needing to be inlined before we could
process it. Since we use the keyword now, that is no longer an issue.
2022-09-04 01:19:01 -07:00
Meghana Gupta
bd295d73a6 Move OwnershipLowering to just before SimplifyCFG 2022-08-30 20:50:00 -07:00
Michael Gottesman
6440e16440 [move-only] Move object checking before PredMemOpts.
Otherwise in certain cases due to load promotion, we emit incorrect errors. As
an example:

let x = ...
var y = x
print(y)

would show an error that x is consumed twice... which is incorrect.
2022-08-21 22:46:34 -07:00
Michael Gottesman
3e52007562 [builtin] Remove "unsafeGuaranteed" and related code since Unmanaged now has an Ownership SSA based implementation that works completely in SILGen.
This isn't used in the stdlib anymore as well.
2022-08-21 01:22:36 -07:00
Michael Gottesman
e65601f592 Rename MoveOnlyChecker -> MoveOnlyObjectChecker.cpp. 2022-08-16 16:19:55 -07:00
Erik Eckstein
f4f2ca13f6 SIL Optimizer: add the OptimizeHopToExecutor in the late pipeline.
This is important to remove redundant `hop_to_executor` instructions after inlining.

rdar://95796233
2022-07-20 21:48:44 +02:00
Erik Eckstein
1cbea04103 run the TargetConstantFolding pass also at -Onone
This is important for performance diagnostics: it’s assumed that (non-generic) MemoryLayout constants do not need to create metadata at runtime. At Onone this is only guaranteed if the TargetConstantFolding pass runs.

rdar://94836837
2022-07-07 08:35:04 +02:00
Michael Gottesman
6a24087f90 Merge pull request #59611 from gottesmm/moveonly-rebase
[no-implicit-copy] Update SILGen/move checker to work with new patterns from copyable_to_moveonly and friends.
2022-06-28 13:45:15 -07:00
Erik Eckstein
f420468b27 SILOptimizer: add a pass to perform target specific constant folding.
TargetConstantFolding performs constant folding for target-specific values:

```
  MemoryLayout<S>.size
  MemoryLayout<S>.alignment
  MemoryLayout<S>.stride
```

Constant folding those expressions in the middle of the SIL pipeline enables other optimizations to e.g. allow such expressions in statically allocated global variables (done by the GlobalOpt pass).

The implementation requires to create a temporary IRGenModule, which is used to get actual constant sizes/alignments from IRGen's type lowering.

rdar://94831524
2022-06-23 22:16:42 +02:00
Michael Gottesman
2f9d67de18 [move-only] Add a new pass called MoveOnlyTypeEliminator that runs after move only checking.
This pass lowers moveonly-ness from the IR after we have finished move only
checking. The transform can be configured in two ways: such that it only handles
trivial types and such that it does trivial and non-trivial types. For ease of
use, I created two top level transforms (TrivialMoveOnlyTypeEliminator and
MoveOnlyTypeElimintor) that invoke the two behaviors by configuring the
underlying transform slightly differently.

For now, I am running first the trivial-only and then the all of the above
lowering. The trivial only pass will remain at this part of the pipeline
forever, but with time we are going to move the lower everything pass later into
the pipeline once I have audited the optimizer pipeline to just not perform any
work on move only types. That being said, currently we do not have this
guarantee and this patch at least improves the world and lets us codegen no
implicit copy code again.
2022-06-22 15:31:57 -07: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
Meghana Gupta
fb0be6ad97 Run AddressLowering after DI and RawSILInstLowering 2022-05-31 20:49:29 -07:00
Michael Gottesman
dd5d2f49ca Merge pull request #58410 from gottesmm/move-function-dbg-info-dataflow
[debug-info] Implement a global dataflow that propagates debug info for async vars and clones the dbg info after funclet points.
2022-05-06 14:35:52 -07:00
Michael Gottesman
640d5902e6 [debug-info] Implement a global dataflow that propagates debug info for async vars and clones the dbg info after funclet points.
The overall flow of the pass is:

1. We walk over the blocks summarizing the debug info instruction the blocks gen
as well as whether or not the block had an async funclet edge with in it.

2. We then perform a simple forward iterative optimistic dataflow using
intersection at merge points. At points where we find after merging that we have
a conflict and thus need to stop propagation, we insert a debug_value undef.

3. We then walk the CFG again visiting only blocks that we know had async
funclet edges. We then walk each said block from top to bottom starting with the
propagating gen information and updating as we go, dumping the current set of
debug_info we are tracking after each coroutine funclet boundary.

rdar://85020571
2022-05-05 14:16:51 -07:00
Arnold Schwaighofer
bcf24e4715 Eager specializer: Fix pre-specialization of imported code
We must no pre-specialize imported code (except if this was explicitly
called for by the importing module).

Therefore, don't pre-specialize `shared` definitions based on their
pre-specialization attributes.

Rather, only pre-specialize if the pre-specialization is called for
using a `target: "theFunctionToSpecialize"` parameter.

Run OnonePrespecializations before serialization so that module native functions
are not yet marked `shared` and can be identified as native.

rdar://92337361
2022-05-04 08:32:41 -07:00
Joe Groff
85760d5348 SIL: Add a PartialApplySimplification pass.
This will turn `partial_apply` instructions into explicit box construction and
extraction code sequences. To begin with, recognize when a private function
is only used in partial applications and directly modify the function to be
usable as a closure invocation function. This simplifies the lowering in IRGen
and avoids generating a "partial application forwarder" thunk.
2022-04-21 12:47:44 -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
Nate Chandler
11e5c97f45 [SILOpt] Added flag to disable destroy hoisting.
It is on by default.  The default changes with the value of the
CopyPropagation setting.  But it can still be overridden.
2022-04-05 20:01:17 -07:00
Michael Gottesman
1e2b94ec04 Merge pull request #41944 from gottesmm/add_initial_dominance_impl
[move-function] Add initial support for moved lets over async funclet edges
2022-03-22 09:33:53 -07:00
Andrew Trick
406aa86d2e Merge pull request #41557 from atrick/addrlower-update
Update and reimplement AddressLowering pass (for SIL opaque values).
2022-03-21 22:15:06 -07:00
Michael Gottesman
056132cca0 [move-function] Add a new pass that propagates debug_value [moved] into coroutine func-lets.
NOTE: debug_value [moved] appearing in the source code implies a _move was
used. So this will not effect current stable swift code.

This is just a first version of this that I am using to commit/bring up tests
for IRGen supporting a full dataflow version of this patch.

Big picture is that there is a bunch of work that is done in the LLVM level in
the coroutine splitter to work around communicating live variables in the
various coroutine func-lets. This logic is all done with debug.declare and we
would need to update that logic in the coroutine splitter to handle
debug.addr. Rather than do this, after some conversation, AdrianP and I realized
that we could get the same effect of a debug.declare by just redeclaring the
current live set of debug_value after each possible coroutine funclet start. To
do this in full generality, we need a full dataflow but just to bring this up we
initially perform a dominance propagation algorithm of the following sort:

1. We walk the CFG along successors. By doing this we guarantee that we visit
   blocks after their dominators.

2. When we visit a block, we walk the block from start->end. During this walk:

   a. We grab a new block state from the centralized block->blockState map. This
      state is a [SILDebugVariable : DebugValueInst].

   b. If we see a debug_value, we map blockState[debug_value.getDbgVar()] =
      debug_value. This ensures that when we get to the bottom of the block, we
      have pairs of SILDebugVariable + last debug_value on it.

   c. If we see any coroutine funclet boundaries, we clone the current tracked
      set of our block state and then walk up the dom tree dumping in each block
      any debug_value with a SILDebugVariable that we have not already
      dumped. This is maintained by using a visited set of SILDebugVariable for
      each funclet boundary.

The end result is that at the beginning of each funclet we will basically
declare the debug info for an addr.

This is insufficient of course for moves that are in conditional control flow,
e.x.:

```
let x = Klass()
if boolValue {
  await asyncCall()
  let _ = _move(x)
}
```

but this at least lets me begin to write tests for this in lldb using straight
line code and work out the rest of the issues in CodeGen using those tests.
2022-03-21 14:20:06 -07:00
Nate Chandler
7c1c9cea94 [SILOpt] Disabled DestroyHoisting. 2022-03-16 20:45:40 -07:00
Andrew Trick
2907c61203 SILModule::hasLoweredAddress 2022-03-09 17:18:15 -08:00
Andrew Trick
7aeada1151 Merge pull request #41469 from atrick/disable-mandatory-copyprop
Disable MandatoryCopyPropagation.
2022-02-19 03:38:47 -08:00
Andrew Trick
4eb7351f4d Disable MandatoryCopyPropagation.
Mandatory copy propagation was primarily a stop-gap until lexcial
lifetimes were implemented. It supposedly made variables lifetimes
more consistent between -O and -Onone builds. Now that lexical
lifetimes are enabled, it is no longer needed for that purpose (and
will never satisfactorily meet that goal anyway).

Mandatory copy propagation may be enabled again later as a -Onone "
optimization. But that requires a more careful audit of the effect on
debug information.

For now, it should be disabled.
2022-02-18 17:29:04 -08:00
Nate Chandler
ed1b3f2968 [SILOpt] Put DestroyHoisting behind flag.
Tested that import enum case is optimized appropriately without the
classic DestroyHoisting pass.
2022-02-18 10:10:18 -08:00
Nate Chandler
014876d4ca [SILOpt] Enabled SSADestroyHoisting.
The new destroy_addr hoisting respects lexical lifetimes.  It will
replace all other destory hoisting.
2022-02-10 20:17:57 -08:00
Kavon Farvardin
4f28b87de9 basic implementation of flow-isolation for SE-327
Flow-isolation is a diagnostic SIL pass that finds
unsafe accesses to properties in initializers and
deinitializers that cannot gain isolation to otherwise
protect those accesses from concurrent modifications.
See SE-327 for more details about how and why it exists.

This commit includes changes and features like:

- The removal of the escaping-use restriction
- Flow-isolation that works properly with `defer` statements
- Flow-isolation with an emphasis on helpful diagnostics.

It also includes known issues like:

- Local / nonescaping functions are not analyzed by
  flow-isolation, despite it being technically possible.
  The main challenge in supporting it efficiently is that
  such functions do not have a single exit-point, like
  a `defer`. In particular, arbitrary functions can throw
  so there are points where nonisolation should _not_ flow
  out of the function at a call-site in the initializer, etc.

- The implementation of the flow-isolation pass is not
  particularly memory efficient; it relies on BitDataflow
  even though the particular flow problem is simple.
  So, a more efficient implementation would be specialized for
  this particular problem, etc.

There are also some changes to the Swift language itself: defer
will respect its context when deciding its property access kind.

Previously, a defer in an initializer would always access a stored
property through its accessor methods, instead of doing so directly
like its enclosing function might. This inconsistency is unfortunate,
so for Swift 6+ we make this consistent. For Swift 5, only a defer
in a function that is a member of the following kinds of types
will gain this consistency:

- an actor type
- any nominal type that is actor-isolated, excluding UnsafeGlobalActor.

These types are still rather new, so there is much less of a chance of
breaking expected behaviors around defer. In particular, the danger is
that users are relying on the behavior of defer triggering a property
observer within an init or deinit, when it would not be triggering it
without the defer.
2022-02-02 13:31:14 -07:00
Michael Gottesman
0032b3818c [move-only] Move move function kills values checking and move only value lifetime checking before diagnostic constant prop.
This is part of a larger piece of work that is going to introduce the ability in
SIL for us to wrap trivial values in a move only type wrapper and thus perform
ownership based diagnostics upon those trivial values. This is being done now so
that we can perform SSA based ownership diagnostics on trivial types. This will
allow us to eventually be able to do things like no escape analysis on
UnsafePointer.

That all sounds great, but also we must consider how this effects the rest of
the optimizer. For instance, what if we want to have a no escape integer and
have overflow checks used upon it! To ensure that we can do this, the authors
realized that we did not need to persist the ownership information so late in
that part of the pipeline and we can just do the ownership checking earlier than
constant propagation and then lower. This is safe to do since the rest of the
optimizer will not introduce escapes of a pointer or extra copies unlike if the
underlying non move only type variant was also non-trivial.

With that in hand, this PR moves these two move only passes earlier than
constant propagation for this purpose. The reason they were put in the current
position vs earlier is that I wanted them to run after predictable dead
allocation elimination since it cleaned up the SIL I was reading as I designed
it. There isn't any reason that they can't run earlier. Once I bring in the new
SIL move only type wrapper, after these run, the trivial type lowering will then
run.
2022-01-28 14:02:47 -08:00
Max Desiatov
42e6fac1ea libswift: reimplement AssumeSingleThreaded pass 2022-01-10 08:47:43 +00:00
Meghana Gupta
a52b8966c6 Move non-transparent OME to just before Mem2Reg 2021-12-23 17:42:31 -08:00
Erik Eckstein
408cf02bc8 rework cross-module-optimization
* rename the CrossModuleSerializationSetup pass to simply CrossModuleOptimization
* remove the CMO specific serializer pass. Instead run the CrossModuleSerializationSetup pass directly before the standard serializer pass.
* correctly handle shared functions (e.g. specializations)
* refactoring
2021-12-20 11:33:02 +01:00
Nate Chandler
59ae5180ba [NFC] Used SILOption field for copy propagation.
Replaced the quad-state (of state which one was illegal) of two booleans
(EnableCopyPropagation and DisableCopyPropagation) with an enum.
2021-12-13 17:44:28 -08:00