about summary refs log tree commit diff
path: root/instrumentation/lto-marker.so.cc
blob: fa6835bb73ff0864f8b5df2e8f79984b4a1d8c35 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#define AFL_LLVM_PASS

#include "llvm/Pass.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"

#if LLVM_VERSION_MAJOR >= 11
  #include "llvm/Passes/PassPlugin.h"
  #include "llvm/Passes/PassBuilder.h"
  #include "llvm/IR/PassManager.h"
#else
  #include "llvm/IR/LegacyPassManager.h"
#endif

#include "llvm/Transforms/IPO/PassManagerBuilder.h"

#include "debug.h"

using namespace llvm;

#include <iostream>
#include <string>
#include <unistd.h>

namespace
{
#if LLVM_VERSION_MAJOR >= 11
class LTOMarker : public PassInfoMixin<LTOMarker>
{
public:
	LTOMarker() { }
	PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
};
#else
class LTOMarker : public ModulePass
{
public:
	static char ID;
	LTOMarker() : ModulePass(ID) { }
	bool runOnModule(Module &M) override;
};
#endif // LLVM_VERSION_MAJOR >= 11
} // namespace

#if LLVM_MAJOR >= 11
extern "C" ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK
llvmGetPassPluginInfo()
{
	return {LLVM_PLUGIN_API_VERSION, "LTOMarker", "v0.1",
			/* lambda to insert our pass into the pass pipeline. */
			[](PassBuilder &PB)
			{

#if LLVM_VERSION_MAJOR <= 13
			using OptimizationLevel = typename PassBuilder::OptimizationLevel;
#endif
        PB.registerOptimizerLastEPCallback(
				[](ModulePassManager &MPM, OptimizationLevel OL)
				{
					MPM.addPass(LTOMarker());
        });
			}};
}
#else
char LTOMarker::ID = 0;
#endif

#if LLVM_VERSION_MAJOR >= 11
PreservedAnalyses LTOMarker::run(Module &M, ModuleAnalysisManager &MAM)
#else
bool LTOMarker::runOnModule(Module &M)
#endif
{
	using namespace std;
	LLVMContext &C = M.getContext();
	bool output = isatty(2) && !getenv("AFL_QUIET");
	if (output)
		OKF("Start LTO Marking");
	for (auto &F : M)
	{
		// cout << F.getName().str() << endl;
		for (auto &BB : F)
		{
			BB.getTerminator()->setMetadata(
				M.getMDKindID("keybranch"), MDNode::get(C, None));
		}
	}
	if (output)
		OKF("Finish LTO Marking");
#if LLVM_VERSION_MAJOR >= 11
	return PreservedAnalyses::all();
#else
	return true;
#endif
}

#if LLVM_VERSION_MAJOR < 11
static void registerLTOPass(
	const PassManagerBuilder &, legacy::PassManagerBase &PM)
{
	PM.add(new LTOMarker());
}

static RegisterStandardPasses RegisterLTOPass(
	PassManagerBuilder::EP_OptimizerLast, registerLTOPass);

static RegisterStandardPasses RegisterLTOPass0(
	PassManagerBuilder::EP_EnabledOnOptLevel0, registerLTOPass);
#endif