slang.cpp revision 6f4e0a9955a53a6f715af7e674e68ed15270a47c
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 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 Diag->Report(clang::diag::err_fe_error_opening) << OutputFile << *Error; 134 135 return NULL; 136} 137 138void Slang::GlobalInitialization() { 139 if (!GlobalInitialized) { 140 // We only support x86, x64 and ARM target 141 142 // For ARM 143 LLVMInitializeARMTargetInfo(); 144 LLVMInitializeARMTarget(); 145 LLVMInitializeARMAsmPrinter(); 146 147 // For x86 and x64 148 LLVMInitializeX86TargetInfo(); 149 LLVMInitializeX86Target(); 150 LLVMInitializeX86AsmPrinter(); 151 152 // Please refer to include/clang/Basic/LangOptions.h to setup 153 // the options. 154 LangOpts.RTTI = 0; // Turn off the RTTI information support 155 LangOpts.NeXTRuntime = 0; // Turn off the NeXT runtime uses 156 LangOpts.C99 = 1; 157 158 CodeGenOpts.OptimizationLevel = 3; /* -O3 */ 159 160 GlobalInitialized = true; 161 } 162 163 return; 164} 165 166void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) { 167 clang::Diagnostic* Diags = static_cast<clang::Diagnostic*>(UserData); 168 Diags->Report(clang::diag::err_fe_error_backend) << Message; 169 exit(1); 170} 171 172void Slang::createDiagnostic() { 173 mDiagClient = new DiagnosticBuffer(); 174 mDiagIDs = new clang::DiagnosticIDs(); 175 mDiagnostics = new clang::Diagnostic(mDiagIDs, mDiagClient, true); 176 initDiagnostic(); 177 return; 178} 179 180void Slang::createTarget(const std::string &Triple, const std::string &CPU, 181 const std::vector<std::string> &Features) { 182 if (!Triple.empty()) 183 mTargetOpts.Triple = Triple; 184 else 185 mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING; 186 187 if (!CPU.empty()) 188 mTargetOpts.CPU = CPU; 189 190 if (!Features.empty()) 191 mTargetOpts.Features = Features; 192 193 mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagnostics, 194 mTargetOpts)); 195 196 return; 197} 198 199void Slang::createFileManager() { 200 mFileSysOpt.reset(new clang::FileSystemOptions()); 201 mFileMgr.reset(new clang::FileManager(*mFileSysOpt)); 202} 203 204void Slang::createSourceManager() { 205 mSourceMgr.reset(new clang::SourceManager(*mDiagnostics, *mFileMgr)); 206 return; 207} 208 209void Slang::createPreprocessor() { 210 // Default only search header file in current dir 211 clang::HeaderSearch *HS = new clang::HeaderSearch(*mFileMgr); 212 213 mPP.reset(new clang::Preprocessor(*mDiagnostics, 214 LangOpts, 215 *mTarget, 216 *mSourceMgr, 217 *HS, 218 NULL, 219 /* OwnsHeaderSearch = */true)); 220 // Initialize the preprocessor 221 mPragmas.clear(); 222 mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas)); 223 224 std::vector<clang::DirectoryLookup> SearchList; 225 for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) { 226 if (const clang::DirectoryEntry *DE = 227 mFileMgr->getDirectory(mIncludePaths[i])) { 228 SearchList.push_back(clang::DirectoryLookup(DE, 229 clang::SrcMgr::C_System, 230 false, 231 false)); 232 } 233 } 234 235 HS->SetSearchPaths(SearchList, 1, false); 236 237 initPreprocessor(); 238 return; 239} 240 241void Slang::createASTContext() { 242 mASTContext.reset(new clang::ASTContext(LangOpts, 243 *mSourceMgr, 244 *mTarget, 245 mPP->getIdentifierTable(), 246 mPP->getSelectorTable(), 247 mPP->getBuiltinInfo(), 248 /* size_reserve = */0)); 249 initASTContext(); 250 return; 251} 252 253clang::ASTConsumer 254*Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts, 255 llvm::raw_ostream *OS, 256 OutputType OT) { 257 return new Backend(mDiagnostics.getPtr(), 258 CodeGenOpts, 259 mTargetOpts, 260 &mPragmas, 261 OS, 262 OT); 263} 264 265Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) { 266 GlobalInitialization(); 267 return; 268} 269 270void Slang::init(const std::string &Triple, const std::string &CPU, 271 const std::vector<std::string> &Features) { 272 if (mInitialized) 273 return; 274 275 createDiagnostic(); 276 llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagnostics.getPtr()); 277 278 createTarget(Triple, CPU, Features); 279 createFileManager(); 280 createSourceManager(); 281 282 mInitialized = true; 283 284 return; 285} 286 287bool Slang::setInputSource(llvm::StringRef InputFile, 288 const char *Text, 289 size_t TextLength) { 290 mInputFileName = InputFile.str(); 291 292 // Reset the ID tables if we are reusing the SourceManager 293 mSourceMgr->clearIDTables(); 294 295 // Load the source 296 llvm::MemoryBuffer *SB = 297 llvm::MemoryBuffer::getMemBuffer(Text, Text + TextLength); 298 mSourceMgr->createMainFileIDForMemBuffer(SB); 299 300 if (mSourceMgr->getMainFileID().isInvalid()) { 301 mDiagnostics->Report(clang::diag::err_fe_error_reading) << InputFile; 302 return false; 303 } 304 return true; 305} 306 307bool Slang::setInputSource(llvm::StringRef InputFile) { 308 mInputFileName = InputFile.str(); 309 310 mSourceMgr->clearIDTables(); 311 312 const clang::FileEntry *File = mFileMgr->getFile(InputFile); 313 if (File) 314 mSourceMgr->createMainFileID(File); 315 316 if (mSourceMgr->getMainFileID().isInvalid()) { 317 mDiagnostics->Report(clang::diag::err_fe_error_reading) << InputFile; 318 return false; 319 } 320 321 return true; 322} 323 324bool Slang::setOutput(const char *OutputFile) { 325 llvm::sys::Path OutputFilePath(OutputFile); 326 std::string Error; 327 llvm::tool_output_file *OS = NULL; 328 329 switch (mOT) { 330 case OT_Dependency: 331 case OT_Assembly: 332 case OT_LLVMAssembly: { 333 OS = OpenOutputFile(OutputFile, 0, &Error, mDiagnostics.getPtr()); 334 break; 335 } 336 case OT_Nothing: { 337 break; 338 } 339 case OT_Object: 340 case OT_Bitcode: { 341 OS = OpenOutputFile(OutputFile, 342 llvm::raw_fd_ostream::F_Binary, 343 &Error, 344 mDiagnostics.getPtr()); 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, mDiagnostics.getPtr())); 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 (mDiagnostics->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 (!mDiagnostics->hasErrorOccurred()) 413 mDOS->keep(); 414 415 // Clean up after compilation 416 mPP.reset(); 417 mDOS.reset(); 418 419 return mDiagnostics->hasErrorOccurred() ? 1 : 0; 420} 421 422int Slang::compile() { 423 if (mDiagnostics->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 (!mDiagnostics->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 mDiagnostics->hasErrorOccurred() ? 1 : 0; 454} 455 456void Slang::reset() { 457 mDiagnostics->Reset(); 458 mDiagClient->reset(); 459 return; 460} 461 462Slang::~Slang() { 463 llvm::llvm_shutdown(); 464 return; 465} 466 467} // namespace slang 468