1 #include "llvm/Bitcode/ReaderWriter.h"
2 #include "llvm/IR/Function.h"
3 #include "llvm/IR/GlobalVariable.h"
4 #include "llvm/IR/LLVMContext.h"
5 #include "llvm/IR/Module.h"
6 #include "llvm/Support/CommandLine.h"
7 #include "llvm/Support/ManagedStatic.h"
8 #include "llvm/Support/MemoryBuffer.h"
9 #include "llvm/Support/FileSystem.h"
10 #include "llvm/Support/raw_ostream.h"
11 #include "llvm/Support/ErrorOr.h"
12 #include "llvm/Support/ToolOutputFile.h"
13 #include "llvm/Config/llvm-config.h"
14 
15 #include <system_error>
16 
17 using namespace llvm;
18 
19 static cl::opt<std::string>
20 InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
21 
22 static cl::opt<std::string>
23 OutputFilename("o", cl::desc("Output filename"),
24                cl::value_desc("filename"));
25 
26 int main(int argc, char **argv) {
27   LLVMContext &Context = getGlobalContext();
28   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
29 
30   cl::ParseCommandLineOptions(argc, argv, "libclc builtin preparation tool\n");
31 
32   std::string ErrorMessage;
33   Module *M = nullptr;
34 
35   {
36     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
37       MemoryBuffer::getFile(InputFilename);
38     std::unique_ptr<MemoryBuffer> &BufferPtr = BufferOrErr.get();
39     if (std::error_code  ec = BufferOrErr.getError())
40       ErrorMessage = ec.message();
41     else {
42       ErrorOr<std::unique_ptr<Module>> ModuleOrErr =
43           parseBitcodeFile(BufferPtr.get()->getMemBufferRef(), Context);
44       if (std::error_code ec = ModuleOrErr.getError())
45         ErrorMessage = ec.message();
46 
47       M = ModuleOrErr.get().release();
48     }
49   }
50 
51   if (!M) {
52     errs() << argv[0] << ": ";
53     if (ErrorMessage.size())
54       errs() << ErrorMessage << "\n";
55     else
56       errs() << "bitcode didn't read correctly.\n";
57     return 1;
58   }
59 
60   // Set linkage of every external definition to linkonce_odr.
61   for (Module::iterator i = M->begin(), e = M->end(); i != e; ++i) {
62     if (!i->isDeclaration() && i->getLinkage() == GlobalValue::ExternalLinkage)
63       i->setLinkage(GlobalValue::LinkOnceODRLinkage);
64   }
65 
66   for (Module::global_iterator i = M->global_begin(), e = M->global_end();
67        i != e; ++i) {
68     if (!i->isDeclaration() && i->getLinkage() == GlobalValue::ExternalLinkage)
69       i->setLinkage(GlobalValue::LinkOnceODRLinkage);
70   }
71 
72   if (OutputFilename.empty()) {
73     errs() << "no output file\n";
74     return 1;
75   }
76 
77   std::error_code EC;
78   std::unique_ptr<tool_output_file> Out
79   (new tool_output_file(OutputFilename, EC, sys::fs::F_None));
80   if (EC) {
81     errs() << EC.message() << '\n';
82     exit(1);
83   }
84 
85   WriteBitcodeToFile(M, Out->os());
86 
87   // Declare success.
88   Out->keep();
89   return 0;
90 }
91 
92