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