ASTUnit.cpp revision 07d87b418a9899b382796c698ebab186067d61ee
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/Frontend/PCHWriter.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/DeclVisitor.h"
19#include "clang/AST/StmtVisitor.h"
20#include "clang/Driver/Compilation.h"
21#include "clang/Driver/Driver.h"
22#include "clang/Driver/Job.h"
23#include "clang/Driver/Tool.h"
24#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/FrontendActions.h"
26#include "clang/Frontend/FrontendDiagnostic.h"
27#include "clang/Frontend/FrontendOptions.h"
28#include "clang/Frontend/PCHReader.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Basic/TargetOptions.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Basic/Diagnostic.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/System/Host.h"
36#include "llvm/System/Path.h"
37#include "llvm/Support/raw_ostream.h"
38#include "llvm/Support/Timer.h"
39#include <cstdlib>
40#include <cstdio>
41#include <sys/stat.h>
42using namespace clang;
43
44/// \brief After failing to build a precompiled preamble (due to
45/// errors in the source that occurs in the preamble), the number of
46/// reparses during which we'll skip even trying to precompile the
47/// preamble.
48const unsigned DefaultPreambleRebuildInterval = 5;
49
50ASTUnit::ASTUnit(bool _MainFileIsAST)
51  : CaptureDiagnostics(false), MainFileIsAST(_MainFileIsAST),
52    CompleteTranslationUnit(true), ConcurrencyCheckValue(CheckUnlocked),
53    PreambleRebuildCounter(0), SavedMainFileBuffer(0) {
54}
55
56ASTUnit::~ASTUnit() {
57  ConcurrencyCheckValue = CheckLocked;
58  CleanTemporaryFiles();
59  if (!PreambleFile.empty())
60    llvm::sys::Path(PreambleFile).eraseFromDisk();
61
62  // Free the buffers associated with remapped files. We are required to
63  // perform this operation here because we explicitly request that the
64  // compiler instance *not* free these buffers for each invocation of the
65  // parser.
66  if (Invocation.get()) {
67    PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
68    for (PreprocessorOptions::remapped_file_buffer_iterator
69           FB = PPOpts.remapped_file_buffer_begin(),
70           FBEnd = PPOpts.remapped_file_buffer_end();
71         FB != FBEnd;
72         ++FB)
73      delete FB->second;
74  }
75
76  delete SavedMainFileBuffer;
77
78  for (unsigned I = 0, N = Timers.size(); I != N; ++I)
79    delete Timers[I];
80}
81
82void ASTUnit::CleanTemporaryFiles() {
83  for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I)
84    TemporaryFiles[I].eraseFromDisk();
85  TemporaryFiles.clear();
86}
87
88namespace {
89
90/// \brief Gathers information from PCHReader that will be used to initialize
91/// a Preprocessor.
92class PCHInfoCollector : public PCHReaderListener {
93  LangOptions &LangOpt;
94  HeaderSearch &HSI;
95  std::string &TargetTriple;
96  std::string &Predefines;
97  unsigned &Counter;
98
99  unsigned NumHeaderInfos;
100
101public:
102  PCHInfoCollector(LangOptions &LangOpt, HeaderSearch &HSI,
103                   std::string &TargetTriple, std::string &Predefines,
104                   unsigned &Counter)
105    : LangOpt(LangOpt), HSI(HSI), TargetTriple(TargetTriple),
106      Predefines(Predefines), Counter(Counter), NumHeaderInfos(0) {}
107
108  virtual bool ReadLanguageOptions(const LangOptions &LangOpts) {
109    LangOpt = LangOpts;
110    return false;
111  }
112
113  virtual bool ReadTargetTriple(llvm::StringRef Triple) {
114    TargetTriple = Triple;
115    return false;
116  }
117
118  virtual bool ReadPredefinesBuffer(const PCHPredefinesBlocks &Buffers,
119                                    llvm::StringRef OriginalFileName,
120                                    std::string &SuggestedPredefines) {
121    Predefines = Buffers[0].Data;
122    for (unsigned I = 1, N = Buffers.size(); I != N; ++I) {
123      Predefines += Buffers[I].Data;
124    }
125    return false;
126  }
127
128  virtual void ReadHeaderFileInfo(const HeaderFileInfo &HFI, unsigned ID) {
129    HSI.setHeaderFileInfoForUID(HFI, NumHeaderInfos++);
130  }
131
132  virtual void ReadCounter(unsigned Value) {
133    Counter = Value;
134  }
135};
136
137class StoredDiagnosticClient : public DiagnosticClient {
138  llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags;
139
140public:
141  explicit StoredDiagnosticClient(
142                          llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
143    : StoredDiags(StoredDiags) { }
144
145  virtual void HandleDiagnostic(Diagnostic::Level Level,
146                                const DiagnosticInfo &Info);
147};
148
149/// \brief RAII object that optionally captures diagnostics, if
150/// there is no diagnostic client to capture them already.
151class CaptureDroppedDiagnostics {
152  Diagnostic &Diags;
153  StoredDiagnosticClient Client;
154  DiagnosticClient *PreviousClient;
155
156public:
157  CaptureDroppedDiagnostics(bool RequestCapture, Diagnostic &Diags,
158                           llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiags)
159    : Diags(Diags), Client(StoredDiags), PreviousClient(Diags.getClient())
160  {
161    if (RequestCapture || Diags.getClient() == 0)
162      Diags.setClient(&Client);
163  }
164
165  ~CaptureDroppedDiagnostics() {
166    Diags.setClient(PreviousClient);
167  }
168};
169
170} // anonymous namespace
171
172void StoredDiagnosticClient::HandleDiagnostic(Diagnostic::Level Level,
173                                              const DiagnosticInfo &Info) {
174  StoredDiags.push_back(StoredDiagnostic(Level, Info));
175}
176
177const std::string &ASTUnit::getOriginalSourceFileName() {
178  return OriginalSourceFile;
179}
180
181const std::string &ASTUnit::getPCHFileName() {
182  assert(isMainFileAST() && "Not an ASTUnit from a PCH file!");
183  return static_cast<PCHReader *>(Ctx->getExternalSource())->getFileName();
184}
185
186ASTUnit *ASTUnit::LoadFromPCHFile(const std::string &Filename,
187                                  llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
188                                  bool OnlyLocalDecls,
189                                  RemappedFile *RemappedFiles,
190                                  unsigned NumRemappedFiles,
191                                  bool CaptureDiagnostics) {
192  llvm::OwningPtr<ASTUnit> AST(new ASTUnit(true));
193
194  if (!Diags.getPtr()) {
195    // No diagnostics engine was provided, so create our own diagnostics object
196    // with the default options.
197    DiagnosticOptions DiagOpts;
198    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
199  }
200
201  AST->CaptureDiagnostics = CaptureDiagnostics;
202  AST->OnlyLocalDecls = OnlyLocalDecls;
203  AST->Diagnostics = Diags;
204  AST->FileMgr.reset(new FileManager);
205  AST->SourceMgr.reset(new SourceManager(AST->getDiagnostics()));
206  AST->HeaderInfo.reset(new HeaderSearch(AST->getFileManager()));
207
208  // If requested, capture diagnostics in the ASTUnit.
209  CaptureDroppedDiagnostics Capture(CaptureDiagnostics, AST->getDiagnostics(),
210                                    AST->StoredDiagnostics);
211
212  for (unsigned I = 0; I != NumRemappedFiles; ++I) {
213    // Create the file entry for the file that we're mapping from.
214    const FileEntry *FromFile
215      = AST->getFileManager().getVirtualFile(RemappedFiles[I].first,
216                                    RemappedFiles[I].second->getBufferSize(),
217                                             0);
218    if (!FromFile) {
219      AST->getDiagnostics().Report(diag::err_fe_remap_missing_from_file)
220        << RemappedFiles[I].first;
221      delete RemappedFiles[I].second;
222      continue;
223    }
224
225    // Override the contents of the "from" file with the contents of
226    // the "to" file.
227    AST->getSourceManager().overrideFileContents(FromFile,
228                                                 RemappedFiles[I].second);
229  }
230
231  // Gather Info for preprocessor construction later on.
232
233  LangOptions LangInfo;
234  HeaderSearch &HeaderInfo = *AST->HeaderInfo.get();
235  std::string TargetTriple;
236  std::string Predefines;
237  unsigned Counter;
238
239  llvm::OwningPtr<PCHReader> Reader;
240  llvm::OwningPtr<ExternalASTSource> Source;
241
242  Reader.reset(new PCHReader(AST->getSourceManager(), AST->getFileManager(),
243                             AST->getDiagnostics()));
244  Reader->setListener(new PCHInfoCollector(LangInfo, HeaderInfo, TargetTriple,
245                                           Predefines, Counter));
246
247  switch (Reader->ReadPCH(Filename)) {
248  case PCHReader::Success:
249    break;
250
251  case PCHReader::Failure:
252  case PCHReader::IgnorePCH:
253    AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
254    return NULL;
255  }
256
257  AST->OriginalSourceFile = Reader->getOriginalSourceFile();
258
259  // PCH loaded successfully. Now create the preprocessor.
260
261  // Get information about the target being compiled for.
262  //
263  // FIXME: This is broken, we should store the TargetOptions in the PCH.
264  TargetOptions TargetOpts;
265  TargetOpts.ABI = "";
266  TargetOpts.CXXABI = "itanium";
267  TargetOpts.CPU = "";
268  TargetOpts.Features.clear();
269  TargetOpts.Triple = TargetTriple;
270  AST->Target.reset(TargetInfo::CreateTargetInfo(AST->getDiagnostics(),
271                                                 TargetOpts));
272  AST->PP.reset(new Preprocessor(AST->getDiagnostics(), LangInfo,
273                                 *AST->Target.get(),
274                                 AST->getSourceManager(), HeaderInfo));
275  Preprocessor &PP = *AST->PP.get();
276
277  PP.setPredefines(Reader->getSuggestedPredefines());
278  PP.setCounterValue(Counter);
279  Reader->setPreprocessor(PP);
280
281  // Create and initialize the ASTContext.
282
283  AST->Ctx.reset(new ASTContext(LangInfo,
284                                AST->getSourceManager(),
285                                *AST->Target.get(),
286                                PP.getIdentifierTable(),
287                                PP.getSelectorTable(),
288                                PP.getBuiltinInfo(),
289                                /* size_reserve = */0));
290  ASTContext &Context = *AST->Ctx.get();
291
292  Reader->InitializeContext(Context);
293
294  // Attach the PCH reader to the AST context as an external AST
295  // source, so that declarations will be deserialized from the
296  // PCH file as needed.
297  Source.reset(Reader.take());
298  Context.setExternalSource(Source);
299
300  return AST.take();
301}
302
303namespace {
304
305class TopLevelDeclTrackerConsumer : public ASTConsumer {
306  ASTUnit &Unit;
307
308public:
309  TopLevelDeclTrackerConsumer(ASTUnit &_Unit) : Unit(_Unit) {}
310
311  void HandleTopLevelDecl(DeclGroupRef D) {
312    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
313      Decl *D = *it;
314      // FIXME: Currently ObjC method declarations are incorrectly being
315      // reported as top-level declarations, even though their DeclContext
316      // is the containing ObjC @interface/@implementation.  This is a
317      // fundamental problem in the parser right now.
318      if (isa<ObjCMethodDecl>(D))
319        continue;
320      Unit.addTopLevelDecl(D);
321    }
322  }
323
324  // We're not interested in "interesting" decls.
325  void HandleInterestingDecl(DeclGroupRef) {}
326};
327
328class TopLevelDeclTrackerAction : public ASTFrontendAction {
329public:
330  ASTUnit &Unit;
331
332  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
333                                         llvm::StringRef InFile) {
334    return new TopLevelDeclTrackerConsumer(Unit);
335  }
336
337public:
338  TopLevelDeclTrackerAction(ASTUnit &_Unit) : Unit(_Unit) {}
339
340  virtual bool hasCodeCompletionSupport() const { return false; }
341  virtual bool usesCompleteTranslationUnit()  {
342    return Unit.isCompleteTranslationUnit();
343  }
344};
345
346class PrecompilePreambleConsumer : public PCHGenerator {
347  ASTUnit &Unit;
348  std::vector<Decl *> TopLevelDecls;
349
350public:
351  PrecompilePreambleConsumer(ASTUnit &Unit,
352                             const Preprocessor &PP, bool Chaining,
353                             const char *isysroot, llvm::raw_ostream *Out)
354    : PCHGenerator(PP, Chaining, isysroot, Out), Unit(Unit) { }
355
356  virtual void HandleTopLevelDecl(DeclGroupRef D) {
357    for (DeclGroupRef::iterator it = D.begin(), ie = D.end(); it != ie; ++it) {
358      Decl *D = *it;
359      // FIXME: Currently ObjC method declarations are incorrectly being
360      // reported as top-level declarations, even though their DeclContext
361      // is the containing ObjC @interface/@implementation.  This is a
362      // fundamental problem in the parser right now.
363      if (isa<ObjCMethodDecl>(D))
364        continue;
365      TopLevelDecls.push_back(D);
366    }
367  }
368
369  virtual void HandleTranslationUnit(ASTContext &Ctx) {
370    PCHGenerator::HandleTranslationUnit(Ctx);
371    if (!Unit.getDiagnostics().hasErrorOccurred()) {
372      // Translate the top-level declarations we captured during
373      // parsing into declaration IDs in the precompiled
374      // preamble. This will allow us to deserialize those top-level
375      // declarations when requested.
376      for (unsigned I = 0, N = TopLevelDecls.size(); I != N; ++I)
377        Unit.addTopLevelDeclFromPreamble(
378                                      getWriter().getDeclID(TopLevelDecls[I]));
379    }
380  }
381};
382
383class PrecompilePreambleAction : public ASTFrontendAction {
384  ASTUnit &Unit;
385
386public:
387  explicit PrecompilePreambleAction(ASTUnit &Unit) : Unit(Unit) {}
388
389  virtual ASTConsumer *CreateASTConsumer(CompilerInstance &CI,
390                                         llvm::StringRef InFile) {
391    std::string Sysroot;
392    llvm::raw_ostream *OS = 0;
393    bool Chaining;
394    if (GeneratePCHAction::ComputeASTConsumerArguments(CI, InFile, Sysroot,
395                                                       OS, Chaining))
396      return 0;
397
398    const char *isysroot = CI.getFrontendOpts().RelocatablePCH ?
399                             Sysroot.c_str() : 0;
400    return new PrecompilePreambleConsumer(Unit, CI.getPreprocessor(), Chaining,
401                                          isysroot, OS);
402  }
403
404  virtual bool hasCodeCompletionSupport() const { return false; }
405  virtual bool hasASTFileSupport() const { return false; }
406  virtual bool usesCompleteTranslationUnit() { return false; }
407};
408
409}
410
411/// Parse the source file into a translation unit using the given compiler
412/// invocation, replacing the current translation unit.
413///
414/// \returns True if a failure occurred that causes the ASTUnit not to
415/// contain any translation-unit information, false otherwise.
416bool ASTUnit::Parse(llvm::MemoryBuffer *OverrideMainBuffer) {
417  delete SavedMainFileBuffer;
418  SavedMainFileBuffer = 0;
419
420  if (!Invocation.get())
421    return true;
422
423  // Create the compiler instance to use for building the AST.
424  CompilerInstance Clang;
425  Clang.setInvocation(Invocation.take());
426  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
427
428  // Set up diagnostics, capturing any diagnostics that would
429  // otherwise be dropped.
430  Clang.setDiagnostics(&getDiagnostics());
431  CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
432                                    getDiagnostics(),
433                                    StoredDiagnostics);
434  Clang.setDiagnosticClient(getDiagnostics().getClient());
435
436  // Create the target instance.
437  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
438                                               Clang.getTargetOpts()));
439  if (!Clang.hasTarget()) {
440    Clang.takeDiagnosticClient();
441    return true;
442  }
443
444  // Inform the target of the language options.
445  //
446  // FIXME: We shouldn't need to do this, the target should be immutable once
447  // created. This complexity should be lifted elsewhere.
448  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
449
450  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
451         "Invocation must have exactly one source file!");
452  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
453         "FIXME: AST inputs not yet supported here!");
454  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
455         "IR inputs not support here!");
456
457  // Configure the various subsystems.
458  // FIXME: Should we retain the previous file manager?
459  FileMgr.reset(new FileManager);
460  SourceMgr.reset(new SourceManager(getDiagnostics()));
461  Ctx.reset();
462  PP.reset();
463
464  // Clear out old caches and data.
465  TopLevelDecls.clear();
466  CleanTemporaryFiles();
467  PreprocessedEntitiesByFile.clear();
468
469  if (!OverrideMainBuffer)
470    StoredDiagnostics.clear();
471
472  // Create a file manager object to provide access to and cache the filesystem.
473  Clang.setFileManager(&getFileManager());
474
475  // Create the source manager.
476  Clang.setSourceManager(&getSourceManager());
477
478  // If the main file has been overridden due to the use of a preamble,
479  // make that override happen and introduce the preamble.
480  PreprocessorOptions &PreprocessorOpts = Clang.getPreprocessorOpts();
481  std::string PriorImplicitPCHInclude;
482  if (OverrideMainBuffer) {
483    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
484    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
485    PreprocessorOpts.PrecompiledPreambleBytes.second
486                                                    = PreambleEndsAtStartOfLine;
487    PriorImplicitPCHInclude = PreprocessorOpts.ImplicitPCHInclude;
488    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
489    PreprocessorOpts.DisablePCHValidation = true;
490
491    // Keep track of the override buffer;
492    SavedMainFileBuffer = OverrideMainBuffer;
493
494    // The stored diagnostic has the old source manager in it; update
495    // the locations to refer into the new source manager. Since we've
496    // been careful to make sure that the source manager's state
497    // before and after are identical, so that we can reuse the source
498    // location itself.
499    for (unsigned I = 0, N = StoredDiagnostics.size(); I != N; ++I) {
500      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(),
501                        getSourceManager());
502      StoredDiagnostics[I].setLocation(Loc);
503    }
504  }
505
506  llvm::OwningPtr<TopLevelDeclTrackerAction> Act;
507  Act.reset(new TopLevelDeclTrackerAction(*this));
508  if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
509                            Clang.getFrontendOpts().Inputs[0].first))
510    goto error;
511
512  Act->Execute();
513
514  // Steal the created target, context, and preprocessor, and take back the
515  // source and file managers.
516  Ctx.reset(Clang.takeASTContext());
517  PP.reset(Clang.takePreprocessor());
518  Clang.takeSourceManager();
519  Clang.takeFileManager();
520  Target.reset(Clang.takeTarget());
521
522  Act->EndSourceFile();
523
524  // Remove the overridden buffer we used for the preamble.
525  if (OverrideMainBuffer) {
526    PreprocessorOpts.eraseRemappedFile(
527                               PreprocessorOpts.remapped_file_buffer_end() - 1);
528    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
529  }
530
531  Clang.takeDiagnosticClient();
532
533  Invocation.reset(Clang.takeInvocation());
534  return false;
535
536error:
537  // Remove the overridden buffer we used for the preamble.
538  if (OverrideMainBuffer) {
539    PreprocessorOpts.eraseRemappedFile(
540                               PreprocessorOpts.remapped_file_buffer_end() - 1);
541    PreprocessorOpts.DisablePCHValidation = true;
542    PreprocessorOpts.ImplicitPCHInclude = PriorImplicitPCHInclude;
543  }
544
545  Clang.takeSourceManager();
546  Clang.takeFileManager();
547  Clang.takeDiagnosticClient();
548  Invocation.reset(Clang.takeInvocation());
549  return true;
550}
551
552/// \brief Simple function to retrieve a path for a preamble precompiled header.
553static std::string GetPreamblePCHPath() {
554  // FIXME: This is lame; sys::Path should provide this function (in particular,
555  // it should know how to find the temporary files dir).
556  // FIXME: This is really lame. I copied this code from the Driver!
557  std::string Error;
558  const char *TmpDir = ::getenv("TMPDIR");
559  if (!TmpDir)
560    TmpDir = ::getenv("TEMP");
561  if (!TmpDir)
562    TmpDir = ::getenv("TMP");
563  if (!TmpDir)
564    TmpDir = "/tmp";
565  llvm::sys::Path P(TmpDir);
566  P.appendComponent("preamble");
567  P.appendSuffix("pch");
568  if (P.createTemporaryFileOnDisk())
569    return std::string();
570
571  fprintf(stderr, "Preamble file: %s\n", P.str().c_str());
572  return P.str();
573}
574
575/// \brief Compute the preamble for the main file, providing the source buffer
576/// that corresponds to the main file along with a pair (bytes, start-of-line)
577/// that describes the preamble.
578std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
579ASTUnit::ComputePreamble(CompilerInvocation &Invocation,
580                         unsigned MaxLines, bool &CreatedBuffer) {
581  FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
582  PreprocessorOptions &PreprocessorOpts
583    = Invocation.getPreprocessorOpts();
584  CreatedBuffer = false;
585
586  // Try to determine if the main file has been remapped, either from the
587  // command line (to another file) or directly through the compiler invocation
588  // (to a memory buffer).
589  llvm::MemoryBuffer *Buffer = 0;
590  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
591  if (const llvm::sys::FileStatus *MainFileStatus = MainFilePath.getFileStatus()) {
592    // Check whether there is a file-file remapping of the main file
593    for (PreprocessorOptions::remapped_file_iterator
594          M = PreprocessorOpts.remapped_file_begin(),
595          E = PreprocessorOpts.remapped_file_end();
596         M != E;
597         ++M) {
598      llvm::sys::PathWithStatus MPath(M->first);
599      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
600        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
601          // We found a remapping. Try to load the resulting, remapped source.
602          if (CreatedBuffer) {
603            delete Buffer;
604            CreatedBuffer = false;
605          }
606
607          Buffer = llvm::MemoryBuffer::getFile(M->second);
608          if (!Buffer)
609            return std::make_pair((llvm::MemoryBuffer*)0,
610                                  std::make_pair(0, true));
611          CreatedBuffer = true;
612
613          // Remove this remapping. We've captured the buffer already.
614          M = PreprocessorOpts.eraseRemappedFile(M);
615          E = PreprocessorOpts.remapped_file_end();
616        }
617      }
618    }
619
620    // Check whether there is a file-buffer remapping. It supercedes the
621    // file-file remapping.
622    for (PreprocessorOptions::remapped_file_buffer_iterator
623           M = PreprocessorOpts.remapped_file_buffer_begin(),
624           E = PreprocessorOpts.remapped_file_buffer_end();
625         M != E;
626         ++M) {
627      llvm::sys::PathWithStatus MPath(M->first);
628      if (const llvm::sys::FileStatus *MStatus = MPath.getFileStatus()) {
629        if (MainFileStatus->uniqueID == MStatus->uniqueID) {
630          // We found a remapping.
631          if (CreatedBuffer) {
632            delete Buffer;
633            CreatedBuffer = false;
634          }
635
636          Buffer = const_cast<llvm::MemoryBuffer *>(M->second);
637
638          // Remove this remapping. We've captured the buffer already.
639          M = PreprocessorOpts.eraseRemappedFile(M);
640          E = PreprocessorOpts.remapped_file_buffer_end();
641        }
642      }
643    }
644  }
645
646  // If the main source file was not remapped, load it now.
647  if (!Buffer) {
648    Buffer = llvm::MemoryBuffer::getFile(FrontendOpts.Inputs[0].second);
649    if (!Buffer)
650      return std::make_pair((llvm::MemoryBuffer*)0, std::make_pair(0, true));
651
652    CreatedBuffer = true;
653  }
654
655  return std::make_pair(Buffer, Lexer::ComputePreamble(Buffer, MaxLines));
656}
657
658static llvm::MemoryBuffer *CreatePaddedMainFileBuffer(llvm::MemoryBuffer *Old,
659                                                      bool DeleteOld,
660                                                      unsigned NewSize,
661                                                      llvm::StringRef NewName) {
662  llvm::MemoryBuffer *Result
663    = llvm::MemoryBuffer::getNewUninitMemBuffer(NewSize, NewName);
664  memcpy(const_cast<char*>(Result->getBufferStart()),
665         Old->getBufferStart(), Old->getBufferSize());
666  memset(const_cast<char*>(Result->getBufferStart()) + Old->getBufferSize(),
667         ' ', NewSize - Old->getBufferSize() - 1);
668  const_cast<char*>(Result->getBufferEnd())[-1] = '\n';
669
670  if (DeleteOld)
671    delete Old;
672
673  return Result;
674}
675
676/// \brief Attempt to build or re-use a precompiled preamble when (re-)parsing
677/// the source file.
678///
679/// This routine will compute the preamble of the main source file. If a
680/// non-trivial preamble is found, it will precompile that preamble into a
681/// precompiled header so that the precompiled preamble can be used to reduce
682/// reparsing time. If a precompiled preamble has already been constructed,
683/// this routine will determine if it is still valid and, if so, avoid
684/// rebuilding the precompiled preamble.
685///
686/// \param AllowRebuild When true (the default), this routine is
687/// allowed to rebuild the precompiled preamble if it is found to be
688/// out-of-date.
689///
690/// \param MaxLines When non-zero, the maximum number of lines that
691/// can occur within the preamble.
692///
693/// \returns If the precompiled preamble can be used, returns a newly-allocated
694/// buffer that should be used in place of the main file when doing so.
695/// Otherwise, returns a NULL pointer.
696llvm::MemoryBuffer *ASTUnit::getMainBufferWithPrecompiledPreamble(
697                                                           bool AllowRebuild,
698                                                           unsigned MaxLines) {
699  CompilerInvocation PreambleInvocation(*Invocation);
700  FrontendOptions &FrontendOpts = PreambleInvocation.getFrontendOpts();
701  PreprocessorOptions &PreprocessorOpts
702    = PreambleInvocation.getPreprocessorOpts();
703
704  bool CreatedPreambleBuffer = false;
705  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> > NewPreamble
706    = ComputePreamble(PreambleInvocation, MaxLines, CreatedPreambleBuffer);
707
708  if (!NewPreamble.second.first) {
709    // We couldn't find a preamble in the main source. Clear out the current
710    // preamble, if we have one. It's obviously no good any more.
711    Preamble.clear();
712    if (!PreambleFile.empty()) {
713      llvm::sys::Path(PreambleFile).eraseFromDisk();
714      PreambleFile.clear();
715    }
716    if (CreatedPreambleBuffer)
717      delete NewPreamble.first;
718
719    // The next time we actually see a preamble, precompile it.
720    PreambleRebuildCounter = 1;
721    return 0;
722  }
723
724  if (!Preamble.empty()) {
725    // We've previously computed a preamble. Check whether we have the same
726    // preamble now that we did before, and that there's enough space in
727    // the main-file buffer within the precompiled preamble to fit the
728    // new main file.
729    if (Preamble.size() == NewPreamble.second.first &&
730        PreambleEndsAtStartOfLine == NewPreamble.second.second &&
731        NewPreamble.first->getBufferSize() < PreambleReservedSize-2 &&
732        memcmp(&Preamble[0], NewPreamble.first->getBufferStart(),
733               NewPreamble.second.first) == 0) {
734      // The preamble has not changed. We may be able to re-use the precompiled
735      // preamble.
736
737      // Check that none of the files used by the preamble have changed.
738      bool AnyFileChanged = false;
739
740      // First, make a record of those files that have been overridden via
741      // remapping or unsaved_files.
742      llvm::StringMap<std::pair<off_t, time_t> > OverriddenFiles;
743      for (PreprocessorOptions::remapped_file_iterator
744                R = PreprocessorOpts.remapped_file_begin(),
745             REnd = PreprocessorOpts.remapped_file_end();
746           !AnyFileChanged && R != REnd;
747           ++R) {
748        struct stat StatBuf;
749        if (stat(R->second.c_str(), &StatBuf)) {
750          // If we can't stat the file we're remapping to, assume that something
751          // horrible happened.
752          AnyFileChanged = true;
753          break;
754        }
755
756        OverriddenFiles[R->first] = std::make_pair(StatBuf.st_size,
757                                                   StatBuf.st_mtime);
758      }
759      for (PreprocessorOptions::remapped_file_buffer_iterator
760                R = PreprocessorOpts.remapped_file_buffer_begin(),
761             REnd = PreprocessorOpts.remapped_file_buffer_end();
762           !AnyFileChanged && R != REnd;
763           ++R) {
764        // FIXME: Should we actually compare the contents of file->buffer
765        // remappings?
766        OverriddenFiles[R->first] = std::make_pair(R->second->getBufferSize(),
767                                                   0);
768      }
769
770      // Check whether anything has changed.
771      for (llvm::StringMap<std::pair<off_t, time_t> >::iterator
772             F = FilesInPreamble.begin(), FEnd = FilesInPreamble.end();
773           !AnyFileChanged && F != FEnd;
774           ++F) {
775        llvm::StringMap<std::pair<off_t, time_t> >::iterator Overridden
776          = OverriddenFiles.find(F->first());
777        if (Overridden != OverriddenFiles.end()) {
778          // This file was remapped; check whether the newly-mapped file
779          // matches up with the previous mapping.
780          if (Overridden->second != F->second)
781            AnyFileChanged = true;
782          continue;
783        }
784
785        // The file was not remapped; check whether it has changed on disk.
786        struct stat StatBuf;
787        if (stat(F->first(), &StatBuf)) {
788          // If we can't stat the file, assume that something horrible happened.
789          AnyFileChanged = true;
790        } else if (StatBuf.st_size != F->second.first ||
791                   StatBuf.st_mtime != F->second.second)
792          AnyFileChanged = true;
793      }
794
795      if (!AnyFileChanged) {
796        // Okay! We can re-use the precompiled preamble.
797
798        // Set the state of the diagnostic object to mimic its state
799        // after parsing the preamble.
800        getDiagnostics().Reset();
801        getDiagnostics().setNumWarnings(NumWarningsInPreamble);
802        if (StoredDiagnostics.size() > NumStoredDiagnosticsInPreamble)
803          StoredDiagnostics.erase(
804            StoredDiagnostics.begin() + NumStoredDiagnosticsInPreamble,
805                                  StoredDiagnostics.end());
806
807        // Create a version of the main file buffer that is padded to
808        // buffer size we reserved when creating the preamble.
809        return CreatePaddedMainFileBuffer(NewPreamble.first,
810                                          CreatedPreambleBuffer,
811                                          PreambleReservedSize,
812                                          FrontendOpts.Inputs[0].second);
813      }
814    }
815
816    // If we aren't allowed to rebuild the precompiled preamble, just
817    // return now.
818    if (!AllowRebuild)
819      return 0;
820
821    // We can't reuse the previously-computed preamble. Build a new one.
822    Preamble.clear();
823    llvm::sys::Path(PreambleFile).eraseFromDisk();
824    PreambleRebuildCounter = 1;
825  } else if (!AllowRebuild) {
826    // We aren't allowed to rebuild the precompiled preamble; just
827    // return now.
828    return 0;
829  }
830
831  // If the preamble rebuild counter > 1, it's because we previously
832  // failed to build a preamble and we're not yet ready to try
833  // again. Decrement the counter and return a failure.
834  if (PreambleRebuildCounter > 1) {
835    --PreambleRebuildCounter;
836    return 0;
837  }
838
839  // We did not previously compute a preamble, or it can't be reused anyway.
840  llvm::Timer *PreambleTimer = 0;
841  if (TimerGroup.get()) {
842    PreambleTimer = new llvm::Timer("Precompiling preamble", *TimerGroup);
843    PreambleTimer->startTimer();
844    Timers.push_back(PreambleTimer);
845  }
846
847  // Create a new buffer that stores the preamble. The buffer also contains
848  // extra space for the original contents of the file (which will be present
849  // when we actually parse the file) along with more room in case the file
850  // grows.
851  PreambleReservedSize = NewPreamble.first->getBufferSize();
852  if (PreambleReservedSize < 4096)
853    PreambleReservedSize = 8191;
854  else
855    PreambleReservedSize *= 2;
856
857  // Save the preamble text for later; we'll need to compare against it for
858  // subsequent reparses.
859  Preamble.assign(NewPreamble.first->getBufferStart(),
860                  NewPreamble.first->getBufferStart()
861                                                  + NewPreamble.second.first);
862  PreambleEndsAtStartOfLine = NewPreamble.second.second;
863
864  llvm::MemoryBuffer *PreambleBuffer
865    = llvm::MemoryBuffer::getNewUninitMemBuffer(PreambleReservedSize,
866                                                FrontendOpts.Inputs[0].second);
867  memcpy(const_cast<char*>(PreambleBuffer->getBufferStart()),
868         NewPreamble.first->getBufferStart(), Preamble.size());
869  memset(const_cast<char*>(PreambleBuffer->getBufferStart()) + Preamble.size(),
870         ' ', PreambleReservedSize - Preamble.size() - 1);
871  const_cast<char*>(PreambleBuffer->getBufferEnd())[-1] = '\n';
872
873  // Remap the main source file to the preamble buffer.
874  llvm::sys::PathWithStatus MainFilePath(FrontendOpts.Inputs[0].second);
875  PreprocessorOpts.addRemappedFile(MainFilePath.str(), PreambleBuffer);
876
877  // Tell the compiler invocation to generate a temporary precompiled header.
878  FrontendOpts.ProgramAction = frontend::GeneratePCH;
879  // FIXME: Set ChainedPCH unconditionally, once it is ready.
880  if (::getenv("LIBCLANG_CHAINING"))
881    FrontendOpts.ChainedPCH = true;
882  // FIXME: Generate the precompiled header into memory?
883  FrontendOpts.OutputFile = GetPreamblePCHPath();
884
885  // Create the compiler instance to use for building the precompiled preamble.
886  CompilerInstance Clang;
887  Clang.setInvocation(&PreambleInvocation);
888  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
889
890  // Set up diagnostics, capturing all of the diagnostics produced.
891  Clang.setDiagnostics(&getDiagnostics());
892  CaptureDroppedDiagnostics Capture(CaptureDiagnostics,
893                                    getDiagnostics(),
894                                    StoredDiagnostics);
895  Clang.setDiagnosticClient(getDiagnostics().getClient());
896
897  // Create the target instance.
898  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
899                                               Clang.getTargetOpts()));
900  if (!Clang.hasTarget()) {
901    Clang.takeDiagnosticClient();
902    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
903    Preamble.clear();
904    if (CreatedPreambleBuffer)
905      delete NewPreamble.first;
906    if (PreambleTimer)
907      PreambleTimer->stopTimer();
908    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
909    return 0;
910  }
911
912  // Inform the target of the language options.
913  //
914  // FIXME: We shouldn't need to do this, the target should be immutable once
915  // created. This complexity should be lifted elsewhere.
916  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
917
918  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
919         "Invocation must have exactly one source file!");
920  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
921         "FIXME: AST inputs not yet supported here!");
922  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
923         "IR inputs not support here!");
924
925  // Clear out old caches and data.
926  StoredDiagnostics.clear();
927  TopLevelDecls.clear();
928  TopLevelDeclsInPreamble.clear();
929
930  // Create a file manager object to provide access to and cache the filesystem.
931  Clang.setFileManager(new FileManager);
932
933  // Create the source manager.
934  Clang.setSourceManager(new SourceManager(getDiagnostics()));
935
936  llvm::OwningPtr<PrecompilePreambleAction> Act;
937  Act.reset(new PrecompilePreambleAction(*this));
938  if (!Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
939                            Clang.getFrontendOpts().Inputs[0].first)) {
940    Clang.takeDiagnosticClient();
941    Clang.takeInvocation();
942    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
943    Preamble.clear();
944    if (CreatedPreambleBuffer)
945      delete NewPreamble.first;
946    if (PreambleTimer)
947      PreambleTimer->stopTimer();
948    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
949
950    return 0;
951  }
952
953  Act->Execute();
954  Act->EndSourceFile();
955  Clang.takeDiagnosticClient();
956  Clang.takeInvocation();
957
958  if (Diagnostics->hasErrorOccurred()) {
959    // There were errors parsing the preamble, so no precompiled header was
960    // generated. Forget that we even tried.
961    // FIXME: Should we leave a note for ourselves to try again?
962    llvm::sys::Path(FrontendOpts.OutputFile).eraseFromDisk();
963    Preamble.clear();
964    if (CreatedPreambleBuffer)
965      delete NewPreamble.first;
966    if (PreambleTimer)
967      PreambleTimer->stopTimer();
968    TopLevelDeclsInPreamble.clear();
969    PreambleRebuildCounter = DefaultPreambleRebuildInterval;
970    return 0;
971  }
972
973  // Keep track of the preamble we precompiled.
974  PreambleFile = FrontendOpts.OutputFile;
975  NumStoredDiagnosticsInPreamble = StoredDiagnostics.size();
976  NumWarningsInPreamble = getDiagnostics().getNumWarnings();
977
978  // Keep track of all of the files that the source manager knows about,
979  // so we can verify whether they have changed or not.
980  FilesInPreamble.clear();
981  SourceManager &SourceMgr = Clang.getSourceManager();
982  const llvm::MemoryBuffer *MainFileBuffer
983    = SourceMgr.getBuffer(SourceMgr.getMainFileID());
984  for (SourceManager::fileinfo_iterator F = SourceMgr.fileinfo_begin(),
985                                     FEnd = SourceMgr.fileinfo_end();
986       F != FEnd;
987       ++F) {
988    const FileEntry *File = F->second->Entry;
989    if (!File || F->second->getRawBuffer() == MainFileBuffer)
990      continue;
991
992    FilesInPreamble[File->getName()]
993      = std::make_pair(F->second->getSize(), File->getModificationTime());
994  }
995
996  if (PreambleTimer)
997    PreambleTimer->stopTimer();
998
999  PreambleRebuildCounter = 1;
1000  return CreatePaddedMainFileBuffer(NewPreamble.first,
1001                                    CreatedPreambleBuffer,
1002                                    PreambleReservedSize,
1003                                    FrontendOpts.Inputs[0].second);
1004}
1005
1006void ASTUnit::RealizeTopLevelDeclsFromPreamble() {
1007  std::vector<Decl *> Resolved;
1008  Resolved.reserve(TopLevelDeclsInPreamble.size());
1009  ExternalASTSource &Source = *getASTContext().getExternalSource();
1010  for (unsigned I = 0, N = TopLevelDeclsInPreamble.size(); I != N; ++I) {
1011    // Resolve the declaration ID to an actual declaration, possibly
1012    // deserializing the declaration in the process.
1013    Decl *D = Source.GetExternalDecl(TopLevelDeclsInPreamble[I]);
1014    if (D)
1015      Resolved.push_back(D);
1016  }
1017  TopLevelDeclsInPreamble.clear();
1018  TopLevelDecls.insert(TopLevelDecls.begin(), Resolved.begin(), Resolved.end());
1019}
1020
1021unsigned ASTUnit::getMaxPCHLevel() const {
1022  if (!getOnlyLocalDecls())
1023    return Decl::MaxPCHLevel;
1024
1025  unsigned Result = 0;
1026  if (isMainFileAST() || SavedMainFileBuffer)
1027    ++Result;
1028  return Result;
1029}
1030
1031ASTUnit *ASTUnit::LoadFromCompilerInvocation(CompilerInvocation *CI,
1032                                   llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1033                                             bool OnlyLocalDecls,
1034                                             bool CaptureDiagnostics,
1035                                             bool PrecompilePreamble,
1036                                             bool CompleteTranslationUnit) {
1037  if (!Diags.getPtr()) {
1038    // No diagnostics engine was provided, so create our own diagnostics object
1039    // with the default options.
1040    DiagnosticOptions DiagOpts;
1041    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1042  }
1043
1044  // Create the AST unit.
1045  llvm::OwningPtr<ASTUnit> AST;
1046  AST.reset(new ASTUnit(false));
1047  AST->Diagnostics = Diags;
1048  AST->CaptureDiagnostics = CaptureDiagnostics;
1049  AST->OnlyLocalDecls = OnlyLocalDecls;
1050  AST->CompleteTranslationUnit = CompleteTranslationUnit;
1051  AST->Invocation.reset(CI);
1052  CI->getPreprocessorOpts().RetainRemappedFileBuffers = true;
1053
1054  if (getenv("LIBCLANG_TIMING"))
1055    AST->TimerGroup.reset(
1056                  new llvm::TimerGroup(CI->getFrontendOpts().Inputs[0].second));
1057
1058
1059  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1060  // FIXME: When C++ PCH is ready, allow use of it for a precompiled preamble.
1061  if (PrecompilePreamble && !CI->getLangOpts().CPlusPlus) {
1062    AST->PreambleRebuildCounter = 1;
1063    OverrideMainBuffer = AST->getMainBufferWithPrecompiledPreamble();
1064  }
1065
1066  llvm::Timer *ParsingTimer = 0;
1067  if (AST->TimerGroup.get()) {
1068    ParsingTimer = new llvm::Timer("Initial parse", *AST->TimerGroup);
1069    ParsingTimer->startTimer();
1070    AST->Timers.push_back(ParsingTimer);
1071  }
1072
1073  bool Failed = AST->Parse(OverrideMainBuffer);
1074  if (ParsingTimer)
1075    ParsingTimer->stopTimer();
1076
1077  return Failed? 0 : AST.take();
1078}
1079
1080ASTUnit *ASTUnit::LoadFromCommandLine(const char **ArgBegin,
1081                                      const char **ArgEnd,
1082                                    llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
1083                                      llvm::StringRef ResourceFilesPath,
1084                                      bool OnlyLocalDecls,
1085                                      RemappedFile *RemappedFiles,
1086                                      unsigned NumRemappedFiles,
1087                                      bool CaptureDiagnostics,
1088                                      bool PrecompilePreamble,
1089                                      bool CompleteTranslationUnit) {
1090  if (!Diags.getPtr()) {
1091    // No diagnostics engine was provided, so create our own diagnostics object
1092    // with the default options.
1093    DiagnosticOptions DiagOpts;
1094    Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
1095  }
1096
1097  llvm::SmallVector<const char *, 16> Args;
1098  Args.push_back("<clang>"); // FIXME: Remove dummy argument.
1099  Args.insert(Args.end(), ArgBegin, ArgEnd);
1100
1101  // FIXME: Find a cleaner way to force the driver into restricted modes. We
1102  // also want to force it to use clang.
1103  Args.push_back("-fsyntax-only");
1104
1105  // FIXME: We shouldn't have to pass in the path info.
1106  driver::Driver TheDriver("clang", llvm::sys::getHostTriple(),
1107                           "a.out", false, false, *Diags);
1108
1109  // Don't check that inputs exist, they have been remapped.
1110  TheDriver.setCheckInputsExist(false);
1111
1112  llvm::OwningPtr<driver::Compilation> C(
1113    TheDriver.BuildCompilation(Args.size(), Args.data()));
1114
1115  // We expect to get back exactly one command job, if we didn't something
1116  // failed.
1117  const driver::JobList &Jobs = C->getJobs();
1118  if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
1119    llvm::SmallString<256> Msg;
1120    llvm::raw_svector_ostream OS(Msg);
1121    C->PrintJob(OS, C->getJobs(), "; ", true);
1122    Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
1123    return 0;
1124  }
1125
1126  const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
1127  if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
1128    Diags->Report(diag::err_fe_expected_clang_command);
1129    return 0;
1130  }
1131
1132  const driver::ArgStringList &CCArgs = Cmd->getArguments();
1133  llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
1134  CompilerInvocation::CreateFromArgs(*CI,
1135                                     const_cast<const char **>(CCArgs.data()),
1136                                     const_cast<const char **>(CCArgs.data()) +
1137                                     CCArgs.size(),
1138                                     *Diags);
1139
1140  // Override any files that need remapping
1141  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1142    CI->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1143                                              RemappedFiles[I].second);
1144
1145  // Override the resources path.
1146  CI->getHeaderSearchOpts().ResourceDir = ResourceFilesPath;
1147
1148  CI->getFrontendOpts().DisableFree = true;
1149  return LoadFromCompilerInvocation(CI.take(), Diags, OnlyLocalDecls,
1150                                    CaptureDiagnostics, PrecompilePreamble,
1151                                    CompleteTranslationUnit);
1152}
1153
1154bool ASTUnit::Reparse(RemappedFile *RemappedFiles, unsigned NumRemappedFiles) {
1155  if (!Invocation.get())
1156    return true;
1157
1158  llvm::Timer *ReparsingTimer = 0;
1159  if (TimerGroup.get()) {
1160    ReparsingTimer = new llvm::Timer("Reparse", *TimerGroup);
1161    ReparsingTimer->startTimer();
1162    Timers.push_back(ReparsingTimer);
1163  }
1164
1165  // Remap files.
1166  Invocation->getPreprocessorOpts().clearRemappedFiles();
1167  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1168    Invocation->getPreprocessorOpts().addRemappedFile(RemappedFiles[I].first,
1169                                                      RemappedFiles[I].second);
1170
1171  // If we have a preamble file lying around, or if we might try to
1172  // build a precompiled preamble, do so now.
1173  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1174  if (!PreambleFile.empty() || PreambleRebuildCounter > 0)
1175    OverrideMainBuffer = getMainBufferWithPrecompiledPreamble();
1176
1177  // Clear out the diagnostics state.
1178  if (!OverrideMainBuffer)
1179    getDiagnostics().Reset();
1180
1181  // Parse the sources
1182  bool Result = Parse(OverrideMainBuffer);
1183  if (ReparsingTimer)
1184    ReparsingTimer->stopTimer();
1185  return Result;
1186}
1187
1188void ASTUnit::CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
1189                           RemappedFile *RemappedFiles,
1190                           unsigned NumRemappedFiles,
1191                           bool IncludeMacros,
1192                           bool IncludeCodePatterns,
1193                           CodeCompleteConsumer &Consumer,
1194                           Diagnostic &Diag, LangOptions &LangOpts,
1195                           SourceManager &SourceMgr, FileManager &FileMgr,
1196                   llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics) {
1197  if (!Invocation.get())
1198    return;
1199
1200  llvm::Timer *CompletionTimer = 0;
1201  if (TimerGroup.get()) {
1202    llvm::SmallString<128> TimerName;
1203    llvm::raw_svector_ostream TimerNameOut(TimerName);
1204    TimerNameOut << "Code completion @ " << File << ":" << Line << ":"
1205                 << Column;
1206    CompletionTimer = new llvm::Timer(TimerNameOut.str(), *TimerGroup);
1207    CompletionTimer->startTimer();
1208    Timers.push_back(CompletionTimer);
1209  }
1210
1211  CompilerInvocation CCInvocation(*Invocation);
1212  FrontendOptions &FrontendOpts = CCInvocation.getFrontendOpts();
1213  PreprocessorOptions &PreprocessorOpts = CCInvocation.getPreprocessorOpts();
1214
1215  FrontendOpts.ShowMacrosInCodeCompletion = IncludeMacros;
1216  FrontendOpts.ShowCodePatternsInCodeCompletion = IncludeCodePatterns;
1217  FrontendOpts.CodeCompletionAt.FileName = File;
1218  FrontendOpts.CodeCompletionAt.Line = Line;
1219  FrontendOpts.CodeCompletionAt.Column = Column;
1220
1221  // Turn on spell-checking when performing code completion. It leads
1222  // to better results.
1223  unsigned SpellChecking = CCInvocation.getLangOpts().SpellChecking;
1224  CCInvocation.getLangOpts().SpellChecking = 1;
1225
1226  // Set the language options appropriately.
1227  LangOpts = CCInvocation.getLangOpts();
1228
1229  CompilerInstance Clang;
1230  Clang.setInvocation(&CCInvocation);
1231  OriginalSourceFile = Clang.getFrontendOpts().Inputs[0].second;
1232
1233  // Set up diagnostics, capturing any diagnostics produced.
1234  Clang.setDiagnostics(&Diag);
1235  CaptureDroppedDiagnostics Capture(true,
1236                                    Clang.getDiagnostics(),
1237                                    StoredDiagnostics);
1238  Clang.setDiagnosticClient(Diag.getClient());
1239
1240  // Create the target instance.
1241  Clang.setTarget(TargetInfo::CreateTargetInfo(Clang.getDiagnostics(),
1242                                               Clang.getTargetOpts()));
1243  if (!Clang.hasTarget()) {
1244    Clang.takeDiagnosticClient();
1245    Clang.takeInvocation();
1246  }
1247
1248  // Inform the target of the language options.
1249  //
1250  // FIXME: We shouldn't need to do this, the target should be immutable once
1251  // created. This complexity should be lifted elsewhere.
1252  Clang.getTarget().setForcedLangOptions(Clang.getLangOpts());
1253
1254  assert(Clang.getFrontendOpts().Inputs.size() == 1 &&
1255         "Invocation must have exactly one source file!");
1256  assert(Clang.getFrontendOpts().Inputs[0].first != IK_AST &&
1257         "FIXME: AST inputs not yet supported here!");
1258  assert(Clang.getFrontendOpts().Inputs[0].first != IK_LLVM_IR &&
1259         "IR inputs not support here!");
1260
1261
1262  // Use the source and file managers that we were given.
1263  Clang.setFileManager(&FileMgr);
1264  Clang.setSourceManager(&SourceMgr);
1265
1266  // Remap files.
1267  PreprocessorOpts.clearRemappedFiles();
1268  PreprocessorOpts.RetainRemappedFileBuffers = true;
1269  for (unsigned I = 0; I != NumRemappedFiles; ++I)
1270    PreprocessorOpts.addRemappedFile(RemappedFiles[I].first,
1271                                     RemappedFiles[I].second);
1272
1273  // Use the code completion consumer we were given.
1274  Clang.setCodeCompletionConsumer(&Consumer);
1275
1276  // If we have a precompiled preamble, try to use it. We only allow
1277  // the use of the precompiled preamble if we're if the completion
1278  // point is within the main file, after the end of the precompiled
1279  // preamble.
1280  llvm::MemoryBuffer *OverrideMainBuffer = 0;
1281  if (!PreambleFile.empty()) {
1282    using llvm::sys::FileStatus;
1283    llvm::sys::PathWithStatus CompleteFilePath(File);
1284    llvm::sys::PathWithStatus MainPath(OriginalSourceFile);
1285    if (const FileStatus *CompleteFileStatus = CompleteFilePath.getFileStatus())
1286      if (const FileStatus *MainStatus = MainPath.getFileStatus())
1287        if (CompleteFileStatus->getUniqueID() == MainStatus->getUniqueID())
1288          OverrideMainBuffer = getMainBufferWithPrecompiledPreamble(false,
1289                                                                    Line);
1290  }
1291
1292  // If the main file has been overridden due to the use of a preamble,
1293  // make that override happen and introduce the preamble.
1294  if (OverrideMainBuffer) {
1295    PreprocessorOpts.addRemappedFile(OriginalSourceFile, OverrideMainBuffer);
1296    PreprocessorOpts.PrecompiledPreambleBytes.first = Preamble.size();
1297    PreprocessorOpts.PrecompiledPreambleBytes.second
1298                                                    = PreambleEndsAtStartOfLine;
1299    PreprocessorOpts.ImplicitPCHInclude = PreambleFile;
1300    PreprocessorOpts.DisablePCHValidation = true;
1301
1302    // The stored diagnostics have the old source manager. Copy them
1303    // to our output set of stored diagnostics, updating the source
1304    // manager to the one we were given.
1305    for (unsigned I = 0, N = this->StoredDiagnostics.size(); I != N; ++I) {
1306      StoredDiagnostics.push_back(this->StoredDiagnostics[I]);
1307      FullSourceLoc Loc(StoredDiagnostics[I].getLocation(), SourceMgr);
1308      StoredDiagnostics[I].setLocation(Loc);
1309    }
1310  }
1311
1312  llvm::OwningPtr<SyntaxOnlyAction> Act;
1313  Act.reset(new SyntaxOnlyAction);
1314  if (Act->BeginSourceFile(Clang, Clang.getFrontendOpts().Inputs[0].second,
1315                           Clang.getFrontendOpts().Inputs[0].first)) {
1316    Act->Execute();
1317    Act->EndSourceFile();
1318  }
1319
1320  if (CompletionTimer)
1321    CompletionTimer->stopTimer();
1322
1323  // Steal back our resources.
1324  delete OverrideMainBuffer;
1325  Clang.takeFileManager();
1326  Clang.takeSourceManager();
1327  Clang.takeInvocation();
1328  Clang.takeDiagnosticClient();
1329  Clang.takeCodeCompletionConsumer();
1330  CCInvocation.getLangOpts().SpellChecking = SpellChecking;
1331}
1332