slang.cpp revision 4c622e0953afe3dca4da0aee364a811f3ccb61d9
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{ 122 slangAssert((OutputFile != NULL) && (Error != NULL) && 123 (DiagEngine != NULL) && "Invalid parameter!"); 124 125 if (SlangUtils::CreateDirectoryWithParents( 126 llvm::sys::path::parent_path(OutputFile), Error)) { 127 llvm::tool_output_file *F = 128 new llvm::tool_output_file(OutputFile, *Error, Flags); 129 if (F != NULL) 130 return F; 131 } 132 133 // Report error here. 134 DiagEngine->Report(clang::diag::err_fe_error_opening) 135 << 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 166void Slang::LLVMErrorHandler(void *UserData, const std::string &Message) { 167 clang::DiagnosticsEngine* DiagEngine = 168 static_cast<clang::DiagnosticsEngine *>(UserData); 169 170 DiagEngine->Report(clang::diag::err_fe_error_backend) << Message; 171 exit(1); 172} 173 174void Slang::createDiagnostic() { 175 mDiagClient = new DiagnosticBuffer(); 176 177 mDiagIDs = new clang::DiagnosticIDs(); 178 mDiagEngine = new clang::DiagnosticsEngine(mDiagIDs, mDiagClient, true); 179 mDiag.reset(new clang::Diagnostic(mDiagEngine.getPtr())); 180 181 initDiagnostic(); 182} 183 184void Slang::createTarget(const std::string &Triple, const std::string &CPU, 185 const std::vector<std::string> &Features) { 186 if (!Triple.empty()) 187 mTargetOpts.Triple = Triple; 188 else 189 mTargetOpts.Triple = DEFAULT_TARGET_TRIPLE_STRING; 190 191 if (!CPU.empty()) 192 mTargetOpts.CPU = CPU; 193 194 if (!Features.empty()) 195 mTargetOpts.Features = Features; 196 197 mTarget.reset(clang::TargetInfo::CreateTargetInfo(*mDiagEngine, 198 mTargetOpts)); 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(*mDiagEngine, *mFileMgr)); 208} 209 210void Slang::createPreprocessor() { 211 // Default only search header file in current dir 212 clang::HeaderSearch *HeaderInfo = new clang::HeaderSearch(*mFileMgr, 213 *mDiagEngine); 214 215 mPP.reset(new clang::Preprocessor(*mDiagEngine, 216 LangOpts, 217 mTarget.get(), 218 *mSourceMgr, 219 *HeaderInfo, 220 *this, 221 NULL, 222 /* OwnsHeaderSearch = */true)); 223 // Initialize the preprocessor 224 mPragmas.clear(); 225 mPP->AddPragmaHandler(new PragmaRecorder(&mPragmas)); 226 227 std::vector<clang::DirectoryLookup> SearchList; 228 for (unsigned i = 0, e = mIncludePaths.size(); i != e; i++) { 229 if (const clang::DirectoryEntry *DE = 230 mFileMgr->getDirectory(mIncludePaths[i])) { 231 SearchList.push_back(clang::DirectoryLookup(DE, 232 clang::SrcMgr::C_System, 233 false, 234 false)); 235 } 236 } 237 238 HeaderInfo->SetSearchPaths(SearchList, 239 /* angledDirIdx = */1, 240 /* systemDixIdx = */1, 241 /* noCurDirSearch = */false); 242 243 initPreprocessor(); 244} 245 246void Slang::createASTContext() { 247 mASTContext.reset(new clang::ASTContext(LangOpts, 248 *mSourceMgr, 249 mTarget.get(), 250 mPP->getIdentifierTable(), 251 mPP->getSelectorTable(), 252 mPP->getBuiltinInfo(), 253 /* size_reserve = */0)); 254 initASTContext(); 255} 256 257clang::ASTConsumer * 258Slang::createBackend(const clang::CodeGenOptions& CodeGenOpts, 259 llvm::raw_ostream *OS, OutputType OT) { 260 return new Backend(mDiagEngine.getPtr(), CodeGenOpts, mTargetOpts, 261 &mPragmas, OS, OT); 262} 263 264Slang::Slang() : mInitialized(false), mDiagClient(NULL), mOT(OT_Default) { 265 GlobalInitialization(); 266} 267 268void Slang::init(const std::string &Triple, const std::string &CPU, 269 const std::vector<std::string> &Features) { 270 if (mInitialized) 271 return; 272 273 createDiagnostic(); 274 llvm::install_fatal_error_handler(LLVMErrorHandler, mDiagEngine.getPtr()); 275 276 createTarget(Triple, CPU, Features); 277 createFileManager(); 278 createSourceManager(); 279 280 mInitialized = true; 281} 282 283clang::ModuleKey Slang::loadModule(clang::SourceLocation ImportLoc, 284 clang::IdentifierInfo &ModuleName, 285 clang::SourceLocation ModuleNameLoc) { 286 //FIXME: Don't we have to implement this? 287 slangAssert(0 && "Not implemented"); 288 return NULL; 289} 290 291bool Slang::setInputSource(llvm::StringRef InputFile, 292 const char *Text, 293 size_t TextLength) { 294 mInputFileName = InputFile.str(); 295 296 // Reset the ID tables if we are reusing the SourceManager 297 mSourceMgr->clearIDTables(); 298 299 // Load the source 300 llvm::MemoryBuffer *SB = 301 llvm::MemoryBuffer::getMemBuffer(Text, Text + TextLength); 302 mSourceMgr->createMainFileIDForMemBuffer(SB); 303 304 if (mSourceMgr->getMainFileID().isInvalid()) { 305 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 306 return false; 307 } 308 return true; 309} 310 311bool Slang::setInputSource(llvm::StringRef InputFile) { 312 mInputFileName = InputFile.str(); 313 314 mSourceMgr->clearIDTables(); 315 316 const clang::FileEntry *File = mFileMgr->getFile(InputFile); 317 if (File) 318 mSourceMgr->createMainFileID(File); 319 320 if (mSourceMgr->getMainFileID().isInvalid()) { 321 mDiagEngine->Report(clang::diag::err_fe_error_reading) << InputFile; 322 return false; 323 } 324 325 return true; 326} 327 328bool Slang::setOutput(const char *OutputFile) { 329 llvm::sys::Path OutputFilePath(OutputFile); 330 std::string Error; 331 llvm::tool_output_file *OS = NULL; 332 333 switch (mOT) { 334 case OT_Dependency: 335 case OT_Assembly: 336 case OT_LLVMAssembly: { 337 OS = OpenOutputFile(OutputFile, 0, &Error, mDiagEngine.getPtr()); 338 break; 339 } 340 case OT_Nothing: { 341 break; 342 } 343 case OT_Object: 344 case OT_Bitcode: { 345 OS = OpenOutputFile(OutputFile, llvm::raw_fd_ostream::F_Binary, 346 &Error, mDiagEngine.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, mDiagEngine.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 (mDiagEngine->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 (!mDiagEngine->hasErrorOccurred()) 415 mDOS->keep(); 416 417 // Clean up after compilation 418 mPP.reset(); 419 mDOS.reset(); 420 421 return mDiagEngine->hasErrorOccurred() ? 1 : 0; 422} 423 424int Slang::compile() { 425 if (mDiagEngine->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 (!mDiagEngine->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 mDiagEngine->hasErrorOccurred() ? 1 : 0; 456} 457 458void Slang::reset() { 459 llvm::errs() << mDiagClient->str(); 460 mDiagEngine->Reset(); 461 mDiagClient->reset(); 462} 463 464Slang::~Slang() { 465 llvm::llvm_shutdown(); 466} 467 468} // namespace slang 469