diff options
Diffstat (limited to 'llvm')
29 files changed, 0 insertions, 2176 deletions
diff --git a/llvm/tools/llvm-ifs/CMakeLists.txt b/llvm/tools/llvm-ifs/CMakeLists.txt deleted file mode 100644 index 544b0e41a5ed..000000000000 --- a/llvm/tools/llvm-ifs/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -set(LLVM_LINK_COMPONENTS - Object - Support - TextAPI - ObjectYAML - ) - -add_llvm_tool(llvm-ifs - llvm-ifs.cpp - ) diff --git a/llvm/tools/llvm-ifs/LLVMBuild.txt b/llvm/tools/llvm-ifs/LLVMBuild.txt deleted file mode 100644 index 10dc6bd8f550..000000000000 --- a/llvm/tools/llvm-ifs/LLVMBuild.txt +++ /dev/null @@ -1,21 +0,0 @@ -;===- ./tools/llvm-ifs/LLVMBuild.txt ---------------------------*- Conf -*--===; -; -; Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -; See https://llvm.org/LICENSE.txt for license information. -; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -; -;===------------------------------------------------------------------------===; -; -; This is an LLVMBuild description file for the components in this subdirectory. -; -; For more information on the LLVMBuild system, please see: -; -; http://llvm.org/docs/LLVMBuild.html -; -;===------------------------------------------------------------------------===; - -[component_0] -type = Tool -name = llvm-ifs -parent = Tools -required_libraries = Object Support TextAPI diff --git a/llvm/tools/llvm-ifs/llvm-ifs.cpp b/llvm/tools/llvm-ifs/llvm-ifs.cpp deleted file mode 100644 index f329b4633632..000000000000 --- a/llvm/tools/llvm-ifs/llvm-ifs.cpp +++ /dev/null @@ -1,532 +0,0 @@ -//===- llvm-ifs.cpp -------------------------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===-----------------------------------------------------------------------===/ - -#include "llvm/ADT/StringRef.h" -#include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Triple.h" -#include "llvm/ObjectYAML/yaml2obj.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/Debug.h" -#include "llvm/Support/Errc.h" -#include "llvm/Support/Error.h" -#include "llvm/Support/FileOutputBuffer.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/Path.h" -#include "llvm/Support/VersionTuple.h" -#include "llvm/Support/WithColor.h" -#include "llvm/Support/YAMLTraits.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/TextAPI/MachO/InterfaceFile.h" -#include "llvm/TextAPI/MachO/TextAPIReader.h" -#include "llvm/TextAPI/MachO/TextAPIWriter.h" -#include <set> -#include <string> - -using namespace llvm; -using namespace llvm::yaml; -using namespace llvm::MachO; - -#define DEBUG_TYPE "llvm-ifs" - -namespace { -const VersionTuple IFSVersionCurrent(1, 2); -} - -static cl::opt<std::string> Action("action", cl::desc("<llvm-ifs action>"), - cl::value_desc("write-ifs | write-bin"), - cl::init("write-ifs")); - -static cl::opt<std::string> ForceFormat("force-format", - cl::desc("<force object format>"), - cl::value_desc("ELF | TBD"), - cl::init("")); - -static cl::list<std::string> InputFilenames(cl::Positional, - cl::desc("<input ifs files>"), - cl::ZeroOrMore); - -static cl::opt<std::string> OutputFilename("o", cl::desc("<output file>"), - cl::value_desc("path")); - -enum class IFSSymbolType { - NoType = 0, - Object, - Func, - // Type information is 4 bits, so 16 is safely out of range. - Unknown = 16, -}; - -std::string getTypeName(IFSSymbolType Type) { - switch (Type) { - case IFSSymbolType::NoType: - return "NoType"; - case IFSSymbolType::Func: - return "Func"; - case IFSSymbolType::Object: - return "Object"; - case IFSSymbolType::Unknown: - return "Unknown"; - } - llvm_unreachable("Unexpected ifs symbol type."); -} - -struct IFSSymbol { - IFSSymbol(std::string SymbolName) : Name(SymbolName) {} - std::string Name; - uint64_t Size; - IFSSymbolType Type; - bool Weak; - Optional<std::string> Warning; - bool operator<(const IFSSymbol &RHS) const { return Name < RHS.Name; } -}; - -namespace llvm { -namespace yaml { -/// YAML traits for IFSSymbolType. -template <> struct ScalarEnumerationTraits<IFSSymbolType> { - static void enumeration(IO &IO, IFSSymbolType &SymbolType) { - IO.enumCase(SymbolType, "NoType", IFSSymbolType::NoType); - IO.enumCase(SymbolType, "Func", IFSSymbolType::Func); - IO.enumCase(SymbolType, "Object", IFSSymbolType::Object); - IO.enumCase(SymbolType, "Unknown", IFSSymbolType::Unknown); - // Treat other symbol types as noise, and map to Unknown. - if (!IO.outputting() && IO.matchEnumFallback()) - SymbolType = IFSSymbolType::Unknown; - } -}; - -template <> struct ScalarTraits<VersionTuple> { - static void output(const VersionTuple &Value, void *, - llvm::raw_ostream &Out) { - Out << Value.getAsString(); - } - - static StringRef input(StringRef Scalar, void *, VersionTuple &Value) { - if (Value.tryParse(Scalar)) - return StringRef("Can't parse version: invalid version format."); - - if (Value > IFSVersionCurrent) - return StringRef("Unsupported IFS version."); - - // Returning empty StringRef indicates successful parse. - return StringRef(); - } - - // Don't place quotation marks around version value. - static QuotingType mustQuote(StringRef) { return QuotingType::None; } -}; - -/// YAML traits for IFSSymbol. -template <> struct MappingTraits<IFSSymbol> { - static void mapping(IO &IO, IFSSymbol &Symbol) { - IO.mapRequired("Type", Symbol.Type); - // The need for symbol size depends on the symbol type. - if (Symbol.Type == IFSSymbolType::NoType) - IO.mapOptional("Size", Symbol.Size, (uint64_t)0); - else if (Symbol.Type == IFSSymbolType::Func) - Symbol.Size = 0; - else - IO.mapRequired("Size", Symbol.Size); - IO.mapOptional("Weak", Symbol.Weak, false); - IO.mapOptional("Warning", Symbol.Warning); - } - - // Compacts symbol information into a single line. - static const bool flow = true; -}; - -/// YAML traits for set of IFSSymbols. -template <> struct CustomMappingTraits<std::set<IFSSymbol>> { - static void inputOne(IO &IO, StringRef Key, std::set<IFSSymbol> &Set) { - std::string Name = Key.str(); - IFSSymbol Sym(Name); - IO.mapRequired(Name.c_str(), Sym); - Set.insert(Sym); - } - - static void output(IO &IO, std::set<IFSSymbol> &Set) { - for (auto &Sym : Set) - IO.mapRequired(Sym.Name.c_str(), const_cast<IFSSymbol &>(Sym)); - } -}; -} // namespace yaml -} // namespace llvm - -// A cumulative representation of ELF stubs. -// Both textual and binary stubs will read into and write from this object. -class IFSStub { - // TODO: Add support for symbol versioning. -public: - VersionTuple IfsVersion; - std::string Triple; - std::string ObjectFileFormat; - Optional<std::string> SOName; - std::vector<std::string> NeededLibs; - std::set<IFSSymbol> Symbols; - - IFSStub() = default; - IFSStub(const IFSStub &Stub) - : IfsVersion(Stub.IfsVersion), Triple(Stub.Triple), - ObjectFileFormat(Stub.ObjectFileFormat), SOName(Stub.SOName), - NeededLibs(Stub.NeededLibs), Symbols(Stub.Symbols) {} - IFSStub(IFSStub &&Stub) - : IfsVersion(std::move(Stub.IfsVersion)), Triple(std::move(Stub.Triple)), - ObjectFileFormat(std::move(Stub.ObjectFileFormat)), - SOName(std::move(Stub.SOName)), NeededLibs(std::move(Stub.NeededLibs)), - Symbols(std::move(Stub.Symbols)) {} -}; - -namespace llvm { -namespace yaml { -/// YAML traits for IFSStub objects. -template <> struct MappingTraits<IFSStub> { - static void mapping(IO &IO, IFSStub &Stub) { - if (!IO.mapTag("!experimental-ifs-v1", true)) - IO.setError("Not a .ifs YAML file."); - IO.mapRequired("IfsVersion", Stub.IfsVersion); - IO.mapOptional("Triple", Stub.Triple); - IO.mapOptional("ObjectFileFormat", Stub.ObjectFileFormat); - IO.mapOptional("SOName", Stub.SOName); - IO.mapOptional("NeededLibs", Stub.NeededLibs); - IO.mapRequired("Symbols", Stub.Symbols); - } -}; -} // namespace yaml -} // namespace llvm - -static Expected<std::unique_ptr<IFSStub>> readInputFile(StringRef FilePath) { - // Read in file. - ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError = - MemoryBuffer::getFileOrSTDIN(FilePath); - if (!BufOrError) - return createStringError(BufOrError.getError(), "Could not open `%s`", - FilePath.data()); - - std::unique_ptr<MemoryBuffer> FileReadBuffer = std::move(*BufOrError); - yaml::Input YamlIn(FileReadBuffer->getBuffer()); - std::unique_ptr<IFSStub> Stub(new IFSStub()); - YamlIn >> *Stub; - - if (std::error_code Err = YamlIn.error()) - return createStringError(Err, "Failed reading Interface Stub File."); - - return std::move(Stub); -} - -int writeTbdStub(const llvm::Triple &T, const std::set<IFSSymbol> &Symbols, - const StringRef Format, raw_ostream &Out) { - - auto PlatformKindOrError = - [](const llvm::Triple &T) -> llvm::Expected<llvm::MachO::PlatformKind> { - if (T.isMacOSX()) - return llvm::MachO::PlatformKind::macOS; - if (T.isTvOS()) - return llvm::MachO::PlatformKind::tvOS; - if (T.isWatchOS()) - return llvm::MachO::PlatformKind::watchOS; - // Note: put isiOS last because tvOS and watchOS are also iOS according - // to the Triple. - if (T.isiOS()) - return llvm::MachO::PlatformKind::iOS; - - // TODO: Add an option for ForceTriple, but keep ForceFormat for now. - if (ForceFormat == "TBD") - return llvm::MachO::PlatformKind::macOS; - - return createStringError(errc::not_supported, "Invalid Platform.\n"); - }(T); - - if (!PlatformKindOrError) - return -1; - - PlatformKind Plat = PlatformKindOrError.get(); - TargetList Targets({Target(llvm::MachO::mapToArchitecture(T), Plat)}); - - InterfaceFile File; - File.setFileType(FileType::TBD_V3); // Only supporting v3 for now. - File.addTargets(Targets); - - for (const auto &Symbol : Symbols) { - auto Name = Symbol.Name; - auto Kind = SymbolKind::GlobalSymbol; - switch (Symbol.Type) { - default: - case IFSSymbolType::NoType: - Kind = SymbolKind::GlobalSymbol; - break; - case IFSSymbolType::Object: - Kind = SymbolKind::GlobalSymbol; - break; - case IFSSymbolType::Func: - Kind = SymbolKind::GlobalSymbol; - break; - } - if (Symbol.Weak) - File.addSymbol(Kind, Name, Targets, SymbolFlags::WeakDefined); - else - File.addSymbol(Kind, Name, Targets); - } - - SmallString<4096> Buffer; - raw_svector_ostream OS(Buffer); - if (Error Result = TextAPIWriter::writeToStream(OS, File)) - return -1; - Out << OS.str(); - return 0; -} - -int writeElfStub(const llvm::Triple &T, const std::set<IFSSymbol> &Symbols, - const StringRef Format, raw_ostream &Out) { - SmallString<0> Storage; - Storage.clear(); - raw_svector_ostream OS(Storage); - - OS << "--- !ELF\n"; - OS << "FileHeader:\n"; - OS << " Class: ELFCLASS"; - OS << (T.isArch64Bit() ? "64" : "32"); - OS << "\n"; - OS << " Data: ELFDATA2"; - OS << (T.isLittleEndian() ? "LSB" : "MSB"); - OS << "\n"; - OS << " Type: ET_DYN\n"; - OS << " Machine: " - << llvm::StringSwitch<llvm::StringRef>(T.getArchName()) - .Case("x86_64", "EM_X86_64") - .Case("i386", "EM_386") - .Case("i686", "EM_386") - .Case("aarch64", "EM_AARCH64") - .Case("amdgcn", "EM_AMDGPU") - .Case("r600", "EM_AMDGPU") - .Case("arm", "EM_ARM") - .Case("thumb", "EM_ARM") - .Case("avr", "EM_AVR") - .Case("mips", "EM_MIPS") - .Case("mipsel", "EM_MIPS") - .Case("mips64", "EM_MIPS") - .Case("mips64el", "EM_MIPS") - .Case("msp430", "EM_MSP430") - .Case("ppc", "EM_PPC") - .Case("ppc64", "EM_PPC64") - .Case("ppc64le", "EM_PPC64") - .Case("x86", T.isOSIAMCU() ? "EM_IAMCU" : "EM_386") - .Case("x86_64", "EM_X86_64") - .Default("EM_NONE") - << "\nSections:" - << "\n - Name: .text" - << "\n Type: SHT_PROGBITS" - << "\n - Name: .data" - << "\n Type: SHT_PROGBITS" - << "\n - Name: .rodata" - << "\n Type: SHT_PROGBITS" - << "\nSymbols:\n"; - for (const auto &Symbol : Symbols) { - OS << " - Name: " << Symbol.Name << "\n" - << " Type: STT_"; - switch (Symbol.Type) { - default: - case IFSSymbolType::NoType: - OS << "NOTYPE"; - break; - case IFSSymbolType::Object: - OS << "OBJECT"; - break; - case IFSSymbolType::Func: - OS << "FUNC"; - break; - } - OS << "\n Section: .text" - << "\n Binding: STB_" << (Symbol.Weak ? "WEAK" : "GLOBAL") - << "\n"; - } - OS << "...\n"; - - std::string YamlStr = OS.str(); - - // Only or debugging. Not an offical format. - LLVM_DEBUG({ - if (ForceFormat == "ELFOBJYAML") { - Out << YamlStr; - return 0; - } - }); - - yaml::Input YIn(YamlStr); - auto ErrHandler = [](const Twine &Msg) { - WithColor::error(errs(), "llvm-ifs") << Msg << "\n"; - }; - return convertYAML(YIn, Out, ErrHandler) ? 0 : 1; -} - -int writeIfso(const IFSStub &Stub, bool IsWriteIfs, raw_ostream &Out) { - if (IsWriteIfs) { - yaml::Output YamlOut(Out, NULL, /*WrapColumn =*/0); - YamlOut << const_cast<IFSStub &>(Stub); - return 0; - } - - std::string ObjectFileFormat = - ForceFormat.empty() ? Stub.ObjectFileFormat : ForceFormat; - - if (ObjectFileFormat == "ELF" || ForceFormat == "ELFOBJYAML") - return writeElfStub(llvm::Triple(Stub.Triple), Stub.Symbols, - Stub.ObjectFileFormat, Out); - if (ObjectFileFormat == "TBD") - return writeTbdStub(llvm::Triple(Stub.Triple), Stub.Symbols, - Stub.ObjectFileFormat, Out); - - WithColor::error() - << "Invalid ObjectFileFormat: Only ELF and TBD are supported.\n"; - return -1; -} - -// New Interface Stubs Yaml Format: -// --- !experimental-ifs-v1 -// IfsVersion: 1.0 -// Triple: <llvm triple> -// ObjectFileFormat: <ELF | others not yet supported> -// Symbols: -// _ZSymbolName: { Type: <type> } -// ... - -int main(int argc, char *argv[]) { - // Parse arguments. - cl::ParseCommandLineOptions(argc, argv); - - if (InputFilenames.empty()) - InputFilenames.push_back("-"); - - IFSStub Stub; - std::map<std::string, IFSSymbol> SymbolMap; - - std::string PreviousInputFilePath = ""; - for (const std::string &InputFilePath : InputFilenames) { - Expected<std::unique_ptr<IFSStub>> StubOrErr = readInputFile(InputFilePath); - if (!StubOrErr) { - WithColor::error() << StubOrErr.takeError() << "\n"; - return -1; - } - std::unique_ptr<IFSStub> TargetStub = std::move(StubOrErr.get()); - - if (Stub.Triple.empty()) { - PreviousInputFilePath = InputFilePath; - Stub.IfsVersion = TargetStub->IfsVersion; - Stub.Triple = TargetStub->Triple; - Stub.ObjectFileFormat = TargetStub->ObjectFileFormat; - Stub.SOName = TargetStub->SOName; - Stub.NeededLibs = TargetStub->NeededLibs; - } else { - if (Stub.IfsVersion != TargetStub->IfsVersion) { - if (Stub.IfsVersion.getMajor() != IFSVersionCurrent.getMajor()) { - WithColor::error() - << "Interface Stub: IfsVersion Mismatch." - << "\nFilenames: " << PreviousInputFilePath << " " - << InputFilePath << "\nIfsVersion Values: " << Stub.IfsVersion - << " " << TargetStub->IfsVersion << "\n"; - return -1; - } - if (TargetStub->IfsVersion > Stub.IfsVersion) - Stub.IfsVersion = TargetStub->IfsVersion; - } - if (Stub.ObjectFileFormat != TargetStub->ObjectFileFormat) { - WithColor::error() << "Interface Stub: ObjectFileFormat Mismatch." - << "\nFilenames: " << PreviousInputFilePath << " " - << InputFilePath << "\nObjectFileFormat Values: " - << Stub.ObjectFileFormat << " " - << TargetStub->ObjectFileFormat << "\n"; - return -1; - } - if (Stub.Triple != TargetStub->Triple) { - WithColor::error() << "Interface Stub: Triple Mismatch." - << "\nFilenames: " << PreviousInputFilePath << " " - << InputFilePath - << "\nTriple Values: " << Stub.Triple << " " - << TargetStub->Triple << "\n"; - return -1; - } - if (Stub.SOName != TargetStub->SOName) { - WithColor::error() << "Interface Stub: SOName Mismatch." - << "\nFilenames: " << PreviousInputFilePath << " " - << InputFilePath - << "\nSOName Values: " << Stub.SOName << " " - << TargetStub->SOName << "\n"; - return -1; - } - if (Stub.NeededLibs != TargetStub->NeededLibs) { - WithColor::error() << "Interface Stub: NeededLibs Mismatch." - << "\nFilenames: " << PreviousInputFilePath << " " - << InputFilePath << "\n"; - return -1; - } - } - - for (auto Symbol : TargetStub->Symbols) { - auto SI = SymbolMap.find(Symbol.Name); - if (SI == SymbolMap.end()) { - SymbolMap.insert( - std::pair<std::string, IFSSymbol>(Symbol.Name, Symbol)); - continue; - } - - assert(Symbol.Name == SI->second.Name && "Symbol Names Must Match."); - - // Check conflicts: - if (Symbol.Type != SI->second.Type) { - WithColor::error() << "Interface Stub: Type Mismatch for " - << Symbol.Name << ".\nFilename: " << InputFilePath - << "\nType Values: " << getTypeName(SI->second.Type) - << " " << getTypeName(Symbol.Type) << "\n"; - - return -1; - } - if (Symbol.Size != SI->second.Size) { - WithColor::error() << "Interface Stub: Size Mismatch for " - << Symbol.Name << ".\nFilename: " << InputFilePath - << "\nSize Values: " << SI->second.Size << " " - << Symbol.Size << "\n"; - - return -1; - } - if (Symbol.Weak != SI->second.Weak) { - // TODO: Add conflict resolution for Weak vs non-Weak. - WithColor::error() << "Interface Stub: Weak Mismatch for " - << Symbol.Name << ".\nFilename: " << InputFilePath - << "\nWeak Values: " << SI->second.Weak << " " - << Symbol.Weak << "\n"; - - return -1; - } - // TODO: Not checking Warning. Will be dropped. - } - - PreviousInputFilePath = InputFilePath; - } - - if (Stub.IfsVersion != IFSVersionCurrent) - if (Stub.IfsVersion.getMajor() != IFSVersionCurrent.getMajor()) { - WithColor::error() << "Interface Stub: Bad IfsVersion: " - << Stub.IfsVersion << ", llvm-ifs supported version: " - << IFSVersionCurrent << ".\n"; - return -1; - } - - for (auto &Entry : SymbolMap) - Stub.Symbols.insert(Entry.second); - - std::error_code SysErr; - - // Open file for writing. - raw_fd_ostream Out(OutputFilename, SysErr); - if (SysErr) { - WithColor::error() << "Couldn't open " << OutputFilename - << " for writing.\n"; - return -1; - } - - return writeIfso(Stub, (Action == "write-ifs"), Out); -} diff --git a/llvm/tools/llvm-reduce/CMakeLists.txt b/llvm/tools/llvm-reduce/CMakeLists.txt deleted file mode 100644 index 48de0ffa78a1..000000000000 --- a/llvm/tools/llvm-reduce/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -set(LLVM_LINK_COMPONENTS - AllTargetsAsmParsers - AllTargetsCodeGens - AllTargetsDescs - AllTargetsInfos - Core - IRReader - Support - Target - TransformUtils - ) - -add_llvm_tool(llvm-reduce - llvm-reduce.cpp - TestRunner.cpp - deltas/Delta.cpp - deltas/ReduceFunctions.cpp - deltas/ReduceGlobalVars.cpp - deltas/ReduceMetadata.cpp - deltas/ReduceArguments.cpp - deltas/ReduceBasicBlocks.cpp - deltas/ReduceInstructions.cpp - - DEPENDS - intrinsics_gen - ) diff --git a/llvm/tools/llvm-reduce/DeltaManager.h b/llvm/tools/llvm-reduce/DeltaManager.h deleted file mode 100644 index 2309c3adf4e6..000000000000 --- a/llvm/tools/llvm-reduce/DeltaManager.h +++ /dev/null @@ -1,36 +0,0 @@ -//===- DeltaManager.h - Runs Delta Passes to reduce Input -----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file calls each specialized Delta pass in order to reduce the input IR -// file. -// -//===----------------------------------------------------------------------===// - -#include "TestRunner.h" -#include "deltas/Delta.h" -#include "deltas/ReduceArguments.h" -#include "deltas/ReduceBasicBlocks.h" -#include "deltas/ReduceFunctions.h" -#include "deltas/ReduceGlobalVars.h" -#include "deltas/ReduceMetadata.h" -#include "deltas/ReduceInstructions.h" - -namespace llvm { - -// TODO: Add CLI option to run only specified Passes (for unit tests) -inline void runDeltaPasses(TestRunner &Tester) { - reduceFunctionsDeltaPass(Tester); - reduceBasicBlocksDeltaPass(Tester); - reduceGlobalsDeltaPass(Tester); - reduceMetadataDeltaPass(Tester); - reduceArgumentsDeltaPass(Tester); - reduceInstructionsDeltaPass(Tester); - // TODO: Implement the remaining Delta Passes -} - -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/LLVMBuild.txt b/llvm/tools/llvm-reduce/LLVMBuild.txt deleted file mode 100644 index 7928f0503283..000000000000 --- a/llvm/tools/llvm-reduce/LLVMBuild.txt +++ /dev/null @@ -1,24 +0,0 @@ -;===- ./tools/llvm-reduce/LLVMBuild.txt ------------------------*- Conf -*--===; -; -; Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -; See https://llvm.org/LICENSE.txt for license information. -; SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -; -;===------------------------------------------------------------------------===; -; -; This is an LLVMBuild description file for the components in this subdirectory. -; -; For more information on the LLVMBuild system, please see: -; -; http://llvm.org/docs/LLVMBuild.html -; -;===------------------------------------------------------------------------===; - -[component_0] -type = Tool -name = llvm-reduce -parent = Tools -required_libraries = - BitReader - IRReader - all-targets diff --git a/llvm/tools/llvm-reduce/TestRunner.cpp b/llvm/tools/llvm-reduce/TestRunner.cpp deleted file mode 100644 index d0e195d5697c..000000000000 --- a/llvm/tools/llvm-reduce/TestRunner.cpp +++ /dev/null @@ -1,42 +0,0 @@ -//===-- TestRunner.cpp ----------------------------------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#include "TestRunner.h" - -using namespace llvm; - -TestRunner::TestRunner(StringRef TestName, const std::vector<std::string> &TestArgs) - : TestName(TestName), TestArgs(TestArgs) { -} - -/// Runs the interestingness test, passes file to be tested as first argument -/// and other specified test arguments after that. -int TestRunner::run(StringRef Filename) { - std::vector<StringRef> ProgramArgs; - ProgramArgs.push_back(TestName); - - for (const auto &Arg : TestArgs) - ProgramArgs.push_back(Arg); - - ProgramArgs.push_back(Filename); - - std::string ErrMsg; - int Result = sys::ExecuteAndWait( - TestName, ProgramArgs, /*Env=*/None, /*Redirects=*/None, - /*SecondsToWait=*/0, /*MemoryLimit=*/0, &ErrMsg); - - if (Result < 0) { - Error E = make_error<StringError>("Error running interesting-ness test: " + - ErrMsg, - inconvertibleErrorCode()); - errs() << toString(std::move(E)); - exit(1); - } - - return !Result; -} diff --git a/llvm/tools/llvm-reduce/TestRunner.h b/llvm/tools/llvm-reduce/TestRunner.h deleted file mode 100644 index 2270d6bd90b2..000000000000 --- a/llvm/tools/llvm-reduce/TestRunner.h +++ /dev/null @@ -1,46 +0,0 @@ -//===-- tools/llvm-reduce/TestRunner.h ---------------------------*- C++ -*-===/ -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_TOOLS_LLVMREDUCE_TESTRUNNER_H -#define LLVM_TOOLS_LLVMREDUCE_TESTRUNNER_H - -#include "llvm/ADT/SmallString.h" -#include "llvm/IR/Module.h" -#include "llvm/Support/Error.h" -#include "llvm/Support/FileSystem.h" -#include "llvm/Support/Path.h" -#include "llvm/Support/Program.h" -#include <vector> - -namespace llvm { - -// This class contains all the info necessary for running the provided -// interesting-ness test, as well as the most reduced module and its -// respective filename. -class TestRunner { -public: - TestRunner(StringRef TestName, const std::vector<std::string> &TestArgs); - - /// Runs the interesting-ness test for the specified file - /// @returns 0 if test was successful, 1 if otherwise - int run(StringRef Filename); - - /// Returns the most reduced version of the original testcase - Module *getProgram() const { return Program.get(); } - - void setProgram(std::unique_ptr<Module> P) { Program = std::move(P); } - -private: - StringRef TestName; - const std::vector<std::string> &TestArgs; - std::unique_ptr<Module> Program; -}; - -} // namespace llvm - -#endif diff --git a/llvm/tools/llvm-reduce/deltas/Delta.cpp b/llvm/tools/llvm-reduce/deltas/Delta.cpp deleted file mode 100644 index 0642241ddebd..000000000000 --- a/llvm/tools/llvm-reduce/deltas/Delta.cpp +++ /dev/null @@ -1,162 +0,0 @@ -//===- Delta.cpp - Delta Debugging Algorithm Implementation ---------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file contains the implementation for the Delta Debugging Algorithm: -// it splits a given set of Targets (i.e. Functions, Instructions, BBs, etc.) -// into chunks and tries to reduce the number chunks that are interesting. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/ADT/STLExtras.h" -#include "llvm/Support/ToolOutputFile.h" -#include "llvm/Transforms/Utils/Cloning.h" -#include <fstream> -#include <set> - -using namespace llvm; - -bool IsReduced(Module &M, TestRunner &Test, SmallString<128> &CurrentFilepath) { - // Write Module to tmp file - int FD; - std::error_code EC = - sys::fs::createTemporaryFile("llvm-reduce", "ll", FD, CurrentFilepath); - if (EC) { - errs() << "Error making unique filename: " << EC.message() << "!\n"; - exit(1); - } - - ToolOutputFile Out(CurrentFilepath, FD); - M.print(Out.os(), /*AnnotationWriter=*/nullptr); - Out.os().close(); - if (Out.os().has_error()) { - errs() << "Error emitting bitcode to file '" << CurrentFilepath << "'!\n"; - exit(1); - } - - // Current Chunks aren't interesting - return Test.run(CurrentFilepath); -} - -/// Counts the amount of lines for a given file -static int getLines(StringRef Filepath) { - int Lines = 0; - std::string CurrLine; - std::ifstream FileStream(Filepath); - - while (std::getline(FileStream, CurrLine)) - ++Lines; - - return Lines; -} - -/// Splits Chunks in half and prints them. -/// If unable to split (when chunk size is 1) returns false. -static bool increaseGranularity(std::vector<Chunk> &Chunks) { - errs() << "Increasing granularity..."; - std::vector<Chunk> NewChunks; - bool SplitOne = false; - - for (auto &C : Chunks) { - if (C.end - C.begin == 0) - NewChunks.push_back(C); - else { - int Half = (C.begin + C.end) / 2; - NewChunks.push_back({C.begin, Half}); - NewChunks.push_back({Half + 1, C.end}); - SplitOne = true; - } - } - if (SplitOne) { - Chunks = NewChunks; - errs() << "Success! New Chunks:\n"; - for (auto C : Chunks) { - errs() << '\t'; - C.print(); - errs() << '\n'; - } - } - return SplitOne; -} - -/// Runs the Delta Debugging algorithm, splits the code into chunks and -/// reduces the amount of chunks that are considered interesting by the -/// given test. -void llvm::runDeltaPass( - TestRunner &Test, int Targets, - std::function<void(const std::vector<Chunk> &, Module *)> - ExtractChunksFromModule) { - assert(Targets >= 0); - if (!Targets) { - errs() << "\nNothing to reduce\n"; - return; - } - - if (Module *Program = Test.getProgram()) { - SmallString<128> CurrentFilepath; - if (!IsReduced(*Program, Test, CurrentFilepath)) { - errs() << "\nInput isn't interesting! Verify interesting-ness test\n"; - exit(1); - } - } - - std::vector<Chunk> Chunks = {{1, Targets}}; - std::set<Chunk> UninterestingChunks; - std::unique_ptr<Module> ReducedProgram; - - if (!increaseGranularity(Chunks)) { - errs() << "\nAlready at minimum size. Cannot reduce anymore.\n"; - return; - } - - do { - UninterestingChunks = {}; - for (int I = Chunks.size() - 1; I >= 0; --I) { - std::vector<Chunk> CurrentChunks; - - for (auto C : Chunks) - if (!UninterestingChunks.count(C) && C != Chunks[I]) - CurrentChunks.push_back(C); - - if (CurrentChunks.empty()) - continue; - - // Clone module before hacking it up.. - std::unique_ptr<Module> Clone = CloneModule(*Test.getProgram()); - // Generate Module with only Targets inside Current Chunks - ExtractChunksFromModule(CurrentChunks, Clone.get()); - - errs() << "Ignoring: "; - Chunks[I].print(); - for (auto C : UninterestingChunks) - C.print(); - - - - SmallString<128> CurrentFilepath; - if (!IsReduced(*Clone, Test, CurrentFilepath)) { - errs() << "\n"; - continue; - } - - UninterestingChunks.insert(Chunks[I]); - ReducedProgram = std::move(Clone); - errs() << " **** SUCCESS | lines: " << getLines(CurrentFilepath) << "\n"; - } - // Delete uninteresting chunks - erase_if(Chunks, [&UninterestingChunks](const Chunk &C) { - return UninterestingChunks.count(C); - }); - - } while (!UninterestingChunks.empty() || increaseGranularity(Chunks)); - - // If we reduced the testcase replace it - if (ReducedProgram) - Test.setProgram(std::move(ReducedProgram)); - errs() << "Couldn't increase anymore.\n"; -} diff --git a/llvm/tools/llvm-reduce/deltas/Delta.h b/llvm/tools/llvm-reduce/deltas/Delta.h deleted file mode 100644 index dbb18e4bd07f..000000000000 --- a/llvm/tools/llvm-reduce/deltas/Delta.h +++ /dev/null @@ -1,76 +0,0 @@ -//===- Delta.h - Delta Debugging Algorithm Implementation -----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file contains the implementation for the Delta Debugging Algorithm: -// it splits a given set of Targets (i.e. Functions, Instructions, BBs, etc.) -// into chunks and tries to reduce the number chunks that are interesting. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_TOOLS_LLVMREDUCE_LLVMREDUCE_DELTA_H -#define LLVM_TOOLS_LLVMREDUCE_LLVMREDUCE_DELTA_H - -#include "TestRunner.h" -#include <vector> -#include <utility> -#include <functional> - -namespace llvm { - -struct Chunk { - int begin; - int end; - - /// Helper function to verify if a given Target-index is inside the Chunk - bool contains(int Index) const { return Index >= begin && Index <= end; } - - void print() const { - errs() << "[" << begin; - if (end - begin != 0) - errs() << "," << end; - errs() << "]"; - } - - /// Operator when populating CurrentChunks in Generic Delta Pass - friend bool operator!=(const Chunk &C1, const Chunk &C2) { - return C1.begin != C2.begin || C1.end != C2.end; - } - - /// Operator used for sets - friend bool operator<(const Chunk &C1, const Chunk &C2) { - return std::tie(C1.begin, C1.end) < std::tie(C2.begin, C2.end); - } -}; - -/// This function implements the Delta Debugging algorithm, it receives a -/// number of Targets (e.g. Functions, Instructions, Basic Blocks, etc.) and -/// splits them in half; these chunks of targets are then tested while ignoring -/// one chunk, if a chunk is proven to be uninteresting (i.e. fails the test) -/// it is removed from consideration. The algorithm will attempt to split the -/// Chunks in half and start the process again until it can't split chunks -/// anymore. -/// -/// This function is intended to be called by each specialized delta pass (e.g. -/// RemoveFunctions) and receives three key parameters: -/// * Test: The main TestRunner instance which is used to run the provided -/// interesting-ness test, as well as to store and access the reduced Program. -/// * Targets: The amount of Targets that are going to be reduced by the -/// algorithm, for example, the RemoveGlobalVars pass would send the amount of -/// initialized GVs. -/// * ExtractChunksFromModule: A function used to tailor the main program so it -/// only contains Targets that are inside Chunks of the given iteration. -/// Note: This function is implemented by each specialized Delta pass -/// -/// Other implementations of the Delta Debugging algorithm can also be found in -/// the CReduce, Delta, and Lithium projects. -void runDeltaPass(TestRunner &Test, int Targets, - std::function<void(const std::vector<Chunk> &, Module *)> - ExtractChunksFromModule); -} // namespace llvm - -#endif diff --git a/llvm/tools/llvm-reduce/deltas/ReduceArguments.cpp b/llvm/tools/llvm-reduce/deltas/ReduceArguments.cpp deleted file mode 100644 index f5f14b83f42c..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceArguments.cpp +++ /dev/null @@ -1,125 +0,0 @@ -//===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "ReduceArguments.h" -#include "Delta.h" -#include "llvm/ADT/SmallVector.h" -#include <set> -#include <vector> - -using namespace llvm; - -/// Goes over OldF calls and replaces them with a call to NewF -static void replaceFunctionCalls(Function &OldF, Function &NewF, - const std::set<int> &ArgIndexesToKeep) { - const auto &Users = OldF.users(); - for (auto I = Users.begin(), E = Users.end(); I != E; ) - if (auto *CI = dyn_cast<CallInst>(*I++)) { - SmallVector<Value *, 8> Args; - for (auto ArgI = CI->arg_begin(), E = CI->arg_end(); ArgI != E; ++ArgI) - if (ArgIndexesToKeep.count(ArgI - CI->arg_begin())) - Args.push_back(*ArgI); - - CallInst *NewCI = CallInst::Create(&NewF, Args); - NewCI->setCallingConv(NewF.getCallingConv()); - if (!CI->use_empty()) - CI->replaceAllUsesWith(NewCI); - ReplaceInstWithInst(CI, NewCI); - } -} - -/// Removes out-of-chunk arguments from functions, and modifies their calls -/// accordingly. It also removes allocations of out-of-chunk arguments. -static void extractArgumentsFromModule(std::vector<Chunk> ChunksToKeep, - Module *Program) { - int I = 0, ArgCount = 0; - std::set<Argument *> ArgsToKeep; - std::vector<Function *> Funcs; - // Get inside-chunk arguments, as well as their parent function - for (auto &F : *Program) - if (!F.isDeclaration()) { - Funcs.push_back(&F); - for (auto &A : F.args()) - if (I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(++ArgCount)) - ArgsToKeep.insert(&A); - if (ChunksToKeep[I].end == ArgCount) - ++I; - } - } - - for (auto *F : Funcs) { - ValueToValueMapTy VMap; - std::vector<Instruction *> InstToDelete; - for (auto &A : F->args()) - if (!ArgsToKeep.count(&A)) { - // By adding undesired arguments to the VMap, CloneFunction will remove - // them from the resulting Function - VMap[&A] = UndefValue::get(A.getType()); - for (auto *U : A.users()) - if (auto *I = dyn_cast<Instruction>(*&U)) - InstToDelete.push_back(I); - } - // Delete any instruction that uses the argument - for (auto *I : InstToDelete) { - I->replaceAllUsesWith(UndefValue::get(I->getType())); - I->eraseFromParent(); - } - - // No arguments to reduce - if (VMap.empty()) - continue; - - std::set<int> ArgIndexesToKeep; - int ArgI = 0; - for (auto &Arg : F->args()) - if (ArgsToKeep.count(&Arg)) - ArgIndexesToKeep.insert(++ArgI); - - auto *ClonedFunc = CloneFunction(F, VMap); - // In order to preserve function order, we move Clone after old Function - ClonedFunc->removeFromParent(); - Program->getFunctionList().insertAfter(F->getIterator(), ClonedFunc); - - replaceFunctionCalls(*F, *ClonedFunc, ArgIndexesToKeep); - // Rename Cloned Function to Old's name - std::string FName = F->getName(); - F->eraseFromParent(); - ClonedFunc->setName(FName); - } -} - -/// Counts the amount of arguments in non-declaration functions and prints their -/// respective name, index, and parent function name -static int countArguments(Module *Program) { - // TODO: Silence index with --quiet flag - outs() << "----------------------------\n"; - outs() << "Param Index Reference:\n"; - int ArgsCount = 0; - for (auto &F : *Program) - if (!F.isDeclaration() && F.arg_size()) { - outs() << " " << F.getName() << "\n"; - for (auto &A : F.args()) - outs() << "\t" << ++ArgsCount << ": " << A.getName() << "\n"; - - outs() << "----------------------------\n"; - } - - return ArgsCount; -} - -void llvm::reduceArgumentsDeltaPass(TestRunner &Test) { - outs() << "*** Reducing Arguments...\n"; - int ArgCount = countArguments(Test.getProgram()); - runDeltaPass(Test, ArgCount, extractArgumentsFromModule); -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceArguments.h b/llvm/tools/llvm-reduce/deltas/ReduceArguments.h deleted file mode 100644 index d9682b44f74d..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceArguments.h +++ /dev/null @@ -1,21 +0,0 @@ -//===- ReduceArguments.h - Specialized Delta Pass -------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/IR/Argument.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" -#include "llvm/Transforms/Utils/Cloning.h" - -namespace llvm { -void reduceArgumentsDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp b/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp deleted file mode 100644 index 03c3962d2fd9..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.cpp +++ /dev/null @@ -1,146 +0,0 @@ -//===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "ReduceBasicBlocks.h" -#include "llvm/IR/BasicBlock.h" -#include "llvm/IR/Instruction.h" -#include "llvm/IR/Instructions.h" -#include "llvm/IR/LLVMContext.h" -#include "llvm/IR/Value.h" -#include "llvm/Support/Casting.h" -#include "llvm/Support/raw_ostream.h" -#include <vector> - -using namespace llvm; - -/// Replaces BB Terminator with one that only contains Chunk BBs -static void replaceBranchTerminator(BasicBlock &BB, - std::set<BasicBlock *> BBsToKeep) { - auto Term = BB.getTerminator(); - std::vector<BasicBlock *> ChunkSucessors; - for (auto Succ : successors(&BB)) - if (BBsToKeep.count(Succ)) - ChunkSucessors.push_back(Succ); - - // BB only references Chunk BBs - if (ChunkSucessors.size() == Term->getNumSuccessors()) - return; - - bool IsBranch = isa<BranchInst>(Term); - Value *Address = nullptr; - if (auto IndBI = dyn_cast<IndirectBrInst>(Term)) - Address = IndBI->getAddress(); - - Term->eraseFromParent(); - - if (ChunkSucessors.empty()) { - ReturnInst::Create(BB.getContext(), nullptr, &BB); - return; - } - - if (IsBranch) - BranchInst::Create(ChunkSucessors[0], &BB); - - if (Address) { - auto NewIndBI = - IndirectBrInst::Create(Address, ChunkSucessors.size(), &BB); - for (auto Dest : ChunkSucessors) - NewIndBI->addDestination(Dest); - } -} - -/// Removes uninteresting BBs from switch, if the default case ends up being -/// uninteresting, the switch is replaced with a void return (since it has to be -/// replace with something) -static void removeUninterestingBBsFromSwitch(SwitchInst &SwInst, - std::set<BasicBlock *> BBsToKeep) { - if (!BBsToKeep.count(SwInst.getDefaultDest())) { - ReturnInst::Create(SwInst.getContext(), nullptr, SwInst.getParent()); - SwInst.eraseFromParent(); - } else - for (int I = 0, E = SwInst.getNumCases(); I != E; ++I) { - auto Case = SwInst.case_begin() + I; - if (!BBsToKeep.count(Case->getCaseSuccessor())) { - SwInst.removeCase(Case); - --I; - --E; - } - } -} - -/// Removes out-of-chunk arguments from functions, and modifies their calls -/// accordingly. It also removes allocations of out-of-chunk arguments. -static void extractBasicBlocksFromModule(std::vector<Chunk> ChunksToKeep, - Module *Program) { - int I = 0, BBCount = 0; - std::set<BasicBlock *> BBsToKeep; - - for (auto &F : *Program) - for (auto &BB : F) - if (I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(++BBCount)) - BBsToKeep.insert(&BB); - if (ChunksToKeep[I].end == BBCount) - ++I; - } - - std::vector<BasicBlock *> BBsToDelete; - for (auto &F : *Program) - for (auto &BB : F) { - if (!BBsToKeep.count(&BB)) { - BBsToDelete.push_back(&BB); - // Remove out-of-chunk BB from successor phi nodes - for (auto *Succ : successors(&BB)) - Succ->removePredecessor(&BB); - } - } - - // Replace terminators that reference out-of-chunk BBs - for (auto &F : *Program) - for (auto &BB : F) { - if (auto *SwInst = dyn_cast<SwitchInst>(BB.getTerminator())) - removeUninterestingBBsFromSwitch(*SwInst, BBsToKeep); - else - replaceBranchTerminator(BB, BBsToKeep); - } - - // Replace out-of-chunk switch uses - for (auto &BB : BBsToDelete) { - // Instructions might be referenced in other BBs - for (auto &I : *BB) - I.replaceAllUsesWith(UndefValue::get(I.getType())); - BB->eraseFromParent(); - } -} - -/// Counts the amount of basic blocks and prints their name & respective index -static int countBasicBlocks(Module *Program) { - // TODO: Silence index with --quiet flag - outs() << "----------------------------\n"; - int BBCount = 0; - for (auto &F : *Program) - for (auto &BB : F) { - if (BB.hasName()) - outs() << "\t" << ++BBCount << ": " << BB.getName() << "\n"; - else - outs() << "\t" << ++BBCount << ": Unnamed\n"; - } - - return BBCount; -} - -void llvm::reduceBasicBlocksDeltaPass(TestRunner &Test) { - outs() << "*** Reducing Basic Blocks...\n"; - int BBCount = countBasicBlocks(Test.getProgram()); - runDeltaPass(Test, BBCount, extractBasicBlocksFromModule); -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.h b/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.h deleted file mode 100644 index cf76a0abbcd7..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceBasicBlocks.h +++ /dev/null @@ -1,20 +0,0 @@ -//===- ReduceArguments.h - Specialized Delta Pass -------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" -#include "llvm/Transforms/Utils/Cloning.h" - -namespace llvm { -void reduceBasicBlocksDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/deltas/ReduceFunctions.cpp b/llvm/tools/llvm-reduce/deltas/ReduceFunctions.cpp deleted file mode 100644 index 3382f35a945a..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceFunctions.cpp +++ /dev/null @@ -1,77 +0,0 @@ -//===- ReduceFunctions.cpp - Specialized Delta Pass -----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce functions (and any instruction that calls it) in the provided -// Module. -// -//===----------------------------------------------------------------------===// - -#include "ReduceFunctions.h" -#include "Delta.h" -#include "llvm/ADT/SetVector.h" -#include <set> - -using namespace llvm; - -/// Removes all the Defined Functions (as well as their calls) -/// that aren't inside any of the desired Chunks. -static void extractFunctionsFromModule(const std::vector<Chunk> &ChunksToKeep, - Module *Program) { - // Get functions inside desired chunks - std::set<Function *> FuncsToKeep; - int I = 0, FunctionCount = 0; - for (auto &F : *Program) - if (I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(++FunctionCount)) - FuncsToKeep.insert(&F); - if (FunctionCount == ChunksToKeep[I].end) - ++I; - } - - // Delete out-of-chunk functions, and replace their calls with undef - std::vector<Function *> FuncsToRemove; - SetVector<CallInst *> CallsToRemove; - for (auto &F : *Program) - if (!FuncsToKeep.count(&F)) { - for (auto U : F.users()) - if (auto *Call = dyn_cast<CallInst>(U)) { - Call->replaceAllUsesWith(UndefValue::get(Call->getType())); - CallsToRemove.insert(Call); - } - F.replaceAllUsesWith(UndefValue::get(F.getType())); - FuncsToRemove.push_back(&F); - } - - for (auto *C : CallsToRemove) - C->eraseFromParent(); - - for (auto *F : FuncsToRemove) - F->eraseFromParent(); -} - -/// Counts the amount of non-declaration functions and prints their -/// respective name & index -static int countFunctions(Module *Program) { - // TODO: Silence index with --quiet flag - errs() << "----------------------------\n"; - errs() << "Function Index Reference:\n"; - int FunctionCount = 0; - for (auto &F : *Program) - errs() << "\t" << ++FunctionCount << ": " << F.getName() << "\n"; - - errs() << "----------------------------\n"; - return FunctionCount; -} - -void llvm::reduceFunctionsDeltaPass(TestRunner &Test) { - errs() << "*** Reducing Functions...\n"; - int Functions = countFunctions(Test.getProgram()); - runDeltaPass(Test, Functions, extractFunctionsFromModule); - errs() << "----------------------------\n"; -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceFunctions.h b/llvm/tools/llvm-reduce/deltas/ReduceFunctions.h deleted file mode 100644 index 7c2cd3f33e9f..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceFunctions.h +++ /dev/null @@ -1,20 +0,0 @@ -//===- ReduceFunctions.h - Specialized Delta Pass -------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce functions (and any instruction that calls it) in the provided -// Module. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/Transforms/Utils/Cloning.h" - -namespace llvm { -void reduceFunctionsDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp b/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp deleted file mode 100644 index 5732208ee0a9..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.cpp +++ /dev/null @@ -1,74 +0,0 @@ -//===- ReduceGlobalVars.cpp - Specialized Delta Pass ----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce initialized Global Variables in the provided Module. -// -//===----------------------------------------------------------------------===// - -#include "ReduceGlobalVars.h" -#include <set> - -using namespace llvm; - -/// Removes all the Initialized GVs that aren't inside the desired Chunks. -static void extractGVsFromModule(std::vector<Chunk> ChunksToKeep, - Module *Program) { - // Get GVs inside desired chunks - std::set<GlobalVariable *> GVsToKeep; - int I = 0, GVCount = 0; - for (auto &GV : Program->globals()) - if (GV.hasInitializer() && I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(++GVCount)) - GVsToKeep.insert(&GV); - if (GVCount == ChunksToKeep[I].end) - ++I; - } - - // Delete out-of-chunk GVs and their uses - std::vector<GlobalVariable *> ToRemove; - std::vector<Instruction *> InstToRemove; - for (auto &GV : Program->globals()) - if (GV.hasInitializer() && !GVsToKeep.count(&GV)) { - for (auto U : GV.users()) - if (auto *Inst = dyn_cast<Instruction>(U)) - InstToRemove.push_back(Inst); - - GV.replaceAllUsesWith(UndefValue::get(GV.getType())); - ToRemove.push_back(&GV); - } - - // Delete Instruction uses of unwanted GVs - for (auto *Inst : InstToRemove) { - Inst->replaceAllUsesWith(UndefValue::get(Inst->getType())); - Inst->eraseFromParent(); - } - - for (auto *GV : ToRemove) - GV->eraseFromParent(); -} - -/// Counts the amount of initialized GVs and displays their -/// respective name & index -static int countGVs(Module *Program) { - // TODO: Silence index with --quiet flag - outs() << "----------------------------\n"; - outs() << "GlobalVariable Index Reference:\n"; - int GVCount = 0; - for (auto &GV : Program->globals()) - if (GV.hasInitializer()) - outs() << "\t" << ++GVCount << ": " << GV.getName() << "\n"; - outs() << "----------------------------\n"; - return GVCount; -} - -void llvm::reduceGlobalsDeltaPass(TestRunner &Test) { - outs() << "*** Reducing GVs...\n"; - int GVCount = countGVs(Test.getProgram()); - runDeltaPass(Test, GVCount, extractGVsFromModule); -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.h b/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.h deleted file mode 100644 index d4a870aded58..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceGlobalVars.h +++ /dev/null @@ -1,20 +0,0 @@ -//===- ReduceGlobalVars.h - Specialized Delta Pass ------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce initialized Global Variables in the provided Module. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/IR/Value.h" -#include "llvm/Transforms/Utils/Cloning.h" - -namespace llvm { -void reduceGlobalsDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp b/llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp deleted file mode 100644 index b3497ad2dc02..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceInstructions.cpp +++ /dev/null @@ -1,65 +0,0 @@ -//===- ReduceArguments.cpp - Specialized Delta Pass -----------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "ReduceInstructions.h" - -using namespace llvm; - -/// Removes out-of-chunk arguments from functions, and modifies their calls -/// accordingly. It also removes allocations of out-of-chunk arguments. -static void extractInstrFromModule(std::vector<Chunk> ChunksToKeep, - Module *Program) { - int I = 0, InstCount = 0; - std::set<Instruction *> InstToKeep; - - for (auto &F : *Program) - for (auto &BB : F) - for (auto &Inst : BB) - if (I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(++InstCount)) - InstToKeep.insert(&Inst); - if (ChunksToKeep[I].end == InstCount) - ++I; - } - - std::vector<Instruction *> InstToDelete; - for (auto &F : *Program) - for (auto &BB : F) - for (auto &Inst : BB) - if (!InstToKeep.count(&Inst)) { - Inst.replaceAllUsesWith(UndefValue::get(Inst.getType())); - InstToDelete.push_back(&Inst); - } - - for (auto &I : InstToDelete) - I->eraseFromParent(); -} - -/// Counts the amount of basic blocks and prints their name & respective index -static unsigned countInstructions(Module *Program) { - // TODO: Silence index with --quiet flag - outs() << "----------------------------\n"; - int InstCount = 0; - for (auto &F : *Program) - for (auto &BB : F) - InstCount += BB.getInstList().size(); - outs() << "Number of instructions: " << InstCount << "\n"; - - return InstCount; -} - -void llvm::reduceInstructionsDeltaPass(TestRunner &Test) { - outs() << "*** Reducing Insructions...\n"; - unsigned InstCount = countInstructions(Test.getProgram()); - runDeltaPass(Test, InstCount, extractInstrFromModule); -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceInstructions.h b/llvm/tools/llvm-reduce/deltas/ReduceInstructions.h deleted file mode 100644 index a9266acd051a..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceInstructions.h +++ /dev/null @@ -1,20 +0,0 @@ -//===- ReduceArguments.h - Specialized Delta Pass -------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements a function which calls the Generic Delta pass in order -// to reduce uninteresting Arguments from defined functions. -// -//===----------------------------------------------------------------------===// - -#include "Delta.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" -#include "llvm/Transforms/Utils/Cloning.h" - -namespace llvm { -void reduceInstructionsDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/deltas/ReduceMetadata.cpp b/llvm/tools/llvm-reduce/deltas/ReduceMetadata.cpp deleted file mode 100644 index 4ea223546efa..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceMetadata.cpp +++ /dev/null @@ -1,138 +0,0 @@ -//===- ReduceMetadata.cpp - Specialized Delta Pass ------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements two functions used by the Generic Delta Debugging -// Algorithm, which are used to reduce Metadata nodes. -// -//===----------------------------------------------------------------------===// - -#include "ReduceMetadata.h" -#include "Delta.h" -#include "llvm/ADT/SmallVector.h" -#include <set> -#include <vector> - -using namespace llvm; - -/// Adds all Unnamed Metadata Nodes that are inside desired Chunks to set -template <class T> -static void getChunkMetadataNodes(T &MDUser, int &I, - const std::vector<Chunk> &ChunksToKeep, - std::set<MDNode *> &SeenNodes, - std::set<MDNode *> &NodesToKeep) { - SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; - MDUser.getAllMetadata(MDs); - for (auto &MD : MDs) { - SeenNodes.insert(MD.second); - if (I < (int)ChunksToKeep.size()) { - if (ChunksToKeep[I].contains(SeenNodes.size())) - NodesToKeep.insert(MD.second); - if (ChunksToKeep[I].end == (int)SeenNodes.size()) - ++I; - } - } -} - -/// Erases out-of-chunk unnamed metadata nodes from its user -template <class T> -static void eraseMetadataIfOutsideChunk(T &MDUser, - const std::set<MDNode *> &NodesToKeep) { - SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; - MDUser.getAllMetadata(MDs); - for (int I = 0, E = MDs.size(); I != E; ++I) - if (!NodesToKeep.count(MDs[I].second)) - MDUser.setMetadata(I, NULL); -} - -/// Removes all the Named and Unnamed Metadata Nodes, as well as any debug -/// functions that aren't inside the desired Chunks. -static void extractMetadataFromModule(const std::vector<Chunk> &ChunksToKeep, - Module *Program) { - std::set<MDNode *> SeenNodes; - std::set<MDNode *> NodesToKeep; - int I = 0; - - // Add chunk MDNodes used by GVs, Functions, and Instructions to set - for (auto &GV : Program->globals()) - getChunkMetadataNodes(GV, I, ChunksToKeep, SeenNodes, NodesToKeep); - - for (auto &F : *Program) { - getChunkMetadataNodes(F, I, ChunksToKeep, SeenNodes, NodesToKeep); - for (auto &BB : F) - for (auto &Inst : BB) - getChunkMetadataNodes(Inst, I, ChunksToKeep, SeenNodes, NodesToKeep); - } - - // Once more, go over metadata nodes, but deleting the ones outside chunks - for (auto &GV : Program->globals()) - eraseMetadataIfOutsideChunk(GV, NodesToKeep); - - for (auto &F : *Program) { - eraseMetadataIfOutsideChunk(F, NodesToKeep); - for (auto &BB : F) - for (auto &Inst : BB) - eraseMetadataIfOutsideChunk(Inst, NodesToKeep); - } - - - // Get out-of-chunk Named metadata nodes - unsigned MetadataCount = SeenNodes.size(); - std::vector<NamedMDNode *> NamedNodesToDelete; - for (auto &MD : Program->named_metadata()) { - if (I < (int)ChunksToKeep.size()) { - if (!ChunksToKeep[I].contains(++MetadataCount)) - NamedNodesToDelete.push_back(&MD); - if (ChunksToKeep[I].end == (int)SeenNodes.size()) - ++I; - } else - NamedNodesToDelete.push_back(&MD); - } - - for (auto *NN : NamedNodesToDelete) { - for (int I = 0, E = NN->getNumOperands(); I != E; ++I) - NN->setOperand(I, NULL); - NN->eraseFromParent(); - } -} - -// Gets unnamed metadata nodes used by a given instruction/GV/function and adds -// them to the set of seen nodes -template <class T> -static void addMetadataToSet(T &MDUser, std::set<MDNode *> &UnnamedNodes) { - SmallVector<std::pair<unsigned, MDNode *>, 4> MDs; - MDUser.getAllMetadata(MDs); - for (auto &MD : MDs) - UnnamedNodes.insert(MD.second); -} - -/// Returns the amount of Named and Unnamed Metadata Nodes -static int countMetadataTargets(Module *Program) { - std::set<MDNode *> UnnamedNodes; - int NamedMetadataNodes = Program->named_metadata_size(); - - // Get metadata nodes used by globals - for (auto &GV : Program->globals()) - addMetadataToSet(GV, UnnamedNodes); - - // Do the same for nodes used by functions & instructions - for (auto &F : *Program) { - addMetadataToSet(F, UnnamedNodes); - for (auto &BB : F) - for (auto &I : BB) - addMetadataToSet(I, UnnamedNodes); - } - - return UnnamedNodes.size() + NamedMetadataNodes; -} - -void llvm::reduceMetadataDeltaPass(TestRunner &Test) { - outs() << "*** Reducing Metadata...\n"; - int MDCount = countMetadataTargets(Test.getProgram()); - runDeltaPass(Test, MDCount, extractMetadataFromModule); - outs() << "----------------------------\n"; -} diff --git a/llvm/tools/llvm-reduce/deltas/ReduceMetadata.h b/llvm/tools/llvm-reduce/deltas/ReduceMetadata.h deleted file mode 100644 index 275b44c2aa7d..000000000000 --- a/llvm/tools/llvm-reduce/deltas/ReduceMetadata.h +++ /dev/null @@ -1,18 +0,0 @@ -//===- ReduceMetadata.h - Specialized Delta Pass ------------------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This file implements two functions used by the Generic Delta Debugging -// Algorithm, which are used to reduce Metadata nodes. -// -//===----------------------------------------------------------------------===// - -#include "TestRunner.h" - -namespace llvm { -void reduceMetadataDeltaPass(TestRunner &Test); -} // namespace llvm diff --git a/llvm/tools/llvm-reduce/llvm-reduce.cpp b/llvm/tools/llvm-reduce/llvm-reduce.cpp deleted file mode 100644 index 83dcf980a786..000000000000 --- a/llvm/tools/llvm-reduce/llvm-reduce.cpp +++ /dev/null @@ -1,114 +0,0 @@ -//===- llvm-reduce.cpp - The LLVM Delta Reduction utility -----------------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// This program tries to reduce an IR test case for a given interesting-ness -// test. It runs multiple delta debugging passes in order to minimize the input -// file. It's worth noting that this is a part of the bugpoint redesign -// proposal, and thus a *temporary* tool that will eventually be integrated -// into the bugpoint tool itself. -// -//===----------------------------------------------------------------------===// - -#include "DeltaManager.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/IR/LLVMContext.h" -#include "llvm/IR/Verifier.h" -#include "llvm/IRReader/IRReader.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/InitLLVM.h" -#include "llvm/Support/SourceMgr.h" -#include "llvm/Support/raw_ostream.h" -#include <system_error> -#include <vector> - -using namespace llvm; - -static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden); -static cl::opt<bool> Version("v", cl::desc("Alias for -version"), cl::Hidden); - -static cl::opt<std::string> InputFilename(cl::Positional, cl::Required, - cl::desc("<input llvm ll/bc file>")); - -static cl::opt<std::string> - TestFilename("test", cl::Required, - cl::desc("Name of the interesting-ness test to be run")); - -static cl::list<std::string> - TestArguments("test-arg", cl::ZeroOrMore, - cl::desc("Arguments passed onto the interesting-ness test")); - -static cl::opt<std::string> - OutputFilename("output", - cl::desc("Specify the output file. default: reduced.ll")); -static cl::alias OutputFileAlias("o", cl::desc("Alias for -output"), - cl::aliasopt(OutputFilename)); - -static cl::opt<bool> - ReplaceInput("in-place", - cl::desc("WARNING: This option will replace your input file" - "with the reduced version!")); - -// Parses IR into a Module and verifies it -static std::unique_ptr<Module> parseInputFile(StringRef Filename, - LLVMContext &Ctxt) { - SMDiagnostic Err; - std::unique_ptr<Module> Result = parseIRFile(Filename, Err, Ctxt); - if (!Result) { - Err.print("llvm-reduce", errs()); - return Result; - } - - if (verifyModule(*Result, &errs())) { - errs() << "Error: " << Filename << " - input module is broken!\n"; - return std::unique_ptr<Module>(); - } - - return Result; -} - -int main(int argc, char **argv) { - InitLLVM X(argc, argv); - - cl::ParseCommandLineOptions(argc, argv, "LLVM automatic testcase reducer.\n"); - - LLVMContext Context; - std::unique_ptr<Module> OriginalProgram = - parseInputFile(InputFilename, Context); - - // Initialize test environment - TestRunner Tester(TestFilename, TestArguments); - Tester.setProgram(std::move(OriginalProgram)); - - // Try to reduce code - runDeltaPasses(Tester); - - if (!Tester.getProgram()) { - errs() << "\nCouldnt reduce input :/\n"; - } else { - // Print reduced file to STDOUT - if (OutputFilename == "-") - Tester.getProgram()->print(outs(), nullptr); - else { - if (ReplaceInput) // In-place - OutputFilename = InputFilename.c_str(); - else if (OutputFilename.empty()) - OutputFilename = "reduced.ll"; - - std::error_code EC; - raw_fd_ostream Out(OutputFilename, EC); - if (EC) { - errs() << "Error opening output file: " << EC.message() << "!\n"; - exit(1); - } - Tester.getProgram()->print(Out, /*AnnotationWriter=*/nullptr); - errs() << "\nDone reducing! Reduced testcase: " << OutputFilename << "\n"; - } - } - - return 0; -} diff --git a/llvm/tools/vfabi-demangle-fuzzer/CMakeLists.txt b/llvm/tools/vfabi-demangle-fuzzer/CMakeLists.txt deleted file mode 100644 index 908364690f5e..000000000000 --- a/llvm/tools/vfabi-demangle-fuzzer/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -set(LLVM_LINK_COMPONENTS - Analysis - Support -) -add_llvm_fuzzer(vfabi-demangler-fuzzer - vfabi-demangler-fuzzer.cpp -) diff --git a/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp b/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp deleted file mode 100644 index 13657effbbeb..000000000000 --- a/llvm/tools/vfabi-demangle-fuzzer/vfabi-demangler-fuzzer.cpp +++ /dev/null @@ -1,26 +0,0 @@ -//===-- vfabi-demangler-fuzzer.cpp - Fuzzer VFABI using lib/Fuzzer ------===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// -// -// Build tool to fuzz the demangler for the vector function ABI names. -// -//===----------------------------------------------------------------------===// - -#include "llvm/Analysis/VectorUtils.h" - -using namespace llvm; - -extern "C" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) { - const StringRef MangledName((const char *)Data, Size); - const auto Info = VFABI::tryDemangleForVFABI(MangledName); - - // Do not optimize away the return value. Inspired by - // https://github.com/google/benchmark/blob/master/include/benchmark/benchmark.h#L307-L345 - asm volatile("" : : "r,m"(Info) : "memory"); - - return 0; -} diff --git a/llvm/utils/TableGen/GlobalISel/CMakeLists.txt b/llvm/utils/TableGen/GlobalISel/CMakeLists.txt deleted file mode 100644 index 2f74d1087bcd..000000000000 --- a/llvm/utils/TableGen/GlobalISel/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -set(LLVM_LINK_COMPONENTS - Support - ) - -llvm_add_library(LLVMTableGenGlobalISel STATIC DISABLE_LLVM_LINK_LLVM_DYLIB - CodeExpander.cpp - ) diff --git a/llvm/utils/add_argument_names.py b/llvm/utils/add_argument_names.py deleted file mode 100755 index 38dde2599794..000000000000 --- a/llvm/utils/add_argument_names.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python3 -import re, sys - -def fix_string(s): - TYPE = re.compile('\s*(i[0-9]+|float|double|x86_fp80|fp128|ppc_fp128|\[\[.*?\]\]|\[2 x \[\[[A-Z_0-9]+\]\]\]|<.*?>|{.*?}|\[[0-9]+ x .*?\]|%["a-z:A-Z0-9._]+({{.*?}})?|%{{.*?}}|{{.*?}}|\[\[.*?\]\])(\s*(\*|addrspace\(.*?\)|dereferenceable\(.*?\)|byval\(.*?\)|sret|zeroext|inreg|returned|signext|nocapture|align \d+|swiftself|swifterror|readonly|noalias|inalloca|nocapture))*\s*') - - counter = 0 - if 'i32{{.*}}' in s: - counter = 1 - - at_pos = s.find('@') - if at_pos == -1: - at_pos = 0 - - annoying_pos = s.find('{{[^(]+}}') - if annoying_pos != -1: - at_pos = annoying_pos + 9 - - paren_pos = s.find('(', at_pos) - if paren_pos == -1: - return s - - res = s[:paren_pos+1] - s = s[paren_pos+1:] - - m = TYPE.match(s) - while m: - res += m.group() - s = s[m.end():] - if s.startswith(',') or s.startswith(')'): - res += f' %{counter}' - counter += 1 - - next_arg = s.find(',') - if next_arg == -1: - break - - res += s[:next_arg+1] - s = s[next_arg+1:] - m = TYPE.match(s) - - return res+s - -def process_file(contents): - PREFIX = re.compile(r'check-prefix(es)?(=|\s+)([a-zA-Z0-9,]+)') - check_prefixes = ['CHECK'] - result = '' - for line in contents.split('\n'): - if 'FileCheck' in line: - m = PREFIX.search(line) - if m: - check_prefixes.extend(m.group(3).split(',')) - - found_check = False - for prefix in check_prefixes: - if prefix in line: - found_check = True - break - - if not found_check or 'define' not in line: - result += line + '\n' - continue - - # We have a check for a function definition. Number the args. - line = fix_string(line) - result += line + '\n' - return result - -def main(): - print(f'Processing {sys.argv[1]}') - f = open(sys.argv[1]) - content = f.read() - f.close() - - content = process_file(content) - - f = open(sys.argv[1], 'w') - f.write(content) - f.close() - -if __name__ == '__main__': - main() diff --git a/llvm/utils/llvm-locstats/CMakeLists.txt b/llvm/utils/llvm-locstats/CMakeLists.txt deleted file mode 100644 index a919023e141e..000000000000 --- a/llvm/utils/llvm-locstats/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -if (LLVM_BUILD_UTILS AND LLVM_BUILD_TOOLS) - add_custom_command( - OUTPUT ${LLVM_TOOLS_BINARY_DIR}/llvm-locstats - DEPENDS ${LLVM_MAIN_SRC_DIR}/utils/llvm-locstats/llvm-locstats.py - COMMAND ${CMAKE_COMMAND} -E copy ${LLVM_MAIN_SRC_DIR}/utils/llvm-locstats/llvm-locstats.py ${LLVM_TOOLS_BINARY_DIR}/llvm-locstats - COMMENT "Copying llvm-locstats into ${LLVM_TOOLS_BINARY_DIR}" - ) - add_custom_target(llvm-locstats ALL - DEPENDS ${LLVM_TOOLS_BINARY_DIR}/llvm-locstats - ) - set_target_properties(llvm-locstats PROPERTIES FOLDER "Tools") -endif() diff --git a/llvm/utils/llvm-locstats/llvm-locstats.py b/llvm/utils/llvm-locstats/llvm-locstats.py deleted file mode 100755 index 4df525ed1a96..000000000000 --- a/llvm/utils/llvm-locstats/llvm-locstats.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/env python -# -# This is a tool that works like debug location coverage calculator. -# It parses the llvm-dwarfdump --statistics output by reporting it -# in a more human readable way. -# - -from __future__ import print_function -import argparse -import os -import sys -from json import loads -from math import ceil -from subprocess import Popen, PIPE - -def coverage_buckets(): - yield '0%' - yield '1-9%' - for start in range(10, 91, 10): - yield '{0}-{1}%'.format(start, start + 9) - yield '100%' - -def locstats_output( - variables_total, - variables_total_locstats, - variables_with_loc, - scope_bytes_covered, - scope_bytes_from_first_def, - variables_coverage_map - ): - - pc_ranges_covered = int(ceil(scope_bytes_covered * 100.0) - / scope_bytes_from_first_def) - variables_coverage_per_map = {} - for cov_bucket in coverage_buckets(): - variables_coverage_per_map[cov_bucket] = \ - int(ceil(variables_coverage_map[cov_bucket] * 100.0) \ - / variables_total_locstats) - - print (' =================================================') - print (' Debug Location Statistics ') - print (' =================================================') - print (' cov% samples percentage(~) ') - print (' -------------------------------------------------') - for cov_bucket in coverage_buckets(): - print (' {0:6} {1:8d} {2:3d}%'. \ - format(cov_bucket, variables_coverage_map[cov_bucket], \ - variables_coverage_per_map[cov_bucket])) - print (' =================================================') - print (' -the number of debug variables processed: ' \ - + str(variables_total_locstats)) - print (' -PC ranges covered: ' + str(pc_ranges_covered) + '%') - - # Only if we are processing all the variables output the total - # availability. - if variables_total and variables_with_loc: - total_availability = int(ceil(variables_with_loc * 100.0) \ - / variables_total) - print (' -------------------------------------------------') - print (' -total availability: ' + str(total_availability) + '%') - print (' =================================================') - -def parse_program_args(parser): - parser.add_argument('-only-variables', action='store_true', - default=False, - help='calculate the location statistics only for ' - 'local variables' - ) - parser.add_argument('-only-formal-parameters', action='store_true', - default=False, - help='calculate the location statistics only for ' - 'formal parameters' - ) - parser.add_argument('-ignore-debug-entry-values', action='store_true', - default=False, - help='ignore the location statistics on locations with ' - 'entry values' - ) - parser.add_argument('file_name', type=str, help='file to process') - return parser.parse_args() - - -def Main(): - parser = argparse.ArgumentParser() - results = parse_program_args(parser) - - if len(sys.argv) < 2: - print ('error: Too few arguments.') - parser.print_help() - sys.exit(1) - - if results.only_variables and results.only_formal_parameters: - print ('error: Please use just one only* option.') - parser.print_help() - sys.exit(1) - - # These will be different due to different options enabled. - variables_total = None - variables_total_locstats = None - variables_with_loc = None - variables_scope_bytes_covered = None - variables_scope_bytes_from_first_def = None - variables_scope_bytes_entry_values = None - variables_coverage_map = {} - binary = results.file_name - - # Get the directory of the LLVM tools. - llvm_dwarfdump_cmd = os.path.join(os.path.dirname(__file__), \ - "llvm-dwarfdump") - # The statistics llvm-dwarfdump option. - llvm_dwarfdump_stats_opt = "--statistics" - - subproc = Popen([llvm_dwarfdump_cmd, llvm_dwarfdump_stats_opt, binary], \ - stdin=PIPE, stdout=PIPE, stderr=PIPE, \ - universal_newlines = True) - cmd_stdout, cmd_stderr = subproc.communicate() - - # Get the JSON and parse it. - json_parsed = None - - try: - json_parsed = loads(cmd_stdout) - except: - print ('error: No valid llvm-dwarfdump statistics found.') - sys.exit(1) - - if results.only_variables: - # Read the JSON only for local variables. - variables_total_locstats = \ - json_parsed['total vars procesed by location statistics'] - variables_scope_bytes_covered = \ - json_parsed['vars scope bytes covered'] - variables_scope_bytes_from_first_def = \ - json_parsed['vars scope bytes total'] - if not results.ignore_debug_entry_values: - for cov_bucket in coverage_buckets(): - cov_category = "vars with {} of its scope covered".format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - else: - variables_scope_bytes_entry_values = \ - json_parsed['vars entry value scope bytes covered'] - variables_scope_bytes_covered = variables_scope_bytes_covered \ - - variables_scope_bytes_entry_values - for cov_bucket in coverage_buckets(): - cov_category = \ - "vars (excluding the debug entry values) " \ - "with {} of its scope covered".format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - elif results.only_formal_parameters: - # Read the JSON only for formal parameters. - variables_total_locstats = \ - json_parsed['total params procesed by location statistics'] - variables_scope_bytes_covered = \ - json_parsed['formal params scope bytes covered'] - variables_scope_bytes_from_first_def = \ - json_parsed['formal params scope bytes total'] - if not results.ignore_debug_entry_values: - for cov_bucket in coverage_buckets(): - cov_category = "params with {} of its scope covered".format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - else: - variables_scope_bytes_entry_values = \ - json_parsed['formal params entry value scope bytes covered'] - variables_scope_bytes_covered = variables_scope_bytes_covered \ - - variables_scope_bytes_entry_values - for cov_bucket in coverage_buckets(): - cov_category = \ - "params (excluding the debug entry values) " \ - "with {} of its scope covered".format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - else: - # Read the JSON for both local variables and formal parameters. - variables_total = \ - json_parsed['source variables'] - variables_with_loc = json_parsed['variables with location'] - variables_total_locstats = \ - json_parsed['total variables procesed by location statistics'] - variables_scope_bytes_covered = \ - json_parsed['scope bytes covered'] - variables_scope_bytes_from_first_def = \ - json_parsed['scope bytes total'] - if not results.ignore_debug_entry_values: - for cov_bucket in coverage_buckets(): - cov_category = "variables with {} of its scope covered". \ - format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - else: - variables_scope_bytes_entry_values = \ - json_parsed['entry value scope bytes covered'] - variables_scope_bytes_covered = variables_scope_bytes_covered \ - - variables_scope_bytes_entry_values - for cov_bucket in coverage_buckets(): - cov_category = "variables (excluding the debug entry values) " \ - "with {} of its scope covered". format(cov_bucket) - variables_coverage_map[cov_bucket] = json_parsed[cov_category] - - # Pretty print collected info. - locstats_output( - variables_total, - variables_total_locstats, - variables_with_loc, - variables_scope_bytes_covered, - variables_scope_bytes_from_first_def, - variables_coverage_map - ) - -if __name__ == '__main__': - Main() - sys.exit(0) |