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/LLVMContext.h"
31#include "llvm/Target/TargetData.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      mTarget(Target),
54      mPragmas(Pragmas),
55      mTargetAPI(TargetAPI),
56      mGeneratedFileNames(GeneratedFileNames),
57      mTargetData(NULL),
58      mLLVMContext(llvm::getGlobalContext()),
59      mLicenseNote(NULL),
60      mRSPackageName("android.renderscript"),
61      version(0),
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  mTargetData = new llvm::TargetData(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,
120                                                    getDiagnostics(), FD);
121  } else if (RSExportForEach::isRSForEachFunc(mTargetAPI, FD)) {
122    RSExportForEach *EFE = RSExportForEach::Create(this, FD);
123    if (EFE == NULL)
124      return false;
125    else
126      mExportForEach.push_back(EFE);
127    return true;
128  }
129
130  RSExportFunc *EF = RSExportFunc::Create(this, FD);
131  if (EF == NULL)
132    return false;
133  else
134    mExportFuncs.push_back(EF);
135
136  return true;
137}
138
139
140bool RSContext::processExportType(const llvm::StringRef &Name) {
141  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
142
143  slangAssert(TUDecl != NULL && "Translation unit declaration (top-level "
144                                "declaration) is null object");
145
146  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
147  if (II == NULL)
148    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
149    //             found
150    return false;
151
152  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
153  RSExportType *ET = NULL;
154
155  for (clang::DeclContext::lookup_const_iterator I = R.first, E = R.second;
156       I != E;
157       I++) {
158    clang::NamedDecl *const ND = *I;
159    const clang::Type *T = NULL;
160
161    switch (ND->getKind()) {
162      case clang::Decl::Typedef: {
163        T = static_cast<const clang::TypedefDecl*>(
164            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
165        break;
166      }
167      case clang::Decl::Record: {
168        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
169        break;
170      }
171      default: {
172        // unsupported, skip
173        break;
174      }
175    }
176
177    if (T != NULL)
178      ET = RSExportType::Create(this, T);
179  }
180
181  return (ET != NULL);
182}
183
184
185// Possibly re-order ForEach exports (maybe generating a dummy "root" function).
186// We require "root" to be listed as slot 0 of our exported compute kernels,
187// so this only needs to be created if we have other non-root kernels.
188void RSContext::cleanupForEach() {
189  bool foundNonRoot = false;
190  ExportForEachList::iterator begin = mExportForEach.begin();
191
192  for (ExportForEachList::iterator I = begin, E = mExportForEach.end();
193       I != E;
194       I++) {
195    RSExportForEach *EFE = *I;
196    if (!EFE->getName().compare("root")) {
197      if (I == begin) {
198        // Nothing to do, since it is the first function
199        return;
200      }
201
202      mExportForEach.erase(I);
203      mExportForEach.push_front(EFE);
204      return;
205    } else {
206      foundNonRoot = true;
207    }
208  }
209
210  // If we found a non-root kernel, but no root() function, we need to add a
211  // dummy version (so that script->script calls of rsForEach don't behave
212  // erratically).
213  if (foundNonRoot) {
214    RSExportForEach *DummyRoot = RSExportForEach::CreateDummyRoot(this);
215    mExportForEach.push_front(DummyRoot);
216  }
217}
218
219
220bool RSContext::processExport() {
221  bool valid = true;
222
223  if (getDiagnostics()->hasErrorOccurred()) {
224    return false;
225  }
226
227  // Export variable
228  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
229  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
230           DE = TUDecl->decls_end();
231       DI != DE;
232       DI++) {
233    if (DI->getKind() == clang::Decl::Var) {
234      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
235      if (VD->getLinkage() == clang::ExternalLinkage) {
236        if (!processExportVar(VD)) {
237          valid = false;
238        }
239      }
240    } else if (DI->getKind() == clang::Decl::Function) {
241      // Export functions
242      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
243      if (FD->getLinkage() == clang::ExternalLinkage) {
244        if (!processExportFunc(FD)) {
245          valid = false;
246        }
247      }
248    }
249  }
250
251  if (valid) {
252    cleanupForEach();
253  }
254
255  // Finally, export type forcely set to be exported by user
256  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
257           EE = mNeedExportTypes.end();
258       EI != EE;
259       EI++) {
260    if (!processExportType(EI->getKey())) {
261      valid = false;
262    }
263  }
264
265  return valid;
266}
267
268bool RSContext::insertExportType(const llvm::StringRef &TypeName,
269                                 RSExportType *ET) {
270  ExportTypeMap::value_type *NewItem =
271      ExportTypeMap::value_type::Create(TypeName.begin(),
272                                        TypeName.end(),
273                                        mExportTypes.getAllocator(),
274                                        ET);
275
276  if (mExportTypes.insert(NewItem)) {
277    return true;
278  } else {
279    free(NewItem);
280    return false;
281  }
282}
283
284bool RSContext::reflectToJava(const std::string &OutputPathBase,
285                              const std::string &OutputPackageName,
286                              const std::string &RSPackageName,
287                              const std::string &InputFileName,
288                              const std::string &OutputBCFileName,
289                              std::string *RealPackageName) {
290  if (RealPackageName != NULL)
291    RealPackageName->clear();
292
293  const std::string &PackageName =
294      ((OutputPackageName.empty()) ? mReflectJavaPackageName :
295                                     OutputPackageName);
296  slangAssert(!PackageName.empty());
297
298  // Copy back the really applied package name
299  RealPackageName->assign(PackageName);
300
301  if (!RSPackageName.empty()) {
302    mRSPackageName = RSPackageName;
303  }
304
305  RSReflection *R = new RSReflection(this, mGeneratedFileNames);
306  bool ret = R->reflect(OutputPathBase, PackageName, mRSPackageName,
307                        InputFileName, OutputBCFileName);
308  if (!ret)
309    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
310                    "(%s)\n", R->getLastError());
311  delete R;
312  return ret;
313}
314
315RSContext::~RSContext() {
316  delete mLicenseNote;
317  delete mTargetData;
318  for (ExportableList::iterator I = mExportables.begin(),
319          E = mExportables.end();
320       I != E;
321       I++) {
322    if (!(*I)->isKeep())
323      delete *I;
324  }
325}
326
327}  // namespace slang
328