1 //===- unittests/Passes/Plugins/PluginsTest.cpp ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Analysis/CGSCCPassManager.h"
10 #include "llvm/Config/config.h"
11 #include "llvm/IR/PassManager.h"
12 #include "llvm/Passes/PassBuilder.h"
13 #include "llvm/Passes/PassPlugin.h"
14 #include "llvm/Support/FileSystem.h"
15 #include "llvm/Support/ManagedStatic.h"
16 #include "llvm/Support/Path.h"
17 #include "llvm/Testing/Support/Error.h"
18 #include "llvm/Transforms/Scalar/LoopPassManager.h"
19 #include "gtest/gtest.h"
20 
21 #include "TestPlugin.h"
22 
23 #include <cstdint>
24 
25 using namespace llvm;
26 
27 void anchor() {}
28 
29 static std::string LibPath(const std::string Name = "TestPlugin") {
30   const std::vector<testing::internal::string> &Argvs =
31       testing::internal::GetArgvs();
32   const char *Argv0 = Argvs.size() > 0 ? Argvs[0].c_str() : "PluginsTests";
33   void *Ptr = (void *)(intptr_t)anchor;
34   std::string Path = sys::fs::getMainExecutable(Argv0, Ptr);
35   llvm::SmallString<256> Buf{sys::path::parent_path(Path)};
36   sys::path::append(Buf, (Name + LLVM_PLUGIN_EXT).c_str());
37   return std::string(Buf.str());
38 }
39 
40 TEST(PluginsTests, LoadPlugin) {
41 #if !defined(LLVM_ENABLE_PLUGINS)
42   // Disable the test if plugins are disabled.
43   return;
44 #endif
45 
46   auto PluginPath = LibPath();
47   ASSERT_NE("", PluginPath);
48 
49   Expected<PassPlugin> Plugin = PassPlugin::Load(PluginPath);
50   ASSERT_TRUE(!!Plugin) << "Plugin path: " << PluginPath;
51 
52   ASSERT_EQ(TEST_PLUGIN_NAME, Plugin->getPluginName());
53   ASSERT_EQ(TEST_PLUGIN_VERSION, Plugin->getPluginVersion());
54 
55   PassBuilder PB;
56   ModulePassManager PM;
57   ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, "plugin-pass"), Failed());
58 
59   Plugin->registerPassBuilderCallbacks(PB);
60   ASSERT_THAT_ERROR(PB.parsePassPipeline(PM, "plugin-pass"), Succeeded());
61 }
62