Compiler.cpp revision 10f2a8f1d60724c306d01cdd0682e38122637502
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 transformPasses;
152
153  // Empty MCContext.
154  llvm::MCContext *mc_context = nullptr;
155
156  transformPasses.add(
157      createTargetTransformInfoWrapperPass(mTarget->getTargetIRAnalysis()));
158
159  // Add some initial custom passes.
160  addInvokeHelperPass(transformPasses);
161  addExpandKernelPass(transformPasses);
162  addDebugInfoPass(pScript, transformPasses);
163  addInvariantPass(transformPasses);
164  if (!addInternalizeSymbolsPass(pScript, transformPasses))
165    return kErrCustomPasses;
166  addGlobalInfoPass(pScript, transformPasses);
167
168  if (mTarget->getOptLevel() == llvm::CodeGenOpt::None) {
169    transformPasses.add(llvm::createGlobalOptimizerPass());
170    transformPasses.add(llvm::createConstantMergePass());
171
172  } else {
173    // FIXME: Figure out which passes should be executed.
174    llvm::PassManagerBuilder Builder;
175    Builder.Inliner = llvm::createFunctionInliningPass();
176    Builder.populateLTOPassManager(transformPasses);
177
178    /* FIXME: Reenable autovectorization after rebase.
179       bug 19324423
180    // Add vectorization passes after LTO passes are in
181    // additional flag: -unroll-runtime
182    transformPasses.add(llvm::createLoopUnrollPass(-1, 16, 0, 1));
183    // Need to pass appropriate flags here: -scalarize-load-store
184    transformPasses.add(llvm::createScalarizerPass());
185    transformPasses.add(llvm::createCFGSimplificationPass());
186    transformPasses.add(llvm::createScopedNoAliasAAPass());
187    transformPasses.add(llvm::createScalarEvolutionAliasAnalysisPass());
188    // additional flags: -slp-vectorize-hor -slp-vectorize-hor-store (unnecessary?)
189    transformPasses.add(llvm::createSLPVectorizerPass());
190    transformPasses.add(llvm::createDeadCodeEliminationPass());
191    transformPasses.add(llvm::createInstructionCombiningPass());
192    */
193  }
194
195  // These passes have to come after LTO, since we don't want to examine
196  // functions that are never actually called.
197  if (llvm::Triple(getTargetMachine().getTargetTriple()).getArch() == llvm::Triple::x86_64)
198    transformPasses.add(createRSX86_64CallConvPass());  // Add pass to correct calling convention for X86-64.
199  transformPasses.add(createRSIsThreadablePass());      // Add pass to mark script as threadable.
200
201  // RSEmbedInfoPass needs to come after we have scanned for non-threadable
202  // functions.
203  // Script passed to RSCompiler must be a RSScript.
204  RSScript &script = static_cast<RSScript &>(pScript);
205  if (script.getEmbedInfo())
206    transformPasses.add(createRSEmbedInfoPass());
207
208  // Execute the passes.
209  transformPasses.run(pScript.getSource().getModule());
210
211  // Run backend separately to avoid interference between debug metadata
212  // generation and backend initialization.
213  llvm::legacy::PassManager codeGenPasses;
214
215  // Add passes to the pass manager to emit machine code through MC layer.
216  if (mTarget->addPassesToEmitMC(codeGenPasses, mc_context, pResult,
217                                 /* DisableVerify */false)) {
218    return kPrepareCodeGenPass;
219  }
220
221  // Execute the passes.
222  codeGenPasses.run(pScript.getSource().getModule());
223
224  return kSuccess;
225}
226
227enum Compiler::ErrorCode Compiler::compile(Script &pScript,
228                                           llvm::raw_pwrite_stream &pResult,
229                                           llvm::raw_ostream *IRStream) {
230  llvm::Module &module = pScript.getSource().getModule();
231  enum ErrorCode err;
232
233  if (mTarget == nullptr) {
234    return kErrNoTargetMachine;
235  }
236
237  const std::string &triple = module.getTargetTriple();
238  const llvm::DataLayout *dl = getTargetMachine().getDataLayout();
239  unsigned int pointerSize = dl->getPointerSizeInBits();
240  if (triple == "armv7-none-linux-gnueabi") {
241    if (pointerSize != 32) {
242      return kErrInvalidSource;
243    }
244  } else if (triple == "aarch64-none-linux-gnueabi") {
245    if (pointerSize != 64) {
246      return kErrInvalidSource;
247    }
248  } else {
249    return kErrInvalidSource;
250  }
251
252  // Sanitize module's target information.
253  module.setTargetTriple(getTargetMachine().getTargetTriple());
254  module.setDataLayout(*getTargetMachine().getDataLayout());
255
256  // Materialize the bitcode module.
257  if (module.getMaterializer() != nullptr) {
258    // A module with non-null materializer means that it is a lazy-load module.
259    // Materialize it now via invoking MaterializeAllPermanently(). This
260    // function returns false when the materialization is successful.
261    std::error_code ec = module.materializeAllPermanently();
262    if (ec) {
263      ALOGE("Failed to materialize the module `%s'! (%s)",
264            module.getModuleIdentifier().c_str(), ec.message().c_str());
265      return kErrMaterialization;
266    }
267  }
268
269  if ((err = runPasses(pScript, pResult)) != kSuccess) {
270    return err;
271  }
272
273  if (IRStream) {
274    *IRStream << module;
275  }
276
277  return kSuccess;
278}
279
280enum Compiler::ErrorCode Compiler::compile(Script &pScript,
281                                           OutputFile &pResult,
282                                           llvm::raw_ostream *IRStream) {
283  // Check the state of the specified output file.
284  if (pResult.hasError()) {
285    return kErrInvalidOutputFileState;
286  }
287
288  // Open the output file decorated in llvm::raw_ostream.
289  llvm::raw_pwrite_stream *out = pResult.dup();
290  if (out == nullptr) {
291    return kErrPrepareOutput;
292  }
293
294  // Delegate the request.
295  enum Compiler::ErrorCode err = compile(pScript, *out, IRStream);
296
297  // Close the output before return.
298  delete out;
299
300  return err;
301}
302
303bool Compiler::addInternalizeSymbolsPass(Script &pScript, llvm::legacy::PassManager &pPM) {
304  // Add a pass to internalize the symbols that don't need to have global
305  // visibility.
306  RSScript &script = static_cast<RSScript &>(pScript);
307  llvm::Module &module = script.getSource().getModule();
308  bcinfo::MetadataExtractor me(&module);
309  if (!me.extract()) {
310    bccAssert(false && "Could not extract metadata for module!");
311    return false;
312  }
313
314  // The vector contains the symbols that should not be internalized.
315  std::vector<const char *> export_symbols;
316
317  const char *sf[] = {
318    kRoot,               // Graphics drawing function or compute kernel.
319    kInit,               // Initialization routine called implicitly on startup.
320    kRsDtor,             // Static global destructor for a script instance.
321    kRsInfo,             // Variable containing string of RS metadata info.
322    kRsGlobalEntries,    // Optional number of global variables.
323    kRsGlobalNames,      // Optional global variable name info.
324    kRsGlobalAddresses,  // Optional global variable address info.
325    kRsGlobalSizes,      // Optional global variable size info.
326    kRsGlobalProperties, // Optional global variable properties.
327    nullptr              // Must be nullptr-terminated.
328  };
329  const char **special_functions = sf;
330  // Special RS functions should always be global symbols.
331  while (*special_functions != nullptr) {
332    export_symbols.push_back(*special_functions);
333    special_functions++;
334  }
335
336  // Visibility of symbols appeared in rs_export_var and rs_export_func should
337  // also be preserved.
338  size_t exportVarCount = me.getExportVarCount();
339  size_t exportFuncCount = me.getExportFuncCount();
340  size_t exportForEachCount = me.getExportForEachSignatureCount();
341  size_t exportReduceCount = me.getExportReduceCount();
342  size_t exportReduceNewCount = me.getExportReduceNewCount();
343  const char **exportVarNameList = me.getExportVarNameList();
344  const char **exportFuncNameList = me.getExportFuncNameList();
345  const char **exportForEachNameList = me.getExportForEachNameList();
346  const char **exportReduceNameList = me.getExportReduceNameList();
347  const bcinfo::MetadataExtractor::ReduceNew *exportReduceNewList = me.getExportReduceNewList();
348  size_t i;
349
350  for (i = 0; i < exportVarCount; ++i) {
351    export_symbols.push_back(exportVarNameList[i]);
352  }
353
354  for (i = 0; i < exportFuncCount; ++i) {
355    export_symbols.push_back(exportFuncNameList[i]);
356  }
357
358  // Expanded foreach and reduce functions should not be
359  // internalized. expanded_funcs keeps the names of the expanded
360  // functions around until createInternalizePass() is finished making
361  // its own copy of the visible symbols.
362  std::vector<std::string> expanded_funcs;
363  expanded_funcs.reserve(exportForEachCount + exportReduceCount + exportReduceNewCount);
364
365  for (i = 0; i < exportForEachCount; ++i) {
366    expanded_funcs.push_back(std::string(exportForEachNameList[i]) + ".expand");
367  }
368  for (i = 0; i < exportReduceCount; ++i) {
369    expanded_funcs.push_back(std::string(exportReduceNameList[i]) + ".expand");
370  }
371  for (i = 0; i < exportReduceNewCount; ++i) {
372    expanded_funcs.push_back(std::string(exportReduceNewList[i].mAccumulatorName) + ".expand");
373  }
374
375  for (auto &symbol_name : expanded_funcs) {
376    export_symbols.push_back(symbol_name.c_str());
377  }
378
379  // http://b/26165616 - WAR for this bug defines the __truncxfhf2 function in
380  // frameworks/rs/driver/runtime.  Don't internalize this function for x86, so
381  // that a script can find and link against it.
382  llvm::Triple triple(getTargetMachine().getTargetTriple());
383  if (triple.getArch() == llvm::Triple::x86) {
384    export_symbols.push_back("__truncxfhf2");
385  }
386
387  pPM.add(llvm::createInternalizePass(export_symbols));
388
389  return true;
390}
391
392void Compiler::addInvokeHelperPass(llvm::legacy::PassManager &pPM) {
393  llvm::Triple arch(getTargetMachine().getTargetTriple());
394  if (arch.isArch64Bit()) {
395    pPM.add(createRSInvokeHelperPass());
396  }
397}
398
399void Compiler::addDebugInfoPass(Script &pScript, llvm::legacy::PassManager &pPM) {
400  if (pScript.getSource().getDebugInfoEnabled())
401    pPM.add(createRSAddDebugInfoPass());
402}
403
404void Compiler::addExpandKernelPass(llvm::legacy::PassManager &pPM) {
405  // Expand ForEach and reduce on CPU path to reduce launch overhead.
406  bool pEnableStepOpt = true;
407  pPM.add(createRSKernelExpandPass(pEnableStepOpt));
408}
409
410void Compiler::addGlobalInfoPass(Script &pScript, llvm::legacy::PassManager &pPM) {
411  // Add additional information about RS global variables inside the Module.
412  RSScript &script = static_cast<RSScript &>(pScript);
413  if (script.getEmbedGlobalInfo()) {
414    pPM.add(createRSGlobalInfoPass(script.getEmbedGlobalInfoSkipConstant()));
415  }
416}
417
418void Compiler::addInvariantPass(llvm::legacy::PassManager &pPM) {
419  // Mark Loads from RsExpandKernelDriverInfo as "load.invariant".
420  // Should run after ExpandForEach and before inlining.
421  pPM.add(createRSInvariantPass());
422}
423
424enum Compiler::ErrorCode Compiler::screenGlobalFunctions(Script &pScript) {
425  llvm::Module &module = pScript.getSource().getModule();
426
427  // Materialize the bitcode module in case this is a lazy-load module.  Do not
428  // clear the materializer by calling materializeAllPermanently since the
429  // runtime library has not been merged into the module yet.
430  if (module.getMaterializer() != nullptr) {
431    std::error_code ec = module.materializeAll();
432    if (ec) {
433      ALOGE("Failed to materialize module `%s' when screening globals! (%s)",
434            module.getModuleIdentifier().c_str(), ec.message().c_str());
435      return kErrMaterialization;
436    }
437  }
438
439  // Add pass to check for illegal function calls.
440  llvm::legacy::PassManager pPM;
441  pPM.add(createRSScreenFunctionsPass());
442  pPM.run(module);
443
444  return kSuccess;
445
446}
447