Commit Graph

94 Commits

Author SHA1 Message Date
Erik Eckstein
606f7693d4 MandatoryPerformanceOptimizations: don't de-virtualize a generic class method call to specialized method
This results in wrong argument/return calling conventions.
First, the method call must be specialized. Only then the call can be de-virtualized.
Usually, it's done in this order anyway, because the `class_method` instruction is located before the `apply`.
But when inlining functions, the order (in the worklist) can be the other way round.

Fixes a compiler crash.
rdar://154631438
2025-07-01 09:44:47 +02:00
Doug Gregor
bc4cf1236b [SIL] Generalize CastingIsolatedConformances to CheckedCastInstOptions
We are going to need to add more flags to the various checked cast
instructions. Generalize the CastingIsolatedConformances bit in all of
these SIL instructions to an "options" struct that's easier to extend.

Precursor to rdar://152335805.
2025-06-04 17:12:28 -07:00
Doug Gregor
e0b52cd20e [SIL] Extend checked-cast instructions with "prohibit isolated conformances" flag
When performing a dynamic cast to an existential type that satisfies
(Metatype)Sendable, it is unsafe to allow isolated conformances of any
kind to satisfy protocol requirements for the existential. Identify
these cases and mark the corresponding cast instructions with a new flag,
`[prohibit_isolated_conformances]` that will be used to indicate to the
runtime that isolated conformances need to be rejected.
2025-03-26 22:31:47 -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
Erik Eckstein
e14c1d1f62 SIL, Optimizer: update and handle borrowed-from instructions
Compute, update and handle borrowed-from instruction in various utilities and passes.
Also, used borrowed-from to simplify `gatherBorrowIntroducers` and `gatherEnclosingValues`.
Replace those utilities by `Value.getBorrowIntroducers` and `Value.getEnclosingValues`, which return a lazily computed Sequence of borrowed/enclosing values.
2024-04-10 13:38:10 +02:00
Doug Gregor
84a078b361 Teach the speculative devirtualize to deal with error basic blocks without args 2023-11-13 14:51:14 -08:00
Kuba Mracek
afced311f9 [embedded] Fix class_method devirtualizer to consider specialized VTables 2023-11-06 17:08:12 -08:00
Nate Chandler
e5d87f75a8 [SIL] Add source formal type to checked_cast_br.
It is necessary for opaque values where for casts that will newly start
out as checked_cast_brs and be lowered to checked_cast_addr_brs, since
the latter has the source formal type, IRGen relies on being able to
access it, and there's no way in general to obtain the source formal
type from the source lowered type.
2023-07-27 15:04:15 -07:00
Ellie Shin
1c66d02f92 Add package access level to enum AccessLevel
Resolves rdar://104198440
2023-01-19 15:54:18 -08:00
Andrew Trick
e989c9b0e9 SpeculativeDevirtualizer - Fix OSSA support
The OSSA verifier was never enabled for block terminators. So we could
blindly give terminator results any ownership without knowing.
2022-10-22 21:57:47 -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
Erik Eckstein
6ec788ff09 SIL: remove the SILOpenedArchetypesTracker
Instead, put the archetype->instrution map into SIlModule.

SILOpenedArchetypesTracker tried to maintain and reconstruct the mapping locally, e.g. during a use of SILBuilder.
Having a "global" map in SILModule makes the whole logic _much_ simpler.

I'm wondering why we didn't do this in the first place.

This requires that opened archetypes must be unique in a module - which makes sense. This was the case anyway, except for keypath accessors (which I fixed in the previous commit) and in some sil test files.
2021-04-14 08:36:10 +02:00
Slava Pestov
7ccc41a7b7 SIL: Preliminary support for 'apply [noasync]' calls
Refactor SILGen's ApplyOptions into an OptionSet, add a
DoesNotAwait flag to go with DoesNotThrow, and sink it
all down into SILInstruction.h.

Then, replace the isNonThrowing() flag in ApplyInst and
BeginApplyInst with getApplyOptions(), and plumb it
through to TryApplyInst as well.

Set the flag when SILGen emits a sync call to a reasync
function.

When set, this disables the SIL verifier check against
calling async functions from sync functions.

Finally, this allows us to add end-to-end tests for
rdar://problem/71098795.
2021-03-04 22:41:46 -05:00
Michael Gottesman
c026e95cce [ownership] Extract out SILOwnershipKind from ValueOwnershipKind into its own type and rename Invalid -> Any.
This makes it easier to understand conceptually why a ValueOwnershipKind with
Any ownership is invalid and also allowed me to explicitly document the lattice
that relates ownership constraints/value ownership kinds.
2020-11-10 14:29:11 -08:00
Andrew Trick
5ae231eaab Rename getFieldNo() to getFieldIndex().
Do I really need to justify this?
2020-09-24 22:44:13 -07:00
Michael Gottesman
750c8d32ac [opt-remark] Have OptEmitter store a SILFunction instead of a SILModule.
In all of these cases, we already had a SILFunction and were just grabbing its
SILModule instead of passing it in. So this is just an NFC change.

The reason why I am doing this is so that I can force emit opt-remarks on
functions with the semantics attribute "optremark", so I need to be able to
access the SILFunction in the optimization remark infrastructure.
2020-07-24 17:11:47 -07:00
Michael Gottesman
ac3109a21d [eager-specializer] Fix for ownership and add a bunch of missing code coverage for ossa.
Specifically, we were missing a bunch of coverage around specializing guaranteed
parameters and non-trivial values in general.
2020-07-09 21:46:19 -07:00
Anthony Latsis
9fd1aa5d59 [NFC] Pre- increment and decrement where possible 2020-06-01 15:39:29 +03:00
Hamish Knight
2d9b63ed11 A SILModule Always Has An Associated Context
Now that the integrated REPL has been removed,
there is always an associated decl context, and
we can assert as such.
2020-05-10 19:56:12 -07:00
Arnold Schwaighofer
147144baa6 SIL: Thread type expansion context through to function convention apis
This became necessary after recent function type changes that keep
substituted generic function types abstract even after substitution to
correctly handle automatic opaque result type substitution.

Instead of performing the opaque result type substitution as part of
substituting the generic args the underlying type will now be reified as
part of looking at the parameter/return types which happens as part of
the function convention apis.

rdar://62560867
2020-05-04 13:53:30 -07:00
Andrew Trick
70678ab856 SILOptimizer: Fix analysis invalidation after devirtualization.
Devirtualizing try_apply modified the CFG, but passes that run
devirtualization were not invalidating any CFG analyses, such as the
domtree.

This could hypothetically have caused miscompilation, but will be
caught by running with -sil-verify-all.
2020-03-18 10:21:35 -07:00
Meghana Gupta
5285bf7200 Turn off speculative devirtualization by default. (#29359)
Turn off speculative devirtualization by default. Add a flag to support enabling the pass.
Fixes rdar://58778959 and rdar://58429282
2020-01-24 10:23:06 -08:00
Slava Pestov
64971e7e55 SILOptimizer: Fix speculative devirtualization to correctly use casted value
We used to emit this:

  checked_cast_br [exact] %0 : $Foo to $Bar, bb1, bb2

bb1(%1 : $Bar):
  %2 = unchecked_ref_cast %0 : $Foo to %1 : $Bar
  apply ...(..., %2)
  br ...

bb2:
  ...

This is not ownership SIL-safe, because we're re-using the original
operand, which will have already been consumed at that point.

The more immediate problem here is that this is actually not safe
when combined with other optimizations. Suppose that after the
speculative devirtualization, our function is inlined into another
function where the operand was an upcast. Now we have this code:

  %0 = upcast ...
  checked_cast_br [exact] %0 : $Foo to $Bar, bb1, bb2

bb1(%1 : $Bar):
  %2 = unchecked_ref_cast %0 : $Foo to %1 : $Bar
  apply ...(..., %2)
  br ...

bb2:
  ...

The SILCombiner will simplify the unchecked_ref_cast of the upcast
into an unchecked_ref_cast of the upcast's original operand. At
this point, we have an unchecked_ref_cast between two unrelated
class types. While this means the block bb1 is unreachable, we
might perform further optimizations on it before we run the cast
optimizer and delete it altogether.

In particular, the devirtualizer follows chains of reference cast
instructions, and it will get very confused if it finds this invalid
cast between unrelated types.

Fixes <rdar://problem/57712094>, <https://bugs.swift.org/browse/SR-11916>.
2020-01-03 20:17:37 -05:00
Erik Eckstein
d224031efc SpeculativeDevirtualizer: Make sure to link SILFunctions after speculative de-virtualization.
This makes sure that the pass de-serializes all always-emit-into-client functions.
2019-12-04 09:16:28 +01:00
Slava Pestov
53bfc767a3 SIL: Track target formal type for casts
SIL type lowering erases DynamicSelfType, so we generate
incorrect code when casting to DynamicSelfType. Fixing this
requires a fair amount of plumbing, but most of the
changes are mechanical.

Note that the textual SIL syntax for casts has changed
slightly; the target type is now a formal type without a '$',
not a SIL type.

Also, the unconditional_checked_cast_value and
checked_cast_value_br instructions now take the _source_
formal type as well, just like the *_addr forms they are
intended to replace.
2019-11-20 21:30:28 -05:00
Joe Groff
03c7919b4a SIL: Add fields to SILFunctionType for substituted function types.
https://forums.swift.org/t/improving-the-representation-of-polymorphic-interfaces-in-sil-with-substituted-function-types/29711

This prepares SIL to be able to more accurately preserve the calling convention of
polymorphic generic interfaces by letting the type system represent "substituted function types".
We add a couple of fields to SILFunctionType to support this:

- A substitution map, accessed by `getSubstitutions()`, which maps the generic signature
  of the function to its concrete implementation. This will allow, for instance, a protocol
  witness for a requirement of type `<Self: P> (Self, ...) -> ...` for a concrete conforming
  type `Foo` to express its type as `<Self: P> (Self, ...) -> ... for <Foo>`, preserving the relation
  to the protocol interface without relying on the pile of hacks that is the `witness_method`
  protocol.

- A bool for whether the generic signature of the function is "implied" by the substitutions.
  If true, the generic signature isn't really part of the calling convention of the function.
  This will allow closure types to distinguish a closure being passed to a generic function, like
  `<T, U> in (*T, *U) -> T for <Int, String>`, from the concrete type `(*Int, *String) -> Int`,
  which will make it easier for us to differentiate the representation of those as types, for
  instance by giving them different pointer authentication discriminators to harden arm64e
  code.

This patch is currently NFC, it just introduces the new APIs and takes a first pass at updating
code to use them. Much more work will need to be done once we start exercising these new
fields.

This does bifurcate some existing APIs:

- SILFunctionType now has two accessors to get its generic signature.
  `getSubstGenericSignature` gets the generic signature that is used to apply its
  substitution map, if any. `getInvocationGenericSignature` gets the generic signature
  used to invoke the function at apply sites. These differ if the generic signature is
  implied.
- SILParameterInfo and SILResultInfo values carry the unsubstituted types of the parameters
  and results of the function. They now have two APIs to get that type. `getInterfaceType`
  returns the unsubstituted type of the generic interface, and
  `getArgumentType`/`getReturnValueType` produce the substituted type that is used at
  apply sites.
2019-10-25 13:38:51 -07:00
Slava Pestov
72c9840025 SILOptimizer: Fix speculative devirtualization of constructor calls
By unintentionally using SILDeclRef::getFuncDecl() we were getting a nullptr back,
and passing it in to ClassDecl::getOverridingDecl(). This started crashing with a
refactoring I'm making. Fix this and add a test.
2019-07-30 15:14:33 -04:00
Slava Pestov
cece98b2ed AST: Generalize ClassDecl::checkObjCAncestry() to ClassDecl::checkAncestry()
This replaces ClassDecl::hasObjCMembers() and some hand-coded walks.
2019-03-26 18:42:59 -04:00
Slava Pestov
112d1bd561 SILOptimizer: Small cleanups for devirtualizer
Where possible, pass around a ClassDecl or a CanType instead of a
SILType that might wrap a metatype; the unwrapping logic was
repeated in several places.

Also add a FIXME for a bug I found by inspection.
2019-02-28 22:40:54 -05:00
Slava Pestov
c970caedd5 SIL: Optimization remarks can take SILType by value
No need to pass a pointer to SILType; it is a pointer-sized value itself.
2019-02-28 21:28:16 -05:00
Adrian Prantl
ff63eaea6f Remove \brief commands from doxygen comments.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.

Patch produced by

      for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
2018-12-04 15:45:04 -08:00
Andrew Trick
12bb49f57a Expose SIL/BasicBlockUtils for critical edge splitting.
The primary interfaces for CFG manipulation belong in SIL. This is
just what's necessary to fix SILCloner.
2018-10-22 08:34:57 -07:00
Michael Gottesman
d57a88af0d [gardening] Rename references to SILPHIArgument => SILPhiArgument. 2018-09-25 22:23:34 -07:00
Andrew Trick
3a445fee96 Fix the no-swift-assert stdlib build. (#19037)
Partially revert a recent attempt to fix build warnings.

Fixes: <rdar://problem/43824067> Swift CI:
1. OSS - Swift (Tools Opt+No Assert, Stdlib Opt+DebInfo, Test Simulator)
   - OS X (master) - SimplifyCFG crashes at AssertCommon.swift:283:10
2018-08-28 19:59:21 -07:00
Ben Cohen
6567438027 Squash release build warnings (#18986) 2018-08-28 09:56:17 -07:00
John McCall
94b748a14c Update SIL devirtualization to handle begin_apply instructions.
In order to make this reasonable, I needed to shift responsibilities
around a little; the devirtualization operation is now responsible for
replacing uses of the original apply.  I wanted to remove the
phase-separation completely, but there was optimization-remark code
relying on the old apply site not having been deleted yet.

The begin_apply aspects of this aren't testable independently of
replacing materializeForSet because coroutines are currently never
called indirectly.
2018-08-19 19:50:13 -04:00
Bob Wilson
8e330ee344 NFC: Fix indentation around the newly renamed LLVM_DEBUG macro.
Jordan used a sed command to rename DEBUG to LLVM_DEBUG. That caused some
lines to wrap and messed up indentiation for multi-line arguments.
2018-07-21 00:56:18 -07:00
Jordan Rose
cefb0b62ba Replace old DEBUG macro with new LLVM_DEBUG
...using a sed command provided by Vedant:

$ find . -name \*.cpp -print -exec sed -i "" -E "s/ DEBUG\(/ LLVM_DEBUG(/g" {} \;
2018-07-20 14:37:26 -07:00
Doug Gregor
4b5abbddbc [SIL] Teach *ApplyInst to traffic in SubstitutionMap.
Push SubstitutionMaps through most of SILGen and the SIL optimizers
that involve the various *ApplyInsts.
2018-05-11 13:18:06 -07:00
David Zarzycki
8c0c55539f [SIL] NFC: Rename misleading getSwiftRValueType() to getASTType()
Reference storage types are not RValues. Also, use more SILType helper
methods to avoid line wrap.
2018-05-04 08:14:38 -04:00
Adam Nemet
5d7b8106c3 Add opt-remarks to the Speculative Devirtualizer pass 2017-12-18 13:29:46 -08:00
Slava Pestov
1d6ec8e69e SILOptimizer: Fix incorrect check for unsupported generic case
We don't have a way to represent a cast in SIL where the destination
type introduces new archetypes that depend on the input value, sort
of like opening an existential.

Previously we would only rule out the case where the class itself
was generic, but a class can also be nested inside another generic
context.

Fixes <rdar://problem/35478838>.
2017-11-27 22:27:35 -08:00
Slava Pestov
47a3a66e52 SILOptimizer: Kill off duplicated getAllSubclasses() algorithm 2017-11-27 22:20:14 -08:00
Erik Eckstein
90c21be191 Unify the implementation of optimization mode in various option classes.
This commit is mostly refactoring.

*) Introduce a new OptimizationMode enum and use that in SILOptions and IRGenOptions
*) Allow the optimization mode also be specified for specific SILFunctions. This is not used in this commit yet and thus still a NFC.

Also, fixes a minor bug: we didn’t run mandatory IRGen passes for functions with @_semantics("optimize.sil.never")
2017-11-14 11:25:02 -08:00
Slava Pestov
1e6bec0633 SILOptimizer: Don't speculatively devirtualize method calls inside thunks 2017-11-11 16:31:52 -08:00
Slava Pestov
7bf3b90b62 SIL: Split off objc_method / objc_super_method from class_method / super_method
This replaces the '[volatile]' flag. Now, class_method and
super_method are only used for vtable dispatch.

The witness_method instruction is still overloaded for use
with both ObjC protocol requirements and Swift protocol
requirements; the next step is to make it only mean the
latter, also using objc_method for ObjC protocol calls.
2017-10-03 22:13:31 -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
Jordan Rose
1c651973c3 Excise "Accessibility" from the compiler (2/3)
"Accessibility" has a different meaning for app developers, so we've
already deliberately excised it from our diagnostics in favor of terms
like "access control" and "access level". Do the same in the compiler
now that we aren't constantly pulling things into the release branch.

This commit changes the 'Accessibility' enum to be named 'AccessLevel'.
2017-08-28 11:34:44 -07:00
Jordan Rose
5f30eac288 Excise "Accessibility" from the compiler (1/3)
"Accessibility" has a different meaning for app developers, so we've
already deliberately excised it from our diagnostics in favor of terms
like "access control" and "access level". Do the same in the compiler
now that we aren't constantly pulling things into the release branch.

This commit changes the names of methods, fields, a few local
variables, and even a swift-ide-test flag. The full list is below.

accessibilityForDiagnostics -> accessLevelForDiagnostics
checkAccessibility -> checkAccess
checkGenericParamAccessibility -> checkGenericParamAccess
checkTypeAccessibility -> checkTypeAccess
checkWitnessAccessibility -> checkWitnessAccessibility
computeAccessibility -> computeAccessLevel
computeDefaultAccessibility -> computeDefaultAccessLevel
fixItAccessibility -> fixItAccess
getAccessibilityString -> getAccessLevelString
getAccessibilityStrictly -> getAccessLevelStrictly
getAccessibilityUID -> getAccessLevelUID
getActualAccessibility -> getActualAccessLevel
getDefaultAccessibility -> getDefaultAccessLevel
getMaxAccessibility -> getMaxAccessLevel
getOverridableAccessibility -> getOverridableAccessLevel
getRawStableAccessibility -> getRawStableAccessLevel
getSetterAccessibility -> getSetterFormalAccess
hasAccessibility -> hasAccess
hasDefaultAccessibility -> hasDefaultAccessLevel
inferAccessibility -> inferAccessLevel
inferDefaultAccessibility -> inferDefaultAccessLevel
inferSetterAccessibility -> inferSetterAccessLevel
overwriteAccessibility -> overwriteAccess
overwriteSetterAccessibility -> overwriteSetterAccess
printAccessibility -> printAccess
requiredAccessibilityForDiagnostics -> requiredAccessForDiagnostics
resolveAccessibility -> resolveAccessControl
setAccessibility -> setAccess
setSetterAccessibility -> setSetterAccess
setDefaultAndMaxAccessibility -> setDefaultAndMaxAccess
validateAccessibility -> validateAccessControl

Accessibility -> AccessLevel
AccessibilityFilter -> AccessFilter
IgnoreAccessibility -> IgnoreAccessControl
NL_IgnoreAccessibility -> NL_IgnoreAccessControl
PrintAccessibility -> PrintAccess
PrintInternalAccessibilityKeyword -> PrintInternalAccessKeyword
SetterAccessibility -> SetterAccessLevel

setterAccessibility -> setterAccess
storedPropertyAccessibility -> storedPropertyAccess

-print-accessibility -> -print-access
2017-08-28 11:11:57 -07:00
Arnold Schwaighofer
64f2d64b54 Disable SpeculativeDevirtualization at -Os 2017-08-17 14:57:22 -07:00