clang API Documentation

GeneratePCH.cpp
Go to the documentation of this file.
00001 //===--- GeneratePCH.cpp - Sema Consumer for PCH Generation -----*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the PCHGenerator, which as a SemaConsumer that generates
00011 //  a PCH file.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "clang/Serialization/ASTWriter.h"
00016 #include "clang/AST/ASTConsumer.h"
00017 #include "clang/AST/ASTContext.h"
00018 #include "clang/Basic/FileManager.h"
00019 #include "clang/Lex/Preprocessor.h"
00020 #include "clang/Sema/SemaConsumer.h"
00021 #include "llvm/Bitcode/BitstreamWriter.h"
00022 #include "llvm/Support/raw_ostream.h"
00023 #include <string>
00024 
00025 using namespace clang;
00026 
00027 PCHGenerator::PCHGenerator(const Preprocessor &PP,
00028                            StringRef OutputFile,
00029                            clang::Module *Module,
00030                            StringRef isysroot,
00031                            raw_ostream *OS, bool AllowASTWithErrors)
00032   : PP(PP), OutputFile(OutputFile), Module(Module), 
00033     isysroot(isysroot.str()), Out(OS), 
00034     SemaPtr(nullptr), Stream(Buffer), Writer(Stream),
00035     AllowASTWithErrors(AllowASTWithErrors),
00036     HasEmittedPCH(false) {
00037 }
00038 
00039 PCHGenerator::~PCHGenerator() {
00040 }
00041 
00042 void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) {
00043   // Don't create a PCH if there were fatal failures during module loading.
00044   if (PP.getModuleLoader().HadFatalFailure)
00045     return;
00046 
00047   bool hasErrors = PP.getDiagnostics().hasErrorOccurred();
00048   if (hasErrors && !AllowASTWithErrors)
00049     return;
00050   
00051   // Emit the PCH file
00052   assert(SemaPtr && "No Sema?");
00053   Writer.WriteAST(*SemaPtr, OutputFile, Module, isysroot, hasErrors);
00054 
00055   // Write the generated bitstream to "Out".
00056   Out->write((char *)&Buffer.front(), Buffer.size());
00057 
00058   // Make sure it hits disk now.
00059   Out->flush();
00060 
00061   // Free up some memory, in case the process is kept alive.
00062   Buffer.clear();
00063 
00064   HasEmittedPCH = true;
00065 }
00066 
00067 ASTMutationListener *PCHGenerator::GetASTMutationListener() {
00068   return &Writer;
00069 }
00070 
00071 ASTDeserializationListener *PCHGenerator::GetASTDeserializationListener() {
00072   return &Writer;
00073 }