slang.cpp revision 68e8e9f98730b3672fb96d49e33b9db70a90ed3f
1#include "slang.hpp"
2
3#include <stdlib.h>                     /* for getenv */
4
5#include "libslang.h"
6
7#include "llvm/ADT/Twine.h"     /* for class llvm::Twine */
8
9#include "llvm/Target/TargetSelect.h"       /* for function LLVMInitialize[ARM|X86][TargetInfo|Target|AsmPrinter]() */
10
11#include "llvm/Support/MemoryBuffer.h"      /* for class llvm::MemoryBuffer */
12#include "llvm/Support/ErrorHandling.h"     /* for function llvm::install_fatal_error_handler() */
13#include "llvm/Support/ManagedStatic.h"     /* for class llvm::llvm_shutdown */
14
15#include "clang/Basic/TargetInfo.h"     /* for class clang::TargetInfo */
16#include "clang/Basic/LangOptions.h"    /* for class clang::LangOptions */
17#include "clang/Basic/TargetOptions.h"  /* for class clang::TargetOptions */
18
19#include "clang/Frontend/FrontendDiagnostic.h"      /* for clang::diag::* */
20
21#include "clang/Sema/ParseAST.h"        /* for function clang::ParseAST() */
22
23#if defined(__arm__)
24#   define DEFAULT_TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
25#elif defined(__x86_64__)
26#   define DEFAULT_TARGET_TRIPLE_STRING "x86_64-unknown-linux"
27#else
28#   define DEFAULT_TARGET_TRIPLE_STRING "i686-unknown-linux"    // let's use x86 as default target
29#endif
30
31namespace slang {
32
33bool Slang::GlobalInitialized = false;
34
35/* Language option (define the language feature for compiler such as C99) */
36LangOptions Slang::LangOpts;
37
38/* Code generation option for the compiler */
39CodeGenOptions Slang::CodeGenOpts;
40
41const std::string Slang::TargetDescription = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-n32";
42
43/* The named of metadata node that pragma resides (should be synced with bcc.cpp) */
44const llvm::Twine Slang::PragmaMetadataName = "#pragma";
45
46void Slang::GlobalInitialization() {
47    if(!GlobalInitialized) {
48        /* We only support x86, x64 and ARM target */
49
50        /* For ARM */
51        LLVMInitializeARMTargetInfo();
52        LLVMInitializeARMTarget();
53        LLVMInitializeARMAsmPrinter();
54
55        /* For x86 and x64 */
56        LLVMInitializeX86TargetInfo();
57        LLVMInitializeX86Target();
58        LLVMInitializeX86AsmPrinter();
59
60        /* Please refer to clang/include/clang/Basic/LangOptions.h for setting up the options */
61        LangOpts.RTTI = 0;  /* turn off the RTTI information support */
62        LangOpts.NeXTRuntime = 0;   /* turn off the NeXT runtime uses */
63        LangOpts.Bool = 1;  /* turn on 'bool', 'true', 'false' keywords. */
64
65        CodeGenOpts.OptimizationLevel = 3;  /* -O3 */
66
67        GlobalInitialized = true;
68    }
69
70    return;
71}
72
73void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) {
74    Diagnostic* Diags = static_cast<Diagnostic*>(UserData);
75    Diags->Report(clang::diag::err_fe_error_backend) << Message;
76    exit(1);
77}
78
79void Slang::createTarget(const char* Triple, const char* CPU, const char** Features) {
80    if(Triple != NULL)
81        mTargetOpts.Triple = Triple;
82    else
83        mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING;
84
85    if(CPU != NULL)
86        mTargetOpts.CPU = CPU;
87
88    mTarget.reset(TargetInfo::CreateTargetInfo(*mDiagnostics, mTargetOpts));
89
90    if(Features != NULL)
91        for(int i=0;Features[i]!=NULL;i++)
92            mTargetOpts.Features.push_back(Features[i]);
93
94    return;
95}
96
97void Slang::createPreprocessor() {
98  HeaderSearch* HS = new HeaderSearch(*mFileMgr); /* Default only search header file in current dir */
99
100  mPP.reset(new Preprocessor( *mDiagnostics,
101                              LangOpts,
102                              *mTarget,
103                              *mSourceMgr,
104                              *HS,
105                              NULL,
106                              true /* OwnsHeaderSearch */));
107  /* Initialize the prepocessor */
108  mPragmas.clear();
109  mPP->AddPragmaHandler(NULL, new PragmaRecorder(mPragmas));
110
111  /* Like ApplyHeaderSearchOptions in InitHeaderSearch.cpp */
112  const char*inclDir = getenv("ANDROID_BUILD_TOP");
113
114  printf("%s\n", inclDir);
115  if (inclDir) {
116    std::vector<DirectoryLookup> SearchList;
117    if (const DirectoryEntry *DE = mFileMgr->getDirectory(inclDir, inclDir + strlen(inclDir))) {
118      SearchList.push_back(DirectoryLookup(DE, SrcMgr::C_System, false, false));
119      HS->SetSearchPaths(SearchList, 1, false);
120    }
121  }
122
123  return;
124}
125
126Slang::Slang(const char* Triple, const char* CPU, const char** Features) :
127    mOutputType(SlangCompilerOutput_Default),
128    mAllowRSPrefix(false)
129{
130    GlobalInitialization();
131
132    createDiagnostic();
133    llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagnostics.get());
134
135    createTarget(Triple, CPU, Features);
136    createFileManager();
137    createSourceManager();
138
139    return;
140}
141
142bool Slang::setInputSource(llvm::StringRef inputFile, const char* text, size_t textLength) {
143    mInputFileName = inputFile.str();
144
145    /* Reset the ID tables if we are reusing the SourceManager */
146    mSourceMgr->clearIDTables();
147
148    /* Load the source */
149    llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getMemBuffer(text, text + textLength);
150    mSourceMgr->createMainFileIDForMemBuffer(SB);
151
152    if(mSourceMgr->getMainFileID().isInvalid()) {
153        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
154        return false;
155    }
156
157    return true;
158}
159
160bool Slang::setInputSource(llvm::StringRef inputFile) {
161    mInputFileName = inputFile.str();
162
163    mSourceMgr->clearIDTables();
164
165    const FileEntry* File = mFileMgr->getFile(inputFile);
166    if(File)
167        mSourceMgr->createMainFileID(File, SourceLocation());
168
169    if(mSourceMgr->getMainFileID().isInvalid()) {
170        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
171        return false;
172    }
173
174    return true;
175}
176
177void Slang::setOutputType(SlangCompilerOutputTy outputType) {
178    mOutputType = outputType;
179    if( mOutputType != SlangCompilerOutput_Assembly &&
180        mOutputType != SlangCompilerOutput_LL &&
181        mOutputType != SlangCompilerOutput_Bitcode &&
182        mOutputType != SlangCompilerOutput_Nothing &&
183        mOutputType != SlangCompilerOutput_Obj)
184        mOutputType = SlangCompilerOutput_Default;
185    return;
186}
187
188static void _mkdir_given_a_file(const char *file) {
189    char buf[256];
190    char *tmp, *p = NULL;
191    size_t len = strlen(file);
192
193    if (len + 1 <= sizeof(buf))
194        tmp = buf;
195    else
196        tmp = new char [len + 1];
197
198    strcpy(tmp, file);
199
200    if (tmp[len - 1] == '/')
201        tmp[len - 1] = 0;
202
203    for (p = tmp + 1; *p; p++) {
204        if (*p == '/') {
205            *p = 0;
206            mkdir(tmp, S_IRWXU);
207            *p = '/';
208        }
209    }
210
211    if (tmp != buf)
212        delete[] tmp;
213}
214
215bool Slang::setOutput(const char* outputFile) {
216    std::string Error;
217
218    _mkdir_given_a_file(outputFile);
219
220    switch(mOutputType) {
221        case SlangCompilerOutput_Assembly:
222        case SlangCompilerOutput_LL:
223            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, 0) );
224        break;
225
226        case SlangCompilerOutput_Nothing:
227            mOS.reset();
228        break;
229
230        case SlangCompilerOutput_Obj:
231        case SlangCompilerOutput_Bitcode:
232        default:
233            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, llvm::raw_fd_ostream::F_Binary) );
234        break;
235    }
236
237    if(!Error.empty()) {
238        mOS.reset();
239        mDiagnostics->Report(clang::diag::err_fe_error_opening) << outputFile << Error;
240        return false;
241    }
242
243    mOutputFileName = outputFile;
244
245    return true;
246}
247
248int Slang::compile() {
249    if((mDiagnostics->getNumErrors() > 0) || (mOS.get() == NULL))
250        return mDiagnostics->getNumErrors();
251
252    /* Here is per-compilation needed initialization */
253    createPreprocessor();
254    createASTContext();
255    createRSContext();
256    //createBackend();
257    createRSBackend();
258
259    /* Inform the diagnostic client we are processing a source file */
260    mDiagClient->BeginSourceFile(LangOpts, mPP.get());
261
262    /* The core of the slang compiler */
263    ParseAST(*mPP, mBackend.get(), *mASTContext);
264
265    /* The compilation ended, clear up */
266    mBackend.reset();
267    mASTContext.reset();
268    mPP.reset();
269
270    /* Inform the diagnostic client we are done with previous source file */
271    mDiagClient->EndSourceFile();
272
273    return mDiagnostics->getNumErrors();
274}
275
276bool Slang::reflectToJava(const char* outputPackageName) {
277    if(mRSContext.get())
278        return mRSContext->reflectToJava(outputPackageName, mInputFileName, mOutputFileName);
279    else
280        return false;
281}
282
283bool Slang::reflectToJavaPath(const char* outputPathName) {
284    if(mRSContext.get())
285        return mRSContext->reflectToJavaPath(outputPathName);
286    else
287        return false;
288}
289
290void Slang::getPragmas(size_t* actualStringCount, size_t maxStringCount, char** strings) {
291    int stringCount = mPragmas.size() * 2;
292
293    if(actualStringCount)
294        *actualStringCount = stringCount;
295    if(stringCount > maxStringCount)
296        stringCount = maxStringCount;
297    if(strings)
298        for(PragmaList::const_iterator it = mPragmas.begin();
299            stringCount > 0;
300            stringCount-=2, it++)
301        {
302            *strings++ = const_cast<char*>(it->first.c_str());
303            *strings++ = const_cast<char*>(it->second.c_str());
304        }
305
306    return;
307}
308
309Slang::~Slang() {
310    llvm::llvm_shutdown();
311    return;
312}
313
314}   /* namespace slang */
315