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.
12//
13//===----------------------------------------------------------------------===//
14
15#include "DeltaManager.h"
16#include "ReducerWorkItem.h"
17#include "TestRunner.h"
18#include "deltas/Delta.h"
19#include "llvm/Bitcode/BitcodeReader.h"
20#include "llvm/CodeGen/CommandFlags.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Support/InitLLVM.h"
23#include "llvm/Support/Process.h"
24#include "llvm/Support/TargetSelect.h"
25#include "llvm/Support/WithColor.h"
26#include "llvm/Support/raw_ostream.h"
27
28#ifdef _WIN32
29#include <windows.h>
30#endif
31
32using namespace llvm;
33
34cl::OptionCategory LLVMReduceOptions("llvm-reduce options");
35
36static cl::opt<bool> Version("v", cl::desc("Alias for -version"), cl::Hidden,
37 cl::cat(LLVMReduceOptions));
38
39static cl::opt<bool> PreserveDebugEnvironment(
40 "preserve-debug-environment",
41 cl::desc("Don't disable features used for crash "
42 "debugging (crash reports, llvm-symbolizer and core dumps)"),
43 cl::cat(LLVMReduceOptions));
44
45static 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
51static cl::opt<std::string> InputFilename(cl::Positional,
52 cl::desc("<input llvm ll/bc file>"),
53 cl::cat(LLVMReduceOptions));
54
55static cl::opt<std::string>
56 TestFilename("test",
57 cl::desc("Name of the interesting-ness test to be run"),
58 cl::cat(LLVMReduceOptions));
59
60static cl::list<std::string>
61 TestArguments("test-arg",
62 cl::desc("Arguments passed onto the interesting-ness test"),
63 cl::cat(LLVMReduceOptions));
64
65static cl::opt<std::string> OutputFilename(
66 "output",
67 cl::desc("Specify the output file. default: reduced.ll|.bc|.mir"));
68static cl::alias OutputFileAlias("o", cl::desc("Alias for -output"),
69 cl::aliasopt(OutputFilename),
70 cl::cat(LLVMReduceOptions));
71
72static cl::opt<bool>
73 ReplaceInput("in-place",
74 cl::desc("WARNING: This option will replace your input file "
75 "with the reduced version!"),
76 cl::cat(LLVMReduceOptions));
77
78enum class InputLanguages { None, IR, MIR };
79
80static cl::opt<InputLanguages>
81 InputLanguage("x", cl::ValueOptional,
82 cl::desc("Input language ('ir' or 'mir')"),
83 cl::init(Val: InputLanguages::None),
84 cl::values(clEnumValN(InputLanguages::IR, "ir", ""),
85 clEnumValN(InputLanguages::MIR, "mir", "")),
86 cl::cat(LLVMReduceOptions));
87
88static cl::opt<bool> ForceOutputBitcode(
89 "output-bitcode",
90 cl::desc("Emit final result as bitcode instead of text IR"), cl::Hidden,
91 cl::cat(LLVMReduceOptions));
92
93static cl::opt<int>
94 MaxPassIterations("max-pass-iterations",
95 cl::desc("Maximum number of times to run the full set "
96 "of delta passes (default=5)"),
97 cl::init(Val: 5), cl::cat(LLVMReduceOptions));
98
99static codegen::RegisterCodeGenFlags CGF;
100
101/// Turn off crash debugging features
102///
103/// Crash is expected, so disable crash reports and symbolization to reduce
104/// output clutter and avoid potentially slow symbolization.
105static void disableEnvironmentDebugFeatures() {
106 sys::Process::PreventCoreFiles();
107
108 // TODO: Copied from not. Should have a wrapper around setenv.
109#ifdef _WIN32
110 SetEnvironmentVariableA("LLVM_DISABLE_CRASH_REPORT", "1");
111 SetEnvironmentVariableA("LLVM_DISABLE_SYMBOLIZATION", "1");
112#else
113 setenv(name: "LLVM_DISABLE_CRASH_REPORT", value: "1", /*overwrite=*/replace: 1);
114 setenv(name: "LLVM_DISABLE_SYMBOLIZATION", value: "1", /*overwrite=*/replace: 1);
115#endif
116}
117
118static std::pair<StringRef, bool> determineOutputType(bool IsMIR,
119 bool InputIsBitcode) {
120 bool OutputBitcode = ForceOutputBitcode || InputIsBitcode;
121
122 if (ReplaceInput) { // In-place
123 OutputFilename = InputFilename.c_str();
124 } else if (OutputFilename.empty()) {
125 // Default to producing bitcode if the input was bitcode, if not explicitly
126 // requested.
127
128 OutputFilename =
129 IsMIR ? "reduced.mir" : (OutputBitcode ? "reduced.bc" : "reduced.ll");
130 }
131
132 return {OutputFilename, OutputBitcode};
133}
134
135int main(int Argc, char **Argv) {
136 InitLLVM X(Argc, Argv);
137 const StringRef ToolName(Argv[0]);
138
139 InitializeAllTargets();
140 InitializeAllTargetMCs();
141 InitializeAllAsmPrinters();
142 InitializeAllAsmParsers();
143
144 cl::HideUnrelatedOptions(Categories: {&LLVMReduceOptions, &getColorCategory()});
145 cl::ParseCommandLineOptions(
146 argc: Argc, argv: Argv,
147 Overview: "LLVM automatic testcase reducer.\n"
148 "See https://llvm.org/docs/CommandGuide/llvm-reduce.html for more "
149 "information.\n");
150
151 if (Argc == 1) {
152 cl::PrintHelpMessage();
153 return 0;
154 }
155
156 if (PrintDeltaPasses) {
157 printDeltaPasses(OS&: outs());
158 return 0;
159 }
160
161 bool ReduceModeMIR = false;
162 if (InputLanguage != InputLanguages::None) {
163 if (InputLanguage == InputLanguages::MIR)
164 ReduceModeMIR = true;
165 } else if (StringRef(InputFilename).ends_with(Suffix: ".mir")) {
166 ReduceModeMIR = true;
167 }
168
169 if (InputFilename.empty()) {
170 WithColor::error(OS&: errs(), Prefix: ToolName)
171 << "reduction testcase positional argument must be specified\n";
172 return 1;
173 }
174
175 if (TestFilename.empty()) {
176 WithColor::error(OS&: errs(), Prefix: ToolName) << "--test option must be specified\n";
177 return 1;
178 }
179
180 // Chunks are handed to worker threads by round tripping the program through
181 // bitcode, which cannot represent MachineFunctions.
182 if (ReduceModeMIR && getNumChunkProcessingJobs() > 1) {
183 WithColor::error(OS&: errs(), Prefix: ToolName)
184 << "-j is not supported for MIR reduction\n";
185 return 1;
186 }
187
188 if (!PreserveDebugEnvironment)
189 disableEnvironmentDebugFeatures();
190
191 LLVMContext Context;
192 std::unique_ptr<TargetMachine> TM;
193
194 auto [OriginalProgram, InputIsBitcode] =
195 parseReducerWorkItem(ToolName, Filename: InputFilename, Ctxt&: Context, TM, IsMIR: ReduceModeMIR);
196 if (!OriginalProgram) {
197 return 1;
198 }
199
200 StringRef OutputFilename;
201 bool OutputBitcode;
202 std::tie(args&: OutputFilename, args&: OutputBitcode) =
203 determineOutputType(IsMIR: ReduceModeMIR, InputIsBitcode);
204
205 // Initialize test environment
206 TestRunner Tester(TestFilename, TestArguments, std::move(OriginalProgram),
207 std::move(TM), ToolName, OutputFilename, InputIsBitcode,
208 OutputBitcode);
209
210 // This parses and writes out the testcase into a temporary file copy for the
211 // test, rather than evaluating the source IR directly. This is for the
212 // convenience of lit tests; the stripped out comments may have broken the
213 // interestingness checks.
214 if (!Tester.getProgram().isReduced(Test: Tester)) {
215 errs() << "\nInput isn't interesting! Verify interesting-ness test\n";
216 return 2;
217 }
218
219 // Try to reduce code
220 runDeltaPasses(Tester, MaxPassIterations);
221
222 // Print reduced file to STDOUT
223 if (OutputFilename == "-")
224 Tester.getProgram().print(ROS&: outs(), p: nullptr);
225 else
226 Tester.writeOutput(Message: "Done reducing! Reduced testcase: ");
227
228 return 0;
229}
230