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