1 //===--- GeneratePCH.cpp - AST 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 CreatePCHGenerate function, which creates an 11 // ASTConsumer that generates a PCH file. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Frontend/ASTConsumers.h" 16 #include "clang/Serialization/ASTWriter.h" 17 #include "clang/Sema/SemaConsumer.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/ASTConsumer.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/Basic/FileManager.h" 22 #include "clang/Basic/FileSystemStatCache.h" 23 #include "llvm/Bitcode/BitstreamWriter.h" 24 #include "llvm/Support/raw_ostream.h" 25 #include <string> 26 27 using namespace clang; 28 29 PCHGenerator::PCHGenerator(const Preprocessor &PP, 30 StringRef OutputFile, 31 bool IsModule, 32 StringRef isysroot, 33 raw_ostream *OS) 34 : PP(PP), OutputFile(OutputFile), IsModule(IsModule), 35 isysroot(isysroot.str()), Out(OS), 36 SemaPtr(0), StatCalls(0), Stream(Buffer), Writer(Stream) { 37 // Install a stat() listener to keep track of all of the stat() 38 // calls. 39 StatCalls = new MemorizeStatCalls(); 40 PP.getFileManager().addStatCache(StatCalls, /*AtBeginning=*/false); 41 } 42 43 PCHGenerator::~PCHGenerator() { 44 } 45 46 void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { 47 if (PP.getDiagnostics().hasErrorOccurred()) 48 return; 49 50 // Set up the serialization listener. 51 Writer.SetSerializationListener(GetASTSerializationListener()); 52 53 // Emit the PCH file 54 assert(SemaPtr && "No Sema?"); 55 Writer.WriteAST(*SemaPtr, StatCalls, OutputFile, IsModule, isysroot); 56 57 // Write the generated bitstream to "Out". 58 Out->write((char *)&Buffer.front(), Buffer.size()); 59 60 // Make sure it hits disk now. 61 Out->flush(); 62 63 // Free up some memory, in case the process is kept alive. 64 Buffer.clear(); 65 } 66 67 ASTMutationListener *PCHGenerator::GetASTMutationListener() { 68 return &Writer; 69 } 70 71 ASTSerializationListener *PCHGenerator::GetASTSerializationListener() { 72 return 0; 73 } 74 75 ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() { 76 return &Writer; 77 } 78