Commit Graph

72 Commits

Author SHA1 Message Date
Erik Eckstein
b54117c22d GenericSpecializer: drop unused indirect arguments.
If there is no read from an indirect argument, this argument has to be dropped.
At the call site the store to the argument's memory location could have been removed (based on the callee's memory effects).
Therefore, converting such an unused indirect argument to a direct argument, would load an uninitialized value at the call site.
This would lead to verifier errors and in worst case to a miscompile because IRGen can implicitly use dead arguments, e.g. for getting the type of a class reference.
2024-08-26 11:19:12 +02:00
Erik Eckstein
c8e74b8393 Generic specialization: change the mangling for dropped metatype arguments
Instead of adding a "flag" (`m` in `...Tgm5`) make it more generic to allow to drop any unused argument.
Add all dropped arguments with a `t<n-1>` (where `<n-1>` is empty for n === 0). For example `...Ttt2g5`.
2024-08-26 10:43:15 +02:00
Ellie Shin
5ccc4cd394 SIL function can be serialized with different kinds: [serialized] or
[serialized_for_package] if Package CMO is enabled. The latter kind
allows a function to be serialized even if it contains loadable types,
if Package CMO is enabled. Renamed IsSerialized_t as SerializedKind_t.

The tri-state serialization kind requires validating inlinability
depending on the serialization kinds of callee vs caller; e.g. if the
callee is [serialized_for_package], the caller must be _not_ [serialized].
Renamed `hasValidLinkageForFragileInline` as `canBeInlinedIntoCaller`
that takes in its caller's SerializedKind as an argument. Another argument
`assumeFragileCaller` is also added to ensure that the calle sites of
this function know the caller is serialized unless it's called for SIL
inlining optimization passes.

The [serialized_for_package] attribute is allowed for SIL function, global var,
v-table, and witness-table.

Resolves rdar://128406520
2024-05-23 15:53:02 -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
Erik Eckstein
8458481f0e GenericSpecializer: support specializing typed throws
This means to support specializing functions with indirect error results.
Also, when specializing (and the concrete error type is loadable), convert the indirect error to a direct error.

rdar://118532113
2023-11-27 08:51:13 +01:00
Erik Eckstein
d6e86a8cd4 Fix specialization of class method calls in embedded swift.
Unlike in regular swift, The class_method instruction references the specialized version of a class method.
This must be handled in ReabstractionInfo: it needs to work without a concrete callee SIL function.

Also, the SILVerifier must handle the case that a class_method instruction references a specialized method.
2023-11-06 21:08:22 +01:00
Kuba Mracek
d0c2a4ccf8 [embedded] Initial support for generic classes in embedded Swift
- VTableSpecializer, a new pass that synthesizes a new vtable per each observed concrete type used
- Don't use full type metadata refs in embedded Swift
- Lazily emit specialized class metadata (LazySpecializedClassMetadata) in IRGen
- Don't emit regular class metadata for a class decl if it's generic (only emit the specialized metadata)
2023-09-12 09:44:54 -07:00
Erik Eckstein
7839b54b8a GenericSpecializer: drop metatype arguments in specialized functions
And replace them with explicit `metatype` instruction in the entry block.
This allows such metatype instructions to be deleted if they are dead.

This was already done for performance-annotated functions. But now do this for all functions.

It is essential that performance-annotated functions are specialized in the same way as other functions.
Because otherwise it can happen that the same specialization has different performance characteristics in different modules.
And it's up to the linker to select one of those ODR functions when linking.

Also, dropping metatype arguments is good for performance and code size in general.

This change also contains a few bug fixes for dropping metatype arguments.

rdar://110509780
2023-06-15 21:42:01 +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
Erik Eckstein
c3de7c1317 MandatoryGenericSpecializer: drop metatype arguments in specialized functions
And replace them with explicit `metatype` instruction in the entry block.
This allows such metatype instructions to be deleted if they are dead.

rdar://94388453
2022-07-07 08:34:54 +02:00
Erik Eckstein
569a520db2 SILOptimizer: add a mandatory generic-specialization pass.
This pass is only used for functions with performance annotations (@_noLocks, @_noAllocation).
It runs in the mandatory pipeline and specializes all function calls in performance-annotated functions and functions which are called from such functions.
In addition, the pass also does some other related optimizations: devirtualization, constant-folding Builtin.canBeClass, inlining of transparent functions and memory access optimizations.
2021-10-28 18:43:14 +02:00
Erik Eckstein
9e43f493f3 GenericSpecializer: use an alternative mangling if the function has re-abstracted resilient type parameters.
If the specialized function has a re-abstracted (= converted from indirect to direct) resilient argument or return types, use an alternative mangling: "TB" instead of "Tg".
Resilient parameters/returns can be converted from indirect to direct if the specialization is created within the type's resilience domain, i.e. in its module (where the type is loadable).
In this case we need to generate a different mangled name for the specialized function to distinguish it from specializations in other modules, which cannot re-abstract this resilient type.

This fixes a miscompile resulting from ODR-linking specializations from different modules, which in fact have different function signatures.

https://bugs.swift.org/browse/SR-13900
rdar://71914016
2020-12-07 17:23:46 +01:00
Arnold Schwaighofer
b994bf3191 Add support for _specialize(exported: true, ...)
This attribute allows to define a pre-specialized entry point of a
generic function in a library.

The following definition provides a pre-specialized entry point for
`genericFunc(_:)` for the parameter type `Int` that clients of the
library can call.

```
@_specialize(exported: true, where T == Int)
public func genericFunc<T>(_ t: T) { ... }
```

Pre-specializations of internal `@inlinable` functions are allowed.

```
@usableFromInline
internal struct GenericThing<T> {
  @_specialize(exported: true, where T == Int)
  @inlinable
  internal func genericMethod(_ t: T) {
  }
}
```

There is syntax to pre-specialize a method from a different module.

```
import ModuleDefiningGenericFunc

@_specialize(exported: true, target: genericFunc(_:), where T == Double)
func prespecialize_genericFunc(_ t: T) { fatalError("dont call") }

```

Specially marked extensions allow for pre-specialization of internal
methods accross module boundries (respecting `@inlinable` and
`@usableFromInline`).

```
import ModuleDefiningGenericThing
public struct Something {}

@_specializeExtension
extension GenericThing {
  @_specialize(exported: true, target: genericMethod(_:), where T == Something)
  func prespecialize_genericMethod(_ t: T) { fatalError("dont call") }
}
```

rdar://64993425
2020-10-12 09:19:29 -07:00
Erik Eckstein
4017570de7 Generic Specializer: Use getResilienceExpansion() throughout ReabstractionInfo
It must be consistent, otherwise the specialized function types may not match for calls in functions with different resilience expansions.

Fixes an assertion crash in the generic specializer.

rdar://problem/57844964
2019-12-13 11:15:38 +01:00
Arnold Schwaighofer
8aaa7b4dc1 SILOptimizer: Pipe through TypeExpansionContext 2019-11-11 14:21:52 -08:00
Andrew Trick
bddc69c8a6 Organize SILOptimizer/Utils headers. Remove Local.h.
The XXOptUtils.h convention is already established and parallels
the SIL/XXUtils convention.

New:
- InstOptUtils.h
- CFGOptUtils.h
- BasicBlockOptUtils.h
- ValueLifetime.h

Removed:
- Local.h
- Two conflicting CFG.h files

This reorganization is helpful before I introduce more
utilities for block cloning similar to SinkAddressProjections.

Move the control flow utilies out of Local.h, which was an
unreadable, unprincipled mess. Rename it to InstOptUtils.h, and
confine it to small APIs for working with individual instructions.
These are the optimizer's additions to /SIL/InstUtils.h.

Rename CFG.h to CFGOptUtils.h and remove the one in /Analysis. Now
there is only SIL/CFG.h, resolving the naming conflict within the
swift project (this has always been a problem for source tools). Limit
this header to low-level APIs for working with branches and CFG edges.

Add BasicBlockOptUtils.h for block level transforms (it makes me sad
that I can't use BBOptUtils.h, but SIL already has
BasicBlockUtils.h). These are larger APIs for cloning or removing
whole blocks.
2019-10-02 11:34:54 -07:00
Robert Widmann
5a8d0744c3 [NFC] Adopt TypeBase-isms for GenericSignature
Structurally prevent a number of common anti-patterns involving generic
signatures by separating the interface into GenericSignature and the
implementation into GenericSignatureBase.  In particular, this allows
the comparison operators to be deleted which forces callers to
canonicalize the signature or ask to compare pointers explicitly.
2019-09-30 14:04:36 -07:00
Doug Gregor
c8ac000fbb Record specialized signature in (SIL)SpecializeAttr.
Rather than storing the set of input requirements in a
(SIL)SpecializeAttr, store the specialized generic signature. This
prevents clients from having to rebuild the same specialized generic
signature on every use.
2019-08-26 09:54:56 -07:00
Slava Pestov
16d5716e71 SIL: Use the best resilience expansion when lowering types
This is a large patch; I couldn't split it up further while still
keeping things working. There are four things being changed at
once here:

- Places that call SILType::isAddressOnly()/isLoadable() now call
  the SILFunction overload and not the SILModule one.

- SILFunction's overloads of getTypeLowering() and getLoweredType()
  now pass the function's resilience expansion down, instead of
  hardcoding ResilienceExpansion::Minimal.

- Various other places with '// FIXME: Expansion' now use a better
  resilience expansion.

- A few tests were updated to reflect SILGen's improved code
  generation, and some new tests are added to cover more code paths
  that previously were uncovered and only manifested themselves as
  standard library build failures while I was working on this change.
2019-04-26 22:47:59 -04:00
Erik Eckstein
00599eeb3c Check for completeness of the SwiftOnoneSupport library
When compiling SwiftOnoneSupport, issue errors for missing functions which are expected in the module.
This ensures ABI compatibility.

rdar://problem/48924409
2019-03-25 14:57:03 -07:00
Slava Pestov
e9bd15f7fc SILOptimizer: More generic specializer plumbing for using the right resilience expansion
Also NFC for now.
2019-03-13 02:21:53 -04:00
Slava Pestov
00b4662ab9 SILOptimizer: Clean up the generic specializer a bit 2019-03-12 01:16:04 -04:00
Michael Gottesman
c62f31f5dc Inject llvm::SmallBitVector into namespace swift;
I also eliminated all llvm:: before SmallBitVector in the code base.
2018-09-21 09:49:25 -07:00
Michael Gottesman
b72304415d [passmanager] Change the optimizer to use SILOptFunctionBuilder.
I am going to add the code in a bit that does the notifications. I tried to pass
down the builder instead of the pass manager. I also tried not to change the
formatting.

rdar://42301529
2018-08-05 21:21:55 -07:00
Slava Pestov
ebb1198d57 AST: There's no longer any reason to pass SubstitutionMap by const reference
SubstitutionMaps are now just a trivial pointer-sized value, so
pass them by value instead.

I did have to move a couple of functors from Type.h to SubstitutionMap.h
to resolve some issues with forward declarations.
2018-05-19 00:45:36 -07:00
Doug Gregor
f2279520ed [SIL Optimizer] Eliminate some uses of SubstitutionList for debug output. 2018-05-11 13:18:06 -07:00
Doug Gregor
09446defef Eliminate yet more SubstitutionLists from SIL in search of a steady-state 2018-05-11 13:18:06 -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
Doug Gregor
b1f338a00b [SIL Opt] Switch GenericSpecializationInformation over to SubstitutionMap.
There isn't a clean cut point here, so switch
GenericSpecializationInformation from SubstitutionList to
SubstitutionMap and carry along dual SubstitutionMap/SubstitutionList
representations for a small part of ReabstractionInfo.
2018-05-03 09:27:21 -07:00
Adam Nemet
bd8764caaa Add opt remarks to Generic Specializer pass
Adds a combined API to output both debug message and optimization remarks.

The previously added test partial_specialization_debug.sil ensures that it's an
NFC for debug output.
2017-11-16 10:10:24 -08:00
Jordan Rose
f8b7db4e76 Excise the terms "blacklist" and "whitelist" from Swift source. (#11687)
The etymology of these terms isn't about race, but "black" = "blocked"
and "white" = "allowed" isn't really a good look these days. In most
cases we weren't using these terms particularly precisely anyway, so
the rephrasing is actually an improvement.
2017-08-30 09:28:00 -07:00
Roman Levenstein
8503daee0d Implement a more robust way to avoid infinite generic specialization loops
The existing simple mechanism for avoiding infinite generic specialization loops is based on checking the structural depth and width of types passed as generic type parameters. If the depth or the width of a type is above a certain threshold, the type is considered too complex for generic specialization and no specialization is produced. While this approach prevents the possibility of producing an infinite number of generic specializations for ever-growing generic type parameters, it catches the issue too late in some cases, leading to excessive CPU and memory usage.

Therefore, the new method tries to solve the problem at its root. An infinite generic specialization loop can be triggered by specializing a given generic call-site if and only if:
-  Doing so would result in a loop inside the specialization graph represented by the `GenericSpecializationInformations`, i.e. it would produce direct or indirect recursion involving a generic call
-  The substitutions used by the current generic call-site are structurally more complex than the substitutions used by the same call-site in the previous iteration inside specialization graph. More complex in this context means that the new generic type parameter structurally contains the generic type parameter from a previous iteration inside the specialization graph and has greater structural depth, e.g. `Array<Int>` is more complex than `Int`.

The generic specializer now records all the required information about specializations it produces and uses it later to detect and prevent any generic specializations which would result in an infinite specialization loop. It detects them as early as possible and thus reduces compile times, memory consumption and potentially also reduces the code-size by not generating useless specializations.
2017-08-06 12:51:49 -07:00
Roman Levenstein
8fb8cc4367 [generic-specializer] Cosmetic renaming of some vars and functions to match the new naming scheme 2017-04-20 08:16:24 -07:00
Roman Levenstein
686b83b6cb [generic-specializer] Improve comments 2017-04-20 08:16:24 -07:00
Roman Levenstein
f28e28c0a8 [generic-specializer] Big re-factoring of the partial specialization implementation
- Introduced a new helper class FunctionSignaturePartialSpecializer which provides most of the functionality required for producing a specialized generic signature based on the provided substitutions or requirements. The class consists of many small functions, which should make it easier to understand the code.

- Added a full support for partial specialization of generic parameters with generic substitutions (use flag `-Xllvm -sil-partial-specialization-with-generic-substitutions` to enable it)

- Removed the simpler version of the partial specializer which could partially specialize only generic parameters with non-generic substitutions. It is not needed anymore, because we can handle any substations now when performing the partial specialization.

- The functionality used by the EagerSpecializer to implement the partial specializations required by @_specialize is expressed in terms of FunctionSignaturePartialSpecializer as well. The code implementing it is much smaller now.

Partial specialization of generic parameters with generic substitutions is fully functional, but it is disabled by default, because it needs some tweaks when it comes to compile times and size of produced code. These issues will be addressed in the subsequent commits.
2017-04-20 08:16:24 -07:00
Roman Levenstein
ce8d986999 [generic-specializer] Rename OriginalF into Callee 2017-04-20 08:16:24 -07:00
practicalswift
7eb7d5b109 [gardening] Fix 100 typos. 2017-04-18 17:01:42 +02:00
Slava Pestov
8fe8b89b0f SIL: Terminology change: [fragile] => [serialized]
Also, add a third [serializable] state for functions whose bodies we
*can* serialize, but only do so if they're referenced from another
serialized function.

This will be used for bodies synthesized for imported definitions,
such as init(rawValue:), etc, and various thunks, but for now this
change is NFC.
2017-03-29 16:47:28 -07:00
Roman Levenstein
fae0628a97 Implement partial specialization which supports generic substitutions.
Use -sil-partial-specialization-with-generic-substitutions to enable the partial specialization even in cases of substitutions containing generic replacement types.
2017-03-21 08:46:40 -07:00
Erik Eckstein
1625345b90 Remove the old mangler.
NFC
2017-03-17 16:10:36 -07:00
Roman Levenstein
c336dafb04 [sil-generic-specializer] Provide a possibility to disable the indirect-to-direct conversions of parameters and results
This is required by the capture propagation pass. Indirect-to-direct conversions are still performed by default.
2017-03-15 08:27:21 -07:00
Greg Parker
44135ae69a Revert "[sil-capture-propagation] Switch to the new notifyAddFunction API" 2017-03-15 00:49:07 -07:00
Roman Levenstein
b3f558321a [sil-generic-specializer] Provide a possibility to disable the indirect-to-direct conversions of parameters and results
This is required by the capture propagation pass. Indirect-to-direct conversions are still performed by default.
2017-03-14 17:37:19 -07:00
Greg Parker
5c01a65a40 Revert "[sil-capture-propagation] Support generic partial_apply instructions" 2017-03-14 17:32:42 -07:00
Roman Levenstein
65091d6dbf [sil-generic-specializer] Provide a possibility to disable the indirect-to-direct conversions of parameters and results
This is required by the capture propagation pass. Indirect-to-direct conversions are still performed by default.
2017-03-14 08:36:00 -07:00
Roman Levenstein
a9db867e8d Implement partial specialization behind a flag.
Partial specialization is disabled by default. Use -sil-partial-specialization to enable it.

Use -sil-partial-specialization-with-generic-substitutions to enable the partial specialization even in cases of substitutions containing generic replacement types.
2017-03-02 23:29:55 -08:00
Slava Pestov
e069d6553c SILOptimizer: Clean up partial specialization substitution construction 2017-02-12 00:51:28 -08:00
Slava Pestov
5296d02485 AST: More include-what-you-use gardening 2017-02-12 00:51:26 -08:00
Roman Levenstein
26c963f27b Generic specializer API changes to prepare for the new @_specialize attribute and partial specializations. 2017-02-07 23:16:00 -08:00
Slava Pestov
3519e0cd25 AST: Introduce new SubstitutionList type to replace ArrayRef<Substitution>
SubstitutionList is going to be a more compact representation of
a SubstitutionMap, suitable for inline allocation inside another
object.

For now, it's just a typedef for ArrayRef<Substitution>.
2017-02-06 21:36:33 -08:00