xref: /openbsd-src/gnu/llvm/clang/tools/clang-fuzzer/handle-llvm/handle_llvm.cpp (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
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/ADT/Triple.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/CodeGen/CommandFlags.inc"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/TargetPassConfig.h"
25 #include "llvm/ExecutionEngine/JITEventListener.h"
26 #include "llvm/ExecutionEngine/JITSymbol.h"
27 #include "llvm/ExecutionEngine/MCJIT.h"
28 #include "llvm/ExecutionEngine/ObjectCache.h"
29 #include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
30 #include "llvm/ExecutionEngine/SectionMemoryManager.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/LegacyPassNameParser.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/Pass.h"
39 #include "llvm/PassRegistry.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
46 #include "llvm/Transforms/IPO.h"
47 #include "llvm/Transforms/Vectorize.h"
48 
49 using namespace llvm;
50 
51 // Define a type for the functions that are compiled and executed
52 typedef void (*LLVMFunc)(int*, int*, int*, int);
53 
54 // Helper function to parse command line args and find the optimization level
55 static void getOptLevel(const std::vector<const char *> &ExtraArgs,
56                               CodeGenOpt::Level &OLvl) {
57   // Find the optimization level from the command line args
58   OLvl = CodeGenOpt::Default;
59   for (auto &A : ExtraArgs) {
60     if (A[0] == '-' && A[1] == 'O') {
61       switch(A[2]) {
62         case '0': OLvl = CodeGenOpt::None; break;
63         case '1': OLvl = CodeGenOpt::Less; break;
64         case '2': OLvl = CodeGenOpt::Default; break;
65         case '3': OLvl = CodeGenOpt::Aggressive; break;
66         default:
67           errs() << "error: opt level must be between 0 and 3.\n";
68           std::exit(1);
69       }
70     }
71   }
72 }
73 
74 static void ErrorAndExit(std::string message) {
75   errs()<< "ERROR: " << message << "\n";
76   std::exit(1);
77 }
78 
79 // Helper function to add optimization passes to the TargetMachine at the
80 // specified optimization level, OptLevel
81 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
82                                   CodeGenOpt::Level OptLevel,
83                                   unsigned SizeLevel) {
84   // Create and initialize a PassManagerBuilder
85   PassManagerBuilder Builder;
86   Builder.OptLevel = OptLevel;
87   Builder.SizeLevel = SizeLevel;
88   Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
89   Builder.LoopVectorize = true;
90   Builder.populateModulePassManager(MPM);
91 }
92 
93 // Mimics the opt tool to run an optimization pass over the provided IR
94 static std::string OptLLVM(const std::string &IR, CodeGenOpt::Level OLvl) {
95   // Create a module that will run the optimization passes
96   SMDiagnostic Err;
97   LLVMContext Context;
98   std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
99   if (!M || verifyModule(*M, &errs()))
100     ErrorAndExit("Could not parse IR");
101 
102   Triple ModuleTriple(M->getTargetTriple());
103   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
104   std::string E;
105   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, ModuleTriple, E);
106   TargetMachine *Machine =
107       TheTarget->createTargetMachine(M->getTargetTriple(), getCPUStr(),
108                                      getFeaturesStr(), Options, getRelocModel(),
109                                      getCodeModel(), OLvl);
110   std::unique_ptr<TargetMachine> TM(Machine);
111   setFunctionAttributes(getCPUStr(), getFeaturesStr(), *M);
112 
113   legacy::PassManager Passes;
114 
115   Passes.add(new TargetLibraryInfoWrapperPass(ModuleTriple));
116   Passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
117 
118   LLVMTargetMachine &LTM = static_cast<LLVMTargetMachine &>(*TM);
119   Passes.add(LTM.createPassConfig(Passes));
120 
121   Passes.add(createVerifierPass());
122 
123   AddOptimizationPasses(Passes, OLvl, 0);
124 
125   // Add a pass that writes the optimized IR to an output stream
126   std::string outString;
127   raw_string_ostream OS(outString);
128   Passes.add(createPrintModulePass(OS, "", false));
129 
130   Passes.run(*M);
131 
132   return OS.str();
133 }
134 
135 // Takes a function and runs it on a set of inputs
136 // First determines whether f is the optimized or unoptimized function
137 static void RunFuncOnInputs(LLVMFunc f, int Arr[kNumArrays][kArraySize]) {
138   for (int i = 0; i < kNumArrays / 3; i++)
139     f(Arr[i], Arr[i + (kNumArrays / 3)], Arr[i + (2 * kNumArrays / 3)],
140       kArraySize);
141 }
142 
143 // Takes a string of IR and compiles it using LLVM's JIT Engine
144 static void CreateAndRunJITFunc(const std::string &IR, CodeGenOpt::Level OLvl) {
145   SMDiagnostic Err;
146   LLVMContext Context;
147   std::unique_ptr<Module> M = parseIR(MemoryBufferRef(IR, "IR"), Err, Context);
148   if (!M)
149     ErrorAndExit("Could not parse IR");
150 
151   Function *EntryFunc = M->getFunction("foo");
152   if (!EntryFunc)
153     ErrorAndExit("Function not found in module");
154 
155   std::string ErrorMsg;
156   EngineBuilder builder(std::move(M));
157   builder.setMArch(MArch);
158   builder.setMCPU(getCPUStr());
159   builder.setMAttrs(getFeatureList());
160   builder.setErrorStr(&ErrorMsg);
161   builder.setEngineKind(EngineKind::JIT);
162   builder.setMCJITMemoryManager(std::make_unique<SectionMemoryManager>());
163   builder.setOptLevel(OLvl);
164   builder.setTargetOptions(InitTargetOptionsFromCodeGenFlags());
165 
166   std::unique_ptr<ExecutionEngine> EE(builder.create());
167   if (!EE)
168     ErrorAndExit("Could not create execution engine");
169 
170   EE->finalizeObject();
171   EE->runStaticConstructorsDestructors(false);
172 
173 #if defined(__GNUC__) && !defined(__clang) &&                                  \
174     ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
175 // Silence
176 //
177 //   warning: ISO C++ forbids casting between pointer-to-function and
178 //   pointer-to-object [-Wpedantic]
179 //
180 // Since C++11 this casting is conditionally supported and GCC versions
181 // starting from 4.9.0 don't warn about the cast.
182 #pragma GCC diagnostic push
183 #pragma GCC diagnostic ignored "-Wpedantic"
184 #endif
185   LLVMFunc f = reinterpret_cast<LLVMFunc>(EE->getPointerToFunction(EntryFunc));
186 #if defined(__GNUC__) && !defined(__clang) &&                                  \
187     ((__GNUC__ == 4) && (__GNUC_MINOR__ < 9))
188 #pragma GCC diagnostic pop
189 #endif
190 
191   // Figure out if we are running the optimized func or the unoptimized func
192   RunFuncOnInputs(f, (OLvl == CodeGenOpt::None) ? UnoptArrays : OptArrays);
193 
194   EE->runStaticConstructorsDestructors(true);
195 }
196 
197 // Main fuzz target called by ExampleClangLLVMProtoFuzzer.cpp
198 // Mimics the lli tool to JIT the LLVM IR code and execute it
199 void clang_fuzzer::HandleLLVM(const std::string &IR,
200                               const std::vector<const char *> &ExtraArgs) {
201   // Populate OptArrays and UnoptArrays with the arrays from InputArrays
202   memcpy(OptArrays, InputArrays, kTotalSize);
203   memcpy(UnoptArrays, InputArrays, kTotalSize);
204 
205   // Parse ExtraArgs to set the optimization level
206   CodeGenOpt::Level OLvl;
207   getOptLevel(ExtraArgs, OLvl);
208 
209   // First we optimize the IR by running a loop vectorizer pass
210   std::string OptIR = OptLLVM(IR, OLvl);
211 
212   CreateAndRunJITFunc(OptIR, OLvl);
213   CreateAndRunJITFunc(IR, CodeGenOpt::None);
214 
215   if (memcmp(OptArrays, UnoptArrays, kTotalSize))
216     ErrorAndExit("!!!BUG!!!");
217 
218   return;
219 }
220