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