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