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 "llvm/Support/raw_ostream.h" 23 #include <string> 24 25 using namespace clang; 26 27 PCHGenerator::PCHGenerator(const Preprocessor &PP, StringRef OutputFile, 28 clang::Module *Module, StringRef isysroot, 29 std::shared_ptr<PCHBuffer> Buffer, 30 bool AllowASTWithErrors) 31 : PP(PP), OutputFile(OutputFile), Module(Module), isysroot(isysroot.str()), 32 SemaPtr(nullptr), Buffer(Buffer), Stream(Buffer->Data), Writer(Stream), 33 AllowASTWithErrors(AllowASTWithErrors) { 34 Buffer->IsComplete = false; 35 } 36 37 PCHGenerator::~PCHGenerator() { 38 } 39 40 void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { 41 // Don't create a PCH if there were fatal failures during module loading. 42 if (PP.getModuleLoader().HadFatalFailure) 43 return; 44 45 bool hasErrors = PP.getDiagnostics().hasErrorOccurred(); 46 if (hasErrors && !AllowASTWithErrors) 47 return; 48 49 // Emit the PCH file to the Buffer. 50 assert(SemaPtr && "No Sema?"); 51 Writer.WriteAST(*SemaPtr, OutputFile, Module, isysroot, hasErrors); 52 53 Buffer->IsComplete = true; 54 } 55 56 ASTMutationListener *PCHGenerator::GetASTMutationListener() { 57 return &Writer; 58 } 59 60 ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() { 61 return &Writer; 62 } 63