slang.cpp revision 66819a96bda9362f86e4f26ed8a9b1f73961b27a
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  if (inclDir) {
114    std::vector<DirectoryLookup> SearchList;
115    if (const DirectoryEntry *DE = mFileMgr->getDirectory(inclDir, inclDir + strlen(inclDir))) {
116      SearchList.push_back(DirectoryLookup(DE, SrcMgr::C_System, false, false));
117      HS->SetSearchPaths(SearchList, 1, false);
118    }
119  }
120
121  return;
122}
123
124Slang::Slang(const char* Triple, const char* CPU, const char** Features) :
125    mOutputType(SlangCompilerOutput_Default),
126    mAllowRSPrefix(false)
127{
128    GlobalInitialization();
129
130    createDiagnostic();
131    llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagnostics.get());
132
133    createTarget(Triple, CPU, Features);
134    createFileManager();
135    createSourceManager();
136
137    return;
138}
139
140bool Slang::setInputSource(llvm::StringRef inputFile, const char* text, size_t textLength) {
141    mInputFileName = inputFile.str();
142
143    /* Reset the ID tables if we are reusing the SourceManager */
144    mSourceMgr->clearIDTables();
145
146    /* Load the source */
147    llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getMemBuffer(text, text + textLength);
148    mSourceMgr->createMainFileIDForMemBuffer(SB);
149
150    if(mSourceMgr->getMainFileID().isInvalid()) {
151        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
152        return false;
153    }
154
155    return true;
156}
157
158bool Slang::setInputSource(llvm::StringRef inputFile) {
159    mInputFileName = inputFile.str();
160
161    mSourceMgr->clearIDTables();
162
163    const FileEntry* File = mFileMgr->getFile(inputFile);
164    if(File)
165        mSourceMgr->createMainFileID(File, SourceLocation());
166
167    if(mSourceMgr->getMainFileID().isInvalid()) {
168        mDiagnostics->Report(clang::diag::err_fe_error_reading) << inputFile;
169        return false;
170    }
171
172    return true;
173}
174
175void Slang::setOutputType(SlangCompilerOutputTy outputType) {
176    mOutputType = outputType;
177    if( mOutputType != SlangCompilerOutput_Assembly &&
178        mOutputType != SlangCompilerOutput_LL &&
179        mOutputType != SlangCompilerOutput_Bitcode &&
180        mOutputType != SlangCompilerOutput_Nothing &&
181        mOutputType != SlangCompilerOutput_Obj)
182        mOutputType = SlangCompilerOutput_Default;
183    return;
184}
185
186static void _mkdir_given_a_file(const char *file) {
187    char buf[256];
188    char *tmp, *p = NULL;
189    size_t len = strlen(file);
190
191    if (len + 1 <= sizeof(buf))
192        tmp = buf;
193    else
194        tmp = new char [len + 1];
195
196    strcpy(tmp, file);
197
198    if (tmp[len - 1] == '/')
199        tmp[len - 1] = 0;
200
201    for (p = tmp + 1; *p; p++) {
202        if (*p == '/') {
203            *p = 0;
204            mkdir(tmp, S_IRWXU);
205            *p = '/';
206        }
207    }
208
209    if (tmp != buf)
210        delete[] tmp;
211}
212
213bool Slang::setOutput(const char* outputFile) {
214    std::string Error;
215
216    _mkdir_given_a_file(outputFile);
217
218    switch(mOutputType) {
219        case SlangCompilerOutput_Assembly:
220        case SlangCompilerOutput_LL:
221            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, 0) );
222        break;
223
224        case SlangCompilerOutput_Nothing:
225            mOS.reset();
226        break;
227
228        case SlangCompilerOutput_Obj:
229        case SlangCompilerOutput_Bitcode:
230        default:
231            mOS.reset( new llvm::raw_fd_ostream(outputFile, Error, llvm::raw_fd_ostream::F_Binary) );
232        break;
233    }
234
235    if(!Error.empty()) {
236        mOS.reset();
237        mDiagnostics->Report(clang::diag::err_fe_error_opening) << outputFile << Error;
238        return false;
239    }
240
241    mOutputFileName = outputFile;
242
243    return true;
244}
245
246int Slang::compile() {
247    if((mDiagnostics->getNumErrors() > 0) || (mOS.get() == NULL))
248        return mDiagnostics->getNumErrors();
249
250    /* Here is per-compilation needed initialization */
251    createPreprocessor();
252    createASTContext();
253    createRSContext();
254    //createBackend();
255    createRSBackend();
256
257    /* Inform the diagnostic client we are processing a source file */
258    mDiagClient->BeginSourceFile(LangOpts, mPP.get());
259
260    /* The core of the slang compiler */
261    ParseAST(*mPP, mBackend.get(), *mASTContext);
262
263    /* The compilation ended, clear up */
264    mBackend.reset();
265    mASTContext.reset();
266    mPP.reset();
267
268    /* Inform the diagnostic client we are done with previous source file */
269    mDiagClient->EndSourceFile();
270
271    return mDiagnostics->getNumErrors();
272}
273
274bool Slang::reflectToJava(const char* outputPackageName) {
275    if(mRSContext.get())
276        return mRSContext->reflectToJava(outputPackageName, mInputFileName, mOutputFileName);
277    else
278        return false;
279}
280
281bool Slang::reflectToJavaPath(const char* outputPathName) {
282    if(mRSContext.get())
283        return mRSContext->reflectToJavaPath(outputPathName);
284    else
285        return false;
286}
287
288void Slang::getPragmas(size_t* actualStringCount, size_t maxStringCount, char** strings) {
289    int stringCount = mPragmas.size() * 2;
290
291    if(actualStringCount)
292        *actualStringCount = stringCount;
293    if(stringCount > maxStringCount)
294        stringCount = maxStringCount;
295    if(strings)
296        for(PragmaList::const_iterator it = mPragmas.begin();
297            stringCount > 0;
298            stringCount-=2, it++)
299        {
300            *strings++ = const_cast<char*>(it->first.c_str());
301            *strings++ = const_cast<char*>(it->second.c_str());
302        }
303
304    return;
305}
306
307Slang::~Slang() {
308    llvm::llvm_shutdown();
309    return;
310}
311
312}   /* namespace slang */
313