blob: e0c6f58f42886c2aca708ee38af70e9c788cb36e [file] [log] [blame]
Shih-wei Liaod577d112012-04-25 04:06:29 -07001/*
2 * Copyright 2012, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <string>
18#include <vector>
19
20#include <stdlib.h>
21
22#include <llvm/ADT/STLExtras.h>
23#include <llvm/ADT/SmallString.h>
24#include <llvm/Config/config.h>
25#include <llvm/Support/CommandLine.h>
26#include <llvm/Support/FileSystem.h>
Stephen Hines88f8c522013-06-13 00:35:03 -070027#include <llvm/Support/PathV1.h>
Shih-wei Liaod577d112012-04-25 04:06:29 -070028#include <llvm/Support/Path.h>
29#include <llvm/Support/raw_ostream.h>
30#include <llvm/Support/system_error.h>
31
32#include <bcc/BCCContext.h>
33#include <bcc/Compiler.h>
34#include <bcc/Config/BuildInfo.h>
35#include <bcc/Config/Config.h>
Shih-wei Liao09ca9542013-01-25 17:00:08 -080036#include <bcc/ExecutionEngine/CompilerRTSymbolResolver.h>
Shih-wei Liaod577d112012-04-25 04:06:29 -070037#include <bcc/ExecutionEngine/ObjectLoader.h>
38#include <bcc/ExecutionEngine/SymbolResolverProxy.h>
39#include <bcc/ExecutionEngine/SymbolResolvers.h>
40#include <bcc/Script.h>
41#include <bcc/Source.h>
42#include <bcc/Support/CompilerConfig.h>
43#include <bcc/Support/Initialization.h>
44#include <bcc/Support/InputFile.h>
45#include <bcc/Support/OutputFile.h>
46#include <bcc/Support/TargetCompilerConfigs.h>
47
48using namespace bcc;
49
50//===----------------------------------------------------------------------===//
51// General Options
52//===----------------------------------------------------------------------===//
53namespace {
54
55llvm::cl::list<std::string>
56OptInputFilenames(llvm::cl::Positional, llvm::cl::OneOrMore,
57 llvm::cl::desc("<input bitcode files>"));
58
59llvm::cl::opt<std::string>
60OptOutputFilename("o", llvm::cl::desc("Specify the output filename"),
61 llvm::cl::value_desc("filename"));
62
63#ifdef TARGET_BUILD
64const std::string OptTargetTriple(DEFAULT_TARGET_TRIPLE_STRING);
65#else
66llvm::cl::opt<std::string>
67OptTargetTriple("mtriple",
68 llvm::cl::desc("Specify the target triple (default: "
69 DEFAULT_TARGET_TRIPLE_STRING ")"),
70 llvm::cl::init(DEFAULT_TARGET_TRIPLE_STRING),
71 llvm::cl::value_desc("triple"));
72
73llvm::cl::alias OptTargetTripleC("C", llvm::cl::NotHidden,
74 llvm::cl::desc("Alias for -mtriple"),
75 llvm::cl::aliasopt(OptTargetTriple));
76#endif
77
78//===----------------------------------------------------------------------===//
79// Compiler Options
80//===----------------------------------------------------------------------===//
81llvm::cl::opt<bool>
82OptPIC("fPIC", llvm::cl::desc("Generate fully relocatable, position independent"
83 " code"));
84
85llvm::cl::opt<char>
86OptOptLevel("O", llvm::cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
87 "(default: -O2)"),
88 llvm::cl::Prefix, llvm::cl::ZeroOrMore, llvm::cl::init('2'));
89
90llvm::cl::opt<bool>
91OptC("c", llvm::cl::desc("Compile and assemble, but do not link."));
92
93//===----------------------------------------------------------------------===//
94// Linker Options
95//===----------------------------------------------------------------------===//
96// FIXME: this option will be removed in the future when MCLinker is capable
97// of generating shared library directly from given bitcode. It only
98// takes effect when -shared is supplied.
99llvm::cl::opt<std::string>
100OptImmObjectOutput("or", llvm::cl::desc("Specify the filename for output the "
101 "intermediate relocatable when linking "
102 "the input bitcode to the shared "
103 "library"), llvm::cl::ValueRequired);
104
105llvm::cl::opt<bool>
106OptShared("shared", llvm::cl::desc("Create a shared library from input bitcode "
107 "files"));
108
109
110//===----------------------------------------------------------------------===//
111// Loader Options
112//===----------------------------------------------------------------------===//
113llvm::cl::opt<bool>
114OptRunEntry("R", llvm::cl::desc("Run the entry method after successfully load "
115 "and compile."));
116
117llvm::cl::opt<std::string>
118OptEntryFunction("entry-function", llvm::cl::desc("Specify the entry function "
119 "for -R (default: main)"),
120 llvm::cl::value_desc("function"), llvm::cl::init("main"));
121
122llvm::cl::opt<bool>
123OptEnableGDB("enable-gdb", llvm::cl::desc("Enable GDB JIT debugging when "
124 "runs the entry method"));
125
126llvm::cl::list<std::string>
127OptRuntimeLibs("load", llvm::cl::desc("Specify the shared libraries for "
128 "execution (e.g., -load=c will search "
129 "and load libc.so for execution)"),
130 llvm::cl::ZeroOrMore, llvm::cl::value_desc("namespec"));
131
132// Override "bcc -version" since the LLVM version information is not correct on
133// Android build.
134void BCCVersionPrinter() {
135 llvm::raw_ostream &os = llvm::outs();
136 os << "libbcc (The Android Open Source Project, http://www.android.com/):\n"
137 << " Build time: " << BuildInfo::GetBuildTime() << "\n"
138 << " Build revision: " << BuildInfo::GetBuildRev() << "\n"
139 << " Build source blob: " << BuildInfo::GetBuildSourceBlob() << "\n"
140 << " Default target: " << DEFAULT_TARGET_TRIPLE_STRING << "\n";
141
142 os << "\n";
143
144 os << "LLVM (http://llvm.org/):\n"
145 << " Version: " << PACKAGE_VERSION << "\n";
146 return;
147}
148
149} // end anonymous namespace
150
151static inline
152Script *PrepareScript(BCCContext &pContext,
153 const llvm::cl::list<std::string> &pBitcodeFiles) {
154 Script *result = NULL;
155
156 for (unsigned i = 0; i < pBitcodeFiles.size(); i++) {
157 const std::string &input_bitcode = pBitcodeFiles[i];
158 Source *source = Source::CreateFromFile(pContext, input_bitcode);
159 if (source == NULL) {
160 llvm::errs() << "Failed to load llvm module from file `" << input_bitcode
161 << "'!\n";
162 return NULL;
163 }
164
165 if (result != NULL) {
166 if (!result->mergeSource(*source, /* pPreserveSource */false)) {
167 llvm::errs() << "Failed to merge the llvm module `" << input_bitcode
168 << "' to compile!\n";
169 delete source;
170 return NULL;
171 }
172 } else {
173 result = new (std::nothrow) Script(*source);
174 if (result == NULL) {
175 llvm::errs() << "Out of memory when create script for file `"
176 << input_bitcode << "'!\n";
177 delete source;
178 return NULL;
179 }
180 }
181 }
182
183 return result;
184}
185
186static inline
187bool ConfigCompiler(Compiler &pCompiler) {
188 CompilerConfig *config = NULL;
189
190#ifdef TARGET_BUILD
191 config = new (std::nothrow) DefaultCompilerConfig();
192#else
193 config = new (std::nothrow) CompilerConfig(OptTargetTriple);
194#endif
195 if (config == NULL) {
196 llvm::errs() << "Out of memory when create the compiler configuration!\n";
197 return false;
198 }
199
200 // Setup the config according to the valud of command line option.
201 if (OptPIC) {
202 config->setRelocationModel(llvm::Reloc::PIC_);
203 }
204 switch (OptOptLevel) {
205 case '0': config->setOptimizationLevel(llvm::CodeGenOpt::None); break;
206 case '1': config->setOptimizationLevel(llvm::CodeGenOpt::Less); break;
207 case '3': config->setOptimizationLevel(llvm::CodeGenOpt::Aggressive); break;
208 case '2':
209 default: {
210 config->setOptimizationLevel(llvm::CodeGenOpt::Default);
211 break;
212 }
213 }
214
215 Compiler::ErrorCode result = pCompiler.config(*config);
216
217 delete config;
218
219 if (result != Compiler::kSuccess) {
220 llvm::errs() << "Failed to configure the compiler! (detail: "
221 << Compiler::GetErrorString(result) << ")\n";
222 return false;
223 }
224
225 return true;
226}
227
228#define DEFAULT_OUTPUT_PATH "/sdcard/a.out"
229static inline
230std::string DetermineOutputFilename(const std::string &pOutputPath) {
231 if (!pOutputPath.empty()) {
232 return pOutputPath;
233 }
234
235 // User doesn't specify the value to -o.
236 if (OptInputFilenames.size() > 1) {
237 llvm::errs() << "Use " DEFAULT_OUTPUT_PATH " for output file!\n";
238 return DEFAULT_OUTPUT_PATH;
239 }
240
241 // There's only one input bitcode file.
242 const std::string &input_path = OptInputFilenames[0];
243 llvm::SmallString<200> output_path(input_path);
244
245 llvm::error_code err = llvm::sys::fs::make_absolute(output_path);
246 if (err != llvm::errc::success) {
247 llvm::errs() << "Failed to determine the absolute path of `" << input_path
248 << "'! (detail: " << err.message() << ")\n";
249 return "";
250 }
251
252 if (OptC) {
253 // -c was specified. Replace the extension to .o.
254 llvm::sys::path::replace_extension(output_path, "o");
255 } else {
256 // Use a.out under current working directory when compile executable or
257 // shared library.
258 llvm::sys::path::remove_filename(output_path);
259 llvm::sys::path::append(output_path, "a.out");
260 }
261
262 return output_path.c_str();
263}
264
265static inline
266bool CompileScript(Compiler &pCompiler, Script &pScript,
267 const std::string &pOutputPath) {
268 // Open the output file.
Shih-wei Liaoc02eae62012-07-22 16:23:32 -0700269 OutputFile output_file(pOutputPath, FileBase::kTruncate);
Shih-wei Liaod577d112012-04-25 04:06:29 -0700270
271 if (output_file.hasError()) {
272 llvm::errs() << "Failed to open the output file `" << pOutputPath
273 << "'! (detail: " << output_file.getErrorMessage() << ")\n";
274 return false;
275 }
276
277 // Run the compiler.
278 Compiler::ErrorCode result = pCompiler.compile(pScript, output_file);
279 if (result != Compiler::kSuccess) {
280 llvm::errs() << "Fatal error during compilation (detail: "
281 << Compiler::GetErrorString(result) << ".)\n";
282 return false;
283 }
284
285 return true;
286}
287
Shih-wei Liaod577d112012-04-25 04:06:29 -0700288int main(int argc, char **argv) {
289 llvm::cl::SetVersionPrinter(BCCVersionPrinter);
290 llvm::cl::ParseCommandLineOptions(argc, argv);
291 init::Initialize();
292
293 BCCContext context;
294 Compiler compiler;
295
296 Script *script = PrepareScript(context, OptInputFilenames);
297 if (script == NULL) {
298 return EXIT_FAILURE;
299 }
300
301 if (!ConfigCompiler(compiler)) {
302 return EXIT_FAILURE;
303 }
304
305 std::string OutputFilename = DetermineOutputFilename(OptOutputFilename);
306 if (OutputFilename.empty()) {
307 return EXIT_FAILURE;
308 }
309
310 if (!CompileScript(compiler, *script, OutputFilename)) {
311 return EXIT_FAILURE;
312 }
313
Shih-wei Liaod577d112012-04-25 04:06:29 -0700314 return EXIT_SUCCESS;
315}