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