1 //===--- GeneratePCH.cpp - Sema Consumer for PCH Generation -----*- C++ -*-===//
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 //  This file defines the PCHGenerator, which as a SemaConsumer that generates
11 //  a PCH file.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Sema/SemaConsumer.h"
18 #include "clang/Serialization/ASTWriter.h"
19 #include "llvm/Bitcode/BitstreamWriter.h"
20 
21 using namespace clang;
22 
23 PCHGenerator::PCHGenerator(
24   const Preprocessor &PP, StringRef OutputFile,
25   clang::Module *Module, StringRef isysroot,
26   std::shared_ptr<PCHBuffer> Buffer,
27   ArrayRef<llvm::IntrusiveRefCntPtr<ModuleFileExtension>> Extensions,
28   bool AllowASTWithErrors, bool IncludeTimestamps)
29     : PP(PP), OutputFile(OutputFile), Module(Module), isysroot(isysroot.str()),
30       SemaPtr(nullptr), Buffer(Buffer), Stream(Buffer->Data),
31       Writer(Stream, Extensions, IncludeTimestamps),
32       AllowASTWithErrors(AllowASTWithErrors) {
33   Buffer->IsComplete = false;
34 }
35 
36 PCHGenerator::~PCHGenerator() {
37 }
38 
39 void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
40   // Don't create a PCH if there were fatal failures during module loading.
41   if (PP.getModuleLoader().HadFatalFailure)
42     return;
43 
44   bool hasErrors = PP.getDiagnostics().hasErrorOccurred();
45   if (hasErrors && !AllowASTWithErrors)
46     return;
47 
48   // Emit the PCH file to the Buffer.
49   assert(SemaPtr && "No Sema?");
50   Buffer->Signature =
51       Writer.WriteAST(*SemaPtr, OutputFile, Module, isysroot,
52                       // For serialization we are lenient if the errors were
53                       // only warn-as-error kind.
54                       PP.getDiagnostics().hasUncompilableErrorOccurred());
55 
56   Buffer->IsComplete = true;
57 }
58 
59 ASTMutationListener *PCHGenerator::GetASTMutationListener() {
60   return &Writer;
61 }
62 
63 ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() {
64   return &Writer;
65 }
66