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