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