slang.cpp revision e67239de8d94975e7e2216ee6860ae2e6cb8b15a
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 159 CodeGenOpts.OptimizationLevel = 3; /* -O3 */ 160 161 GlobalInitialized = true; 162 } 163} 164 165void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) { 166 clang::DiagnosticsEngine* DiagEngine = 167 static_cast<clang::DiagnosticsEngine *>(UserData); 168 169 DiagEngine->Report(clang::diag::err_fe_error_backend) << Message; 170 exit(1); 171} 172 173void Slang::createTarget(const std::string &Triple, const std::string &CPU, 174 const std::vector<std::string> &Features) { 175 if (!Triple.empty()) 176 mTargetOpts.Triple = Triple; 177 else 178 mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING; 179 180 if (!CPU.empty()) 181 mTargetOpts.CPU = CPU; 182 183 if (!Features.empty()) 184 mTargetOpts.Features = Features; 185 186 mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine, 187 mTargetOpts)); 188} 189 190void Slang::createFileManager() { 191 mFileSysOpt.reset(new clang::FileSystemOptions()); 192 mFileMgr.reset(new clang::FileManager(*mFileSysOpt)); 193} 194 195void Slang::createSourceManager() { 196 mSourceMgr.reset(new clang::SourceManager(*mDiagEngine, *mFileMgr)); 197} 198 199void Slang::createPreprocessor() { 200 // Default only search header file in current dir 201 clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(*mFileMgr, 202 *mDiagEngine); 203 204 mPP.reset(new clang::Preprocessor(*mDiagEngine, 205 LangOpts, 206 mTarget.get(), 207 *mSourceMgr, 208 *HeaderInfo, 209 *this, 210 NULL, 211 /* OwnsHeaderSearch = */true)); 212 // Initialize the preprocessor 213 mPragmas.clear(); 214 mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas)); 215 216 std::vector<clang::DirectoryLookup> SearchList; 217 for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) { 218 if (const clang::DirectoryEntry *DE = 219 mFileMgr->getDirectory(mIncludePaths[i])) { 220 SearchList.push_back(clang::DirectoryLookup(DE, 221 clang::SrcMgr::C_System, 222 false, 223 false)); 224 } 225 } 226 227 HeaderInfo->SetSearchPaths(SearchList, 228 /* angledDirIdx = */1, 229 /* systemDixIdx = */1, 230 /* noCurDirSearch = */false); 231 232 initPreprocessor(); 233} 234 235void Slang::createASTContext() { 236 mASTContext.reset(new clang::ASTContext(LangOpts, 237 *mSourceMgr, 238 mTarget.get(), 239 mPP->getIdentifierTable(), 240 mPP->getSelectorTable(), 241 mPP->getBuiltinInfo(), 242 /* size_reserve = */0)); 243 initASTContext(); 244} 245 246clang::ASTConsumer * 247Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts, 248 llvm::raw_ostream *OS, OutputType OT) { 249 return new Backend(mDiagEngine, CodeGenOpts, mTargetOpts, 250 &mPragmas, OS, OT); 251} 252 253Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) { 254 GlobalInitialization(); 255} 256 257void Slang::init(const std::string &Triple, const std::string &CPU, 258 const std::vector<std::string> &Features, 259 clang::DiagnosticsEngine *DiagEngine, 260 DiagnosticBuffer *DiagClient) { 261 if (mInitialized) 262 return; 263 264 mDiagEngine = DiagEngine; 265 mDiagClient = DiagClient; 266 mDiag.reset(new clang::Diagnostic(mDiagEngine)); 267 initDiagnostic(); 268 llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagEngine); 269 270 createTarget(Triple, CPU, Features); 271 createFileManager(); 272 createSourceManager(); 273 274 mInitialized = true; 275} 276 277clang::Module *Slang::loadModule(clang::SourceLocation ImportLoc, 278 clang::ModuleIdPath Path, 279 clang::Module::NameVisibilityKind Visibility, 280 bool IsInclusionDirective) { 281 slangAssert(0 && "Not implemented"); 282 return NULL; 283} 284 285bool Slang::setInputSource(llvm::StringRef InputFile, 286 const char *Text, 287 size_t TextLength) { 288 mInputFileName = InputFile.str(); 289 290 // Reset the ID tables if we are reusing the SourceManager 291 mSourceMgr->clearIDTables(); 292 293 // Load the source 294 llvm::MemoryBuffer *SB = 295 llvm::MemoryBuffer::getMemBuffer(Text, Text + TextLength); 296 mSourceMgr->createMainFileIDForMemBuffer(SB); 297 298 if (mSourceMgr->getMainFileID().isInvalid()) { 299 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 300 return false; 301 } 302 return true; 303} 304 305bool Slang::setInputSource(llvm::StringRef InputFile) { 306 mInputFileName = InputFile.str(); 307 308 mSourceMgr->clearIDTables(); 309 310 const clang::FileEntry *File = mFileMgr->getFile(InputFile); 311 if (File) 312 mSourceMgr->createMainFileID(File); 313 314 if (mSourceMgr->getMainFileID().isInvalid()) { 315 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 316 return false; 317 } 318 319 return true; 320} 321 322bool Slang::setOutput(const char *OutputFile) { 323 llvm::sys::Path OutputFilePath(OutputFile); 324 std::string Error; 325 llvm::tool_output_file *OS = NULL; 326 327 switch (mOT) { 328 case OT_Dependency: 329 case OT_Assembly: 330 case OT_LLVMAssembly: { 331 OS = OpenOutputFile(OutputFile, 0, &Error, mDiagEngine); 332 break; 333 } 334 case OT_Nothing: { 335 break; 336 } 337 case OT_Object: 338 case OT_Bitcode: { 339 OS = OpenOutputFile(OutputFile, llvm::raw_fd_ostream::F_Binary, 340 &Error, mDiagEngine); 341 break; 342 } 343 default: { 344 llvm_unreachable("Unknown compiler output type"); 345 } 346 } 347 348 if (!Error.empty()) 349 return false; 350 351 mOS.reset(OS); 352 353 mOutputFileName = OutputFile; 354 355 return true; 356} 357 358bool Slang::setDepOutput(const char *OutputFile) { 359 llvm::sys::Path OutputFilePath(OutputFile); 360 std::string Error; 361 362 mDOS.reset(OpenOutputFile(OutputFile, 0, &Error, mDiagEngine)); 363 if (!Error.empty() || (mDOS.get() == NULL)) 364 return false; 365 366 mDepOutputFileName = OutputFile; 367 368 return true; 369} 370 371int Slang::generateDepFile() { 372 if (mDiagEngine->hasErrorOccurred()) 373 return 1; 374 if (mDOS.get() == NULL) 375 return 1; 376 377 // Initialize options for generating dependency file 378 clang::DependencyOutputOptions DepOpts; 379 DepOpts.IncludeSystemHeaders = 1; 380 DepOpts.OutputFile = mDepOutputFileName; 381 DepOpts.Targets = mAdditionalDepTargets; 382 DepOpts.Targets.push_back(mDepTargetBCFileName); 383 for (std::vector<std::string>::const_iterator 384 I = mGeneratedFileNames.begin(), E = mGeneratedFileNames.end(); 385 I != E; 386 I++) { 387 DepOpts.Targets.push_back(*I); 388 } 389 mGeneratedFileNames.clear(); 390 391 // Per-compilation needed initialization 392 createPreprocessor(); 393 AttachDependencyFileGen(*mPP.get(), DepOpts); 394 395 // Inform the diagnostic client we are processing a source file 396 mDiagClient->BeginSourceFile(LangOpts, mPP.get()); 397 398 // Go through the source file (no operations necessary) 399 clang::Token Tok; 400 mPP->EnterMainSourceFile(); 401 do { 402 mPP->Lex(Tok); 403 } while (Tok.isNot(clang::tok::eof)); 404 405 mPP->EndSourceFile(); 406 407 // Declare success if no error 408 if (!mDiagEngine->hasErrorOccurred()) 409 mDOS->keep(); 410 411 // Clean up after compilation 412 mPP.reset(); 413 mDOS.reset(); 414 415 return mDiagEngine->hasErrorOccurred() ? 1 : 0; 416} 417 418int Slang::compile() { 419 if (mDiagEngine->hasErrorOccurred()) 420 return 1; 421 if (mOS.get() == NULL) 422 return 1; 423 424 // Here is per-compilation needed initialization 425 createPreprocessor(); 426 createASTContext(); 427 428 mBackend.reset(createBackend(CodeGenOpts, &mOS->os(), mOT)); 429 430 // Inform the diagnostic client we are processing a source file 431 mDiagClient->BeginSourceFile(LangOpts, mPP.get()); 432 433 // The core of the slang compiler 434 ParseAST(*mPP, mBackend.get(), *mASTContext); 435 436 // Inform the diagnostic client we are done with previous source file 437 mDiagClient->EndSourceFile(); 438 439 // Declare success if no error 440 if (!mDiagEngine->hasErrorOccurred()) 441 mOS->keep(); 442 443 // The compilation ended, clear 444 mBackend.reset(); 445 mASTContext.reset(); 446 mPP.reset(); 447 mOS.reset(); 448 449 return mDiagEngine->hasErrorOccurred() ? 1 : 0; 450} 451 452void Slang::reset() { 453 llvm::errs() << mDiagClient->str(); 454 mDiagEngine->Reset(); 455 mDiagClient->reset(); 456} 457 458Slang::~Slang() { 459 llvm::llvm_shutdown(); 460} 461 462} // namespace slang 463