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/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 BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
46 llvm::BytecodeHandler* H )
48 , mapFile( sys::Path(Filename))
51 unsigned char* buffer = reinterpret_cast<unsigned char*>(mapFile.base());
52 ParseBytecode(buffer, mapFile.size(), Filename);
55 //===----------------------------------------------------------------------===//
56 // BytecodeBufferReader - Read from a memory buffer
60 /// BytecodeBufferReader - parses a bytecode file from a buffer
62 class BytecodeBufferReader : public BytecodeReader {
64 const unsigned char *Buffer;
67 BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
68 void operator=(const BytecodeBufferReader &BFR); // Do not implement
71 BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
72 const std::string &ModuleID,
73 llvm::BytecodeHandler* Handler = 0);
74 ~BytecodeBufferReader();
79 BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
81 const std::string &ModuleID,
82 llvm::BytecodeHandler* H )
85 // If not aligned, allocate a new buffer to hold the bytecode...
86 const unsigned char *ParseBegin = 0;
87 if (reinterpret_cast<uint64_t>(Buf) & 3) {
88 Buffer = new unsigned char[Length+4];
89 unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
90 ParseBegin = Buffer + Offset;
91 memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
94 // If we don't need to copy it over, just use the caller's copy
95 ParseBegin = Buffer = Buf;
99 ParseBytecode(ParseBegin, Length, ModuleID);
101 if (MustDelete) delete [] Buffer;
106 BytecodeBufferReader::~BytecodeBufferReader() {
107 if (MustDelete) delete [] Buffer;
110 //===----------------------------------------------------------------------===//
111 // BytecodeStdinReader - Read bytecode from Standard Input
115 /// BytecodeStdinReader - parses a bytecode file from stdin
117 class BytecodeStdinReader : public BytecodeReader {
119 std::vector<unsigned char> FileData;
120 unsigned char *FileBuf;
122 BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
123 void operator=(const BytecodeStdinReader &BFR); // Do not implement
126 BytecodeStdinReader( llvm::BytecodeHandler* H = 0 );
130 BytecodeStdinReader::BytecodeStdinReader( BytecodeHandler* H )
135 // Read in all of the data from stdin, we cannot mmap stdin...
136 while (std::cin.good()) {
137 std::cin.read(Buffer, 4096*4);
138 int BlockSize = std::cin.gcount();
141 FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
144 if (FileData.empty())
145 throw std::string("Standard Input empty!");
147 FileBuf = &FileData[0];
148 ParseBytecode(FileBuf, FileData.size(), "<stdin>");
151 //===----------------------------------------------------------------------===//
152 // Varargs transmogrification code...
155 // CheckVarargs - This is used to automatically translate old-style varargs to
156 // new style varargs for backwards compatibility.
157 static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
158 Module *M = MP->getModule();
160 // Check to see if va_start takes arguments...
161 Function *F = M->getNamedFunction("llvm.va_start");
162 if (F == 0) return MP; // No varargs use, just return.
164 if (F->getFunctionType()->getNumParams() == 0)
165 return MP; // Modern varargs processing, just return.
167 // If we get to this point, we know that we have an old-style module.
168 // Materialize the whole thing to perform the rewriting.
169 MP->materializeModule();
171 // If the user is making use of obsolete varargs intrinsics, adjust them for
173 if (Function *F = M->getNamedFunction("llvm.va_start")) {
174 assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
176 const Type *RetTy = F->getFunctionType()->getParamType(0);
177 RetTy = cast<PointerType>(RetTy)->getElementType();
178 Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
180 for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
181 if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
182 Value *V = new CallInst(NF, "", CI);
183 new StoreInst(V, CI->getOperand(1), CI);
184 CI->getParent()->getInstList().erase(CI);
189 if (Function *F = M->getNamedFunction("llvm.va_end")) {
190 assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
191 const Type *ArgTy = F->getFunctionType()->getParamType(0);
192 ArgTy = cast<PointerType>(ArgTy)->getElementType();
193 Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
196 for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
197 if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
198 Value *V = new LoadInst(CI->getOperand(1), "", CI);
199 new CallInst(NF, V, "", CI);
200 CI->getParent()->getInstList().erase(CI);
205 if (Function *F = M->getNamedFunction("llvm.va_copy")) {
206 assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
207 const Type *ArgTy = F->getFunctionType()->getParamType(0);
208 ArgTy = cast<PointerType>(ArgTy)->getElementType();
209 Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
212 for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
213 if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
214 Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
215 new StoreInst(V, CI->getOperand(1), CI);
216 CI->getParent()->getInstList().erase(CI);
223 //===----------------------------------------------------------------------===//
225 //===----------------------------------------------------------------------===//
227 /// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
230 llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
232 const std::string &ModuleID,
233 BytecodeHandler* H ) {
235 new BytecodeBufferReader(Buffer, Length, ModuleID, H));
238 /// ParseBytecodeBuffer - Parse a given bytecode buffer
240 Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
241 const std::string &ModuleID,
242 std::string *ErrorStr){
244 std::auto_ptr<ModuleProvider>
245 AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
246 return AMP->releaseModule();
247 } catch (std::string &err) {
248 if (ErrorStr) *ErrorStr = err;
253 /// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
255 ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename,
256 BytecodeHandler* H) {
257 if (Filename != std::string("-")) // Read from a file...
258 return CheckVarargs(new BytecodeFileReader(Filename,H));
259 else // Read from stdin
260 return CheckVarargs(new BytecodeStdinReader(H));
263 /// ParseBytecodeFile - Parse the given bytecode file
265 Module *llvm::ParseBytecodeFile(const std::string &Filename,
266 std::string *ErrorStr) {
268 std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
269 return AMP->releaseModule();
270 } catch (std::string &err) {
271 if (ErrorStr) *ErrorStr = err;
276 // AnalyzeBytecodeFile - analyze one file
277 Module* llvm::AnalyzeBytecodeFile(
278 const std::string &Filename, ///< File to analyze
279 BytecodeAnalysis& bca, ///< Statistical output
280 std::string *ErrorStr, ///< Error output
281 std::ostream* output ///< Dump output
285 BytecodeHandler* analyzerHandler =createBytecodeAnalyzerHandler(bca,output);
286 std::auto_ptr<ModuleProvider> AMP(
287 getBytecodeModuleProvider(Filename,analyzerHandler));
288 return AMP->releaseModule();
289 } catch (std::string &err) {
290 if (ErrorStr) *ErrorStr = err;
295 // AnalyzeBytecodeBuffer - analyze a buffer
296 Module* llvm::AnalyzeBytecodeBuffer(
297 const unsigned char* Buffer, ///< Pointer to start of bytecode buffer
298 unsigned Length, ///< Size of the bytecode buffer
299 const std::string& ModuleID, ///< Identifier for the module
300 BytecodeAnalysis& bca, ///< The results of the analysis
301 std::string* ErrorStr, ///< Errors, if any.
302 std::ostream* output ///< Dump output, if any
306 BytecodeHandler* hdlr = createBytecodeAnalyzerHandler(bca, output);
307 std::auto_ptr<ModuleProvider>
308 AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, hdlr));
309 return AMP->releaseModule();
310 } catch (std::string &err) {
311 if (ErrorStr) *ErrorStr = err;
316 bool llvm::GetBytecodeDependentLibraries(const std::string &fname,
317 Module::LibraryListType& deplibs) {
319 std::auto_ptr<ModuleProvider> AMP( getBytecodeModuleProvider(fname));
320 Module* M = AMP->releaseModule();
322 deplibs = M->getLibraries();
331 static void getSymbols(Module*M, std::vector<std::string>& symbols) {
332 // Loop over global variables
333 for (Module::giterator GI = M->gbegin(), GE=M->gend(); GI != GE; ++GI)
334 if (!GI->isExternal() && !GI->hasInternalLinkage())
335 if (!GI->getName().empty())
336 symbols.push_back(GI->getName());
338 // Loop over functions.
339 for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI)
340 if (!FI->isExternal() && !FI->hasInternalLinkage())
341 if (!FI->getName().empty())
342 symbols.push_back(FI->getName());
345 // Get just the externally visible defined symbols from the bytecode
346 bool llvm::GetBytecodeSymbols(const sys::Path& fName,
347 std::vector<std::string>& symbols) {
349 std::auto_ptr<ModuleProvider> AMP(
350 getBytecodeModuleProvider(fName.toString()));
352 // Get the module from the provider
353 Module* M = AMP->materializeModule();
356 getSymbols(M, symbols);
358 // Done with the module
367 llvm::GetBytecodeSymbols(const unsigned char*Buffer, unsigned Length,
368 const std::string& ModuleID,
369 std::vector<std::string>& symbols) {
371 ModuleProvider* MP = 0;
373 // Get the module provider
374 MP = getBytecodeBufferModuleProvider(Buffer, Length, ModuleID);
376 // Get the module from the provider
377 Module* M = MP->materializeModule();
380 getSymbols(M, symbols);
382 // Done with the module. Note that ModuleProvider will delete the
383 // Module when it is deleted. Also note that its the caller's responsibility
384 // to delete the ModuleProvider.
388 // We delete only the ModuleProvider here because its destructor will
389 // also delete the Module (we used materializeModule not releaseModule).