xref: /llvm-project/llvm/lib/Transforms/IPO/EmbedBitcodePass.cpp (revision a67208e1c697649ce432e6497f56a93675273dd8)
1 //===- EmbedBitcodePass.cpp - Pass that embeds the bitcode into a global---===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Transforms/IPO/EmbedBitcodePass.h"
10 #include "llvm/Bitcode/BitcodeWriter.h"
11 #include "llvm/Bitcode/BitcodeWriterPass.h"
12 #include "llvm/IR/Constants.h"
13 #include "llvm/IR/PassManager.h"
14 #include "llvm/InitializePasses.h"
15 #include "llvm/Pass.h"
16 #include "llvm/Passes/PassBuilder.h"
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/TargetParser/Triple.h"
20 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Transforms/Utils/ModuleUtils.h"
23 
24 using namespace llvm;
25 
26 PreservedAnalyses EmbedBitcodePass::run(Module &M, ModuleAnalysisManager &AM) {
27   if (M.getGlobalVariable("llvm.embedded.module", /*AllowInternal=*/true))
28     report_fatal_error("Can only embed the module once",
29                        /*gen_crash_diag=*/false);
30 
31   Triple T(M.getTargetTriple());
32   if (T.getObjectFormat() != Triple::ELF)
33     report_fatal_error(
34         "EmbedBitcode pass currently only supports ELF object format",
35         /*gen_crash_diag=*/false);
36 
37   std::unique_ptr<Module> NewModule = CloneModule(M);
38   MPM.run(*NewModule, AM);
39 
40   std::string Data;
41   raw_string_ostream OS(Data);
42   if (IsThinLTO)
43     ThinLTOBitcodeWriterPass(OS, /*ThinLinkOS=*/nullptr).run(*NewModule, AM);
44   else
45     BitcodeWriterPass(OS, /*ShouldPreserveUseListOrder=*/false, EmitLTOSummary)
46         .run(*NewModule, AM);
47 
48   embedBufferInModule(M, MemoryBufferRef(Data, "ModuleData"), ".llvm.lto");
49 
50   return PreservedAnalyses::all();
51 }
52