xref: /freebsd/contrib/llvm-project/llvm/tools/bugpoint/bugpoint.cpp (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 //===- bugpoint.cpp - The LLVM Bugpoint 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 is an automated compiler debugger tool.  It is used to narrow
10 // down miscompilations and crash problems to a specific pass in the compiler,
11 // and the specific Module or Function input that is causing the problem.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "BugDriver.h"
16 #include "ToolRunner.h"
17 #include "llvm/Config/llvm-config.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/LegacyPassNameParser.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/LinkAllIR.h"
23 #include "llvm/LinkAllPasses.h"
24 #include "llvm/Passes/PassPlugin.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/InitLLVM.h"
27 #include "llvm/Support/PluginLoader.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/Process.h"
30 #include "llvm/Support/TargetSelect.h"
31 #include "llvm/Support/Valgrind.h"
32 #include "llvm/Transforms/IPO/AlwaysInliner.h"
33 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
34 
35 // Enable this macro to debug bugpoint itself.
36 //#define DEBUG_BUGPOINT 1
37 
38 using namespace llvm;
39 
40 static cl::opt<bool>
41     FindBugs("find-bugs", cl::desc("Run many different optimization sequences "
42                                    "on program to find bugs"),
43              cl::init(false));
44 
45 static cl::list<std::string>
46     InputFilenames(cl::Positional, cl::OneOrMore,
47                    cl::desc("<input llvm ll/bc files>"));
48 
49 static cl::opt<unsigned> TimeoutValue(
50     "timeout", cl::init(300), cl::value_desc("seconds"),
51     cl::desc("Number of seconds program is allowed to run before it "
52              "is killed (default is 300s), 0 disables timeout"));
53 
54 static cl::opt<int> MemoryLimit(
55     "mlimit", cl::init(-1), cl::value_desc("MBytes"),
56     cl::desc("Maximum amount of memory to use. 0 disables check. Defaults to "
57              "400MB (800MB under valgrind, 0 with sanitizers)."));
58 
59 static cl::opt<bool>
60     UseValgrind("enable-valgrind",
61                 cl::desc("Run optimizations through valgrind"));
62 
63 // The AnalysesList is automatically populated with registered Passes by the
64 // PassNameParser.
65 //
66 static cl::list<const PassInfo *, bool, PassNameParser>
67     PassList(cl::desc("Passes available:"));
68 
69 static cl::opt<bool>
70     OptLevelO1("O1", cl::desc("Optimization level 1. Identical to 'opt -O1'"));
71 
72 static cl::opt<bool>
73     OptLevelO2("O2", cl::desc("Optimization level 2. Identical to 'opt -O2'"));
74 
75 static cl::opt<bool> OptLevelOs(
76     "Os",
77     cl::desc(
78         "Like -O2 with extra optimizations for size. Similar to clang -Os"));
79 
80 static cl::opt<bool>
81 OptLevelOz("Oz",
82            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
83 
84 static cl::opt<bool>
85     OptLevelO3("O3", cl::desc("Optimization level 3. Identical to 'opt -O3'"));
86 
87 static cl::opt<std::string>
88     OverrideTriple("mtriple", cl::desc("Override target triple for module"));
89 
90 /// BugpointIsInterrupted - Set to true when the user presses ctrl-c.
91 bool llvm::BugpointIsInterrupted = false;
92 
93 #ifndef DEBUG_BUGPOINT
94 static void BugpointInterruptFunction() { BugpointIsInterrupted = true; }
95 #endif
96 
97 // Hack to capture a pass list.
98 namespace {
99 class AddToDriver : public legacy::FunctionPassManager {
100   BugDriver &D;
101 
102 public:
103   AddToDriver(BugDriver &_D) : FunctionPassManager(nullptr), D(_D) {}
104 
105   void add(Pass *P) override {
106     const void *ID = P->getPassID();
107     const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
108     D.addPass(std::string(PI->getPassArgument()));
109   }
110 };
111 }
112 
113 // This routine adds optimization passes based on selected optimization level,
114 // OptLevel.
115 //
116 // OptLevel - Optimization Level
117 static void AddOptimizationPasses(legacy::FunctionPassManager &FPM,
118                                   unsigned OptLevel,
119                                   unsigned SizeLevel) {
120   PassManagerBuilder Builder;
121   Builder.OptLevel = OptLevel;
122   Builder.SizeLevel = SizeLevel;
123 
124   if (OptLevel > 1)
125     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
126   else
127     Builder.Inliner = createAlwaysInlinerLegacyPass();
128 
129   Builder.populateFunctionPassManager(FPM);
130   Builder.populateModulePassManager(FPM);
131 }
132 
133 #define HANDLE_EXTENSION(Ext)                                                  \
134   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
135 #include "llvm/Support/Extension.def"
136 
137 int main(int argc, char **argv) {
138 #ifndef DEBUG_BUGPOINT
139   InitLLVM X(argc, argv);
140 #endif
141 
142   // Initialize passes
143   PassRegistry &Registry = *PassRegistry::getPassRegistry();
144   initializeCore(Registry);
145   initializeScalarOpts(Registry);
146   initializeVectorization(Registry);
147   initializeIPO(Registry);
148   initializeAnalysis(Registry);
149   initializeTransformUtils(Registry);
150   initializeInstCombine(Registry);
151   initializeTarget(Registry);
152 
153   if (std::getenv("bar") == (char*) -1) {
154     InitializeAllTargets();
155     InitializeAllTargetMCs();
156     InitializeAllAsmPrinters();
157     InitializeAllAsmParsers();
158   }
159 
160   cl::ParseCommandLineOptions(argc, argv,
161                               "LLVM automatic testcase reducer. See\nhttp://"
162                               "llvm.org/cmds/bugpoint.html"
163                               " for more information.\n");
164 #ifndef DEBUG_BUGPOINT
165   sys::SetInterruptFunction(BugpointInterruptFunction);
166 #endif
167 
168   LLVMContext Context;
169   // If we have an override, set it and then track the triple we want Modules
170   // to use.
171   if (!OverrideTriple.empty()) {
172     TargetTriple.setTriple(Triple::normalize(OverrideTriple));
173     outs() << "Override triple set to '" << TargetTriple.getTriple() << "'\n";
174   }
175 
176   if (MemoryLimit < 0) {
177     // Set the default MemoryLimit.  Be sure to update the flag's description if
178     // you change this.
179     if (sys::RunningOnValgrind() || UseValgrind)
180       MemoryLimit = 800;
181     else
182       MemoryLimit = 400;
183 #if (LLVM_ADDRESS_SANITIZER_BUILD || LLVM_MEMORY_SANITIZER_BUILD ||            \
184      LLVM_THREAD_SANITIZER_BUILD)
185     // Starting from kernel 4.9 memory allocated with mmap is counted against
186     // RLIMIT_DATA. Sanitizers need to allocate tens of terabytes for shadow.
187     MemoryLimit = 0;
188 #endif
189   }
190 
191   BugDriver D(argv[0], FindBugs, TimeoutValue, MemoryLimit, UseValgrind,
192               Context);
193   if (D.addSources(InputFilenames))
194     return 1;
195 
196   AddToDriver PM(D);
197 
198   if (OptLevelO1)
199     AddOptimizationPasses(PM, 1, 0);
200   else if (OptLevelO2)
201     AddOptimizationPasses(PM, 2, 0);
202   else if (OptLevelO3)
203     AddOptimizationPasses(PM, 3, 0);
204   else if (OptLevelOs)
205     AddOptimizationPasses(PM, 2, 1);
206   else if (OptLevelOz)
207     AddOptimizationPasses(PM, 2, 2);
208 
209   for (const PassInfo *PI : PassList)
210     D.addPass(std::string(PI->getPassArgument()));
211 
212 // Bugpoint has the ability of generating a plethora of core files, so to
213 // avoid filling up the disk, we prevent it
214 #ifndef DEBUG_BUGPOINT
215   sys::Process::PreventCoreFiles();
216 #endif
217 
218 // Needed to pull in symbols from statically linked extensions, including static
219 // registration. It is unused otherwise because bugpoint has no support for
220 // NewPM.
221 #define HANDLE_EXTENSION(Ext)                                                  \
222   (void)get##Ext##PluginInfo();
223 #include "llvm/Support/Extension.def"
224 
225   if (Error E = D.run()) {
226     errs() << toString(std::move(E));
227     return 1;
228   }
229   return 0;
230 }
231