Compiler.cpp revision 4e7a50685ae18a24087f6f2a51c604e71fab69e2
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 addExpandKernelPass(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 size_t exportReduceCount = me.getExportReduceCount(); 333 const char **exportVarNameList = me.getExportVarNameList(); 334 const char **exportFuncNameList = me.getExportFuncNameList(); 335 const char **exportForEachNameList = me.getExportForEachNameList(); 336 const char **exportReduceNameList = me.getExportReduceNameList(); 337 size_t i; 338 339 for (i = 0; i < exportVarCount; ++i) { 340 export_symbols.push_back(exportVarNameList[i]); 341 } 342 343 for (i = 0; i < exportFuncCount; ++i) { 344 export_symbols.push_back(exportFuncNameList[i]); 345 } 346 347 // Expanded foreach and reduce functions should not be 348 // internalized. expanded_funcs keeps the names of the expanded 349 // functions around until createInternalizePass() is finished making 350 // its own copy of the visible symbols. 351 std::vector<std::string> expanded_funcs; 352 expanded_funcs.reserve(exportForEachCount + exportReduceCount); 353 354 for (i = 0; i < exportForEachCount; ++i) { 355 expanded_funcs.push_back(std::string(exportForEachNameList[i]) + ".expand"); 356 } 357 for (i = 0; i < exportReduceCount; ++i) { 358 expanded_funcs.push_back(std::string(exportReduceNameList[i]) + ".expand"); 359 } 360 361 for (auto &symbol_name : expanded_funcs) { 362 export_symbols.push_back(symbol_name.c_str()); 363 } 364 365 pPM.add(llvm::createInternalizePass(export_symbols)); 366 367 return true; 368} 369 370void Compiler::addInvokeHelperPass(llvm::legacy::PassManager &pPM) { 371 llvm::Triple arch(getTargetMachine().getTargetTriple()); 372 if (arch.isArch64Bit()) { 373 pPM.add(createRSInvokeHelperPass()); 374 } 375} 376 377void Compiler::addExpandKernelPass(llvm::legacy::PassManager &pPM) { 378 // Expand ForEach and reduce on CPU path to reduce launch overhead. 379 bool pEnableStepOpt = true; 380 pPM.add(createRSKernelExpandPass(pEnableStepOpt)); 381} 382 383void Compiler::addGlobalInfoPass(Script &pScript, llvm::legacy::PassManager &pPM) { 384 // Add additional information about RS global variables inside the Module. 385 RSScript &script = static_cast<RSScript &>(pScript); 386 if (script.getEmbedGlobalInfo()) { 387 pPM.add(createRSGlobalInfoPass(script.getEmbedGlobalInfoSkipConstant())); 388 } 389} 390 391void Compiler::addInvariantPass(llvm::legacy::PassManager &pPM) { 392 // Mark Loads from RsExpandKernelDriverInfo as "load.invariant". 393 // Should run after ExpandForEach and before inlining. 394 pPM.add(createRSInvariantPass()); 395} 396 397enum Compiler::ErrorCode Compiler::screenGlobalFunctions(Script &pScript) { 398 llvm::Module &module = pScript.getSource().getModule(); 399 400 // Materialize the bitcode module in case this is a lazy-load module. Do not 401 // clear the materializer by calling materializeAllPermanently since the 402 // runtime library has not been merged into the module yet. 403 if (module.getMaterializer() != nullptr) { 404 std::error_code ec = module.materializeAll(); 405 if (ec) { 406 ALOGE("Failed to materialize module `%s' when screening globals! (%s)", 407 module.getModuleIdentifier().c_str(), ec.message().c_str()); 408 return kErrMaterialization; 409 } 410 } 411 412 // Add pass to check for illegal function calls. 413 llvm::legacy::PassManager pPM; 414 pPM.add(createRSScreenFunctionsPass()); 415 pPM.run(module); 416 417 return kSuccess; 418 419} 420