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