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