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 10 #include "clang/CodeGen/ObjectFilePCHContainerOperations.h" 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" 16 #include "clang/AST/RecursiveASTVisitor.h" 17 #include "clang/Basic/Diagnostic.h" 18 #include "clang/Basic/TargetInfo.h" 19 #include "clang/CodeGen/BackendUtil.h" 20 #include "clang/Frontend/CodeGenOptions.h" 21 #include "clang/Serialization/ASTWriter.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 ModuleContainerGenerator : 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 ModuleContainerGenerator( 55 DiagnosticsEngine &diags, 56 const HeaderSearchOptions &HSO, const PreprocessorOptions &PPO, 57 const TargetOptions &TO, const LangOptions &LO, 58 const std::string &MainFileName, const std::string &OutputFileName, 59 raw_pwrite_stream *OS, std::shared_ptr<PCHBuffer> Buffer) 60 : Diags(diags), HeaderSearchOpts(HSO), PreprocessorOpts(PPO), 61 TargetOpts(TO), LangOpts(LO), OS(OS), 62 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 ~ModuleContainerGenerator() {} 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, 80 *M, 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 // Initialize the backend if we haven't done so already. 102 LLVMInitializeAllTargetInfos(); 103 LLVMInitializeAllTargets(); 104 LLVMInitializeAllAsmPrinters(); 105 LLVMInitializeAllTargetMCs(); 106 107 // Ensure the target exists. 108 std::string Error; 109 auto Triple = Ctx.getTargetInfo().getTriple(); 110 if (!llvm::TargetRegistry::lookupTarget(Triple.getTriple(), Error)) 111 llvm::report_fatal_error(Error); 112 113 // Emit the serialized Clang AST into its own section. 114 assert(Buffer->IsComplete && "serialization did not complete"); 115 auto &SerializedAST = Buffer->Data; 116 auto Size = SerializedAST.size(); 117 auto Int8Ty = llvm::Type::getInt8Ty(*VMContext); 118 auto *Ty = llvm::ArrayType::get(Int8Ty, Size); 119 auto *Data = llvm::ConstantDataArray:: 120 getString(*VMContext, StringRef(SerializedAST.data(), Size), 121 /*AddNull=*/false); 122 auto *ASTSym = new llvm::GlobalVariable( 123 *M, Ty, /*constant*/ true, llvm::GlobalVariable::InternalLinkage, Data, 124 "__clang_ast"); 125 // The on-disk hashtable needs to be aligned. 126 ASTSym->setAlignment(8); 127 128 // Mach-O also needs a segment name. 129 if (Triple.isOSBinFormatMachO()) 130 ASTSym->setSection("__CLANG,__clangast"); 131 // COFF has an eight character length limit. 132 else if (Triple.isOSBinFormatCOFF()) 133 ASTSym->setSection("clangast"); 134 else 135 ASTSym->setSection("__clangast"); 136 137 DEBUG({ 138 // Print the IR for the PCH container to the debug output. 139 llvm::SmallString<0> Buffer; 140 llvm::raw_svector_ostream OS(Buffer); 141 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, 142 Ctx.getTargetInfo().getTargetDescription(), 143 M.get(), BackendAction::Backend_EmitLL, &OS); 144 OS.flush(); 145 llvm::dbgs()<<Buffer; 146 }); 147 148 // Use the LLVM backend to emit the pch container. 149 clang::EmitBackendOutput(Diags, CodeGenOpts, TargetOpts, LangOpts, 150 Ctx.getTargetInfo().getTargetDescription(), 151 M.get(), BackendAction::Backend_EmitObj, OS); 152 153 // Make sure the pch container hits disk. 154 OS->flush(); 155 156 // Free the memory for the temporary buffer. 157 llvm::SmallVector<char, 0> Empty; 158 SerializedAST = std::move(Empty); 159 } 160 }; 161 } 162 163 std::unique_ptr<ASTConsumer> 164 ObjectFilePCHContainerOperations::CreatePCHContainerGenerator( 165 DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO, 166 const PreprocessorOptions &PPO, const TargetOptions &TO, 167 const LangOptions &LO, const std::string &MainFileName, 168 const std::string &OutputFileName, llvm::raw_pwrite_stream *OS, 169 std::shared_ptr<PCHBuffer> Buffer) const { 170 return llvm::make_unique<ModuleContainerGenerator> 171 (Diags, HSO, PPO, TO, LO, MainFileName, OutputFileName, OS, Buffer); 172 } 173 174 void ObjectFilePCHContainerOperations::ExtractPCH( 175 llvm::MemoryBufferRef Buffer, llvm::BitstreamReader &StreamFile) const { 176 if (auto OF = llvm::object::ObjectFile::createObjectFile(Buffer)) { 177 auto *Obj = OF.get().get(); 178 bool IsCOFF = isa<llvm::object::COFFObjectFile>(Obj); 179 // Find the clang AST section in the container. 180 for (auto &Section : OF->get()->sections()) { 181 StringRef Name; 182 Section.getName(Name); 183 if ((!IsCOFF && Name == "__clangast") || 184 ( IsCOFF && Name == "clangast")) { 185 StringRef Buf; 186 Section.getContents(Buf); 187 StreamFile.init((const unsigned char *)Buf.begin(), 188 (const unsigned char *)Buf.end()); 189 return; 190 } 191 } 192 } 193 194 // As a fallback, treat the buffer as a raw AST. 195 StreamFile.init((const unsigned char *)Buffer.getBufferStart(), 196 (const unsigned char *)Buffer.getBufferEnd()); 197 return; 198 } 199