clang  3.7.0
ObjectFilePCHContainerOperations.cpp
Go to the documentation of this file.
1 //===--- ObjectFilePCHContainerOperations.cpp -----------------------------===//
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 
11 #include "CGDebugInfo.h"
12 #include "CodeGenModule.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/Expr.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/TargetInfo.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Bitcode/BitstreamReader.h"
24 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Object/COFF.h"
30 #include "llvm/Object/ObjectFile.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include <memory>
33 using namespace clang;
34 
35 #define DEBUG_TYPE "pchcontainer"
36 
37 namespace {
38 class PCHContainerGenerator : public ASTConsumer {
39  DiagnosticsEngine &Diags;
40  const std::string MainFileName;
41  ASTContext *Ctx;
42  const HeaderSearchOptions &HeaderSearchOpts;
43  const PreprocessorOptions &PreprocessorOpts;
44  CodeGenOptions CodeGenOpts;
45  const TargetOptions TargetOpts;
46  const LangOptions LangOpts;
47  std::unique_ptr<llvm::LLVMContext> VMContext;
48  std::unique_ptr<llvm::Module> M;
49  std::unique_ptr<CodeGen::CodeGenModule> Builder;
50  raw_pwrite_stream *OS;
51  std::shared_ptr<PCHBuffer> Buffer;
52 
53 public:
54  PCHContainerGenerator(DiagnosticsEngine &diags,
55  const HeaderSearchOptions &HSO,
56  const PreprocessorOptions &PPO, const TargetOptions &TO,
57  const LangOptions &LO, const std::string &MainFileName,
58  const std::string &OutputFileName,
59  raw_pwrite_stream *OS,
60  std::shared_ptr<PCHBuffer> Buffer)
61  : Diags(diags), HeaderSearchOpts(HSO), PreprocessorOpts(PPO),
62  TargetOpts(TO), LangOpts(LO), OS(OS), Buffer(Buffer) {
63  // The debug info output isn't affected by CodeModel and
64  // ThreadModel, but the backend expects them to be nonempty.
65  CodeGenOpts.CodeModel = "default";
66  CodeGenOpts.ThreadModel = "single";
67  CodeGenOpts.setDebugInfo(CodeGenOptions::FullDebugInfo);
68  CodeGenOpts.SplitDwarfFile = OutputFileName;
69  }
70 
71  virtual ~PCHContainerGenerator() {}
72 
73  void Initialize(ASTContext &Context) override {
74  Ctx = &Context;
75  VMContext.reset(new llvm::LLVMContext());
76  M.reset(new llvm::Module(MainFileName, *VMContext));
77  M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
78  Builder.reset(new CodeGen::CodeGenModule(*Ctx, HeaderSearchOpts,
79  PreprocessorOpts, CodeGenOpts, *M,
80  M->getDataLayout(), Diags));
81  }
82 
83  /// Emit a container holding the serialized AST.
84  void HandleTranslationUnit(ASTContext &Ctx) override {
85  assert(M && VMContext && Builder);
86  // Delete these on function exit.
87  std::unique_ptr<llvm::LLVMContext> VMContext = std::move(this->VMContext);
88  std::unique_ptr<llvm::Module> M = std::move(this->M);
89  std::unique_ptr<CodeGen::CodeGenModule> Builder = std::move(this->Builder);
90 
91  if (Diags.hasErrorOccurred())
92  return;
93 
94  M->setTargetTriple(Ctx.getTargetInfo().getTriple().getTriple());
95  M->setDataLayout(Ctx.getTargetInfo().getTargetDescription());
96 
97  // Finalize the Builder.
98  if (Builder)
99  Builder->Release();
100 
101  // Ensure the target exists.
102  std::string Error;
103  auto Triple = Ctx.getTargetInfo().getTriple();
104  if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error))
105  llvm::report_fatal_error(Error);
106 
107  // Emit the serialized Clang AST into its own section.
108  assert(Buffer->IsComplete && "serialization did not complete");
109  auto &SerializedAST = Buffer->Data;
110  auto Size = SerializedAST.size();
111  auto Int8Ty = llvm::Type::getInt8Ty(*VMContext);
112  auto *Ty = llvm::ArrayType::get(Int8Ty, Size);
113  auto *Data = llvm::ConstantDataArray::getString(
114  *VMContext, StringRef(SerializedAST.data(), Size),
115  /*AddNull=*/false);
116  auto *ASTSym = new llvm::GlobalVariable(
117  *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data,
118  "__clang_ast");
119  // The on-disk hashtable needs to be aligned.
120  ASTSym->setAlignment(8);
121 
122  // Mach-O also needs a segment name.
123  if (Triple.isOSBinFormatMachO())
124  ASTSym->setSection("__CLANG,__clangast");
125  // COFF has an eight character length limit.
126  else if (Triple.isOSBinFormatCOFF())
127  ASTSym->setSection("clangast");
128  else
129  ASTSym->setSection("__clangast");
130 
131  DEBUG({
132  // Print the IR for the PCH container to the debug output.
133  llvm::SmallString<0> Buffer;
134  llvm::raw_svector_ostream OS(Buffer);
135  clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
137  M.get(), BackendAction::Backend_EmitLL, &OS);
138  OS.flush();
139  llvm::dbgs() << Buffer;
140  });
141 
142  // Use the LLVM backend to emit the pch container.
143  clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts,
145  M.get(), BackendAction::Backend_EmitObj, OS);
146 
147  // Make sure the pch container hits disk.
148  OS->flush();
149 
150  // Free the memory for the temporary buffer.
152  SerializedAST = std::move(Empty);
153  }
154 };
155 
156 } // namespace
157 
158 std::unique_ptr<ASTConsumer>
159 ObjectFilePCHContainerWriter::CreatePCHContainerGenerator(
160  DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
161  const PreprocessorOptions &PPO, const TargetOptions &TO,
162  const LangOptions &LO, const std::string &MainFileName,
163  const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
164  std::shared_ptr<PCHBuffer> Buffer) const {
165  return llvm::make_unique<PCHContainerGenerator>(
166  Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer);
167 }
168 
169 void ObjectFilePCHContainerReader::ExtractPCH(
170  llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const {
171  if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) {
172  auto *Obj = OF.get().get();
173  bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj);
174  // Find the clang AST section in the container.
175  for (auto &Section : OF->get()->sections()) {
176  StringRef Name;
177  Section.getName(Name);
178  if ((!IsCOFF && Name == "__clangast") ||
179  ( IsCOFF && Name == "clangast")) {
180  StringRef Buf;
181  Section.getContents(Buf);
182  StreamFile.init((const unsigned char *)Buf.begin(),
183  (const unsigned char *)Buf.end());
184  return;
185  }
186  }
187  }
188 
189  // As a fallback, treat the buffer as a raw AST.
190  StreamFile.init((const unsigned char *)Buffer.getBufferStart(),
191  (const unsigned char *)Buffer.getBufferEnd());
192  return;
193 }
Defines the clang::ASTContext interface.
Emit human-readable LLVM assembly.
Definition: BackendUtil.h:28
Options for controlling the target.
Definition: TargetOptions.h:24
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:89
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
void EmitBackendOutput(DiagnosticsEngine &Diags, const CodeGenOptions &CGOpts, const TargetOptions &TOpts, const LangOptions &LOpts, StringRef TDesc, llvm::Module *M, BackendAction Action, raw_pwrite_stream *OS)
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:518
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:135
ASTContext * Context
Emit native object files.
Definition: BackendUtil.h:31
const char * getTargetDescription() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Defines the Diagnostic-related interfaces.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
BoundNodesTreeBuilder *const Builder
Defines the clang::TargetInfo interface.
Generate complete debug info.