slang_rs_context.cpp revision 50cab07b24f9d85899e697cac88a05cb8347fe74
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_context.h"
18
19#include <string>
20
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/Mangle.h"
25#include "clang/AST/Type.h"
26
27#include "clang/Basic/Linkage.h"
28#include "clang/Basic/TargetInfo.h"
29
30#include "llvm/IR/LLVMContext.h"
31#include "llvm/IR/DataLayout.h"
32
33#include "slang.h"
34#include "slang_assert.h"
35#include "slang_rs_export_foreach.h"
36#include "slang_rs_export_func.h"
37#include "slang_rs_export_type.h"
38#include "slang_rs_export_var.h"
39#include "slang_rs_exportable.h"
40#include "slang_rs_pragma_handler.h"
41#include "slang_rs_reflection.h"
42
43namespace slang {
44
45RSContext::RSContext(clang::Preprocessor &PP,
46                     clang::ASTContext &Ctx,
47                     const clang::TargetInfo &Target,
48                     PragmaList *Pragmas,
49                     unsigned int TargetAPI,
50                     std::vector<std::string> *GeneratedFileNames)
51    : mPP(PP),
52      mCtx(Ctx),
53      mPragmas(Pragmas),
54      mTargetAPI(TargetAPI),
55      mGeneratedFileNames(GeneratedFileNames),
56      mDataLayout(NULL),
57      mLLVMContext(llvm::getGlobalContext()),
58      mLicenseNote(NULL),
59      mRSPackageName("android.renderscript"),
60      version(0),
61      mIsCompatLib(false),
62      mMangleCtx(Ctx.createMangleContext()) {
63  slangAssert(mGeneratedFileNames && "Must supply GeneratedFileNames");
64
65  // For #pragma rs export_type
66  PP.AddPragmaHandler(
67      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
68
69  // For #pragma rs java_package_name
70  PP.AddPragmaHandler(
71      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
72
73  // For #pragma rs set_reflect_license
74  PP.AddPragmaHandler(
75      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
76
77  // For #pragma version
78  PP.AddPragmaHandler(RSPragmaHandler::CreatePragmaVersionHandler(this));
79
80  // Prepare target data
81  mDataLayout = new llvm::DataLayout(Target.getTargetDescription());
82
83  return;
84}
85
86bool RSContext::processExportVar(const clang::VarDecl *VD) {
87  slangAssert(!VD->getName().empty() && "Variable name should not be empty");
88
89  // TODO(zonr): some check on variable
90
91  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
92  if (!ET)
93    return false;
94
95  RSExportVar *EV = new RSExportVar(this, VD, ET);
96  if (EV == NULL)
97    return false;
98  else
99    mExportVars.push_back(EV);
100
101  return true;
102}
103
104bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
105  slangAssert(!FD->getName().empty() && "Function name should not be empty");
106
107  if (!FD->isThisDeclarationADefinition()) {
108    return true;
109  }
110
111  if (FD->getStorageClass() != clang::SC_None) {
112    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
113                    "static function '%s'\n", FD->getName().str().c_str());
114    return false;
115  }
116
117  if (RSExportForEach::isSpecialRSFunc(mTargetAPI, FD)) {
118    // Do not reflect specialized functions like init, dtor, or graphics root.
119    return RSExportForEach::validateSpecialFuncDecl(mTargetAPI, this, FD);
120  } else if (RSExportForEach::isRSForEachFunc(mTargetAPI, this, FD)) {
121    RSExportForEach *EFE = RSExportForEach::Create(this, FD);
122    if (EFE == NULL)
123      return false;
124    else
125      mExportForEach.push_back(EFE);
126    return true;
127  }
128
129  RSExportFunc *EF = RSExportFunc::Create(this, FD);
130  if (EF == NULL)
131    return false;
132  else
133    mExportFuncs.push_back(EF);
134
135  return true;
136}
137
138
139bool RSContext::processExportType(const llvm::StringRef &Name) {
140  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
141
142  slangAssert(TUDecl != NULL && "Translation unit declaration (top-level "
143                                "declaration) is null object");
144
145  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
146  if (II == NULL)
147    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
148    //             found
149    return false;
150
151  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
152  RSExportType *ET = NULL;
153
154  for (clang::DeclContext::lookup_const_iterator I = R.begin(), E = R.end();
155       I != E;
156       I++) {
157    clang::NamedDecl *const ND = *I;
158    const clang::Type *T = NULL;
159
160    switch (ND->getKind()) {
161      case clang::Decl::Typedef: {
162        T = static_cast<const clang::TypedefDecl*>(
163            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
164        break;
165      }
166      case clang::Decl::Record: {
167        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
168        break;
169      }
170      default: {
171        // unsupported, skip
172        break;
173      }
174    }
175
176    if (T != NULL)
177      ET = RSExportType::Create(this, T);
178  }
179
180  return (ET != NULL);
181}
182
183
184// Possibly re-order ForEach exports (maybe generating a dummy "root" function).
185// We require "root" to be listed as slot 0 of our exported compute kernels,
186// so this only needs to be created if we have other non-root kernels.
187void RSContext::cleanupForEach() {
188  bool foundNonRoot = false;
189  ExportForEachList::iterator begin = mExportForEach.begin();
190
191  for (ExportForEachList::iterator I = begin, E = mExportForEach.end();
192       I != E;
193       I++) {
194    RSExportForEach *EFE = *I;
195    if (!EFE->getName().compare("root")) {
196      if (I == begin) {
197        // Nothing to do, since it is the first function
198        return;
199      }
200
201      mExportForEach.erase(I);
202      mExportForEach.push_front(EFE);
203      return;
204    } else {
205      foundNonRoot = true;
206    }
207  }
208
209  // If we found a non-root kernel, but no root() function, we need to add a
210  // dummy version (so that script->script calls of rsForEach don't behave
211  // erratically).
212  if (foundNonRoot) {
213    RSExportForEach *DummyRoot = RSExportForEach::CreateDummyRoot(this);
214    mExportForEach.push_front(DummyRoot);
215  }
216}
217
218
219bool RSContext::processExport() {
220  bool valid = true;
221
222  if (getDiagnostics()->hasErrorOccurred()) {
223    return false;
224  }
225
226  // Export variable
227  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
228  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
229           DE = TUDecl->decls_end();
230       DI != DE;
231       DI++) {
232    if (DI->getKind() == clang::Decl::Var) {
233      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
234      if (VD->getFormalLinkage() == clang::ExternalLinkage) {
235        if (!processExportVar(VD)) {
236          valid = false;
237        }
238      }
239    } else if (DI->getKind() == clang::Decl::Function) {
240      // Export functions
241      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
242      if (FD->getFormalLinkage() == clang::ExternalLinkage) {
243        if (!processExportFunc(FD)) {
244          valid = false;
245        }
246      }
247    }
248  }
249
250  if (valid) {
251    cleanupForEach();
252  }
253
254  // Finally, export type forcely set to be exported by user
255  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
256           EE = mNeedExportTypes.end();
257       EI != EE;
258       EI++) {
259    if (!processExportType(EI->getKey())) {
260      valid = false;
261    }
262  }
263
264  return valid;
265}
266
267bool RSContext::insertExportType(const llvm::StringRef &TypeName,
268                                 RSExportType *ET) {
269  ExportTypeMap::value_type *NewItem =
270      ExportTypeMap::value_type::Create(TypeName.begin(),
271                                        TypeName.end(),
272                                        mExportTypes.getAllocator(),
273                                        ET);
274
275  if (mExportTypes.insert(NewItem)) {
276    return true;
277  } else {
278    free(NewItem);
279    return false;
280  }
281}
282
283bool RSContext::reflectToJava(const std::string &OutputPathBase,
284                              const std::string &RSPackageName,
285                              const std::string &InputFileName,
286                              const std::string &OutputBCFileName) {
287  if (!RSPackageName.empty()) {
288    mRSPackageName = RSPackageName;
289  }
290
291  // If we are not targeting the actual Android Renderscript classes,
292  // we should reflect code that works with the compatibility library.
293  if (mRSPackageName.compare("android.renderscript") != 0) {
294    mIsCompatLib = true;
295  }
296
297  RSReflection *R = new RSReflection(this, mGeneratedFileNames);
298  bool ret = R->reflect(OutputPathBase, mReflectJavaPackageName, mRSPackageName,
299                        InputFileName, OutputBCFileName);
300  if (!ret)
301    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
302                    "(%s)\n", R->getLastError());
303  delete R;
304  return ret;
305}
306
307RSContext::~RSContext() {
308  delete mLicenseNote;
309  delete mDataLayout;
310  for (ExportableList::iterator I = mExportables.begin(),
311          E = mExportables.end();
312       I != E;
313       I++) {
314    if (!(*I)->isKeep())
315      delete *I;
316  }
317}
318
319clang::DiagnosticBuilder RSContext::Report(
320    clang::DiagnosticsEngine::Level Level, const char *Message) {
321  clang::DiagnosticsEngine *DiagEngine = getDiagnostics();
322  return DiagEngine->Report(DiagEngine->getCustomDiagID(Level, Message));
323}
324
325clang::DiagnosticBuilder RSContext::Report(
326    clang::DiagnosticsEngine::Level Level, const clang::SourceLocation Loc,
327    const char *Message) {
328  clang::DiagnosticsEngine *DiagEngine = getDiagnostics();
329  const clang::SourceManager *SM = getSourceManager();
330  return DiagEngine->Report(clang::FullSourceLoc(Loc, *SM),
331                            DiagEngine->getCustomDiagID(Level, Message));
332}
333
334}  // namespace slang
335