Compiler.cpp revision 579361346abc6696c805e3904a18178ebce4e4a3
1/*
2 * Copyright 2010-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 "bcc/Compiler.h"
18
19#include <llvm/Analysis/Passes.h>
20#include <llvm/CodeGen/RegAllocRegistry.h>
21#include <llvm/IR/Module.h>
22#include <llvm/PassManager.h>
23#include <llvm/Support/TargetRegistry.h>
24#include <llvm/Support/raw_ostream.h>
25#include <llvm/IR/DataLayout.h>
26#include <llvm/Target/TargetSubtargetInfo.h>
27#include <llvm/Target/TargetMachine.h>
28#include <llvm/Transforms/IPO.h>
29#include <llvm/Transforms/IPO/PassManagerBuilder.h>
30#include <llvm/Transforms/Scalar.h>
31
32#include "bcc/Assert.h"
33#include "bcc/Renderscript/RSExecutable.h"
34#include "bcc/Renderscript/RSScript.h"
35#include "bcc/Renderscript/RSTransforms.h"
36#include "bcc/Script.h"
37#include "bcc/Source.h"
38#include "bcc/Support/CompilerConfig.h"
39#include "bcc/Support/Log.h"
40#include "bcc/Support/OutputFile.h"
41#include "bcinfo/MetadataExtractor.h"
42
43#include <string>
44
45using namespace bcc;
46
47const char *Compiler::GetErrorString(enum ErrorCode pErrCode) {
48  switch (pErrCode) {
49  case kSuccess:
50    return "Successfully compiled.";
51  case kInvalidConfigNoTarget:
52    return "Invalid compiler config supplied (getTarget() returns nullptr.) "
53           "(missing call to CompilerConfig::initialize()?)";
54  case kErrCreateTargetMachine:
55    return "Failed to create llvm::TargetMachine.";
56  case kErrSwitchTargetMachine:
57    return  "Failed to switch llvm::TargetMachine.";
58  case kErrNoTargetMachine:
59    return "Failed to compile the script since there's no available "
60           "TargetMachine. (missing call to Compiler::config()?)";
61  case kErrDataLayoutNoMemory:
62    return "Out of memory when create DataLayout during compilation.";
63  case kErrMaterialization:
64    return "Failed to materialize the module.";
65  case kErrInvalidOutputFileState:
66    return "Supplied output file was invalid (in the error state.)";
67  case kErrPrepareOutput:
68    return "Failed to prepare file for output.";
69  case kPrepareCodeGenPass:
70    return "Failed to construct pass list for code-generation.";
71  case kErrCustomPasses:
72    return "Error occurred while adding custom passes.";
73  case kErrInvalidSource:
74    return "Error loading input bitcode";
75  }
76
77  // This assert should never be reached as the compiler verifies that the
78  // above switch coveres all enum values.
79  assert(false && "Unknown error code encountered");
80  return  "";
81}
82
83//===----------------------------------------------------------------------===//
84// Instance Methods
85//===----------------------------------------------------------------------===//
86Compiler::Compiler() : mTarget(nullptr), mEnableOpt(true) {
87  return;
88}
89
90Compiler::Compiler(const CompilerConfig &pConfig) : mTarget(nullptr),
91                                                    mEnableOpt(true) {
92  const std::string &triple = pConfig.getTriple();
93
94  enum ErrorCode err = config(pConfig);
95  if (err != kSuccess) {
96    ALOGE("%s (%s, features: %s)", GetErrorString(err),
97          triple.c_str(), pConfig.getFeatureString().c_str());
98    return;
99  }
100
101  return;
102}
103
104enum Compiler::ErrorCode Compiler::config(const CompilerConfig &pConfig) {
105  if (pConfig.getTarget() == nullptr) {
106    return kInvalidConfigNoTarget;
107  }
108
109  llvm::TargetMachine *new_target =
110      (pConfig.getTarget())->createTargetMachine(pConfig.getTriple(),
111                                                 pConfig.getCPU(),
112                                                 pConfig.getFeatureString(),
113                                                 pConfig.getTargetOptions(),
114                                                 pConfig.getRelocationModel(),
115                                                 pConfig.getCodeModel(),
116                                                 pConfig.getOptimizationLevel());
117
118  if (new_target == nullptr) {
119    return ((mTarget != nullptr) ? kErrSwitchTargetMachine :
120                                   kErrCreateTargetMachine);
121  }
122
123  // Replace the old TargetMachine.
124  delete mTarget;
125  mTarget = new_target;
126
127  // Adjust register allocation policy according to the optimization level.
128  //  createFastRegisterAllocator: fast but bad quality
129  //  createLinearScanRegisterAllocator: not so fast but good quality
130  if ((pConfig.getOptimizationLevel() == llvm::CodeGenOpt::None)) {
131    llvm::RegisterRegAlloc::setDefault(llvm::createFastRegisterAllocator);
132  } else {
133    llvm::RegisterRegAlloc::setDefault(llvm::createGreedyRegisterAllocator);
134  }
135
136  return kSuccess;
137}
138
139Compiler::~Compiler() {
140  delete mTarget;
141}
142
143enum Compiler::ErrorCode Compiler::runPasses(Script &pScript,
144                                             llvm::raw_ostream &pResult) {
145  // Pass manager for link-time optimization
146  llvm::PassManager passes;
147
148  // Empty MCContext.
149  llvm::MCContext *mc_context = nullptr;
150
151  mTarget->addAnalysisPasses(passes);
152
153  // Prepare DataLayout target data from Module
154  llvm::DataLayoutPass *data_layout_pass =
155    new (std::nothrow) llvm::DataLayoutPass();
156
157  if (data_layout_pass == nullptr) {
158    return kErrDataLayoutNoMemory;
159  }
160
161  // Add DataLayout to the pass manager.
162  passes.add(data_layout_pass);
163
164  // Add our custom passes.
165  if (!addCustomPasses(pScript, passes)) {
166    return kErrCustomPasses;
167  }
168
169  if (mTarget->getOptLevel() == llvm::CodeGenOpt::None) {
170    passes.add(llvm::createGlobalOptimizerPass());
171    passes.add(llvm::createConstantMergePass());
172
173  } else {
174    // FIXME: Figure out which passes should be executed.
175    llvm::PassManagerBuilder Builder;
176    Builder.Inliner = llvm::createFunctionInliningPass();
177    Builder.populateLTOPassManager(passes, mTarget);
178  }
179
180  // Add passes to the pass manager to emit machine code through MC layer.
181  if (mTarget->addPassesToEmitMC(passes, mc_context, pResult,
182                                 /* DisableVerify */false)) {
183    return kPrepareCodeGenPass;
184  }
185
186  // Execute the passes.
187  passes.run(pScript.getSource().getModule());
188
189  return kSuccess;
190}
191
192enum Compiler::ErrorCode Compiler::compile(Script &pScript,
193                                           llvm::raw_ostream &pResult,
194                                           llvm::raw_ostream *IRStream) {
195  llvm::Module &module = pScript.getSource().getModule();
196  enum ErrorCode err;
197
198  if (mTarget == nullptr) {
199    return kErrNoTargetMachine;
200  }
201
202  const std::string &triple = module.getTargetTriple();
203  const llvm::DataLayout *dl = getTargetMachine().getSubtargetImpl()->getDataLayout();
204  unsigned int pointerSize = dl->getPointerSizeInBits();
205  if (triple == "armv7-none-linux-gnueabi") {
206    if (pointerSize != 32) {
207      return kErrInvalidSource;
208    }
209  } else if (triple == "aarch64-none-linux-gnueabi") {
210    if (pointerSize != 64) {
211      return kErrInvalidSource;
212    }
213  } else {
214    return kErrInvalidSource;
215  }
216
217  // Materialize the bitcode module.
218  if (module.getMaterializer() != nullptr) {
219    // A module with non-null materializer means that it is a lazy-load module.
220    // Materialize it now via invoking MaterializeAllPermanently(). This
221    // function returns false when the materialization is successful.
222    std::error_code ec = module.materializeAllPermanently();
223    if (ec) {
224      ALOGE("Failed to materialize the module `%s'! (%s)",
225            module.getModuleIdentifier().c_str(), ec.message().c_str());
226      return kErrMaterialization;
227    }
228  }
229
230  if ((err = runPasses(pScript, pResult)) != kSuccess) {
231    return err;
232  }
233
234  if (IRStream) {
235    *IRStream << module;
236  }
237
238  return kSuccess;
239}
240
241enum Compiler::ErrorCode Compiler::compile(Script &pScript,
242                                           OutputFile &pResult,
243                                           llvm::raw_ostream *IRStream) {
244  // Check the state of the specified output file.
245  if (pResult.hasError()) {
246    return kErrInvalidOutputFileState;
247  }
248
249  // Open the output file decorated in llvm::raw_ostream.
250  llvm::raw_ostream *out = pResult.dup();
251  if (out == nullptr) {
252    return kErrPrepareOutput;
253  }
254
255  // Delegate the request.
256  enum Compiler::ErrorCode err = compile(pScript, *out, IRStream);
257
258  // Close the output before return.
259  delete out;
260
261  return err;
262}
263
264bool Compiler::addInternalizeSymbolsPass(Script &pScript, llvm::PassManager &pPM) {
265  // Add a pass to internalize the symbols that don't need to have global
266  // visibility.
267  RSScript &script = static_cast<RSScript &>(pScript);
268  llvm::Module &module = script.getSource().getModule();
269  bcinfo::MetadataExtractor me(&module);
270  if (!me.extract()) {
271    bccAssert(false && "Could not extract metadata for module!");
272    return false;
273  }
274
275  // The vector contains the symbols that should not be internalized.
276  std::vector<const char *> export_symbols;
277
278  // Special RS functions should always be global symbols.
279  const char **special_functions = RSExecutable::SpecialFunctionNames;
280  while (*special_functions != nullptr) {
281    export_symbols.push_back(*special_functions);
282    special_functions++;
283  }
284
285  // Visibility of symbols appeared in rs_export_var and rs_export_func should
286  // also be preserved.
287  size_t exportVarCount = me.getExportVarCount();
288  size_t exportFuncCount = me.getExportFuncCount();
289  size_t exportForEachCount = me.getExportForEachSignatureCount();
290  const char **exportVarNameList = me.getExportVarNameList();
291  const char **exportFuncNameList = me.getExportFuncNameList();
292  const char **exportForEachNameList = me.getExportForEachNameList();
293  size_t i;
294
295  for (i = 0; i < exportVarCount; ++i) {
296    export_symbols.push_back(exportVarNameList[i]);
297  }
298
299  for (i = 0; i < exportFuncCount; ++i) {
300    export_symbols.push_back(exportFuncNameList[i]);
301  }
302
303  // Expanded foreach functions should not be internalized, too.
304  // expanded_foreach_funcs keeps the .expand version of the kernel names
305  // around until createInternalizePass() is finished making its own
306  // copy of the visible symbols.
307  std::vector<std::string> expanded_foreach_funcs;
308  for (i = 0; i < exportForEachCount; ++i) {
309    expanded_foreach_funcs.push_back(
310        std::string(exportForEachNameList[i]) + ".expand");
311  }
312
313  for (i = 0; i < exportForEachCount; i++) {
314      export_symbols.push_back(expanded_foreach_funcs[i].c_str());
315  }
316
317  pPM.add(llvm::createInternalizePass(export_symbols));
318
319  return true;
320}
321
322bool Compiler::addInvokeHelperPass(llvm::PassManager &pPM) {
323  llvm::Triple arch(getTargetMachine().getTargetTriple());
324  if (arch.isArch64Bit()) {
325    pPM.add(createRSInvokeHelperPass());
326  }
327  return true;
328}
329
330bool Compiler::addExpandForEachPass(Script &pScript, llvm::PassManager &pPM) {
331  // Script passed to RSCompiler must be a RSScript.
332  RSScript &script = static_cast<RSScript &>(pScript);
333
334  // Expand ForEach on CPU path to reduce launch overhead.
335  bool pEnableStepOpt = true;
336  pPM.add(createRSForEachExpandPass(pEnableStepOpt));
337  if (script.getEmbedInfo())
338    pPM.add(createRSEmbedInfoPass());
339
340  return true;
341}
342
343bool Compiler::addCustomPasses(Script &pScript, llvm::PassManager &pPM) {
344  if (!addInvokeHelperPass(pPM))
345    return false;
346
347  if (!addExpandForEachPass(pScript, pPM))
348    return false;
349
350  if (!addInternalizeSymbolsPass(pScript, pPM))
351    return false;
352
353  return true;
354}
355