ASTUnit.cpp revision 5535d5721b6bfb5df9583bc0632da910a176109d
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/Frontend/PCHWriter.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/ASTConsumer.h" 18#include "clang/AST/DeclVisitor.h" 19#include "clang/AST/TypeOrdering.h" 20#include "clang/AST/StmtVisitor.h" 21#include "clang/Driver/Compilation.h" 22#include "clang/Driver/Driver.h" 23#include "clang/Driver/Job.h" 24#include "clang/Driver/Tool.h" 25#include "clang/Frontend/CompilerInstance.h" 26#include "clang/Frontend/FrontendActions.h" 27#include "clang/Frontend/FrontendDiagnostic.h" 28#include "clang/Frontend/FrontendOptions.h" 29#include "clang/Frontend/PCHReader.h" 30#include "clang/Lex/HeaderSearch.h" 31#include "clang/Lex/Preprocessor.h" 32#include "clang/Basic/TargetOptions.h" 33#include "clang/Basic/TargetInfo.h" 34#include "clang/Basic/Diagnostic.h" 35#include "llvm/Support/MemoryBuffer.h" 36#include "llvm/System/Host.h" 37#include "llvm/System/Path.h" 38#include "llvm/Support/raw_ostream.h" 39#include "llvm/Support/Timer.h" 40#include <cstdlib> 41#include <cstdio> 42#include <sys/stat.h> 43using namespace clang; 44 45/// \brief After failing to build a precompiled preamble (due to 46/// errors in the source that occurs in the preamble), the number of 47/// reparses during which we'll skip even trying to precompile the 48/// preamble. 49const unsigned DefaultPreambleRebuildInterval = 5; 50 51ASTUnit::ASTUnit(bool _MainFileIsAST) 52 : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST), 53 CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked), 54 PreambleRebuildCounter(0), SavedMainFileBuffer(0), 55 ShouldCacheCodeCompletionResults(false) { 56} 57 58ASTUnit::~ASTUnit() { 59 ConcurrencyCheckValue = CheckLocked; 60 CleanTemporaryFiles(); 61 if (!PreambleFile.empty()) 62 llvm::sys::Path(PreambleFile).eraseFromDisk(); 63 64 // Free the buffers associated with remapped files. We are required to 65 // perform this operation here because we explicitly request that the 66 // compiler instance *not* free these buffers for each invocation of the 67 // parser. 68 if (Invocation.get()) { 69 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts(); 70 for (PreprocessorOptions::remapped_file_buffer_iterator 71 FB = PPOpts.remapped_file_buffer_begin(), 72 FBEnd = PPOpts.remapped_file_buffer_end(); 73 FB != FBEnd; 74 ++FB) 75 delete FB->second; 76 } 77 78 delete SavedMainFileBuffer; 79 80 ClearCachedCompletionResults(); 81 82 for (unsigned I = 0, N = Timers.size(); I != N; ++I) 83 delete Timers[I]; 84} 85 86void ASTUnit::CleanTemporaryFiles() { 87 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) 88 TemporaryFiles[I].eraseFromDisk(); 89 TemporaryFiles.clear(); 90} 91 92/// \brief Determine the set of code-completion contexts in which this 93/// declaration should be shown. 94static unsigned getDeclShowContexts(NamedDecl *ND, 95 const LangOptions &LangOpts) { 96 if (isa<UsingShadowDecl>(ND)) 97 ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl()); 98 if (!ND) 99 return 0; 100 101 unsigned Contexts = 0; 102 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) || 103 isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) { 104 // Types can appear in these contexts. 105 if (LangOpts.CPlusPlus || !isa<TagDecl>(ND)) 106 Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 107 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 108 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 109 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 110 | (1 << (CodeCompletionContext::CCC_Type - 1)); 111 112 // In C++, types can appear in expressions contexts (for functional casts). 113 if (LangOpts.CPlusPlus) 114 Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1)); 115 116 // In Objective-C, message sends can send interfaces. In Objective-C++, 117 // all types are available due to functional casts. 118 if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND)) 119 Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 120 121 // Deal with tag names. 122 if (isa<EnumDecl>(ND)) { 123 Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)); 124 125 // Part of the nested-name-specifier. 126 if (LangOpts.CPlusPlus0x) 127 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1)); 128 } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) { 129 if (Record->isUnion()) 130 Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1)); 131 else 132 Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 133 134 // Part of the nested-name-specifier. 135 if (LangOpts.CPlusPlus) 136 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1)); 137 } 138 } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) { 139 // Values can appear in these contexts. 140 Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1)) 141 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 142 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 143 } else if (isa<ObjCProtocolDecl>(ND)) { 144 Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)); 145 } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) { 146 Contexts = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 147 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 148 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 149 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 150 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 151 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 152 | (1 << (CodeCompletionContext::CCC_Namespace - 1)); 153 154 // Part of the nested-name-specifier. 155 Contexts |= (1 << (CodeCompletionContext::CCC_MemberAccess - 1)) 156 | (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 157 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 158 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)) 159 | (1 << (CodeCompletionContext::CCC_Type - 1)); 160 } 161 162 return Contexts; 163} 164 165void ASTUnit::CacheCodeCompletionResults() { 166 if (!TheSema) 167 return; 168 169 llvm::Timer *CachingTimer = 0; 170 if (TimerGroup.get()) { 171 CachingTimer = new llvm::Timer("Cache global code completions", 172 *TimerGroup); 173 CachingTimer->startTimer(); 174 Timers.push_back(CachingTimer); 175 } 176 177 // Clear out the previous results. 178 ClearCachedCompletionResults(); 179 180 // Gather the set of global code completions. 181 typedef CodeCompleteConsumer::Result Result; 182 llvm::SmallVector<Result, 8> Results; 183 TheSema->GatherGlobalCodeCompletions(Results); 184 185 // Translate global code completions into cached completions. 186 llvm::DenseMap<CanQualType, unsigned> CompletionTypes; 187 188 for (unsigned I = 0, N = Results.size(); I != N; ++I) { 189 switch (Results[I].Kind) { 190 case Result::RK_Declaration: { 191 CachedCodeCompletionResult CachedResult; 192 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema); 193 CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration, 194 Ctx->getLangOptions()); 195 CachedResult.Priority = Results[I].Priority; 196 CachedResult.Kind = Results[I].CursorKind; 197 198 // Keep track of the type of this completion in an ASTContext-agnostic 199 // way. 200 QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration); 201 if (UsageType.isNull()) { 202 CachedResult.TypeClass = STC_Void; 203 CachedResult.Type = 0; 204 } else { 205 CanQualType CanUsageType 206 = Ctx->getCanonicalType(UsageType.getUnqualifiedType()); 207 CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType); 208 209 // Determine whether we have already seen this type. If so, we save 210 // ourselves the work of formatting the type string by using the 211 // temporary, CanQualType-based hash table to find the associated value. 212 unsigned &TypeValue = CompletionTypes[CanUsageType]; 213 if (TypeValue == 0) { 214 TypeValue = CompletionTypes.size(); 215 CachedCompletionTypes[QualType(CanUsageType).getAsString()] 216 = TypeValue; 217 } 218 219 CachedResult.Type = TypeValue; 220 } 221 222 CachedCompletionResults.push_back(CachedResult); 223 break; 224 } 225 226 case Result::RK_Keyword: 227 case Result::RK_Pattern: 228 // Ignore keywords and patterns; we don't care, since they are so 229 // easily regenerated. 230 break; 231 232 case Result::RK_Macro: { 233 CachedCodeCompletionResult CachedResult; 234 CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema); 235 CachedResult.ShowInContexts 236 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 237 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 238 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 239 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 240 | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1)) 241 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 242 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 243 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)); 244 CachedResult.Priority = Results[I].Priority; 245 CachedResult.Kind = Results[I].CursorKind; 246 CachedResult.TypeClass = STC_Void; 247 CachedResult.Type = 0; 248 CachedCompletionResults.push_back(CachedResult); 249 break; 250 } 251 } 252 Results[I].Destroy(); 253 } 254 255 if (CachingTimer) 256 CachingTimer->stopTimer(); 257} 258 259void ASTUnit::ClearCachedCompletionResults() { 260 for (unsigned I = 0, N = CachedCompletionResults.size(); I != N; ++I) 261 delete CachedCompletionResults[I].Completion; 262 CachedCompletionResults.clear(); 263 CachedCompletionTypes.clear(); 264} 265 266namespace { 267 268/// \brief Gathers information from PCHReader that will be used to initialize 269/// a Preprocessor. 270class PCHInfoCollector : public PCHReaderListener { 271 LangOptions &LangOpt; 272 HeaderSearch &HSI; 273 std::string &TargetTriple; 274 std::string &Predefines; 275 unsigned &Counter; 276 277 unsigned NumHeaderInfos; 278 279public: 280 PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI, 281 std::string &TargetTriple, std::string &Predefines, 282 unsigned &Counter) 283 : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple), 284 Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {} 285 286 virtual bool ReadLanguageOptions(const LangOptions &LangOpts) { 287 LangOpt = LangOpts; 288 return false; 289 } 290 291 virtual bool ReadTargetTriple(llvm::StringRef Triple) { 292 TargetTriple = Triple; 293 return false; 294 } 295 296 virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers, 297 llvm::StringRef OriginalFileName, 298 std::string &SuggestedPredefines) { 299 Predefines = Buffers[0].Data; 300 for (unsigned I = 1, N = Buffers.size(); I != N; ++I) { 301 Predefines += Buffers[I].Data; 302 } 303 return false; 304 } 305 306 virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) { 307 HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++); 308 } 309 310 virtual void ReadCounter(unsigned Value) { 311 Counter = Value; 312 } 313}; 314 315class StoredDiagnosticClient : public DiagnosticClient { 316 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags; 317 318public: 319 explicit StoredDiagnosticClient( 320 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 321 : StoredDiags(StoredDiags) { } 322 323 virtual void HandleDiagnostic(Diagnostic::Level Level, 324 const DiagnosticInfo &Info); 325}; 326 327/// \brief RAII object that optionally captures diagnostics, if 328/// there is no diagnostic client to capture them already. 329class CaptureDroppedDiagnostics { 330 Diagnostic &Diags; 331 StoredDiagnosticClient Client; 332 DiagnosticClient *PreviousClient; 333 334public: 335 CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags, 336 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags) 337 : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient()) 338 { 339 if (RequestCapture || Diags.getClient() == 0) 340 Diags.setClient(&Client); 341 } 342 343 ~CaptureDroppedDiagnostics() { 344 Diags.setClient(PreviousClient); 345 } 346}; 347 348} // anonymous namespace 349 350void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level, 351 const DiagnosticInfo &Info) { 352 StoredDiags.push_back(StoredDiagnostic(Level, Info)); 353} 354 355const std::string &ASTUnit::getOriginalSourceFileName() { 356 return OriginalSourceFile; 357} 358 359const std::string &ASTUnit::getPCHFileName() { 360 assert(isMainFileAST() && "Not an ASTUnit from a PCH file!"); 361 return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName(); 362} 363 364ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename, 365 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 366 bool OnlyLocalDecls, 367 RemappedFile *RemappedFiles, 368 unsigned NumRemappedFiles, 369 bool CaptureDiagnostics) { 370 llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true)); 371 372 if (!Diags.getPtr()) { 373 // No diagnostics engine was provided, so create our own diagnostics object 374 // with the default options. 375 DiagnosticOptions DiagOpts; 376 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 377 } 378 379 AST->CaptureDiagnostics = CaptureDiagnostics; 380 AST->OnlyLocalDecls = OnlyLocalDecls; 381 AST->Diagnostics = Diags; 382 AST->FileMgr.reset(new FileManager); 383 AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics())); 384 AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager())); 385 386 // If requested, capture diagnostics in the ASTUnit. 387 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(), 388 AST->StoredDiagnostics); 389 390 for (unsigned I = 0; I != NumRemappedFiles; ++I) { 391 // Create the file entry for the file that we're mapping from. 392 const FileEntry *FromFile 393 = AST->getFileManager().getVirtualFile(RemappedFiles[I].first, 394 RemappedFiles[I].second->getBufferSize(), 395 0); 396 if (!FromFile) { 397 AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file) 398 << RemappedFiles[I].first; 399 delete RemappedFiles[I].second; 400 continue; 401 } 402 403 // Override the contents of the "from" file with the contents of 404 // the "to" file. 405 AST->getSourceManager().overrideFileContents(FromFile, 406 RemappedFiles[I].second); 407 } 408 409 // Gather Info for preprocessor construction later on. 410 411 LangOptions LangInfo; 412 HeaderSearch &HeaderInfo = *AST->HeaderInfo.get(); 413 std::string TargetTriple; 414 std::string Predefines; 415 unsigned Counter; 416 417 llvm::OwningPtr<PCHReader> Reader; 418 419 Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(), 420 AST->getDiagnostics())); 421 Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple, 422 Predefines, Counter)); 423 424 switch (Reader->ReadPCH(Filename)) { 425 case PCHReader::Success: 426 break; 427 428 case PCHReader::Failure: 429 case PCHReader::IgnorePCH: 430 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch); 431 return NULL; 432 } 433 434 AST->OriginalSourceFile = Reader->getOriginalSourceFile(); 435 436 // PCH loaded successfully. Now create the preprocessor. 437 438 // Get information about the target being compiled for. 439 // 440 // FIXME: This is broken, we should store the TargetOptions in the PCH. 441 TargetOptions TargetOpts; 442 TargetOpts.ABI = ""; 443 TargetOpts.CXXABI = "itanium"; 444 TargetOpts.CPU = ""; 445 TargetOpts.Features.clear(); 446 TargetOpts.Triple = TargetTriple; 447 AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(), 448 TargetOpts)); 449 AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo, 450 *AST->Target.get(), 451 AST->getSourceManager(), HeaderInfo)); 452 Preprocessor &PP = *AST->PP.get(); 453 454 PP.setPredefines(Reader->getSuggestedPredefines()); 455 PP.setCounterValue(Counter); 456 Reader->setPreprocessor(PP); 457 458 // Create and initialize the ASTContext. 459 460 AST->Ctx.reset(new ASTContext(LangInfo, 461 AST->getSourceManager(), 462 *AST->Target.get(), 463 PP.getIdentifierTable(), 464 PP.getSelectorTable(), 465 PP.getBuiltinInfo(), 466 /* size_reserve = */0)); 467 ASTContext &Context = *AST->Ctx.get(); 468 469 Reader->InitializeContext(Context); 470 471 // Attach the PCH reader to the AST context as an external AST 472 // source, so that declarations will be deserialized from the 473 // PCH file as needed. 474 PCHReader *ReaderPtr = Reader.get(); 475 llvm::OwningPtr<ExternalASTSource> Source(Reader.take()); 476 Context.setExternalSource(Source); 477 478 // Create an AST consumer, even though it isn't used. 479 AST->Consumer.reset(new ASTConsumer); 480 481 // Create a semantic analysis object and tell the PCH reader about it. 482 AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer)); 483 AST->TheSema->Initialize(); 484 ReaderPtr->InitializeSema(*AST->TheSema); 485 486 return AST.take(); 487} 488 489namespace { 490 491class TopLevelDeclTrackerConsumer : public ASTConsumer { 492 ASTUnit &Unit; 493 494public: 495 TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {} 496 497 void HandleTopLevelDecl(DeclGroupRef D) { 498 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 499 Decl *D = *it; 500 // FIXME: Currently ObjC method declarations are incorrectly being 501 // reported as top-level declarations, even though their DeclContext 502 // is the containing ObjC @interface/@implementation. This is a 503 // fundamental problem in the parser right now. 504 if (isa<ObjCMethodDecl>(D)) 505 continue; 506 Unit.addTopLevelDecl(D); 507 } 508 } 509 510 // We're not interested in "interesting" decls. 511 void HandleInterestingDecl(DeclGroupRef) {} 512}; 513 514class TopLevelDeclTrackerAction : public ASTFrontendAction { 515public: 516 ASTUnit &Unit; 517 518 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 519 llvm::StringRef InFile) { 520 return new TopLevelDeclTrackerConsumer(Unit); 521 } 522 523public: 524 TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {} 525 526 virtual bool hasCodeCompletionSupport() const { return false; } 527 virtual bool usesCompleteTranslationUnit() { 528 return Unit.isCompleteTranslationUnit(); 529 } 530}; 531 532class PrecompilePreambleConsumer : public PCHGenerator { 533 ASTUnit &Unit; 534 std::vector<Decl *> TopLevelDecls; 535 536public: 537 PrecompilePreambleConsumer(ASTUnit &Unit, 538 const Preprocessor &PP, bool Chaining, 539 const char *isysroot, llvm::raw_ostream *Out) 540 : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { } 541 542 virtual void HandleTopLevelDecl(DeclGroupRef D) { 543 for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) { 544 Decl *D = *it; 545 // FIXME: Currently ObjC method declarations are incorrectly being 546 // reported as top-level declarations, even though their DeclContext 547 // is the containing ObjC @interface/@implementation. This is a 548 // fundamental problem in the parser right now. 549 if (isa<ObjCMethodDecl>(D)) 550 continue; 551 TopLevelDecls.push_back(D); 552 } 553 } 554 555 virtual void HandleTranslationUnit(ASTContext &Ctx) { 556 PCHGenerator::HandleTranslationUnit(Ctx); 557 if (!Unit.getDiagnostics().hasErrorOccurred()) { 558 // Translate the top-level declarations we captured during 559 // parsing into declaration IDs in the precompiled 560 // preamble. This will allow us to deserialize those top-level 561 // declarations when requested. 562 for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I) 563 Unit.addTopLevelDeclFromPreamble( 564 getWriter().getDeclID(TopLevelDecls[I])); 565 } 566 } 567}; 568 569class PrecompilePreambleAction : public ASTFrontendAction { 570 ASTUnit &Unit; 571 572public: 573 explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {} 574 575 virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI, 576 llvm::StringRef InFile) { 577 std::string Sysroot; 578 llvm::raw_ostream *OS = 0; 579 bool Chaining; 580 if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot, 581 OS, Chaining)) 582 return 0; 583 584 const char *isysroot = CI.getFrontendOpts().RelocatablePCH ? 585 Sysroot.c_str() : 0; 586 return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining, 587 isysroot, OS); 588 } 589 590 virtual bool hasCodeCompletionSupport() const { return false; } 591 virtual bool hasASTFileSupport() const { return false; } 592 virtual bool usesCompleteTranslationUnit() { return false; } 593}; 594 595} 596 597/// Parse the source file into a translation unit using the given compiler 598/// invocation, replacing the current translation unit. 599/// 600/// \returns True if a failure occurred that causes the ASTUnit not to 601/// contain any translation-unit information, false otherwise. 602bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) { 603 delete SavedMainFileBuffer; 604 SavedMainFileBuffer = 0; 605 606 if (!Invocation.get()) 607 return true; 608 609 // Create the compiler instance to use for building the AST. 610 CompilerInstance Clang; 611 Clang.setInvocation(Invocation.take()); 612 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 613 614 // Set up diagnostics, capturing any diagnostics that would 615 // otherwise be dropped. 616 Clang.setDiagnostics(&getDiagnostics()); 617 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, 618 getDiagnostics(), 619 StoredDiagnostics); 620 Clang.setDiagnosticClient(getDiagnostics().getClient()); 621 622 // Create the target instance. 623 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 624 Clang.getTargetOpts())); 625 if (!Clang.hasTarget()) { 626 Clang.takeDiagnosticClient(); 627 return true; 628 } 629 630 // Inform the target of the language options. 631 // 632 // FIXME: We shouldn't need to do this, the target should be immutable once 633 // created. This complexity should be lifted elsewhere. 634 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 635 636 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 637 "Invocation must have exactly one source file!"); 638 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 639 "FIXME: AST inputs not yet supported here!"); 640 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 641 "IR inputs not support here!"); 642 643 // Configure the various subsystems. 644 // FIXME: Should we retain the previous file manager? 645 FileMgr.reset(new FileManager); 646 SourceMgr.reset(new SourceManager(getDiagnostics())); 647 TheSema.reset(); 648 Ctx.reset(); 649 PP.reset(); 650 651 // Clear out old caches and data. 652 TopLevelDecls.clear(); 653 CleanTemporaryFiles(); 654 PreprocessedEntitiesByFile.clear(); 655 656 if (!OverrideMainBuffer) 657 StoredDiagnostics.clear(); 658 659 // Create a file manager object to provide access to and cache the filesystem. 660 Clang.setFileManager(&getFileManager()); 661 662 // Create the source manager. 663 Clang.setSourceManager(&getSourceManager()); 664 665 // If the main file has been overridden due to the use of a preamble, 666 // make that override happen and introduce the preamble. 667 PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts(); 668 std::string PriorImplicitPCHInclude; 669 if (OverrideMainBuffer) { 670 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 671 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 672 PreprocessorOpts.PrecompiledPreambleBytes.second 673 = PreambleEndsAtStartOfLine; 674 PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude; 675 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 676 PreprocessorOpts.DisablePCHValidation = true; 677 678 // Keep track of the override buffer; 679 SavedMainFileBuffer = OverrideMainBuffer; 680 681 // The stored diagnostic has the old source manager in it; update 682 // the locations to refer into the new source manager. Since we've 683 // been careful to make sure that the source manager's state 684 // before and after are identical, so that we can reuse the source 685 // location itself. 686 for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) { 687 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), 688 getSourceManager()); 689 StoredDiagnostics[I].setLocation(Loc); 690 } 691 } 692 693 llvm::OwningPtr<TopLevelDeclTrackerAction> Act; 694 Act.reset(new TopLevelDeclTrackerAction(*this)); 695 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 696 Clang.getFrontendOpts().Inputs[0].first)) 697 goto error; 698 699 Act->Execute(); 700 701 // Steal the created target, context, and preprocessor, and take back the 702 // source and file managers. 703 TheSema.reset(Clang.takeSema()); 704 Consumer.reset(Clang.takeASTConsumer()); 705 Ctx.reset(Clang.takeASTContext()); 706 PP.reset(Clang.takePreprocessor()); 707 Clang.takeSourceManager(); 708 Clang.takeFileManager(); 709 Target.reset(Clang.takeTarget()); 710 711 Act->EndSourceFile(); 712 713 // Remove the overridden buffer we used for the preamble. 714 if (OverrideMainBuffer) { 715 PreprocessorOpts.eraseRemappedFile( 716 PreprocessorOpts.remapped_file_buffer_end() - 1); 717 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 718 } 719 720 Clang.takeDiagnosticClient(); 721 722 Invocation.reset(Clang.takeInvocation()); 723 724 // If we were asked to cache code-completion results and don't have any 725 // results yet, do so now. 726 if (ShouldCacheCodeCompletionResults && CachedCompletionResults.empty()) 727 CacheCodeCompletionResults(); 728 729 return false; 730 731error: 732 // Remove the overridden buffer we used for the preamble. 733 if (OverrideMainBuffer) { 734 PreprocessorOpts.eraseRemappedFile( 735 PreprocessorOpts.remapped_file_buffer_end() - 1); 736 PreprocessorOpts.DisablePCHValidation = true; 737 PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude; 738 } 739 740 Clang.takeSourceManager(); 741 Clang.takeFileManager(); 742 Clang.takeDiagnosticClient(); 743 Invocation.reset(Clang.takeInvocation()); 744 return true; 745} 746 747/// \brief Simple function to retrieve a path for a preamble precompiled header. 748static std::string GetPreamblePCHPath() { 749 // FIXME: This is lame; sys::Path should provide this function (in particular, 750 // it should know how to find the temporary files dir). 751 // FIXME: This is really lame. I copied this code from the Driver! 752 std::string Error; 753 const char *TmpDir = ::getenv("TMPDIR"); 754 if (!TmpDir) 755 TmpDir = ::getenv("TEMP"); 756 if (!TmpDir) 757 TmpDir = ::getenv("TMP"); 758 if (!TmpDir) 759 TmpDir = "/tmp"; 760 llvm::sys::Path P(TmpDir); 761 P.appendComponent("preamble"); 762 P.appendSuffix("pch"); 763 if (P.createTemporaryFileOnDisk()) 764 return std::string(); 765 766 return P.str(); 767} 768 769/// \brief Compute the preamble for the main file, providing the source buffer 770/// that corresponds to the main file along with a pair (bytes, start-of-line) 771/// that describes the preamble. 772std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > 773ASTUnit::ComputePreamble(CompilerInvocation &Invocation, 774 unsigned MaxLines, bool &CreatedBuffer) { 775 FrontendOptions &FrontendOpts = Invocation.getFrontendOpts(); 776 PreprocessorOptions &PreprocessorOpts 777 = Invocation.getPreprocessorOpts(); 778 CreatedBuffer = false; 779 780 // Try to determine if the main file has been remapped, either from the 781 // command line (to another file) or directly through the compiler invocation 782 // (to a memory buffer). 783 llvm::MemoryBuffer *Buffer = 0; 784 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 785 if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) { 786 // Check whether there is a file-file remapping of the main file 787 for (PreprocessorOptions::remapped_file_iterator 788 M = PreprocessorOpts.remapped_file_begin(), 789 E = PreprocessorOpts.remapped_file_end(); 790 M != E; 791 ++M) { 792 llvm::sys::PathWithStatus MPath(M->first); 793 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 794 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 795 // We found a remapping. Try to load the resulting, remapped source. 796 if (CreatedBuffer) { 797 delete Buffer; 798 CreatedBuffer = false; 799 } 800 801 Buffer = llvm::MemoryBuffer::getFile(M->second); 802 if (!Buffer) 803 return std::make_pair((llvm::MemoryBuffer*)0, 804 std::make_pair(0, true)); 805 CreatedBuffer = true; 806 807 // Remove this remapping. We've captured the buffer already. 808 M = PreprocessorOpts.eraseRemappedFile(M); 809 E = PreprocessorOpts.remapped_file_end(); 810 } 811 } 812 } 813 814 // Check whether there is a file-buffer remapping. It supercedes the 815 // file-file remapping. 816 for (PreprocessorOptions::remapped_file_buffer_iterator 817 M = PreprocessorOpts.remapped_file_buffer_begin(), 818 E = PreprocessorOpts.remapped_file_buffer_end(); 819 M != E; 820 ++M) { 821 llvm::sys::PathWithStatus MPath(M->first); 822 if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) { 823 if (MainFileStatus->uniqueID == MStatus->uniqueID) { 824 // We found a remapping. 825 if (CreatedBuffer) { 826 delete Buffer; 827 CreatedBuffer = false; 828 } 829 830 Buffer = const_cast<llvm::MemoryBuffer *>(M->second); 831 832 // Remove this remapping. We've captured the buffer already. 833 M = PreprocessorOpts.eraseRemappedFile(M); 834 E = PreprocessorOpts.remapped_file_buffer_end(); 835 } 836 } 837 } 838 } 839 840 // If the main source file was not remapped, load it now. 841 if (!Buffer) { 842 Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second); 843 if (!Buffer) 844 return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true)); 845 846 CreatedBuffer = true; 847 } 848 849 return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines)); 850} 851 852static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old, 853 bool DeleteOld, 854 unsigned NewSize, 855 llvm::StringRef NewName) { 856 llvm::MemoryBuffer *Result 857 = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName); 858 memcpy(const_cast<char*>(Result->getBufferStart()), 859 Old->getBufferStart(), Old->getBufferSize()); 860 memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(), 861 ' ', NewSize - Old->getBufferSize() - 1); 862 const_cast<char*>(Result->getBufferEnd())[-1] = '\n'; 863 864 if (DeleteOld) 865 delete Old; 866 867 return Result; 868} 869 870/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing 871/// the source file. 872/// 873/// This routine will compute the preamble of the main source file. If a 874/// non-trivial preamble is found, it will precompile that preamble into a 875/// precompiled header so that the precompiled preamble can be used to reduce 876/// reparsing time. If a precompiled preamble has already been constructed, 877/// this routine will determine if it is still valid and, if so, avoid 878/// rebuilding the precompiled preamble. 879/// 880/// \param AllowRebuild When true (the default), this routine is 881/// allowed to rebuild the precompiled preamble if it is found to be 882/// out-of-date. 883/// 884/// \param MaxLines When non-zero, the maximum number of lines that 885/// can occur within the preamble. 886/// 887/// \returns If the precompiled preamble can be used, returns a newly-allocated 888/// buffer that should be used in place of the main file when doing so. 889/// Otherwise, returns a NULL pointer. 890llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble( 891 bool AllowRebuild, 892 unsigned MaxLines) { 893 CompilerInvocation PreambleInvocation(*Invocation); 894 FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts(); 895 PreprocessorOptions &PreprocessorOpts 896 = PreambleInvocation.getPreprocessorOpts(); 897 898 bool CreatedPreambleBuffer = false; 899 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble 900 = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer); 901 902 if (!NewPreamble.second.first) { 903 // We couldn't find a preamble in the main source. Clear out the current 904 // preamble, if we have one. It's obviously no good any more. 905 Preamble.clear(); 906 if (!PreambleFile.empty()) { 907 llvm::sys::Path(PreambleFile).eraseFromDisk(); 908 PreambleFile.clear(); 909 } 910 if (CreatedPreambleBuffer) 911 delete NewPreamble.first; 912 913 // The next time we actually see a preamble, precompile it. 914 PreambleRebuildCounter = 1; 915 return 0; 916 } 917 918 if (!Preamble.empty()) { 919 // We've previously computed a preamble. Check whether we have the same 920 // preamble now that we did before, and that there's enough space in 921 // the main-file buffer within the precompiled preamble to fit the 922 // new main file. 923 if (Preamble.size() == NewPreamble.second.first && 924 PreambleEndsAtStartOfLine == NewPreamble.second.second && 925 NewPreamble.first->getBufferSize() < PreambleReservedSize-2 && 926 memcmp(&Preamble[0], NewPreamble.first->getBufferStart(), 927 NewPreamble.second.first) == 0) { 928 // The preamble has not changed. We may be able to re-use the precompiled 929 // preamble. 930 931 // Check that none of the files used by the preamble have changed. 932 bool AnyFileChanged = false; 933 934 // First, make a record of those files that have been overridden via 935 // remapping or unsaved_files. 936 llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles; 937 for (PreprocessorOptions::remapped_file_iterator 938 R = PreprocessorOpts.remapped_file_begin(), 939 REnd = PreprocessorOpts.remapped_file_end(); 940 !AnyFileChanged && R != REnd; 941 ++R) { 942 struct stat StatBuf; 943 if (stat(R->second.c_str(), &StatBuf)) { 944 // If we can't stat the file we're remapping to, assume that something 945 // horrible happened. 946 AnyFileChanged = true; 947 break; 948 } 949 950 OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size, 951 StatBuf.st_mtime); 952 } 953 for (PreprocessorOptions::remapped_file_buffer_iterator 954 R = PreprocessorOpts.remapped_file_buffer_begin(), 955 REnd = PreprocessorOpts.remapped_file_buffer_end(); 956 !AnyFileChanged && R != REnd; 957 ++R) { 958 // FIXME: Should we actually compare the contents of file->buffer 959 // remappings? 960 OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(), 961 0); 962 } 963 964 // Check whether anything has changed. 965 for (llvm::StringMap<std::pair<off_t, time_t> >::iterator 966 F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end(); 967 !AnyFileChanged && F != FEnd; 968 ++F) { 969 llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden 970 = OverriddenFiles.find(F->first()); 971 if (Overridden != OverriddenFiles.end()) { 972 // This file was remapped; check whether the newly-mapped file 973 // matches up with the previous mapping. 974 if (Overridden->second != F->second) 975 AnyFileChanged = true; 976 continue; 977 } 978 979 // The file was not remapped; check whether it has changed on disk. 980 struct stat StatBuf; 981 if (stat(F->first(), &StatBuf)) { 982 // If we can't stat the file, assume that something horrible happened. 983 AnyFileChanged = true; 984 } else if (StatBuf.st_size != F->second.first || 985 StatBuf.st_mtime != F->second.second) 986 AnyFileChanged = true; 987 } 988 989 if (!AnyFileChanged) { 990 // Okay! We can re-use the precompiled preamble. 991 992 // Set the state of the diagnostic object to mimic its state 993 // after parsing the preamble. 994 getDiagnostics().Reset(); 995 getDiagnostics().setNumWarnings(NumWarningsInPreamble); 996 if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble) 997 StoredDiagnostics.erase( 998 StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble, 999 StoredDiagnostics.end()); 1000 1001 // Create a version of the main file buffer that is padded to 1002 // buffer size we reserved when creating the preamble. 1003 return CreatePaddedMainFileBuffer(NewPreamble.first, 1004 CreatedPreambleBuffer, 1005 PreambleReservedSize, 1006 FrontendOpts.Inputs[0].second); 1007 } 1008 } 1009 1010 // If we aren't allowed to rebuild the precompiled preamble, just 1011 // return now. 1012 if (!AllowRebuild) 1013 return 0; 1014 1015 // We can't reuse the previously-computed preamble. Build a new one. 1016 Preamble.clear(); 1017 llvm::sys::Path(PreambleFile).eraseFromDisk(); 1018 PreambleRebuildCounter = 1; 1019 } else if (!AllowRebuild) { 1020 // We aren't allowed to rebuild the precompiled preamble; just 1021 // return now. 1022 return 0; 1023 } 1024 1025 // If the preamble rebuild counter > 1, it's because we previously 1026 // failed to build a preamble and we're not yet ready to try 1027 // again. Decrement the counter and return a failure. 1028 if (PreambleRebuildCounter > 1) { 1029 --PreambleRebuildCounter; 1030 return 0; 1031 } 1032 1033 // We did not previously compute a preamble, or it can't be reused anyway. 1034 llvm::Timer *PreambleTimer = 0; 1035 if (TimerGroup.get()) { 1036 PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup); 1037 PreambleTimer->startTimer(); 1038 Timers.push_back(PreambleTimer); 1039 } 1040 1041 // Create a new buffer that stores the preamble. The buffer also contains 1042 // extra space for the original contents of the file (which will be present 1043 // when we actually parse the file) along with more room in case the file 1044 // grows. 1045 PreambleReservedSize = NewPreamble.first->getBufferSize(); 1046 if (PreambleReservedSize < 4096) 1047 PreambleReservedSize = 8191; 1048 else 1049 PreambleReservedSize *= 2; 1050 1051 // Save the preamble text for later; we'll need to compare against it for 1052 // subsequent reparses. 1053 Preamble.assign(NewPreamble.first->getBufferStart(), 1054 NewPreamble.first->getBufferStart() 1055 + NewPreamble.second.first); 1056 PreambleEndsAtStartOfLine = NewPreamble.second.second; 1057 1058 llvm::MemoryBuffer *PreambleBuffer 1059 = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize, 1060 FrontendOpts.Inputs[0].second); 1061 memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()), 1062 NewPreamble.first->getBufferStart(), Preamble.size()); 1063 memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(), 1064 ' ', PreambleReservedSize - Preamble.size() - 1); 1065 const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n'; 1066 1067 // Remap the main source file to the preamble buffer. 1068 llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second); 1069 PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer); 1070 1071 // Tell the compiler invocation to generate a temporary precompiled header. 1072 FrontendOpts.ProgramAction = frontend::GeneratePCH; 1073 // FIXME: Set ChainedPCH unconditionally, once it is ready. 1074 if (::getenv("LIBCLANG_CHAINING")) 1075 FrontendOpts.ChainedPCH = true; 1076 // FIXME: Generate the precompiled header into memory? 1077 FrontendOpts.OutputFile = GetPreamblePCHPath(); 1078 1079 // Create the compiler instance to use for building the precompiled preamble. 1080 CompilerInstance Clang; 1081 Clang.setInvocation(&PreambleInvocation); 1082 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 1083 1084 // Set up diagnostics, capturing all of the diagnostics produced. 1085 Clang.setDiagnostics(&getDiagnostics()); 1086 CaptureDroppedDiagnostics Capture(CaptureDiagnostics, 1087 getDiagnostics(), 1088 StoredDiagnostics); 1089 Clang.setDiagnosticClient(getDiagnostics().getClient()); 1090 1091 // Create the target instance. 1092 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 1093 Clang.getTargetOpts())); 1094 if (!Clang.hasTarget()) { 1095 Clang.takeDiagnosticClient(); 1096 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1097 Preamble.clear(); 1098 if (CreatedPreambleBuffer) 1099 delete NewPreamble.first; 1100 if (PreambleTimer) 1101 PreambleTimer->stopTimer(); 1102 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1103 return 0; 1104 } 1105 1106 // Inform the target of the language options. 1107 // 1108 // FIXME: We shouldn't need to do this, the target should be immutable once 1109 // created. This complexity should be lifted elsewhere. 1110 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 1111 1112 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 1113 "Invocation must have exactly one source file!"); 1114 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 1115 "FIXME: AST inputs not yet supported here!"); 1116 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1117 "IR inputs not support here!"); 1118 1119 // Clear out old caches and data. 1120 StoredDiagnostics.clear(); 1121 TopLevelDecls.clear(); 1122 TopLevelDeclsInPreamble.clear(); 1123 1124 // Create a file manager object to provide access to and cache the filesystem. 1125 Clang.setFileManager(new FileManager); 1126 1127 // Create the source manager. 1128 Clang.setSourceManager(new SourceManager(getDiagnostics())); 1129 1130 llvm::OwningPtr<PrecompilePreambleAction> Act; 1131 Act.reset(new PrecompilePreambleAction(*this)); 1132 if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 1133 Clang.getFrontendOpts().Inputs[0].first)) { 1134 Clang.takeDiagnosticClient(); 1135 Clang.takeInvocation(); 1136 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1137 Preamble.clear(); 1138 if (CreatedPreambleBuffer) 1139 delete NewPreamble.first; 1140 if (PreambleTimer) 1141 PreambleTimer->stopTimer(); 1142 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1143 1144 return 0; 1145 } 1146 1147 Act->Execute(); 1148 Act->EndSourceFile(); 1149 Clang.takeDiagnosticClient(); 1150 Clang.takeInvocation(); 1151 1152 if (Diagnostics->hasErrorOccurred()) { 1153 // There were errors parsing the preamble, so no precompiled header was 1154 // generated. Forget that we even tried. 1155 // FIXME: Should we leave a note for ourselves to try again? 1156 llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk(); 1157 Preamble.clear(); 1158 if (CreatedPreambleBuffer) 1159 delete NewPreamble.first; 1160 if (PreambleTimer) 1161 PreambleTimer->stopTimer(); 1162 TopLevelDeclsInPreamble.clear(); 1163 PreambleRebuildCounter = DefaultPreambleRebuildInterval; 1164 return 0; 1165 } 1166 1167 // Keep track of the preamble we precompiled. 1168 PreambleFile = FrontendOpts.OutputFile; 1169 NumStoredDiagnosticsInPreamble = StoredDiagnostics.size(); 1170 NumWarningsInPreamble = getDiagnostics().getNumWarnings(); 1171 1172 // Keep track of all of the files that the source manager knows about, 1173 // so we can verify whether they have changed or not. 1174 FilesInPreamble.clear(); 1175 SourceManager &SourceMgr = Clang.getSourceManager(); 1176 const llvm::MemoryBuffer *MainFileBuffer 1177 = SourceMgr.getBuffer(SourceMgr.getMainFileID()); 1178 for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(), 1179 FEnd = SourceMgr.fileinfo_end(); 1180 F != FEnd; 1181 ++F) { 1182 const FileEntry *File = F->second->Entry; 1183 if (!File || F->second->getRawBuffer() == MainFileBuffer) 1184 continue; 1185 1186 FilesInPreamble[File->getName()] 1187 = std::make_pair(F->second->getSize(), File->getModificationTime()); 1188 } 1189 1190 if (PreambleTimer) 1191 PreambleTimer->stopTimer(); 1192 1193 PreambleRebuildCounter = 1; 1194 return CreatePaddedMainFileBuffer(NewPreamble.first, 1195 CreatedPreambleBuffer, 1196 PreambleReservedSize, 1197 FrontendOpts.Inputs[0].second); 1198} 1199 1200void ASTUnit::RealizeTopLevelDeclsFromPreamble() { 1201 std::vector<Decl *> Resolved; 1202 Resolved.reserve(TopLevelDeclsInPreamble.size()); 1203 ExternalASTSource &Source = *getASTContext().getExternalSource(); 1204 for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) { 1205 // Resolve the declaration ID to an actual declaration, possibly 1206 // deserializing the declaration in the process. 1207 Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]); 1208 if (D) 1209 Resolved.push_back(D); 1210 } 1211 TopLevelDeclsInPreamble.clear(); 1212 TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end()); 1213} 1214 1215unsigned ASTUnit::getMaxPCHLevel() const { 1216 if (!getOnlyLocalDecls()) 1217 return Decl::MaxPCHLevel; 1218 1219 unsigned Result = 0; 1220 if (isMainFileAST() || SavedMainFileBuffer) 1221 ++Result; 1222 return Result; 1223} 1224 1225ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI, 1226 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1227 bool OnlyLocalDecls, 1228 bool CaptureDiagnostics, 1229 bool PrecompilePreamble, 1230 bool CompleteTranslationUnit, 1231 bool CacheCodeCompletionResults) { 1232 if (!Diags.getPtr()) { 1233 // No diagnostics engine was provided, so create our own diagnostics object 1234 // with the default options. 1235 DiagnosticOptions DiagOpts; 1236 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 1237 } 1238 1239 // Create the AST unit. 1240 llvm::OwningPtr<ASTUnit> AST; 1241 AST.reset(new ASTUnit(false)); 1242 AST->Diagnostics = Diags; 1243 AST->CaptureDiagnostics = CaptureDiagnostics; 1244 AST->OnlyLocalDecls = OnlyLocalDecls; 1245 AST->CompleteTranslationUnit = CompleteTranslationUnit; 1246 AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults; 1247 AST->Invocation.reset(CI); 1248 CI->getPreprocessorOpts().RetainRemappedFileBuffers = true; 1249 1250 if (getenv("LIBCLANG_TIMING")) 1251 AST->TimerGroup.reset( 1252 new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second)); 1253 1254 1255 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1256 // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble. 1257 if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) { 1258 AST->PreambleRebuildCounter = 1; 1259 OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble(); 1260 } 1261 1262 llvm::Timer *ParsingTimer = 0; 1263 if (AST->TimerGroup.get()) { 1264 ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup); 1265 ParsingTimer->startTimer(); 1266 AST->Timers.push_back(ParsingTimer); 1267 } 1268 1269 bool Failed = AST->Parse(OverrideMainBuffer); 1270 if (ParsingTimer) 1271 ParsingTimer->stopTimer(); 1272 1273 return Failed? 0 : AST.take(); 1274} 1275 1276ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin, 1277 const char **ArgEnd, 1278 llvm::IntrusiveRefCntPtr<Diagnostic> Diags, 1279 llvm::StringRef ResourceFilesPath, 1280 bool OnlyLocalDecls, 1281 RemappedFile *RemappedFiles, 1282 unsigned NumRemappedFiles, 1283 bool CaptureDiagnostics, 1284 bool PrecompilePreamble, 1285 bool CompleteTranslationUnit, 1286 bool CacheCodeCompletionResults) { 1287 if (!Diags.getPtr()) { 1288 // No diagnostics engine was provided, so create our own diagnostics object 1289 // with the default options. 1290 DiagnosticOptions DiagOpts; 1291 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); 1292 } 1293 1294 llvm::SmallVector<const char *, 16> Args; 1295 Args.push_back("<clang>"); // FIXME: Remove dummy argument. 1296 Args.insert(Args.end(), ArgBegin, ArgEnd); 1297 1298 // FIXME: Find a cleaner way to force the driver into restricted modes. We 1299 // also want to force it to use clang. 1300 Args.push_back("-fsyntax-only"); 1301 1302 // FIXME: We shouldn't have to pass in the path info. 1303 driver::Driver TheDriver("clang", llvm::sys::getHostTriple(), 1304 "a.out", false, false, *Diags); 1305 1306 // Don't check that inputs exist, they have been remapped. 1307 TheDriver.setCheckInputsExist(false); 1308 1309 llvm::OwningPtr<driver::Compilation> C( 1310 TheDriver.BuildCompilation(Args.size(), Args.data())); 1311 1312 // We expect to get back exactly one command job, if we didn't something 1313 // failed. 1314 const driver::JobList &Jobs = C->getJobs(); 1315 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) { 1316 llvm::SmallString<256> Msg; 1317 llvm::raw_svector_ostream OS(Msg); 1318 C->PrintJob(OS, C->getJobs(), "; ", true); 1319 Diags->Report(diag::err_fe_expected_compiler_job) << OS.str(); 1320 return 0; 1321 } 1322 1323 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin()); 1324 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") { 1325 Diags->Report(diag::err_fe_expected_clang_command); 1326 return 0; 1327 } 1328 1329 const driver::ArgStringList &CCArgs = Cmd->getArguments(); 1330 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation); 1331 CompilerInvocation::CreateFromArgs(*CI, 1332 const_cast<const char **>(CCArgs.data()), 1333 const_cast<const char **>(CCArgs.data()) + 1334 CCArgs.size(), 1335 *Diags); 1336 1337 // Override any files that need remapping 1338 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1339 CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1340 RemappedFiles[I].second); 1341 1342 // Override the resources path. 1343 CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath; 1344 1345 CI->getFrontendOpts().DisableFree = true; 1346 return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls, 1347 CaptureDiagnostics, PrecompilePreamble, 1348 CompleteTranslationUnit, 1349 CacheCodeCompletionResults); 1350} 1351 1352bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) { 1353 if (!Invocation.get()) 1354 return true; 1355 1356 llvm::Timer *ReparsingTimer = 0; 1357 if (TimerGroup.get()) { 1358 ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup); 1359 ReparsingTimer->startTimer(); 1360 Timers.push_back(ReparsingTimer); 1361 } 1362 1363 // Remap files. 1364 Invocation->getPreprocessorOpts().clearRemappedFiles(); 1365 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1366 Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, 1367 RemappedFiles[I].second); 1368 1369 // If we have a preamble file lying around, or if we might try to 1370 // build a precompiled preamble, do so now. 1371 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1372 if (!PreambleFile.empty() || PreambleRebuildCounter > 0) 1373 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(); 1374 1375 // Clear out the diagnostics state. 1376 if (!OverrideMainBuffer) 1377 getDiagnostics().Reset(); 1378 1379 // Parse the sources 1380 bool Result = Parse(OverrideMainBuffer); 1381 if (ReparsingTimer) 1382 ReparsingTimer->stopTimer(); 1383 return Result; 1384} 1385 1386//----------------------------------------------------------------------------// 1387// Code completion 1388//----------------------------------------------------------------------------// 1389 1390namespace { 1391 /// \brief Code completion consumer that combines the cached code-completion 1392 /// results from an ASTUnit with the code-completion results provided to it, 1393 /// then passes the result on to 1394 class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer { 1395 unsigned NormalContexts; 1396 ASTUnit &AST; 1397 CodeCompleteConsumer &Next; 1398 1399 public: 1400 AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next, 1401 bool IncludeMacros, bool IncludeCodePatterns, 1402 bool IncludeGlobals) 1403 : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals, 1404 Next.isOutputBinary()), AST(AST), Next(Next) 1405 { 1406 // Compute the set of contexts in which we will look when we don't have 1407 // any information about the specific context. 1408 NormalContexts 1409 = (1 << (CodeCompletionContext::CCC_TopLevel - 1)) 1410 | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1)) 1411 | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1)) 1412 | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1)) 1413 | (1 << (CodeCompletionContext::CCC_Statement - 1)) 1414 | (1 << (CodeCompletionContext::CCC_Expression - 1)) 1415 | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1)) 1416 | (1 << (CodeCompletionContext::CCC_MemberAccess - 1)) 1417 | (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1)); 1418 1419 if (AST.getASTContext().getLangOptions().CPlusPlus) 1420 NormalContexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1)) 1421 | (1 << (CodeCompletionContext::CCC_UnionTag - 1)) 1422 | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1)); 1423 } 1424 1425 virtual void ProcessCodeCompleteResults(Sema &S, 1426 CodeCompletionContext Context, 1427 Result *Results, 1428 unsigned NumResults); 1429 1430 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 1431 OverloadCandidate *Candidates, 1432 unsigned NumCandidates) { 1433 Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates); 1434 } 1435 }; 1436} 1437 1438/// \brief Helper function that computes which global names are hidden by the 1439/// local code-completion results. 1440void CalculateHiddenNames(const CodeCompletionContext &Context, 1441 CodeCompleteConsumer::Result *Results, 1442 unsigned NumResults, 1443 ASTContext &Ctx, 1444 llvm::StringSet<> &HiddenNames) { 1445 bool OnlyTagNames = false; 1446 switch (Context.getKind()) { 1447 case CodeCompletionContext::CCC_Other: 1448 case CodeCompletionContext::CCC_TopLevel: 1449 case CodeCompletionContext::CCC_ObjCInterface: 1450 case CodeCompletionContext::CCC_ObjCImplementation: 1451 case CodeCompletionContext::CCC_ObjCIvarList: 1452 case CodeCompletionContext::CCC_ClassStructUnion: 1453 case CodeCompletionContext::CCC_Statement: 1454 case CodeCompletionContext::CCC_Expression: 1455 case CodeCompletionContext::CCC_ObjCMessageReceiver: 1456 case CodeCompletionContext::CCC_MemberAccess: 1457 case CodeCompletionContext::CCC_Namespace: 1458 case CodeCompletionContext::CCC_Type: 1459 break; 1460 1461 case CodeCompletionContext::CCC_EnumTag: 1462 case CodeCompletionContext::CCC_UnionTag: 1463 case CodeCompletionContext::CCC_ClassOrStructTag: 1464 OnlyTagNames = true; 1465 break; 1466 1467 case CodeCompletionContext::CCC_ObjCProtocolName: 1468 // If we're just looking for protocol names, nothing can hide them. 1469 return; 1470 } 1471 1472 typedef CodeCompleteConsumer::Result Result; 1473 for (unsigned I = 0; I != NumResults; ++I) { 1474 if (Results[I].Kind != Result::RK_Declaration) 1475 continue; 1476 1477 unsigned IDNS 1478 = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace(); 1479 1480 bool Hiding = false; 1481 if (OnlyTagNames) 1482 Hiding = (IDNS & Decl::IDNS_Tag); 1483 else { 1484 unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member | 1485 Decl::IDNS_Namespace | Decl::IDNS_Ordinary | 1486 Decl::IDNS_NonMemberOperator); 1487 if (Ctx.getLangOptions().CPlusPlus) 1488 HiddenIDNS |= Decl::IDNS_Tag; 1489 Hiding = (IDNS & HiddenIDNS); 1490 } 1491 1492 if (!Hiding) 1493 continue; 1494 1495 DeclarationName Name = Results[I].Declaration->getDeclName(); 1496 if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo()) 1497 HiddenNames.insert(Identifier->getName()); 1498 else 1499 HiddenNames.insert(Name.getAsString()); 1500 } 1501} 1502 1503 1504void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S, 1505 CodeCompletionContext Context, 1506 Result *Results, 1507 unsigned NumResults) { 1508 // Merge the results we were given with the results we cached. 1509 bool AddedResult = false; 1510 unsigned InContexts 1511 = (Context.getKind() == CodeCompletionContext::CCC_Other? NormalContexts 1512 : (1 << (Context.getKind() - 1))); 1513 1514 // Contains the set of names that are hidden by "local" completion results. 1515 llvm::StringSet<> HiddenNames; 1516 1517 typedef CodeCompleteConsumer::Result Result; 1518 llvm::SmallVector<Result, 8> AllResults; 1519 for (ASTUnit::cached_completion_iterator 1520 C = AST.cached_completion_begin(), 1521 CEnd = AST.cached_completion_end(); 1522 C != CEnd; ++C) { 1523 // If the context we are in matches any of the contexts we are 1524 // interested in, we'll add this result. 1525 if ((C->ShowInContexts & InContexts) == 0) 1526 continue; 1527 1528 // If we haven't added any results previously, do so now. 1529 if (!AddedResult) { 1530 CalculateHiddenNames(Context, Results, NumResults, S.Context, 1531 HiddenNames); 1532 AllResults.insert(AllResults.end(), Results, Results + NumResults); 1533 AddedResult = true; 1534 } 1535 1536 // Determine whether this global completion result is hidden by a local 1537 // completion result. If so, skip it. 1538 if (C->Kind != CXCursor_MacroDefinition && 1539 HiddenNames.count(C->Completion->getTypedText())) 1540 continue; 1541 1542 // Adjust priority based on similar type classes. 1543 unsigned Priority = C->Priority; 1544 if (!Context.getPreferredType().isNull()) { 1545 if (C->Kind == CXCursor_MacroDefinition) { 1546 Priority = getMacroUsagePriority(C->Completion->getTypedText(), 1547 Context.getPreferredType()->isAnyPointerType()); 1548 } else if (C->Type) { 1549 CanQualType Expected 1550 = S.Context.getCanonicalType( 1551 Context.getPreferredType().getUnqualifiedType()); 1552 SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected); 1553 if (ExpectedSTC == C->TypeClass) { 1554 // We know this type is similar; check for an exact match. 1555 llvm::StringMap<unsigned> &CachedCompletionTypes 1556 = AST.getCachedCompletionTypes(); 1557 llvm::StringMap<unsigned>::iterator Pos 1558 = CachedCompletionTypes.find(QualType(Expected).getAsString()); 1559 if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type) 1560 Priority /= CCF_ExactTypeMatch; 1561 else 1562 Priority /= CCF_SimilarTypeMatch; 1563 } 1564 } 1565 } 1566 1567 AllResults.push_back(Result(C->Completion, Priority, C->Kind)); 1568 } 1569 1570 // If we did not add any cached completion results, just forward the 1571 // results we were given to the next consumer. 1572 if (!AddedResult) { 1573 Next.ProcessCodeCompleteResults(S, Context, Results, NumResults); 1574 return; 1575 } 1576 1577 Next.ProcessCodeCompleteResults(S, Context, AllResults.data(), 1578 AllResults.size()); 1579} 1580 1581 1582 1583void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column, 1584 RemappedFile *RemappedFiles, 1585 unsigned NumRemappedFiles, 1586 bool IncludeMacros, 1587 bool IncludeCodePatterns, 1588 CodeCompleteConsumer &Consumer, 1589 Diagnostic &Diag, LangOptions &LangOpts, 1590 SourceManager &SourceMgr, FileManager &FileMgr, 1591 llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) { 1592 if (!Invocation.get()) 1593 return; 1594 1595 llvm::Timer *CompletionTimer = 0; 1596 if (TimerGroup.get()) { 1597 llvm::SmallString<128> TimerName; 1598 llvm::raw_svector_ostream TimerNameOut(TimerName); 1599 TimerNameOut << "Code completion @ " << File << ":" << Line << ":" 1600 << Column; 1601 CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup); 1602 CompletionTimer->startTimer(); 1603 Timers.push_back(CompletionTimer); 1604 } 1605 1606 CompilerInvocation CCInvocation(*Invocation); 1607 FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts(); 1608 PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts(); 1609 1610 FrontendOpts.ShowMacrosInCodeCompletion 1611 = IncludeMacros && CachedCompletionResults.empty(); 1612 FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns; 1613 FrontendOpts.ShowGlobalSymbolsInCodeCompletion 1614 = CachedCompletionResults.empty(); 1615 FrontendOpts.CodeCompletionAt.FileName = File; 1616 FrontendOpts.CodeCompletionAt.Line = Line; 1617 FrontendOpts.CodeCompletionAt.Column = Column; 1618 1619 // Turn on spell-checking when performing code completion. It leads 1620 // to better results. 1621 unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking; 1622 CCInvocation.getLangOpts().SpellChecking = 1; 1623 1624 // Set the language options appropriately. 1625 LangOpts = CCInvocation.getLangOpts(); 1626 1627 CompilerInstance Clang; 1628 Clang.setInvocation(&CCInvocation); 1629 OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second; 1630 1631 // Set up diagnostics, capturing any diagnostics produced. 1632 Clang.setDiagnostics(&Diag); 1633 CaptureDroppedDiagnostics Capture(true, 1634 Clang.getDiagnostics(), 1635 StoredDiagnostics); 1636 Clang.setDiagnosticClient(Diag.getClient()); 1637 1638 // Create the target instance. 1639 Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(), 1640 Clang.getTargetOpts())); 1641 if (!Clang.hasTarget()) { 1642 Clang.takeDiagnosticClient(); 1643 Clang.takeInvocation(); 1644 } 1645 1646 // Inform the target of the language options. 1647 // 1648 // FIXME: We shouldn't need to do this, the target should be immutable once 1649 // created. This complexity should be lifted elsewhere. 1650 Clang.getTarget().setForcedLangOptions(Clang.getLangOpts()); 1651 1652 assert(Clang.getFrontendOpts().Inputs.size() == 1 && 1653 "Invocation must have exactly one source file!"); 1654 assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST && 1655 "FIXME: AST inputs not yet supported here!"); 1656 assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR && 1657 "IR inputs not support here!"); 1658 1659 1660 // Use the source and file managers that we were given. 1661 Clang.setFileManager(&FileMgr); 1662 Clang.setSourceManager(&SourceMgr); 1663 1664 // Remap files. 1665 PreprocessorOpts.clearRemappedFiles(); 1666 PreprocessorOpts.RetainRemappedFileBuffers = true; 1667 for (unsigned I = 0; I != NumRemappedFiles; ++I) 1668 PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, 1669 RemappedFiles[I].second); 1670 1671 // Use the code completion consumer we were given, but adding any cached 1672 // code-completion results. 1673 AugmentedCodeCompleteConsumer 1674 AugmentedConsumer(*this, Consumer, FrontendOpts.ShowMacrosInCodeCompletion, 1675 FrontendOpts.ShowCodePatternsInCodeCompletion, 1676 FrontendOpts.ShowGlobalSymbolsInCodeCompletion); 1677 Clang.setCodeCompletionConsumer(&AugmentedConsumer); 1678 1679 // If we have a precompiled preamble, try to use it. We only allow 1680 // the use of the precompiled preamble if we're if the completion 1681 // point is within the main file, after the end of the precompiled 1682 // preamble. 1683 llvm::MemoryBuffer *OverrideMainBuffer = 0; 1684 if (!PreambleFile.empty()) { 1685 using llvm::sys::FileStatus; 1686 llvm::sys::PathWithStatus CompleteFilePath(File); 1687 llvm::sys::PathWithStatus MainPath(OriginalSourceFile); 1688 if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus()) 1689 if (const FileStatus *MainStatus = MainPath.getFileStatus()) 1690 if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID()) 1691 OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false, 1692 Line); 1693 } 1694 1695 // If the main file has been overridden due to the use of a preamble, 1696 // make that override happen and introduce the preamble. 1697 if (OverrideMainBuffer) { 1698 PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer); 1699 PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size(); 1700 PreprocessorOpts.PrecompiledPreambleBytes.second 1701 = PreambleEndsAtStartOfLine; 1702 PreprocessorOpts.ImplicitPCHInclude = PreambleFile; 1703 PreprocessorOpts.DisablePCHValidation = true; 1704 1705 // The stored diagnostics have the old source manager. Copy them 1706 // to our output set of stored diagnostics, updating the source 1707 // manager to the one we were given. 1708 for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) { 1709 StoredDiagnostics.push_back(this->StoredDiagnostics[I]); 1710 FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr); 1711 StoredDiagnostics[I].setLocation(Loc); 1712 } 1713 } 1714 1715 llvm::OwningPtr<SyntaxOnlyAction> Act; 1716 Act.reset(new SyntaxOnlyAction); 1717 if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second, 1718 Clang.getFrontendOpts().Inputs[0].first)) { 1719 Act->Execute(); 1720 Act->EndSourceFile(); 1721 } 1722 1723 if (CompletionTimer) 1724 CompletionTimer->stopTimer(); 1725 1726 // Steal back our resources. 1727 delete OverrideMainBuffer; 1728 Clang.takeFileManager(); 1729 Clang.takeSourceManager(); 1730 Clang.takeInvocation(); 1731 Clang.takeDiagnosticClient(); 1732 Clang.takeCodeCompletionConsumer(); 1733 CCInvocation.getLangOpts().SpellChecking = SpellChecking; 1734} 1735 1736bool ASTUnit::Save(llvm::StringRef File) { 1737 if (getDiagnostics().hasErrorOccurred()) 1738 return true; 1739 1740 // FIXME: Can we somehow regenerate the stat cache here, or do we need to 1741 // unconditionally create a stat cache when we parse the file? 1742 std::string ErrorInfo; 1743 llvm::raw_fd_ostream Out(File.str().c_str(), ErrorInfo, 1744 llvm::raw_fd_ostream::F_Binary); 1745 if (!ErrorInfo.empty() || Out.has_error()) 1746 return true; 1747 1748 std::vector<unsigned char> Buffer; 1749 llvm::BitstreamWriter Stream(Buffer); 1750 PCHWriter Writer(Stream); 1751 Writer.WritePCH(getSema(), 0, 0); 1752 1753 // Write the generated bitstream to "Out". 1754 Out.write((char *)&Buffer.front(), Buffer.size()); 1755 Out.close(); 1756 return Out.has_error(); 1757} 1758