slang_rs.cpp revision 7f5704efe0c59d5599f1ac7056976225dbfab946
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 "slang_rs.h"
18
19#include <cstring>
20#include <list>
21#include <sstream>
22#include <string>
23#include <utility>
24#include <vector>
25
26#include "clang/Basic/SourceLocation.h"
27
28#include "clang/Frontend/FrontendDiagnostic.h"
29
30#include "clang/Sema/SemaDiagnostic.h"
31
32#include "llvm/Support/Path.h"
33
34#include "os_sep.h"
35#include "rs_cc_options.h"
36#include "slang_rs_backend.h"
37#include "slang_rs_context.h"
38#include "slang_rs_export_type.h"
39
40#include "slang_rs_reflection.h"
41#include "slang_rs_reflection_cpp.h"
42
43namespace slang {
44
45#define FS_SUFFIX  "fs"
46
47#define RS_HEADER_SUFFIX  "rsh"
48
49/* RS_HEADER_ENTRY(name) */
50#define ENUM_RS_HEADER()  \
51  RS_HEADER_ENTRY(rs_allocation) \
52  RS_HEADER_ENTRY(rs_atomic) \
53  RS_HEADER_ENTRY(rs_cl) \
54  RS_HEADER_ENTRY(rs_core) \
55  RS_HEADER_ENTRY(rs_core_math) \
56  RS_HEADER_ENTRY(rs_debug) \
57  RS_HEADER_ENTRY(rs_element) \
58  RS_HEADER_ENTRY(rs_graphics) \
59  RS_HEADER_ENTRY(rs_math) \
60  RS_HEADER_ENTRY(rs_mesh) \
61  RS_HEADER_ENTRY(rs_matrix) \
62  RS_HEADER_ENTRY(rs_object) \
63  RS_HEADER_ENTRY(rs_program) \
64  RS_HEADER_ENTRY(rs_quaternion) \
65  RS_HEADER_ENTRY(rs_sampler) \
66  RS_HEADER_ENTRY(rs_time) \
67  RS_HEADER_ENTRY(rs_types) \
68
69// Returns true if \p Filename ends in ".fs".
70bool SlangRS::isFilterscript(const char *Filename) {
71  const char *c = strrchr(Filename, '.');
72  if (c && !strncmp(FS_SUFFIX, c + 1, strlen(FS_SUFFIX) + 1)) {
73    return true;
74  } else {
75    return false;
76  }
77}
78
79bool SlangRS::generateJavaBitcodeAccessor(const std::string &OutputPathBase,
80                                          const std::string &PackageName,
81                                          const std::string *LicenseNote) {
82  RSSlangReflectUtils::BitCodeAccessorContext BCAccessorContext;
83
84  BCAccessorContext.rsFileName = getInputFileName().c_str();
85  BCAccessorContext.bcFileName = getOutputFileName().c_str();
86  BCAccessorContext.reflectPath = OutputPathBase.c_str();
87  BCAccessorContext.packageName = PackageName.c_str();
88  BCAccessorContext.licenseNote = LicenseNote;
89  BCAccessorContext.bcStorage = BCST_JAVA_CODE;   // Must be BCST_JAVA_CODE
90
91  return RSSlangReflectUtils::GenerateJavaBitCodeAccessor(BCAccessorContext);
92}
93
94bool SlangRS::checkODR(const char *CurInputFile) {
95  for (RSContext::ExportableList::iterator I = mRSContext->exportable_begin(),
96          E = mRSContext->exportable_end();
97       I != E;
98       I++) {
99    RSExportable *RSE = *I;
100    if (RSE->getKind() != RSExportable::EX_TYPE)
101      continue;
102
103    RSExportType *ET = static_cast<RSExportType *>(RSE);
104    if (ET->getClass() != RSExportType::ExportClassRecord)
105      continue;
106
107    RSExportRecordType *ERT = static_cast<RSExportRecordType *>(ET);
108
109    // Artificial record types (create by us not by user in the source) always
110    // conforms the ODR.
111    if (ERT->isArtificial())
112      continue;
113
114    // Key to lookup ERT in ReflectedDefinitions
115    llvm::StringRef RDKey(ERT->getName());
116    ReflectedDefinitionListTy::const_iterator RD =
117        ReflectedDefinitions.find(RDKey);
118
119    if (RD != ReflectedDefinitions.end()) {
120      const RSExportRecordType *Reflected = RD->getValue().first;
121      // There's a record (struct) with the same name reflected before. Enforce
122      // ODR checking - the Reflected must hold *exactly* the same "definition"
123      // as the one defined previously. We say two record types A and B have the
124      // same definition iff:
125      //
126      //  struct A {              struct B {
127      //    Type(a1) a1,            Type(b1) b1,
128      //    Type(a2) a2,            Type(b1) b2,
129      //    ...                     ...
130      //    Type(aN) aN             Type(b3) b3,
131      //  };                      }
132      //  Cond. #1. They have same number of fields, i.e., N = M;
133      //  Cond. #2. for (i := 1 to N)
134      //              Type(ai) = Type(bi) must hold;
135      //  Cond. #3. for (i := 1 to N)
136      //              Name(ai) = Name(bi) must hold;
137      //
138      // where,
139      //  Type(F) = the type of field F and
140      //  Name(F) = the field name.
141
142      bool PassODR = false;
143      // Cond. #1 and Cond. #2
144      if (Reflected->equals(ERT)) {
145        // Cond #3.
146        RSExportRecordType::const_field_iterator AI = Reflected->fields_begin(),
147                                                 BI = ERT->fields_begin();
148
149        for (unsigned i = 0, e = Reflected->getFields().size(); i != e; i++) {
150          if ((*AI)->getName() != (*BI)->getName())
151            break;
152          AI++;
153          BI++;
154        }
155        PassODR = (AI == (Reflected->fields_end()));
156      }
157
158      if (!PassODR) {
159        getDiagnostics().Report(mDiagErrorODR) << Reflected->getName()
160                                               << getInputFileName()
161                                               << RD->getValue().second;
162        return false;
163      }
164    } else {
165      llvm::StringMapEntry<ReflectedDefinitionTy> *ME =
166          llvm::StringMapEntry<ReflectedDefinitionTy>::Create(RDKey.begin(),
167                                                              RDKey.end());
168      ME->setValue(std::make_pair(ERT, CurInputFile));
169
170      if (!ReflectedDefinitions.insert(ME))
171        delete ME;
172
173      // Take the ownership of ERT such that it won't be freed in ~RSContext().
174      ERT->keep();
175    }
176  }
177  return true;
178}
179
180void SlangRS::initDiagnostic() {
181  clang::DiagnosticsEngine &DiagEngine = getDiagnostics();
182
183  if (DiagEngine.setDiagnosticGroupMapping("implicit-function-declaration",
184                                           clang::diag::MAP_ERROR))
185    DiagEngine.Report(clang::diag::warn_unknown_warning_option)
186      << "implicit-function-declaration";
187
188  DiagEngine.setDiagnosticMapping(
189    clang::diag::ext_typecheck_convert_discards_qualifiers,
190    clang::diag::MAP_ERROR,
191    clang::SourceLocation());
192
193  mDiagErrorInvalidOutputDepParameter =
194    DiagEngine.getCustomDiagID(
195      clang::DiagnosticsEngine::Error,
196      "invalid parameter for output dependencies files.");
197
198  mDiagErrorODR =
199    DiagEngine.getCustomDiagID(
200      clang::DiagnosticsEngine::Error,
201      "type '%0' in different translation unit (%1 v.s. %2) "
202      "has incompatible type definition");
203
204  mDiagErrorTargetAPIRange =
205    DiagEngine.getCustomDiagID(
206      clang::DiagnosticsEngine::Error,
207      "target API level '%0' is out of range ('%1' - '%2')");
208}
209
210void SlangRS::initPreprocessor() {
211  clang::Preprocessor &PP = getPreprocessor();
212
213  std::stringstream RSH;
214  RSH << PP.getPredefines();
215  RSH << "#define RS_VERSION " << mTargetAPI << "\n";
216  RSH << "#include \"rs_core." RS_HEADER_SUFFIX "\"\n";
217  PP.setPredefines(RSH.str());
218}
219
220void SlangRS::initASTContext() {
221  mRSContext = new RSContext(getPreprocessor(),
222                             getASTContext(),
223                             getTargetInfo(),
224                             &mPragmas,
225                             mTargetAPI);
226}
227
228clang::ASTConsumer
229*SlangRS::createBackend(const clang::CodeGenOptions& CodeGenOpts,
230                        llvm::raw_ostream *OS,
231                        Slang::OutputType OT) {
232    return new RSBackend(mRSContext,
233                         &getDiagnostics(),
234                         CodeGenOpts,
235                         getTargetOptions(),
236                         &mPragmas,
237                         OS,
238                         OT,
239                         getSourceManager(),
240                         mAllowRSPrefix,
241                         mIsFilterscript);
242}
243
244bool SlangRS::IsRSHeaderFile(const char *File) {
245#define RS_HEADER_ENTRY(name)  \
246  if (::strcmp(File, #name "." RS_HEADER_SUFFIX) == 0)  \
247    return true;
248ENUM_RS_HEADER()
249#undef RS_HEADER_ENTRY
250  return false;
251}
252
253bool SlangRS::IsLocInRSHeaderFile(const clang::SourceLocation &Loc,
254                                  const clang::SourceManager &SourceMgr) {
255  clang::FullSourceLoc FSL(Loc, SourceMgr);
256  clang::PresumedLoc PLoc = SourceMgr.getPresumedLoc(FSL);
257
258  const char *Filename = PLoc.getFilename();
259  if (!Filename) {
260    return false;
261  } else {
262    return IsRSHeaderFile(llvm::sys::path::filename(Filename).data());
263  }
264}
265
266SlangRS::SlangRS()
267  : Slang(), mRSContext(NULL), mAllowRSPrefix(false), mTargetAPI(0),
268    mIsFilterscript(false) {
269}
270
271bool SlangRS::compile(
272    const std::list<std::pair<const char*, const char*> > &IOFiles,
273    const std::list<std::pair<const char*, const char*> > &DepFiles,
274    const RSCCOptions &Opts) {
275  if (IOFiles.empty())
276    return true;
277
278  if (Opts.mEmitDependency && (DepFiles.size() != IOFiles.size())) {
279    getDiagnostics().Report(mDiagErrorInvalidOutputDepParameter);
280    return false;
281  }
282
283  std::string RealPackageName;
284
285  const char *InputFile, *OutputFile, *BCOutputFile, *DepOutputFile;
286  std::list<std::pair<const char*, const char*> >::const_iterator
287      IOFileIter = IOFiles.begin(), DepFileIter = DepFiles.begin();
288
289  setIncludePaths(Opts.mIncludePaths);
290  setOutputType(Opts.mOutputType);
291  if (Opts.mEmitDependency) {
292    setAdditionalDepTargets(Opts.mAdditionalDepTargets);
293  }
294
295  setDebugMetadataEmission(Opts.mDebugEmission);
296
297  setOptimizationLevel(Opts.mOptimizationLevel);
298
299  mAllowRSPrefix = Opts.mAllowRSPrefix;
300
301  mTargetAPI = Opts.mTargetAPI;
302  if (mTargetAPI < SLANG_MINIMUM_TARGET_API ||
303      mTargetAPI > SLANG_MAXIMUM_TARGET_API) {
304    getDiagnostics().Report(mDiagErrorTargetAPIRange) << mTargetAPI
305        << SLANG_MINIMUM_TARGET_API << SLANG_MAXIMUM_TARGET_API;
306    return false;
307  }
308
309  // Skip generation of warnings a second time if we are doing more than just
310  // a single pass over the input file.
311  bool SuppressAllWarnings = (Opts.mOutputType != Slang::OT_Dependency);
312
313  for (unsigned i = 0, e = IOFiles.size(); i != e; i++) {
314    InputFile = IOFileIter->first;
315    OutputFile = IOFileIter->second;
316
317    reset();
318
319    if (!setInputSource(InputFile))
320      return false;
321
322    if (!setOutput(OutputFile))
323      return false;
324
325    mIsFilterscript = isFilterscript(InputFile);
326
327    if (Slang::compile() > 0)
328      return false;
329
330    if (!Opts.mJavaReflectionPackageName.empty()) {
331      mRSContext->setReflectJavaPackageName(Opts.mJavaReflectionPackageName);
332    }
333    const std::string &RealPackageName =
334        mRSContext->getReflectJavaPackageName();
335
336    if (Opts.mOutputType != Slang::OT_Dependency) {
337
338      if (Opts.mBitcodeStorage == BCST_CPP_CODE) {
339          RSReflectionCpp R(mRSContext, Opts.mJavaReflectionPathBase,
340                            getInputFileName(), getOutputFileName());
341          if (!R.reflect()) {
342            return false;
343          }
344      } else {
345        if (!Opts.mRSPackageName.empty()) {
346          mRSContext->setRSPackageName(Opts.mRSPackageName);
347        }
348
349        RSReflectionJava R(mRSContext, &mGeneratedFileNames,
350                           Opts.mJavaReflectionPathBase, getInputFileName(),
351                           getOutputFileName(),
352                           Opts.mBitcodeStorage == BCST_JAVA_CODE);
353        if (!R.reflect()) {
354          // TODO Is this needed or will the error message have been printed
355          // already? and why not for the C++ case?
356          fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
357                          "(%s)\n",
358                  R.getLastError());
359          return false;
360        }
361
362        for (std::vector<std::string>::const_iterator
363                 I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
364             I != E;
365             I++) {
366          std::string ReflectedName = RSSlangReflectUtils::ComputePackagedPath(
367              Opts.mJavaReflectionPathBase.c_str(),
368              (RealPackageName + OS_PATH_SEPARATOR_STR + *I).c_str());
369          appendGeneratedFileName(ReflectedName + ".java");
370        }
371
372        if ((Opts.mOutputType == Slang::OT_Bitcode) &&
373            (Opts.mBitcodeStorage == BCST_JAVA_CODE) &&
374            !generateJavaBitcodeAccessor(Opts.mJavaReflectionPathBase,
375                                         RealPackageName.c_str(),
376                                         mRSContext->getLicenseNote())) {
377          return false;
378        }
379      }
380    }
381
382    if (Opts.mEmitDependency) {
383      BCOutputFile = DepFileIter->first;
384      DepOutputFile = DepFileIter->second;
385
386      setDepTargetBC(BCOutputFile);
387
388      if (!setDepOutput(DepOutputFile))
389        return false;
390
391      if (SuppressAllWarnings) {
392        getDiagnostics().setSuppressAllDiagnostics(true);
393      }
394      if (generateDepFile() > 0)
395        return false;
396      if (SuppressAllWarnings) {
397        getDiagnostics().setSuppressAllDiagnostics(false);
398      }
399
400      DepFileIter++;
401    }
402
403    if (!checkODR(InputFile))
404      return false;
405
406    IOFileIter++;
407  }
408
409  return true;
410}
411
412void SlangRS::reset() {
413  delete mRSContext;
414  mRSContext = NULL;
415  mGeneratedFileNames.clear();
416  Slang::reset();
417}
418
419SlangRS::~SlangRS() {
420  delete mRSContext;
421  for (ReflectedDefinitionListTy::iterator I = ReflectedDefinitions.begin(),
422          E = ReflectedDefinitions.end();
423       I != E;
424       I++) {
425    delete I->getValue().first;
426  }
427}
428
429}  // namespace slang
430