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
99/// Turn off crash debugging features
100///
101/// Crash is expected, so disable crash reports and symbolization to reduce
102/// output clutter and avoid potentially slow symbolization.
103static void disableEnvironmentDebugFeatures() {
104 sys::Process::PreventCoreFiles();
105
106 // TODO: Copied from not. Should have a wrapper around setenv.
107#ifdef _WIN32
108 SetEnvironmentVariableA("LLVM_DISABLE_CRASH_REPORT", "1");
109 SetEnvironmentVariableA("LLVM_DISABLE_SYMBOLIZATION", "1");
110#else
111 setenv(name: "LLVM_DISABLE_CRASH_REPORT", value: "1", /*overwrite=*/replace: 1);
112 setenv(name: "LLVM_DISABLE_SYMBOLIZATION", value: "1", /*overwrite=*/replace: 1);
113#endif
114}
115
116static std::pair<StringRef, bool> determineOutputType(bool IsMIR,
117 bool InputIsBitcode) {
118 bool OutputBitcode = ForceOutputBitcode || InputIsBitcode;
119
120 if (ReplaceInput) { // In-place
121 OutputFilename = InputFilename.c_str();
122 } else if (OutputFilename.empty()) {
123 // Default to producing bitcode if the input was bitcode, if not explicitly
124 // requested.
125
126 OutputFilename =
127 IsMIR ? "reduced.mir" : (OutputBitcode ? "reduced.bc" : "reduced.ll");
128 }
129
130 return {OutputFilename, OutputBitcode};
131}
132
133int main(int Argc, char **Argv) {
134 InitLLVM X(Argc, Argv);
135 const StringRef ToolName(Argv[0]);
136
137 InitializeAllTargets();
138 InitializeAllTargetMCs();
139 InitializeAllAsmPrinters();
140 InitializeAllAsmParsers();
141
142 LLVMContext Context;
143 cl::HideUnrelatedOptions(Categories: {&LLVMReduceOptions, &getColorCategory()});
144 cl::parseCommandLineOptions(
145 Context&: Context.getLibraryOptions(), ToolOptions: codegen::getToolOptions(),
146 Args: ArrayRef(Argv, Argc),
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 std::unique_ptr<TargetMachine> TM;
192
193 auto [OriginalProgram, InputIsBitcode] =
194 parseReducerWorkItem(ToolName, Filename: InputFilename, Ctxt&: Context, TM, IsMIR: ReduceModeMIR);
195 if (!OriginalProgram) {
196 return 1;
197 }
198
199 StringRef OutputFilename;
200 bool OutputBitcode;
201 std::tie(args&: OutputFilename, args&: OutputBitcode) =
202 determineOutputType(IsMIR: ReduceModeMIR, InputIsBitcode);
203
204 // Initialize test environment
205 TestRunner Tester(TestFilename, TestArguments, std::move(OriginalProgram),
206 std::move(TM), ToolName, OutputFilename, InputIsBitcode,
207 OutputBitcode);
208
209 // This parses and writes out the testcase into a temporary file copy for the
210 // test, rather than evaluating the source IR directly. This is for the
211 // convenience of lit tests; the stripped out comments may have broken the
212 // interestingness checks.
213 if (!Tester.getProgram().isReduced(Test: Tester)) {
214 errs() << "\nInput isn't interesting! Verify interesting-ness test\n";
215 return 2;
216 }
217
218 // Try to reduce code
219 runDeltaPasses(Tester, MaxPassIterations);
220
221 // Print reduced file to STDOUT
222 if (OutputFilename == "-")
223 Tester.getProgram().print(ROS&: outs(), p: nullptr);
224 else
225 Tester.writeOutput(Message: "Done reducing! Reduced testcase: ");
226
227 return 0;
228}
229