slang_rs_context.cpp revision c97a333bc84ce8c28c96d07734cbded75c914639
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_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/Type.h"
25
26#include "clang/Basic/Linkage.h"
27#include "clang/Basic/TargetInfo.h"
28
29#include "clang/Index/ASTLocation.h"
30
31#include "llvm/LLVMContext.h"
32
33#include "llvm/Target/TargetData.h"
34
35#include "slang.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    : mPP(PP),
49      mCtx(Ctx),
50      mTarget(Target),
51      mTargetData(NULL),
52      mLLVMContext(llvm::getGlobalContext()),
53      mLicenseNote(NULL) {
54  // For #pragma rs export_type
55  PP.AddPragmaHandler(
56      "rs", RSPragmaHandler::CreatePragmaExportTypeHandler(this));
57
58  // For #pragma rs java_package_name
59  PP.AddPragmaHandler(
60      "rs", RSPragmaHandler::CreatePragmaJavaPackageNameHandler(this));
61
62  // For #pragma rs set_reflect_license
63  PP.AddPragmaHandler(
64      "rs", RSPragmaHandler::CreatePragmaReflectLicenseHandler(this));
65
66  // Prepare target data
67  mTargetData = new llvm::TargetData(Target.getTargetDescription());
68
69  return;
70}
71
72bool RSContext::processExportVar(const clang::VarDecl *VD) {
73  assert(!VD->getName().empty() && "Variable name should not be empty");
74
75  // TODO(zonr): some check on variable
76
77  RSExportType *ET = RSExportType::CreateFromDecl(this, VD);
78  if (!ET)
79    return false;
80
81  RSExportVar *EV = new RSExportVar(this, VD, ET);
82  if (EV == NULL)
83    return false;
84  else
85    mExportVars.push_back(EV);
86
87  return true;
88}
89
90static bool isSpecialRSFunc(const llvm::StringRef& Name) {
91  static llvm::StringRef FuncInit("init");
92  static llvm::StringRef FuncRoot("root");
93  return Name.equals(FuncInit) || Name.equals(FuncRoot);
94}
95
96bool RSContext::processExportFunc(const clang::FunctionDecl *FD) {
97  assert(!FD->getName().empty() && "Function name should not be empty");
98
99  if (!FD->isThisDeclarationADefinition()) {
100    return true;
101  }
102
103  if (FD->getStorageClass() != clang::SC_None) {
104    fprintf(stderr, "RSContext::processExportFunc : cannot export extern or "
105                    "static function '%s'\n", FD->getName().str().c_str());
106    return false;
107  }
108
109  // Do not reflect specialized RS functions like init/root.
110  if (isSpecialRSFunc(FD->getName())) {
111    return true;
112  }
113
114  RSExportFunc *EF = RSExportFunc::Create(this, FD);
115  if (EF == NULL)
116    return false;
117  else
118    mExportFuncs.push_back(EF);
119
120  return true;
121}
122
123
124bool RSContext::processExportType(const llvm::StringRef &Name) {
125  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
126
127  assert(TUDecl != NULL && "Translation unit declaration (top-level "
128                           "declaration) is null object");
129
130  const clang::IdentifierInfo *II = mPP.getIdentifierInfo(Name);
131  if (II == NULL)
132    // TODO(zonr): alert identifier @Name mark as an exportable type cannot be
133    //             found
134    return false;
135
136  clang::DeclContext::lookup_const_result R = TUDecl->lookup(II);
137  RSExportType *ET = NULL;
138
139  RSExportPointerType::IntegerType = mCtx.IntTy.getTypePtr();
140
141  for (clang::DeclContext::lookup_const_iterator I = R.first, E = R.second;
142       I != E;
143       I++) {
144    clang::NamedDecl *const ND = *I;
145    const clang::Type *T = NULL;
146
147    switch (ND->getKind()) {
148      case clang::Decl::Typedef: {
149        T = static_cast<const clang::TypedefDecl*>(
150            ND)->getCanonicalDecl()->getUnderlyingType().getTypePtr();
151        break;
152      }
153      case clang::Decl::Record: {
154        T = static_cast<const clang::RecordDecl*>(ND)->getTypeForDecl();
155        break;
156      }
157      default: {
158        // unsupported, skip
159        break;
160      }
161    }
162
163    if (T != NULL)
164      ET = RSExportType::Create(this, T);
165  }
166
167  RSExportPointerType::IntegerType = NULL;
168
169  return (ET != NULL);
170}
171
172bool RSContext::processExport() {
173  // Export variable
174  clang::TranslationUnitDecl *TUDecl = mCtx.getTranslationUnitDecl();
175  for (clang::DeclContext::decl_iterator DI = TUDecl->decls_begin(),
176           DE = TUDecl->decls_end();
177       DI != DE;
178       DI++) {
179    if (DI->getKind() == clang::Decl::Var) {
180      clang::VarDecl *VD = (clang::VarDecl*) (*DI);
181      if (VD->getLinkage() == clang::ExternalLinkage) {
182        if (!processExportVar(VD)) {
183          fprintf(stderr, "RSContext::processExport : failed to export var "
184                          "'%s'\n", VD->getNameAsString().c_str());
185          return false;
186        }
187      }
188    } else if (DI->getKind() == clang::Decl::Function) {
189      // Export functions
190      clang::FunctionDecl *FD = (clang::FunctionDecl*) (*DI);
191      if (FD->getLinkage() == clang::ExternalLinkage) {
192        if (!processExportFunc(FD)) {
193          fprintf(stderr, "RSContext::processExport : failed to export func "
194                          "'%s'\n", FD->getNameAsString().c_str());
195          return false;
196        }
197      }
198    }
199  }
200
201  // Finally, export type forcely set to be exported by user
202  for (NeedExportTypeSet::const_iterator EI = mNeedExportTypes.begin(),
203           EE = mNeedExportTypes.end();
204       EI != EE;
205       EI++) {
206    if (!processExportType(EI->getKey())) {
207      fprintf(stderr, "RSContext::processExport : failed to export type "
208              "'%s'\n", EI->getKey().str().c_str());
209      return false;
210    }
211  }
212
213  return true;
214}
215
216bool RSContext::insertExportType(const llvm::StringRef &TypeName,
217                                 RSExportType *ET) {
218  ExportTypeMap::value_type *NewItem =
219      ExportTypeMap::value_type::Create(TypeName.begin(),
220                                        TypeName.end(),
221                                        mExportTypes.getAllocator(),
222                                        ET);
223
224  if (mExportTypes.insert(NewItem)) {
225    return true;
226  } else {
227    free(NewItem);
228    return false;
229  }
230}
231
232bool RSContext::reflectToJava(const std::string &OutputPathBase,
233                              const std::string &OutputPackageName,
234                              const std::string &InputFileName,
235                              const std::string &OutputBCFileName,
236                              std::string *RealPackageName) {
237  if (RealPackageName != NULL)
238    RealPackageName->clear();
239
240  const std::string &PackageName =
241      ((OutputPackageName.empty()) ? mReflectJavaPackageName :
242                                     OutputPackageName);
243  if (PackageName.empty()) {
244    std::cerr << "Error: Missing \"#pragma rs "
245              << "java_package_name(com.foo.bar)\" in "
246              << InputFileName << std::endl;
247    return false;
248  }
249
250  // Copy back the really applied package name
251  RealPackageName->assign(PackageName);
252
253  RSReflection *R = new RSReflection(this);
254  bool ret = R->reflect(OutputPathBase, PackageName,
255                        InputFileName, OutputBCFileName);
256  if (!ret)
257    fprintf(stderr, "RSContext::reflectToJava : failed to do reflection "
258                    "(%s)\n", R->getLastError());
259  delete R;
260  return ret;
261}
262
263RSContext::~RSContext() {
264  delete mLicenseNote;
265  delete mTargetData;
266  for (ExportableList::iterator I = mExportables.begin(),
267          E = mExportables.end();
268       I != E;
269       I++) {
270    if (!(*I)->isKeep())
271      delete *I;
272  }
273}
274
275}  // namespace slang
276