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