slang.cpp revision 52d132c53a57c3bb4b517f87ec4f0148ef8a4216
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/Path.h"
63#include "llvm/Support/TargetSelect.h"
64#include "llvm/Support/ToolOutputFile.h"
65
66#include "slang_assert.h"
67#include "slang_backend.h"
68#include "slang_utils.h"
69
70namespace {
71
72struct ForceSlangLinking {
73  ForceSlangLinking() {
74    // We must reference the functions in such a way that compilers will not
75    // delete it all as dead code, even with whole program optimization,
76    // yet is effectively a NO-OP. As the compiler isn't smart enough
77    // to know that getenv() never returns -1, this will do the job.
78    if (std::getenv("bar") != reinterpret_cast<char*>(-1))
79      return;
80
81    // llvm-rs-link needs following functions existing in libslang.
82    llvm::ParseBitcodeFile(NULL, llvm::getGlobalContext(), NULL);
83    llvm::Linker::LinkModules(NULL, NULL, 0, NULL);
84
85    // llvm-rs-cc need this.
86    new clang::TextDiagnosticPrinter(llvm::errs(),
87                                     clang::DiagnosticOptions());
88  }
89} ForceSlangLinking;
90
91}  // namespace
92
93namespace slang {
94
95#if defined(__arm__)
96#   define DEFAULT_TARGET_TRIPLE_STRING "armv7-none-linux-gnueabi"
97#elif defined(__x86_64__)
98#   define DEFAULT_TARGET_TRIPLE_STRING "x86_64-unknown-linux"
99#else
100// let's use x86 as default target
101#   define DEFAULT_TARGET_TRIPLE_STRING "i686-unknown-linux"
102#endif
103
104bool Slang::GlobalInitialized = false;
105
106// Language option (define the language feature for compiler such as C99)
107clang::LangOptions Slang::LangOpts;
108
109// Code generation option for the compiler
110clang::CodeGenOptions Slang::CodeGenOpts;
111
112// The named of metadata node that pragma resides (should be synced with
113// bcc.cpp)
114const llvm::StringRef Slang::PragmaMetadataName = "#pragma";
115
116static inline llvm::tool_output_file *
117OpenOutputFile(const char *OutputFile,
118               unsigned Flags,
119               std::string* Error,
120               clang::DiagnosticsEngine *DiagEngine) {
121  slangAssert((OutputFile != NULL) && (Error != NULL) &&
122              (DiagEngine != NULL) && "Invalid parameter!");
123
124  if (SlangUtils::CreateDirectoryWithParents(
125                        llvm::sys::path::parent_path(OutputFile), Error)) {
126    llvm::tool_output_file *F =
127          new llvm::tool_output_file(OutputFile, *Error, Flags);
128    if (F != NULL)
129      return F;
130  }
131
132  // Report error here.
133  DiagEngine->Report(clang::diag::err_fe_error_opening)
134    << OutputFile << *Error;
135
136  return NULL;
137}
138
139void Slang::GlobalInitialization() {
140  if (!GlobalInitialized) {
141    // We only support x86, x64 and ARM target
142
143    // For ARM
144    LLVMInitializeARMTargetInfo();
145    LLVMInitializeARMTarget();
146    LLVMInitializeARMAsmPrinter();
147
148    // For x86 and x64
149    LLVMInitializeX86TargetInfo();
150    LLVMInitializeX86Target();
151    LLVMInitializeX86AsmPrinter();
152
153    // Please refer to include/clang/Basic/LangOptions.h to setup
154    // the options.
155    LangOpts.RTTI = 0;  // Turn off the RTTI information support
156    LangOpts.NeXTRuntime = 0;   // Turn off the NeXT runtime uses
157    LangOpts.C99 = 1;
158    LangOpts.Renderscript = 1;
159    LangOpts.CharIsSigned = 1;  // Signed char is our default.
160
161    CodeGenOpts.OptimizationLevel = 3;
162
163    GlobalInitialized = true;
164  }
165}
166
167void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) {
168  clang::DiagnosticsEngine* DiagEngine =
169    static_cast<clang::DiagnosticsEngine *>(UserData);
170
171  DiagEngine->Report(clang::diag::err_fe_error_backend) << Message;
172  exit(1);
173}
174
175void Slang::createTarget(const std::string &Triple, const std::string &CPU,
176                         const std::vector<std::string> &Features) {
177  if (!Triple.empty())
178    mTargetOpts.Triple = Triple;
179  else
180    mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING;
181
182  if (!CPU.empty())
183    mTargetOpts.CPU = CPU;
184
185  if (!Features.empty())
186    mTargetOpts.Features = Features;
187
188  mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine,
189                                                    mTargetOpts));
190}
191
192void Slang::createFileManager() {
193  mFileSysOpt.reset(new clang::FileSystemOptions());
194  mFileMgr.reset(new clang::FileManager(*mFileSysOpt));
195}
196
197void Slang::createSourceManager() {
198  mSourceMgr.reset(new clang::SourceManager(*mDiagEngine, *mFileMgr));
199}
200
201void Slang::createPreprocessor() {
202  // Default only search header file in current dir
203  clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(*mFileMgr,
204                                                            *mDiagEngine,
205                                                            LangOpts,
206                                                            mTarget.get());
207
208  mPP.reset(new clang::Preprocessor(*mDiagEngine,
209                                    LangOpts,
210                                    mTarget.get(),
211                                    *mSourceMgr,
212                                    *HeaderInfo,
213                                    *this,
214                                    NULL,
215                                    /* OwnsHeaderSearch = */true));
216  // Initialize the preprocessor
217  mPragmas.clear();
218  mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas));
219
220  std::vector<clang::DirectoryLookup> SearchList;
221  for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) {
222    if (const clang::DirectoryEntry *DE =
223            mFileMgr->getDirectory(mIncludePaths[i])) {
224      SearchList.push_back(clang::DirectoryLookup(DE,
225                                                  clang::SrcMgr::C_System,
226                                                  false,
227                                                  false));
228    }
229  }
230
231  HeaderInfo->SetSearchPaths(SearchList,
232                             /* angledDirIdx = */1,
233                             /* systemDixIdx = */1,
234                             /* noCurDirSearch = */false);
235
236  initPreprocessor();
237}
238
239void Slang::createASTContext() {
240  mASTContext.reset(new clang::ASTContext(LangOpts,
241                                          *mSourceMgr,
242                                          mTarget.get(),
243                                          mPP->getIdentifierTable(),
244                                          mPP->getSelectorTable(),
245                                          mPP->getBuiltinInfo(),
246                                          /* size_reserve = */0));
247  initASTContext();
248}
249
250clang::ASTConsumer *
251Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts,
252                     llvm::raw_ostream *OS, OutputType OT) {
253  return new Backend(mDiagEngine, CodeGenOpts, mTargetOpts,
254                     &mPragmas, OS, OT);
255}
256
257Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) {
258  GlobalInitialization();
259}
260
261void Slang::init(const std::string &Triple, const std::string &CPU,
262                 const std::vector<std::string> &Features,
263                 clang::DiagnosticsEngine *DiagEngine,
264                 DiagnosticBuffer *DiagClient) {
265  if (mInitialized)
266    return;
267
268  mDiagEngine = DiagEngine;
269  mDiagClient = DiagClient;
270  mDiag.reset(new clang::Diagnostic(mDiagEngine));
271  initDiagnostic();
272  llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagEngine);
273
274  createTarget(Triple, CPU, Features);
275  createFileManager();
276  createSourceManager();
277
278  mInitialized = true;
279}
280
281clang::Module *Slang::loadModule(clang::SourceLocation ImportLoc,
282                                 clang::ModuleIdPath Path,
283                                 clang::Module::NameVisibilityKind Visibility,
284                                 bool IsInclusionDirective) {
285  slangAssert(0 && "Not implemented");
286  return NULL;
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    mDiagEngine->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    mDiagEngine->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, mDiagEngine);
336      break;
337    }
338    case OT_Nothing: {
339      break;
340    }
341    case OT_Object:
342    case OT_Bitcode: {
343      OS = OpenOutputFile(OutputFile, llvm::raw_fd_ostream::F_Binary,
344                          &Error, mDiagEngine);
345      break;
346    }
347    default: {
348      llvm_unreachable("Unknown compiler output type");
349    }
350  }
351
352  if (!Error.empty())
353    return false;
354
355  mOS.reset(OS);
356
357  mOutputFileName = OutputFile;
358
359  return true;
360}
361
362bool Slang::setDepOutput(const char *OutputFile) {
363  llvm::sys::Path OutputFilePath(OutputFile);
364  std::string Error;
365
366  mDOS.reset(OpenOutputFile(OutputFile, 0, &Error, mDiagEngine));
367  if (!Error.empty() || (mDOS.get() == NULL))
368    return false;
369
370  mDepOutputFileName = OutputFile;
371
372  return true;
373}
374
375int Slang::generateDepFile() {
376  if (mDiagEngine->hasErrorOccurred())
377    return 1;
378  if (mDOS.get() == NULL)
379    return 1;
380
381  // Initialize options for generating dependency file
382  clang::DependencyOutputOptions DepOpts;
383  DepOpts.IncludeSystemHeaders = 1;
384  DepOpts.OutputFile = mDepOutputFileName;
385  DepOpts.Targets = mAdditionalDepTargets;
386  DepOpts.Targets.push_back(mDepTargetBCFileName);
387  for (std::vector<std::string>::const_iterator
388           I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end();
389       I != E;
390       I++) {
391    DepOpts.Targets.push_back(*I);
392  }
393  mGeneratedFileNames.clear();
394
395  // Per-compilation needed initialization
396  createPreprocessor();
397  AttachDependencyFileGen(*mPP.get(), DepOpts);
398
399  // Inform the diagnostic client we are processing a source file
400  mDiagClient->BeginSourceFile(LangOpts, mPP.get());
401
402  // Go through the source file (no operations necessary)
403  clang::Token Tok;
404  mPP->EnterMainSourceFile();
405  do {
406    mPP->Lex(Tok);
407  } while (Tok.isNot(clang::tok::eof));
408
409  mPP->EndSourceFile();
410
411  // Declare success if no error
412  if (!mDiagEngine->hasErrorOccurred())
413    mDOS->keep();
414
415  // Clean up after compilation
416  mPP.reset();
417  mDOS.reset();
418
419  return mDiagEngine->hasErrorOccurred() ? 1 : 0;
420}
421
422int Slang::compile() {
423  if (mDiagEngine->hasErrorOccurred())
424    return 1;
425  if (mOS.get() == NULL)
426    return 1;
427
428  // Here is per-compilation needed initialization
429  createPreprocessor();
430  createASTContext();
431
432  mBackend.reset(createBackend(CodeGenOpts, &mOS->os(), mOT));
433
434  // Inform the diagnostic client we are processing a source file
435  mDiagClient->BeginSourceFile(LangOpts, mPP.get());
436
437  // The core of the slang compiler
438  ParseAST(*mPP, mBackend.get(), *mASTContext);
439
440  // Inform the diagnostic client we are done with previous source file
441  mDiagClient->EndSourceFile();
442
443  // Declare success if no error
444  if (!mDiagEngine->hasErrorOccurred())
445    mOS->keep();
446
447  // The compilation ended, clear
448  mBackend.reset();
449  mASTContext.reset();
450  mPP.reset();
451  mOS.reset();
452
453  return mDiagEngine->hasErrorOccurred() ? 1 : 0;
454}
455
456void Slang::setDebugMetadataEmission(bool EmitDebug) {
457  CodeGenOpts.DebugInfo = EmitDebug;
458}
459
460void Slang::setOptimizationLevel(llvm::CodeGenOpt::Level OptimizationLevel) {
461  CodeGenOpts.OptimizationLevel = OptimizationLevel;
462}
463
464void Slang::reset() {
465  llvm::errs() << mDiagClient->str();
466  mDiagEngine->Reset();
467  mDiagClient->reset();
468}
469
470Slang::~Slang() {
471  llvm::llvm_shutdown();
472}
473
474}  // namespace slang
475