[ARM] Cortex-M4 schedule additions
[llvm-complete.git] / tools / llvm-opt-fuzzer / llvm-opt-fuzzer.cpp
blob02c113d117bd1aa482f7a6701020a98b8b82be4a
1 //===--- llvm-opt-fuzzer.cpp - Fuzzer for instruction selection ----------===//
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 // Tool to fuzz optimization passes using libFuzzer.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Bitcode/BitcodeReader.h"
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "llvm/CodeGen/CommandFlags.inc"
16 #include "llvm/FuzzMutate/FuzzerCLI.h"
17 #include "llvm/FuzzMutate/IRMutator.h"
18 #include "llvm/IR/Verifier.h"
19 #include "llvm/Passes/PassBuilder.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Support/TargetRegistry.h"
22 #include "llvm/Support/TargetSelect.h"
24 using namespace llvm;
26 static cl::opt<std::string>
27 TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
29 // Passes to run for this fuzzer instance. Expects new pass manager syntax.
30 static cl::opt<std::string> PassPipeline(
31 "passes",
32 cl::desc("A textual description of the pass pipeline for testing"));
34 static std::unique_ptr<IRMutator> Mutator;
35 static std::unique_ptr<TargetMachine> TM;
37 std::unique_ptr<IRMutator> createOptMutator() {
38 std::vector<TypeGetter> Types{
39 Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
40 Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
42 std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
43 Strategies.push_back(
44 std::make_unique<InjectorIRStrategy>(
45 InjectorIRStrategy::getDefaultOps()));
46 Strategies.push_back(
47 std::make_unique<InstDeleterIRStrategy>());
49 return std::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
52 extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
53 uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
55 assert(Mutator &&
56 "IR mutator should have been created during fuzzer initialization");
58 LLVMContext Context;
59 auto M = parseAndVerify(Data, Size, Context);
60 if (!M) {
61 errs() << "error: mutator input module is broken!\n";
62 return 0;
65 Mutator->mutateModule(*M, Seed, Size, MaxSize);
67 if (verifyModule(*M, &errs())) {
68 errs() << "mutation result doesn't pass verification\n";
69 #ifndef NDEBUG
70 M->dump();
71 #endif
72 // Avoid adding incorrect test cases to the corpus.
73 return 0;
76 std::string Buf;
78 raw_string_ostream OS(Buf);
79 WriteBitcodeToFile(*M, OS);
81 if (Buf.size() > MaxSize)
82 return 0;
84 // There are some invariants which are not checked by the verifier in favor
85 // of having them checked by the parser. They may be considered as bugs in the
86 // verifier and should be fixed there. However until all of those are covered
87 // we want to check for them explicitly. Otherwise we will add incorrect input
88 // to the corpus and this is going to confuse the fuzzer which will start
89 // exploration of the bitcode reader error handling code.
90 auto NewM = parseAndVerify(
91 reinterpret_cast<const uint8_t*>(Buf.data()), Buf.size(), Context);
92 if (!NewM) {
93 errs() << "mutator failed to re-read the module\n";
94 #ifndef NDEBUG
95 M->dump();
96 #endif
97 return 0;
100 memcpy(Data, Buf.data(), Buf.size());
101 return Buf.size();
104 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
105 assert(TM && "Should have been created during fuzzer initialization");
107 if (Size <= 1)
108 // We get bogus data given an empty corpus - ignore it.
109 return 0;
111 // Parse module
114 LLVMContext Context;
115 auto M = parseAndVerify(Data, Size, Context);
116 if (!M) {
117 errs() << "error: input module is broken!\n";
118 return 0;
121 // Set up target dependant options
124 M->setTargetTriple(TM->getTargetTriple().normalize());
125 M->setDataLayout(TM->createDataLayout());
126 setFunctionAttributes(TM->getTargetCPU(), TM->getTargetFeatureString(), *M);
128 // Create pass pipeline
131 PassBuilder PB(TM.get());
133 LoopAnalysisManager LAM;
134 FunctionAnalysisManager FAM;
135 CGSCCAnalysisManager CGAM;
136 ModulePassManager MPM;
137 ModuleAnalysisManager MAM;
139 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
140 PB.registerModuleAnalyses(MAM);
141 PB.registerCGSCCAnalyses(CGAM);
142 PB.registerFunctionAnalyses(FAM);
143 PB.registerLoopAnalyses(LAM);
144 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
146 auto Err = PB.parsePassPipeline(MPM, PassPipeline, false, false);
147 assert(!Err && "Should have been checked during fuzzer initialization");
148 // Only fail with assert above, otherwise ignore the parsing error.
149 consumeError(std::move(Err));
151 // Run passes which we need to test
154 MPM.run(*M, MAM);
156 // Check that passes resulted in a correct code
157 if (verifyModule(*M, &errs())) {
158 errs() << "Transformation resulted in an invalid module\n";
159 abort();
162 return 0;
165 static void handleLLVMFatalError(void *, const std::string &Message, bool) {
166 // TODO: Would it be better to call into the fuzzer internals directly?
167 dbgs() << "LLVM ERROR: " << Message << "\n"
168 << "Aborting to trigger fuzzer exit handling.\n";
169 abort();
172 extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(
173 int *argc, char ***argv) {
174 EnableDebugBuffering = true;
176 // Make sure we print the summary and the current unit when LLVM errors out.
177 install_fatal_error_handler(handleLLVMFatalError, nullptr);
179 // Initialize llvm
182 InitializeAllTargets();
183 InitializeAllTargetMCs();
185 PassRegistry &Registry = *PassRegistry::getPassRegistry();
186 initializeCore(Registry);
187 initializeCoroutines(Registry);
188 initializeScalarOpts(Registry);
189 initializeObjCARCOpts(Registry);
190 initializeVectorization(Registry);
191 initializeIPO(Registry);
192 initializeAnalysis(Registry);
193 initializeTransformUtils(Registry);
194 initializeInstCombine(Registry);
195 initializeAggressiveInstCombine(Registry);
196 initializeInstrumentation(Registry);
197 initializeTarget(Registry);
199 // Parse input options
202 handleExecNameEncodedOptimizerOpts(*argv[0]);
203 parseFuzzerCLOpts(*argc, *argv);
205 // Create TargetMachine
208 if (TargetTripleStr.empty()) {
209 errs() << *argv[0] << ": -mtriple must be specified\n";
210 exit(1);
212 Triple TargetTriple = Triple(Triple::normalize(TargetTripleStr));
214 std::string Error;
215 const Target *TheTarget =
216 TargetRegistry::lookupTarget(MArch, TargetTriple, Error);
217 if (!TheTarget) {
218 errs() << *argv[0] << ": " << Error;
219 exit(1);
222 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
223 TM.reset(TheTarget->createTargetMachine(
224 TargetTriple.getTriple(), getCPUStr(), getFeaturesStr(),
225 Options, getRelocModel(), getCodeModel(), CodeGenOpt::Default));
226 assert(TM && "Could not allocate target machine!");
228 // Check that pass pipeline is specified and correct
231 if (PassPipeline.empty()) {
232 errs() << *argv[0] << ": at least one pass should be specified\n";
233 exit(1);
236 PassBuilder PB(TM.get());
237 ModulePassManager MPM;
238 if (auto Err = PB.parsePassPipeline(MPM, PassPipeline, false, false)) {
239 errs() << *argv[0] << ": " << toString(std::move(Err)) << "\n";
240 exit(1);
243 // Create mutator
246 Mutator = createOptMutator();
248 return 0;