Commit Graph

232 Commits

Author SHA1 Message Date
Erik Eckstein
7217722c83 Optimizer: remove the now unused NonTransparentFunctionOwnershipModelEliminator pass
Also remove the `skipStdlibModule` flag from the OwnershipModelEliminator, because it's always false
2025-09-26 08:01:09 +02:00
Erik Eckstein
65c9828cb3 SwiftCompilerSources: move the Context protocols from the Optimizer to the SIL module
This allows to move many SIL APIs and utilities, which require a context, to the SIL module.

The SIL-part of SwiftPassInvocation is extracted into a base class SILContext which now lives in SIL.

Also: simplify the begin/end-pass functions of the SwiftPassInvocation.
2025-07-28 14:19:07 +02:00
Erik Eckstein
1a6ad0c512 Optimizer: add var insertedPhis in SSAUpdater 2025-07-04 11:10:27 +02:00
Erik Eckstein
cf8c8561ca Optimizer: move optimizer bridging code from PassManager.cpp into its own file.
The bridging code was in PassManager.cpp only for historical reasons.
It's now in OptimizerBridging.cpp.

NFC
2025-03-19 09:28:53 +01:00
Erik Eckstein
62ea5b1c81 PassManager: cleanup Passes.def
* move the "SILCombine passes" into a separate file `Simplifications.def` which lives in the SILCombiner directory
* group passes by kind
* rename PASS -> LEGACY_PASS and add a comment to make clear that new passes should be implemented in Swift

NFC
2025-03-18 18:34:52 +01:00
Erik Eckstein
37455b6ab6 Optimizer: use formal types instead of SIL types for classifying dynamic casts.
Casts always work with formal rather than lowered types.
This fixes a potential bug when lowered types are different than formal types, like function types.
2025-03-14 09:45:27 +01:00
Erik Eckstein
9b143d876b PassManager: invalidate analysis if a pass forgot to do so.
If a pass forgot to call invalidateAnalysis but deleted some instructions, the pass-manager can fix this.

Currently following passes do not invalidate analysis when they change the SIL:
* LowerTupleAddrConstructor
* DestroyAddrHoisting
* MoveOnlyChecker
* PredictableDeadAllocationElimination

Ideally we should fix those passes. But with this addition in the pass-manager it's not strictly necessary.

Fixes a compiler crash.
2025-02-14 08:08:43 +01:00
Nate Chandler
1d22288f24 [NFC] SIL: Subpass runs can take values.
Allow continueWithNextSubpassRun to take a SILValue.
2025-01-16 08:18:29 -08:00
Andrew Trick
98da813f02 [NFC] SwiftCompilerSources: add isConvertPointerToPointerArgument 2024-12-14 22:46:54 -08:00
Meghana Gupta
8b1ecb8a71 Add new flag -sil-ownership-verify-all
This flag enables ownership verification after every transform.
2024-12-12 23:55:37 -08:00
Kuba Mracek
6f4ae28520 [ASTMangler] Pass ASTContext to all instantiations of ASTMangler 2024-12-02 15:01:04 -08:00
Erik Eckstein
6a0b7d1f8c ObjectOutliner: create outlined arrays as let variables
This will allow load-simplification to replace a load of such an array.
2024-11-28 09:40:12 +01:00
Erik Eckstein
ed67e36ce5 bridging: reduce #ifdef USED_IN_CPP_SOURCE in bridging headers
Especially avoid any constructors in `#ifdef USED_IN_CPP_SOURCE` blocks, because this breaks Windows ARM64.
2024-10-25 09:47:56 +02:00
Erik Eckstein
709dfc2d21 MandatoryPerformanceOptimization: don't let not-inlinable functions to be inlined
Also refactor canInline.

Fixes a compiler crash.
rdar://137544788
2024-10-15 12:19:50 +02:00
Erik Eckstein
e0533e6125 SIL: add an API to replace all entries of a VTable
* add `ModulePassContext.replaceVTableEntries()`
* add `ModulePassContext.notifyFunctionTablesChanged()`
2024-10-14 14:43:11 +02:00
Erik Eckstein
52deb58251 Optimizer: add the FunctionPassContext.completeLifetime(of: Value) utility
Implemented by bridging the OSSALifetimeCompletion utility
2024-10-11 09:41:37 +02:00
Erik Eckstein
c05234e677 MandatoryPerformanceOptimizations: specialize witness_method instructions
In Embedded Swift, witness method lookup is done from specialized witness tables.
For this to work, the type of witness_method must be specialized as well.
Otherwise the method call would be done with wrong parameter conventions (indirect instead of direct).
2024-10-07 09:00:31 +02:00
Erik Eckstein
10782cf42b SwiftCompilerSources: introduce the AST module
As the optimizer uses more and more AST stuff, it's now time to create an "AST" module.
Initially it defines following AST datastructures:
* declarations: `Decl` + derived classes
* `Conformance`
* `SubstitutionMap`
* `Type` and `CanonicalType`

Some of those were already defined in the SIL module and are now moved to the AST module.
This change also cleans up a few things:
* proper definition of `NominalTypeDecl`-related APIs in `SIL.Type`
* rename `ProtocolConformance` to `Conformance`
* use `AST.Type`/`AST.CanonicalType` instead of `BridgedASTType` in SIL and the Optimizer
2024-10-02 07:10:29 +02:00
Erik Eckstein
7ffd270008 embedded: move the VTableSpecializer pass into MandatoryPerformanceOptimizations
MandatoryPerformanceOptimizations already did most of the vtable specialization work.
So it makes sense to remove the VTableSpecializerPass completely and do everything in MandatoryPerformanceOptimizations.
2024-09-25 19:32:14 +02:00
Erik Eckstein
3775a3548e ModulePassContext: add some utility functions
* `specialize(function:)`
* `deserializeCallees(of:)`
* `createWitnessTable()`
* `createSpecializedVTable`
* `Function.set(isSerialized:)`
2024-09-25 19:32:08 +02:00
Erik Eckstein
0ee51e4d90 StaticInitCloner: skip begin_access instructions when cloning the initial value of a global
Fixes a crash when simplifying a load of an UnsafePointer-global which points to another global.

rdar://135223354
2024-09-14 14:12:36 +02:00
Erik Eckstein
4c49e0039b Verifier: in the swift verifier call the bridged C++ verificationFailure function in case of a failure
This brings all the nice verifier features to the swift verifier, like printing the surrounding instructions in case of a failure, etc.
2024-07-29 17:33:43 +02:00
eeckstein
31c07c95b0 Merge pull request #74689 from eeckstein/refactor-dynamic-self-check
SwiftCompilerSources: refactor `Function.mayBindDynamicSelf`
2024-06-26 08:47:18 +02:00
Erik Eckstein
c61733f985 SwiftCompilerSources: refactor Function.mayBindDynamicSelf
Instead of bridging the whole function, just bridge `hasDynamicSelfMetadata` and do the other work in swift.
2024-06-25 17:59:23 +02:00
Erik Eckstein
718ea4b018 replace require with the new ASSERT macro 2024-06-25 10:45:55 +02: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
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
Erik Eckstein
cc78c8f094 Optimizer: add Context.canMakeStaticObjectReadOnly API 2024-05-16 21:34:35 +02:00
Kshitij
ab751d57ab [Autodiff] Adds logic to generate specialized functions in the closure-spec pass 2024-05-13 11:16:42 -07:00
Kshitij
c6330a7d3f Rev: Addressed feedback 2024-05-02 13:16:12 -07:00
Kshitij
a7f8d6c647 [Autodiff] Adds bridging code in preparation for the Swift based Autodiff closure-spec pass 2024-05-02 09:14:05 -07:00
Nate Chandler
7fbf22c9f2 [NFC] SIL: Add hook to print after every subpass. 2024-04-15 17:49:08 -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
Ben Barham
1fdda023b3 Rename StringRef::endswith references to StringRef::ends_with
Missed this when doing the `startswith` renaming. `endswith` has also
been deprecated upstream (and presumably soon to be removed).
2024-04-01 10:59:16 -07:00
Kuba (Brecka) Mracek
89cd62604b Merge pull request #72472 from kubamracek/embedded-keypaths
[embedded] Compile-time (literal) KeyPaths for Embedded Swift
2024-03-25 10:58:51 -07:00
Erik Eckstein
367dc1a299 SwiftCompilerSources: add OperandSet and OperandWorklist
Implemented by bridging the C++ OperandSet, similar to BasicBlockSet and NodeSet
2024-03-21 15:52:39 +01:00
Erik Eckstein
7afa419dd4 SIL: improve inline bitfields in SILNode, SILBasicBlock and Operand
* Let the customBits and lastInitializedBitfieldID share a single uint64_t. This increases the number of available bits in SILNode and Operand from 8 to 20. Also, it simplifies the Operand class because no PointerIntPairs are used anymore to store the operand pointer fields.
* Instead make the "deleted" flag a separate bool field in SILNode (instead of encoding it with the sign of lastInitializedBitfieldID). Another simplification
* Enable important invariant checks also in release builds by using `require` instead of `assert`. Not catching such errors in release builds would be a disaster.
* Let the Swift optimization passes use all the available bits and not only a fixed amount of 8 (SILNode) and 16 (SILBasicBlock).
2024-03-21 15:52:39 +01:00
Kuba Mracek
b642d771be [embedded] Compile-time (literal) KeyPaths for Embedded Swift
Enable KeyPath/AnyKeyPath/PartialKeyPath/WritableKeyPath in Embedded Swift, but
for compile-time use only:

- Add keypath optimizations into the mandatory optimizations pipeline
- Allow keypath optimizations to look through begin_borrow, to make them work
  even in OSSA.
- If a use of a KeyPath doesn't optimize away, diagnose in PerformanceDiagnostics
- Make UnsafePointer.pointer(to:) transparent to allow the keypath optimization
  to happen in the callers of UnsafePointer.pointer(to:).
2024-03-20 15:35:46 -07:00
Erik Eckstein
308b5f9ff7 Swift Optimizer: add bridging for dynamic cast utilities
* `func canDynamicallyCast`
* `var CheckedCastAddrBranchInst.dynamicCastResult`
2024-03-19 10:54:38 +01:00
Ben Barham
9779c18da3 Rename startswith to starts_with
LLVM is presumably moving towards `std::string_view` -
`StringRef::startswith` is deprecated on tip. `SmallString::startswith`
was just renamed there (maybe with some small deprecation inbetween, but
if so, we've missed it).

The `SmallString::startswith` references were moved to
`.str().starts_with()`, rather than adding the `starts_with` on
`stable/20230725` as we only had a few of them. Open to switching that
over if anyone feels strongly though.
2024-03-13 22:25:47 -07:00
Meghana Gupta
dacf5b47e3 Add an option -sil-break-before-pass-count to break before running a pass when in the debugger
We often look at the SIL output of -sil-print-function and may want to debug a specific pass
after looking at the output.

-sil-break-before-pass-count=<pass_number> will allow to automatically break in the debugger
after <pass_count> of passes are run.

Example:
From -sil-print-function dump:
"SIL function after  #6680, stage MidLevel,Function, pass 38: RedundantLoadElimination"

-Xllvm -sil-break-before-pass-count=6680 will break before running this pass in the debugger
2024-03-12 15:16:01 -07:00
Erik Eckstein
71fcae7fe8 SwiftCompilerSources: add the ability to implement SIL verification in swift 2024-02-22 07:12:10 +01: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
Slava Pestov
06b1aee360 Evaluator: Cache circular evaluation to avoid redundant diagnostics
Previously, if a request R evaluated itself N times, we would emit N
"circular reference" diagnostics. These add no value, so instead let's
cache the user-provided default value on the first circular evaluation.

This changes things slightly so that instead of returning an
llvm::Expected<Request::OutputType>, various evaluator methods take
a callback which can produce the default value.

The existing evaluateOrDefault() interface is unchanged, and a new
evaluateOrFatal() entry point replaces
llvm::cantFail(ctx.evaluator(...)).

Direct callers of the evaluator's operator() were updated to pass in
the callback. The benefit of the callback over evaluateOrDefault() is
that if the default value is expensive to constuct, like a dummy
generic signature, we will only construct it in the case where a
cycle actually happened, otherwise we just delete the callback.

(cherry picked from commit b8fcf1c709efa6cd28e1217bd0efe876f7c0d2b7)
2024-02-09 16:02:24 -08:00
Erik Eckstein
7fb4fc0f36 MandatoryPerformanceOptimizations: fix the linkage of function-signature-specialized functions
We need to keep the original linkage because it would be illegal to call a shared not-serialized function from a serialized function.

Also, rename the API to create the specialized function.
2024-02-02 07:27:38 +01:00
Erik Eckstein
250e2680aa SwiftCompilerSources: add some module-level APIs
* `Context.lookupFunction`
* `ModulePassContext.loadFunction`
* `ModulePassContext.createSpecializedFunctionDeclaration`
* `ModulePassContext.moveFunctionBody`
* `ModulePassContext.mangle(withDeadArguments:)`
2024-01-31 17:16:13 +01:00
Erik Eckstein
04a6bbbb7a docs: add documentation for the -sil-pass-count-config-file option in DebuggingTheCompiler
Also, add this option in swift-autocomplete.bash.
Unrelated: support aliased commands in swift-autocomplete.bash
2024-01-11 11:10:05 +01:00
Erik Eckstein
4aa51ffeab PassManager: add the -sil-pass-count-config-file for easier bisecting pass counts in large projects
This is useful for bisecting passes in large projects:
  1. create a config file from a full build log. E.g. with
        ```
        grep -e '-module-name' build.log  | sed -e 's/.*-module-name \([^ ]*\) .*/\1:10000000/' | sort | uniq > config.txt
        ```
  2. add the `-Xllvm -sil-pass-count-config-file config.txt` option to the project settings
  3. bisect by modifying the counts in the config file
  4. clean-rebuild after each bisecting step
2024-01-09 12:12:33 +01:00
Erik Eckstein
b3cccb3ef5 PassManager: correctly pass the CalleeCache to SILModule::verify
Fixes a compiler warning and improves verification.
2023-12-13 13:45:53 +01:00
Dario Rexin
406fe3eed2 [SILOpt] Allow pre-specializations for _Trivial of known size (#70256)
* [SILOpt] Allow pre-specializations for _Trivial of known size

rdar://119224542

This allows pre-specializations to be generated and applied for trivial types of a shared size.
2023-12-08 19:42:49 -08:00