Merge Dumper.cpp and AnalyzerWrappers.cpp into this file. Also, adjust the
[oota-llvm.git] / lib / Bytecode / Reader / ReaderWrappers.cpp
1 //===- ReaderWrappers.cpp - Parse bytecode from file or buffer  -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements loading and parsing a bytecode file and parsing a
11 // bytecode module from a given buffer.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Bytecode/Reader.h"
16 #include "ReaderInternals.h"
17 #include "llvm/Module.h"
18 #include "llvm/Instructions.h"
19 #include "Support/FileUtilities.h"
20 #include "Support/StringExtras.h"
21 #include "Config/unistd.h"
22 #include <cerrno>
23 using namespace llvm;
24
25 //===----------------------------------------------------------------------===//
26 // BytecodeFileReader - Read from an mmap'able file descriptor.
27 //
28
29 namespace {
30   /// BytecodeFileReader - parses a bytecode file from a file
31   ///
32   class BytecodeFileReader : public BytecodeParser {
33   private:
34     unsigned char *Buffer;
35     unsigned Length;
36
37     BytecodeFileReader(const BytecodeFileReader&); // Do not implement
38     void operator=(const BytecodeFileReader &BFR); // Do not implement
39
40   public:
41     BytecodeFileReader(const std::string &Filename);
42     ~BytecodeFileReader();
43   };
44 }
45
46 static std::string ErrnoMessage (int savedErrNum, std::string descr) {
47    return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
48 }
49
50 BytecodeFileReader::BytecodeFileReader(const std::string &Filename) {
51   Buffer = (unsigned char*)ReadFileIntoAddressSpace(Filename, Length);
52   if (Buffer == 0)
53     throw "Error reading file '" + Filename + "'.";
54
55   try {
56     // Parse the bytecode we mmapped in
57     ParseBytecode(Buffer, Length, Filename);
58   } catch (...) {
59     UnmapFileFromAddressSpace(Buffer, Length);
60     throw;
61   }
62 }
63
64 BytecodeFileReader::~BytecodeFileReader() {
65   // Unmmap the bytecode...
66   UnmapFileFromAddressSpace(Buffer, Length);
67 }
68
69 //===----------------------------------------------------------------------===//
70 // BytecodeBufferReader - Read from a memory buffer
71 //
72
73 namespace {
74   /// BytecodeBufferReader - parses a bytecode file from a buffer
75   ///
76   class BytecodeBufferReader : public BytecodeParser {
77   private:
78     const unsigned char *Buffer;
79     bool MustDelete;
80
81     BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
82     void operator=(const BytecodeBufferReader &BFR);   // Do not implement
83
84   public:
85     BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
86                          const std::string &ModuleID);
87     ~BytecodeBufferReader();
88
89   };
90 }
91
92 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
93                                            unsigned Length,
94                                            const std::string &ModuleID)
95 {
96   // If not aligned, allocate a new buffer to hold the bytecode...
97   const unsigned char *ParseBegin = 0;
98   if ((intptr_t)Buf & 3) {
99     Buffer = new unsigned char[Length+4];
100     unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
101     ParseBegin = Buffer + Offset;
102     memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
103     MustDelete = true;
104   } else {
105     // If we don't need to copy it over, just use the caller's copy
106     ParseBegin = Buffer = Buf;
107     MustDelete = false;
108   }
109   try {
110     ParseBytecode(ParseBegin, Length, ModuleID);
111   } catch (...) {
112     if (MustDelete) delete [] Buffer;
113     throw;
114   }
115 }
116
117 BytecodeBufferReader::~BytecodeBufferReader() {
118   if (MustDelete) delete [] Buffer;
119 }
120
121 //===----------------------------------------------------------------------===//
122 //  BytecodeStdinReader - Read bytecode from Standard Input
123 //
124
125 namespace {
126   /// BytecodeStdinReader - parses a bytecode file from stdin
127   /// 
128   class BytecodeStdinReader : public BytecodeParser {
129   private:
130     std::vector<unsigned char> FileData;
131     unsigned char *FileBuf;
132
133     BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
134     void operator=(const BytecodeStdinReader &BFR);  // Do not implement
135
136   public:
137     BytecodeStdinReader();
138   };
139 }
140
141 BytecodeStdinReader::BytecodeStdinReader() {
142   int BlockSize;
143   unsigned char Buffer[4096*4];
144
145   // Read in all of the data from stdin, we cannot mmap stdin...
146   while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
147     if (BlockSize == -1)
148       throw ErrnoMessage(errno, "read from standard input");
149     
150     FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
151   }
152
153   if (FileData.empty())
154     throw std::string("Standard Input empty!");
155
156   FileBuf = &FileData[0];
157   ParseBytecode(FileBuf, FileData.size(), "<stdin>");
158 }
159
160 //===----------------------------------------------------------------------===//
161 //  Varargs transmogrification code...
162 //
163
164 // CheckVarargs - This is used to automatically translate old-style varargs to
165 // new style varargs for backwards compatibility.
166 static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
167   Module *M = MP->getModule();
168   
169   // Check to see if va_start takes arguments...
170   Function *F = M->getNamedFunction("llvm.va_start");
171   if (F == 0) return MP;  // No varargs use, just return.
172
173   if (F->getFunctionType()->getNumParams() == 0)
174     return MP;  // Modern varargs processing, just return.
175
176   // If we get to this point, we know that we have an old-style module.
177   // Materialize the whole thing to perform the rewriting.
178   MP->materializeModule();
179
180   // If the user is making use of obsolete varargs intrinsics, adjust them for
181   // the user.
182   if (Function *F = M->getNamedFunction("llvm.va_start")) {
183     assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
184         
185     const Type *RetTy = F->getFunctionType()->getParamType(0);
186     RetTy = cast<PointerType>(RetTy)->getElementType();
187     Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
188         
189     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
190       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
191         Value *V = new CallInst(NF, "", CI);
192         new StoreInst(V, CI->getOperand(1), CI);
193         CI->getParent()->getInstList().erase(CI);
194       }
195     F->setName("");
196   }
197
198   if (Function *F = M->getNamedFunction("llvm.va_end")) {
199     assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
200     const Type *ArgTy = F->getFunctionType()->getParamType(0);
201     ArgTy = cast<PointerType>(ArgTy)->getElementType();
202     Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
203                                                   ArgTy, 0);
204         
205     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
206       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
207         Value *V = new LoadInst(CI->getOperand(1), "", CI);
208         new CallInst(NF, V, "", CI);
209         CI->getParent()->getInstList().erase(CI);
210       }
211     F->setName("");
212   }
213       
214   if (Function *F = M->getNamedFunction("llvm.va_copy")) {
215     assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
216     const Type *ArgTy = F->getFunctionType()->getParamType(0);
217     ArgTy = cast<PointerType>(ArgTy)->getElementType();
218     Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
219                                                   ArgTy, 0);
220         
221     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
222       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
223         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
224         new StoreInst(V, CI->getOperand(1), CI);
225         CI->getParent()->getInstList().erase(CI);
226       }
227     F->setName("");
228   }
229   return MP;
230 }
231
232 //===----------------------------------------------------------------------===//
233 // Wrapper functions
234 //===----------------------------------------------------------------------===//
235
236 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
237 /// buffer
238 ModuleProvider* 
239 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
240                                       unsigned Length,
241                                       const std::string &ModuleID) {
242   return CheckVarargs(new BytecodeBufferReader(Buffer, Length, ModuleID));
243 }
244
245 /// ParseBytecodeBuffer - Parse a given bytecode buffer
246 ///
247 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
248                                   const std::string &ModuleID,
249                                   std::string *ErrorStr){
250   try {
251     std::auto_ptr<ModuleProvider>
252       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
253     return AMP->releaseModule();
254   } catch (std::string &err) {
255     if (ErrorStr) *ErrorStr = err;
256     return 0;
257   }
258 }
259
260 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
261 ///
262 ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename) {
263   if (Filename != std::string("-"))        // Read from a file...
264     return CheckVarargs(new BytecodeFileReader(Filename));
265   else                                     // Read from stdin
266     return CheckVarargs(new BytecodeStdinReader());
267 }
268
269 /// ParseBytecodeFile - Parse the given bytecode file
270 ///
271 Module *llvm::ParseBytecodeFile(const std::string &Filename,
272                                 std::string *ErrorStr) {
273   try {
274     std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
275     return AMP->releaseModule();
276   } catch (std::string &err) {
277     if (ErrorStr) *ErrorStr = err;
278     return 0;
279   }
280 }
281