For PR351:
[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/Analyzer.h"
16 #include "llvm/Bytecode/Reader.h"
17 #include "Reader.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Config/unistd.h"
22 #include "llvm/System/MappedFile.h"
23 #include <cerrno>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // BytecodeFileReader - Read from an mmap'able file descriptor.
28 //
29
30 namespace {
31   /// BytecodeFileReader - parses a bytecode file from a file
32   ///
33   class BytecodeFileReader : public BytecodeReader {
34   private:
35     sys::MappedFile mapFile;
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, llvm::BytecodeHandler* H=0);
42   };
43 }
44
45 static std::string ErrnoMessage (int savedErrNum, std::string descr) {
46    return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
47 }
48
49 BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
50                                        llvm::BytecodeHandler* H ) 
51   : BytecodeReader(H)
52   , mapFile( sys::Path(Filename))
53 {
54   mapFile.map();
55   unsigned char* buffer = reinterpret_cast<unsigned char*>(mapFile.base());
56   ParseBytecode(buffer, mapFile.size(), Filename);
57 }
58
59 //===----------------------------------------------------------------------===//
60 // BytecodeBufferReader - Read from a memory buffer
61 //
62
63 namespace {
64   /// BytecodeBufferReader - parses a bytecode file from a buffer
65   ///
66   class BytecodeBufferReader : public BytecodeReader {
67   private:
68     const unsigned char *Buffer;
69     bool MustDelete;
70
71     BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
72     void operator=(const BytecodeBufferReader &BFR);   // Do not implement
73
74   public:
75     BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
76                          const std::string &ModuleID,
77                          llvm::BytecodeHandler* Handler = 0);
78     ~BytecodeBufferReader();
79
80   };
81 }
82
83 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
84                                            unsigned Length,
85                                            const std::string &ModuleID,
86                                            llvm::BytecodeHandler* H )
87   : BytecodeReader(H)
88 {
89   // If not aligned, allocate a new buffer to hold the bytecode...
90   const unsigned char *ParseBegin = 0;
91   if (reinterpret_cast<uint64_t>(Buf) & 3) {
92     Buffer = new unsigned char[Length+4];
93     unsigned Offset = 4 - ((intptr_t)Buffer & 3);   // Make sure it's aligned
94     ParseBegin = Buffer + Offset;
95     memcpy((unsigned char*)ParseBegin, Buf, Length);    // Copy it over
96     MustDelete = true;
97   } else {
98     // If we don't need to copy it over, just use the caller's copy
99     ParseBegin = Buffer = Buf;
100     MustDelete = false;
101   }
102   try {
103     ParseBytecode(ParseBegin, Length, ModuleID);
104   } catch (...) {
105     if (MustDelete) delete [] Buffer;
106     throw;
107   }
108 }
109
110 BytecodeBufferReader::~BytecodeBufferReader() {
111   if (MustDelete) delete [] Buffer;
112 }
113
114 //===----------------------------------------------------------------------===//
115 //  BytecodeStdinReader - Read bytecode from Standard Input
116 //
117
118 namespace {
119   /// BytecodeStdinReader - parses a bytecode file from stdin
120   /// 
121   class BytecodeStdinReader : public BytecodeReader {
122   private:
123     std::vector<unsigned char> FileData;
124     unsigned char *FileBuf;
125
126     BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
127     void operator=(const BytecodeStdinReader &BFR);  // Do not implement
128
129   public:
130     BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
131   };
132 }
133
134 BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H ) 
135   : BytecodeReader(H)
136 {
137   int BlockSize;
138   unsigned char Buffer[4096*4];
139
140   // Read in all of the data from stdin, we cannot mmap stdin...
141   while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
142     if (BlockSize == -1)
143       throw ErrnoMessage(errno, "read from standard input");
144     
145     FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
146   }
147
148   if (FileData.empty())
149     throw std::string("Standard Input empty!");
150
151   FileBuf = &FileData[0];
152   ParseBytecode(FileBuf, FileData.size(), "<stdin>");
153 }
154
155 //===----------------------------------------------------------------------===//
156 //  Varargs transmogrification code...
157 //
158
159 // CheckVarargs - This is used to automatically translate old-style varargs to
160 // new style varargs for backwards compatibility.
161 static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
162   Module *M = MP->getModule();
163   
164   // Check to see if va_start takes arguments...
165   Function *F = M->getNamedFunction("llvm.va_start");
166   if (F == 0) return MP;  // No varargs use, just return.
167
168   if (F->getFunctionType()->getNumParams() == 0)
169     return MP;  // Modern varargs processing, just return.
170
171   // If we get to this point, we know that we have an old-style module.
172   // Materialize the whole thing to perform the rewriting.
173   MP->materializeModule();
174
175   // If the user is making use of obsolete varargs intrinsics, adjust them for
176   // the user.
177   if (Function *F = M->getNamedFunction("llvm.va_start")) {
178     assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
179         
180     const Type *RetTy = F->getFunctionType()->getParamType(0);
181     RetTy = cast<PointerType>(RetTy)->getElementType();
182     Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
183         
184     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
185       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
186         Value *V = new CallInst(NF, "", CI);
187         new StoreInst(V, CI->getOperand(1), CI);
188         CI->getParent()->getInstList().erase(CI);
189       }
190     F->setName("");
191   }
192
193   if (Function *F = M->getNamedFunction("llvm.va_end")) {
194     assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
195     const Type *ArgTy = F->getFunctionType()->getParamType(0);
196     ArgTy = cast<PointerType>(ArgTy)->getElementType();
197     Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
198                                                   ArgTy, 0);
199         
200     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
201       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
202         Value *V = new LoadInst(CI->getOperand(1), "", CI);
203         new CallInst(NF, V, "", CI);
204         CI->getParent()->getInstList().erase(CI);
205       }
206     F->setName("");
207   }
208       
209   if (Function *F = M->getNamedFunction("llvm.va_copy")) {
210     assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
211     const Type *ArgTy = F->getFunctionType()->getParamType(0);
212     ArgTy = cast<PointerType>(ArgTy)->getElementType();
213     Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
214                                                   ArgTy, 0);
215         
216     for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
217       if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
218         Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
219         new StoreInst(V, CI->getOperand(1), CI);
220         CI->getParent()->getInstList().erase(CI);
221       }
222     F->setName("");
223   }
224   return MP;
225 }
226
227 //===----------------------------------------------------------------------===//
228 // Wrapper functions
229 //===----------------------------------------------------------------------===//
230
231 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
232 /// buffer
233 ModuleProvider* 
234 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
235                                       unsigned Length,
236                                       const std::string &ModuleID,
237                                       BytecodeHandler* H ) {
238   return CheckVarargs(
239       new BytecodeBufferReader(Buffer, Length, ModuleID, H));
240 }
241
242 /// ParseBytecodeBuffer - Parse a given bytecode buffer
243 ///
244 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
245                                   const std::string &ModuleID,
246                                   std::string *ErrorStr){
247   try {
248     std::auto_ptr<ModuleProvider>
249       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
250     return AMP->releaseModule();
251   } catch (std::string &err) {
252     if (ErrorStr) *ErrorStr = err;
253     return 0;
254   }
255 }
256
257 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
258 ///
259 ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
260                                                 BytecodeHandler* H) {
261   if (Filename != std::string("-"))        // Read from a file...
262     return CheckVarargs(new BytecodeFileReader(Filename,H));
263   else                                     // Read from stdin
264     return CheckVarargs(new BytecodeStdinReader(H));
265 }
266
267 /// ParseBytecodeFile - Parse the given bytecode file
268 ///
269 Module *llvm::ParseBytecodeFile(const std::string &Filename,
270                                 std::string *ErrorStr) {
271   try {
272     std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
273     return AMP->releaseModule();
274   } catch (std::string &err) {
275     if (ErrorStr) *ErrorStr = err;
276     return 0;
277   }
278 }
279
280 // AnalyzeBytecodeFile - analyze one file
281 Module* llvm::AnalyzeBytecodeFile(
282   const std::string &Filename,  ///< File to analyze
283   BytecodeAnalysis& bca,        ///< Statistical output
284   std::string *ErrorStr,        ///< Error output
285   std::ostream* output          ///< Dump output
286 )
287 {
288   try {
289     BytecodeHandler* analyzerHandler =createBytecodeAnalyzerHandler(bca,output);
290     std::auto_ptr<ModuleProvider> AMP(
291       getBytecodeModuleProvider(Filename,analyzerHandler));
292     return AMP->releaseModule();
293   } catch (std::string &err) {
294     if (ErrorStr) *ErrorStr = err;
295     return 0;
296   }
297 }
298
299 // AnalyzeBytecodeBuffer - analyze a buffer
300 Module* llvm::AnalyzeBytecodeBuffer(
301   const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
302   unsigned Length,             ///< Size of the bytecode buffer
303   const std::string& ModuleID, ///< Identifier for the module
304   BytecodeAnalysis& bca,       ///< The results of the analysis
305   std::string* ErrorStr,       ///< Errors, if any.
306   std::ostream* output         ///< Dump output, if any
307 )
308 {
309   try {
310     BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
311     std::auto_ptr<ModuleProvider>
312       AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
313     return AMP->releaseModule();
314   } catch (std::string &err) {
315     if (ErrorStr) *ErrorStr = err;
316     return 0;
317   }
318 }
319
320 bool llvm::GetBytecodeDependentLibraries(const std::string &fname, 
321                                          Module::LibraryListType& deplibs) {
322   try {
323     std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
324     Module* M = AMP->releaseModule();
325
326     deplibs = M->getLibraries();
327     delete M;
328     return true;
329   } catch (...) {
330     deplibs.clear();
331     return false;
332   }
333 }
334
335 namespace {
336 void getSymbols(Module*M, std::vector<std::string>& symbols) {
337   // Loop over global variables
338   for (Module::giterator GI = M->gbegin(), GE=M->gend(); GI != GE; ++GI) {
339     if (GI->hasInitializer()) {
340       std::string name ( GI->getName() );
341       if (!name.empty()) {
342         symbols.push_back(name);
343       }
344     }
345   }
346
347   //Loop over functions
348   for (Module::iterator FI = M->begin(), FE=M->end(); FI != FE; ++FI) {
349     if (!FI->isExternal()) {
350       std::string name ( FI->getName() );
351       if (!name.empty()) {
352         symbols.push_back(name);
353       }
354     }
355   }
356 }
357 }
358
359 // Get just the externally visible defined symbols from the bytecode
360 bool llvm::GetBytecodeSymbols(const sys::Path& fName,
361                               std::vector<std::string>& symbols) {
362   try {
363     std::auto_ptr<ModuleProvider> AMP( 
364         getBytecodeModuleProvider(fName.toString()));
365
366     // Get the module from the provider
367     Module* M = AMP->materializeModule();
368
369     // Get the symbols
370     getSymbols(M, symbols);
371
372     // Done with the module
373     return true;
374
375   } catch (...) {
376     return false;
377   }
378 }
379
380 ModuleProvider* 
381 llvm::GetBytecodeSymbols(const unsigned char*Buffer, unsigned Length,
382                          const std::string& ModuleID,
383                          std::vector<std::string>& symbols) {
384
385   ModuleProvider* MP = 0;
386   try {
387     // Get the module provider
388     MP = getBytecodeBufferModuleProvider(Buffer, Length, ModuleID);
389
390     // Get the module from the provider
391     Module* M = MP->materializeModule();
392
393     // Get the symbols
394     getSymbols(M, symbols);
395
396     // Done with the module. Note that ModuleProvider will delete the
397     // Module when it is deleted. Also note that its the caller's responsibility
398     // to delete the ModuleProvider.
399     return MP;
400
401   } catch (...) {
402     // We delete only the ModuleProvider here because its destructor will
403     // also delete the Module (we used materializeModule not releaseModule).
404     delete MP;
405   }
406   return 0;
407 }
408 // vim: sw=2 ai