1/*
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>
27#include <llvm/Support/Path.h>
28#include <llvm/Support/raw_ostream.h>
29
30#include <bcc/BCCContext.h>
31#include <bcc/Compiler.h>
32#include <bcc/Config/Config.h>
33#include <bcc/Renderscript/RSCompilerDriver.h>
34#include <bcc/Script.h>
35#include <bcc/Source.h>
36#include <bcc/Support/CompilerConfig.h>
37#include <bcc/Support/Initialization.h>
38#include <bcc/Support/InputFile.h>
39#include <bcc/Support/OutputFile.h>
40
41using namespace bcc;
42
43//===----------------------------------------------------------------------===//
44// General Options
45//===----------------------------------------------------------------------===//
46namespace {
47
48llvm::cl::list<std::string>
49OptInputFilenames(llvm::cl::Positional, llvm::cl::OneOrMore,
50                  llvm::cl::desc("<input bitcode files>"));
51
52llvm::cl::opt<std::string>
53OptOutputFilename("o", llvm::cl::desc("Specify the output filename"),
54                  llvm::cl::value_desc("filename"));
55
56llvm::cl::opt<std::string>
57OptRuntimePath("rt-path", llvm::cl::desc("Specify the runtime library path"),
58               llvm::cl::value_desc("path"));
59
60llvm::cl::opt<std::string>
61OptTargetTriple("mtriple",
62                llvm::cl::desc("Specify the target triple (default: "
63                               DEFAULT_TARGET_TRIPLE_STRING ")"),
64                llvm::cl::init(DEFAULT_TARGET_TRIPLE_STRING),
65                llvm::cl::value_desc("triple"));
66
67llvm::cl::alias OptTargetTripleC("C", llvm::cl::NotHidden,
68                                 llvm::cl::desc("Alias for -mtriple"),
69                                 llvm::cl::aliasopt(OptTargetTriple));
70
71//===----------------------------------------------------------------------===//
72// Compiler Options
73//===----------------------------------------------------------------------===//
74llvm::cl::opt<bool>
75OptPIC("fPIC", llvm::cl::desc("Generate fully relocatable, position independent"
76                              " code"));
77
78llvm::cl::opt<char>
79OptOptLevel("O", llvm::cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
80                                "(default: -O2)"),
81            llvm::cl::Prefix, llvm::cl::ZeroOrMore, llvm::cl::init('2'));
82
83llvm::cl::opt<bool>
84OptC("c", llvm::cl::desc("Compile and assemble, but do not link."));
85
86//===----------------------------------------------------------------------===//
87// Linker Options
88//===----------------------------------------------------------------------===//
89// FIXME: this option will be removed in the future when MCLinker is capable
90//        of generating shared library directly from given bitcode. It only
91//        takes effect when -shared is supplied.
92llvm::cl::opt<std::string>
93OptImmObjectOutput("or", llvm::cl::desc("Specify the filename for output the "
94                                        "intermediate relocatable when linking "
95                                        "the input bitcode to the shared "
96                                        "library"), llvm::cl::ValueRequired);
97
98llvm::cl::opt<bool>
99OptShared("shared", llvm::cl::desc("Create a shared library from input bitcode "
100                                   "files"));
101
102
103// Override "bcc -version" since the LLVM version information is not correct on
104// Android build.
105void BCCVersionPrinter() {
106  llvm::raw_ostream &os = llvm::outs();
107  os << "libbcc (The Android Open Source Project, http://www.android.com/):\n"
108     << "  Default target: " << DEFAULT_TARGET_TRIPLE_STRING << "\n\n"
109     << "LLVM (http://llvm.org/):\n"
110     << "  Version: " << PACKAGE_VERSION << "\n";
111  return;
112}
113
114} // end anonymous namespace
115
116RSScript *PrepareRSScript(BCCContext &pContext,
117                          const llvm::cl::list<std::string> &pBitcodeFiles) {
118  RSScript *result = nullptr;
119
120  for (unsigned i = 0; i < pBitcodeFiles.size(); i++) {
121    const std::string &input_bitcode = pBitcodeFiles[i];
122    Source *source = Source::CreateFromFile(pContext, input_bitcode);
123    if (source == nullptr) {
124      llvm::errs() << "Failed to load llvm module from file `" << input_bitcode
125                   << "'!\n";
126      return nullptr;
127    }
128
129    if (result != nullptr) {
130      if (!result->mergeSource(*source)) {
131        llvm::errs() << "Failed to merge the llvm module `" << input_bitcode
132                     << "' to compile!\n";
133        delete source;
134        return nullptr;
135      }
136    } else {
137      result = new (std::nothrow) RSScript(*source);
138      if (result == nullptr) {
139        llvm::errs() << "Out of memory when create script for file `"
140                     << input_bitcode << "'!\n";
141        delete source;
142        return nullptr;
143      }
144    }
145  }
146
147  return result;
148}
149
150static inline
151bool ConfigCompiler(RSCompilerDriver &pCompilerDriver) {
152  Compiler *compiler = pCompilerDriver.getCompiler();
153  CompilerConfig *config = nullptr;
154
155  config = new (std::nothrow) CompilerConfig(OptTargetTriple);
156  if (config == nullptr) {
157    llvm::errs() << "Out of memory when create the compiler configuration!\n";
158    return false;
159  }
160
161  // Explicitly set ARM feature vector
162  if (config->getTriple().find("arm") != std::string::npos) {
163    std::vector<std::string> fv;
164    fv.push_back("+vfp3");
165    fv.push_back("+d16");
166    fv.push_back("-neon");
167    fv.push_back("-neonfp");
168    config->setFeatureString(fv);
169  }
170
171  // Explicitly set X86 feature vector
172  if ((config->getTriple().find("i686") != std::string::npos) ||
173    (config->getTriple().find("x86_64") != std::string::npos)) {
174    std::vector<std::string> fv;
175    fv.push_back("+sse3");
176    config->setFeatureString(fv);
177  }
178
179  // Compatibility mode on x86 requires atom code generation.
180  if (config->getTriple().find("i686") != std::string::npos) {
181    config->setCPU("atom");
182  }
183
184  // Setup the config according to the value of command line option.
185  if (OptPIC) {
186    config->setRelocationModel(llvm::Reloc::PIC_);
187    // For x86_64, CodeModel needs to be small if PIC_ reloc is used.
188    // Otherwise, we end up with TEXTRELs in the shared library.
189    if (config->getTriple().find("x86_64") != std::string::npos) {
190        config->setCodeModel(llvm::CodeModel::Small);
191    }
192  }
193  switch (OptOptLevel) {
194    case '0': config->setOptimizationLevel(llvm::CodeGenOpt::None); break;
195    case '1': config->setOptimizationLevel(llvm::CodeGenOpt::Less); break;
196    case '3': config->setOptimizationLevel(llvm::CodeGenOpt::Aggressive); break;
197    case '2':
198    default: {
199      config->setOptimizationLevel(llvm::CodeGenOpt::Default);
200      break;
201    }
202  }
203
204  pCompilerDriver.setConfig(config);
205  Compiler::ErrorCode result = compiler->config(*config);
206
207  if (result != Compiler::kSuccess) {
208    llvm::errs() << "Failed to configure the compiler! (detail: "
209                 << Compiler::GetErrorString(result) << ")\n";
210    return false;
211  }
212
213  return true;
214}
215
216#define DEFAULT_OUTPUT_PATH   "/sdcard/a.out"
217static inline
218std::string DetermineOutputFilename(const std::string &pOutputPath) {
219  if (!pOutputPath.empty()) {
220    return pOutputPath;
221  }
222
223  // User doesn't specify the value to -o.
224  if (OptInputFilenames.size() > 1) {
225    llvm::errs() << "Use " DEFAULT_OUTPUT_PATH " for output file!\n";
226    return DEFAULT_OUTPUT_PATH;
227  }
228
229  // There's only one input bitcode file.
230  const std::string &input_path = OptInputFilenames[0];
231  llvm::SmallString<200> output_path(input_path);
232
233  std::error_code err = llvm::sys::fs::make_absolute(output_path);
234  if (err) {
235    llvm::errs() << "Failed to determine the absolute path of `" << input_path
236                 << "'! (detail: " << err.message() << ")\n";
237    return "";
238  }
239
240  if (OptC) {
241    // -c was specified. Replace the extension to .o.
242    llvm::sys::path::replace_extension(output_path, "o");
243  } else {
244    // Use a.out under current working directory when compile executable or
245    // shared library.
246    llvm::sys::path::remove_filename(output_path);
247    llvm::sys::path::append(output_path, "a.out");
248  }
249
250  return output_path.c_str();
251}
252
253int main(int argc, char **argv) {
254  llvm::cl::SetVersionPrinter(BCCVersionPrinter);
255  llvm::cl::ParseCommandLineOptions(argc, argv);
256  init::Initialize();
257
258  if (OptRuntimePath.empty()) {
259    fprintf(stderr, "You must set \"-rt-path </path/to/libclcore.bc>\" with "
260                    "this tool\n");
261    return EXIT_FAILURE;
262  }
263
264  BCCContext context;
265  RSCompilerDriver rscd(false);
266  Compiler compiler;
267
268  if (!ConfigCompiler(rscd)) {
269    return EXIT_FAILURE;
270  }
271
272  std::string OutputFilename = DetermineOutputFilename(OptOutputFilename);
273  if (OutputFilename.empty()) {
274    return EXIT_FAILURE;
275  }
276
277  std::unique_ptr<RSScript> s(PrepareRSScript(context, OptInputFilenames));
278  if (!rscd.buildForCompatLib(*s, OutputFilename.c_str(), nullptr, OptRuntimePath.c_str(), false)) {
279    fprintf(stderr, "Failed to compile script!");
280    return EXIT_FAILURE;
281  }
282
283  return EXIT_SUCCESS;
284}
285