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