Home | History | Annotate | Download | only in slang
      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 <cstdlib>
     18 #include <list>
     19 #include <set>
     20 #include <string>
     21 #include <utility>
     22 #include <vector>
     23 
     24 #include "clang/Driver/DriverDiagnostic.h"
     25 #include "clang/Driver/Options.h"
     26 
     27 #include "clang/Basic/DiagnosticOptions.h"
     28 #include "clang/Frontend/TextDiagnosticPrinter.h"
     29 #include "clang/Frontend/Utils.h"
     30 
     31 #include "llvm/ADT/SmallVector.h"
     32 #include "llvm/ADT/IntrusiveRefCntPtr.h"
     33 #include "llvm/ADT/OwningPtr.h"
     34 
     35 #include "llvm/Option/Arg.h"
     36 #include "llvm/Option/ArgList.h"
     37 #include "llvm/Option/Option.h"
     38 #include "llvm/Option/OptTable.h"
     39 #include "llvm/Support/CommandLine.h"
     40 #include "llvm/Support/ManagedStatic.h"
     41 #include "llvm/Support/MemoryBuffer.h"
     42 #include "llvm/Support/Path.h"
     43 #include "llvm/Support/raw_ostream.h"
     44 #include "llvm/Support/system_error.h"
     45 #include "llvm/Target/TargetMachine.h"
     46 
     47 #include "slang.h"
     48 #include "slang_assert.h"
     49 #include "slang_diagnostic_buffer.h"
     50 #include "slang_rs.h"
     51 #include "slang_rs_reflect_utils.h"
     52 
     53 using clang::driver::options::DriverOption;
     54 using llvm::opt::arg_iterator;
     55 using llvm::opt::Arg;
     56 using llvm::opt::ArgList;
     57 using llvm::opt::InputArgList;
     58 using llvm::opt::Option;
     59 using llvm::opt::OptTable;
     60 
     61 // SaveStringInSet, ExpandArgsFromBuf and ExpandArgv are all copied from
     62 // $(CLANG_ROOT)/tools/driver/driver.cpp for processing argc/argv passed in
     63 // main().
     64 static inline const char *SaveStringInSet(std::set<std::string> &SavedStrings,
     65                                           llvm::StringRef S) {
     66   return SavedStrings.insert(S).first->c_str();
     67 }
     68 static void ExpandArgsFromBuf(const char *Arg,
     69                               llvm::SmallVectorImpl<const char*> &ArgVector,
     70                               std::set<std::string> &SavedStrings);
     71 static void ExpandArgv(int argc, const char **argv,
     72                        llvm::SmallVectorImpl<const char*> &ArgVector,
     73                        std::set<std::string> &SavedStrings);
     74 
     75 enum {
     76   OPT_INVALID = 0,  // This is not an option ID.
     77 #define PREFIX(NAME, VALUE)
     78 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
     79                HELPTEXT, METAVAR) OPT_##ID,
     80 #include "RSCCOptions.inc"
     81   LastOption
     82 #undef OPTION
     83 #undef PREFIX
     84 };
     85 
     86 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
     87 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
     88                HELPTEXT, METAVAR)
     89 #include "RSCCOptions.inc"
     90 #undef OPTION
     91 #undef PREFIX
     92 
     93 static const OptTable::Info RSCCInfoTable[] = {
     94 #define PREFIX(NAME, VALUE)
     95 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
     96                HELPTEXT, METAVAR)   \
     97   { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, PARAM, \
     98     FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
     99 #include "RSCCOptions.inc"
    100 #undef OPTION
    101 #undef PREFIX
    102 };
    103 
    104 class RSCCOptTable : public OptTable {
    105  public:
    106   RSCCOptTable()
    107       : OptTable(RSCCInfoTable,
    108                  sizeof(RSCCInfoTable) / sizeof(RSCCInfoTable[0])) {
    109   }
    110 };
    111 
    112 OptTable *createRSCCOptTable() {
    113   return new RSCCOptTable();
    114 }
    115 
    116 ///////////////////////////////////////////////////////////////////////////////
    117 
    118 class RSCCOptions {
    119  public:
    120   // The include search paths
    121   std::vector<std::string> mIncludePaths;
    122 
    123   // The output directory, if any.
    124   std::string mOutputDir;
    125 
    126   // The output type
    127   slang::Slang::OutputType mOutputType;
    128 
    129   unsigned mAllowRSPrefix : 1;
    130 
    131   // The name of the target triple to compile for.
    132   std::string mTriple;
    133 
    134   // The name of the target CPU to generate code for.
    135   std::string mCPU;
    136 
    137   // The list of target specific features to enable or disable -- this should
    138   // be a list of strings starting with by '+' or '-'.
    139   std::vector<std::string> mFeatures;
    140 
    141   std::string mJavaReflectionPathBase;
    142 
    143   std::string mJavaReflectionPackageName;
    144 
    145   std::string mRSPackageName;
    146 
    147   slang::BitCodeStorageType mBitcodeStorage;
    148 
    149   unsigned mOutputDep : 1;
    150 
    151   std::string mOutputDepDir;
    152 
    153   std::vector<std::string> mAdditionalDepTargets;
    154 
    155   unsigned mShowHelp : 1;  // Show the -help text.
    156   unsigned mShowVersion : 1;  // Show the -version text.
    157 
    158   unsigned int mTargetAPI;
    159 
    160   // Enable emission of debugging symbols
    161   unsigned mDebugEmission : 1;
    162 
    163   // The optimization level used in CodeGen, and encoded in emitted bitcode
    164   llvm::CodeGenOpt::Level mOptimizationLevel;
    165 
    166   RSCCOptions() {
    167     mOutputType = slang::Slang::OT_Bitcode;
    168     // Triple/CPU/Features must be hard-coded to our chosen portable ABI.
    169     mTriple = "armv7-none-linux-gnueabi";
    170     mCPU = "";
    171     slangAssert(mFeatures.empty());
    172     mFeatures.push_back("+long64");
    173     mBitcodeStorage = slang::BCST_APK_RESOURCE;
    174     mOutputDep = 0;
    175     mShowHelp = 0;
    176     mShowVersion = 0;
    177     mTargetAPI = RS_VERSION;
    178     mDebugEmission = 0;
    179     mOptimizationLevel = llvm::CodeGenOpt::Aggressive;
    180   }
    181 };
    182 
    183 // ParseArguments -
    184 static void ParseArguments(llvm::SmallVectorImpl<const char*> &ArgVector,
    185                            llvm::SmallVectorImpl<const char*> &Inputs,
    186                            RSCCOptions &Opts,
    187                            clang::DiagnosticsEngine &DiagEngine) {
    188   if (ArgVector.size() > 1) {
    189     const char **ArgBegin = ArgVector.data() + 1;
    190     const char **ArgEnd = ArgVector.data() + ArgVector.size();
    191     unsigned MissingArgIndex, MissingArgCount;
    192     llvm::OwningPtr<OptTable> OptParser(createRSCCOptTable());
    193     llvm::OwningPtr<InputArgList> Args(
    194       OptParser->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount));
    195 
    196     // Check for missing argument error.
    197     if (MissingArgCount)
    198       DiagEngine.Report(clang::diag::err_drv_missing_argument)
    199         << Args->getArgString(MissingArgIndex) << MissingArgCount;
    200 
    201     clang::DiagnosticOptions DiagOpts;
    202     DiagOpts.IgnoreWarnings = Args->hasArg(OPT_w);
    203     DiagOpts.Warnings = Args->getAllArgValues(OPT_W);
    204     clang::ProcessWarningOptions(DiagEngine, DiagOpts);
    205 
    206     // Issue errors on unknown arguments.
    207     for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
    208         ie = Args->filtered_end(); it != ie; ++it)
    209       DiagEngine.Report(clang::diag::err_drv_unknown_argument)
    210         << (*it)->getAsString(*Args);
    211 
    212     for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
    213         it != ie; ++it) {
    214       const Arg *A = *it;
    215       if (A->getOption().getKind() == Option::InputClass)
    216         Inputs.push_back(A->getValue());
    217     }
    218 
    219     Opts.mIncludePaths = Args->getAllArgValues(OPT_I);
    220 
    221     Opts.mOutputDir = Args->getLastArgValue(OPT_o);
    222 
    223     if (const Arg *A = Args->getLastArg(OPT_M_Group)) {
    224       switch (A->getOption().getID()) {
    225         case OPT_M: {
    226           Opts.mOutputDep = 1;
    227           Opts.mOutputType = slang::Slang::OT_Dependency;
    228           break;
    229         }
    230         case OPT_MD: {
    231           Opts.mOutputDep = 1;
    232           Opts.mOutputType = slang::Slang::OT_Bitcode;
    233           break;
    234         }
    235         default: {
    236           slangAssert(false && "Invalid option in M group!");
    237         }
    238       }
    239     }
    240 
    241     if (const Arg *A = Args->getLastArg(OPT_Output_Type_Group)) {
    242       switch (A->getOption().getID()) {
    243         case OPT_emit_asm: {
    244           Opts.mOutputType = slang::Slang::OT_Assembly;
    245           break;
    246         }
    247         case OPT_emit_llvm: {
    248           Opts.mOutputType = slang::Slang::OT_LLVMAssembly;
    249           break;
    250         }
    251         case OPT_emit_bc: {
    252           Opts.mOutputType = slang::Slang::OT_Bitcode;
    253           break;
    254         }
    255         case OPT_emit_nothing: {
    256           Opts.mOutputType = slang::Slang::OT_Nothing;
    257           break;
    258         }
    259         default: {
    260           slangAssert(false && "Invalid option in output type group!");
    261         }
    262       }
    263     }
    264 
    265     if (Opts.mOutputDep &&
    266         ((Opts.mOutputType != slang::Slang::OT_Bitcode) &&
    267          (Opts.mOutputType != slang::Slang::OT_Dependency)))
    268       DiagEngine.Report(clang::diag::err_drv_argument_not_allowed_with)
    269           << Args->getLastArg(OPT_M_Group)->getAsString(*Args)
    270           << Args->getLastArg(OPT_Output_Type_Group)->getAsString(*Args);
    271 
    272     Opts.mAllowRSPrefix = Args->hasArg(OPT_allow_rs_prefix);
    273 
    274     Opts.mJavaReflectionPathBase =
    275         Args->getLastArgValue(OPT_java_reflection_path_base);
    276     Opts.mJavaReflectionPackageName =
    277         Args->getLastArgValue(OPT_java_reflection_package_name);
    278 
    279     Opts.mRSPackageName = Args->getLastArgValue(OPT_rs_package_name);
    280 
    281     llvm::StringRef BitcodeStorageValue =
    282         Args->getLastArgValue(OPT_bitcode_storage);
    283     if (BitcodeStorageValue == "ar")
    284       Opts.mBitcodeStorage = slang::BCST_APK_RESOURCE;
    285     else if (BitcodeStorageValue == "jc")
    286       Opts.mBitcodeStorage = slang::BCST_JAVA_CODE;
    287     else if (!BitcodeStorageValue.empty())
    288       DiagEngine.Report(clang::diag::err_drv_invalid_value)
    289           << OptParser->getOptionName(OPT_bitcode_storage)
    290           << BitcodeStorageValue;
    291 
    292     if (Args->hasArg(OPT_reflect_cpp)) {
    293       Opts.mBitcodeStorage = slang::BCST_CPP_CODE;
    294       // mJavaReflectionPathBase isn't set for C++ reflected builds
    295       // set it to mOutputDir so we can use the path sanely from
    296       // RSReflectionBase later on
    297       Opts.mJavaReflectionPathBase = Opts.mOutputDir;
    298     }
    299 
    300     Opts.mOutputDepDir =
    301         Args->getLastArgValue(OPT_output_dep_dir, Opts.mOutputDir);
    302     Opts.mAdditionalDepTargets =
    303         Args->getAllArgValues(OPT_additional_dep_target);
    304 
    305     Opts.mShowHelp = Args->hasArg(OPT_help);
    306     Opts.mShowVersion = Args->hasArg(OPT_version);
    307     Opts.mDebugEmission = Args->hasArg(OPT_emit_g);
    308 
    309     size_t OptLevel = clang::getLastArgIntValue(*Args,
    310                                                 OPT_optimization_level,
    311                                                 3,
    312                                                 DiagEngine);
    313 
    314     Opts.mOptimizationLevel = OptLevel == 0 ? llvm::CodeGenOpt::None
    315                                             : llvm::CodeGenOpt::Aggressive;
    316 
    317     Opts.mTargetAPI = clang::getLastArgIntValue(*Args,
    318                                                 OPT_target_api,
    319                                                 RS_VERSION,
    320                                                 DiagEngine);
    321   }
    322 
    323   return;
    324 }
    325 
    326 static const char *DetermineOutputFile(const std::string &OutputDir,
    327                                        const char *InputFile,
    328                                        slang::Slang::OutputType OutputType,
    329                                        std::set<std::string> &SavedStrings) {
    330   if (OutputType == slang::Slang::OT_Nothing)
    331     return "/dev/null";
    332 
    333   std::string OutputFile(OutputDir);
    334 
    335   // Append '/' to Opts.mOutputDir if not presents
    336   if (!OutputFile.empty() &&
    337       (OutputFile[OutputFile.size() - 1]) != OS_PATH_SEPARATOR)
    338     OutputFile.append(1, OS_PATH_SEPARATOR);
    339 
    340   if (OutputType == slang::Slang::OT_Dependency) {
    341     // The build system wants the .d file name stem to be exactly the same as
    342     // the source .rs file, instead of the .bc file.
    343     OutputFile.append(slang::RSSlangReflectUtils::GetFileNameStem(InputFile));
    344   } else {
    345     OutputFile.append(
    346         slang::RSSlangReflectUtils::BCFileNameFromRSFileName(InputFile));
    347   }
    348 
    349   switch (OutputType) {
    350     case slang::Slang::OT_Dependency: {
    351       OutputFile.append(".d");
    352       break;
    353     }
    354     case slang::Slang::OT_Assembly: {
    355       OutputFile.append(".S");
    356       break;
    357     }
    358     case slang::Slang::OT_LLVMAssembly: {
    359       OutputFile.append(".ll");
    360       break;
    361     }
    362     case slang::Slang::OT_Object: {
    363       OutputFile.append(".o");
    364       break;
    365     }
    366     case slang::Slang::OT_Bitcode: {
    367       OutputFile.append(".bc");
    368       break;
    369     }
    370     case slang::Slang::OT_Nothing:
    371     default: {
    372       slangAssert(false && "Invalid output type!");
    373     }
    374   }
    375 
    376   return SaveStringInSet(SavedStrings, OutputFile);
    377 }
    378 
    379 #define str(s) #s
    380 #define wrap_str(s) str(s)
    381 static void llvm_rs_cc_VersionPrinter() {
    382   llvm::raw_ostream &OS = llvm::outs();
    383   OS << "llvm-rs-cc: Renderscript compiler\n"
    384      << "  (http://developer.android.com/guide/topics/renderscript)\n"
    385      << "  based on LLVM (http://llvm.org):\n";
    386   OS << "  Built " << __DATE__ << " (" << __TIME__ ").\n";
    387   OS << "  Target APIs: " << SLANG_MINIMUM_TARGET_API << " - "
    388      << SLANG_MAXIMUM_TARGET_API;
    389   OS << "\n  Build type: " << wrap_str(TARGET_BUILD_VARIANT);
    390 #ifndef __DISABLE_ASSERTS
    391   OS << " with assertions";
    392 #endif
    393   OS << ".\n";
    394   return;
    395 }
    396 #undef wrap_str
    397 #undef str
    398 
    399 int main(int argc, const char **argv) {
    400   std::set<std::string> SavedStrings;
    401   llvm::SmallVector<const char*, 256> ArgVector;
    402   RSCCOptions Opts;
    403   llvm::SmallVector<const char*, 16> Inputs;
    404   std::string Argv0;
    405 
    406   atexit(llvm::llvm_shutdown);
    407 
    408   ExpandArgv(argc, argv, ArgVector, SavedStrings);
    409 
    410   // Argv0
    411   Argv0 = llvm::sys::path::stem(ArgVector[0]);
    412 
    413   // Setup diagnostic engine
    414   slang::DiagnosticBuffer *DiagClient = new slang::DiagnosticBuffer();
    415 
    416   llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> DiagIDs(
    417     new clang::DiagnosticIDs());
    418 
    419   llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> DiagOpts(
    420     new clang::DiagnosticOptions());
    421   clang::DiagnosticsEngine DiagEngine(DiagIDs, &*DiagOpts, DiagClient, true);
    422 
    423   slang::Slang::GlobalInitialization();
    424 
    425   ParseArguments(ArgVector, Inputs, Opts, DiagEngine);
    426 
    427   // Exits when there's any error occurred during parsing the arguments
    428   if (DiagEngine.hasErrorOccurred()) {
    429     llvm::errs() << DiagClient->str();
    430     return 1;
    431   }
    432 
    433   if (Opts.mShowHelp) {
    434     llvm::OwningPtr<OptTable> OptTbl(createRSCCOptTable());
    435     OptTbl->PrintHelp(llvm::outs(), Argv0.c_str(),
    436                       "Renderscript source compiler");
    437     return 0;
    438   }
    439 
    440   if (Opts.mShowVersion) {
    441     llvm_rs_cc_VersionPrinter();
    442     return 0;
    443   }
    444 
    445   // No input file
    446   if (Inputs.empty()) {
    447     DiagEngine.Report(clang::diag::err_drv_no_input_files);
    448     llvm::errs() << DiagClient->str();
    449     return 1;
    450   }
    451 
    452   // Prepare input data for RS compiler.
    453   std::list<std::pair<const char*, const char*> > IOFiles;
    454   std::list<std::pair<const char*, const char*> > DepFiles;
    455 
    456   llvm::OwningPtr<slang::SlangRS> Compiler(new slang::SlangRS());
    457 
    458   Compiler->init(Opts.mTriple, Opts.mCPU, Opts.mFeatures, &DiagEngine,
    459                  DiagClient);
    460 
    461   for (int i = 0, e = Inputs.size(); i != e; i++) {
    462     const char *InputFile = Inputs[i];
    463     const char *OutputFile =
    464         DetermineOutputFile(Opts.mOutputDir, InputFile,
    465                             Opts.mOutputType, SavedStrings);
    466 
    467     if (Opts.mOutputDep) {
    468       const char *BCOutputFile, *DepOutputFile;
    469 
    470       if (Opts.mOutputType == slang::Slang::OT_Bitcode)
    471         BCOutputFile = OutputFile;
    472       else
    473         BCOutputFile = DetermineOutputFile(Opts.mOutputDepDir,
    474                                            InputFile,
    475                                            slang::Slang::OT_Bitcode,
    476                                            SavedStrings);
    477 
    478       if (Opts.mOutputType == slang::Slang::OT_Dependency)
    479         DepOutputFile = OutputFile;
    480       else
    481         DepOutputFile = DetermineOutputFile(Opts.mOutputDepDir,
    482                                             InputFile,
    483                                             slang::Slang::OT_Dependency,
    484                                             SavedStrings);
    485 
    486       DepFiles.push_back(std::make_pair(BCOutputFile, DepOutputFile));
    487     }
    488 
    489     IOFiles.push_back(std::make_pair(InputFile, OutputFile));
    490   }
    491 
    492   // Let's rock!
    493   int CompileFailed = !Compiler->compile(IOFiles,
    494                                          DepFiles,
    495                                          Opts.mIncludePaths,
    496                                          Opts.mAdditionalDepTargets,
    497                                          Opts.mOutputType,
    498                                          Opts.mBitcodeStorage,
    499                                          Opts.mAllowRSPrefix,
    500                                          Opts.mOutputDep,
    501                                          Opts.mTargetAPI,
    502                                          Opts.mDebugEmission,
    503                                          Opts.mOptimizationLevel,
    504                                          Opts.mJavaReflectionPathBase,
    505                                          Opts.mJavaReflectionPackageName,
    506                                          Opts.mRSPackageName);
    507 
    508   Compiler->reset();
    509 
    510   return CompileFailed;
    511 }
    512 
    513 ///////////////////////////////////////////////////////////////////////////////
    514 
    515 // ExpandArgsFromBuf -
    516 static void ExpandArgsFromBuf(const char *Arg,
    517                               llvm::SmallVectorImpl<const char*> &ArgVector,
    518                               std::set<std::string> &SavedStrings) {
    519   const char *FName = Arg + 1;
    520   llvm::OwningPtr<llvm::MemoryBuffer> MemBuf;
    521   if (llvm::MemoryBuffer::getFile(FName, MemBuf)) {
    522     // Unable to open the file
    523     ArgVector.push_back(SaveStringInSet(SavedStrings, Arg));
    524     return;
    525   }
    526 
    527   const char *Buf = MemBuf->getBufferStart();
    528   char InQuote = ' ';
    529   std::string CurArg;
    530 
    531   for (const char *P = Buf; ; ++P) {
    532     if (*P == '\0' || (isspace(*P) && InQuote == ' ')) {
    533       if (!CurArg.empty()) {
    534         if (CurArg[0] != '@') {
    535           ArgVector.push_back(SaveStringInSet(SavedStrings, CurArg));
    536         } else {
    537           ExpandArgsFromBuf(CurArg.c_str(), ArgVector, SavedStrings);
    538         }
    539 
    540         CurArg = "";
    541       }
    542       if (*P == '\0')
    543         break;
    544       else
    545         continue;
    546     }
    547 
    548     if (isspace(*P)) {
    549       if (InQuote != ' ')
    550         CurArg.push_back(*P);
    551       continue;
    552     }
    553 
    554     if (*P == '"' || *P == '\'') {
    555       if (InQuote == *P)
    556         InQuote = ' ';
    557       else if (InQuote == ' ')
    558         InQuote = *P;
    559       else
    560         CurArg.push_back(*P);
    561       continue;
    562     }
    563 
    564     if (*P == '\\') {
    565       ++P;
    566       if (*P != '\0')
    567         CurArg.push_back(*P);
    568       continue;
    569     }
    570     CurArg.push_back(*P);
    571   }
    572 }
    573 
    574 // ExpandArgsFromBuf -
    575 static void ExpandArgv(int argc, const char **argv,
    576                        llvm::SmallVectorImpl<const char*> &ArgVector,
    577                        std::set<std::string> &SavedStrings) {
    578   for (int i = 0; i < argc; ++i) {
    579     const char *Arg = argv[i];
    580     if (Arg[0] != '@') {
    581       ArgVector.push_back(SaveStringInSet(SavedStrings, std::string(Arg)));
    582       continue;
    583     }
    584 
    585     ExpandArgsFromBuf(Arg, ArgVector, SavedStrings);
    586   }
    587 }
    588