Douglas Gregor | c34897d | 2009-04-09 22:27:44 +0000 | [diff] [blame] | 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 | // ASTConsume that generates a PCH file. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "clang/Frontend/PCHWriter.h" |
| 16 | #include "clang/AST/ASTContext.h" |
| 17 | #include "clang/AST/ASTConsumer.h" |
| 18 | #include "llvm/Bitcode/BitstreamWriter.h" |
| 19 | #include "llvm/System/Path.h" |
| 20 | #include "llvm/Support/Compiler.h" |
| 21 | #include "llvm/Support/raw_ostream.h" |
| 22 | #include "llvm/Support/Streams.h" |
| 23 | #include <string> |
| 24 | |
| 25 | using namespace clang; |
| 26 | using namespace llvm; |
| 27 | |
| 28 | namespace { |
| 29 | class VISIBILITY_HIDDEN PCHGenerator : public ASTConsumer { |
| 30 | Diagnostic &Diags; |
| 31 | std::string OutFile; |
| 32 | |
| 33 | public: |
| 34 | explicit PCHGenerator(Diagnostic &Diags, const std::string &OutFile) |
| 35 | : Diags(Diags), OutFile(OutFile) { } |
| 36 | |
| 37 | virtual void HandleTranslationUnit(ASTContext &Ctx); |
| 38 | }; |
| 39 | } |
| 40 | |
| 41 | void PCHGenerator::HandleTranslationUnit(ASTContext &Ctx) { |
| 42 | if (Diags.hasErrorOccurred()) |
| 43 | return; |
| 44 | |
| 45 | // Write the PCH contents into a buffer |
| 46 | std::vector<unsigned char> Buffer; |
| 47 | BitstreamWriter Stream(Buffer); |
| 48 | PCHWriter Writer(Stream); |
| 49 | |
| 50 | // Emit the PCH file |
| 51 | Writer.WritePCH(Ctx); |
| 52 | |
| 53 | // Open up the PCH file. |
| 54 | std::string ErrMsg; |
| 55 | llvm::raw_fd_ostream Out(OutFile.c_str(), true, ErrMsg); |
| 56 | |
| 57 | if (!ErrMsg.empty()) { |
| 58 | llvm::errs() << "PCH error: " << ErrMsg << "\n"; |
| 59 | return; |
| 60 | } |
| 61 | |
| 62 | // Write the generated bitstream to "Out". |
| 63 | Out.write((char *)&Buffer.front(), Buffer.size()); |
| 64 | |
| 65 | // Make sure it hits disk now. |
| 66 | Out.flush(); |
| 67 | } |
| 68 | |
| 69 | namespace clang { |
| 70 | |
| 71 | ASTConsumer *CreatePCHGenerator(Diagnostic &Diags, |
| 72 | const LangOptions &Features, |
| 73 | const std::string& InFile, |
| 74 | const std::string& OutFile) { |
| 75 | return new PCHGenerator(Diags, OutFile); |
| 76 | } |
| 77 | |
| 78 | } |