xref: /netbsd-src/external/apache2/llvm/dist/llvm/tools/llvm-isel-fuzzer/llvm-isel-fuzzer.cpp (revision 82d56013d7b633d116a93943de88e08335357a7c)
17330f729Sjoerg //===--- llvm-isel-fuzzer.cpp - Fuzzer for instruction selection ----------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // Tool to fuzz instruction selection using libFuzzer.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "llvm/ADT/StringRef.h"
147330f729Sjoerg #include "llvm/Analysis/TargetLibraryInfo.h"
157330f729Sjoerg #include "llvm/Bitcode/BitcodeReader.h"
167330f729Sjoerg #include "llvm/Bitcode/BitcodeWriter.h"
17*82d56013Sjoerg #include "llvm/CodeGen/CommandFlags.h"
187330f729Sjoerg #include "llvm/FuzzMutate/FuzzerCLI.h"
197330f729Sjoerg #include "llvm/FuzzMutate/IRMutator.h"
207330f729Sjoerg #include "llvm/FuzzMutate/Operations.h"
217330f729Sjoerg #include "llvm/IR/Constants.h"
227330f729Sjoerg #include "llvm/IR/LLVMContext.h"
237330f729Sjoerg #include "llvm/IR/LegacyPassManager.h"
247330f729Sjoerg #include "llvm/IR/Module.h"
257330f729Sjoerg #include "llvm/IR/Verifier.h"
267330f729Sjoerg #include "llvm/IRReader/IRReader.h"
27*82d56013Sjoerg #include "llvm/Support/CommandLine.h"
287330f729Sjoerg #include "llvm/Support/DataTypes.h"
297330f729Sjoerg #include "llvm/Support/Debug.h"
307330f729Sjoerg #include "llvm/Support/SourceMgr.h"
317330f729Sjoerg #include "llvm/Support/TargetRegistry.h"
327330f729Sjoerg #include "llvm/Support/TargetSelect.h"
337330f729Sjoerg #include "llvm/Target/TargetMachine.h"
347330f729Sjoerg 
357330f729Sjoerg #define DEBUG_TYPE "isel-fuzzer"
367330f729Sjoerg 
377330f729Sjoerg using namespace llvm;
387330f729Sjoerg 
39*82d56013Sjoerg static codegen::RegisterCodeGenFlags CGF;
40*82d56013Sjoerg 
417330f729Sjoerg static cl::opt<char>
427330f729Sjoerg OptLevel("O",
437330f729Sjoerg          cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
447330f729Sjoerg                   "(default = '-O2')"),
457330f729Sjoerg          cl::Prefix,
467330f729Sjoerg          cl::ZeroOrMore,
477330f729Sjoerg          cl::init(' '));
487330f729Sjoerg 
497330f729Sjoerg static cl::opt<std::string>
507330f729Sjoerg TargetTriple("mtriple", cl::desc("Override target triple for module"));
517330f729Sjoerg 
527330f729Sjoerg static std::unique_ptr<TargetMachine> TM;
537330f729Sjoerg static std::unique_ptr<IRMutator> Mutator;
547330f729Sjoerg 
createISelMutator()557330f729Sjoerg std::unique_ptr<IRMutator> createISelMutator() {
567330f729Sjoerg   std::vector<TypeGetter> Types{
577330f729Sjoerg       Type::getInt1Ty,  Type::getInt8Ty,  Type::getInt16Ty, Type::getInt32Ty,
587330f729Sjoerg       Type::getInt64Ty, Type::getFloatTy, Type::getDoubleTy};
597330f729Sjoerg 
607330f729Sjoerg   std::vector<std::unique_ptr<IRMutationStrategy>> Strategies;
617330f729Sjoerg   Strategies.emplace_back(
627330f729Sjoerg       new InjectorIRStrategy(InjectorIRStrategy::getDefaultOps()));
637330f729Sjoerg   Strategies.emplace_back(new InstDeleterIRStrategy());
647330f729Sjoerg 
657330f729Sjoerg   return std::make_unique<IRMutator>(std::move(Types), std::move(Strategies));
667330f729Sjoerg }
677330f729Sjoerg 
LLVMFuzzerCustomMutator(uint8_t * Data,size_t Size,size_t MaxSize,unsigned int Seed)687330f729Sjoerg extern "C" LLVM_ATTRIBUTE_USED size_t LLVMFuzzerCustomMutator(
697330f729Sjoerg     uint8_t *Data, size_t Size, size_t MaxSize, unsigned int Seed) {
707330f729Sjoerg   LLVMContext Context;
717330f729Sjoerg   std::unique_ptr<Module> M;
727330f729Sjoerg   if (Size <= 1)
737330f729Sjoerg     // We get bogus data given an empty corpus - just create a new module.
747330f729Sjoerg     M.reset(new Module("M", Context));
757330f729Sjoerg   else
767330f729Sjoerg     M = parseModule(Data, Size, Context);
777330f729Sjoerg 
787330f729Sjoerg   Mutator->mutateModule(*M, Seed, Size, MaxSize);
797330f729Sjoerg 
807330f729Sjoerg   return writeModule(*M, Data, MaxSize);
817330f729Sjoerg }
827330f729Sjoerg 
LLVMFuzzerTestOneInput(const uint8_t * Data,size_t Size)837330f729Sjoerg extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {
847330f729Sjoerg   if (Size <= 1)
857330f729Sjoerg     // We get bogus data given an empty corpus - ignore it.
867330f729Sjoerg     return 0;
877330f729Sjoerg 
887330f729Sjoerg   LLVMContext Context;
897330f729Sjoerg   auto M = parseAndVerify(Data, Size, Context);
907330f729Sjoerg   if (!M) {
917330f729Sjoerg     errs() << "error: input module is broken!\n";
927330f729Sjoerg     return 0;
937330f729Sjoerg   }
947330f729Sjoerg 
957330f729Sjoerg   // Set up the module to build for our target.
967330f729Sjoerg   M->setTargetTriple(TM->getTargetTriple().normalize());
977330f729Sjoerg   M->setDataLayout(TM->createDataLayout());
987330f729Sjoerg 
997330f729Sjoerg   // Build up a PM to do instruction selection.
1007330f729Sjoerg   legacy::PassManager PM;
1017330f729Sjoerg   TargetLibraryInfoImpl TLII(TM->getTargetTriple());
1027330f729Sjoerg   PM.add(new TargetLibraryInfoWrapperPass(TLII));
1037330f729Sjoerg   raw_null_ostream OS;
104*82d56013Sjoerg   TM->addPassesToEmitFile(PM, OS, nullptr, CGFT_Null);
1057330f729Sjoerg   PM.run(*M);
1067330f729Sjoerg 
1077330f729Sjoerg   return 0;
1087330f729Sjoerg }
1097330f729Sjoerg 
handleLLVMFatalError(void *,const std::string & Message,bool)1107330f729Sjoerg static void handleLLVMFatalError(void *, const std::string &Message, bool) {
1117330f729Sjoerg   // TODO: Would it be better to call into the fuzzer internals directly?
1127330f729Sjoerg   dbgs() << "LLVM ERROR: " << Message << "\n"
1137330f729Sjoerg          << "Aborting to trigger fuzzer exit handling.\n";
1147330f729Sjoerg   abort();
1157330f729Sjoerg }
1167330f729Sjoerg 
LLVMFuzzerInitialize(int * argc,char *** argv)1177330f729Sjoerg extern "C" LLVM_ATTRIBUTE_USED int LLVMFuzzerInitialize(int *argc,
1187330f729Sjoerg                                                         char ***argv) {
1197330f729Sjoerg   EnableDebugBuffering = true;
1207330f729Sjoerg 
1217330f729Sjoerg   InitializeAllTargets();
1227330f729Sjoerg   InitializeAllTargetMCs();
1237330f729Sjoerg   InitializeAllAsmPrinters();
1247330f729Sjoerg   InitializeAllAsmParsers();
1257330f729Sjoerg 
1267330f729Sjoerg   handleExecNameEncodedBEOpts(*argv[0]);
1277330f729Sjoerg   parseFuzzerCLOpts(*argc, *argv);
1287330f729Sjoerg 
1297330f729Sjoerg   if (TargetTriple.empty()) {
1307330f729Sjoerg     errs() << *argv[0] << ": -mtriple must be specified\n";
1317330f729Sjoerg     exit(1);
1327330f729Sjoerg   }
1337330f729Sjoerg 
1347330f729Sjoerg   Triple TheTriple = Triple(Triple::normalize(TargetTriple));
1357330f729Sjoerg 
1367330f729Sjoerg   // Get the target specific parser.
1377330f729Sjoerg   std::string Error;
1387330f729Sjoerg   const Target *TheTarget =
139*82d56013Sjoerg       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
1407330f729Sjoerg   if (!TheTarget) {
1417330f729Sjoerg     errs() << argv[0] << ": " << Error;
1427330f729Sjoerg     return 1;
1437330f729Sjoerg   }
1447330f729Sjoerg 
1457330f729Sjoerg   // Set up the pipeline like llc does.
146*82d56013Sjoerg   std::string CPUStr = codegen::getCPUStr(),
147*82d56013Sjoerg               FeaturesStr = codegen::getFeaturesStr();
1487330f729Sjoerg 
1497330f729Sjoerg   CodeGenOpt::Level OLvl = CodeGenOpt::Default;
1507330f729Sjoerg   switch (OptLevel) {
1517330f729Sjoerg   default:
1527330f729Sjoerg     errs() << argv[0] << ": invalid optimization level.\n";
1537330f729Sjoerg     return 1;
1547330f729Sjoerg   case ' ': break;
1557330f729Sjoerg   case '0': OLvl = CodeGenOpt::None; break;
1567330f729Sjoerg   case '1': OLvl = CodeGenOpt::Less; break;
1577330f729Sjoerg   case '2': OLvl = CodeGenOpt::Default; break;
1587330f729Sjoerg   case '3': OLvl = CodeGenOpt::Aggressive; break;
1597330f729Sjoerg   }
1607330f729Sjoerg 
161*82d56013Sjoerg   TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags(TheTriple);
162*82d56013Sjoerg   TM.reset(TheTarget->createTargetMachine(
163*82d56013Sjoerg       TheTriple.getTriple(), CPUStr, FeaturesStr, Options,
164*82d56013Sjoerg       codegen::getExplicitRelocModel(), codegen::getExplicitCodeModel(), OLvl));
1657330f729Sjoerg   assert(TM && "Could not allocate target machine!");
1667330f729Sjoerg 
1677330f729Sjoerg   // Make sure we print the summary and the current unit when LLVM errors out.
1687330f729Sjoerg   install_fatal_error_handler(handleLLVMFatalError, nullptr);
1697330f729Sjoerg 
1707330f729Sjoerg   // Finally, create our mutator.
1717330f729Sjoerg   Mutator = createISelMutator();
1727330f729Sjoerg   return 0;
1737330f729Sjoerg }
174