Commit Graph

167 Commits

Author SHA1 Message Date
Nate Chandler
aa85694237 [NFC] OSSACompleteLifetime: Renamed. 2025-08-18 09:45:19 -07:00
Andrew Trick
d9dd93560d Support mark_dependence_addr in SIL passes. 2025-03-25 23:02:45 -07:00
Erik Eckstein
0a011cddd8 Remove the old (and now obsolete) PredictableMemoryAccessOptimizations pass 2025-02-07 11:30:35 +01:00
Anthony Latsis
a84dfc8387 [Gardening] Fix some set but not used variables 2025-01-30 21:34:38 +00:00
Andrew Trick
762cdc4c94 Fix PredictableDeadAllocationElimination ownership for empty structs
Preserve ownership for empty non-trivial structs. This currently applies to
~Escapable structs. People often use empty structs to investigate language
behavior. They should behave just like a struct that wraps a
pointer.

Previously, this would crash later during OSSA lifetime completion:

Assertion failed: (isa<UnreachableInst>(block->getTerminator())),
function computeRegion, file OSSALifetimeCompletion.cpp.
2025-01-13 16:36:40 -08:00
Meghana Gupta
d55cb2ad6c Bailout of PredictableMemOpt utilities when in non-ossa
These utilities are called from MandatorPerformanceOptimizations which can run
on serialized non-ossa functions. Add a bailout to handle this case.
2025-01-07 01:19:09 -08:00
Arnold Schwaighofer
dc3c19164a PMO: Don't block pmo for large types - rather only block expansion of tuples 2024-11-04 17:06:24 -08:00
Arnold Schwaighofer
787c996394 LargeTypesReg2Mem: Add a new heuristic that trys harder to keep large
values on the stack

This heuristic can be enabled by passing -Xfrontend
-enable-aggressive-reg2mem.

rdar://123916109
2024-10-31 13:22:06 -07:00
Andrew Trick
af86ad1e16 Test predictable memopt mark_dependence semantics.
Unit tests for mark_dependence support. Required to fix unsafeAddress.
2024-10-15 16:52:07 -07:00
Andrew Trick
19c1617059 PredictableMemOpts: handle mark_dependence source promotion 2024-10-15 16:48:36 -07:00
Andrew Trick
2e9daa444d PredictableMemOpts: handle MarkDependence base uses. 2024-10-15 11:18:43 -07:00
Andrew Trick
830a3664f1 Rename overloaded computeAvailableValues.
Overloaded names create confusion.
2024-10-15 11:18:43 -07:00
Andrew Trick
1ceebec1a0 [NFC] move a block of code into the correct heading.
No source change here, only reorganization that was deferred to avoid
making diffs hard to read.
2024-10-13 16:36:20 -07:00
Andrew Trick
2fd9e5e196 PredictableMemOpt: remove non-OSSA support
PredictableMemOpt only runs with OSSA. The recent refactoring did not
preserve non-OSSA conditions because it adds complexity. This commit
just makes it official.

In the near future, this pass will be replaced by an OSSA-only pass
anyway, so this brings us one small step closer to that.
2024-10-12 23:16:18 -07:00
Andrew Trick
60cb13e164 [NFC] PredictableMemOpts: refactor to allow extension
Fully encapsulate ownership fixup so we can extend it.
2024-10-12 23:16:12 -07:00
Andrew Trick
415d7ab7e2 [NFC] Fix a future PredictableMemOpt bug introduced by the previous commit.
This fixes a logic error that will only be exposed by the additional
functionality that motivated the cleanup. When the additional
functionality is checked in, it will contain a unit test for this fix.

This bug was introduced in:

commit 755a146730 (public/predmem_rewrite)
Author: Andrew Trick <atrick@apple.com>
Date:   Fri Sep 27 22:18:29 2024

    [NFC] rewrite PredictableMemOpts dead allocation elimination
2024-10-03 21:37:34 -07:00
Andrew Trick
755a146730 [NFC] rewrite PredictableMemOpts dead allocation elimination
Generalize the code that promotes the remaining uses of an allocation to make it
readable and extensible. We need to be able to promote allocations with more
interesting uses, namely mark_dependence.
2024-09-27 22:24:18 -07:00
Andrew Trick
b5e3b3befc [NFC] PredictableMemOpts: refactor isFullyAvailable.
For use as a general utility.
2024-09-27 22:23:29 -07:00
Andrew Trick
a635e8a292 [NFC] Refactor PredictableMemoryOptimization
In preparation for adding mark_dependence support.
Required to support addressors (unsafeAddress) in places
other than UnsafePointer.pointee.
2024-09-25 18:18:59 -07:00
Nate Chandler
dd730b849c [LifetimeCompletion] Flag instructions dead_end. 2024-07-03 16:44:35 -07:00
Tim Kientzle
1d961ba22d Add #include "swift/Basic/Assertions.h" to a lot of source files
Although I don't plan to bring over new assertions wholesale
into the current qualification branch, it's entirely possible
that various minor changes in main will use the new assertions;
having this basic support in the release branch will simplify that.
(This is why I'm adding the includes as a separate pass from
rewriting the individual assertions)
2024-06-05 19:37:30 -07:00
Nate Chandler
518de7c6b1 [LifetimeCompletion] Require boundary spec.
Don't default to one boundary or another based on whether the value
being completed is lexical.
2024-05-08 17:15:15 -07:00
Nate Chandler
5383df755a [NFC] LifetimeCompletion: Clarify modes.
Completion is done along a boundary, either the availability or the
liveness boundary.  Represent which with a type.  Update docs and names.
2024-05-01 08:57:01 -07:00
Erik Eckstein
16b59dbbff PredictableMemOpt: fix a crash, caused by a wrong instruction cast
Instead, bail if the cast does not succeed.

rdar://125166206
2024-03-21 18:49:08 +01:00
Michael Gottesman
11f0ff6e32 [sil] Ensure that all SILValues have a parent function by making it so that SILUndef is uniqued at the function instead of module level.
For years, optimizer engineers have been hitting a common bug caused by passes
assuming all SILValues have a parent function only to be surprised by SILUndef.
Generally we see SILUndef not that often so we see this come up later in
testing. This patch eliminates that problem by making SILUndef uniqued at the
function level instead of the module level. This ensures that it makes sense for
SILUndef to have a parent function, eliminating this possibility since we can
define an API to get its parent function.

rdar://123484595
2024-02-27 13:14:47 -08:00
Ben Barham
ef8825bfe6 Migrate llvm::Optional to std::optional
LLVM has removed llvm::Optional, move over to std::optional. Also
clang-format to fix up all the renamed #includes.
2024-02-21 11:20:06 -08:00
Meghana Gupta
06f0d15c45 Use OSSALifetimeCompletion in PredictableMemOpt
The current algorithm to complete lifetimes is incorrect in a few cases.
Use OSSALifetimeCompletion instead.

Fixes rdar://119204768
2023-12-15 15:16:55 -08:00
Erik Eckstein
c551ae0746 PredictableMemOpt: fix wrong handling of re-borrows of a load_borrow
When promoting a load_borrow, the re-borrows were not considered which lead to leaked values.
Now, just bail if a load_borrow has re-borrows.

rdar://118402432
2023-11-15 16:44:08 +01:00
Slava Pestov
05ccd9734c SIL: Introduce ThrowAddrInst 2023-10-31 16:58:54 -04:00
Evan Wilde
309aed4925 Add SmallSetVector replacement
llvm::SmallSetVector changed semantics
(https://reviews.llvm.org/D152497) resulting in build failures in Swift.
The old semantics allowed usage of types that did not have an
`operator==` because `SmallDenseSet` uses `DenseSetInfo<T>::isEqual` to
determine equality. The new implementation switched to using
`std::find`, which internally uses `operator==`. This type is used
pretty frequently with `swift::Type`, which intentionally deletes
`operator==` as it is not the canonical type and therefore cannot be
compared in normal circumstances.

This patch adds a new type-alias to the Swift namespace that provides
the old semantic behavior for `SmallSetVector`. I've also gone through
and replaced usages of `llvm::SmallSetVector` with the
`Swift::SmallSetVector` in places where we're storing a type that
doesn't implement or explicitly deletes `operator==`. The changes to
`llvm::SmallSetVector` should improve compile-time performance, so I
left the `llvm::SmallSetVector` where possible.
2023-07-25 12:28:27 -07:00
Evan Wilde
250082df25 [NFC] Reformat all the LLVMs
Reformatting everything now that we have `llvm` namespaces. I've
separated this from the main commit to help manage merge-conflicts and
for making it a bit easier to read the mega-patch.
2023-06-27 09:03:52 -07:00
Evan Wilde
f3ff561c6f [NFC] add llvm namespace to Optional and None
This is phase-1 of switching from llvm::Optional to std::optional in the
next rebranch. llvm::Optional was removed from upstream LLVM, so we need
to migrate off rather soon. On Darwin, std::optional, and llvm::Optional
have the same layout, so we don't need to be as concerned about ABI
beyond the name mangling. `llvm::Optional` is only returned from one
function in
```
getStandardTypeSubst(StringRef TypeName,
                     bool allowConcurrencyManglings);
```
It's the return value, so it should not impact the mangling of the
function, and the layout is the same as `std::optional`, so it should be
mostly okay. This function doesn't appear to have users, and the ABI was
already broken 2 years ago for concurrency and no one seemed to notice
so this should be "okay".

I'm doing the migration incrementally so that folks working on main can
cherry-pick back to the release/5.9 branch. Once 5.9 is done and locked
away, then we can go through and finish the replacement. Since `None`
and `Optional` show up in contexts where they are not `llvm::None` and
`llvm::Optional`, I'm preparing the work now by going through and
removing the namespace unwrapping and making the `llvm` namespace
explicit. This should make it fairly mechanical to go through and
replace llvm::Optional with std::optional, and llvm::None with
std::nullopt. It's also a change that can be brought onto the
release/5.9 with minimal impact. This should be an NFC change.
2023-06-27 09:03:52 -07: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
Adrian Prantl
286b2e0c58 PredictableMemOpt: Fix source location for injected destroys
It's not correct to copy the location from an instruction and turn it into a
RegularLocation if the Location was, e.g., a CleanupLocation. It's always safe
to use a compilergenerated location instead.

Caught by the dihole verification int the source compatibility suite.

rdar://107984038
2023-04-17 14:28:31 -07:00
Erik Eckstein
4ea9d0454d PredictableMemOpt: fix a wrong debug info location type
Fixes a crash in the debug info verification

rdar://106594725
2023-03-15 16:54:57 +01:00
Andrew Trick
103a6fefb8 LinearLifetimeChecker - make DeadEndBlocks optional 2023-03-01 21:41:46 -08:00
Erik Eckstein
c180d1363e SIL: simplify deleting instruction while iterating over instructions.
Add `deletableInstructions()` and `reverseDeletableInstructions()` in SILBasicBlock.
It allows deleting instructions while iterating over all instructions of the block.
This is a replacement for `InstructionDeleter::updatingRange()`.
It's a simpler implementation than the existing `UpdatingListIterator` and `UpdatingInstructionIteratorRegistry`, because it just needs to keep the prev/next pointers for "deleted" instructions instead of the iterator-registration machinery.
It's also safer, because it doesn't require to delete instructions via a specific instance of an InstructionDeleter (which can be missed easily).
2022-12-12 19:08:54 +01:00
Erik Eckstein
ab1b343dad use new llvm::Optional API
`getValue` -> `value`
`getValueOr` -> `value_or`
`hasValue` -> `has_value`
`map` -> `transform`

The old API will be deprecated in the rebranch.
To avoid merge conflicts, use the new API already in the main branch.

rdar://102362022
2022-11-21 19:44:24 +01: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
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
1e6187c4f4 [sil] Update all usages of old API SILValue::getOwnershipKind() in favor of new ValueBase::getOwnershipKind().
Andy some time ago already created the new API but didn't go through and update
the old occurences. I did that in this PR and then deprecated the old API. The
tree is clean, so I could just remove it, but I decided to be nicer to
downstream people by deprecating it first.
2022-07-26 11:46:23 -07:00
Andrew Trick
2fd4de411e [SIL-opaque] Removed [Unconditional]CheckedCastValue 2022-03-22 17:04:13 -07:00
Erik Eckstein
736470a5c5 MandatoryGenericSpecializer: fix two crashes
* don't run dead alloc on non-ossa functions
* try to de-serialize transparent functions and don't inline if that doesn't succeed

rdar://87622503
2022-01-17 13:59:14 +01:00
Erik Eckstein
dc8d4821dc SILOptimizer: extract predictable access and dead alloc optimizations into stand-alone utility functions 2021-10-28 18:43:14 +02:00
Andrew Trick
0407a4e34a Add UpdatingInstructionIterator.
Track in-use iterators and update them both when instructions are
deleted and when they are added.

Safe iteration in the presence of arbitrary changes now looks like
this:

    for (SILInstruction *inst : deleter.updatingRange(&bb)) {
      modify(inst);
    }
2021-06-02 07:38:27 -07:00
Andrew Trick
0f88e0f3cc Rewrite instruction deletion logic in many passes
Fix innumerable latent bugs with iterator invalidation and callback invocation.

Removes dead code earlier and chips away at all the redundant copies the compiler generates.
2021-06-02 07:38:27 -07:00
Michael Gottesman
2827d72029 [pred-dead-alloc] Be more conservative and bail if we did not find a complete available value when cleaning up takes. 2021-02-12 23:20:17 -08:00
Michael Gottesman
705373c205 [pred-deadalloc-elim] Fix memory safety issue and handle promoting paths where there is dynamically no value by inserting compensating destroys.
This commit is fixing two things:

1. In certain cases, we are seeing cases where either SILGen or the optimizer
are eliminating destroy_addr along paths where we know that an enum is
dynamically trivial. This can not be expressed in OSSA, so I added code to
pred-deadalloc-elim so that I check if any of our available values after we
finish promoting away an allocation now need to have their consuming use set
completed.

2. That led me to discover that in certain cases load [take] that we were
promoting were available values of other load [take]. This means that we have a
memory safety issue if we promote one load before the other. Consider the
following SIL:

```
%mem = alloc_stack
store %arg to [init] %mem
%0 = load [take] %mem
store %0 to [init] %mem
%1 = load [take] %mem
destroy_value %1
dealloc_stack %mem
```

In this case, if we eliminate %0 before we eliminate %1, we will have a stale
pointer to %0.

I also took this as an opportunity to turn off predictable mem access opt on SIL
that was deserialized canonicalized and non-OSSA SIL. We evidently need to still
do this for pred mem opts for perf reasons (not sure why). But I am pretty sure
this isn't needed and allows me to avoid some nasty code.
2021-02-12 23:20:17 -08:00
Erik Eckstein
fe10f98cf0 SIL: rename the SILBitfield.h header file to BasicBlockBits.h
NFC
2021-02-12 11:15:55 +01:00
Erik Eckstein
f48191966c SILOptimizer: use BasicBlockSet instead of SmallPtrSet in various transformations.
It reduces compile time.
2021-01-27 10:31:17 +01:00