Commit Graph

44 Commits

Author SHA1 Message Date
Erik Eckstein
3b06bef250 RCIdentityAnalysis: don't let a non-copyable value be the RC root of a copyable value
Otherwise optimizations like retain-sinking might create retain_value instructions with a non-copyable operand.

Fixes a compiler crash.
rdar://139103557
2024-11-05 12:05:34 +01: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
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
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
Andrew Trick
280761f0d1 [move-only] Fix SILOptimizer code motion to preserve value deinits
Multiple code motion and ARC related passes were removing struct/enum
deinits.

Passes fixed include:
- SILCombine
- EarlyCodeMotion
- ReleaseHoisting
- *many* passes that rely on ARC analysis (RCIndentity)
2023-06-06 09:17:53 -07:00
Andrew Trick
f9861ec9c0 Add APIs for terminator results that forward ownership.
Add TermInst::forwardedOperand.

Add SILArgument::forwardedTerminatorResultOperand. This API will be
moved into a proper TerminatorResult abstraction.

Remove getSingleTerminatorOperand, which could be misused because it's
not necessarilly forwarding ownership.

Remove the isTransformationTerminator API, which is not useful or well
defined.

Rewrite several instances of complex logic to handle block arguments
with the simple terminator result API. This defines away potential
bugs where we don't detect casts that perform implicit conversion.

Replace uses of the SILPhiArgument type and code that explicitly
handle block arguments. Control flow is irrelevant in these
situations. SILPhiArgument needs to be deleted ASAP. Instead, use
simple APIs like SILArgument::isTerminatorResult(). Eventually this
will be replaced by a TerminatorResult type.
2022-12-12 12:37:35 -08: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
Erik Eckstein
e8e613bd6a RCIdentity: fix another case of not-RC-identity-preserving casts.
When casting from existentials to class - and vice versa - it can happen that a cast is not RC identity preserving (because of potential bridging).
This also affects mayRelease() of such cast instructions.
For details see the comments in SILDynamicCastInst::isRCIdentityPreserving().

This change also includes some refactoring: I centralized the logic in SILDynamicCastInst::isRCIdentityPreserving().

rdar://problem/70454804
2020-10-28 08:10:41 +01:00
Erik Eckstein
77f1647195 RCIdentityAnalysis: some refactoring to improve clarity.
NFC.
2020-10-12 17:28:30 +02:00
Erik Eckstein
f3d668e362 SILOptimizer: fix ARC code motion problem for metatype casts.
RCIdentityAnalysis must not look through casts which cast from a trivial type, like a metatype, to something which is retainable, like an AnyObject.
On some platforms such casts dynamically allocate a ref-counted box for the metatype.
Now, if the RCRoot of such an AnyObject would be a trivial type, ARC optimizations get confused and might eliminate a retain of such an object completely.

rdar://problem/69900051
2020-10-05 22:18:19 +02:00
Michael Gottesman
2daf1d2050 [opt-remark] When looking for debug_value users, look modulo RC Identity preserving users.
A key concept in late ARC optimization is "RC Identity". In short, a result of
an instruction is rc-identical to an operand of the instruction if one can
safely move a retain (release) from before the instruction on the result to one
after on the operand without changing the program semantics. This creates a
simple model where one can work on equivalence classes of rc-identical values
(using a dominating definition generally as the representative) and thus
optimize/pair retain, release.

When preparing for late ARC optimization, the optimizer will normalize aggregate
ARC operations (retain_value, release_value) into singular strong_retain,
strong_release operations on leaf types of the aggregate that are
non-trivial. As an example, a retain_value on a KlassPair would be canonicalized
into two strong_retain, one for the lhs and one for the rhs. When this is done,
the optimizer generally just creates new struct_extract at the point where the
retain is. In such a case, we may have that the debug_value for the underlying
type is actually on a reformed aggregate whose underlying parts we are
retaining:

```
bb0(%0 : $Builtin.NativeObject):
  strong_retain %0
  %1 = struct $Array(%0 : $Builtin.NativeObject, ...)
  debug_value %1 : $Array, ...
```

By looking through RC identical uses, we can handle a large subset of these
cases without much effort: ones were there is a single owning pointer like Array.
To handle more complex cases we would have to calculate an inverse access path needed to get
back to our value and somehow deal with all of the complexity therein (I am sure
we can do it I just haven't thought through all of the details).

The only interesting behavior that this results in is that when we emit
diagnostics, we just use the rc-identical transitive use debug_value's name
without a projection path. This is because the source location associated with
that debug_value is with a separate value that is rc-identical to the actual
value that we visited during our opt-remark traversal up the def-use
graph. Consider the following example below, noting the comments that show in
the SIL itself what I attempted to explain above.

```
struct KlassPair {
  var lhs: Klass
  var rhs: Klass
}

struct StateWithOwningPointer {
  var state: TrivialState
  var owningPtr: Klass
}

sil @theFunction : $@convention(thin) () -> () {
bb0:
  %0 = apply %getKlassPair() : $@convention(thin) () -> @owned KlassPair
  // This debug_value's name can be combined...
  debug_value %0 : $KlassPair, name "myPair"
  // ... with the access path from the struct_extract here...
  %1 = struct_extract %0 : $KlassPair, #KlassPair.lhs
  // ... to emit a nice diagnostic that 'myPair.lhs' is being retained.
  strong_retain %1 : $Klass

  // In contrast in the case below, we rely on looking through rc-identity uses
  // to find the debug_value. In this case, the source info associated with the
  // debug_value (%2) is no longer associated with the underlying access path we
  // have been tracking upwards (%1 is in our access path list). Instead, we
  // know that the debug_value is rc-identical to whatever value we were
  // originally tracking up (%1) and thus the correct identifier to use is the
  // direct name of the identifier alone (without access path) since that source
  // identifier must be some value in the source that by itself is rc-identical
  // to whatever is being manipulated. Thus if we were to emit the access path
  // here for na rc-identical use we would get "myAdditionalState.owningPtr"
  // which is misleading since ArrayWrapperWithMoreState does not have a field
  // named 'owningPtr', its subfield array does. That being said since
  // rc-identity means a retain_value on the value with the debug_value upon it
  // is equivalent to the access path value we found by walking up the def-use
  // graph from our strong_retain's operand.
  %0a = apply %getStateWithOwningPointer() : $@convention(thin) () -> @owned StateWithOwningPointer
  %1 = struct_extract %0a : $StateWithOwningPointer, #StateWithOwningPointer.owningPtr
  strong_retain %1 : $Klass
  %2 = struct $Array(%0 : $Builtin.NativeObject, ...)
  %3 = struct $ArrayWrapperWithMoreState(%2 : $Array, %moreState : MoreState)
  debug_value %2 : $ArrayWrapperWithMoreState, name "myAdditionalState"
}
```
2020-09-01 23:25:59 -07:00
Jordan Rose
844ae38722 Remove some Swift STLExtras that LLVM now provides (#26443)
No functionality change.
2019-07-31 18:34:52 -07:00
Michael Gottesman
d57a88af0d [gardening] Rename references to SILPHIArgument => SILPhiArgument. 2018-09-25 22:23:34 -07:00
Andrew Trick
9d2af79975 Simplify SILPHIArgument::getIncomingValue.
The client of this interface naturally expects to get back the
incoming phi value. Ignoring dominance and SIL ownership, the incoming
phi value and the block argument should be substitutable.

This method was actually returning the incoming operand for
checked_cast and switch_enum terminators, which is deeply misleading
and has been the source of bugs.

If the client wants to peek though casts, and enums, it should do so
explicitly. getSingleTerminatorOperand[s]() will do just that.
2018-08-30 13:01:39 -07:00
Michael Gottesman
d71d69821f [rcid] Add new method getRCUses() and reimplement getRCUsers() on top of it.
The actual algorithm used here has not changed at all so this is basically a NFC
commit. What this PR does is change the underlying algorithm to return the
operands that it computes internally rather than transforming the operand list
into the user list internally. This enables the callers of the optimization to
find the operand number related to the uses. This makes working with
instructions with multiple operands much easier since one does not need to mess
around with rederiving the operand number from the user instruction/SILValue
pair.

getRCUsers() works now by running getRCUses() internally and then maps the
operand list to the user list.

rdar://38196046
2018-05-15 10:22:23 -07:00
Andrew Trick
e13e1fbe9d Fix a latent bug in RCIdentityAnalysis.getUsers.
This bug was introduced by the migration to multi-value SILInstructions.

This fix will be tested by copy forwarding.

WARNING: To handle the potential existence of multi-value
instructions, don't simply iterate over the results. You may be
inadvertently skipping instructions with no results.

Details:

RCIdentityFunctionInfo::getRCUsers searches the def-use chain to find
all users. When visiting a use, it checks the result to determine if
it's casting or extracting the original reference operand. If, so it
continues along the def-use chain. So, it simply wasn't visiting
instructions with no results.

I inverted the logic so that the special case now requires identifying
a SingleValueInstruction, while the default case is conservative.
2018-04-10 22:08:35 -07:00
John McCall
ab3f77baf2 Make SILInstruction no longer a subclass of ValueBase and
introduce a common superclass, SILNode.

This is in preparation for allowing instructions to have multiple
results.  It is also a somewhat more elegant representation for
instructions that have zero results.  Instructions that are known
to have exactly one result inherit from a class, SingleValueInstruction,
that subclasses both ValueBase and SILInstruction.  Some care must be
taken when working with SILNode pointers and testing for equality;
please see the comment on SILNode for more information.

A number of SIL passes needed to be updated in order to handle this
new distinction between SIL values and SIL instructions.

Note that the SIL parser is now stricter about not trying to assign
a result value from an instruction (like 'return' or 'strong_retain')
that does not produce any.
2017-09-25 02:06:26 -04:00
Robert Widmann
3b202c18d8 Use 'hasAssociatedValues'
Use 'hasAssociatedValues' instead of computing and discarding the
interface type of an enum element decl.  This change has specifically not
been made in conditions that use the presence or absence of the
interface type, only conditions that depend on the presence or absence
of associated values in the enum element decl.
2017-05-22 09:54:47 -07:00
Slava Pestov
dca292c652 Serialization: Don't serialize contextual enum argument type
Storing this separately is unnecessary since we already
serialize the enum element's interface type. Also, this
eliminates one of the few remaining cases where we serialize
archetypes during AST serialization.
2017-01-30 00:08:53 -08:00
practicalswift
6d1ae2a39c [gardening] 2016 → 2017 2017-01-06 16:41:22 +01:00
Michael Gottesman
19f0f6e686 [semantic-sil] Reify the split in SILArgument in between function and block arguments via subclasses.
For a long time, we have:

1. Created methods on SILArgument that only work on either function arguments or
block arguments.
2. Created code paths in the compiler that only allow for "function"
SILArguments or "block" SILArguments.

This commit refactors SILArgument into two subclasses, SILPHIArgument and
SILFunctionArgument, separates the function and block APIs onto the subclasses
(leaving the common APIs on SILArgument). It also goes through and changes all
places in the compiler that conditionalize on one of the forms of SILArgument to
just use the relevant subclass. This is made easier by the relevant APIs not
being on SILArgument anymore. If you take a quick look through you will see that
the API now expresses a lot more of its intention.

The reason why I am performing this refactoring now is that SILFunctionArguments
have a ValueOwnershipKind defined by the given function's signature. On the
other hand, SILBlockArguments have a stored ValueOwnershipKind. Rather than
store ValueOwnershipKind in both instances and in the function case have a dead
variable, I decided to just bite the bullet and fix this.

rdar://29671437
2016-12-18 01:11:28 -08:00
Michael Gottesman
38ec08f45f [gardening] Standardize SILBasicBlock successor/predecessor methods that deal with blocks rather than the full successor data structure to have the suffix 'Block'.
This was already done for getSuccessorBlocks() to distinguish getting successor
blocks from getting the full list of SILSuccessors via getSuccessors(). This
commit just makes all of the successor/predecessor code follow that naming
convention.

Some examples:

getSingleSuccessor() => getSingleSuccessorBlock().
isSuccessor() => isSuccessorBlock().
getPreds() => getPredecessorBlocks().

Really, IMO, we should consider renaming SILSuccessor to a more verbose name so
that it is clear that it is more of an internal detail of SILBasicBlock's
implementation rather than something that one should consider as apart of one's
mental model of the IR when one really wants to be thinking about predecessor
and successor blocks. But that is not what this commit is trying to change, it
is just trying to eliminate a bit of technical debt by making the naming
conventions here consistent.
2016-11-27 12:32:51 -08:00
practicalswift
797b80765f [gardening] Use the correct base URL (https://swift.org) in references to the Swift website
Remove all references to the old non-TLS enabled base URL (http://swift.org)
2016-11-20 17:36:03 +01:00
Michael Gottesman
a8c4cc60e8 [gardening] Rename ValueBase::getParentBB() => getParentBlock(). 2016-11-14 00:39:47 -08:00
Xin Tong
b5b905e3cc Bring back rc identity cache.
This takes off 0.7% of the 27.7% of the time we spent in SILoptimizer when building
Stdlib.
2016-05-25 09:25:27 -07:00
Andrew Trick
f6a2e7c362 [comment] Clarify RC identity over casts. 2016-03-18 04:01:16 -07:00
Dmitri Gribenko
f39b443e24 Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-19 01:16:19 -08:00
Michael Gottesman
13cc88f694 Revert "[arc] Put back in the RCIdentity cache."
This reverts commit 6c728daa61.

This is a speculative revert to try and fix the ASAN build.
2016-02-18 18:25:01 -08:00
Dmitri Gribenko
0f36bec31f Merge remote-tracking branch 'origin/master' into swift-3-api-guidelines 2016-02-18 16:41:35 -08:00
Dmitri Gribenko
65d840c0ae stdlib: lowercase cases in Optional and ImplicitlyUnwrappedOptional 2016-02-18 00:40:33 -08:00
Michael Gottesman
6c728daa61 [arc] Put back in the RCIdentity cache.
This shaves of ~0.5 seconds from ARC when compiling the stdlib on my machine.

I wired up the cache to the delete notification trigger so we are still memory
safe.
2016-02-17 21:56:32 -08:00
Erik Eckstein
74d44b74e7 SIL: remove SILValue::getDef and add a cast operator to ValueBase * as a repelacement. NFC. 2016-01-25 15:00:49 -08:00
Erik Eckstein
506ab9809f SIL: remove getTyp() from SILValue 2016-01-25 15:00:49 -08:00
Erik Eckstein
5a53b31f57 SIL: remove use-iteration functions from SILValue.
They are not needed anymore. NFC.
2016-01-25 15:00:49 -08:00
Erik Eckstein
2db6f3d213 SIL: remove multiple result values from SILValue
As there are no instructions left which produce multiple result values, this is a NFC regarding the generated SIL and generated code.
Although this commit is large, most changes are straightforward adoptions to the changes in the ValueBase and SILValue classes.
2016-01-21 10:30:31 -08:00
Michael Gottesman
551b94b7ae [rc-id] Make RCIdentity strip off single-pred arguments.
This was already done in a few different places in the compiler. There is no
reason not to have it in RCIdentity directly.

rdar://24156136
2016-01-14 18:59:42 -08:00
Michael Gottesman
2f3709443d [rc-id] Make RCIdentity strip off single-pred arguments.
In a bunch of use-cases we use stripSinglePredecessorArgs to eliminate this
case. There is no reason to assume that this is being done in the caller of
RCIdentity. Lets make sure that we handle this case here.

rdar://24156136
2016-01-14 18:19:54 -08:00
Michael Gottesman
f93b8559f5 [gardening] Add some textual flags and organize the code a little bit. NFC. 2016-01-12 14:43:19 -08:00
Michael Gottesman
1b83009456 [gardening][rc-id] Move the main RCIdentityRoot analysis entry point into the RCIdentityRoot analysis section. 2016-01-12 14:31:10 -08:00
Zach Panzarino
e3a4147ac9 Update copyright date 2015-12-31 23:28:40 +00:00
practicalswift
fd70b26033 Fix typos in comments. 2015-12-28 02:15:34 +01:00
ken0nek
fcd8fcee91 Convert [Cc]an not -> [Cc]annot 2015-12-23 00:55:48 +09:00
practicalswift
448880afe4 Fix typo: indentity → identity 2015-12-14 00:11:54 +01:00
Andrew Trick
739b0e9c56 Reorganize SILOptimizer directories for better discoverability.
(libraries now)

It has been generally agreed that we need to do this reorg, and now
seems like the perfect time. Some major pass reorganization is in the
works.

This does not have to be the final word on the matter. The consensus
among those working on the code is that it's much better than what we
had and a better starting point for future bike shedding.

Note that the previous organization was designed to allow separate
analysis and optimization libraries. It turns out this is an
artificial distinction and not an important goal.
2015-12-11 15:14:23 -08:00