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