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