ASTUnit.cpp revision 77692f01900b322b8c6f409c785f171877e44be3
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/ASTWriter.h"
33#include "clang/Lex/HeaderSearch.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Basic/TargetOptions.h"
36#include "clang/Basic/TargetInfo.h"
37#include "clang/Basic/Diagnostic.h"
38#include "llvm/ADT/ArrayRef.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/FileSystem.h"
48#include "llvm/Support/Mutex.h"
49#include "llvm/Support/MutexGuard.h"
50#include "llvm/Support/CrashRecoveryContext.h"
51#include <cstdlib>
52#include <cstdio>
53#include <sys/stat.h>
54using namespace clang;
55
56using llvm::TimeRecord;
57
58namespace {
59  class SimpleTimer {
60    bool WantTiming;
61    TimeRecord Start;
62    std::string Output;
63
64  public:
65    explicit SimpleTimer(bool WantTiming) : WantTiming(WantTiming) {
66      if (WantTiming)
67        Start = TimeRecord::getCurrentTime();
68    }
69
70    void setOutput(const Twine &Output) {
71      if (WantTiming)
72        this->Output = Output.str();
73    }
74
75    ~SimpleTimer() {
76      if (WantTiming) {
77        TimeRecord Elapsed = TimeRecord::getCurrentTime();
78        Elapsed -= Start;
79        llvm::errs() << Output << ':';
80        Elapsed.print(Elapsed, llvm::errs());
81        llvm::errs() << '\n';
82      }
83    }
84  };
85
86  struct OnDiskData {
87    /// \brief The file in which the precompiled preamble is stored.
88    std::string PreambleFile;
89
90    /// \brief Temporary files that should be removed when the ASTUnit is
91    /// destroyed.
92    SmallVector<llvm::sys::Path, 4> TemporaryFiles;
93
94    /// \brief Erase temporary files.
95    void CleanTemporaryFiles();
96
97    /// \brief Erase the preamble file.
98    void CleanPreambleFile();
99
100    /// \brief Erase temporary files and the preamble file.
101    void Cleanup();
102  };
103}
104
105static llvm::sys::SmartMutex<false> &getOnDiskMutex() {
106  static llvm::sys::SmartMutex<false> M(/* recursive = */ true);
107  return M;
108}
109
110static void cleanupOnDiskMapAtExit(void);
111
112typedef llvm::DenseMap<const ASTUnit *, OnDiskData *> OnDiskDataMap;
113static OnDiskDataMap &getOnDiskDataMap() {
114  static OnDiskDataMap M;
115  static bool hasRegisteredAtExit = false;
116  if (!hasRegisteredAtExit) {
117    hasRegisteredAtExit = true;
118    atexit(cleanupOnDiskMapAtExit);
119  }
120  return M;
121}
122
123static void cleanupOnDiskMapAtExit(void) {
124  // No mutex required here since we are leaving the program.
125  OnDiskDataMap &M = getOnDiskDataMap();
126  for (OnDiskDataMap::iterator I = M.begin(), E = M.end(); I != E; ++I) {
127    // We don't worry about freeing the memory associated with OnDiskDataMap.
128    // All we care about is erasing stale files.
129    I->second->Cleanup();
130  }
131}
132
133static OnDiskData &getOnDiskData(const ASTUnit *AU) {
134  // We require the mutex since we are modifying the structure of the
135  // DenseMap.
136  llvm::MutexGuard Guard(getOnDiskMutex());
137  OnDiskDataMap &M = getOnDiskDataMap();
138  OnDiskData *&D = M[AU];
139  if (!D)
140    D = new OnDiskData();
141  return *D;
142}
143
144static void erasePreambleFile(const ASTUnit *AU) {
145  getOnDiskData(AU).CleanPreambleFile();
146}
147
148static void removeOnDiskEntry(const ASTUnit *AU) {
149  // We require the mutex since we are modifying the structure of the
150  // DenseMap.
151  llvm::MutexGuard Guard(getOnDiskMutex());
152  OnDiskDataMap &M = getOnDiskDataMap();
153  OnDiskDataMap::iterator I = M.find(AU);
154  if (I != M.end()) {
155    I->second->Cleanup();
156    delete I->second;
157    M.erase(AU);
158  }
159}
160
161static void setPreambleFile(const ASTUnit *AU, llvm::StringRef preambleFile) {
162  getOnDiskData(AU).PreambleFile = preambleFile;
163}
164
165static const std::string &getPreambleFile(const ASTUnit *AU) {
166  return getOnDiskData(AU).PreambleFile;
167}
168
169void OnDiskData::CleanTemporaryFiles() {
170  for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
171    TemporaryFiles[I].eraseFromDisk();
172  TemporaryFiles.clear();
173}
174
175void OnDiskData::CleanPreambleFile() {
176  if (!PreambleFile.empty()) {
177    llvm::sys::Path(PreambleFile).eraseFromDisk();
178    PreambleFile.clear();
179  }
180}
181
182void OnDiskData::Cleanup() {
183  CleanTemporaryFiles();
184  CleanPreambleFile();
185}
186
187void ASTUnit::clearFileLevelDecls() {
188  for (FileDeclsTy::iterator
189         I = FileDecls.begin(), E = FileDecls.end(); I != E; ++I)
190    delete I->second;
191  FileDecls.clear();
192}
193
194void ASTUnit::CleanTemporaryFiles() {
195  getOnDiskData(this).CleanTemporaryFiles();
196}
197
198void ASTUnit::addTemporaryFile(const llvm::sys::Path &TempFile) {
199  getOnDiskData(this).TemporaryFiles.push_back(TempFile);
200}
201
202/// \brief After failing to build a precompiled preamble (due to
203/// errors in the source that occurs in the preamble), the number of
204/// reparses during which we'll skip even trying to precompile the
205/// preamble.
206const unsigned DefaultPreambleRebuildInterval = 5;
207
208/// \brief Tracks the number of ASTUnit objects that are currently active.
209///
210/// Used for debugging purposes only.
211static llvm::sys::cas_flag ActiveASTUnitObjects;
212
213ASTUnit::ASTUnit(bool _MainFileIsAST)
214  : Reader(0), OnlyLocalDecls(false), CaptureDiagnostics(false),
215    MainFileIsAST(_MainFileIsAST),
216    TUKind(TU_Complete), WantTiming(getenv("LIBCLANG_TIMING")),
217    OwnsRemappedFileBuffers(true),
218    NumStoredDiagnosticsFromDriver(0),
219    PreambleRebuildCounter(0), SavedMainFileBuffer(0), PreambleBuffer(0),
220    ShouldCacheCodeCompletionResults(false),
221    NestedMacroExpansions(true),
222    CompletionCacheTopLevelHashValue(0),
223    PreambleTopLevelHashValue(0),
224    CurrentTopLevelHashValue(0),
225    UnsafeToFree(false) {
226  if (getenv("LIBCLANG_OBJTRACKING")) {
227    llvm::sys::AtomicIncrement(&ActiveASTUnitObjects);
228    fprintf(stderr, "+++ %d translation units\n", ActiveASTUnitObjects);
229  }
230}
231
232ASTUnit::~ASTUnit() {
233  clearFileLevelDecls();
234
235  // Clean up the temporary files and the preamble file.
236  removeOnDiskEntry(this);
237
238  // Free the buffers associated with remapped files. We are required to
239  // perform this operation here because we explicitly request that the
240  // compiler instance *not* free these buffers for each invocation of the
241  // parser.
242  if (Invocation.getPtr() && OwnsRemappedFileBuffers) {
243    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
244    for (PreprocessorOptions::remapped_file_buffer_iterator
245           FB = PPOpts.remapped_file_buffer_begin(),
246           FBEnd = PPOpts.remapped_file_buffer_end();
247         FB != FBEnd;
248         ++FB)
249      delete FB->second;
250  }
251
252  delete SavedMainFileBuffer;
253  delete PreambleBuffer;
254
255  ClearCachedCompletionResults();
256
257  if (getenv("LIBCLANG_OBJTRACKING")) {
258    llvm::sys::AtomicDecrement(&ActiveASTUnitObjects);
259    fprintf(stderr, "--- %d translation units\n", ActiveASTUnitObjects);
260  }
261}
262
263/// \brief Determine the set of code-completion contexts in which this
264/// declaration should be shown.
265static unsigned getDeclShowContexts(NamedDecl *ND,
266                                    const LangOptions &LangOpts,
267                                    bool &IsNestedNameSpecifier) {
268  IsNestedNameSpecifier = false;
269
270  if (isa<UsingShadowDecl>(ND))
271    ND = dyn_cast<NamedDecl>(ND->getUnderlyingDecl());
272  if (!ND)
273    return 0;
274
275  unsigned Contexts = 0;
276  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND) ||
277      isa<ClassTemplateDecl>(ND) || isa<TemplateTemplateParmDecl>(ND)) {
278    // Types can appear in these contexts.
279    if (LangOpts.CPlusPlus || !isa<TagDecl>(ND))
280      Contexts |= (1 << (CodeCompletionContext::CCC_TopLevel - 1))
281                | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
282                | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
283                | (1 << (CodeCompletionContext::CCC_Statement - 1))
284                | (1 << (CodeCompletionContext::CCC_Type - 1))
285              | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
286
287    // In C++, types can appear in expressions contexts (for functional casts).
288    if (LangOpts.CPlusPlus)
289      Contexts |= (1 << (CodeCompletionContext::CCC_Expression - 1));
290
291    // In Objective-C, message sends can send interfaces. In Objective-C++,
292    // all types are available due to functional casts.
293    if (LangOpts.CPlusPlus || isa<ObjCInterfaceDecl>(ND))
294      Contexts |= (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
295
296    // In Objective-C, you can only be a subclass of another Objective-C class
297    if (isa<ObjCInterfaceDecl>(ND))
298      Contexts |= (1 << (CodeCompletionContext::CCC_ObjCInterfaceName - 1));
299
300    // Deal with tag names.
301    if (isa<EnumDecl>(ND)) {
302      Contexts |= (1 << (CodeCompletionContext::CCC_EnumTag - 1));
303
304      // Part of the nested-name-specifier in C++0x.
305      if (LangOpts.CPlusPlus0x)
306        IsNestedNameSpecifier = true;
307    } else if (RecordDecl *Record = dyn_cast<RecordDecl>(ND)) {
308      if (Record->isUnion())
309        Contexts |= (1 << (CodeCompletionContext::CCC_UnionTag - 1));
310      else
311        Contexts |= (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
312
313      if (LangOpts.CPlusPlus)
314        IsNestedNameSpecifier = true;
315    } else if (isa<ClassTemplateDecl>(ND))
316      IsNestedNameSpecifier = true;
317  } else if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
318    // Values can appear in these contexts.
319    Contexts = (1 << (CodeCompletionContext::CCC_Statement - 1))
320             | (1 << (CodeCompletionContext::CCC_Expression - 1))
321             | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
322             | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1));
323  } else if (isa<ObjCProtocolDecl>(ND)) {
324    Contexts = (1 << (CodeCompletionContext::CCC_ObjCProtocolName - 1));
325  } else if (isa<ObjCCategoryDecl>(ND)) {
326    Contexts = (1 << (CodeCompletionContext::CCC_ObjCCategoryName - 1));
327  } else if (isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND)) {
328    Contexts = (1 << (CodeCompletionContext::CCC_Namespace - 1));
329
330    // Part of the nested-name-specifier.
331    IsNestedNameSpecifier = true;
332  }
333
334  return Contexts;
335}
336
337void ASTUnit::CacheCodeCompletionResults() {
338  if (!TheSema)
339    return;
340
341  SimpleTimer Timer(WantTiming);
342  Timer.setOutput("Cache global code completions for " + getMainFileName());
343
344  // Clear out the previous results.
345  ClearCachedCompletionResults();
346
347  // Gather the set of global code completions.
348  typedef CodeCompletionResult Result;
349  SmallVector<Result, 8> Results;
350  CachedCompletionAllocator = new GlobalCodeCompletionAllocator;
351  TheSema->GatherGlobalCodeCompletions(*CachedCompletionAllocator, Results);
352
353  // Translate global code completions into cached completions.
354  llvm::DenseMap<CanQualType, unsigned> CompletionTypes;
355
356  for (unsigned I = 0, N = Results.size(); I != N; ++I) {
357    switch (Results[I].Kind) {
358    case Result::RK_Declaration: {
359      bool IsNestedNameSpecifier = false;
360      CachedCodeCompletionResult CachedResult;
361      CachedResult.Completion = Results[I].CreateCodeCompletionString(*TheSema,
362                                                    *CachedCompletionAllocator);
363      CachedResult.ShowInContexts = getDeclShowContexts(Results[I].Declaration,
364                                                        Ctx->getLangOptions(),
365                                                        IsNestedNameSpecifier);
366      CachedResult.Priority = Results[I].Priority;
367      CachedResult.Kind = Results[I].CursorKind;
368      CachedResult.Availability = Results[I].Availability;
369
370      // Keep track of the type of this completion in an ASTContext-agnostic
371      // way.
372      QualType UsageType = getDeclUsageType(*Ctx, Results[I].Declaration);
373      if (UsageType.isNull()) {
374        CachedResult.TypeClass = STC_Void;
375        CachedResult.Type = 0;
376      } else {
377        CanQualType CanUsageType
378          = Ctx->getCanonicalType(UsageType.getUnqualifiedType());
379        CachedResult.TypeClass = getSimplifiedTypeClass(CanUsageType);
380
381        // Determine whether we have already seen this type. If so, we save
382        // ourselves the work of formatting the type string by using the
383        // temporary, CanQualType-based hash table to find the associated value.
384        unsigned &TypeValue = CompletionTypes[CanUsageType];
385        if (TypeValue == 0) {
386          TypeValue = CompletionTypes.size();
387          CachedCompletionTypes[QualType(CanUsageType).getAsString()]
388            = TypeValue;
389        }
390
391        CachedResult.Type = TypeValue;
392      }
393
394      CachedCompletionResults.push_back(CachedResult);
395
396      /// Handle nested-name-specifiers in C++.
397      if (TheSema->Context.getLangOptions().CPlusPlus &&
398          IsNestedNameSpecifier && !Results[I].StartsNestedNameSpecifier) {
399        // The contexts in which a nested-name-specifier can appear in C++.
400        unsigned NNSContexts
401          = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
402          | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
403          | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
404          | (1 << (CodeCompletionContext::CCC_Statement - 1))
405          | (1 << (CodeCompletionContext::CCC_Expression - 1))
406          | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
407          | (1 << (CodeCompletionContext::CCC_EnumTag - 1))
408          | (1 << (CodeCompletionContext::CCC_UnionTag - 1))
409          | (1 << (CodeCompletionContext::CCC_ClassOrStructTag - 1))
410          | (1 << (CodeCompletionContext::CCC_Type - 1))
411          | (1 << (CodeCompletionContext::CCC_PotentiallyQualifiedName - 1))
412          | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1));
413
414        if (isa<NamespaceDecl>(Results[I].Declaration) ||
415            isa<NamespaceAliasDecl>(Results[I].Declaration))
416          NNSContexts |= (1 << (CodeCompletionContext::CCC_Namespace - 1));
417
418        if (unsigned RemainingContexts
419                                = NNSContexts & ~CachedResult.ShowInContexts) {
420          // If there any contexts where this completion can be a
421          // nested-name-specifier but isn't already an option, create a
422          // nested-name-specifier completion.
423          Results[I].StartsNestedNameSpecifier = true;
424          CachedResult.Completion
425            = Results[I].CreateCodeCompletionString(*TheSema,
426                                                    *CachedCompletionAllocator);
427          CachedResult.ShowInContexts = RemainingContexts;
428          CachedResult.Priority = CCP_NestedNameSpecifier;
429          CachedResult.TypeClass = STC_Void;
430          CachedResult.Type = 0;
431          CachedCompletionResults.push_back(CachedResult);
432        }
433      }
434      break;
435    }
436
437    case Result::RK_Keyword:
438    case Result::RK_Pattern:
439      // Ignore keywords and patterns; we don't care, since they are so
440      // easily regenerated.
441      break;
442
443    case Result::RK_Macro: {
444      CachedCodeCompletionResult CachedResult;
445      CachedResult.Completion
446        = Results[I].CreateCodeCompletionString(*TheSema,
447                                                *CachedCompletionAllocator);
448      CachedResult.ShowInContexts
449        = (1 << (CodeCompletionContext::CCC_TopLevel - 1))
450        | (1 << (CodeCompletionContext::CCC_ObjCInterface - 1))
451        | (1 << (CodeCompletionContext::CCC_ObjCImplementation - 1))
452        | (1 << (CodeCompletionContext::CCC_ObjCIvarList - 1))
453        | (1 << (CodeCompletionContext::CCC_ClassStructUnion - 1))
454        | (1 << (CodeCompletionContext::CCC_Statement - 1))
455        | (1 << (CodeCompletionContext::CCC_Expression - 1))
456        | (1 << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
457        | (1 << (CodeCompletionContext::CCC_MacroNameUse - 1))
458        | (1 << (CodeCompletionContext::CCC_PreprocessorExpression - 1))
459        | (1 << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
460        | (1 << (CodeCompletionContext::CCC_OtherWithMacros - 1));
461
462      CachedResult.Priority = Results[I].Priority;
463      CachedResult.Kind = Results[I].CursorKind;
464      CachedResult.Availability = Results[I].Availability;
465      CachedResult.TypeClass = STC_Void;
466      CachedResult.Type = 0;
467      CachedCompletionResults.push_back(CachedResult);
468      break;
469    }
470    }
471  }
472
473  // Save the current top-level hash value.
474  CompletionCacheTopLevelHashValue = CurrentTopLevelHashValue;
475}
476
477void ASTUnit::ClearCachedCompletionResults() {
478  CachedCompletionResults.clear();
479  CachedCompletionTypes.clear();
480  CachedCompletionAllocator = 0;
481}
482
483namespace {
484
485/// \brief Gathers information from ASTReader that will be used to initialize
486/// a Preprocessor.
487class ASTInfoCollector : public ASTReaderListener {
488  Preprocessor &PP;
489  ASTContext &Context;
490  LangOptions &LangOpt;
491  HeaderSearch &HSI;
492  llvm::IntrusiveRefCntPtr<TargetInfo> &Target;
493  std::string &Predefines;
494  unsigned &Counter;
495
496  unsigned NumHeaderInfos;
497
498  bool InitializedLanguage;
499public:
500  ASTInfoCollector(Preprocessor &PP, ASTContext &Context, LangOptions &LangOpt,
501                   HeaderSearch &HSI,
502                   llvm::IntrusiveRefCntPtr<TargetInfo> &Target,
503                   std::string &Predefines,
504                   unsigned &Counter)
505    : PP(PP), Context(Context), LangOpt(LangOpt), HSI(HSI), Target(Target),
506      Predefines(Predefines), Counter(Counter), NumHeaderInfos(0),
507      InitializedLanguage(false) {}
508
509  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
510    if (InitializedLanguage)
511      return false;
512
513    LangOpt = LangOpts;
514
515    // Initialize the preprocessor.
516    PP.Initialize(*Target);
517
518    // Initialize the ASTContext
519    Context.InitBuiltinTypes(*Target);
520
521    InitializedLanguage = true;
522    return false;
523  }
524
525  virtual bool ReadTargetTriple(StringRef Triple) {
526    // If we've already initialized the target, don't do it again.
527    if (Target)
528      return false;
529
530    // FIXME: This is broken, we should store the TargetOptions in the AST file.
531    TargetOptions TargetOpts;
532    TargetOpts.ABI = "";
533    TargetOpts.CXXABI = "";
534    TargetOpts.CPU = "";
535    TargetOpts.Features.clear();
536    TargetOpts.Triple = Triple;
537    Target = TargetInfo::CreateTargetInfo(PP.getDiagnostics(), TargetOpts);
538    return false;
539  }
540
541  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
542                                    StringRef OriginalFileName,
543                                    std::string &SuggestedPredefines,
544                                    FileManager &FileMgr) {
545    Predefines = Buffers[0].Data;
546    for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
547      Predefines += Buffers[I].Data;
548    }
549    return false;
550  }
551
552  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
553    HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
554  }
555
556  virtual void ReadCounter(unsigned Value) {
557    Counter = Value;
558  }
559};
560
561class StoredDiagnosticConsumer : public DiagnosticConsumer {
562  SmallVectorImpl<StoredDiagnostic> &StoredDiags;
563
564public:
565  explicit StoredDiagnosticConsumer(
566                          SmallVectorImpl<StoredDiagnostic> &StoredDiags)
567    : StoredDiags(StoredDiags) { }
568
569  virtual void HandleDiagnostic(DiagnosticsEngine::Level Level,
570                                const Diagnostic &Info);
571
572  DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
573    // Just drop any diagnostics that come from cloned consumers; they'll
574    // have different source managers anyway.
575    return new IgnoringDiagConsumer();
576  }
577};
578
579/// \brief RAII object that optionally captures diagnostics, if
580/// there is no diagnostic client to capture them already.
581class CaptureDroppedDiagnostics {
582  DiagnosticsEngine &Diags;
583  StoredDiagnosticConsumer Client;
584  DiagnosticConsumer *PreviousClient;
585
586public:
587  CaptureDroppedDiagnostics(bool RequestCapture, DiagnosticsEngine &Diags,
588                          SmallVectorImpl<StoredDiagnostic> &StoredDiags)
589    : Diags(Diags), Client(StoredDiags), PreviousClient(0)
590  {
591    if (RequestCapture || Diags.getClient() == 0) {
592      PreviousClient = Diags.takeClient();
593      Diags.setClient(&Client);
594    }
595  }
596
597  ~CaptureDroppedDiagnostics() {
598    if (Diags.getClient() == &Client) {
599      Diags.takeClient();
600      Diags.setClient(PreviousClient);
601    }
602  }
603};
604
605} // anonymous namespace
606
607void StoredDiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level Level,
608                                              const Diagnostic &Info) {
609  // Default implementation (Warnings/errors count).
610  DiagnosticConsumer::HandleDiagnostic(Level, Info);
611
612  StoredDiags.push_back(StoredDiagnostic(Level, Info));
613}
614
615const std::string &ASTUnit::getOriginalSourceFileName() {
616  return OriginalSourceFile;
617}
618
619llvm::MemoryBuffer *ASTUnit::getBufferForFile(StringRef Filename,
620                                              std::string *ErrorStr) {
621  assert(FileMgr);
622  return FileMgr->getBufferForFile(Filename, ErrorStr);
623}
624
625/// \brief Configure the diagnostics object for use with ASTUnit.
626void ASTUnit::ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
627                             const char **ArgBegin, const char **ArgEnd,
628                             ASTUnit &AST, bool CaptureDiagnostics) {
629  if (!Diags.getPtr()) {
630    // No diagnostics engine was provided, so create our own diagnostics object
631    // with the default options.
632    DiagnosticOptions DiagOpts;
633    DiagnosticConsumer *Client = 0;
634    if (CaptureDiagnostics)
635      Client = new StoredDiagnosticConsumer(AST.StoredDiagnostics);
636    Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd- ArgBegin,
637                                                ArgBegin, Client);
638  } else if (CaptureDiagnostics) {
639    Diags->setClient(new StoredDiagnosticConsumer(AST.StoredDiagnostics));
640  }
641}
642
643ASTUnit *ASTUnit::LoadFromASTFile(const std::string &Filename,
644                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
645                                  const FileSystemOptions &FileSystemOpts,
646                                  bool OnlyLocalDecls,
647                                  RemappedFile *RemappedFiles,
648                                  unsigned NumRemappedFiles,
649                                  bool CaptureDiagnostics) {
650  llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
651
652  // Recover resources if we crash before exiting this method.
653  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
654    ASTUnitCleanup(AST.get());
655  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
656    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
657    DiagCleanup(Diags.getPtr());
658
659  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
660
661  AST->OnlyLocalDecls = OnlyLocalDecls;
662  AST->CaptureDiagnostics = CaptureDiagnostics;
663  AST->Diagnostics = Diags;
664  AST->FileMgr = new FileManager(FileSystemOpts);
665  AST->SourceMgr = new SourceManager(AST->getDiagnostics(),
666                                     AST->getFileManager());
667  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager(),
668                                         AST->getDiagnostics()));
669
670  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
671    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
672    if (const llvm::MemoryBuffer *
673          memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
674      // Create the file entry for the file that we're mapping from.
675      const FileEntry *FromFile
676        = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
677                                               memBuf->getBufferSize(),
678                                               0);
679      if (!FromFile) {
680        AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
681          << RemappedFiles[I].first;
682        delete memBuf;
683        continue;
684      }
685
686      // Override the contents of the "from" file with the contents of
687      // the "to" file.
688      AST->getSourceManager().overrideFileContents(FromFile, memBuf);
689
690    } else {
691      const char *fname = fileOrBuf.get<const char *>();
692      const FileEntry *ToFile = AST->FileMgr->getFile(fname);
693      if (!ToFile) {
694        AST->getDiagnostics().Report(diag::err_fe_remap_missing_to_file)
695        << RemappedFiles[I].first << fname;
696        continue;
697      }
698
699      // Create the file entry for the file that we're mapping from.
700      const FileEntry *FromFile
701        = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
702                                               ToFile->getSize(),
703                                               0);
704      if (!FromFile) {
705        AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
706          << RemappedFiles[I].first;
707        delete memBuf;
708        continue;
709      }
710
711      // Override the contents of the "from" file with the contents of
712      // the "to" file.
713      AST->getSourceManager().overrideFileContents(FromFile, ToFile);
714    }
715  }
716
717  // Gather Info for preprocessor construction later on.
718
719  HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
720  std::string Predefines;
721  unsigned Counter;
722
723  llvm::OwningPtr<ASTReader> Reader;
724
725  AST->PP = new Preprocessor(AST->getDiagnostics(), AST->ASTFileLangOpts,
726                             /*Target=*/0, AST->getSourceManager(), HeaderInfo,
727                             *AST,
728                             /*IILookup=*/0,
729                             /*OwnsHeaderSearch=*/false,
730                             /*DelayInitialization=*/true);
731  Preprocessor &PP = *AST->PP;
732
733  AST->Ctx = new ASTContext(AST->ASTFileLangOpts,
734                            AST->getSourceManager(),
735                            /*Target=*/0,
736                            PP.getIdentifierTable(),
737                            PP.getSelectorTable(),
738                            PP.getBuiltinInfo(),
739                            /* size_reserve = */0,
740                            /*DelayInitialization=*/true);
741  ASTContext &Context = *AST->Ctx;
742
743  Reader.reset(new ASTReader(PP, Context));
744
745  // Recover resources if we crash before exiting this method.
746  llvm::CrashRecoveryContextCleanupRegistrar<ASTReader>
747    ReaderCleanup(Reader.get());
748
749  Reader->setListener(new ASTInfoCollector(*AST->PP, Context,
750                                           AST->ASTFileLangOpts, HeaderInfo,
751                                           AST->Target, Predefines, Counter));
752
753  switch (Reader->ReadAST(Filename, serialization::MK_MainFile)) {
754  case ASTReader::Success:
755    break;
756
757  case ASTReader::Failure:
758  case ASTReader::IgnorePCH:
759    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
760    return NULL;
761  }
762
763  AST->OriginalSourceFile = Reader->getOriginalSourceFile();
764
765  PP.setPredefines(Reader->getSuggestedPredefines());
766  PP.setCounterValue(Counter);
767
768  // Attach the AST reader to the AST context as an external AST
769  // source, so that declarations will be deserialized from the
770  // AST file as needed.
771  ASTReader *ReaderPtr = Reader.get();
772  llvm::OwningPtr<ExternalASTSource> Source(Reader.take());
773
774  // Unregister the cleanup for ASTReader.  It will get cleaned up
775  // by the ASTUnit cleanup.
776  ReaderCleanup.unregister();
777
778  Context.setExternalSource(Source);
779
780  // Create an AST consumer, even though it isn't used.
781  AST->Consumer.reset(new ASTConsumer);
782
783  // Create a semantic analysis object and tell the AST reader about it.
784  AST->TheSema.reset(new Sema(PP, Context, *AST->Consumer));
785  AST->TheSema->Initialize();
786  ReaderPtr->InitializeSema(*AST->TheSema);
787  AST->Reader = ReaderPtr;
788
789  return AST.take();
790}
791
792namespace {
793
794/// \brief Preprocessor callback class that updates a hash value with the names
795/// of all macros that have been defined by the translation unit.
796class MacroDefinitionTrackerPPCallbacks : public PPCallbacks {
797  unsigned &Hash;
798
799public:
800  explicit MacroDefinitionTrackerPPCallbacks(unsigned &Hash) : Hash(Hash) { }
801
802  virtual void MacroDefined(const Token &MacroNameTok, const MacroInfo *MI) {
803    Hash = llvm::HashString(MacroNameTok.getIdentifierInfo()->getName(), Hash);
804  }
805};
806
807/// \brief Add the given declaration to the hash of all top-level entities.
808void AddTopLevelDeclarationToHash(Decl *D, unsigned &Hash) {
809  if (!D)
810    return;
811
812  DeclContext *DC = D->getDeclContext();
813  if (!DC)
814    return;
815
816  if (!(DC->isTranslationUnit() || DC->getLookupParent()->isTranslationUnit()))
817    return;
818
819  if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
820    if (ND->getIdentifier())
821      Hash = llvm::HashString(ND->getIdentifier()->getName(), Hash);
822    else if (DeclarationName Name = ND->getDeclName()) {
823      std::string NameStr = Name.getAsString();
824      Hash = llvm::HashString(NameStr, Hash);
825    }
826    return;
827  }
828
829  if (ObjCForwardProtocolDecl *Forward
830      = dyn_cast<ObjCForwardProtocolDecl>(D)) {
831    for (ObjCForwardProtocolDecl::protocol_iterator
832         P = Forward->protocol_begin(),
833         PEnd = Forward->protocol_end();
834         P != PEnd; ++P)
835      AddTopLevelDeclarationToHash(*P, Hash);
836    return;
837  }
838
839  if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(D)) {
840    AddTopLevelDeclarationToHash(Class->getForwardInterfaceDecl(), Hash);
841    return;
842  }
843}
844
845class TopLevelDeclTrackerConsumer : public ASTConsumer {
846  ASTUnit &Unit;
847  unsigned &Hash;
848
849public:
850  TopLevelDeclTrackerConsumer(ASTUnit &_Unit, unsigned &Hash)
851    : Unit(_Unit), Hash(Hash) {
852    Hash = 0;
853  }
854
855  void handleTopLevelDecl(Decl *D) {
856    // FIXME: Currently ObjC method declarations are incorrectly being
857    // reported as top-level declarations, even though their DeclContext
858    // is the containing ObjC @interface/@implementation.  This is a
859    // fundamental problem in the parser right now.
860    if (isa<ObjCMethodDecl>(D))
861      return;
862
863    AddTopLevelDeclarationToHash(D, Hash);
864    Unit.addTopLevelDecl(D);
865
866    handleFileLevelDecl(D);
867  }
868
869  void handleFileLevelDecl(Decl *D) {
870    Unit.addFileLevelDecl(D);
871    if (NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(D)) {
872      for (NamespaceDecl::decl_iterator
873             I = NSD->decls_begin(), E = NSD->decls_end(); I != E; ++I)
874        handleFileLevelDecl(*I);
875    }
876  }
877
878  void HandleTopLevelDecl(DeclGroupRef D) {
879    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
880      handleTopLevelDecl(*it);
881  }
882
883  // We're not interested in "interesting" decls.
884  void HandleInterestingDecl(DeclGroupRef) {}
885
886  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
887    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it)
888      handleTopLevelDecl(*it);
889  }
890};
891
892class TopLevelDeclTrackerAction : public ASTFrontendAction {
893public:
894  ASTUnit &Unit;
895
896  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
897                                         StringRef InFile) {
898    CI.getPreprocessor().addPPCallbacks(
899     new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
900    return new TopLevelDeclTrackerConsumer(Unit,
901                                           Unit.getCurrentTopLevelHashValue());
902  }
903
904public:
905  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
906
907  virtual bool hasCodeCompletionSupport() const { return false; }
908  virtual TranslationUnitKind getTranslationUnitKind()  {
909    return Unit.getTranslationUnitKind();
910  }
911};
912
913class PrecompilePreambleConsumer : public PCHGenerator {
914  ASTUnit &Unit;
915  unsigned &Hash;
916  std::vector<Decl *> TopLevelDecls;
917
918public:
919  PrecompilePreambleConsumer(ASTUnit &Unit, const Preprocessor &PP,
920                             StringRef isysroot, raw_ostream *Out)
921    : PCHGenerator(PP, "", /*IsModule=*/false, isysroot, Out), Unit(Unit),
922      Hash(Unit.getCurrentTopLevelHashValue()) {
923    Hash = 0;
924  }
925
926  virtual void HandleTopLevelDecl(DeclGroupRef D) {
927    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
928      Decl *D = *it;
929      // FIXME: Currently ObjC method declarations are incorrectly being
930      // reported as top-level declarations, even though their DeclContext
931      // is the containing ObjC @interface/@implementation.  This is a
932      // fundamental problem in the parser right now.
933      if (isa<ObjCMethodDecl>(D))
934        continue;
935      AddTopLevelDeclarationToHash(D, Hash);
936      TopLevelDecls.push_back(D);
937    }
938  }
939
940  virtual void HandleTranslationUnit(ASTContext &Ctx) {
941    PCHGenerator::HandleTranslationUnit(Ctx);
942    if (!Unit.getDiagnostics().hasErrorOccurred()) {
943      // Translate the top-level declarations we captured during
944      // parsing into declaration IDs in the precompiled
945      // preamble. This will allow us to deserialize those top-level
946      // declarations when requested.
947      for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
948        Unit.addTopLevelDeclFromPreamble(
949                                      getWriter().getDeclID(TopLevelDecls[I]));
950    }
951  }
952};
953
954class PrecompilePreambleAction : public ASTFrontendAction {
955  ASTUnit &Unit;
956
957public:
958  explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
959
960  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
961                                         StringRef InFile) {
962    std::string Sysroot;
963    std::string OutputFile;
964    raw_ostream *OS = 0;
965    if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
966                                                       OutputFile,
967                                                       OS))
968      return 0;
969
970    if (!CI.getFrontendOpts().RelocatablePCH)
971      Sysroot.clear();
972
973    CI.getPreprocessor().addPPCallbacks(
974     new MacroDefinitionTrackerPPCallbacks(Unit.getCurrentTopLevelHashValue()));
975    return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Sysroot,
976                                          OS);
977  }
978
979  virtual bool hasCodeCompletionSupport() const { return false; }
980  virtual bool hasASTFileSupport() const { return false; }
981  virtual TranslationUnitKind getTranslationUnitKind() { return TU_Prefix; }
982};
983
984}
985
986/// Parse the source file into a translation unit using the given compiler
987/// invocation, replacing the current translation unit.
988///
989/// \returns True if a failure occurred that causes the ASTUnit not to
990/// contain any translation-unit information, false otherwise.
991bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
992  delete SavedMainFileBuffer;
993  SavedMainFileBuffer = 0;
994
995  if (!Invocation) {
996    delete OverrideMainBuffer;
997    return true;
998  }
999
1000  // Create the compiler instance to use for building the AST.
1001  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1002
1003  // Recover resources if we crash before exiting this method.
1004  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1005    CICleanup(Clang.get());
1006
1007  llvm::IntrusiveRefCntPtr<CompilerInvocation>
1008    CCInvocation(new CompilerInvocation(*Invocation));
1009
1010  Clang->setInvocation(CCInvocation.getPtr());
1011  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1012
1013  // Set up diagnostics, capturing any diagnostics that would
1014  // otherwise be dropped.
1015  Clang->setDiagnostics(&getDiagnostics());
1016
1017  // Create the target instance.
1018  Clang->getTargetOpts().Features = TargetFeatures;
1019  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1020                   Clang->getTargetOpts()));
1021  if (!Clang->hasTarget()) {
1022    delete OverrideMainBuffer;
1023    return true;
1024  }
1025
1026  // Inform the target of the language options.
1027  //
1028  // FIXME: We shouldn't need to do this, the target should be immutable once
1029  // created. This complexity should be lifted elsewhere.
1030  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1031
1032  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1033         "Invocation must have exactly one source file!");
1034  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1035         "FIXME: AST inputs not yet supported here!");
1036  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1037         "IR inputs not support here!");
1038
1039  // Configure the various subsystems.
1040  // FIXME: Should we retain the previous file manager?
1041  FileSystemOpts = Clang->getFileSystemOpts();
1042  FileMgr = new FileManager(FileSystemOpts);
1043  SourceMgr = new SourceManager(getDiagnostics(), *FileMgr);
1044  TheSema.reset();
1045  Ctx = 0;
1046  PP = 0;
1047  Reader = 0;
1048
1049  // Clear out old caches and data.
1050  TopLevelDecls.clear();
1051  clearFileLevelDecls();
1052  CleanTemporaryFiles();
1053
1054  if (!OverrideMainBuffer) {
1055    StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1056    TopLevelDeclsInPreamble.clear();
1057  }
1058
1059  // Create a file manager object to provide access to and cache the filesystem.
1060  Clang->setFileManager(&getFileManager());
1061
1062  // Create the source manager.
1063  Clang->setSourceManager(&getSourceManager());
1064
1065  // If the main file has been overridden due to the use of a preamble,
1066  // make that override happen and introduce the preamble.
1067  PreprocessorOptions &PreprocessorOpts = Clang->getPreprocessorOpts();
1068  PreprocessorOpts.DetailedRecordIncludesNestedMacroExpansions
1069    = NestedMacroExpansions;
1070  if (OverrideMainBuffer) {
1071    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1072    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1073    PreprocessorOpts.PrecompiledPreambleBytes.second
1074                                                    = PreambleEndsAtStartOfLine;
1075    PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
1076    PreprocessorOpts.DisablePCHValidation = true;
1077
1078    // The stored diagnostic has the old source manager in it; update
1079    // the locations to refer into the new source manager. Since we've
1080    // been careful to make sure that the source manager's state
1081    // before and after are identical, so that we can reuse the source
1082    // location itself.
1083    for (unsigned I = NumStoredDiagnosticsFromDriver,
1084                  N = StoredDiagnostics.size();
1085         I < N; ++I) {
1086      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
1087                        getSourceManager());
1088      StoredDiagnostics[I].setLocation(Loc);
1089    }
1090
1091    // Keep track of the override buffer;
1092    SavedMainFileBuffer = OverrideMainBuffer;
1093  }
1094
1095  llvm::OwningPtr<TopLevelDeclTrackerAction> Act(
1096    new TopLevelDeclTrackerAction(*this));
1097
1098  // Recover resources if we crash before exiting this method.
1099  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1100    ActCleanup(Act.get());
1101
1102  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1103                            Clang->getFrontendOpts().Inputs[0].first))
1104    goto error;
1105
1106  if (OverrideMainBuffer) {
1107    std::string ModName = getPreambleFile(this);
1108    TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
1109                               getSourceManager(), PreambleDiagnostics,
1110                               StoredDiagnostics);
1111  }
1112
1113  Act->Execute();
1114
1115  // Steal the created target, context, and preprocessor.
1116  TheSema.reset(Clang->takeSema());
1117  Consumer.reset(Clang->takeASTConsumer());
1118  Ctx = &Clang->getASTContext();
1119  PP = &Clang->getPreprocessor();
1120  Clang->setSourceManager(0);
1121  Clang->setFileManager(0);
1122  Target = &Clang->getTarget();
1123  Reader = Clang->getModuleManager();
1124
1125  Act->EndSourceFile();
1126
1127  return false;
1128
1129error:
1130  // Remove the overridden buffer we used for the preamble.
1131  if (OverrideMainBuffer) {
1132    delete OverrideMainBuffer;
1133    SavedMainFileBuffer = 0;
1134  }
1135
1136  StoredDiagnostics.clear();
1137  NumStoredDiagnosticsFromDriver = 0;
1138  return true;
1139}
1140
1141/// \brief Simple function to retrieve a path for a preamble precompiled header.
1142static std::string GetPreamblePCHPath() {
1143  // FIXME: This is lame; sys::Path should provide this function (in particular,
1144  // it should know how to find the temporary files dir).
1145  // FIXME: This is really lame. I copied this code from the Driver!
1146  // FIXME: This is a hack so that we can override the preamble file during
1147  // crash-recovery testing, which is the only case where the preamble files
1148  // are not necessarily cleaned up.
1149  const char *TmpFile = ::getenv("CINDEXTEST_PREAMBLE_FILE");
1150  if (TmpFile)
1151    return TmpFile;
1152
1153  std::string Error;
1154  const char *TmpDir = ::getenv("TMPDIR");
1155  if (!TmpDir)
1156    TmpDir = ::getenv("TEMP");
1157  if (!TmpDir)
1158    TmpDir = ::getenv("TMP");
1159#ifdef LLVM_ON_WIN32
1160  if (!TmpDir)
1161    TmpDir = ::getenv("USERPROFILE");
1162#endif
1163  if (!TmpDir)
1164    TmpDir = "/tmp";
1165  llvm::sys::Path P(TmpDir);
1166  P.createDirectoryOnDisk(true);
1167  P.appendComponent("preamble");
1168  P.appendSuffix("pch");
1169  if (P.makeUnique(/*reuse_current=*/false, /*ErrMsg*/0))
1170    return std::string();
1171
1172  return P.str();
1173}
1174
1175/// \brief Compute the preamble for the main file, providing the source buffer
1176/// that corresponds to the main file along with a pair (bytes, start-of-line)
1177/// that describes the preamble.
1178std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
1179ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
1180                         unsigned MaxLines, bool &CreatedBuffer) {
1181  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
1182  PreprocessorOptions &PreprocessorOpts = Invocation.getPreprocessorOpts();
1183  CreatedBuffer = false;
1184
1185  // Try to determine if the main file has been remapped, either from the
1186  // command line (to another file) or directly through the compiler invocation
1187  // (to a memory buffer).
1188  llvm::MemoryBuffer *Buffer = 0;
1189  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1190  if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
1191    // Check whether there is a file-file remapping of the main file
1192    for (PreprocessorOptions::remapped_file_iterator
1193          M = PreprocessorOpts.remapped_file_begin(),
1194          E = PreprocessorOpts.remapped_file_end();
1195         M != E;
1196         ++M) {
1197      llvm::sys::PathWithStatus MPath(M->first);
1198      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1199        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1200          // We found a remapping. Try to load the resulting, remapped source.
1201          if (CreatedBuffer) {
1202            delete Buffer;
1203            CreatedBuffer = false;
1204          }
1205
1206          Buffer = getBufferForFile(M->second);
1207          if (!Buffer)
1208            return std::make_pair((llvm::MemoryBuffer*)0,
1209                                  std::make_pair(0, true));
1210          CreatedBuffer = true;
1211        }
1212      }
1213    }
1214
1215    // Check whether there is a file-buffer remapping. It supercedes the
1216    // file-file remapping.
1217    for (PreprocessorOptions::remapped_file_buffer_iterator
1218           M = PreprocessorOpts.remapped_file_buffer_begin(),
1219           E = PreprocessorOpts.remapped_file_buffer_end();
1220         M != E;
1221         ++M) {
1222      llvm::sys::PathWithStatus MPath(M->first);
1223      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
1224        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
1225          // We found a remapping.
1226          if (CreatedBuffer) {
1227            delete Buffer;
1228            CreatedBuffer = false;
1229          }
1230
1231          Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
1232        }
1233      }
1234    }
1235  }
1236
1237  // If the main source file was not remapped, load it now.
1238  if (!Buffer) {
1239    Buffer = getBufferForFile(FrontendOpts.Inputs[0].second);
1240    if (!Buffer)
1241      return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
1242
1243    CreatedBuffer = true;
1244  }
1245
1246  return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer,
1247                                                       Invocation.getLangOpts(),
1248                                                       MaxLines));
1249}
1250
1251static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
1252                                                      unsigned NewSize,
1253                                                      StringRef NewName) {
1254  llvm::MemoryBuffer *Result
1255    = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
1256  memcpy(const_cast<char*>(Result->getBufferStart()),
1257         Old->getBufferStart(), Old->getBufferSize());
1258  memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
1259         ' ', NewSize - Old->getBufferSize() - 1);
1260  const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
1261
1262  return Result;
1263}
1264
1265/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
1266/// the source file.
1267///
1268/// This routine will compute the preamble of the main source file. If a
1269/// non-trivial preamble is found, it will precompile that preamble into a
1270/// precompiled header so that the precompiled preamble can be used to reduce
1271/// reparsing time. If a precompiled preamble has already been constructed,
1272/// this routine will determine if it is still valid and, if so, avoid
1273/// rebuilding the precompiled preamble.
1274///
1275/// \param AllowRebuild When true (the default), this routine is
1276/// allowed to rebuild the precompiled preamble if it is found to be
1277/// out-of-date.
1278///
1279/// \param MaxLines When non-zero, the maximum number of lines that
1280/// can occur within the preamble.
1281///
1282/// \returns If the precompiled preamble can be used, returns a newly-allocated
1283/// buffer that should be used in place of the main file when doing so.
1284/// Otherwise, returns a NULL pointer.
1285llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
1286                              const CompilerInvocation &PreambleInvocationIn,
1287                                                           bool AllowRebuild,
1288                                                           unsigned MaxLines) {
1289
1290  llvm::IntrusiveRefCntPtr<CompilerInvocation>
1291    PreambleInvocation(new CompilerInvocation(PreambleInvocationIn));
1292  FrontendOptions &FrontendOpts = PreambleInvocation->getFrontendOpts();
1293  PreprocessorOptions &PreprocessorOpts
1294    = PreambleInvocation->getPreprocessorOpts();
1295
1296  bool CreatedPreambleBuffer = false;
1297  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
1298    = ComputePreamble(*PreambleInvocation, MaxLines, CreatedPreambleBuffer);
1299
1300  // If ComputePreamble() Take ownership of the preamble buffer.
1301  llvm::OwningPtr<llvm::MemoryBuffer> OwnedPreambleBuffer;
1302  if (CreatedPreambleBuffer)
1303    OwnedPreambleBuffer.reset(NewPreamble.first);
1304
1305  if (!NewPreamble.second.first) {
1306    // We couldn't find a preamble in the main source. Clear out the current
1307    // preamble, if we have one. It's obviously no good any more.
1308    Preamble.clear();
1309    erasePreambleFile(this);
1310
1311    // The next time we actually see a preamble, precompile it.
1312    PreambleRebuildCounter = 1;
1313    return 0;
1314  }
1315
1316  if (!Preamble.empty()) {
1317    // We've previously computed a preamble. Check whether we have the same
1318    // preamble now that we did before, and that there's enough space in
1319    // the main-file buffer within the precompiled preamble to fit the
1320    // new main file.
1321    if (Preamble.size() == NewPreamble.second.first &&
1322        PreambleEndsAtStartOfLine == NewPreamble.second.second &&
1323        NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
1324        memcmp(Preamble.getBufferStart(), NewPreamble.first->getBufferStart(),
1325               NewPreamble.second.first) == 0) {
1326      // The preamble has not changed. We may be able to re-use the precompiled
1327      // preamble.
1328
1329      // Check that none of the files used by the preamble have changed.
1330      bool AnyFileChanged = false;
1331
1332      // First, make a record of those files that have been overridden via
1333      // remapping or unsaved_files.
1334      llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
1335      for (PreprocessorOptions::remapped_file_iterator
1336                R = PreprocessorOpts.remapped_file_begin(),
1337             REnd = PreprocessorOpts.remapped_file_end();
1338           !AnyFileChanged && R != REnd;
1339           ++R) {
1340        struct stat StatBuf;
1341        if (FileMgr->getNoncachedStatValue(R->second, StatBuf)) {
1342          // If we can't stat the file we're remapping to, assume that something
1343          // horrible happened.
1344          AnyFileChanged = true;
1345          break;
1346        }
1347
1348        OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
1349                                                   StatBuf.st_mtime);
1350      }
1351      for (PreprocessorOptions::remapped_file_buffer_iterator
1352                R = PreprocessorOpts.remapped_file_buffer_begin(),
1353             REnd = PreprocessorOpts.remapped_file_buffer_end();
1354           !AnyFileChanged && R != REnd;
1355           ++R) {
1356        // FIXME: Should we actually compare the contents of file->buffer
1357        // remappings?
1358        OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
1359                                                   0);
1360      }
1361
1362      // Check whether anything has changed.
1363      for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
1364             F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
1365           !AnyFileChanged && F != FEnd;
1366           ++F) {
1367        llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
1368          = OverriddenFiles.find(F->first());
1369        if (Overridden != OverriddenFiles.end()) {
1370          // This file was remapped; check whether the newly-mapped file
1371          // matches up with the previous mapping.
1372          if (Overridden->second != F->second)
1373            AnyFileChanged = true;
1374          continue;
1375        }
1376
1377        // The file was not remapped; check whether it has changed on disk.
1378        struct stat StatBuf;
1379        if (FileMgr->getNoncachedStatValue(F->first(), StatBuf)) {
1380          // If we can't stat the file, assume that something horrible happened.
1381          AnyFileChanged = true;
1382        } else if (StatBuf.st_size != F->second.first ||
1383                   StatBuf.st_mtime != F->second.second)
1384          AnyFileChanged = true;
1385      }
1386
1387      if (!AnyFileChanged) {
1388        // Okay! We can re-use the precompiled preamble.
1389
1390        // Set the state of the diagnostic object to mimic its state
1391        // after parsing the preamble.
1392        getDiagnostics().Reset();
1393        ProcessWarningOptions(getDiagnostics(),
1394                              PreambleInvocation->getDiagnosticOpts());
1395        getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1396
1397        // Create a version of the main file buffer that is padded to
1398        // buffer size we reserved when creating the preamble.
1399        return CreatePaddedMainFileBuffer(NewPreamble.first,
1400                                          PreambleReservedSize,
1401                                          FrontendOpts.Inputs[0].second);
1402      }
1403    }
1404
1405    // If we aren't allowed to rebuild the precompiled preamble, just
1406    // return now.
1407    if (!AllowRebuild)
1408      return 0;
1409
1410    // We can't reuse the previously-computed preamble. Build a new one.
1411    Preamble.clear();
1412    PreambleDiagnostics.clear();
1413    erasePreambleFile(this);
1414    PreambleRebuildCounter = 1;
1415  } else if (!AllowRebuild) {
1416    // We aren't allowed to rebuild the precompiled preamble; just
1417    // return now.
1418    return 0;
1419  }
1420
1421  // If the preamble rebuild counter > 1, it's because we previously
1422  // failed to build a preamble and we're not yet ready to try
1423  // again. Decrement the counter and return a failure.
1424  if (PreambleRebuildCounter > 1) {
1425    --PreambleRebuildCounter;
1426    return 0;
1427  }
1428
1429  // Create a temporary file for the precompiled preamble. In rare
1430  // circumstances, this can fail.
1431  std::string PreamblePCHPath = GetPreamblePCHPath();
1432  if (PreamblePCHPath.empty()) {
1433    // Try again next time.
1434    PreambleRebuildCounter = 1;
1435    return 0;
1436  }
1437
1438  // We did not previously compute a preamble, or it can't be reused anyway.
1439  SimpleTimer PreambleTimer(WantTiming);
1440  PreambleTimer.setOutput("Precompiling preamble");
1441
1442  // Create a new buffer that stores the preamble. The buffer also contains
1443  // extra space for the original contents of the file (which will be present
1444  // when we actually parse the file) along with more room in case the file
1445  // grows.
1446  PreambleReservedSize = NewPreamble.first->getBufferSize();
1447  if (PreambleReservedSize < 4096)
1448    PreambleReservedSize = 8191;
1449  else
1450    PreambleReservedSize *= 2;
1451
1452  // Save the preamble text for later; we'll need to compare against it for
1453  // subsequent reparses.
1454  StringRef MainFilename = PreambleInvocation->getFrontendOpts().Inputs[0].second;
1455  Preamble.assign(FileMgr->getFile(MainFilename),
1456                  NewPreamble.first->getBufferStart(),
1457                  NewPreamble.first->getBufferStart()
1458                                                  + NewPreamble.second.first);
1459  PreambleEndsAtStartOfLine = NewPreamble.second.second;
1460
1461  delete PreambleBuffer;
1462  PreambleBuffer
1463    = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
1464                                                FrontendOpts.Inputs[0].second);
1465  memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
1466         NewPreamble.first->getBufferStart(), Preamble.size());
1467  memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
1468         ' ', PreambleReservedSize - Preamble.size() - 1);
1469  const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
1470
1471  // Remap the main source file to the preamble buffer.
1472  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
1473  PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
1474
1475  // Tell the compiler invocation to generate a temporary precompiled header.
1476  FrontendOpts.ProgramAction = frontend::GeneratePCH;
1477  // FIXME: Generate the precompiled header into memory?
1478  FrontendOpts.OutputFile = PreamblePCHPath;
1479  PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
1480  PreprocessorOpts.PrecompiledPreambleBytes.second = false;
1481
1482  // Create the compiler instance to use for building the precompiled preamble.
1483  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1484
1485  // Recover resources if we crash before exiting this method.
1486  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1487    CICleanup(Clang.get());
1488
1489  Clang->setInvocation(&*PreambleInvocation);
1490  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1491
1492  // Set up diagnostics, capturing all of the diagnostics produced.
1493  Clang->setDiagnostics(&getDiagnostics());
1494
1495  // Create the target instance.
1496  Clang->getTargetOpts().Features = TargetFeatures;
1497  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1498                                               Clang->getTargetOpts()));
1499  if (!Clang->hasTarget()) {
1500    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1501    Preamble.clear();
1502    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1503    PreprocessorOpts.eraseRemappedFile(
1504                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1505    return 0;
1506  }
1507
1508  // Inform the target of the language options.
1509  //
1510  // FIXME: We shouldn't need to do this, the target should be immutable once
1511  // created. This complexity should be lifted elsewhere.
1512  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1513
1514  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1515         "Invocation must have exactly one source file!");
1516  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1517         "FIXME: AST inputs not yet supported here!");
1518  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1519         "IR inputs not support here!");
1520
1521  // Clear out old caches and data.
1522  getDiagnostics().Reset();
1523  ProcessWarningOptions(getDiagnostics(), Clang->getDiagnosticOpts());
1524  StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1525  TopLevelDecls.clear();
1526  TopLevelDeclsInPreamble.clear();
1527
1528  // Create a file manager object to provide access to and cache the filesystem.
1529  Clang->setFileManager(new FileManager(Clang->getFileSystemOpts()));
1530
1531  // Create the source manager.
1532  Clang->setSourceManager(new SourceManager(getDiagnostics(),
1533                                            Clang->getFileManager()));
1534
1535  llvm::OwningPtr<PrecompilePreambleAction> Act;
1536  Act.reset(new PrecompilePreambleAction(*this));
1537  if (!Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
1538                            Clang->getFrontendOpts().Inputs[0].first)) {
1539    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1540    Preamble.clear();
1541    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1542    PreprocessorOpts.eraseRemappedFile(
1543                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1544    return 0;
1545  }
1546
1547  Act->Execute();
1548  Act->EndSourceFile();
1549
1550  if (Diagnostics->hasErrorOccurred()) {
1551    // There were errors parsing the preamble, so no precompiled header was
1552    // generated. Forget that we even tried.
1553    // FIXME: Should we leave a note for ourselves to try again?
1554    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
1555    Preamble.clear();
1556    TopLevelDeclsInPreamble.clear();
1557    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
1558    PreprocessorOpts.eraseRemappedFile(
1559                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1560    return 0;
1561  }
1562
1563  // Transfer any diagnostics generated when parsing the preamble into the set
1564  // of preamble diagnostics.
1565  PreambleDiagnostics.clear();
1566  PreambleDiagnostics.insert(PreambleDiagnostics.end(),
1567                            stored_diag_afterDriver_begin(), stored_diag_end());
1568  StoredDiagnostics.erase(stored_diag_afterDriver_begin(), stored_diag_end());
1569
1570  // Keep track of the preamble we precompiled.
1571  setPreambleFile(this, FrontendOpts.OutputFile);
1572  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
1573
1574  // Keep track of all of the files that the source manager knows about,
1575  // so we can verify whether they have changed or not.
1576  FilesInPreamble.clear();
1577  SourceManager &SourceMgr = Clang->getSourceManager();
1578  const llvm::MemoryBuffer *MainFileBuffer
1579    = SourceMgr.getBuffer(SourceMgr.getMainFileID());
1580  for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
1581                                     FEnd = SourceMgr.fileinfo_end();
1582       F != FEnd;
1583       ++F) {
1584    const FileEntry *File = F->second->OrigEntry;
1585    if (!File || F->second->getRawBuffer() == MainFileBuffer)
1586      continue;
1587
1588    FilesInPreamble[File->getName()]
1589      = std::make_pair(F->second->getSize(), File->getModificationTime());
1590  }
1591
1592  PreambleRebuildCounter = 1;
1593  PreprocessorOpts.eraseRemappedFile(
1594                               PreprocessorOpts.remapped_file_buffer_end() - 1);
1595
1596  // If the hash of top-level entities differs from the hash of the top-level
1597  // entities the last time we rebuilt the preamble, clear out the completion
1598  // cache.
1599  if (CurrentTopLevelHashValue != PreambleTopLevelHashValue) {
1600    CompletionCacheTopLevelHashValue = 0;
1601    PreambleTopLevelHashValue = CurrentTopLevelHashValue;
1602  }
1603
1604  return CreatePaddedMainFileBuffer(NewPreamble.first,
1605                                    PreambleReservedSize,
1606                                    FrontendOpts.Inputs[0].second);
1607}
1608
1609void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1610  std::vector<Decl *> Resolved;
1611  Resolved.reserve(TopLevelDeclsInPreamble.size());
1612  ExternalASTSource &Source = *getASTContext().getExternalSource();
1613  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1614    // Resolve the declaration ID to an actual declaration, possibly
1615    // deserializing the declaration in the process.
1616    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1617    if (D)
1618      Resolved.push_back(D);
1619  }
1620  TopLevelDeclsInPreamble.clear();
1621  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1622}
1623
1624StringRef ASTUnit::getMainFileName() const {
1625  return Invocation->getFrontendOpts().Inputs[0].second;
1626}
1627
1628ASTUnit *ASTUnit::create(CompilerInvocation *CI,
1629                         llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags) {
1630  llvm::OwningPtr<ASTUnit> AST;
1631  AST.reset(new ASTUnit(false));
1632  ConfigureDiags(Diags, 0, 0, *AST, /*CaptureDiagnostics=*/false);
1633  AST->Diagnostics = Diags;
1634  AST->Invocation = CI;
1635  AST->FileSystemOpts = CI->getFileSystemOpts();
1636  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1637  AST->SourceMgr = new SourceManager(AST->getDiagnostics(), *AST->FileMgr);
1638
1639  return AST.take();
1640}
1641
1642ASTUnit *ASTUnit::LoadFromCompilerInvocationAction(CompilerInvocation *CI,
1643                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1644                                             ASTFrontendAction *Action,
1645                                             ASTUnit *Unit) {
1646  assert(CI && "A CompilerInvocation is required");
1647
1648  llvm::OwningPtr<ASTUnit> OwnAST;
1649  ASTUnit *AST = Unit;
1650  if (!AST) {
1651    // Create the AST unit.
1652    OwnAST.reset(create(CI, Diags));
1653    AST = OwnAST.get();
1654  }
1655
1656  AST->OnlyLocalDecls = false;
1657  AST->CaptureDiagnostics = false;
1658  AST->TUKind = Action ? Action->getTranslationUnitKind() : TU_Complete;
1659  AST->ShouldCacheCodeCompletionResults = false;
1660
1661  // Recover resources if we crash before exiting this method.
1662  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1663    ASTUnitCleanup(OwnAST.get());
1664  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1665    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1666    DiagCleanup(Diags.getPtr());
1667
1668  // We'll manage file buffers ourselves.
1669  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1670  CI->getFrontendOpts().DisableFree = false;
1671  ProcessWarningOptions(AST->getDiagnostics(), CI->getDiagnosticOpts());
1672
1673  // Save the target features.
1674  AST->TargetFeatures = CI->getTargetOpts().Features;
1675
1676  // Create the compiler instance to use for building the AST.
1677  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
1678
1679  // Recover resources if we crash before exiting this method.
1680  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
1681    CICleanup(Clang.get());
1682
1683  Clang->setInvocation(CI);
1684  AST->OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
1685
1686  // Set up diagnostics, capturing any diagnostics that would
1687  // otherwise be dropped.
1688  Clang->setDiagnostics(&AST->getDiagnostics());
1689
1690  // Create the target instance.
1691  Clang->getTargetOpts().Features = AST->TargetFeatures;
1692  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
1693                   Clang->getTargetOpts()));
1694  if (!Clang->hasTarget())
1695    return 0;
1696
1697  // Inform the target of the language options.
1698  //
1699  // FIXME: We shouldn't need to do this, the target should be immutable once
1700  // created. This complexity should be lifted elsewhere.
1701  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
1702
1703  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
1704         "Invocation must have exactly one source file!");
1705  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
1706         "FIXME: AST inputs not yet supported here!");
1707  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1708         "IR inputs not supported here!");
1709
1710  // Configure the various subsystems.
1711  AST->TheSema.reset();
1712  AST->Ctx = 0;
1713  AST->PP = 0;
1714  AST->Reader = 0;
1715
1716  // Create a file manager object to provide access to and cache the filesystem.
1717  Clang->setFileManager(&AST->getFileManager());
1718
1719  // Create the source manager.
1720  Clang->setSourceManager(&AST->getSourceManager());
1721
1722  ASTFrontendAction *Act = Action;
1723
1724  llvm::OwningPtr<TopLevelDeclTrackerAction> TrackerAct;
1725  if (!Act) {
1726    TrackerAct.reset(new TopLevelDeclTrackerAction(*AST));
1727    Act = TrackerAct.get();
1728  }
1729
1730  // Recover resources if we crash before exiting this method.
1731  llvm::CrashRecoveryContextCleanupRegistrar<TopLevelDeclTrackerAction>
1732    ActCleanup(TrackerAct.get());
1733
1734  if (!Act->BeginSourceFile(*Clang.get(),
1735                            Clang->getFrontendOpts().Inputs[0].second,
1736                            Clang->getFrontendOpts().Inputs[0].first))
1737    return 0;
1738
1739  Act->Execute();
1740
1741  // Steal the created target, context, and preprocessor.
1742  AST->TheSema.reset(Clang->takeSema());
1743  AST->Consumer.reset(Clang->takeASTConsumer());
1744  AST->Ctx = &Clang->getASTContext();
1745  AST->PP = &Clang->getPreprocessor();
1746  Clang->setSourceManager(0);
1747  Clang->setFileManager(0);
1748  AST->Target = &Clang->getTarget();
1749  AST->Reader = Clang->getModuleManager();
1750
1751  Act->EndSourceFile();
1752
1753  if (OwnAST)
1754    return OwnAST.take();
1755  else
1756    return AST;
1757}
1758
1759bool ASTUnit::LoadFromCompilerInvocation(bool PrecompilePreamble) {
1760  if (!Invocation)
1761    return true;
1762
1763  // We'll manage file buffers ourselves.
1764  Invocation->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1765  Invocation->getFrontendOpts().DisableFree = false;
1766  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1767
1768  // Save the target features.
1769  TargetFeatures = Invocation->getTargetOpts().Features;
1770
1771  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1772  if (PrecompilePreamble) {
1773    PreambleRebuildCounter = 2;
1774    OverrideMainBuffer
1775      = getMainBufferWithPrecompiledPreamble(*Invocation);
1776  }
1777
1778  SimpleTimer ParsingTimer(WantTiming);
1779  ParsingTimer.setOutput("Parsing " + getMainFileName());
1780
1781  // Recover resources if we crash before exiting this method.
1782  llvm::CrashRecoveryContextCleanupRegistrar<llvm::MemoryBuffer>
1783    MemBufferCleanup(OverrideMainBuffer);
1784
1785  return Parse(OverrideMainBuffer);
1786}
1787
1788ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1789                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1790                                             bool OnlyLocalDecls,
1791                                             bool CaptureDiagnostics,
1792                                             bool PrecompilePreamble,
1793                                             TranslationUnitKind TUKind,
1794                                             bool CacheCodeCompletionResults,
1795                                             bool NestedMacroExpansions) {
1796  // Create the AST unit.
1797  llvm::OwningPtr<ASTUnit> AST;
1798  AST.reset(new ASTUnit(false));
1799  ConfigureDiags(Diags, 0, 0, *AST, CaptureDiagnostics);
1800  AST->Diagnostics = Diags;
1801  AST->OnlyLocalDecls = OnlyLocalDecls;
1802  AST->CaptureDiagnostics = CaptureDiagnostics;
1803  AST->TUKind = TUKind;
1804  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1805  AST->Invocation = CI;
1806  AST->NestedMacroExpansions = NestedMacroExpansions;
1807
1808  // Recover resources if we crash before exiting this method.
1809  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1810    ASTUnitCleanup(AST.get());
1811  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1812    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1813    DiagCleanup(Diags.getPtr());
1814
1815  return AST->LoadFromCompilerInvocation(PrecompilePreamble)? 0 : AST.take();
1816}
1817
1818ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1819                                      const char **ArgEnd,
1820                                    llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
1821                                      StringRef ResourceFilesPath,
1822                                      bool OnlyLocalDecls,
1823                                      bool CaptureDiagnostics,
1824                                      RemappedFile *RemappedFiles,
1825                                      unsigned NumRemappedFiles,
1826                                      bool RemappedFilesKeepOriginalName,
1827                                      bool PrecompilePreamble,
1828                                      TranslationUnitKind TUKind,
1829                                      bool CacheCodeCompletionResults,
1830                                      bool NestedMacroExpansions) {
1831  if (!Diags.getPtr()) {
1832    // No diagnostics engine was provided, so create our own diagnostics object
1833    // with the default options.
1834    DiagnosticOptions DiagOpts;
1835    Diags = CompilerInstance::createDiagnostics(DiagOpts, ArgEnd - ArgBegin,
1836                                                ArgBegin);
1837  }
1838
1839  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1840
1841  llvm::IntrusiveRefCntPtr<CompilerInvocation> CI;
1842
1843  {
1844
1845    CaptureDroppedDiagnostics Capture(CaptureDiagnostics, *Diags,
1846                                      StoredDiagnostics);
1847
1848    CI = clang::createInvocationFromCommandLine(
1849                                           llvm::makeArrayRef(ArgBegin, ArgEnd),
1850                                           Diags);
1851    if (!CI)
1852      return 0;
1853  }
1854
1855  // Override any files that need remapping
1856  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1857    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1858    if (const llvm::MemoryBuffer *
1859            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1860      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, memBuf);
1861    } else {
1862      const char *fname = fileOrBuf.get<const char *>();
1863      CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first, fname);
1864    }
1865  }
1866  CI->getPreprocessorOpts().RemappedFilesKeepOriginalName =
1867                                                  RemappedFilesKeepOriginalName;
1868
1869  // Override the resources path.
1870  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1871
1872  // Create the AST unit.
1873  llvm::OwningPtr<ASTUnit> AST;
1874  AST.reset(new ASTUnit(false));
1875  ConfigureDiags(Diags, ArgBegin, ArgEnd, *AST, CaptureDiagnostics);
1876  AST->Diagnostics = Diags;
1877
1878  AST->FileSystemOpts = CI->getFileSystemOpts();
1879  AST->FileMgr = new FileManager(AST->FileSystemOpts);
1880  AST->OnlyLocalDecls = OnlyLocalDecls;
1881  AST->CaptureDiagnostics = CaptureDiagnostics;
1882  AST->TUKind = TUKind;
1883  AST->ShouldCacheCodeCompletionResults = CacheCodeCompletionResults;
1884  AST->NumStoredDiagnosticsFromDriver = StoredDiagnostics.size();
1885  AST->StoredDiagnostics.swap(StoredDiagnostics);
1886  AST->Invocation = CI;
1887  AST->NestedMacroExpansions = NestedMacroExpansions;
1888
1889  // Recover resources if we crash before exiting this method.
1890  llvm::CrashRecoveryContextCleanupRegistrar<ASTUnit>
1891    ASTUnitCleanup(AST.get());
1892  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInvocation,
1893    llvm::CrashRecoveryContextReleaseRefCleanup<CompilerInvocation> >
1894    CICleanup(CI.getPtr());
1895  llvm::CrashRecoveryContextCleanupRegistrar<DiagnosticsEngine,
1896    llvm::CrashRecoveryContextReleaseRefCleanup<DiagnosticsEngine> >
1897    DiagCleanup(Diags.getPtr());
1898
1899  return AST->LoadFromCompilerInvocation(PrecompilePreamble) ? 0 : AST.take();
1900}
1901
1902bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1903  if (!Invocation)
1904    return true;
1905
1906  clearFileLevelDecls();
1907
1908  SimpleTimer ParsingTimer(WantTiming);
1909  ParsingTimer.setOutput("Reparsing " + getMainFileName());
1910
1911  // Remap files.
1912  PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1913  PPOpts.DisableStatCache = true;
1914  for (PreprocessorOptions::remapped_file_buffer_iterator
1915         R = PPOpts.remapped_file_buffer_begin(),
1916         REnd = PPOpts.remapped_file_buffer_end();
1917       R != REnd;
1918       ++R) {
1919    delete R->second;
1920  }
1921  Invocation->getPreprocessorOpts().clearRemappedFiles();
1922  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
1923    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
1924    if (const llvm::MemoryBuffer *
1925            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
1926      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1927                                                        memBuf);
1928    } else {
1929      const char *fname = fileOrBuf.get<const char *>();
1930      Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1931                                                        fname);
1932    }
1933  }
1934
1935  // If we have a preamble file lying around, or if we might try to
1936  // build a precompiled preamble, do so now.
1937  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1938  if (!getPreambleFile(this).empty() || PreambleRebuildCounter > 0)
1939    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(*Invocation);
1940
1941  // Clear out the diagnostics state.
1942  getDiagnostics().Reset();
1943  ProcessWarningOptions(getDiagnostics(), Invocation->getDiagnosticOpts());
1944  if (OverrideMainBuffer)
1945    getDiagnostics().setNumWarnings(NumWarningsInPreamble);
1946
1947  // Parse the sources
1948  bool Result = Parse(OverrideMainBuffer);
1949
1950  // If we're caching global code-completion results, and the top-level
1951  // declarations have changed, clear out the code-completion cache.
1952  if (!Result && ShouldCacheCodeCompletionResults &&
1953      CurrentTopLevelHashValue != CompletionCacheTopLevelHashValue)
1954    CacheCodeCompletionResults();
1955
1956  // We now need to clear out the completion allocator for
1957  // clang_getCursorCompletionString; it'll be recreated if necessary.
1958  CursorCompletionAllocator = 0;
1959
1960  return Result;
1961}
1962
1963//----------------------------------------------------------------------------//
1964// Code completion
1965//----------------------------------------------------------------------------//
1966
1967namespace {
1968  /// \brief Code completion consumer that combines the cached code-completion
1969  /// results from an ASTUnit with the code-completion results provided to it,
1970  /// then passes the result on to
1971  class AugmentedCodeCompleteConsumer : public CodeCompleteConsumer {
1972    unsigned long long NormalContexts;
1973    ASTUnit &AST;
1974    CodeCompleteConsumer &Next;
1975
1976  public:
1977    AugmentedCodeCompleteConsumer(ASTUnit &AST, CodeCompleteConsumer &Next,
1978                                  bool IncludeMacros, bool IncludeCodePatterns,
1979                                  bool IncludeGlobals)
1980      : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
1981                             Next.isOutputBinary()), AST(AST), Next(Next)
1982    {
1983      // Compute the set of contexts in which we will look when we don't have
1984      // any information about the specific context.
1985      NormalContexts
1986        = (1LL << (CodeCompletionContext::CCC_TopLevel - 1))
1987        | (1LL << (CodeCompletionContext::CCC_ObjCInterface - 1))
1988        | (1LL << (CodeCompletionContext::CCC_ObjCImplementation - 1))
1989        | (1LL << (CodeCompletionContext::CCC_ObjCIvarList - 1))
1990        | (1LL << (CodeCompletionContext::CCC_Statement - 1))
1991        | (1LL << (CodeCompletionContext::CCC_Expression - 1))
1992        | (1LL << (CodeCompletionContext::CCC_ObjCMessageReceiver - 1))
1993        | (1LL << (CodeCompletionContext::CCC_DotMemberAccess - 1))
1994        | (1LL << (CodeCompletionContext::CCC_ArrowMemberAccess - 1))
1995        | (1LL << (CodeCompletionContext::CCC_ObjCPropertyAccess - 1))
1996        | (1LL << (CodeCompletionContext::CCC_ObjCProtocolName - 1))
1997        | (1LL << (CodeCompletionContext::CCC_ParenthesizedExpression - 1))
1998        | (1LL << (CodeCompletionContext::CCC_Recovery - 1));
1999
2000      if (AST.getASTContext().getLangOptions().CPlusPlus)
2001        NormalContexts |= (1LL << (CodeCompletionContext::CCC_EnumTag - 1))
2002                   | (1LL << (CodeCompletionContext::CCC_UnionTag - 1))
2003                   | (1LL << (CodeCompletionContext::CCC_ClassOrStructTag - 1));
2004    }
2005
2006    virtual void ProcessCodeCompleteResults(Sema &S,
2007                                            CodeCompletionContext Context,
2008                                            CodeCompletionResult *Results,
2009                                            unsigned NumResults);
2010
2011    virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
2012                                           OverloadCandidate *Candidates,
2013                                           unsigned NumCandidates) {
2014      Next.ProcessOverloadCandidates(S, CurrentArg, Candidates, NumCandidates);
2015    }
2016
2017    virtual CodeCompletionAllocator &getAllocator() {
2018      return Next.getAllocator();
2019    }
2020  };
2021}
2022
2023/// \brief Helper function that computes which global names are hidden by the
2024/// local code-completion results.
2025static void CalculateHiddenNames(const CodeCompletionContext &Context,
2026                                 CodeCompletionResult *Results,
2027                                 unsigned NumResults,
2028                                 ASTContext &Ctx,
2029                          llvm::StringSet<llvm::BumpPtrAllocator> &HiddenNames){
2030  bool OnlyTagNames = false;
2031  switch (Context.getKind()) {
2032  case CodeCompletionContext::CCC_Recovery:
2033  case CodeCompletionContext::CCC_TopLevel:
2034  case CodeCompletionContext::CCC_ObjCInterface:
2035  case CodeCompletionContext::CCC_ObjCImplementation:
2036  case CodeCompletionContext::CCC_ObjCIvarList:
2037  case CodeCompletionContext::CCC_ClassStructUnion:
2038  case CodeCompletionContext::CCC_Statement:
2039  case CodeCompletionContext::CCC_Expression:
2040  case CodeCompletionContext::CCC_ObjCMessageReceiver:
2041  case CodeCompletionContext::CCC_DotMemberAccess:
2042  case CodeCompletionContext::CCC_ArrowMemberAccess:
2043  case CodeCompletionContext::CCC_ObjCPropertyAccess:
2044  case CodeCompletionContext::CCC_Namespace:
2045  case CodeCompletionContext::CCC_Type:
2046  case CodeCompletionContext::CCC_Name:
2047  case CodeCompletionContext::CCC_PotentiallyQualifiedName:
2048  case CodeCompletionContext::CCC_ParenthesizedExpression:
2049  case CodeCompletionContext::CCC_ObjCInterfaceName:
2050    break;
2051
2052  case CodeCompletionContext::CCC_EnumTag:
2053  case CodeCompletionContext::CCC_UnionTag:
2054  case CodeCompletionContext::CCC_ClassOrStructTag:
2055    OnlyTagNames = true;
2056    break;
2057
2058  case CodeCompletionContext::CCC_ObjCProtocolName:
2059  case CodeCompletionContext::CCC_MacroName:
2060  case CodeCompletionContext::CCC_MacroNameUse:
2061  case CodeCompletionContext::CCC_PreprocessorExpression:
2062  case CodeCompletionContext::CCC_PreprocessorDirective:
2063  case CodeCompletionContext::CCC_NaturalLanguage:
2064  case CodeCompletionContext::CCC_SelectorName:
2065  case CodeCompletionContext::CCC_TypeQualifiers:
2066  case CodeCompletionContext::CCC_Other:
2067  case CodeCompletionContext::CCC_OtherWithMacros:
2068  case CodeCompletionContext::CCC_ObjCInstanceMessage:
2069  case CodeCompletionContext::CCC_ObjCClassMessage:
2070  case CodeCompletionContext::CCC_ObjCCategoryName:
2071    // We're looking for nothing, or we're looking for names that cannot
2072    // be hidden.
2073    return;
2074  }
2075
2076  typedef CodeCompletionResult Result;
2077  for (unsigned I = 0; I != NumResults; ++I) {
2078    if (Results[I].Kind != Result::RK_Declaration)
2079      continue;
2080
2081    unsigned IDNS
2082      = Results[I].Declaration->getUnderlyingDecl()->getIdentifierNamespace();
2083
2084    bool Hiding = false;
2085    if (OnlyTagNames)
2086      Hiding = (IDNS & Decl::IDNS_Tag);
2087    else {
2088      unsigned HiddenIDNS = (Decl::IDNS_Type | Decl::IDNS_Member |
2089                             Decl::IDNS_Namespace | Decl::IDNS_Ordinary |
2090                             Decl::IDNS_NonMemberOperator);
2091      if (Ctx.getLangOptions().CPlusPlus)
2092        HiddenIDNS |= Decl::IDNS_Tag;
2093      Hiding = (IDNS & HiddenIDNS);
2094    }
2095
2096    if (!Hiding)
2097      continue;
2098
2099    DeclarationName Name = Results[I].Declaration->getDeclName();
2100    if (IdentifierInfo *Identifier = Name.getAsIdentifierInfo())
2101      HiddenNames.insert(Identifier->getName());
2102    else
2103      HiddenNames.insert(Name.getAsString());
2104  }
2105}
2106
2107
2108void AugmentedCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &S,
2109                                            CodeCompletionContext Context,
2110                                            CodeCompletionResult *Results,
2111                                            unsigned NumResults) {
2112  // Merge the results we were given with the results we cached.
2113  bool AddedResult = false;
2114  unsigned InContexts
2115    = (Context.getKind() == CodeCompletionContext::CCC_Recovery? NormalContexts
2116                                        : (1ULL << (Context.getKind() - 1)));
2117  // Contains the set of names that are hidden by "local" completion results.
2118  llvm::StringSet<llvm::BumpPtrAllocator> HiddenNames;
2119  typedef CodeCompletionResult Result;
2120  SmallVector<Result, 8> AllResults;
2121  for (ASTUnit::cached_completion_iterator
2122            C = AST.cached_completion_begin(),
2123         CEnd = AST.cached_completion_end();
2124       C != CEnd; ++C) {
2125    // If the context we are in matches any of the contexts we are
2126    // interested in, we'll add this result.
2127    if ((C->ShowInContexts & InContexts) == 0)
2128      continue;
2129
2130    // If we haven't added any results previously, do so now.
2131    if (!AddedResult) {
2132      CalculateHiddenNames(Context, Results, NumResults, S.Context,
2133                           HiddenNames);
2134      AllResults.insert(AllResults.end(), Results, Results + NumResults);
2135      AddedResult = true;
2136    }
2137
2138    // Determine whether this global completion result is hidden by a local
2139    // completion result. If so, skip it.
2140    if (C->Kind != CXCursor_MacroDefinition &&
2141        HiddenNames.count(C->Completion->getTypedText()))
2142      continue;
2143
2144    // Adjust priority based on similar type classes.
2145    unsigned Priority = C->Priority;
2146    CXCursorKind CursorKind = C->Kind;
2147    CodeCompletionString *Completion = C->Completion;
2148    if (!Context.getPreferredType().isNull()) {
2149      if (C->Kind == CXCursor_MacroDefinition) {
2150        Priority = getMacroUsagePriority(C->Completion->getTypedText(),
2151                                         S.getLangOptions(),
2152                               Context.getPreferredType()->isAnyPointerType());
2153      } else if (C->Type) {
2154        CanQualType Expected
2155          = S.Context.getCanonicalType(
2156                               Context.getPreferredType().getUnqualifiedType());
2157        SimplifiedTypeClass ExpectedSTC = getSimplifiedTypeClass(Expected);
2158        if (ExpectedSTC == C->TypeClass) {
2159          // We know this type is similar; check for an exact match.
2160          llvm::StringMap<unsigned> &CachedCompletionTypes
2161            = AST.getCachedCompletionTypes();
2162          llvm::StringMap<unsigned>::iterator Pos
2163            = CachedCompletionTypes.find(QualType(Expected).getAsString());
2164          if (Pos != CachedCompletionTypes.end() && Pos->second == C->Type)
2165            Priority /= CCF_ExactTypeMatch;
2166          else
2167            Priority /= CCF_SimilarTypeMatch;
2168        }
2169      }
2170    }
2171
2172    // Adjust the completion string, if required.
2173    if (C->Kind == CXCursor_MacroDefinition &&
2174        Context.getKind() == CodeCompletionContext::CCC_MacroNameUse) {
2175      // Create a new code-completion string that just contains the
2176      // macro name, without its arguments.
2177      CodeCompletionBuilder Builder(getAllocator(), CCP_CodePattern,
2178                                    C->Availability);
2179      Builder.AddTypedTextChunk(C->Completion->getTypedText());
2180      CursorKind = CXCursor_NotImplemented;
2181      Priority = CCP_CodePattern;
2182      Completion = Builder.TakeString();
2183    }
2184
2185    AllResults.push_back(Result(Completion, Priority, CursorKind,
2186                                C->Availability));
2187  }
2188
2189  // If we did not add any cached completion results, just forward the
2190  // results we were given to the next consumer.
2191  if (!AddedResult) {
2192    Next.ProcessCodeCompleteResults(S, Context, Results, NumResults);
2193    return;
2194  }
2195
2196  Next.ProcessCodeCompleteResults(S, Context, AllResults.data(),
2197                                  AllResults.size());
2198}
2199
2200
2201
2202void ASTUnit::CodeComplete(StringRef File, unsigned Line, unsigned Column,
2203                           RemappedFile *RemappedFiles,
2204                           unsigned NumRemappedFiles,
2205                           bool IncludeMacros,
2206                           bool IncludeCodePatterns,
2207                           CodeCompleteConsumer &Consumer,
2208                           DiagnosticsEngine &Diag, LangOptions &LangOpts,
2209                           SourceManager &SourceMgr, FileManager &FileMgr,
2210                   SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
2211             SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers) {
2212  if (!Invocation)
2213    return;
2214
2215  SimpleTimer CompletionTimer(WantTiming);
2216  CompletionTimer.setOutput("Code completion @ " + File + ":" +
2217                            Twine(Line) + ":" + Twine(Column));
2218
2219  llvm::IntrusiveRefCntPtr<CompilerInvocation>
2220    CCInvocation(new CompilerInvocation(*Invocation));
2221
2222  FrontendOptions &FrontendOpts = CCInvocation->getFrontendOpts();
2223  PreprocessorOptions &PreprocessorOpts = CCInvocation->getPreprocessorOpts();
2224
2225  FrontendOpts.ShowMacrosInCodeCompletion
2226    = IncludeMacros && CachedCompletionResults.empty();
2227  FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
2228  FrontendOpts.ShowGlobalSymbolsInCodeCompletion
2229    = CachedCompletionResults.empty();
2230  FrontendOpts.CodeCompletionAt.FileName = File;
2231  FrontendOpts.CodeCompletionAt.Line = Line;
2232  FrontendOpts.CodeCompletionAt.Column = Column;
2233
2234  // Set the language options appropriately.
2235  LangOpts = CCInvocation->getLangOpts();
2236
2237  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
2238
2239  // Recover resources if we crash before exiting this method.
2240  llvm::CrashRecoveryContextCleanupRegistrar<CompilerInstance>
2241    CICleanup(Clang.get());
2242
2243  Clang->setInvocation(&*CCInvocation);
2244  OriginalSourceFile = Clang->getFrontendOpts().Inputs[0].second;
2245
2246  // Set up diagnostics, capturing any diagnostics produced.
2247  Clang->setDiagnostics(&Diag);
2248  ProcessWarningOptions(Diag, CCInvocation->getDiagnosticOpts());
2249  CaptureDroppedDiagnostics Capture(true,
2250                                    Clang->getDiagnostics(),
2251                                    StoredDiagnostics);
2252
2253  // Create the target instance.
2254  Clang->getTargetOpts().Features = TargetFeatures;
2255  Clang->setTarget(TargetInfo::CreateTargetInfo(Clang->getDiagnostics(),
2256                                               Clang->getTargetOpts()));
2257  if (!Clang->hasTarget()) {
2258    Clang->setInvocation(0);
2259    return;
2260  }
2261
2262  // Inform the target of the language options.
2263  //
2264  // FIXME: We shouldn't need to do this, the target should be immutable once
2265  // created. This complexity should be lifted elsewhere.
2266  Clang->getTarget().setForcedLangOptions(Clang->getLangOpts());
2267
2268  assert(Clang->getFrontendOpts().Inputs.size() == 1 &&
2269         "Invocation must have exactly one source file!");
2270  assert(Clang->getFrontendOpts().Inputs[0].first != IK_AST &&
2271         "FIXME: AST inputs not yet supported here!");
2272  assert(Clang->getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
2273         "IR inputs not support here!");
2274
2275
2276  // Use the source and file managers that we were given.
2277  Clang->setFileManager(&FileMgr);
2278  Clang->setSourceManager(&SourceMgr);
2279
2280  // Remap files.
2281  PreprocessorOpts.clearRemappedFiles();
2282  PreprocessorOpts.RetainRemappedFileBuffers = true;
2283  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
2284    FilenameOrMemBuf fileOrBuf = RemappedFiles[I].second;
2285    if (const llvm::MemoryBuffer *
2286            memBuf = fileOrBuf.dyn_cast<const llvm::MemoryBuffer *>()) {
2287      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, memBuf);
2288      OwnedBuffers.push_back(memBuf);
2289    } else {
2290      const char *fname = fileOrBuf.get<const char *>();
2291      PreprocessorOpts.addRemappedFile(RemappedFiles[I].first, fname);
2292    }
2293  }
2294
2295  // Use the code completion consumer we were given, but adding any cached
2296  // code-completion results.
2297  AugmentedCodeCompleteConsumer *AugmentedConsumer
2298    = new AugmentedCodeCompleteConsumer(*this, Consumer,
2299                                        FrontendOpts.ShowMacrosInCodeCompletion,
2300                                FrontendOpts.ShowCodePatternsInCodeCompletion,
2301                                FrontendOpts.ShowGlobalSymbolsInCodeCompletion);
2302  Clang->setCodeCompletionConsumer(AugmentedConsumer);
2303
2304  // If we have a precompiled preamble, try to use it. We only allow
2305  // the use of the precompiled preamble if we're if the completion
2306  // point is within the main file, after the end of the precompiled
2307  // preamble.
2308  llvm::MemoryBuffer *OverrideMainBuffer = 0;
2309  if (!getPreambleFile(this).empty()) {
2310    using llvm::sys::FileStatus;
2311    llvm::sys::PathWithStatus CompleteFilePath(File);
2312    llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
2313    if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
2314      if (const FileStatus *MainStatus = MainPath.getFileStatus())
2315        if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID() &&
2316            Line > 1)
2317          OverrideMainBuffer
2318            = getMainBufferWithPrecompiledPreamble(*CCInvocation, false,
2319                                                   Line - 1);
2320  }
2321
2322  // If the main file has been overridden due to the use of a preamble,
2323  // make that override happen and introduce the preamble.
2324  PreprocessorOpts.DisableStatCache = true;
2325  StoredDiagnostics.insert(StoredDiagnostics.end(),
2326                           stored_diag_begin(),
2327                           stored_diag_afterDriver_begin());
2328  if (OverrideMainBuffer) {
2329    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
2330    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
2331    PreprocessorOpts.PrecompiledPreambleBytes.second
2332                                                    = PreambleEndsAtStartOfLine;
2333    PreprocessorOpts.ImplicitPCHInclude = getPreambleFile(this);
2334    PreprocessorOpts.DisablePCHValidation = true;
2335
2336    OwnedBuffers.push_back(OverrideMainBuffer);
2337  } else {
2338    PreprocessorOpts.PrecompiledPreambleBytes.first = 0;
2339    PreprocessorOpts.PrecompiledPreambleBytes.second = false;
2340  }
2341
2342  // Disable the preprocessing record
2343  PreprocessorOpts.DetailedRecord = false;
2344
2345  llvm::OwningPtr<SyntaxOnlyAction> Act;
2346  Act.reset(new SyntaxOnlyAction);
2347  if (Act->BeginSourceFile(*Clang.get(), Clang->getFrontendOpts().Inputs[0].second,
2348                           Clang->getFrontendOpts().Inputs[0].first)) {
2349    if (OverrideMainBuffer) {
2350      std::string ModName = getPreambleFile(this);
2351      TranslateStoredDiagnostics(Clang->getModuleManager(), ModName,
2352                                 getSourceManager(), PreambleDiagnostics,
2353                                 StoredDiagnostics);
2354    }
2355    Act->Execute();
2356    Act->EndSourceFile();
2357  }
2358}
2359
2360CXSaveError ASTUnit::Save(StringRef File) {
2361  if (getDiagnostics().hasUnrecoverableErrorOccurred())
2362    return CXSaveError_TranslationErrors;
2363
2364  // Write to a temporary file and later rename it to the actual file, to avoid
2365  // possible race conditions.
2366  llvm::SmallString<128> TempPath;
2367  TempPath = File;
2368  TempPath += "-%%%%%%%%";
2369  int fd;
2370  if (llvm::sys::fs::unique_file(TempPath.str(), fd, TempPath,
2371                                 /*makeAbsolute=*/false))
2372    return CXSaveError_Unknown;
2373
2374  // FIXME: Can we somehow regenerate the stat cache here, or do we need to
2375  // unconditionally create a stat cache when we parse the file?
2376  llvm::raw_fd_ostream Out(fd, /*shouldClose=*/true);
2377
2378  serialize(Out);
2379  Out.close();
2380  if (Out.has_error())
2381    return CXSaveError_Unknown;
2382
2383  if (llvm::error_code ec = llvm::sys::fs::rename(TempPath.str(), File)) {
2384    bool exists;
2385    llvm::sys::fs::remove(TempPath.str(), exists);
2386    return CXSaveError_Unknown;
2387  }
2388
2389  return CXSaveError_None;
2390}
2391
2392bool ASTUnit::serialize(raw_ostream &OS) {
2393  if (getDiagnostics().hasErrorOccurred())
2394    return true;
2395
2396  std::vector<unsigned char> Buffer;
2397  llvm::BitstreamWriter Stream(Buffer);
2398  ASTWriter Writer(Stream);
2399  // FIXME: Handle modules
2400  Writer.WriteAST(getSema(), 0, std::string(), /*IsModule=*/false, "");
2401
2402  // Write the generated bitstream to "Out".
2403  if (!Buffer.empty())
2404    OS.write((char *)&Buffer.front(), Buffer.size());
2405
2406  return false;
2407}
2408
2409typedef ContinuousRangeMap<unsigned, int, 2> SLocRemap;
2410
2411static void TranslateSLoc(SourceLocation &L, SLocRemap &Remap) {
2412  unsigned Raw = L.getRawEncoding();
2413  const unsigned MacroBit = 1U << 31;
2414  L = SourceLocation::getFromRawEncoding((Raw & MacroBit) |
2415      ((Raw & ~MacroBit) + Remap.find(Raw & ~MacroBit)->second));
2416}
2417
2418void ASTUnit::TranslateStoredDiagnostics(
2419                          ASTReader *MMan,
2420                          StringRef ModName,
2421                          SourceManager &SrcMgr,
2422                          const SmallVectorImpl<StoredDiagnostic> &Diags,
2423                          SmallVectorImpl<StoredDiagnostic> &Out) {
2424  // The stored diagnostic has the old source manager in it; update
2425  // the locations to refer into the new source manager. We also need to remap
2426  // all the locations to the new view. This includes the diag location, any
2427  // associated source ranges, and the source ranges of associated fix-its.
2428  // FIXME: There should be a cleaner way to do this.
2429
2430  SmallVector<StoredDiagnostic, 4> Result;
2431  Result.reserve(Diags.size());
2432  assert(MMan && "Don't have a module manager");
2433  serialization::Module *Mod = MMan->ModuleMgr.lookup(ModName);
2434  assert(Mod && "Don't have preamble module");
2435  SLocRemap &Remap = Mod->SLocRemap;
2436  for (unsigned I = 0, N = Diags.size(); I != N; ++I) {
2437    // Rebuild the StoredDiagnostic.
2438    const StoredDiagnostic &SD = Diags[I];
2439    SourceLocation L = SD.getLocation();
2440    TranslateSLoc(L, Remap);
2441    FullSourceLoc Loc(L, SrcMgr);
2442
2443    SmallVector<CharSourceRange, 4> Ranges;
2444    Ranges.reserve(SD.range_size());
2445    for (StoredDiagnostic::range_iterator I = SD.range_begin(),
2446                                          E = SD.range_end();
2447         I != E; ++I) {
2448      SourceLocation BL = I->getBegin();
2449      TranslateSLoc(BL, Remap);
2450      SourceLocation EL = I->getEnd();
2451      TranslateSLoc(EL, Remap);
2452      Ranges.push_back(CharSourceRange(SourceRange(BL, EL), I->isTokenRange()));
2453    }
2454
2455    SmallVector<FixItHint, 2> FixIts;
2456    FixIts.reserve(SD.fixit_size());
2457    for (StoredDiagnostic::fixit_iterator I = SD.fixit_begin(),
2458                                          E = SD.fixit_end();
2459         I != E; ++I) {
2460      FixIts.push_back(FixItHint());
2461      FixItHint &FH = FixIts.back();
2462      FH.CodeToInsert = I->CodeToInsert;
2463      SourceLocation BL = I->RemoveRange.getBegin();
2464      TranslateSLoc(BL, Remap);
2465      SourceLocation EL = I->RemoveRange.getEnd();
2466      TranslateSLoc(EL, Remap);
2467      FH.RemoveRange = CharSourceRange(SourceRange(BL, EL),
2468                                       I->RemoveRange.isTokenRange());
2469    }
2470
2471    Result.push_back(StoredDiagnostic(SD.getLevel(), SD.getID(),
2472                                      SD.getMessage(), Loc, Ranges, FixIts));
2473  }
2474  Result.swap(Out);
2475}
2476
2477static inline bool compLocDecl(std::pair<unsigned, Decl *> L,
2478                               std::pair<unsigned, Decl *> R) {
2479  return L.first < R.first;
2480}
2481
2482void ASTUnit::addFileLevelDecl(Decl *D) {
2483  assert(D);
2484
2485  // We only care about local declarations.
2486  if (D->isFromASTFile())
2487    return;
2488
2489  SourceManager &SM = *SourceMgr;
2490  SourceLocation Loc = D->getLocation();
2491  if (Loc.isInvalid() || !SM.isLocalSourceLocation(Loc))
2492    return;
2493
2494  // We only keep track of the file-level declarations of each file.
2495  if (!D->getLexicalDeclContext()->isFileContext())
2496    return;
2497
2498  SourceLocation FileLoc = SM.getFileLoc(Loc);
2499  assert(SM.isLocalSourceLocation(FileLoc));
2500  FileID FID;
2501  unsigned Offset;
2502  llvm::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
2503  if (FID.isInvalid())
2504    return;
2505
2506  LocDeclsTy *&Decls = FileDecls[FID];
2507  if (!Decls)
2508    Decls = new LocDeclsTy();
2509
2510  std::pair<unsigned, Decl *> LocDecl(Offset, D);
2511
2512  if (Decls->empty() || Decls->back().first <= Offset) {
2513    Decls->push_back(LocDecl);
2514    return;
2515  }
2516
2517  LocDeclsTy::iterator
2518    I = std::upper_bound(Decls->begin(), Decls->end(), LocDecl, compLocDecl);
2519
2520  Decls->insert(I, LocDecl);
2521}
2522
2523void ASTUnit::findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
2524                                  SmallVectorImpl<Decl *> &Decls) {
2525  if (File.isInvalid())
2526    return;
2527
2528  if (SourceMgr->isLoadedFileID(File)) {
2529    assert(Ctx->getExternalSource() && "No external source!");
2530    return Ctx->getExternalSource()->FindFileRegionDecls(File, Offset, Length,
2531                                                         Decls);
2532  }
2533
2534  FileDeclsTy::iterator I = FileDecls.find(File);
2535  if (I == FileDecls.end())
2536    return;
2537
2538  LocDeclsTy &LocDecls = *I->second;
2539  if (LocDecls.empty())
2540    return;
2541
2542  LocDeclsTy::iterator
2543    BeginIt = std::lower_bound(LocDecls.begin(), LocDecls.end(),
2544                               std::make_pair(Offset, (Decl*)0), compLocDecl);
2545  if (BeginIt != LocDecls.begin())
2546    --BeginIt;
2547
2548  LocDeclsTy::iterator
2549    EndIt = std::upper_bound(LocDecls.begin(), LocDecls.end(),
2550                             std::make_pair(Offset+Length, (Decl*)0),
2551                             compLocDecl);
2552  if (EndIt != LocDecls.end())
2553    ++EndIt;
2554
2555  for (LocDeclsTy::iterator DIt = BeginIt; DIt != EndIt; ++DIt)
2556    Decls.push_back(DIt->second);
2557}
2558
2559SourceLocation ASTUnit::getLocation(const FileEntry *File,
2560                                    unsigned Line, unsigned Col) const {
2561  const SourceManager &SM = getSourceManager();
2562  SourceLocation Loc = SM.translateFileLineCol(File, Line, Col);
2563  return SM.getMacroArgExpandedLocation(Loc);
2564}
2565
2566SourceLocation ASTUnit::getLocation(const FileEntry *File,
2567                                    unsigned Offset) const {
2568  const SourceManager &SM = getSourceManager();
2569  SourceLocation FileLoc = SM.translateFileLineCol(File, 1, 1);
2570  return SM.getMacroArgExpandedLocation(FileLoc.getLocWithOffset(Offset));
2571}
2572
2573/// \brief If \arg Loc is a loaded location from the preamble, returns
2574/// the corresponding local location of the main file, otherwise it returns
2575/// \arg Loc.
2576SourceLocation ASTUnit::mapLocationFromPreamble(SourceLocation Loc) {
2577  FileID PreambleID;
2578  if (SourceMgr)
2579    PreambleID = SourceMgr->getPreambleFileID();
2580
2581  if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2582    return Loc;
2583
2584  unsigned Offs;
2585  if (SourceMgr->isInFileID(Loc, PreambleID, &Offs) && Offs < Preamble.size()) {
2586    SourceLocation FileLoc
2587        = SourceMgr->getLocForStartOfFile(SourceMgr->getMainFileID());
2588    return FileLoc.getLocWithOffset(Offs);
2589  }
2590
2591  return Loc;
2592}
2593
2594/// \brief If \arg Loc is a local location of the main file but inside the
2595/// preamble chunk, returns the corresponding loaded location from the
2596/// preamble, otherwise it returns \arg Loc.
2597SourceLocation ASTUnit::mapLocationToPreamble(SourceLocation Loc) {
2598  FileID PreambleID;
2599  if (SourceMgr)
2600    PreambleID = SourceMgr->getPreambleFileID();
2601
2602  if (Loc.isInvalid() || Preamble.empty() || PreambleID.isInvalid())
2603    return Loc;
2604
2605  unsigned Offs;
2606  if (SourceMgr->isInFileID(Loc, SourceMgr->getMainFileID(), &Offs) &&
2607      Offs < Preamble.size()) {
2608    SourceLocation FileLoc = SourceMgr->getLocForStartOfFile(PreambleID);
2609    return FileLoc.getLocWithOffset(Offs);
2610  }
2611
2612  return Loc;
2613}
2614
2615bool ASTUnit::isInPreambleFileID(SourceLocation Loc) {
2616  FileID FID;
2617  if (SourceMgr)
2618    FID = SourceMgr->getPreambleFileID();
2619
2620  if (Loc.isInvalid() || FID.isInvalid())
2621    return false;
2622
2623  return SourceMgr->isInFileID(Loc, FID);
2624}
2625
2626bool ASTUnit::isInMainFileID(SourceLocation Loc) {
2627  FileID FID;
2628  if (SourceMgr)
2629    FID = SourceMgr->getMainFileID();
2630
2631  if (Loc.isInvalid() || FID.isInvalid())
2632    return false;
2633
2634  return SourceMgr->isInFileID(Loc, FID);
2635}
2636
2637SourceLocation ASTUnit::getEndOfPreambleFileID() {
2638  FileID FID;
2639  if (SourceMgr)
2640    FID = SourceMgr->getPreambleFileID();
2641
2642  if (FID.isInvalid())
2643    return SourceLocation();
2644
2645  return SourceMgr->getLocForEndOfFile(FID);
2646}
2647
2648SourceLocation ASTUnit::getStartOfMainFileID() {
2649  FileID FID;
2650  if (SourceMgr)
2651    FID = SourceMgr->getMainFileID();
2652
2653  if (FID.isInvalid())
2654    return SourceLocation();
2655
2656  return SourceMgr->getLocForStartOfFile(FID);
2657}
2658
2659void ASTUnit::PreambleData::countLines() const {
2660  NumLines = 0;
2661  if (empty())
2662    return;
2663
2664  for (std::vector<char>::const_iterator
2665         I = Buffer.begin(), E = Buffer.end(); I != E; ++I) {
2666    if (*I == '\n')
2667      ++NumLines;
2668  }
2669  if (Buffer.back() != '\n')
2670    ++NumLines;
2671}
2672
2673#ifndef NDEBUG
2674ASTUnit::ConcurrencyState::ConcurrencyState() {
2675  Mutex = new llvm::sys::MutexImpl(/*recursive=*/true);
2676}
2677
2678ASTUnit::ConcurrencyState::~ConcurrencyState() {
2679  delete static_cast<llvm::sys::MutexImpl *>(Mutex);
2680}
2681
2682void ASTUnit::ConcurrencyState::start() {
2683  bool acquired = static_cast<llvm::sys::MutexImpl *>(Mutex)->tryacquire();
2684  assert(acquired && "Concurrent access to ASTUnit!");
2685}
2686
2687void ASTUnit::ConcurrencyState::finish() {
2688  static_cast<llvm::sys::MutexImpl *>(Mutex)->release();
2689}
2690
2691#else // NDEBUG
2692
2693ASTUnit::ConcurrencyState::ConcurrencyState() {}
2694ASTUnit::ConcurrencyState::~ConcurrencyState() {}
2695void ASTUnit::ConcurrencyState::start() {}
2696void ASTUnit::ConcurrencyState::finish() {}
2697
2698#endif
2699