slang.cpp revision be27482cdeaf08576bc39b72a15d35d13014a636
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.h"
18
19#include <stdlib.h>
20
21#include <string>
22#include <vector>
23
24#include "clang/AST/ASTConsumer.h"
25#include "clang/AST/ASTContext.h"
26
27#include "clang/Basic/DiagnosticIDs.h"
28#include "clang/Basic/FileManager.h"
29#include "clang/Basic/FileSystemOptions.h"
30#include "clang/Basic/LangOptions.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/TargetOptions.h"
34
35#include "clang/Frontend/CodeGenOptions.h"
36#include "clang/Frontend/DiagnosticOptions.h"
37#include "clang/Frontend/DependencyOutputOptions.h"
38#include "clang/Frontend/FrontendDiagnostic.h"
39#include "clang/Frontend/TextDiagnosticPrinter.h"
40#include "clang/Frontend/Utils.h"
41
42#include "clang/Lex/Preprocessor.h"
43#include "clang/Lex/HeaderSearch.h"
44
45#include "clang/Parse/ParseAST.h"
46
47#include "llvm/ADT/IntrusiveRefCntPtr.h"
48
49#include "llvm/Bitcode/ReaderWriter.h"
50
51// More force linking
52#include "llvm/Linker.h"
53
54// Force linking all passes/vmcore stuffs to libslang.so
55#include "llvm/LinkAllPasses.h"
56#include "llvm/LinkAllVMCore.h"
57
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Support/MemoryBuffer.h"
60#include "llvm/Support/ErrorHandling.h"
61#include "llvm/Support/ManagedStatic.h"
62#include "llvm/Support/ToolOutputFile.h"
63#include "llvm/Support/Path.h"
64
65#include "llvm/Target/TargetSelect.h"
66
67#include "slang_assert.h"
68#include "slang_backend.h"
69#include "slang_utils.h"
70
71namespace {
72
73struct ForceSlangLinking {
74  ForceSlangLinking() {
75    // We must reference the functions in such a way that compilers will not
76    // delete it all as dead code, even with whole program optimization,
77    // yet is effectively a NO-OP. As the compiler isn't smart enough
78    // to know that getenv() never returns -1, this will do the job.
79    if (std::getenv("bar") != reinterpret_cast<char*>(-1))
80      return;
81
82    // llvm-rs-link needs following functions existing in libslang.
83    llvm::ParseBitcodeFile(NULL, llvm::getGlobalContext(), NULL);
84    llvm::Linker::LinkModules(NULL, NULL, NULL);
85
86    // llvm-rs-cc need this.
87    new clang::TextDiagnosticPrinter(llvm::errs(),
88                                     clang::DiagnosticOptions());
89  }
90} ForceSlangLinking;
91
92}  // namespace
93
94namespace slang {
95
96#if defined(__arm__)
97#   define DEFAULT_TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
98#elif defined(__x86_64__)
99#   define DEFAULT_TARGET_TRIPLE_STRING "x86_64-unknown-linux"
100#else
101// let's use x86 as default target
102#   define DEFAULT_TARGET_TRIPLE_STRING "i686-unknown-linux"
103#endif
104
105bool Slang::GlobalInitialized = false;
106
107// Language option (define the language feature for compiler such as C99)
108clang::LangOptions Slang::LangOpts;
109
110// Code generation option for the compiler
111clang::CodeGenOptions Slang::CodeGenOpts;
112
113// The named of metadata node that pragma resides (should be synced with
114// bcc.cpp)
115const llvm::StringRef Slang::PragmaMetadataName = "#pragma";
116
117static inline llvm::tool_output_file *OpenOutputFile(const char *OutputFile,
118                                                     unsigned Flags,
119                                                     std::string* Error,
120                                                     clang::Diagnostic* Diag) {
121  slangAssert((OutputFile != NULL) && (Error != NULL) && (Diag != NULL) &&
122              "Invalid parameter!");
123
124  llvm::sys::Path OutputFilePath(OutputFile);
125
126  if (SlangUtils::CreateDirectoryWithParents(OutputFilePath.getDirname(),
127                                             Error)) {
128    llvm::tool_output_file *F =
129          new llvm::tool_output_file(OutputFile, *Error, Flags);
130    if (F != NULL)
131      return F;
132  }
133
134  // Report error here.
135  Diag->Report(clang::diag::err_fe_error_opening) << OutputFile << *Error;
136
137  return NULL;
138}
139
140void Slang::GlobalInitialization() {
141  if (!GlobalInitialized) {
142    // We only support x86, x64 and ARM target
143
144    // For ARM
145    LLVMInitializeARMTargetInfo();
146    LLVMInitializeARMTarget();
147    LLVMInitializeARMAsmPrinter();
148
149    // For x86 and x64
150    LLVMInitializeX86TargetInfo();
151    LLVMInitializeX86Target();
152    LLVMInitializeX86AsmPrinter();
153
154    // Please refer to include/clang/Basic/LangOptions.h to setup
155    // the options.
156    LangOpts.RTTI = 0;  // Turn off the RTTI information support
157    LangOpts.NeXTRuntime = 0;   // Turn off the NeXT runtime uses
158    LangOpts.C99 = 1;
159
160    CodeGenOpts.OptimizationLevel = 3;  /* -O3 */
161
162    GlobalInitialized = true;
163  }
164
165  return;
166}
167
168void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) {
169  clang::Diagnostic* Diags = static_cast<clang::Diagnostic*>(UserData);
170  Diags->Report(clang::diag::err_fe_error_backend) << Message;
171  exit(1);
172}
173
174void Slang::createDiagnostic() {
175  mDiagClient = new DiagnosticBuffer();
176  mDiagIDs = new clang::DiagnosticIDs();
177  mDiagnostics = new clang::Diagnostic(mDiagIDs, mDiagClient, true);
178  initDiagnostic();
179  return;
180}
181
182void Slang::createTarget(const std::string &Triple, const std::string &CPU,
183                         const std::vector<std::string> &Features) {
184  if (!Triple.empty())
185    mTargetOpts.Triple = Triple;
186  else
187    mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING;
188
189  if (!CPU.empty())
190    mTargetOpts.CPU = CPU;
191
192  if (!Features.empty())
193    mTargetOpts.Features = Features;
194
195  mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagnostics,
196                                                    mTargetOpts));
197
198  return;
199}
200
201void Slang::createFileManager() {
202  mFileSysOpt.reset(new clang::FileSystemOptions());
203  mFileMgr.reset(new clang::FileManager(*mFileSysOpt));
204}
205
206void Slang::createSourceManager() {
207  mSourceMgr.reset(new clang::SourceManager(*mDiagnostics, *mFileMgr));
208  return;
209}
210
211void Slang::createPreprocessor() {
212  // Default only search header file in current dir
213  clang::HeaderSearch *HS = new clang::HeaderSearch(*mFileMgr);
214
215  mPP.reset(new clang::Preprocessor(*mDiagnostics,
216                                    LangOpts,
217                                    *mTarget,
218                                    *mSourceMgr,
219                                    *HS,
220                                    NULL,
221                                    /* OwnsHeaderSearch = */true));
222  // Initialize the preprocessor
223  mPragmas.clear();
224  mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas));
225
226  std::vector<clang::DirectoryLookup> SearchList;
227  for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) {
228    if (const clang::DirectoryEntry *DE =
229            mFileMgr->getDirectory(mIncludePaths[i])) {
230      SearchList.push_back(clang::DirectoryLookup(DE,
231                                                  clang::SrcMgr::C_System,
232                                                  false,
233                                                  false));
234    }
235  }
236
237  HS->SetSearchPaths(SearchList, 1, false);
238
239  initPreprocessor();
240  return;
241}
242
243void Slang::createASTContext() {
244  mASTContext.reset(new clang::ASTContext(LangOpts,
245                                          *mSourceMgr,
246                                          *mTarget,
247                                          mPP->getIdentifierTable(),
248                                          mPP->getSelectorTable(),
249                                          mPP->getBuiltinInfo(),
250                                          /* size_reserve = */0));
251  initASTContext();
252  return;
253}
254
255clang::ASTConsumer
256*Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts,
257                      llvm::raw_ostream *OS,
258                      OutputType OT) {
259  return new Backend(mDiagnostics.getPtr(),
260                     CodeGenOpts,
261                     mTargetOpts,
262                     &mPragmas,
263                     OS,
264                     OT);
265}
266
267Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) {
268  GlobalInitialization();
269  return;
270}
271
272void Slang::init(const std::string &Triple, const std::string &CPU,
273                 const std::vector<std::string> &Features) {
274  if (mInitialized)
275    return;
276
277  createDiagnostic();
278  llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagnostics.getPtr());
279
280  createTarget(Triple, CPU, Features);
281  createFileManager();
282  createSourceManager();
283
284  mInitialized = true;
285
286  return;
287}
288
289bool Slang::setInputSource(llvm::StringRef InputFile,
290                           const char *Text,
291                           size_t TextLength) {
292  mInputFileName = InputFile.str();
293
294  // Reset the ID tables if we are reusing the SourceManager
295  mSourceMgr->clearIDTables();
296
297  // Load the source
298  llvm::MemoryBuffer *SB =
299      llvm::MemoryBuffer::getMemBuffer(Text, Text + TextLength);
300  mSourceMgr->createMainFileIDForMemBuffer(SB);
301
302  if (mSourceMgr->getMainFileID().isInvalid()) {
303    mDiagnostics->Report(clang::diag::err_fe_error_reading) << InputFile;
304    return false;
305  }
306  return true;
307}
308
309bool Slang::setInputSource(llvm::StringRef InputFile) {
310  mInputFileName = InputFile.str();
311
312  mSourceMgr->clearIDTables();
313
314  const clang::FileEntry *File = mFileMgr->getFile(InputFile);
315  if (File)
316    mSourceMgr->createMainFileID(File);
317
318  if (mSourceMgr->getMainFileID().isInvalid()) {
319    mDiagnostics->Report(clang::diag::err_fe_error_reading) << InputFile;
320    return false;
321  }
322
323  return true;
324}
325
326bool Slang::setOutput(const char *OutputFile) {
327  llvm::sys::Path OutputFilePath(OutputFile);
328  std::string Error;
329  llvm::tool_output_file *OS = NULL;
330
331  switch (mOT) {
332    case OT_Dependency:
333    case OT_Assembly:
334    case OT_LLVMAssembly: {
335      OS = OpenOutputFile(OutputFile, 0, &Error, mDiagnostics.getPtr());
336      break;
337    }
338    case OT_Nothing: {
339      break;
340    }
341    case OT_Object:
342    case OT_Bitcode: {
343      OS = OpenOutputFile(OutputFile,
344                          llvm::raw_fd_ostream::F_Binary,
345                          &Error,
346                          mDiagnostics.getPtr());
347      break;
348    }
349    default: {
350      llvm_unreachable("Unknown compiler output type");
351    }
352  }
353
354  if (!Error.empty())
355    return false;
356
357  mOS.reset(OS);
358
359  mOutputFileName = OutputFile;
360
361  return true;
362}
363
364bool Slang::setDepOutput(const char *OutputFile) {
365  llvm::sys::Path OutputFilePath(OutputFile);
366  std::string Error;
367
368  mDOS.reset(OpenOutputFile(OutputFile, 0, &Error, mDiagnostics.getPtr()));
369  if (!Error.empty() || (mDOS.get() == NULL))
370    return false;
371
372  mDepOutputFileName = OutputFile;
373
374  return true;
375}
376
377int Slang::generateDepFile() {
378  if (mDiagnostics->hasErrorOccurred())
379    return 1;
380  if (mDOS.get() == NULL)
381    return 1;
382
383  // Initialize options for generating dependency file
384  clang::DependencyOutputOptions DepOpts;
385  DepOpts.IncludeSystemHeaders = 1;
386  DepOpts.OutputFile = mDepOutputFileName;
387  DepOpts.Targets = mAdditionalDepTargets;
388  DepOpts.Targets.push_back(mDepTargetBCFileName);
389  for (std::vector<std::string>::const_iterator
390           I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
391       I != E;
392       I++) {
393    DepOpts.Targets.push_back(*I);
394  }
395  mGeneratedFileNames.clear();
396
397  // Per-compilation needed initialization
398  createPreprocessor();
399  AttachDependencyFileGen(*mPP.get(), DepOpts);
400
401  // Inform the diagnostic client we are processing a source file
402  mDiagClient->BeginSourceFile(LangOpts, mPP.get());
403
404  // Go through the source file (no operations necessary)
405  clang::Token Tok;
406  mPP->EnterMainSourceFile();
407  do {
408    mPP->Lex(Tok);
409  } while (Tok.isNot(clang::tok::eof));
410
411  mPP->EndSourceFile();
412
413  // Declare success if no error
414  if (!mDiagnostics->hasErrorOccurred())
415    mDOS->keep();
416
417  // Clean up after compilation
418  mPP.reset();
419  mDOS.reset();
420
421  return mDiagnostics->hasErrorOccurred() ? 1 : 0;
422}
423
424int Slang::compile() {
425  if (mDiagnostics->hasErrorOccurred())
426    return 1;
427  if (mOS.get() == NULL)
428    return 1;
429
430  // Here is per-compilation needed initialization
431  createPreprocessor();
432  createASTContext();
433
434  mBackend.reset(createBackend(CodeGenOpts, &mOS->os(), mOT));
435
436  // Inform the diagnostic client we are processing a source file
437  mDiagClient->BeginSourceFile(LangOpts, mPP.get());
438
439  // The core of the slang compiler
440  ParseAST(*mPP, mBackend.get(), *mASTContext);
441
442  // Inform the diagnostic client we are done with previous source file
443  mDiagClient->EndSourceFile();
444
445  // Declare success if no error
446  if (!mDiagnostics->hasErrorOccurred())
447    mOS->keep();
448
449  // The compilation ended, clear
450  mBackend.reset();
451  mASTContext.reset();
452  mPP.reset();
453  mOS.reset();
454
455  return mDiagnostics->hasErrorOccurred() ? 1 : 0;
456}
457
458void Slang::reset() {
459  mDiagnostics->Reset();
460  mDiagClient->reset();
461  return;
462}
463
464Slang::~Slang() {
465  llvm::llvm_shutdown();
466  return;
467}
468
469}  // namespace slang
470