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