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