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