Skip to content

Commit f4d021f

Browse files
[Driver][Frontend] Introduce load-pass-plugin option
Allow dynamic loading of LLVM passes via `load-pass-plugin` option passed to the Swift compiler driver.
1 parent c2a5028 commit f4d021f

File tree

10 files changed

+119
-18
lines changed

10 files changed

+119
-18
lines changed

include/swift/AST/DiagnosticsIRGen.def

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,5 +80,8 @@ ERROR(attr_objc_implementation_resilient_property_deployment_target, none,
8080
"target to %0 %2 or store this value in an object or 'any' type",
8181
(StringRef, const llvm::VersionTuple, const llvm::VersionTuple))
8282

83+
ERROR(unable_to_load_pass_plugin,none,
84+
"unable to load plugin '%0': '%1'", (StringRef, StringRef))
85+
8386
#define UNDEFINE_DIAGNOSTIC_MACROS
8487
#include "DefineDiagnosticMacros.h"

include/swift/AST/IRGenOptions.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,6 +519,9 @@ class IRGenOptions {
519519
/// Emit a .casid file next to the object file if CAS Backend is used.
520520
bool EmitCASIDFile;
521521

522+
/// Paths to the pass plugins registered via -load-pass-plugin.
523+
std::vector<std::string> LLVMPassPlugins;
524+
522525
IRGenOptions()
523526
: OutputKind(IRGenOutputKind::LLVMAssemblyAfterOptimization),
524527
Verify(true), OptMode(OptimizationMode::NotSet),

include/swift/Option/Options.td

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1761,6 +1761,11 @@ def use_interface_for_module: Separate<["-", "--"], "use-interface-for-module">,
17611761
HelpText<"Prefer loading these modules via interface">,
17621762
MetaVarName<"<name>">;
17631763

1764+
def load_pass_plugin_EQ : Joined<["-"], "load-pass-plugin=">,
1765+
Flags<[FrontendOption, ArgumentIsPath]>,
1766+
HelpText<"Load LLVM pass plugin from a dynamic shared object file.">,
1767+
MetaVarName<"<path>">;
1768+
17641769
// ONLY SUPPORTED IN NEW DRIVER
17651770

17661771
// These flags only exist here so that the old driver doesn't fail with unknown

include/swift/Subsystems.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,10 @@ namespace swift {
266266
/// Given an already created LLVM module, construct a pass pipeline and run
267267
/// the Swift LLVM Pipeline upon it. This will include the emission of LLVM IR
268268
/// if requested (\out is not null).
269-
void performLLVMOptimizations(const IRGenOptions &Opts, llvm::Module *Module,
269+
void performLLVMOptimizations(const IRGenOptions &Opts,
270+
DiagnosticEngine &Diags,
271+
llvm::sys::Mutex *DiagMutex,
272+
llvm::Module *Module,
270273
llvm::TargetMachine *TargetMachine,
271274
llvm::raw_pwrite_stream *out);
272275

lib/Driver/ToolChains.cpp

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ void ToolChain::addCommonFrontendArgs(const OutputInfo &OI,
343343
inputArgs.AddLastArg(arguments, options::OPT_enable_experimental_cxx_interop);
344344
inputArgs.AddLastArg(arguments, options::OPT_cxx_interoperability_mode);
345345
inputArgs.AddLastArg(arguments, options::OPT_enable_builtin_module);
346+
inputArgs.AddLastArg(arguments, options::OPT_load_pass_plugin_EQ);
346347

347348
// Pass on any build config options
348349
inputArgs.AddAllArgs(arguments, options::OPT_D);

lib/DriverTool/swift_llvm_opt_main.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,10 @@ int swift_llvm_opt_main(ArrayRef<const char *> argv, void *MainAddr) {
214214
Opts.OutputKind = IRGenOutputKind::LLVMAssemblyAfterOptimization;
215215

216216
// Then perform the optimizations.
217-
performLLVMOptimizations(Opts, M.get(), TM.get(), &Out->os());
217+
SourceManager SM;
218+
DiagnosticEngine Diags(SM);
219+
performLLVMOptimizations(Opts, Diags, nullptr, M.get(), TM.get(),
220+
&Out->os());
218221
} else {
219222
std::string Pipeline = PassPipeline;
220223
llvm::TargetLibraryInfoImpl TLII(ModuleTriple);

lib/Frontend/CompilerInvocation.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2886,6 +2886,10 @@ static bool ParseIRGenArgs(IRGenOptions &Opts, ArgList &Args,
28862886
}
28872887
}
28882888

2889+
for (const Arg *A : Args.filtered(OPT_load_pass_plugin_EQ)) {
2890+
Opts.LLVMPassPlugins.push_back(A->getValue());
2891+
}
2892+
28892893
for (const Arg *A : Args.filtered(OPT_verify_type_layout)) {
28902894
Opts.VerifyTypeLayoutNames.push_back(A->getValue());
28912895
}

lib/IRGen/IRGen.cpp

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
#include "llvm/MC/TargetRegistry.h"
6969
#include "llvm/Object/ObjectFile.h"
7070
#include "llvm/Passes/PassBuilder.h"
71+
#include "llvm/Passes/PassPlugin.h"
7172
#include "llvm/Passes/StandardInstrumentations.h"
7273
#include "llvm/Support/CommandLine.h"
7374
#include "llvm/Support/Debug.h"
@@ -196,7 +197,21 @@ static void align(llvm::Module *Module) {
196197
}
197198
}
198199

200+
template <typename... ArgTypes>
201+
void diagnoseSync(
202+
DiagnosticEngine &Diags, llvm::sys::Mutex *DiagMutex, SourceLoc Loc,
203+
Diag<ArgTypes...> ID,
204+
typename swift::detail::PassArgument<ArgTypes>::type... Args) {
205+
std::optional<llvm::sys::ScopedLock> Lock;
206+
if (DiagMutex)
207+
Lock.emplace(*DiagMutex);
208+
209+
Diags.diagnose(Loc, ID, std::move(Args)...);
210+
}
211+
199212
void swift::performLLVMOptimizations(const IRGenOptions &Opts,
213+
DiagnosticEngine &Diags,
214+
llvm::sys::Mutex *DiagMutex,
200215
llvm::Module *Module,
201216
llvm::TargetMachine *TargetMachine,
202217
llvm::raw_pwrite_stream *out) {
@@ -238,6 +253,18 @@ void swift::performLLVMOptimizations(const IRGenOptions &Opts,
238253

239254
PassBuilder PB(TargetMachine, PTO, PGOOpt, &PIC);
240255

256+
// Attempt to load pass plugins and register their callbacks with PB.
257+
for (const auto &PluginFile : Opts.LLVMPassPlugins) {
258+
Expected<PassPlugin> PassPlugin = PassPlugin::Load(PluginFile);
259+
if (PassPlugin) {
260+
PassPlugin->registerPassBuilderCallbacks(PB);
261+
} else {
262+
diagnoseSync(Diags, DiagMutex, SourceLoc(),
263+
diag::unable_to_load_pass_plugin, PluginFile,
264+
toString(PassPlugin.takeError()));
265+
}
266+
}
267+
241268
// Register the AA manager first so that our version is the one used.
242269
FAM.registerPass([&] {
243270
auto AA = PB.buildDefaultAAPipeline();
@@ -520,20 +547,6 @@ static void countStatsPostIRGen(UnifiedStatsReporter &Stats,
520547
}
521548
}
522549

523-
template<typename ...ArgTypes>
524-
void
525-
diagnoseSync(DiagnosticEngine &Diags, llvm::sys::Mutex *DiagMutex,
526-
SourceLoc Loc, Diag<ArgTypes...> ID,
527-
typename swift::detail::PassArgument<ArgTypes>::type... Args) {
528-
if (DiagMutex)
529-
DiagMutex->lock();
530-
531-
Diags.diagnose(Loc, ID, std::move(Args)...);
532-
533-
if (DiagMutex)
534-
DiagMutex->unlock();
535-
}
536-
537550
/// Run the LLVM passes. In multi-threaded compilation this will be done for
538551
/// multiple LLVM modules in parallel.
539552
bool swift::performLLVM(const IRGenOptions &Opts,
@@ -602,7 +615,7 @@ bool swift::performLLVM(const IRGenOptions &Opts,
602615
assert(Opts.OutputKind == IRGenOutputKind::Module && "no output specified");
603616
}
604617

605-
performLLVMOptimizations(Opts, Module, TargetMachine,
618+
performLLVMOptimizations(Opts, Diags, DiagMutex, Module, TargetMachine,
606619
OutputFile ? &OutputFile->getOS() : nullptr);
607620

608621
if (Stats) {
@@ -1709,7 +1722,7 @@ GeneratedModule OptimizedIRRequest::evaluate(Evaluator &evaluator,
17091722
if (!irMod)
17101723
return irMod;
17111724

1712-
performLLVMOptimizations(desc.Opts, irMod.getModule(),
1725+
performLLVMOptimizations(desc.Opts, ctx.Diags, nullptr, irMod.getModule(),
17131726
irMod.getTargetMachine(), desc.out);
17141727
return irMod;
17151728
}

test/Frontend/Inputs/TestPlugin.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
//===---------------------- TestPlugin.cpp --------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2023 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
// Used by -load-pass-plugin
14+
15+
#include "llvm/Pass.h"
16+
#include "llvm/Passes/PassBuilder.h"
17+
#include "llvm/Passes/PassPlugin.h"
18+
19+
using namespace llvm;
20+
21+
namespace {
22+
23+
void runTestPlugin(Function &F) {
24+
errs() << "TestPlugin: ";
25+
errs().write_escaped(F.getName()) << '\n';
26+
}
27+
28+
struct TestPluginPass : PassInfoMixin<TestPluginPass> {
29+
PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
30+
runTestPlugin(F);
31+
return PreservedAnalyses::all();
32+
}
33+
};
34+
35+
} // namespace
36+
37+
PassPluginLibraryInfo getTestPluginInfo() {
38+
return {LLVM_PLUGIN_API_VERSION, "TestPlugin", LLVM_VERSION_STRING,
39+
[](PassBuilder &PB) {
40+
PB.registerVectorizerStartEPCallback(
41+
[](llvm::FunctionPassManager &PM, OptimizationLevel Level) {
42+
PM.addPass(TestPluginPass());
43+
});
44+
}};
45+
}
46+
47+
extern "C" LLVM_ATTRIBUTE_WEAK ::llvm::PassPluginLibraryInfo
48+
llvmGetPassPluginInfo() {
49+
return getTestPluginInfo();
50+
}

test/Frontend/load-pass-plugin.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// REQUIRES: OS=macosx
2+
3+
// RUN: %target-swift-frontend -load-pass-plugin=nonexistent.dylib %s -emit-ir -o /dev/null 2>&1 | %FileCheck -check-prefix=CHECK-UNABLE-LOAD %s
4+
// CHECK-UNABLE-LOAD: error: unable to load plugin 'nonexistent.dylib': 'Could not load library{{.*}}'
5+
6+
// RUN: %empty-directory(%t)
7+
// RUN: %target-clangxx %S/Inputs/TestPlugin.cpp -std=c++17 -stdlib=libc++ \
8+
// RUN: -isysroot %sdk -I %llvm_src_root/include -I %llvm_obj_root/include -L %llvm_obj_root/lib -lLLVMSupport \
9+
// RUN: -Wl,-undefined -Wl,suppress -Wl,-flat_namespace \
10+
// RUN: -dynamiclib -o %t/libTestPlugin.dylib
11+
12+
// RUN: %target-swift-frontend -load-pass-plugin=%t/libTestPlugin.dylib %s -emit-ir -o /dev/null 2>&1 | %swift-demangle | %FileCheck %s
13+
// CHECK: TestPlugin: main
14+
// CHECK: TestPlugin: null.empty() -> ()
15+
16+
func empty() {}

0 commit comments

Comments
 (0)