1 //===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements loading and parsing a bytecode file and parsing a
11 // bytecode module from a given buffer.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Bytecode/Analyzer.h"
16 #include "llvm/Bytecode/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"
26 //===----------------------------------------------------------------------===//
27 // BytecodeFileReader - Read from an mmap'able file descriptor.
31 /// BytecodeFileReader - parses a bytecode file from a file
33 class BytecodeFileReader : public BytecodeReader {
35 sys::MappedFile mapFile;
37 BytecodeFileReader(const BytecodeFileReader&); // Do not implement
38 void operator=(const BytecodeFileReader &BFR); // Do not implement
41 BytecodeFileReader(const std::string &Filename, llvm::BytecodeHandler* H=0);
45 static std::string ErrnoMessage (int savedErrNum, std::string descr) {
46 return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
49 BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
50 llvm::BytecodeHandler* H )
52 , mapFile( sys::Path(Filename))
55 unsigned char* buffer = reinterpret_cast<unsigned char*>(mapFile.base());
56 ParseBytecode(buffer, mapFile.size(), Filename);
59 //===----------------------------------------------------------------------===//
60 // BytecodeBufferReader - Read from a memory buffer
64 /// BytecodeBufferReader - parses a bytecode file from a buffer
66 class BytecodeBufferReader : public BytecodeReader {
68 const unsigned char *Buffer;
71 BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
72 void operator=(const BytecodeBufferReader &BFR); // Do not implement
75 BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
76 const std::string &ModuleID,
77 llvm::BytecodeHandler* Handler = 0);
78 ~BytecodeBufferReader();
83 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
85 const std::string &ModuleID,
86 llvm::BytecodeHandler* H )
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
98 // If we don't need to copy it over, just use the caller's copy
99 ParseBegin = Buffer = Buf;
103 ParseBytecode(ParseBegin, Length, ModuleID);
105 if (MustDelete) delete [] Buffer;
110 BytecodeBufferReader::~BytecodeBufferReader() {
111 if (MustDelete) delete [] Buffer;
114 //===----------------------------------------------------------------------===//
115 // BytecodeStdinReader - Read bytecode from Standard Input
119 /// BytecodeStdinReader - parses a bytecode file from stdin
121 class BytecodeStdinReader : public BytecodeReader {
123 std::vector<unsigned char> FileData;
124 unsigned char *FileBuf;
126 BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
127 void operator=(const BytecodeStdinReader &BFR); // Do not implement
130 BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
134 BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
138 unsigned char Buffer[4096*4];
140 // Read in all of the data from stdin, we cannot mmap stdin...
141 while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
143 throw ErrnoMessage(errno, "read from standard input");
145 FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
148 if (FileData.empty())
149 throw std::string("Standard Input empty!");
151 FileBuf = &FileData[0];
152 ParseBytecode(FileBuf, FileData.size(), "<stdin>");
155 //===----------------------------------------------------------------------===//
156 // Varargs transmogrification code...
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();
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.
168 if (F->getFunctionType()->getNumParams() == 0)
169 return MP; // Modern varargs processing, just return.
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();
175 // If the user is making use of obsolete varargs intrinsics, adjust them for
177 if (Function *F = M->getNamedFunction("llvm.va_start")) {
178 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
180 const Type *RetTy = F->getFunctionType()->getParamType(0);
181 RetTy = cast<PointerType>(RetTy)->getElementType();
182 Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
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);
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,
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);
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,
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);
227 //===----------------------------------------------------------------------===//
229 //===----------------------------------------------------------------------===//
231 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
234 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
236 const std::string &ModuleID,
237 BytecodeHandler* H ) {
239 new BytecodeBufferReader(Buffer, Length, ModuleID, H));
242 /// ParseBytecodeBuffer - Parse a given bytecode buffer
244 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
245 const std::string &ModuleID,
246 std::string *ErrorStr){
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;
257 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
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));
267 /// ParseBytecodeFile - Parse the given bytecode file
269 Module *llvm::ParseBytecodeFile(const std::string &Filename,
270 std::string *ErrorStr) {
272 std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
273 return AMP->releaseModule();
274 } catch (std::string &err) {
275 if (ErrorStr) *ErrorStr = err;
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
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;
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
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;
320 bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
321 Module::LibraryListType& deplibs) {
323 std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
324 Module* M = AMP->releaseModule();
326 deplibs = M->getLibraries();
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() );
342 symbols.push_back(name);
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() );
352 symbols.push_back(name);
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) {
363 std::auto_ptr<ModuleProvider> AMP(
364 getBytecodeModuleProvider(fName.toString()));
366 // Get the module from the provider
367 Module* M = AMP->materializeModule();
370 getSymbols(M, symbols);
372 // Done with the module
381 llvm::GetBytecodeSymbols(const unsigned char*Buffer, unsigned Length,
382 const std::string& ModuleID,
383 std::vector<std::string>& symbols) {
385 ModuleProvider* MP = 0;
387 // Get the module provider
388 MP = getBytecodeBufferModuleProvider(Buffer, Length, ModuleID);
390 // Get the module from the provider
391 Module* M = MP->materializeModule();
394 getSymbols(M, symbols);
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.
402 // We delete only the ModuleProvider here because its destructor will
403 // also delete the Module (we used materializeModule not releaseModule).