1 //===- llvm-reduce.cpp - The LLVM Delta Reduction utility -----------------===//
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 // This program tries to reduce an IR test case for a given interesting-ness
10 // test. It runs multiple delta debugging passes in order to minimize the input
11 // file. It's worth noting that this is a part of the bugpoint redesign
12 // proposal, and thus a *temporary* tool that will eventually be integrated
13 // into the bugpoint tool itself.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "DeltaManager.h"
18 #include "ReducerWorkItem.h"
19 #include "TestRunner.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/CodeGen/CommandFlags.h"
22 #include "llvm/IR/LLVMContext.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/MC/TargetRegistry.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Host.h"
28 #include "llvm/Support/InitLLVM.h"
29 #include "llvm/Support/SourceMgr.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "llvm/Support/WithColor.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <system_error>
34 #include <vector>
35 
36 using namespace llvm;
37 
38 cl::OptionCategory LLVMReduceOptions("llvm-reduce options");
39 
40 static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden,
41                           cl::cat(LLVMReduceOptions));
42 static cl::opt<bool> Version("v", cl::desc("Alias for -version"), cl::Hidden,
43                              cl::cat(LLVMReduceOptions));
44 
45 static cl::opt<bool>
46     PrintDeltaPasses("print-delta-passes",
47                      cl::desc("Print list of delta passes, passable to "
48                               "--delta-passes as a comma separated list"),
49                      cl::cat(LLVMReduceOptions));
50 
51 static cl::opt<std::string> InputFilename(cl::Positional, cl::Required,
52                                           cl::desc("<input llvm ll/bc file>"),
53                                           cl::cat(LLVMReduceOptions));
54 
55 static cl::opt<std::string>
56     TestFilename("test", cl::Required,
57                  cl::desc("Name of the interesting-ness test to be run"),
58                  cl::cat(LLVMReduceOptions));
59 
60 static cl::list<std::string>
61     TestArguments("test-arg", cl::ZeroOrMore,
62                   cl::desc("Arguments passed onto the interesting-ness test"),
63                   cl::cat(LLVMReduceOptions));
64 
65 static cl::opt<std::string> OutputFilename(
66     "output", cl::desc("Specify the output file. default: reduced.ll|mir"));
67 static cl::alias OutputFileAlias("o", cl::desc("Alias for -output"),
68                                  cl::aliasopt(OutputFilename),
69                                  cl::cat(LLVMReduceOptions));
70 
71 static cl::opt<bool>
72     ReplaceInput("in-place",
73                  cl::desc("WARNING: This option will replace your input file "
74                           "with the reduced version!"),
75                  cl::cat(LLVMReduceOptions));
76 
77 enum class InputLanguages { None, IR, MIR };
78 
79 static cl::opt<InputLanguages>
80     InputLanguage("x", cl::ValueOptional,
81                   cl::desc("Input language ('ir' or 'mir')"),
82                   cl::init(InputLanguages::None),
83                   cl::values(clEnumValN(InputLanguages::IR, "ir", ""),
84                              clEnumValN(InputLanguages::MIR, "mir", "")),
85                   cl::cat(LLVMReduceOptions));
86 
87 static cl::opt<int>
88     MaxPassIterations("max-pass-iterations",
89                       cl::desc("Maximum number of times to run the full set "
90                                "of delta passes (default=1)"),
91                       cl::init(1), cl::cat(LLVMReduceOptions));
92 
93 static codegen::RegisterCodeGenFlags CGF;
94 
95 static void initializeTargetInfo() {
96   InitializeAllTargets();
97   InitializeAllTargetMCs();
98   InitializeAllAsmPrinters();
99   InitializeAllAsmParsers();
100 }
101 
102 void writeOutput(ReducerWorkItem &M, StringRef Message) {
103   if (ReplaceInput) // In-place
104     OutputFilename = InputFilename.c_str();
105   else if (OutputFilename.empty() || OutputFilename == "-")
106     OutputFilename = M.isMIR() ? "reduced.mir" : "reduced.ll";
107   std::error_code EC;
108   raw_fd_ostream Out(OutputFilename, EC);
109   if (EC) {
110     errs() << "Error opening output file: " << EC.message() << "!\n";
111     exit(1);
112   }
113   M.print(Out, /*AnnotationWriter=*/nullptr);
114   errs() << Message << OutputFilename << "\n";
115 }
116 
117 int main(int Argc, char **Argv) {
118   InitLLVM X(Argc, Argv);
119 
120   cl::HideUnrelatedOptions({&LLVMReduceOptions, &getColorCategory()});
121   cl::ParseCommandLineOptions(Argc, Argv, "LLVM automatic testcase reducer.\n");
122 
123   bool ReduceModeMIR = false;
124   if (InputLanguage != InputLanguages::None) {
125     if (InputLanguage == InputLanguages::MIR)
126       ReduceModeMIR = true;
127   } else if (StringRef(InputFilename).endswith(".mir")) {
128     ReduceModeMIR = true;
129   }
130 
131   if (PrintDeltaPasses) {
132     printDeltaPasses(errs());
133     return 0;
134   }
135 
136   if (ReduceModeMIR)
137     initializeTargetInfo();
138 
139   LLVMContext Context;
140   std::unique_ptr<TargetMachine> TM;
141 
142   std::unique_ptr<ReducerWorkItem> OriginalProgram =
143       parseReducerWorkItem(Argv[0], InputFilename, Context, TM, ReduceModeMIR);
144   if (!OriginalProgram) {
145     return 1;
146   }
147 
148   // Initialize test environment
149   TestRunner Tester(TestFilename, TestArguments, std::move(OriginalProgram),
150                     std::move(TM));
151 
152   // Try to reduce code
153   runDeltaPasses(Tester, MaxPassIterations);
154 
155   // Print reduced file to STDOUT
156   if (OutputFilename == "-")
157     Tester.getProgram().print(outs(), nullptr);
158   else
159     writeOutput(Tester.getProgram(), "\nDone reducing! Reduced testcase: ");
160 
161   return 0;
162 }
163