1//==-- handle_llvm.cpp - Helper function for Clang fuzzers -----------------==//
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// Implements HandleLLVM for use by the Clang fuzzers. First runs a loop
10// vectorizer optimization pass over the given IR code. Then mimics lli on both
11// versions to JIT the generated code and execute it. Currently, functions are
12// executed on dummy inputs.
13//
14//===----------------------------------------------------------------------===//
15
16#include "handle_llvm.h"
17#include "input_arrays.h"
18
19#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/CodeGen/CommandFlags.h"
22#include "llvm/CodeGen/MachineModuleInfo.h"
23#include "llvm/CodeGen/TargetPassConfig.h"
24#include "llvm/ExecutionEngine/JITEventListener.h"
25#include "llvm/ExecutionEngine/JITSymbol.h"
26#include "llvm/ExecutionEngine/MCJIT.h"
27#include "llvm/ExecutionEngine/ObjectCache.h"
28#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
29#include "llvm/ExecutionEngine/SectionMemoryManager.h"
30#include "llvm/IR/IRPrintingPasses.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/Module.h"
33#include "llvm/IR/Verifier.h"
34#include "llvm/IRPrinter/IRPrintingPasses.h"
35#include "llvm/IRReader/IRReader.h"
36#include "llvm/MC/TargetRegistry.h"
37#include "llvm/Passes/OptimizationLevel.h"
38#include "llvm/Passes/PassBuilder.h"
39#include "llvm/Support/MemoryBuffer.h"
40#include "llvm/Support/SourceMgr.h"
41#include "llvm/Support/TargetSelect.h"
42#include "llvm/Target/TargetMachine.h"
43#include "llvm/TargetParser/Triple.h"
44
45using namespace llvm;
46
47// Define a type for the functions that are compiled and executed
48typedef void (*LLVMFunc)(int*, int*, int*, int);
49
50// Helper function to parse command line args and find the optimization level
51static CodeGenOptLevel getOptLevel(const std::vector<const char *> &ExtraArgs) {
52 // Find the optimization level from the command line args
53 CodeGenOptLevel OLvl = CodeGenOptLevel::Default;
54 for (auto &A : ExtraArgs) {
55 if (A[0] == '-' && A[1] == 'O') {
56 if (auto Level = CodeGenOpt::parseLevel(C: A[2])) {
57 OLvl = *Level;
58 } else {
59 errs() << "error: opt level must be between 0 and 3.\n";
60 std::exit(status: 1);
61 }
62 }
63 }
64 return OLvl;
65}
66
67static void ErrorAndExit(std::string message) {
68 errs()<< "ERROR: " << message << "\n";
69 std::exit(status: 1);
70}
71
72// Helper function to add optimization passes to the TargetMachine at the
73// specified optimization level, OptLevel
74static void RunOptimizationPasses(raw_ostream &OS, Module &M,
75 CodeGenOptLevel OptLevel) {
76 llvm::OptimizationLevel OL;
77 switch (OptLevel) {
78 case CodeGenOptLevel::None:
79 OL = OptimizationLevel::O0;
80 break;
81 case CodeGenOptLevel::Less:
82 OL = OptimizationLevel::O1;
83 break;
84 case CodeGenOptLevel::Default:
85 OL = OptimizationLevel::O2;
86 break;
87 case CodeGenOptLevel::Aggressive:
88 OL = OptimizationLevel::O3;
89 break;
90 }
91
92 LoopAnalysisManager LAM;
93 FunctionAnalysisManager FAM;
94 CGSCCAnalysisManager CGAM;
95 ModuleAnalysisManager MAM;
96
97 PassBuilder PB(M.getContext());
98
99 PB.registerModuleAnalyses(MAM);
100 PB.registerCGSCCAnalyses(CGAM);
101 PB.registerFunctionAnalyses(FAM);
102 PB.registerLoopAnalyses(LAM);
103 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
104
105 ModulePassManager MPM = PB.buildPerModuleDefaultPipeline(Level: OL);
106 MPM.addPass(Pass: PrintModulePass(OS, /*Banner=*/"",
107 /*ShouldPreserveUseListOrder=*/false,
108 /*EmitSummaryIndex=*/false,
109 /*ShouldRenumberMetadata=*/true));
110
111 MPM.run(IR&: M, AM&: MAM);
112}
113
114// Mimics the opt tool to run an optimization pass over the provided IR
115static std::string OptLLVM(const std::string &IR, CodeGenOptLevel OLvl) {
116 // Create a module that will run the optimization passes
117 SMDiagnostic Err;
118 LLVMContext Context;
119 std::unique_ptr<Module> M = parseIR(Buffer: MemoryBufferRef(IR, "IR"), Err, Context);
120 if (!M || verifyModule(M: *M, OS: &errs()))
121 ErrorAndExit(message: "Could not parse IR");
122
123 Triple ModuleTriple(M->getTargetTriple());
124 const TargetOptions Options =
125 codegen::getTargetOptions(LibraryOptions: Context.getLibraryOptions(), TheTriple: ModuleTriple);
126 std::string E;
127 const Target *TheTarget = TargetRegistry::lookupTarget(
128 ArchName: codegen::getMArch(C: Context.getLibraryOptions()), TheTriple&: ModuleTriple, Error&: E);
129 if (!TheTarget)
130 ErrorAndExit(message: E);
131
132 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
133 TT: M->getTargetTriple(), CPU: codegen::getCPUStr(C: Context.getLibraryOptions()),
134 Features: codegen::getFeaturesStr(C: Context.getLibraryOptions()), Options,
135 RM: codegen::getExplicitRelocModel(C: Context.getLibraryOptions()),
136 CM: codegen::getExplicitCodeModel(C: Context.getLibraryOptions()), OL: OLvl));
137 if (!TM)
138 ErrorAndExit(message: "Could not create target machine");
139
140 codegen::setFunctionAttributes(
141 M&: *M, CPU: codegen::getCPUStr(C: Context.getLibraryOptions()),
142 Features: codegen::getFeaturesStr(C: Context.getLibraryOptions()));
143
144 // Add a pass that writes the optimized IR to an output stream
145 std::string outString;
146 raw_string_ostream OS(outString);
147 RunOptimizationPasses(OS, M&: *M, OptLevel: OLvl);
148
149 return outString;
150}
151
152// Takes a function and runs it on a set of inputs
153// First determines whether f is the optimized or unoptimized function
154static void RunFuncOnInputs(LLVMFunc f, int Arr[kNumArrays][kArraySize]) {
155 for (int i = 0; i < kNumArrays / 3; i++)
156 f(Arr[i], Arr[i + (kNumArrays / 3)], Arr[i + (2 * kNumArrays / 3)],
157 kArraySize);
158}
159
160// Takes a string of IR and compiles it using LLVM's JIT Engine
161static void CreateAndRunJITFunc(const std::string &IR, CodeGenOptLevel OLvl) {
162 SMDiagnostic Err;
163 LLVMContext Context;
164 std::unique_ptr<Module> M = parseIR(Buffer: MemoryBufferRef(IR, "IR"), Err, Context);
165 if (!M)
166 ErrorAndExit(message: "Could not parse IR");
167
168 Function *EntryFunc = M->getFunction(Name: "foo");
169 if (!EntryFunc)
170 ErrorAndExit(message: "Function not found in module");
171
172 std::string ErrorMsg;
173 Triple ModuleTriple(M->getTargetTriple());
174
175 EngineBuilder builder(std::move(M));
176 builder.setMArch(codegen::getMArch(C: Context.getLibraryOptions()));
177 builder.setMCPU(codegen::getCPUStr(C: Context.getLibraryOptions()));
178 builder.setMAttrs(codegen::getFeatureList(C: Context.getLibraryOptions()));
179 builder.setErrorStr(&ErrorMsg);
180 builder.setEngineKind(EngineKind::JIT);
181 builder.setMCJITMemoryManager(std::make_unique<SectionMemoryManager>());
182 builder.setOptLevel(OLvl);
183 builder.setTargetOptions(
184 codegen::getTargetOptions(LibraryOptions: Context.getLibraryOptions(), TheTriple: ModuleTriple));
185
186 std::unique_ptr<ExecutionEngine> EE(builder.create());
187 if (!EE)
188 ErrorAndExit(message: "Could not create execution engine");
189
190 EE->finalizeObject();
191 EE->runStaticConstructorsDestructors(isDtors: false);
192
193 LLVMFunc f = reinterpret_cast<LLVMFunc>(EE->getPointerToFunction(F: EntryFunc));
194
195 // Figure out if we are running the optimized func or the unoptimized func
196 RunFuncOnInputs(f, Arr: (OLvl == CodeGenOptLevel::None) ? UnoptArrays : OptArrays);
197
198 EE->runStaticConstructorsDestructors(isDtors: true);
199}
200
201// Main fuzz target called by ExampleClangLLVMProtoFuzzer.cpp
202// Mimics the lli tool to JIT the LLVM IR code and execute it
203void clang_fuzzer::HandleLLVM(const std::string &IR,
204 const std::vector<const char *> &ExtraArgs) {
205 // Populate OptArrays and UnoptArrays with the arrays from InputArrays
206 memcpy(dest: OptArrays, src: InputArrays, n: kTotalSize);
207 memcpy(dest: UnoptArrays, src: InputArrays, n: kTotalSize);
208
209 // Parse ExtraArgs to set the optimization level
210 CodeGenOptLevel OLvl = getOptLevel(ExtraArgs);
211
212 // First we optimize the IR by running a loop vectorizer pass
213 std::string OptIR = OptLLVM(IR, OLvl);
214
215 CreateAndRunJITFunc(IR: OptIR, OLvl);
216 CreateAndRunJITFunc(IR, OLvl: CodeGenOptLevel::None);
217
218 if (memcmp(s1: OptArrays, s2: UnoptArrays, n: kTotalSize))
219 ErrorAndExit(message: "!!!BUG!!!");
220}
221