ASTUnit.cpp revision 03201fbbdeb3eb7f465610b09c281ee6aa84e3ca
1//===--- ASTUnit.cpp - ASTUnit utility ------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// ASTUnit Implementation. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Frontend/ASTUnit.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/DeclVisitor.h" 18#include "clang/AST/TypeOrdering.h" 19#include "clang/AST/StmtVisitor.h" 20#include "clang/Driver/Compilation.h" 21#include "clang/Driver/Driver.h" 22#include "clang/Driver/Job.h" 23#include "clang/Driver/ArgList.h" 24#include "clang/Driver/Options.h" 25#include "clang/Driver/Tool.h" 26#include "clang/Frontend/CompilerInstance.h" 27#include "clang/Frontend/FrontendActions.h" 28#include "clang/Frontend/FrontendDiagnostic.h" 29#include "clang/Frontend/FrontendOptions.h" 30#include "clang/Frontend/Utils.h" 31#include "clang/Serialization/ASTReader.h" 32#include "clang/Serialization/ASTSerializationListener.h" 33#include "clang/Serialization/ASTWriter.h" 34#include "clang/Lex/HeaderSearch.h" 35#include "clang/Lex/Preprocessor.h" 36#include "clang/Basic/TargetOptions.h" 37#include "clang/Basic/TargetInfo.h" 38#include "clang/Basic/Diagnostic.h" 39#include "llvm/ADT/StringExtras.h" 40#include "llvm/ADT/StringSet.h" 41#include "llvm/Support/Atomic.h" 42#include "llvm/Support/MemoryBuffer.h" 43#include "llvm/Support/Host.h" 44#include "llvm/Support/Path.h" 45#include "llvm/Support/raw_ostream.h" 46#include "llvm/Support/Timer.h" 47#include "llvm/Support/CrashRecoveryContext.h" 48#include <cstdlib> 49#include <cstdio> 50#include <sys/stat.h> 51using namespace clang; 52 53using llvm::TimeRecord; 54 55namespace { 56 class SimpleTimer { 57 bool WantTiming; 58 TimeRecord Start; 59 std::string Output; 60 61 public: 62 explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) { 63 if (WantTiming) 64 Start = TimeRecord::getCurrentTime(); 65 } 66 67 void setOutput(const llvm::Twine &Output) { 68 if (WantTiming) 69 this->Output = Output.str(); 70 } 71 72 ~SimpleTimer() { 73 if (WantTiming) { 74 TimeRecord Elapsed = TimeRecord::getCurrentTime(); 75 Elapsed -= Start; 76 llvm::errs() << Output << ':'; 77 Elapsed.print(Elapsed, llvm::errs()); 78 llvm::errs() << '\n'; 79 } 80 } 81 }; 82} 83 84/// \brief After failing to build a precompiled preamble (due to 85/// errors in the source that occurs in the preamble), the number of 86/// reparses during which we'll skip even trying to precompile the 87/// preamble. 88const unsigned DefaultPreambleRebuildInterval = 5; 89 90/// \brief Tracks the number of ASTUnit objects that are currently active. 91/// 92/// Used for debugging purposes only. 93static llvm::sys::cas_flag ActiveASTUnitObjects; 94 95ASTUnit::ASTUnit(bool _MainFileIsAST) 96 : OnlyLocalDecls(false), CaptureDiagnostics(false), 97 MainFileIsAST(_MainFileIsAST), 98 CompleteTranslationUnit(true), WantTiming(getenv("LIBCLANG_TIMING")), 99 OwnsRemappedFileBuffers(true), 100 NumStoredDiagnosticsFromDriver(0), 101 ConcurrencyCheckValue(CheckUnlocked), 102 PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0), 103 ShouldCacheCodeCompletionResults(false), 104 CompletionCacheTopLevelHashValue(0), 105 PreambleTopLevelHashValue(0), 106 CurrentTopLevelHashValue(0), 107 UnsafeToFree(false) { 108 if (getenv("LIBCLANG_OBJTRACKING")) { 109 llvm::sys::AtomicIncrement(&ActiveASTUnitObjects); 110 fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects); 111 } 112} 113 114ASTUnit::~ASTUnit() { 115 ConcurrencyCheckValue = CheckLocked; 116 CleanTemporaryFiles(); 117 if (!PreambleFile.empty()) 118 llvm::sys::Path(PreambleFile).eraseFromDisk(); 119 120 // Free the buffers associated with remapped files. We are required to 121 // perform this operation here because we explicitly request that the 122 // compiler instance *not* free these buffers for each invocation of the 123 // parser. 124 if (Invocation.get() && OwnsRemappedFileBuffers) { 125 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 126 for (PreprocessorOptions::remapped_file_buffer_iterator 127 FB = PPOpts.remapped_file_buffer_begin(), 128 FBEnd = PPOpts.remapped_file_buffer_end(); 129 FB != FBEnd; 130 ++FB) 131 delete FB->second; 132 } 133 134 delete SavedMainFileBuffer; 135 delete PreambleBuffer; 136 137 ClearCachedCompletionResults(); 138 139 if (getenv("LIBCLANG_OBJTRACKING")) { 140 llvm::sys::AtomicDecrement(&ActiveASTUnitObjects); 141 fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects); 142 } 143} 144 145void ASTUnit::CleanTemporaryFiles() { 146 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) 147 TemporaryFiles[I].eraseFromDisk(); 148 TemporaryFiles.clear(); 149} 150 151/// \brief Determine the set of code-completion contexts in which this 152/// declaration should be shown. 153static unsigned getDeclShowContexts(NamedDecl *ND, 154 const LangOptions &LangOpts, 155 bool &IsNestedNameSpecifier) { 156 IsNestedNameSpecifier = false; 157 158 if (isa<UsingShadowDecl>(ND)) 159 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl()); 160 if (!ND) 161 return 0; 162 163 unsigned Contexts = 0; 164 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 165 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) { 166 // Types can appear in these contexts. 167 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)) 168 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 169 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 170 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 171 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 172 | (1 << (CodeCompletionContext::CCC_Type - 1)) 173 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)); 174 175 // In C++, types can appear in expressions contexts (for functional casts). 176 if (LangOpts.CPlusPlus) 177 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1)); 178 179 // In Objective-C, message sends can send interfaces. In Objective-C++, 180 // all types are available due to functional casts. 181 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)) 182 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 183 184 // Deal with tag names. 185 if (isa<EnumDecl>(ND)) { 186 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)); 187 188 // Part of the nested-name-specifier in C++0x. 189 if (LangOpts.CPlusPlus0x) 190 IsNestedNameSpecifier = true; 191 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) { 192 if (Record->isUnion()) 193 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1)); 194 else 195 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 196 197 if (LangOpts.CPlusPlus) 198 IsNestedNameSpecifier = true; 199 } else if (isa<ClassTemplateDecl>(ND)) 200 IsNestedNameSpecifier = true; 201 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 202 // Values can appear in these contexts. 203 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1)) 204 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 205 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 206 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 207 } else if (isa<ObjCProtocolDecl>(ND)) { 208 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)); 209 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) { 210 Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1)); 211 212 // Part of the nested-name-specifier. 213 IsNestedNameSpecifier = true; 214 } 215 216 return Contexts; 217} 218 219void ASTUnit::CacheCodeCompletionResults() { 220 if (!TheSema) 221 return; 222 223 SimpleTimer Timer(WantTiming); 224 Timer.setOutput("Cache global code completions for " + getMainFileName()); 225 226 // Clear out the previous results. 227 ClearCachedCompletionResults(); 228 229 // Gather the set of global code completions. 230 typedef CodeCompletionResult Result; 231 llvm::SmallVector<Result, 8> Results; 232 CachedCompletionAllocator = new GlobalCodeCompletionAllocator; 233 TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results); 234 235 // Translate global code completions into cached completions. 236 llvm::DenseMap<CanQualType, unsigned> CompletionTypes; 237 238 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 239 switch (Results[I].Kind) { 240 case Result::RK_Declaration: { 241 bool IsNestedNameSpecifier = false; 242 CachedCodeCompletionResult CachedResult; 243 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema, 244 *CachedCompletionAllocator); 245 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration, 246 Ctx->getLangOptions(), 247 IsNestedNameSpecifier); 248 CachedResult.Priority = Results[I].Priority; 249 CachedResult.Kind = Results[I].CursorKind; 250 CachedResult.Availability = Results[I].Availability; 251 252 // Keep track of the type of this completion in an ASTContext-agnostic 253 // way. 254 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration); 255 if (UsageType.isNull()) { 256 CachedResult.TypeClass = STC_Void; 257 CachedResult.Type = 0; 258 } else { 259 CanQualType CanUsageType 260 = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); 261 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); 262 263 // Determine whether we have already seen this type. If so, we save 264 // ourselves the work of formatting the type string by using the 265 // temporary, CanQualType-based hash table to find the associated value. 266 unsigned &TypeValue = CompletionTypes[CanUsageType]; 267 if (TypeValue == 0) { 268 TypeValue = CompletionTypes.size(); 269 CachedCompletionTypes[QualType(CanUsageType).getAsString()] 270 = TypeValue; 271 } 272 273 CachedResult.Type = TypeValue; 274 } 275 276 CachedCompletionResults.push_back(CachedResult); 277 278 /// Handle nested-name-specifiers in C++. 279 if (TheSema->Context.getLangOptions().CPlusPlus && 280 IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) { 281 // The contexts in which a nested-name-specifier can appear in C++. 282 unsigned NNSContexts 283 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 284 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 285 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 286 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 287 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 288 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 289 | (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 290 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 291 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)) 292 | (1 << (CodeCompletionContext::CCC_Type - 1)) 293 | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1)) 294 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)); 295 296 if (isa<NamespaceDecl>(Results[I].Declaration) || 297 isa<NamespaceAliasDecl>(Results[I].Declaration)) 298 NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1)); 299 300 if (unsigned RemainingContexts 301 = NNSContexts & ~CachedResult.ShowInContexts) { 302 // If there any contexts where this completion can be a 303 // nested-name-specifier but isn't already an option, create a 304 // nested-name-specifier completion. 305 Results[I].StartsNestedNameSpecifier = true; 306 CachedResult.Completion 307 = Results[I].CreateCodeCompletionString(*TheSema, 308 *CachedCompletionAllocator); 309 CachedResult.ShowInContexts = RemainingContexts; 310 CachedResult.Priority = CCP_NestedNameSpecifier; 311 CachedResult.TypeClass = STC_Void; 312 CachedResult.Type = 0; 313 CachedCompletionResults.push_back(CachedResult); 314 } 315 } 316 break; 317 } 318 319 case Result::RK_Keyword: 320 case Result::RK_Pattern: 321 // Ignore keywords and patterns; we don't care, since they are so 322 // easily regenerated. 323 break; 324 325 case Result::RK_Macro: { 326 CachedCodeCompletionResult CachedResult; 327 CachedResult.Completion 328 = Results[I].CreateCodeCompletionString(*TheSema, 329 *CachedCompletionAllocator); 330 CachedResult.ShowInContexts 331 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 332 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 333 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 334 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 335 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 336 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 337 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 338 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 339 | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1)) 340 | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1)) 341 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 342 | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1)); 343 344 CachedResult.Priority = Results[I].Priority; 345 CachedResult.Kind = Results[I].CursorKind; 346 CachedResult.Availability = Results[I].Availability; 347 CachedResult.TypeClass = STC_Void; 348 CachedResult.Type = 0; 349 CachedCompletionResults.push_back(CachedResult); 350 break; 351 } 352 } 353 } 354 355 // Save the current top-level hash value. 356 CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue; 357} 358 359void ASTUnit::ClearCachedCompletionResults() { 360 CachedCompletionResults.clear(); 361 CachedCompletionTypes.clear(); 362 CachedCompletionAllocator = 0; 363} 364 365namespace { 366 367/// \brief Gathers information from ASTReader that will be used to initialize 368/// a Preprocessor. 369class ASTInfoCollector : public ASTReaderListener { 370 LangOptions &LangOpt; 371 HeaderSearch &HSI; 372 std::string &TargetTriple; 373 std::string &Predefines; 374 unsigned &Counter; 375 376 unsigned NumHeaderInfos; 377 378public: 379 ASTInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, 380 std::string &TargetTriple, std::string &Predefines, 381 unsigned &Counter) 382 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), 383 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} 384 385 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { 386 LangOpt = LangOpts; 387 return false; 388 } 389 390 virtual bool ReadTargetTriple(llvm::StringRef Triple) { 391 TargetTriple = Triple; 392 return false; 393 } 394 395 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers, 396 llvm::StringRef OriginalFileName, 397 std::string &SuggestedPredefines, 398 FileManager &FileMgr) { 399 Predefines = Buffers[0].Data; 400 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) { 401 Predefines += Buffers[I].Data; 402 } 403 return false; 404 } 405 406 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) { 407 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); 408 } 409 410 virtual void ReadCounter(unsigned Value) { 411 Counter = Value; 412 } 413}; 414 415class StoredDiagnosticClient : public DiagnosticClient { 416 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags; 417 418public: 419 explicit StoredDiagnosticClient( 420 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 421 : StoredDiags(StoredDiags) { } 422 423 virtual void HandleDiagnostic(Diagnostic::Level Level, 424 const DiagnosticInfo &Info); 425}; 426 427/// \brief RAII object that optionally captures diagnostics, if 428/// there is no diagnostic client to capture them already. 429class CaptureDroppedDiagnostics { 430 Diagnostic &Diags; 431 StoredDiagnosticClient Client; 432 DiagnosticClient *PreviousClient; 433 434public: 435 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags, 436 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 437 : Diags(Diags), Client(StoredDiags), PreviousClient(0) 438 { 439 if (RequestCapture || Diags.getClient() == 0) { 440 PreviousClient = Diags.takeClient(); 441 Diags.setClient(&Client); 442 } 443 } 444 445 ~CaptureDroppedDiagnostics() { 446 if (Diags.getClient() == &Client) { 447 Diags.takeClient(); 448 Diags.setClient(PreviousClient); 449 } 450 } 451}; 452 453} // anonymous namespace 454 455void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level, 456 const DiagnosticInfo &Info) { 457 // Default implementation (Warnings/errors count). 458 DiagnosticClient::HandleDiagnostic(Level, Info); 459 460 StoredDiags.push_back(StoredDiagnostic(Level, Info)); 461} 462 463const std::string &ASTUnit::getOriginalSourceFileName() { 464 return OriginalSourceFile; 465} 466 467const std::string &ASTUnit::getASTFileName() { 468 assert(isMainFileAST() && "Not an ASTUnit from an AST file!"); 469 return static_cast<ASTReader *>(Ctx->getExternalSource())->getFileName(); 470} 471 472llvm::MemoryBuffer *ASTUnit::getBufferForFile(llvm::StringRef Filename, 473 std::string *ErrorStr) { 474 assert(FileMgr); 475 return FileMgr->getBufferForFile(Filename, ErrorStr); 476} 477 478/// \brief Configure the diagnostics object for use with ASTUnit. 479void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags, 480 const char **ArgBegin, const char **ArgEnd, 481 ASTUnit &AST, bool CaptureDiagnostics) { 482 if (!Diags.getPtr()) { 483 // No diagnostics engine was provided, so create our own diagnostics object 484 // with the default options. 485 DiagnosticOptions DiagOpts; 486 DiagnosticClient *Client = 0; 487 if (CaptureDiagnostics) 488 Client = new StoredDiagnosticClient(AST.StoredDiagnostics); 489 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin, 490 ArgBegin, Client); 491 } else if (CaptureDiagnostics) { 492 Diags->setClient(new StoredDiagnosticClient(AST.StoredDiagnostics)); 493 } 494} 495 496ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename, 497 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 498 const FileSystemOptions &FileSystemOpts, 499 bool OnlyLocalDecls, 500 RemappedFile *RemappedFiles, 501 unsigned NumRemappedFiles, 502 bool CaptureDiagnostics) { 503 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true)); 504 505 // Recover resources if we crash before exiting this method. 506 llvm::CrashRecoveryContextCleanupRegistrar 507 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup:: 508 create<ASTUnit>(AST.get())); 509 510 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics); 511 512 AST->OnlyLocalDecls = OnlyLocalDecls; 513 AST->CaptureDiagnostics = CaptureDiagnostics; 514 AST->Diagnostics = Diags; 515 AST->FileMgr.reset(new FileManager(FileSystemOpts)); 516 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics(), 517 AST->getFileManager())); 518 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager())); 519 520 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 521 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 522 if (const llvm::MemoryBuffer * 523 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 524 // Create the file entry for the file that we're mapping from. 525 const FileEntry *FromFile 526 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 527 memBuf->getBufferSize(), 528 0); 529 if (!FromFile) { 530 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 531 << RemappedFiles[I].first; 532 delete memBuf; 533 continue; 534 } 535 536 // Override the contents of the "from" file with the contents of 537 // the "to" file. 538 AST->getSourceManager().overrideFileContents(FromFile, memBuf); 539 540 } else { 541 const char *fname = fileOrBuf.get<const char *>(); 542 const FileEntry *ToFile = AST->FileMgr->getFile(fname); 543 if (!ToFile) { 544 AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file) 545 << RemappedFiles[I].first << fname; 546 continue; 547 } 548 549 // Create the file entry for the file that we're mapping from. 550 const FileEntry *FromFile 551 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 552 ToFile->getSize(), 553 0); 554 if (!FromFile) { 555 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 556 << RemappedFiles[I].first; 557 delete memBuf; 558 continue; 559 } 560 561 // Override the contents of the "from" file with the contents of 562 // the "to" file. 563 AST->getSourceManager().overrideFileContents(FromFile, ToFile); 564 } 565 } 566 567 // Gather Info for preprocessor construction later on. 568 569 LangOptions LangInfo; 570 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); 571 std::string TargetTriple; 572 std::string Predefines; 573 unsigned Counter; 574 575 llvm::OwningPtr<ASTReader> Reader; 576 577 Reader.reset(new ASTReader(AST->getSourceManager(), AST->getFileManager(), 578 AST->getDiagnostics())); 579 Reader->setListener(new ASTInfoCollector(LangInfo, HeaderInfo, TargetTriple, 580 Predefines, Counter)); 581 582 switch (Reader->ReadAST(Filename, ASTReader::MainFile)) { 583 case ASTReader::Success: 584 break; 585 586 case ASTReader::Failure: 587 case ASTReader::IgnorePCH: 588 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 589 return NULL; 590 } 591 592 AST->OriginalSourceFile = Reader->getOriginalSourceFile(); 593 594 // AST file loaded successfully. Now create the preprocessor. 595 596 // Get information about the target being compiled for. 597 // 598 // FIXME: This is broken, we should store the TargetOptions in the AST file. 599 TargetOptions TargetOpts; 600 TargetOpts.ABI = ""; 601 TargetOpts.CXXABI = ""; 602 TargetOpts.CPU = ""; 603 TargetOpts.Features.clear(); 604 TargetOpts.Triple = TargetTriple; 605 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(), 606 TargetOpts)); 607 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo, 608 *AST->Target.get(), 609 AST->getSourceManager(), HeaderInfo)); 610 Preprocessor &PP = *AST->PP.get(); 611 612 PP.setPredefines(Reader->getSuggestedPredefines()); 613 PP.setCounterValue(Counter); 614 Reader->setPreprocessor(PP); 615 616 // Create and initialize the ASTContext. 617 618 AST->Ctx.reset(new ASTContext(LangInfo, 619 AST->getSourceManager(), 620 *AST->Target.get(), 621 PP.getIdentifierTable(), 622 PP.getSelectorTable(), 623 PP.getBuiltinInfo(), 624 /* size_reserve = */0)); 625 ASTContext &Context = *AST->Ctx.get(); 626 627 Reader->InitializeContext(Context); 628 629 // Attach the AST reader to the AST context as an external AST 630 // source, so that declarations will be deserialized from the 631 // AST file as needed. 632 ASTReader *ReaderPtr = Reader.get(); 633 llvm::OwningPtr<ExternalASTSource> Source(Reader.take()); 634 Context.setExternalSource(Source); 635 636 // Create an AST consumer, even though it isn't used. 637 AST->Consumer.reset(new ASTConsumer); 638 639 // Create a semantic analysis object and tell the AST reader about it. 640 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer)); 641 AST->TheSema->Initialize(); 642 ReaderPtr->InitializeSema(*AST->TheSema); 643 644 return AST.take(); 645} 646 647namespace { 648 649/// \brief Preprocessor callback class that updates a hash value with the names 650/// of all macros that have been defined by the translation unit. 651class MacroDefinitionTrackerPPCallbacks : public PPCallbacks { 652 unsigned &Hash; 653 654public: 655 explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { } 656 657 virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) { 658 Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash); 659 } 660}; 661 662/// \brief Add the given declaration to the hash of all top-level entities. 663void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) { 664 if (!D) 665 return; 666 667 DeclContext *DC = D->getDeclContext(); 668 if (!DC) 669 return; 670 671 if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit())) 672 return; 673 674 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) { 675 if (ND->getIdentifier()) 676 Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash); 677 else if (DeclarationName Name = ND->getDeclName()) { 678 std::string NameStr = Name.getAsString(); 679 Hash = llvm::HashString(NameStr, Hash); 680 } 681 return; 682 } 683 684 if (ObjCForwardProtocolDecl *Forward 685 = dyn_cast<ObjCForwardProtocolDecl>(D)) { 686 for (ObjCForwardProtocolDecl::protocol_iterator 687 P = Forward->protocol_begin(), 688 PEnd = Forward->protocol_end(); 689 P != PEnd; ++P) 690 AddTopLevelDeclarationToHash(*P, Hash); 691 return; 692 } 693 694 if (ObjCClassDecl *Class = llvm::dyn_cast<ObjCClassDecl>(D)) { 695 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end(); 696 I != IEnd; ++I) 697 AddTopLevelDeclarationToHash(I->getInterface(), Hash); 698 return; 699 } 700} 701 702class TopLevelDeclTrackerConsumer : public ASTConsumer { 703 ASTUnit &Unit; 704 unsigned &Hash; 705 706public: 707 TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash) 708 : Unit(_Unit), Hash(Hash) { 709 Hash = 0; 710 } 711 712 void HandleTopLevelDecl(DeclGroupRef D) { 713 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 714 Decl *D = *it; 715 // FIXME: Currently ObjC method declarations are incorrectly being 716 // reported as top-level declarations, even though their DeclContext 717 // is the containing ObjC @interface/@implementation. This is a 718 // fundamental problem in the parser right now. 719 if (isa<ObjCMethodDecl>(D)) 720 continue; 721 722 AddTopLevelDeclarationToHash(D, Hash); 723 Unit.addTopLevelDecl(D); 724 } 725 } 726 727 // We're not interested in "interesting" decls. 728 void HandleInterestingDecl(DeclGroupRef) {} 729}; 730 731class TopLevelDeclTrackerAction : public ASTFrontendAction { 732public: 733 ASTUnit &Unit; 734 735 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 736 llvm::StringRef InFile) { 737 CI.getPreprocessor().addPPCallbacks( 738 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue())); 739 return new TopLevelDeclTrackerConsumer(Unit, 740 Unit.getCurrentTopLevelHashValue()); 741 } 742 743public: 744 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 745 746 virtual bool hasCodeCompletionSupport() const { return false; } 747 virtual bool usesCompleteTranslationUnit() { 748 return Unit.isCompleteTranslationUnit(); 749 } 750}; 751 752class PrecompilePreambleConsumer : public PCHGenerator, 753 public ASTSerializationListener { 754 ASTUnit &Unit; 755 unsigned &Hash; 756 std::vector<Decl *> TopLevelDecls; 757 758public: 759 PrecompilePreambleConsumer(ASTUnit &Unit, 760 const Preprocessor &PP, bool Chaining, 761 const char *isysroot, llvm::raw_ostream *Out) 762 : PCHGenerator(PP, "", Chaining, isysroot, Out), Unit(Unit), 763 Hash(Unit.getCurrentTopLevelHashValue()) { 764 Hash = 0; 765 } 766 767 virtual void HandleTopLevelDecl(DeclGroupRef D) { 768 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 769 Decl *D = *it; 770 // FIXME: Currently ObjC method declarations are incorrectly being 771 // reported as top-level declarations, even though their DeclContext 772 // is the containing ObjC @interface/@implementation. This is a 773 // fundamental problem in the parser right now. 774 if (isa<ObjCMethodDecl>(D)) 775 continue; 776 AddTopLevelDeclarationToHash(D, Hash); 777 TopLevelDecls.push_back(D); 778 } 779 } 780 781 virtual void HandleTranslationUnit(ASTContext &Ctx) { 782 PCHGenerator::HandleTranslationUnit(Ctx); 783 if (!Unit.getDiagnostics().hasErrorOccurred()) { 784 // Translate the top-level declarations we captured during 785 // parsing into declaration IDs in the precompiled 786 // preamble. This will allow us to deserialize those top-level 787 // declarations when requested. 788 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) 789 Unit.addTopLevelDeclFromPreamble( 790 getWriter().getDeclID(TopLevelDecls[I])); 791 } 792 } 793 794 virtual void SerializedPreprocessedEntity(PreprocessedEntity *Entity, 795 uint64_t Offset) { 796 Unit.addPreprocessedEntityFromPreamble(Offset); 797 } 798 799 virtual ASTSerializationListener *GetASTSerializationListener() { 800 return this; 801 } 802}; 803 804class PrecompilePreambleAction : public ASTFrontendAction { 805 ASTUnit &Unit; 806 807public: 808 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {} 809 810 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 811 llvm::StringRef InFile) { 812 std::string Sysroot; 813 std::string OutputFile; 814 llvm::raw_ostream *OS = 0; 815 bool Chaining; 816 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, 817 OutputFile, 818 OS, Chaining)) 819 return 0; 820 821 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ? 822 Sysroot.c_str() : 0; 823 CI.getPreprocessor().addPPCallbacks( 824 new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue())); 825 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining, 826 isysroot, OS); 827 } 828 829 virtual bool hasCodeCompletionSupport() const { return false; } 830 virtual bool hasASTFileSupport() const { return false; } 831 virtual bool usesCompleteTranslationUnit() { return false; } 832}; 833 834} 835 836/// Parse the source file into a translation unit using the given compiler 837/// invocation, replacing the current translation unit. 838/// 839/// \returns True if a failure occurred that causes the ASTUnit not to 840/// contain any translation-unit information, false otherwise. 841bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) { 842 delete SavedMainFileBuffer; 843 SavedMainFileBuffer = 0; 844 845 if (!Invocation.get()) { 846 delete OverrideMainBuffer; 847 return true; 848 } 849 850 // Create the compiler instance to use for building the AST. 851 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 852 853 // Recover resources if we crash before exiting this method. 854 llvm::CrashRecoveryContextCleanupRegistrar 855 CICleanup(llvm::CrashRecoveryContextCleanup:: 856 create<CompilerInstance>(Clang.get())); 857 858 Clang->setInvocation(Invocation.take()); 859 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 860 861 // Set up diagnostics, capturing any diagnostics that would 862 // otherwise be dropped. 863 Clang->setDiagnostics(&getDiagnostics()); 864 865 // Create the target instance. 866 Clang->getTargetOpts().Features = TargetFeatures; 867 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 868 Clang->getTargetOpts())); 869 if (!Clang->hasTarget()) { 870 delete OverrideMainBuffer; 871 return true; 872 } 873 874 // Inform the target of the language options. 875 // 876 // FIXME: We shouldn't need to do this, the target should be immutable once 877 // created. This complexity should be lifted elsewhere. 878 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 879 880 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 881 "Invocation must have exactly one source file!"); 882 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 883 "FIXME: AST inputs not yet supported here!"); 884 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 885 "IR inputs not support here!"); 886 887 // Configure the various subsystems. 888 // FIXME: Should we retain the previous file manager? 889 FileSystemOpts = Clang->getFileSystemOpts(); 890 FileMgr.reset(new FileManager(FileSystemOpts)); 891 SourceMgr.reset(new SourceManager(getDiagnostics(), *FileMgr)); 892 TheSema.reset(); 893 Ctx.reset(); 894 PP.reset(); 895 896 // Clear out old caches and data. 897 TopLevelDecls.clear(); 898 PreprocessedEntities.clear(); 899 CleanTemporaryFiles(); 900 PreprocessedEntitiesByFile.clear(); 901 902 if (!OverrideMainBuffer) { 903 StoredDiagnostics.erase( 904 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver, 905 StoredDiagnostics.end()); 906 TopLevelDeclsInPreamble.clear(); 907 PreprocessedEntitiesInPreamble.clear(); 908 } 909 910 // Create a file manager object to provide access to and cache the filesystem. 911 Clang->setFileManager(&getFileManager()); 912 913 // Create the source manager. 914 Clang->setSourceManager(&getSourceManager()); 915 916 // If the main file has been overridden due to the use of a preamble, 917 // make that override happen and introduce the preamble. 918 PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts(); 919 std::string PriorImplicitPCHInclude; 920 if (OverrideMainBuffer) { 921 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 922 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 923 PreprocessorOpts.PrecompiledPreambleBytes.second 924 = PreambleEndsAtStartOfLine; 925 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude; 926 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 927 PreprocessorOpts.DisablePCHValidation = true; 928 929 // The stored diagnostic has the old source manager in it; update 930 // the locations to refer into the new source manager. Since we've 931 // been careful to make sure that the source manager's state 932 // before and after are identical, so that we can reuse the source 933 // location itself. 934 for (unsigned I = NumStoredDiagnosticsFromDriver, 935 N = StoredDiagnostics.size(); 936 I < N; ++I) { 937 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), 938 getSourceManager()); 939 StoredDiagnostics[I].setLocation(Loc); 940 } 941 942 // Keep track of the override buffer; 943 SavedMainFileBuffer = OverrideMainBuffer; 944 } else { 945 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 946 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 947 } 948 949 llvm::OwningPtr<TopLevelDeclTrackerAction> Act; 950 Act.reset(new TopLevelDeclTrackerAction(*this)); 951 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 952 Clang->getFrontendOpts().Inputs[0].first)) 953 goto error; 954 955 Act->Execute(); 956 957 // Steal the created target, context, and preprocessor, and take back the 958 // source and file managers. 959 TheSema.reset(Clang->takeSema()); 960 Consumer.reset(Clang->takeASTConsumer()); 961 Ctx.reset(Clang->takeASTContext()); 962 PP.reset(Clang->takePreprocessor()); 963 Clang->takeSourceManager(); 964 Clang->takeFileManager(); 965 Target.reset(Clang->takeTarget()); 966 967 Act->EndSourceFile(); 968 969 // Remove the overridden buffer we used for the preamble. 970 if (OverrideMainBuffer) { 971 PreprocessorOpts.eraseRemappedFile( 972 PreprocessorOpts.remapped_file_buffer_end() - 1); 973 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 974 } 975 976 Invocation.reset(Clang->takeInvocation()); 977 return false; 978 979error: 980 // Remove the overridden buffer we used for the preamble. 981 if (OverrideMainBuffer) { 982 PreprocessorOpts.eraseRemappedFile( 983 PreprocessorOpts.remapped_file_buffer_end() - 1); 984 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 985 delete OverrideMainBuffer; 986 SavedMainFileBuffer = 0; 987 } 988 989 StoredDiagnostics.clear(); 990 Clang->takeSourceManager(); 991 Clang->takeFileManager(); 992 Invocation.reset(Clang->takeInvocation()); 993 return true; 994} 995 996/// \brief Simple function to retrieve a path for a preamble precompiled header. 997static std::string GetPreamblePCHPath() { 998 // FIXME: This is lame; sys::Path should provide this function (in particular, 999 // it should know how to find the temporary files dir). 1000 // FIXME: This is really lame. I copied this code from the Driver! 1001 // FIXME: This is a hack so that we can override the preamble file during 1002 // crash-recovery testing, which is the only case where the preamble files 1003 // are not necessarily cleaned up. 1004 const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE"); 1005 if (TmpFile) 1006 return TmpFile; 1007 1008 std::string Error; 1009 const char *TmpDir = ::getenv("TMPDIR"); 1010 if (!TmpDir) 1011 TmpDir = ::getenv("TEMP"); 1012 if (!TmpDir) 1013 TmpDir = ::getenv("TMP"); 1014#ifdef LLVM_ON_WIN32 1015 if (!TmpDir) 1016 TmpDir = ::getenv("USERPROFILE"); 1017#endif 1018 if (!TmpDir) 1019 TmpDir = "/tmp"; 1020 llvm::sys::Path P(TmpDir); 1021 P.createDirectoryOnDisk(true); 1022 P.appendComponent("preamble"); 1023 P.appendSuffix("pch"); 1024 if (P.createTemporaryFileOnDisk()) 1025 return std::string(); 1026 1027 return P.str(); 1028} 1029 1030/// \brief Compute the preamble for the main file, providing the source buffer 1031/// that corresponds to the main file along with a pair (bytes, start-of-line) 1032/// that describes the preamble. 1033std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 1034ASTUnit::ComputePreamble(CompilerInvocation &Invocation, 1035 unsigned MaxLines, bool &CreatedBuffer) { 1036 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 1037 PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts(); 1038 CreatedBuffer = false; 1039 1040 // Try to determine if the main file has been remapped, either from the 1041 // command line (to another file) or directly through the compiler invocation 1042 // (to a memory buffer). 1043 llvm::MemoryBuffer *Buffer = 0; 1044 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 1045 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) { 1046 // Check whether there is a file-file remapping of the main file 1047 for (PreprocessorOptions::remapped_file_iterator 1048 M = PreprocessorOpts.remapped_file_begin(), 1049 E = PreprocessorOpts.remapped_file_end(); 1050 M != E; 1051 ++M) { 1052 llvm::sys::PathWithStatus MPath(M->first); 1053 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 1054 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 1055 // We found a remapping. Try to load the resulting, remapped source. 1056 if (CreatedBuffer) { 1057 delete Buffer; 1058 CreatedBuffer = false; 1059 } 1060 1061 Buffer = getBufferForFile(M->second); 1062 if (!Buffer) 1063 return std::make_pair((llvm::MemoryBuffer*)0, 1064 std::make_pair(0, true)); 1065 CreatedBuffer = true; 1066 } 1067 } 1068 } 1069 1070 // Check whether there is a file-buffer remapping. It supercedes the 1071 // file-file remapping. 1072 for (PreprocessorOptions::remapped_file_buffer_iterator 1073 M = PreprocessorOpts.remapped_file_buffer_begin(), 1074 E = PreprocessorOpts.remapped_file_buffer_end(); 1075 M != E; 1076 ++M) { 1077 llvm::sys::PathWithStatus MPath(M->first); 1078 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 1079 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 1080 // We found a remapping. 1081 if (CreatedBuffer) { 1082 delete Buffer; 1083 CreatedBuffer = false; 1084 } 1085 1086 Buffer = const_cast<llvm::MemoryBuffer *>(M->second); 1087 } 1088 } 1089 } 1090 } 1091 1092 // If the main source file was not remapped, load it now. 1093 if (!Buffer) { 1094 Buffer = getBufferForFile(FrontendOpts.Inputs[0].second); 1095 if (!Buffer) 1096 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true)); 1097 1098 CreatedBuffer = true; 1099 } 1100 1101 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines)); 1102} 1103 1104static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old, 1105 unsigned NewSize, 1106 llvm::StringRef NewName) { 1107 llvm::MemoryBuffer *Result 1108 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName); 1109 memcpy(const_cast<char*>(Result->getBufferStart()), 1110 Old->getBufferStart(), Old->getBufferSize()); 1111 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(), 1112 ' ', NewSize - Old->getBufferSize() - 1); 1113 const_cast<char*>(Result->getBufferEnd())[-1] = '\n'; 1114 1115 return Result; 1116} 1117 1118/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing 1119/// the source file. 1120/// 1121/// This routine will compute the preamble of the main source file. If a 1122/// non-trivial preamble is found, it will precompile that preamble into a 1123/// precompiled header so that the precompiled preamble can be used to reduce 1124/// reparsing time. If a precompiled preamble has already been constructed, 1125/// this routine will determine if it is still valid and, if so, avoid 1126/// rebuilding the precompiled preamble. 1127/// 1128/// \param AllowRebuild When true (the default), this routine is 1129/// allowed to rebuild the precompiled preamble if it is found to be 1130/// out-of-date. 1131/// 1132/// \param MaxLines When non-zero, the maximum number of lines that 1133/// can occur within the preamble. 1134/// 1135/// \returns If the precompiled preamble can be used, returns a newly-allocated 1136/// buffer that should be used in place of the main file when doing so. 1137/// Otherwise, returns a NULL pointer. 1138llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble( 1139 CompilerInvocation PreambleInvocation, 1140 bool AllowRebuild, 1141 unsigned MaxLines) { 1142 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts(); 1143 PreprocessorOptions &PreprocessorOpts 1144 = PreambleInvocation.getPreprocessorOpts(); 1145 1146 bool CreatedPreambleBuffer = false; 1147 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble 1148 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer); 1149 1150 // If ComputePreamble() Take ownership of the 1151 llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer; 1152 if (CreatedPreambleBuffer) 1153 OwnedPreambleBuffer.reset(NewPreamble.first); 1154 1155 if (!NewPreamble.second.first) { 1156 // We couldn't find a preamble in the main source. Clear out the current 1157 // preamble, if we have one. It's obviously no good any more. 1158 Preamble.clear(); 1159 if (!PreambleFile.empty()) { 1160 llvm::sys::Path(PreambleFile).eraseFromDisk(); 1161 PreambleFile.clear(); 1162 } 1163 1164 // The next time we actually see a preamble, precompile it. 1165 PreambleRebuildCounter = 1; 1166 return 0; 1167 } 1168 1169 if (!Preamble.empty()) { 1170 // We've previously computed a preamble. Check whether we have the same 1171 // preamble now that we did before, and that there's enough space in 1172 // the main-file buffer within the precompiled preamble to fit the 1173 // new main file. 1174 if (Preamble.size() == NewPreamble.second.first && 1175 PreambleEndsAtStartOfLine == NewPreamble.second.second && 1176 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 && 1177 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(), 1178 NewPreamble.second.first) == 0) { 1179 // The preamble has not changed. We may be able to re-use the precompiled 1180 // preamble. 1181 1182 // Check that none of the files used by the preamble have changed. 1183 bool AnyFileChanged = false; 1184 1185 // First, make a record of those files that have been overridden via 1186 // remapping or unsaved_files. 1187 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles; 1188 for (PreprocessorOptions::remapped_file_iterator 1189 R = PreprocessorOpts.remapped_file_begin(), 1190 REnd = PreprocessorOpts.remapped_file_end(); 1191 !AnyFileChanged && R != REnd; 1192 ++R) { 1193 struct stat StatBuf; 1194 if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) { 1195 // If we can't stat the file we're remapping to, assume that something 1196 // horrible happened. 1197 AnyFileChanged = true; 1198 break; 1199 } 1200 1201 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size, 1202 StatBuf.st_mtime); 1203 } 1204 for (PreprocessorOptions::remapped_file_buffer_iterator 1205 R = PreprocessorOpts.remapped_file_buffer_begin(), 1206 REnd = PreprocessorOpts.remapped_file_buffer_end(); 1207 !AnyFileChanged && R != REnd; 1208 ++R) { 1209 // FIXME: Should we actually compare the contents of file->buffer 1210 // remappings? 1211 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(), 1212 0); 1213 } 1214 1215 // Check whether anything has changed. 1216 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator 1217 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end(); 1218 !AnyFileChanged && F != FEnd; 1219 ++F) { 1220 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden 1221 = OverriddenFiles.find(F->first()); 1222 if (Overridden != OverriddenFiles.end()) { 1223 // This file was remapped; check whether the newly-mapped file 1224 // matches up with the previous mapping. 1225 if (Overridden->second != F->second) 1226 AnyFileChanged = true; 1227 continue; 1228 } 1229 1230 // The file was not remapped; check whether it has changed on disk. 1231 struct stat StatBuf; 1232 if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) { 1233 // If we can't stat the file, assume that something horrible happened. 1234 AnyFileChanged = true; 1235 } else if (StatBuf.st_size != F->second.first || 1236 StatBuf.st_mtime != F->second.second) 1237 AnyFileChanged = true; 1238 } 1239 1240 if (!AnyFileChanged) { 1241 // Okay! We can re-use the precompiled preamble. 1242 1243 // Set the state of the diagnostic object to mimic its state 1244 // after parsing the preamble. 1245 // FIXME: This won't catch any #pragma push warning changes that 1246 // have occurred in the preamble. 1247 getDiagnostics().Reset(); 1248 ProcessWarningOptions(getDiagnostics(), 1249 PreambleInvocation.getDiagnosticOpts()); 1250 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 1251 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble) 1252 StoredDiagnostics.erase( 1253 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble, 1254 StoredDiagnostics.end()); 1255 1256 // Create a version of the main file buffer that is padded to 1257 // buffer size we reserved when creating the preamble. 1258 return CreatePaddedMainFileBuffer(NewPreamble.first, 1259 PreambleReservedSize, 1260 FrontendOpts.Inputs[0].second); 1261 } 1262 } 1263 1264 // If we aren't allowed to rebuild the precompiled preamble, just 1265 // return now. 1266 if (!AllowRebuild) 1267 return 0; 1268 1269 // We can't reuse the previously-computed preamble. Build a new one. 1270 Preamble.clear(); 1271 llvm::sys::Path(PreambleFile).eraseFromDisk(); 1272 PreambleRebuildCounter = 1; 1273 } else if (!AllowRebuild) { 1274 // We aren't allowed to rebuild the precompiled preamble; just 1275 // return now. 1276 return 0; 1277 } 1278 1279 // If the preamble rebuild counter > 1, it's because we previously 1280 // failed to build a preamble and we're not yet ready to try 1281 // again. Decrement the counter and return a failure. 1282 if (PreambleRebuildCounter > 1) { 1283 --PreambleRebuildCounter; 1284 return 0; 1285 } 1286 1287 // Create a temporary file for the precompiled preamble. In rare 1288 // circumstances, this can fail. 1289 std::string PreamblePCHPath = GetPreamblePCHPath(); 1290 if (PreamblePCHPath.empty()) { 1291 // Try again next time. 1292 PreambleRebuildCounter = 1; 1293 return 0; 1294 } 1295 1296 // We did not previously compute a preamble, or it can't be reused anyway. 1297 SimpleTimer PreambleTimer(WantTiming); 1298 PreambleTimer.setOutput("Precompiling preamble"); 1299 1300 // Create a new buffer that stores the preamble. The buffer also contains 1301 // extra space for the original contents of the file (which will be present 1302 // when we actually parse the file) along with more room in case the file 1303 // grows. 1304 PreambleReservedSize = NewPreamble.first->getBufferSize(); 1305 if (PreambleReservedSize < 4096) 1306 PreambleReservedSize = 8191; 1307 else 1308 PreambleReservedSize *= 2; 1309 1310 // Save the preamble text for later; we'll need to compare against it for 1311 // subsequent reparses. 1312 Preamble.assign(NewPreamble.first->getBufferStart(), 1313 NewPreamble.first->getBufferStart() 1314 + NewPreamble.second.first); 1315 PreambleEndsAtStartOfLine = NewPreamble.second.second; 1316 1317 delete PreambleBuffer; 1318 PreambleBuffer 1319 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize, 1320 FrontendOpts.Inputs[0].second); 1321 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()), 1322 NewPreamble.first->getBufferStart(), Preamble.size()); 1323 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(), 1324 ' ', PreambleReservedSize - Preamble.size() - 1); 1325 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n'; 1326 1327 // Remap the main source file to the preamble buffer. 1328 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 1329 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer); 1330 1331 // Tell the compiler invocation to generate a temporary precompiled header. 1332 FrontendOpts.ProgramAction = frontend::GeneratePCH; 1333 FrontendOpts.ChainedPCH = true; 1334 // FIXME: Generate the precompiled header into memory? 1335 FrontendOpts.OutputFile = PreamblePCHPath; 1336 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 1337 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 1338 1339 // Create the compiler instance to use for building the precompiled preamble. 1340 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 1341 1342 // Recover resources if we crash before exiting this method. 1343 llvm::CrashRecoveryContextCleanupRegistrar 1344 CICleanup(llvm::CrashRecoveryContextCleanup:: 1345 create<CompilerInstance>(Clang.get())); 1346 1347 Clang->setInvocation(&PreambleInvocation); 1348 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 1349 1350 // Set up diagnostics, capturing all of the diagnostics produced. 1351 Clang->setDiagnostics(&getDiagnostics()); 1352 1353 // Create the target instance. 1354 Clang->getTargetOpts().Features = TargetFeatures; 1355 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 1356 Clang->getTargetOpts())); 1357 if (!Clang->hasTarget()) { 1358 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1359 Preamble.clear(); 1360 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1361 PreprocessorOpts.eraseRemappedFile( 1362 PreprocessorOpts.remapped_file_buffer_end() - 1); 1363 return 0; 1364 } 1365 1366 // Inform the target of the language options. 1367 // 1368 // FIXME: We shouldn't need to do this, the target should be immutable once 1369 // created. This complexity should be lifted elsewhere. 1370 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 1371 1372 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 1373 "Invocation must have exactly one source file!"); 1374 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 1375 "FIXME: AST inputs not yet supported here!"); 1376 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1377 "IR inputs not support here!"); 1378 1379 // Clear out old caches and data. 1380 getDiagnostics().Reset(); 1381 ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts()); 1382 StoredDiagnostics.erase( 1383 StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver, 1384 StoredDiagnostics.end()); 1385 TopLevelDecls.clear(); 1386 TopLevelDeclsInPreamble.clear(); 1387 PreprocessedEntities.clear(); 1388 PreprocessedEntitiesInPreamble.clear(); 1389 1390 // Create a file manager object to provide access to and cache the filesystem. 1391 Clang->setFileManager(new FileManager(Clang->getFileSystemOpts())); 1392 1393 // Create the source manager. 1394 Clang->setSourceManager(new SourceManager(getDiagnostics(), 1395 Clang->getFileManager())); 1396 1397 llvm::OwningPtr<PrecompilePreambleAction> Act; 1398 Act.reset(new PrecompilePreambleAction(*this)); 1399 if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 1400 Clang->getFrontendOpts().Inputs[0].first)) { 1401 Clang->takeInvocation(); 1402 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1403 Preamble.clear(); 1404 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1405 PreprocessorOpts.eraseRemappedFile( 1406 PreprocessorOpts.remapped_file_buffer_end() - 1); 1407 return 0; 1408 } 1409 1410 Act->Execute(); 1411 Act->EndSourceFile(); 1412 Clang->takeInvocation(); 1413 1414 if (Diagnostics->hasErrorOccurred()) { 1415 // There were errors parsing the preamble, so no precompiled header was 1416 // generated. Forget that we even tried. 1417 // FIXME: Should we leave a note for ourselves to try again? 1418 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1419 Preamble.clear(); 1420 TopLevelDeclsInPreamble.clear(); 1421 PreprocessedEntities.clear(); 1422 PreprocessedEntitiesInPreamble.clear(); 1423 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1424 PreprocessorOpts.eraseRemappedFile( 1425 PreprocessorOpts.remapped_file_buffer_end() - 1); 1426 return 0; 1427 } 1428 1429 // Keep track of the preamble we precompiled. 1430 PreambleFile = FrontendOpts.OutputFile; 1431 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 1432 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 1433 1434 // Keep track of all of the files that the source manager knows about, 1435 // so we can verify whether they have changed or not. 1436 FilesInPreamble.clear(); 1437 SourceManager &SourceMgr = Clang->getSourceManager(); 1438 const llvm::MemoryBuffer *MainFileBuffer 1439 = SourceMgr.getBuffer(SourceMgr.getMainFileID()); 1440 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(), 1441 FEnd = SourceMgr.fileinfo_end(); 1442 F != FEnd; 1443 ++F) { 1444 const FileEntry *File = F->second->OrigEntry; 1445 if (!File || F->second->getRawBuffer() == MainFileBuffer) 1446 continue; 1447 1448 FilesInPreamble[File->getName()] 1449 = std::make_pair(F->second->getSize(), File->getModificationTime()); 1450 } 1451 1452 PreambleRebuildCounter = 1; 1453 PreprocessorOpts.eraseRemappedFile( 1454 PreprocessorOpts.remapped_file_buffer_end() - 1); 1455 1456 // If the hash of top-level entities differs from the hash of the top-level 1457 // entities the last time we rebuilt the preamble, clear out the completion 1458 // cache. 1459 if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) { 1460 CompletionCacheTopLevelHashValue = 0; 1461 PreambleTopLevelHashValue = CurrentTopLevelHashValue; 1462 } 1463 1464 return CreatePaddedMainFileBuffer(NewPreamble.first, 1465 PreambleReservedSize, 1466 FrontendOpts.Inputs[0].second); 1467} 1468 1469void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1470 std::vector<Decl *> Resolved; 1471 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1472 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1473 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) { 1474 // Resolve the declaration ID to an actual declaration, possibly 1475 // deserializing the declaration in the process. 1476 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]); 1477 if (D) 1478 Resolved.push_back(D); 1479 } 1480 TopLevelDeclsInPreamble.clear(); 1481 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1482} 1483 1484void ASTUnit::RealizePreprocessedEntitiesFromPreamble() { 1485 if (!PP) 1486 return; 1487 1488 PreprocessingRecord *PPRec = PP->getPreprocessingRecord(); 1489 if (!PPRec) 1490 return; 1491 1492 ExternalPreprocessingRecordSource *External = PPRec->getExternalSource(); 1493 if (!External) 1494 return; 1495 1496 for (unsigned I = 0, N = PreprocessedEntitiesInPreamble.size(); I != N; ++I) { 1497 if (PreprocessedEntity *PE 1498 = External->ReadPreprocessedEntityAtOffset( 1499 PreprocessedEntitiesInPreamble[I])) 1500 PreprocessedEntities.push_back(PE); 1501 } 1502 1503 if (PreprocessedEntities.empty()) 1504 return; 1505 1506 PreprocessedEntities.insert(PreprocessedEntities.end(), 1507 PPRec->begin(true), PPRec->end(true)); 1508} 1509 1510ASTUnit::pp_entity_iterator ASTUnit::pp_entity_begin() { 1511 if (!PreprocessedEntitiesInPreamble.empty() && 1512 PreprocessedEntities.empty()) 1513 RealizePreprocessedEntitiesFromPreamble(); 1514 1515 if (PreprocessedEntities.empty()) 1516 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 1517 return PPRec->begin(true); 1518 1519 return PreprocessedEntities.begin(); 1520} 1521 1522ASTUnit::pp_entity_iterator ASTUnit::pp_entity_end() { 1523 if (!PreprocessedEntitiesInPreamble.empty() && 1524 PreprocessedEntities.empty()) 1525 RealizePreprocessedEntitiesFromPreamble(); 1526 1527 if (PreprocessedEntities.empty()) 1528 if (PreprocessingRecord *PPRec = PP->getPreprocessingRecord()) 1529 return PPRec->end(true); 1530 1531 return PreprocessedEntities.end(); 1532} 1533 1534unsigned ASTUnit::getMaxPCHLevel() const { 1535 if (!getOnlyLocalDecls()) 1536 return Decl::MaxPCHLevel; 1537 1538 return 0; 1539} 1540 1541llvm::StringRef ASTUnit::getMainFileName() const { 1542 return Invocation->getFrontendOpts().Inputs[0].second; 1543} 1544 1545ASTUnit *ASTUnit::create(CompilerInvocation *CI, 1546 llvm::IntrusiveRefCntPtr<Diagnostic> Diags) { 1547 llvm::OwningPtr<ASTUnit> AST; 1548 AST.reset(new ASTUnit(false)); 1549 ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false); 1550 AST->Diagnostics = Diags; 1551 AST->Invocation.reset(CI); 1552 AST->FileSystemOpts = CI->getFileSystemOpts(); 1553 AST->FileMgr.reset(new FileManager(AST->FileSystemOpts)); 1554 AST->SourceMgr.reset(new SourceManager(*Diags, *AST->FileMgr)); 1555 1556 return AST.take(); 1557} 1558 1559bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) { 1560 if (!Invocation) 1561 return true; 1562 1563 // We'll manage file buffers ourselves. 1564 Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1565 Invocation->getFrontendOpts().DisableFree = false; 1566 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1567 1568 // Save the target features. 1569 TargetFeatures = Invocation->getTargetOpts().Features; 1570 1571 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1572 if (PrecompilePreamble) { 1573 PreambleRebuildCounter = 2; 1574 OverrideMainBuffer 1575 = getMainBufferWithPrecompiledPreamble(*Invocation); 1576 } 1577 1578 SimpleTimer ParsingTimer(WantTiming); 1579 ParsingTimer.setOutput("Parsing " + getMainFileName()); 1580 1581 return Parse(OverrideMainBuffer); 1582} 1583 1584ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI, 1585 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1586 bool OnlyLocalDecls, 1587 bool CaptureDiagnostics, 1588 bool PrecompilePreamble, 1589 bool CompleteTranslationUnit, 1590 bool CacheCodeCompletionResults) { 1591 // Create the AST unit. 1592 llvm::OwningPtr<ASTUnit> AST; 1593 AST.reset(new ASTUnit(false)); 1594 ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics); 1595 AST->Diagnostics = Diags; 1596 AST->OnlyLocalDecls = OnlyLocalDecls; 1597 AST->CaptureDiagnostics = CaptureDiagnostics; 1598 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1599 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1600 AST->Invocation.reset(CI); 1601 1602 // Recover resources if we crash before exiting this method. 1603 llvm::CrashRecoveryContextCleanupRegistrar 1604 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup:: 1605 create<ASTUnit>(AST.get())); 1606 1607 return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take(); 1608} 1609 1610ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin, 1611 const char **ArgEnd, 1612 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1613 llvm::StringRef ResourceFilesPath, 1614 bool OnlyLocalDecls, 1615 bool CaptureDiagnostics, 1616 RemappedFile *RemappedFiles, 1617 unsigned NumRemappedFiles, 1618 bool RemappedFilesKeepOriginalName, 1619 bool PrecompilePreamble, 1620 bool CompleteTranslationUnit, 1621 bool CacheCodeCompletionResults, 1622 bool CXXPrecompilePreamble, 1623 bool CXXChainedPCH) { 1624 if (!Diags.getPtr()) { 1625 // No diagnostics engine was provided, so create our own diagnostics object 1626 // with the default options. 1627 DiagnosticOptions DiagOpts; 1628 Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin, 1629 ArgBegin); 1630 } 1631 1632 llvm::SmallVector<const char *, 16> Args; 1633 Args.push_back("<clang>"); // FIXME: Remove dummy argument. 1634 Args.insert(Args.end(), ArgBegin, ArgEnd); 1635 1636 // FIXME: Find a cleaner way to force the driver into restricted modes. We 1637 // also want to force it to use clang. 1638 Args.push_back("-fsyntax-only"); 1639 1640 llvm::SmallVector<StoredDiagnostic, 4> StoredDiagnostics; 1641 1642 llvm::OwningPtr<CompilerInvocation> CI; 1643 1644 { 1645 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags, 1646 StoredDiagnostics); 1647 1648 // FIXME: We shouldn't have to pass in the path info. 1649 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(), 1650 "a.out", false, false, *Diags); 1651 1652 // Don't check that inputs exist, they have been remapped. 1653 TheDriver.setCheckInputsExist(false); 1654 1655 llvm::OwningPtr<driver::Compilation> C( 1656 TheDriver.BuildCompilation(Args.size(), Args.data())); 1657 1658 // Just print the cc1 options if -### was present. 1659 if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) { 1660 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true); 1661 return 0; 1662 } 1663 1664 // We expect to get back exactly one command job, if we didn't something 1665 // failed. 1666 const driver::JobList &Jobs = C->getJobs(); 1667 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) { 1668 llvm::SmallString<256> Msg; 1669 llvm::raw_svector_ostream OS(Msg); 1670 C->PrintJob(OS, C->getJobs(), "; ", true); 1671 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str(); 1672 return 0; 1673 } 1674 1675 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin()); 1676 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { 1677 Diags->Report(diag::err_fe_expected_clang_command); 1678 return 0; 1679 } 1680 1681 const driver::ArgStringList &CCArgs = Cmd->getArguments(); 1682 CI.reset(new CompilerInvocation); 1683 CompilerInvocation::CreateFromArgs(*CI, 1684 const_cast<const char **>(CCArgs.data()), 1685 const_cast<const char **>(CCArgs.data()) + 1686 CCArgs.size(), 1687 *Diags); 1688 } 1689 1690 // Override any files that need remapping 1691 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 1692 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 1693 if (const llvm::MemoryBuffer * 1694 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 1695 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf); 1696 } else { 1697 const char *fname = fileOrBuf.get<const char *>(); 1698 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname); 1699 } 1700 } 1701 CI->getPreprocessorOpts().RemappedFilesKeepOriginalName = 1702 RemappedFilesKeepOriginalName; 1703 1704 // Override the resources path. 1705 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1706 1707 // Check whether we should precompile the preamble and/or use chained PCH. 1708 // FIXME: This is a temporary hack while we debug C++ chained PCH. 1709 if (CI->getLangOpts().CPlusPlus) { 1710 PrecompilePreamble = PrecompilePreamble && CXXPrecompilePreamble; 1711 1712 if (PrecompilePreamble && !CXXChainedPCH && 1713 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) 1714 PrecompilePreamble = false; 1715 } 1716 1717 // Create the AST unit. 1718 llvm::OwningPtr<ASTUnit> AST; 1719 AST.reset(new ASTUnit(false)); 1720 ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics); 1721 AST->Diagnostics = Diags; 1722 1723 AST->FileSystemOpts = CI->getFileSystemOpts(); 1724 AST->FileMgr.reset(new FileManager(AST->FileSystemOpts)); 1725 AST->OnlyLocalDecls = OnlyLocalDecls; 1726 AST->CaptureDiagnostics = CaptureDiagnostics; 1727 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1728 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1729 AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size(); 1730 AST->NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 1731 AST->StoredDiagnostics.swap(StoredDiagnostics); 1732 AST->Invocation.reset(CI.take()); 1733 1734 // Recover resources if we crash before exiting this method. 1735 llvm::CrashRecoveryContextCleanupRegistrar 1736 ASTUnitCleanup(llvm::CrashRecoveryContextCleanup:: 1737 create<ASTUnit>(AST.get())); 1738 1739 return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take(); 1740} 1741 1742bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) { 1743 if (!Invocation.get()) 1744 return true; 1745 1746 SimpleTimer ParsingTimer(WantTiming); 1747 ParsingTimer.setOutput("Reparsing " + getMainFileName()); 1748 1749 // Remap files. 1750 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 1751 PPOpts.DisableStatCache = true; 1752 for (PreprocessorOptions::remapped_file_buffer_iterator 1753 R = PPOpts.remapped_file_buffer_begin(), 1754 REnd = PPOpts.remapped_file_buffer_end(); 1755 R != REnd; 1756 ++R) { 1757 delete R->second; 1758 } 1759 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1760 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 1761 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 1762 if (const llvm::MemoryBuffer * 1763 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 1764 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1765 memBuf); 1766 } else { 1767 const char *fname = fileOrBuf.get<const char *>(); 1768 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1769 fname); 1770 } 1771 } 1772 1773 // If we have a preamble file lying around, or if we might try to 1774 // build a precompiled preamble, do so now. 1775 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1776 if (!PreambleFile.empty() || PreambleRebuildCounter > 0) 1777 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation); 1778 1779 // Clear out the diagnostics state. 1780 if (!OverrideMainBuffer) { 1781 getDiagnostics().Reset(); 1782 ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts()); 1783 } 1784 1785 // Parse the sources 1786 bool Result = Parse(OverrideMainBuffer); 1787 1788 // If we're caching global code-completion results, and the top-level 1789 // declarations have changed, clear out the code-completion cache. 1790 if (!Result && ShouldCacheCodeCompletionResults && 1791 CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue) 1792 CacheCodeCompletionResults(); 1793 1794 return Result; 1795} 1796 1797//----------------------------------------------------------------------------// 1798// Code completion 1799//----------------------------------------------------------------------------// 1800 1801namespace { 1802 /// \brief Code completion consumer that combines the cached code-completion 1803 /// results from an ASTUnit with the code-completion results provided to it, 1804 /// then passes the result on to 1805 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer { 1806 unsigned NormalContexts; 1807 ASTUnit &AST; 1808 CodeCompleteConsumer &Next; 1809 1810 public: 1811 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, 1812 bool IncludeMacros, bool IncludeCodePatterns, 1813 bool IncludeGlobals) 1814 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals, 1815 Next.isOutputBinary()), AST(AST), Next(Next) 1816 { 1817 // Compute the set of contexts in which we will look when we don't have 1818 // any information about the specific context. 1819 NormalContexts 1820 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 1821 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 1822 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 1823 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 1824 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 1825 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 1826 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 1827 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1)) 1828 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)) 1829 | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1)) 1830 | (1 << (CodeCompletionContext::CCC_Recovery - 1)); 1831 1832 if (AST.getASTContext().getLangOptions().CPlusPlus) 1833 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 1834 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 1835 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 1836 } 1837 1838 virtual void ProcessCodeCompleteResults(Sema &S, 1839 CodeCompletionContext Context, 1840 CodeCompletionResult *Results, 1841 unsigned NumResults); 1842 1843 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 1844 OverloadCandidate *Candidates, 1845 unsigned NumCandidates) { 1846 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates); 1847 } 1848 1849 virtual CodeCompletionAllocator &getAllocator() { 1850 return Next.getAllocator(); 1851 } 1852 }; 1853} 1854 1855/// \brief Helper function that computes which global names are hidden by the 1856/// local code-completion results. 1857static void CalculateHiddenNames(const CodeCompletionContext &Context, 1858 CodeCompletionResult *Results, 1859 unsigned NumResults, 1860 ASTContext &Ctx, 1861 llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){ 1862 bool OnlyTagNames = false; 1863 switch (Context.getKind()) { 1864 case CodeCompletionContext::CCC_Recovery: 1865 case CodeCompletionContext::CCC_TopLevel: 1866 case CodeCompletionContext::CCC_ObjCInterface: 1867 case CodeCompletionContext::CCC_ObjCImplementation: 1868 case CodeCompletionContext::CCC_ObjCIvarList: 1869 case CodeCompletionContext::CCC_ClassStructUnion: 1870 case CodeCompletionContext::CCC_Statement: 1871 case CodeCompletionContext::CCC_Expression: 1872 case CodeCompletionContext::CCC_ObjCMessageReceiver: 1873 case CodeCompletionContext::CCC_MemberAccess: 1874 case CodeCompletionContext::CCC_Namespace: 1875 case CodeCompletionContext::CCC_Type: 1876 case CodeCompletionContext::CCC_Name: 1877 case CodeCompletionContext::CCC_PotentiallyQualifiedName: 1878 case CodeCompletionContext::CCC_ParenthesizedExpression: 1879 break; 1880 1881 case CodeCompletionContext::CCC_EnumTag: 1882 case CodeCompletionContext::CCC_UnionTag: 1883 case CodeCompletionContext::CCC_ClassOrStructTag: 1884 OnlyTagNames = true; 1885 break; 1886 1887 case CodeCompletionContext::CCC_ObjCProtocolName: 1888 case CodeCompletionContext::CCC_MacroName: 1889 case CodeCompletionContext::CCC_MacroNameUse: 1890 case CodeCompletionContext::CCC_PreprocessorExpression: 1891 case CodeCompletionContext::CCC_PreprocessorDirective: 1892 case CodeCompletionContext::CCC_NaturalLanguage: 1893 case CodeCompletionContext::CCC_SelectorName: 1894 case CodeCompletionContext::CCC_TypeQualifiers: 1895 case CodeCompletionContext::CCC_Other: 1896 case CodeCompletionContext::CCC_OtherWithMacros: 1897 // We're looking for nothing, or we're looking for names that cannot 1898 // be hidden. 1899 return; 1900 } 1901 1902 typedef CodeCompletionResult Result; 1903 for (unsigned I = 0; I != NumResults; ++I) { 1904 if (Results[I].Kind != Result::RK_Declaration) 1905 continue; 1906 1907 unsigned IDNS 1908 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); 1909 1910 bool Hiding = false; 1911 if (OnlyTagNames) 1912 Hiding = (IDNS & Decl::IDNS_Tag); 1913 else { 1914 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 1915 Decl::IDNS_Namespace | Decl::IDNS_Ordinary | 1916 Decl::IDNS_NonMemberOperator); 1917 if (Ctx.getLangOptions().CPlusPlus) 1918 HiddenIDNS |= Decl::IDNS_Tag; 1919 Hiding = (IDNS & HiddenIDNS); 1920 } 1921 1922 if (!Hiding) 1923 continue; 1924 1925 DeclarationName Name = Results[I].Declaration->getDeclName(); 1926 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) 1927 HiddenNames.insert(Identifier->getName()); 1928 else 1929 HiddenNames.insert(Name.getAsString()); 1930 } 1931} 1932 1933 1934void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, 1935 CodeCompletionContext Context, 1936 CodeCompletionResult *Results, 1937 unsigned NumResults) { 1938 // Merge the results we were given with the results we cached. 1939 bool AddedResult = false; 1940 unsigned InContexts 1941 = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts 1942 : (1 << (Context.getKind() - 1))); 1943 1944 // Contains the set of names that are hidden by "local" completion results. 1945 llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames; 1946 typedef CodeCompletionResult Result; 1947 llvm::SmallVector<Result, 8> AllResults; 1948 for (ASTUnit::cached_completion_iterator 1949 C = AST.cached_completion_begin(), 1950 CEnd = AST.cached_completion_end(); 1951 C != CEnd; ++C) { 1952 // If the context we are in matches any of the contexts we are 1953 // interested in, we'll add this result. 1954 if ((C->ShowInContexts & InContexts) == 0) 1955 continue; 1956 1957 // If we haven't added any results previously, do so now. 1958 if (!AddedResult) { 1959 CalculateHiddenNames(Context, Results, NumResults, S.Context, 1960 HiddenNames); 1961 AllResults.insert(AllResults.end(), Results, Results + NumResults); 1962 AddedResult = true; 1963 } 1964 1965 // Determine whether this global completion result is hidden by a local 1966 // completion result. If so, skip it. 1967 if (C->Kind != CXCursor_MacroDefinition && 1968 HiddenNames.count(C->Completion->getTypedText())) 1969 continue; 1970 1971 // Adjust priority based on similar type classes. 1972 unsigned Priority = C->Priority; 1973 CXCursorKind CursorKind = C->Kind; 1974 CodeCompletionString *Completion = C->Completion; 1975 if (!Context.getPreferredType().isNull()) { 1976 if (C->Kind == CXCursor_MacroDefinition) { 1977 Priority = getMacroUsagePriority(C->Completion->getTypedText(), 1978 S.getLangOptions(), 1979 Context.getPreferredType()->isAnyPointerType()); 1980 } else if (C->Type) { 1981 CanQualType Expected 1982 = S.Context.getCanonicalType( 1983 Context.getPreferredType().getUnqualifiedType()); 1984 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); 1985 if (ExpectedSTC == C->TypeClass) { 1986 // We know this type is similar; check for an exact match. 1987 llvm::StringMap<unsigned> &CachedCompletionTypes 1988 = AST.getCachedCompletionTypes(); 1989 llvm::StringMap<unsigned>::iterator Pos 1990 = CachedCompletionTypes.find(QualType(Expected).getAsString()); 1991 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) 1992 Priority /= CCF_ExactTypeMatch; 1993 else 1994 Priority /= CCF_SimilarTypeMatch; 1995 } 1996 } 1997 } 1998 1999 // Adjust the completion string, if required. 2000 if (C->Kind == CXCursor_MacroDefinition && 2001 Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) { 2002 // Create a new code-completion string that just contains the 2003 // macro name, without its arguments. 2004 CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern, 2005 C->Availability); 2006 Builder.AddTypedTextChunk(C->Completion->getTypedText()); 2007 CursorKind = CXCursor_NotImplemented; 2008 Priority = CCP_CodePattern; 2009 Completion = Builder.TakeString(); 2010 } 2011 2012 AllResults.push_back(Result(Completion, Priority, CursorKind, 2013 C->Availability)); 2014 } 2015 2016 // If we did not add any cached completion results, just forward the 2017 // results we were given to the next consumer. 2018 if (!AddedResult) { 2019 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); 2020 return; 2021 } 2022 2023 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), 2024 AllResults.size()); 2025} 2026 2027 2028 2029void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 2030 RemappedFile *RemappedFiles, 2031 unsigned NumRemappedFiles, 2032 bool IncludeMacros, 2033 bool IncludeCodePatterns, 2034 CodeCompleteConsumer &Consumer, 2035 Diagnostic &Diag, LangOptions &LangOpts, 2036 SourceManager &SourceMgr, FileManager &FileMgr, 2037 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics, 2038 llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) { 2039 if (!Invocation.get()) 2040 return; 2041 2042 SimpleTimer CompletionTimer(WantTiming); 2043 CompletionTimer.setOutput("Code completion @ " + File + ":" + 2044 llvm::Twine(Line) + ":" + llvm::Twine(Column)); 2045 2046 CompilerInvocation CCInvocation(*Invocation); 2047 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts(); 2048 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts(); 2049 2050 FrontendOpts.ShowMacrosInCodeCompletion 2051 = IncludeMacros && CachedCompletionResults.empty(); 2052 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns; 2053 FrontendOpts.ShowGlobalSymbolsInCodeCompletion 2054 = CachedCompletionResults.empty(); 2055 FrontendOpts.CodeCompletionAt.FileName = File; 2056 FrontendOpts.CodeCompletionAt.Line = Line; 2057 FrontendOpts.CodeCompletionAt.Column = Column; 2058 2059 // Set the language options appropriately. 2060 LangOpts = CCInvocation.getLangOpts(); 2061 2062 llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance()); 2063 2064 // Recover resources if we crash before exiting this method. 2065 llvm::CrashRecoveryContextCleanupRegistrar 2066 CICleanup(llvm::CrashRecoveryContextCleanup:: 2067 create<CompilerInstance>(Clang.get())); 2068 2069 Clang->setInvocation(&CCInvocation); 2070 OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second; 2071 2072 // Set up diagnostics, capturing any diagnostics produced. 2073 Clang->setDiagnostics(&Diag); 2074 ProcessWarningOptions(Diag, CCInvocation.getDiagnosticOpts()); 2075 CaptureDroppedDiagnostics Capture(true, 2076 Clang->getDiagnostics(), 2077 StoredDiagnostics); 2078 2079 // Create the target instance. 2080 Clang->getTargetOpts().Features = TargetFeatures; 2081 Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(), 2082 Clang->getTargetOpts())); 2083 if (!Clang->hasTarget()) { 2084 Clang->takeInvocation(); 2085 return; 2086 } 2087 2088 // Inform the target of the language options. 2089 // 2090 // FIXME: We shouldn't need to do this, the target should be immutable once 2091 // created. This complexity should be lifted elsewhere. 2092 Clang->getTarget().setForcedLangOptions(Clang->getLangOpts()); 2093 2094 assert(Clang->getFrontendOpts().Inputs.size() == 1 && 2095 "Invocation must have exactly one source file!"); 2096 assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST && 2097 "FIXME: AST inputs not yet supported here!"); 2098 assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 2099 "IR inputs not support here!"); 2100 2101 2102 // Use the source and file managers that we were given. 2103 Clang->setFileManager(&FileMgr); 2104 Clang->setSourceManager(&SourceMgr); 2105 2106 // Remap files. 2107 PreprocessorOpts.clearRemappedFiles(); 2108 PreprocessorOpts.RetainRemappedFileBuffers = true; 2109 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 2110 FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second; 2111 if (const llvm::MemoryBuffer * 2112 memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) { 2113 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf); 2114 OwnedBuffers.push_back(memBuf); 2115 } else { 2116 const char *fname = fileOrBuf.get<const char *>(); 2117 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname); 2118 } 2119 } 2120 2121 // Use the code completion consumer we were given, but adding any cached 2122 // code-completion results. 2123 AugmentedCodeCompleteConsumer *AugmentedConsumer 2124 = new AugmentedCodeCompleteConsumer(*this, Consumer, 2125 FrontendOpts.ShowMacrosInCodeCompletion, 2126 FrontendOpts.ShowCodePatternsInCodeCompletion, 2127 FrontendOpts.ShowGlobalSymbolsInCodeCompletion); 2128 Clang->setCodeCompletionConsumer(AugmentedConsumer); 2129 2130 // If we have a precompiled preamble, try to use it. We only allow 2131 // the use of the precompiled preamble if we're if the completion 2132 // point is within the main file, after the end of the precompiled 2133 // preamble. 2134 llvm::MemoryBuffer *OverrideMainBuffer = 0; 2135 if (!PreambleFile.empty()) { 2136 using llvm::sys::FileStatus; 2137 llvm::sys::PathWithStatus CompleteFilePath(File); 2138 llvm::sys::PathWithStatus MainPath(OriginalSourceFile); 2139 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus()) 2140 if (const FileStatus *MainStatus = MainPath.getFileStatus()) 2141 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID()) 2142 OverrideMainBuffer 2143 = getMainBufferWithPrecompiledPreamble(CCInvocation, false, 2144 Line - 1); 2145 } 2146 2147 // If the main file has been overridden due to the use of a preamble, 2148 // make that override happen and introduce the preamble. 2149 PreprocessorOpts.DisableStatCache = true; 2150 StoredDiagnostics.insert(StoredDiagnostics.end(), 2151 this->StoredDiagnostics.begin(), 2152 this->StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver); 2153 if (OverrideMainBuffer) { 2154 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 2155 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 2156 PreprocessorOpts.PrecompiledPreambleBytes.second 2157 = PreambleEndsAtStartOfLine; 2158 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 2159 PreprocessorOpts.DisablePCHValidation = true; 2160 2161 // The stored diagnostics have the old source manager. Copy them 2162 // to our output set of stored diagnostics, updating the source 2163 // manager to the one we were given. 2164 for (unsigned I = NumStoredDiagnosticsFromDriver, 2165 N = this->StoredDiagnostics.size(); 2166 I < N; ++I) { 2167 StoredDiagnostics.push_back(this->StoredDiagnostics[I]); 2168 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr); 2169 StoredDiagnostics[I].setLocation(Loc); 2170 } 2171 2172 OwnedBuffers.push_back(OverrideMainBuffer); 2173 } else { 2174 PreprocessorOpts.PrecompiledPreambleBytes.first = 0; 2175 PreprocessorOpts.PrecompiledPreambleBytes.second = false; 2176 } 2177 2178 llvm::OwningPtr<SyntaxOnlyAction> Act; 2179 Act.reset(new SyntaxOnlyAction); 2180 if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second, 2181 Clang->getFrontendOpts().Inputs[0].first)) { 2182 Act->Execute(); 2183 Act->EndSourceFile(); 2184 } 2185 2186 // Steal back our resources. 2187 Clang->takeFileManager(); 2188 Clang->takeSourceManager(); 2189 Clang->takeInvocation(); 2190} 2191 2192bool ASTUnit::Save(llvm::StringRef File) { 2193 if (getDiagnostics().hasErrorOccurred()) 2194 return true; 2195 2196 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 2197 // unconditionally create a stat cache when we parse the file? 2198 std::string ErrorInfo; 2199 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo, 2200 llvm::raw_fd_ostream::F_Binary); 2201 if (!ErrorInfo.empty() || Out.has_error()) 2202 return true; 2203 2204 serialize(Out); 2205 Out.close(); 2206 return Out.has_error(); 2207} 2208 2209bool ASTUnit::serialize(llvm::raw_ostream &OS) { 2210 if (getDiagnostics().hasErrorOccurred()) 2211 return true; 2212 2213 std::vector<unsigned char> Buffer; 2214 llvm::BitstreamWriter Stream(Buffer); 2215 ASTWriter Writer(Stream); 2216 Writer.WriteAST(getSema(), 0, std::string(), 0); 2217 2218 // Write the generated bitstream to "Out". 2219 if (!Buffer.empty()) 2220 OS.write((char *)&Buffer.front(), Buffer.size()); 2221 2222 return false; 2223} 2224