[DebugInfo] Avoid re-ordering assignments in LCSSA
[llvm-project.git] / llvm / tools / llvm-opt-fuzzer / llvm-opt-fuzzer.cpp
blobc0688bc399f3ef6082e7ca7d5090b0e301b0956e
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/Analysis/AliasAnalysis.h"
14 #include "llvm/Bitcode/BitcodeReader.h"
15 #include "llvm/Bitcode/BitcodeWriter.h"
16 #include "llvm/CodeGen/CommandFlags.h"
17 #include "llvm/FuzzMutate/FuzzerCLI.h"
18 #include "llvm/FuzzMutate/IRMutator.h"
19 #include "llvm/IR/Verifier.h"
20 #include "llvm/InitializePasses.h"
21 #include "llvm/Passes/PassBuilder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Support/TargetRegistry.h"
25 #include "llvm/Support/TargetSelect.h"
26 #include "llvm/Target/TargetMachine.h"
28 using namespace llvm;
30 static codegen::RegisterCodeGenFlags CGF;
32 static cl::opt<std::string>
33 TargetTripleStr("mtriple", cl::desc("Override target triple for module"));
35 // Passes to run for this fuzzer instance. Expects new pass manager syntax.
36 static cl::opt<std::string> PassPipeline(
37 "passes",
38 cl::desc("A textual description of the pass pipeline for testing"));
40 static std::unique_ptr<IRMutator> Mutator;
41 static std::unique_ptr<TargetMachine> TM;
43 std::unique_ptr<IRMutator> createOptMutator() {
44 std::vector<TypeGetter> Types{
45 Type::getInt1Ty, Type::getInt8Ty, Type::getInt16Ty, Type::getInt32Ty,
46 Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
48 std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
49 Strategies.push_back(
50 std::make_unique<InjectorIRStrategy>(
51 InjectorIRStrategy::getDefaultOps()));
52 Strategies.push_back(
53 std::make_unique<InstDeleterIRStrategy>());
55 return std::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
58 extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
59 uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
61 assert(Mutator &&
62 "IR mutator should have been created during fuzzer initialization");
64 LLVMContext Context;
65 auto M = parseAndVerify(Data, Size, Context);
66 if (!M) {
67 errs() << "error: mutator input module is broken!\n";
68 return 0;
71 Mutator->mutateModule(*M, Seed, Size, MaxSize);
73 if (verifyModule(*M, &errs())) {
74 errs() << "mutation result doesn't pass verification\n";
75 #ifndef NDEBUG
76 M->dump();
77 #endif
78 // Avoid adding incorrect test cases to the corpus.
79 return 0;
82 std::string Buf;
84 raw_string_ostream OS(Buf);
85 WriteBitcodeToFile(*M, OS);
87 if (Buf.size() > MaxSize)
88 return 0;
90 // There are some invariants which are not checked by the verifier in favor
91 // of having them checked by the parser. They may be considered as bugs in the
92 // verifier and should be fixed there. However until all of those are covered
93 // we want to check for them explicitly. Otherwise we will add incorrect input
94 // to the corpus and this is going to confuse the fuzzer which will start
95 // exploration of the bitcode reader error handling code.
96 auto NewM = parseAndVerify(
97 reinterpret_cast<const uint8_t*>(Buf.data()), Buf.size(), Context);
98 if (!NewM) {
99 errs() << "mutator failed to re-read the module\n";
100 #ifndef NDEBUG
101 M->dump();
102 #endif
103 return 0;
106 memcpy(Data, Buf.data(), Buf.size());
107 return Buf.size();
110 extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
111 assert(TM && "Should have been created during fuzzer initialization");
113 if (Size <= 1)
114 // We get bogus data given an empty corpus - ignore it.
115 return 0;
117 // Parse module
120 LLVMContext Context;
121 auto M = parseAndVerify(Data, Size, Context);
122 if (!M) {
123 errs() << "error: input module is broken!\n";
124 return 0;
127 // Set up target dependant options
130 M->setTargetTriple(TM->getTargetTriple().normalize());
131 M->setDataLayout(TM->createDataLayout());
132 codegen::setFunctionAttributes(TM->getTargetCPU(),
133 TM->getTargetFeatureString(), *M);
135 // Create pass pipeline
138 PassBuilder PB(false, TM.get());
140 LoopAnalysisManager LAM;
141 FunctionAnalysisManager FAM;
142 CGSCCAnalysisManager CGAM;
143 ModulePassManager MPM;
144 ModuleAnalysisManager MAM;
146 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
147 PB.registerModuleAnalyses(MAM);
148 PB.registerCGSCCAnalyses(CGAM);
149 PB.registerFunctionAnalyses(FAM);
150 PB.registerLoopAnalyses(LAM);
151 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
153 auto Err = PB.parsePassPipeline(MPM, PassPipeline);
154 assert(!Err && "Should have been checked during fuzzer initialization");
155 // Only fail with assert above, otherwise ignore the parsing error.
156 consumeError(std::move(Err));
158 // Run passes which we need to test
161 MPM.run(*M, MAM);
163 // Check that passes resulted in a correct code
164 if (verifyModule(*M, &errs())) {
165 errs() << "Transformation resulted in an invalid module\n";
166 abort();
169 return 0;
172 static void handleLLVMFatalError(void *, const std::string &Message, bool) {
173 // TODO: Would it be better to call into the fuzzer internals directly?
174 dbgs() << "LLVM ERROR: " << Message << "\n"
175 << "Aborting to trigger fuzzer exit handling.\n";
176 abort();
179 extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(
180 int *argc, char ***argv) {
181 EnableDebugBuffering = true;
183 // Make sure we print the summary and the current unit when LLVM errors out.
184 install_fatal_error_handler(handleLLVMFatalError, nullptr);
186 // Initialize llvm
189 InitializeAllTargets();
190 InitializeAllTargetMCs();
192 PassRegistry &Registry = *PassRegistry::getPassRegistry();
193 initializeCore(Registry);
194 initializeCoroutines(Registry);
195 initializeScalarOpts(Registry);
196 initializeObjCARCOpts(Registry);
197 initializeVectorization(Registry);
198 initializeIPO(Registry);
199 initializeAnalysis(Registry);
200 initializeTransformUtils(Registry);
201 initializeInstCombine(Registry);
202 initializeAggressiveInstCombine(Registry);
203 initializeInstrumentation(Registry);
204 initializeTarget(Registry);
206 // Parse input options
209 handleExecNameEncodedOptimizerOpts(*argv[0]);
210 parseFuzzerCLOpts(*argc, *argv);
212 // Create TargetMachine
215 if (TargetTripleStr.empty()) {
216 errs() << *argv[0] << ": -mtriple must be specified\n";
217 exit(1);
219 Triple TargetTriple = Triple(Triple::normalize(TargetTripleStr));
221 std::string Error;
222 const Target *TheTarget =
223 TargetRegistry::lookupTarget(codegen::getMArch(), TargetTriple, Error);
224 if (!TheTarget) {
225 errs() << *argv[0] << ": " << Error;
226 exit(1);
229 TargetOptions Options =
230 codegen::InitTargetOptionsFromCodeGenFlags(TargetTriple);
231 TM.reset(TheTarget->createTargetMachine(
232 TargetTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
233 Options, codegen::getExplicitRelocModel(),
234 codegen::getExplicitCodeModel(), CodeGenOpt::Default));
235 assert(TM && "Could not allocate target machine!");
237 // Check that pass pipeline is specified and correct
240 if (PassPipeline.empty()) {
241 errs() << *argv[0] << ": at least one pass should be specified\n";
242 exit(1);
245 PassBuilder PB(false, TM.get());
246 ModulePassManager MPM;
247 if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) {
248 errs() << *argv[0] << ": " << toString(std::move(Err)) << "\n";
249 exit(1);
252 // Create mutator
255 Mutator = createOptMutator();
257 return 0;