remove bytecode reader

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@36882 91177308-0d34-0410-b5e6-96231b3b80d8
This commit is contained in:
Chris Lattner 2007-05-06 19:42:57 +00:00
parent b11f1a9ee1
commit a066e378e9
5 changed files with 0 additions and 3646 deletions

View File

@ -1,673 +0,0 @@
//===-- Analyzer.cpp - Analysis and Dumping of Bytecode ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the AnalyzerHandler class and PrintBytecodeAnalysis
// function which together comprise the basic functionality of the llmv-abcd
// tool. The AnalyzerHandler collects information about the bytecode file into
// the BytecodeAnalysis structure. The PrintBytecodeAnalysis function prints
// out the content of that structure.
// @see include/llvm/Bytecode/Analysis.h
//
//===----------------------------------------------------------------------===//
#include "Reader.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bytecode/BytecodeHandler.h"
#include "llvm/Assembly/Writer.h"
#include <iomanip>
#include <sstream>
#include <ios>
using namespace llvm;
namespace {
/// @brief Bytecode reading handler for analyzing bytecode.
class AnalyzerHandler : public BytecodeHandler {
BytecodeAnalysis& bca; ///< The structure in which data is recorded
std::ostream* os; ///< A convenience for osing data.
/// @brief Keeps track of current function
BytecodeAnalysis::BytecodeFunctionInfo* currFunc;
Module* M; ///< Keeps track of current module
/// @name Constructor
/// @{
public:
/// The only way to construct an AnalyzerHandler. All that is needed is a
/// reference to the BytecodeAnalysis structure where the output will be
/// placed.
AnalyzerHandler(BytecodeAnalysis& TheBca, std::ostream* output)
: bca(TheBca)
, os(output)
, currFunc(0)
{ }
/// @}
/// @name BytecodeHandler Implementations
/// @{
public:
virtual void handleError(const std::string& str ) {
if (os)
*os << "ERROR: " << str << "\n";
}
virtual void handleStart( Module* Mod, unsigned theSize ) {
M = Mod;
if (os)
*os << "Bytecode {\n";
bca.byteSize = theSize;
bca.ModuleId.clear();
bca.numBlocks = 0;
bca.numTypes = 0;
bca.numValues = 0;
bca.numFunctions = 0;
bca.numConstants = 0;
bca.numGlobalVars = 0;
bca.numInstructions = 0;
bca.numBasicBlocks = 0;
bca.numOperands = 0;
bca.numCmpctnTables = 0;
bca.numSymTab = 0;
bca.numLibraries = 0;
bca.libSize = 0;
bca.maxTypeSlot = 0;
bca.maxValueSlot = 0;
bca.numAlignment = 0;
bca.fileDensity = 0.0;
bca.globalsDensity = 0.0;
bca.functionDensity = 0.0;
bca.instructionSize = 0;
bca.longInstructions = 0;
bca.FunctionInfo.clear();
bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse] = 0;
bca.BlockSizes[BytecodeFormat::ModuleBlockID] = theSize;
bca.BlockSizes[BytecodeFormat::FunctionBlockID] = 0;
bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID] = 0;
bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID] = 0;
bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID] = 0;
bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID] = 0;
bca.BlockSizes[BytecodeFormat::InstructionListBlockID] = 0;
bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID] = 0;
}
virtual void handleFinish() {
if (os)
*os << "} End Bytecode\n";
bca.fileDensity = double(bca.byteSize) / double( bca.numTypes + bca.numValues );
double globalSize = 0.0;
globalSize += double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]);
globalSize += double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]);
globalSize += double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]);
bca.globalsDensity = globalSize / double( bca.numTypes + bca.numConstants +
bca.numGlobalVars );
bca.functionDensity = double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]) /
double(bca.numFunctions);
if (bca.progressiveVerify) {
std::string msg;
if (verifyModule(*M, ReturnStatusAction, &msg))
bca.VerifyInfo += "Verify@Finish: " + msg + "\n";
}
}
virtual void handleModuleBegin(const std::string& id) {
if (os)
*os << " Module " << id << " {\n";
bca.ModuleId = id;
}
virtual void handleModuleEnd(const std::string& id) {
if (os)
*os << " } End Module " << id << "\n";
if (bca.progressiveVerify) {
std::string msg;
if (verifyModule(*M, ReturnStatusAction, &msg))
bca.VerifyInfo += "Verify@EndModule: " + msg + "\n";
}
}
virtual void handleVersionInfo(
unsigned char RevisionNum ///< Byte code revision number
) {
if (os)
*os << " RevisionNum: " << int(RevisionNum) << "\n";
bca.version = RevisionNum;
}
virtual void handleModuleGlobalsBegin() {
if (os)
*os << " BLOCK: ModuleGlobalInfo {\n";
}
virtual void handleGlobalVariable(
const Type* ElemType,
bool isConstant,
GlobalValue::LinkageTypes Linkage,
GlobalValue::VisibilityTypes Visibility,
unsigned SlotNum,
unsigned initSlot,
bool isThreadLocal
) {
if (os) {
*os << " GV: "
<< ( initSlot == 0 ? "Uni" : "I" ) << "nitialized, "
<< ( isConstant? "Constant, " : "Variable, ")
<< " Thread Local = " << ( isThreadLocal? "yes, " : "no, ")
<< " Linkage=" << Linkage
<< " Visibility="<< Visibility
<< " Type=";
//WriteTypeSymbolic(*os, ElemType, M);
*os << " Slot=" << SlotNum << " InitSlot=" << initSlot
<< "\n";
}
bca.numGlobalVars++;
bca.numValues++;
if (SlotNum > bca.maxValueSlot)
bca.maxValueSlot = SlotNum;
if (initSlot > bca.maxValueSlot)
bca.maxValueSlot = initSlot;
}
virtual void handleGlobalAlias(
const Type* ElemType,
GlobalValue::LinkageTypes Linkage,
unsigned TypeSlotNum,
unsigned AliaseeSlot) {
if (os) {
*os << " GA: "
<< " Linkage=" << Linkage
<< " Type=";
//WriteTypeSymbolic(*os, ElemType, M);
*os << " Slot=" << TypeSlotNum << " AliaseeSlot=" << AliaseeSlot
<< "\n";
}
bca.numValues++;
if (TypeSlotNum > bca.maxValueSlot)
bca.maxValueSlot = TypeSlotNum;
if (AliaseeSlot > bca.maxValueSlot)
bca.maxValueSlot = AliaseeSlot;
}
virtual void handleTypeList(unsigned numEntries) {
bca.maxTypeSlot = numEntries - 1;
}
virtual void handleType( const Type* Ty ) {
bca.numTypes++;
if (os) {
*os << " Type: ";
//WriteTypeSymbolic(*os,Ty,M);
*os << "\n";
}
}
virtual void handleFunctionDeclaration(
Function* Func ///< The function
) {
bca.numFunctions++;
bca.numValues++;
if (os) {
*os << " Function Decl: ";
//WriteTypeSymbolic(*os,Func->getType(),M);
*os <<", Linkage=" << Func->getLinkage();
*os <<", Visibility=" << Func->getVisibility();
*os << "\n";
}
}
virtual void handleGlobalInitializer(GlobalVariable* GV, Constant* CV) {
if (os) {
*os << " Initializer: GV=";
GV->print(*os);
*os << " CV=";
CV->print(*os);
*os << "\n";
}
}
virtual void handleDependentLibrary(const std::string& libName) {
bca.numLibraries++;
bca.libSize += libName.size() + (libName.size() < 128 ? 1 : 2);
if (os)
*os << " Library: '" << libName << "'\n";
}
virtual void handleModuleGlobalsEnd() {
if (os)
*os << " } END BLOCK: ModuleGlobalInfo\n";
if (bca.progressiveVerify) {
std::string msg;
if (verifyModule(*M, ReturnStatusAction, &msg))
bca.VerifyInfo += "Verify@EndModuleGlobalInfo: " + msg + "\n";
}
}
virtual void handleTypeSymbolTableBegin(TypeSymbolTable* ST) {
bca.numSymTab++;
if (os)
*os << " BLOCK: TypeSymbolTable {\n";
}
virtual void handleValueSymbolTableBegin(Function* CF, ValueSymbolTable* ST) {
bca.numSymTab++;
if (os)
*os << " BLOCK: ValueSymbolTable {\n";
}
virtual void handleSymbolTableType(unsigned i, unsigned TypSlot,
const std::string& name ) {
if (os)
*os << " Type " << i << " Slot=" << TypSlot
<< " Name: " << name << "\n";
}
virtual void handleSymbolTableValue(unsigned TySlot, unsigned ValSlot,
const char *Name, unsigned NameLen) {
if (os)
*os << " Value " << TySlot << " Slot=" << ValSlot
<< " Name: " << std::string(Name, Name+NameLen) << "\n";
if (ValSlot > bca.maxValueSlot)
bca.maxValueSlot = ValSlot;
}
virtual void handleValueSymbolTableEnd() {
if (os)
*os << " } END BLOCK: ValueSymbolTable\n";
}
virtual void handleTypeSymbolTableEnd() {
if (os)
*os << " } END BLOCK: TypeSymbolTable\n";
}
virtual void handleFunctionBegin(Function* Func, unsigned Size) {
if (os) {
*os << " BLOCK: Function {\n"
<< " Linkage: " << Func->getLinkage() << "\n"
<< " Visibility: " << Func->getVisibility() << "\n"
<< " Type: ";
//WriteTypeSymbolic(*os,Func->getType(),M);
*os << "\n";
}
currFunc = &bca.FunctionInfo[Func];
std::ostringstream tmp;
//WriteTypeSymbolic(tmp,Func->getType(),M);
currFunc->description = tmp.str();
currFunc->name = Func->getName();
currFunc->byteSize = Size;
currFunc->numInstructions = 0;
currFunc->numBasicBlocks = 0;
currFunc->numPhis = 0;
currFunc->numOperands = 0;
currFunc->density = 0.0;
currFunc->instructionSize = 0;
currFunc->longInstructions = 0;
}
virtual void handleFunctionEnd( Function* Func) {
if (os)
*os << " } END BLOCK: Function\n";
currFunc->density = double(currFunc->byteSize) /
double(currFunc->numInstructions);
if (bca.progressiveVerify) {
std::string msg;
if (verifyModule(*M, ReturnStatusAction, &msg))
bca.VerifyInfo += "Verify@EndFunction: " + msg + "\n";
}
}
virtual void handleBasicBlockBegin( unsigned blocknum) {
if (os)
*os << " BLOCK: BasicBlock #" << blocknum << "{\n";
bca.numBasicBlocks++;
bca.numValues++;
if ( currFunc ) currFunc->numBasicBlocks++;
}
virtual bool handleInstruction( unsigned Opcode, const Type* iType,
unsigned *Operands, unsigned NumOps,
Instruction *Inst,
unsigned Size){
if (os) {
*os << " INST: OpCode="
<< Instruction::getOpcodeName(Opcode);
for (unsigned i = 0; i != NumOps; ++i)
*os << " Op(" << Operands[i] << ")";
*os << *Inst;
}
bca.numInstructions++;
bca.numValues++;
bca.instructionSize += Size;
if (Size > 4 ) bca.longInstructions++;
bca.numOperands += NumOps;
for (unsigned i = 0; i != NumOps; ++i)
if (Operands[i] > bca.maxValueSlot)
bca.maxValueSlot = Operands[i];
if ( currFunc ) {
currFunc->numInstructions++;
currFunc->instructionSize += Size;
if (Size > 4 ) currFunc->longInstructions++;
if (Opcode == Instruction::PHI) currFunc->numPhis++;
}
return Instruction::isTerminator(Opcode);
}
virtual void handleBasicBlockEnd(unsigned blocknum) {
if (os)
*os << " } END BLOCK: BasicBlock #" << blocknum << "\n";
}
virtual void handleGlobalConstantsBegin() {
if (os)
*os << " BLOCK: GlobalConstants {\n";
}
virtual void handleConstantExpression(unsigned Opcode,
Constant**ArgVec, unsigned NumArgs, Constant* C) {
if (os) {
*os << " EXPR: " << Instruction::getOpcodeName(Opcode) << "\n";
for ( unsigned i = 0; i != NumArgs; ++i ) {
*os << " Arg#" << i << " "; ArgVec[i]->print(*os);
*os << "\n";
}
*os << " Value=";
C->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantValue( Constant * c ) {
if (os) {
*os << " VALUE: ";
c->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantArray( const ArrayType* AT,
Constant**Elements, unsigned NumElts,
unsigned TypeSlot,
Constant* ArrayVal ) {
if (os) {
*os << " ARRAY: ";
//WriteTypeSymbolic(*os,AT,M);
*os << " TypeSlot=" << TypeSlot << "\n";
for (unsigned i = 0; i != NumElts; ++i) {
*os << " #" << i;
Elements[i]->print(*os);
*os << "\n";
}
*os << " Value=";
ArrayVal->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantStruct(
const StructType* ST,
Constant**Elements, unsigned NumElts,
Constant* StructVal)
{
if (os) {
*os << " STRUC: ";
//WriteTypeSymbolic(*os,ST,M);
*os << "\n";
for ( unsigned i = 0; i != NumElts; ++i) {
*os << " #" << i << " "; Elements[i]->print(*os);
*os << "\n";
}
*os << " Value=";
StructVal->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantVector(
const VectorType* PT,
Constant**Elements, unsigned NumElts,
unsigned TypeSlot,
Constant* VectorVal)
{
if (os) {
*os << " PACKD: ";
//WriteTypeSymbolic(*os,PT,M);
*os << " TypeSlot=" << TypeSlot << "\n";
for ( unsigned i = 0; i != NumElts; ++i ) {
*os << " #" << i;
Elements[i]->print(*os);
*os << "\n";
}
*os << " Value=";
VectorVal->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantPointer( const PointerType* PT,
unsigned Slot, GlobalValue* GV ) {
if (os) {
*os << " PNTR: ";
//WriteTypeSymbolic(*os,PT,M);
*os << " Slot=" << Slot << " GlobalValue=";
GV->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleConstantString( const ConstantArray* CA ) {
if (os) {
*os << " STRNG: ";
CA->print(*os);
*os << "\n";
}
bca.numConstants++;
bca.numValues++;
}
virtual void handleGlobalConstantsEnd() {
if (os)
*os << " } END BLOCK: GlobalConstants\n";
if (bca.progressiveVerify) {
std::string msg;
if (verifyModule(*M, ReturnStatusAction, &msg))
bca.VerifyInfo += "Verify@EndGlobalConstants: " + msg + "\n";
}
}
virtual void handleAlignment(unsigned numBytes) {
bca.numAlignment += numBytes;
}
virtual void handleBlock(
unsigned BType, const unsigned char* StartPtr, unsigned Size) {
bca.numBlocks++;
assert(BType >= BytecodeFormat::ModuleBlockID);
assert(BType < BytecodeFormat::NumberOfBlockIDs);
bca.BlockSizes[
llvm::BytecodeFormat::BytecodeBlockIdentifiers(BType)] += Size;
if (bca.version < 3) // Check for long block headers versions
bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 8;
else
bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 4;
}
};
} // end anonymous namespace
/// @brief Utility for printing a titled unsigned value with
/// an aligned colon.
inline static void print(std::ostream& Out, const char*title,
unsigned val, bool nl = true ) {
Out << std::setw(30) << std::right << title
<< std::setw(0) << ": "
<< std::setw(9) << val << "\n";
}
/// @brief Utility for printing a titled double value with an
/// aligned colon
inline static void print(std::ostream&Out, const char*title,
double val ) {
Out << std::setw(30) << std::right << title
<< std::setw(0) << ": "
<< std::setw(9) << std::setprecision(6) << val << "\n" ;
}
/// @brief Utility for printing a titled double value with a
/// percentage and aligned colon.
inline static void print(std::ostream&Out, const char*title,
double top, double bot ) {
Out << std::setw(30) << std::right << title
<< std::setw(0) << ": "
<< std::setw(9) << std::setprecision(6) << top
<< " (" << std::left << std::setw(0) << std::setprecision(4)
<< (top/bot)*100.0 << "%)\n";
}
/// @brief Utility for printing a titled string value with
/// an aligned colon.
inline static void print(std::ostream&Out, const char*title,
std::string val, bool nl = true) {
Out << std::setw(30) << std::right << title
<< std::setw(0) << ": "
<< std::left << val << (nl ? "\n" : "");
}
/// This function prints the contents of rhe BytecodeAnalysis structure in
/// a human legible form.
/// @brief Print BytecodeAnalysis structure to an ostream
void llvm::PrintBytecodeAnalysis(BytecodeAnalysis& bca, std::ostream& Out )
{
Out << "\nSummary Analysis Of " << bca.ModuleId << ": \n\n";
print(Out, "Bytecode Analysis Of Module", bca.ModuleId);
print(Out, "Bytecode Version Number", bca.version);
print(Out, "File Size", bca.byteSize);
print(Out, "Module Bytes",
double(bca.BlockSizes[BytecodeFormat::ModuleBlockID]),
double(bca.byteSize));
print(Out, "Function Bytes",
double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]),
double(bca.byteSize));
print(Out, "Global Types Bytes",
double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]),
double(bca.byteSize));
print(Out, "Constant Pool Bytes",
double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]),
double(bca.byteSize));
print(Out, "Module Globals Bytes",
double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]),
double(bca.byteSize));
print(Out, "Instruction List Bytes",
double(bca.BlockSizes[BytecodeFormat::InstructionListBlockID]),
double(bca.byteSize));
print(Out, "Value Symbol Table Bytes",
double(bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID]),
double(bca.byteSize));
print(Out, "Type Symbol Table Bytes",
double(bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID]),
double(bca.byteSize));
print(Out, "Alignment Bytes",
double(bca.numAlignment), double(bca.byteSize));
print(Out, "Block Header Bytes",
double(bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse]),
double(bca.byteSize));
print(Out, "Dependent Libraries Bytes", double(bca.libSize),
double(bca.byteSize));
print(Out, "Number Of Bytecode Blocks", bca.numBlocks);
print(Out, "Number Of Functions", bca.numFunctions);
print(Out, "Number Of Types", bca.numTypes);
print(Out, "Number Of Constants", bca.numConstants);
print(Out, "Number Of Global Variables", bca.numGlobalVars);
print(Out, "Number Of Values", bca.numValues);
print(Out, "Number Of Basic Blocks", bca.numBasicBlocks);
print(Out, "Number Of Instructions", bca.numInstructions);
print(Out, "Number Of Long Instructions", bca.longInstructions);
print(Out, "Number Of Operands", bca.numOperands);
print(Out, "Number Of Symbol Tables", bca.numSymTab);
print(Out, "Number Of Dependent Libs", bca.numLibraries);
print(Out, "Total Instruction Size", bca.instructionSize);
print(Out, "Average Instruction Size",
double(bca.instructionSize)/double(bca.numInstructions));
print(Out, "Maximum Type Slot Number", bca.maxTypeSlot);
print(Out, "Maximum Value Slot Number", bca.maxValueSlot);
print(Out, "Bytes Per Value ", bca.fileDensity);
print(Out, "Bytes Per Global", bca.globalsDensity);
print(Out, "Bytes Per Function", bca.functionDensity);
if (bca.detailedResults) {
Out << "\nDetailed Analysis Of " << bca.ModuleId << " Functions:\n";
std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator I =
bca.FunctionInfo.begin();
std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator E =
bca.FunctionInfo.end();
while ( I != E ) {
Out << std::left << std::setw(0) << "\n";
if (I->second.numBasicBlocks == 0) Out << "External ";
Out << "Function: " << I->second.name << "\n";
print(Out, "Type:", I->second.description);
print(Out, "Byte Size", I->second.byteSize);
if (I->second.numBasicBlocks) {
print(Out, "Basic Blocks", I->second.numBasicBlocks);
print(Out, "Instructions", I->second.numInstructions);
print(Out, "Long Instructions", I->second.longInstructions);
print(Out, "Operands", I->second.numOperands);
print(Out, "Instruction Size", I->second.instructionSize);
print(Out, "Average Instruction Size",
double(I->second.instructionSize) / I->second.numInstructions);
print(Out, "Bytes Per Instruction", I->second.density);
}
++I;
}
}
if ( bca.progressiveVerify )
Out << bca.VerifyInfo;
}
// AnalyzeBytecodeFile - analyze one file
Module* llvm::AnalyzeBytecodeFile(const std::string &Filename, ///< File to analyze
BytecodeAnalysis& bca, ///< Statistical output
BCDecompressor_t *BCDC,
std::string *ErrMsg, ///< Error output
std::ostream* output ///< Dump output
) {
BytecodeHandler* AH = new AnalyzerHandler(bca, output);
ModuleProvider* MP = getBytecodeModuleProvider(Filename, BCDC, ErrMsg, AH);
if (!MP) return 0;
Module *M = MP->releaseModule(ErrMsg);
delete MP;
return M;
}

View File

@ -1,14 +0,0 @@
##===- lib/Bytecode/Reader/Makefile ------------------------*- Makefile -*-===##
#
# The LLVM Compiler Infrastructure
#
# This file was developed by the LLVM research group and is distributed under
# the University of Illinois Open Source License. See LICENSE.TXT for details.
#
##===----------------------------------------------------------------------===##
LEVEL = ../../..
LIBRARYNAME = LLVMBCReader
BUILD_ARCHIVE = 1
include $(LEVEL)/Makefile.common

File diff suppressed because it is too large Load Diff

View File

@ -1,491 +0,0 @@
//===-- Reader.h - Interface To Bytecode Reading ----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Reid Spencer and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header file defines the interface to the Bytecode Reader which is
// responsible for correctly interpreting bytecode files (backwards compatible)
// and materializing a module from the bytecode read.
//
//===----------------------------------------------------------------------===//
#ifndef BYTECODE_PARSER_H
#define BYTECODE_PARSER_H
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/ModuleProvider.h"
#include "llvm/Bytecode/Analyzer.h"
#include "llvm/ADT/SmallVector.h"
#include <utility>
#include <setjmp.h>
namespace llvm {
// Forward declarations
class BytecodeHandler;
class TypeSymbolTable;
class ValueSymbolTable;
/// This class defines the interface for parsing a buffer of bytecode. The
/// parser itself takes no action except to call the various functions of
/// the handler interface. The parser's sole responsibility is the correct
/// interpretation of the bytecode buffer. The handler is responsible for
/// instantiating and keeping track of all values. As a convenience, the parser
/// is responsible for materializing types and will pass them through the
/// handler interface as necessary.
/// @see BytecodeHandler
/// @brief Bytecode Reader interface
class BytecodeReader : public ModuleProvider {
/// @name Constructors
/// @{
public:
/// @brief Default constructor. By default, no handler is used.
BytecodeReader(BytecodeHandler* h = 0) {
decompressedBlock = 0;
Handler = h;
}
~BytecodeReader() {
freeState();
if (decompressedBlock) {
::free(decompressedBlock);
decompressedBlock = 0;
}
}
/// @}
/// @name Types
/// @{
public:
/// @brief A convenience type for the buffer pointer
typedef const unsigned char* BufPtr;
/// @brief The type used for a vector of potentially abstract types
typedef std::vector<PATypeHolder> TypeListTy;
/// This type provides a vector of Value* via the User class for
/// storage of Values that have been constructed when reading the
/// bytecode. Because of forward referencing, constant replacement
/// can occur so we ensure that our list of Value* is updated
/// properly through those transitions. This ensures that the
/// correct Value* is in our list when it comes time to associate
/// constants with global variables at the end of reading the
/// globals section.
/// @brief A list of values as a User of those Values.
class ValueList : public User {
SmallVector<Use, 32> Uses;
public:
ValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0) {}
// vector compatibility methods
unsigned size() const { return getNumOperands(); }
void push_back(Value *V) {
Uses.push_back(Use(V, this));
OperandList = &Uses[0];
++NumOperands;
}
Value *back() const { return Uses.back(); }
void pop_back() { Uses.pop_back(); --NumOperands; }
bool empty() const { return NumOperands == 0; }
virtual void print(std::ostream& os) const {
for (unsigned i = 0; i < size(); ++i) {
os << i << " ";
getOperand(i)->print(os);
os << "\n";
}
}
};
/// @brief A 2 dimensional table of values
typedef std::vector<ValueList*> ValueTable;
/// This map is needed so that forward references to constants can be looked
/// up by Type and slot number when resolving those references.
/// @brief A mapping of a Type/slot pair to a Constant*.
typedef std::map<std::pair<unsigned,unsigned>, Constant*> ConstantRefsType;
/// For lazy read-in of functions, we need to save the location in the
/// data stream where the function is located. This structure provides that
/// information. Lazy read-in is used mostly by the JIT which only wants to
/// resolve functions as it needs them.
/// @brief Keeps pointers to function contents for later use.
struct LazyFunctionInfo {
const unsigned char *Buf, *EndBuf;
LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
: Buf(B), EndBuf(EB) {}
};
/// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
/// @brief A list of global variables and the slot number that initializes
/// them.
typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
/// @brief A list of global aliases and the slot number for constant aliasees
typedef std::vector<std::pair<GlobalAlias*, unsigned> > AliaseeList;
/// This type maps a typeslot/valueslot pair to the corresponding Value*.
/// It is used for dealing with forward references as values are read in.
/// @brief A map for dealing with forward references of values.
typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
/// @}
/// @name Methods
/// @{
public:
typedef size_t BCDecompressor_t(const char *, size_t, char*&, std::string*);
/// @returns true if an error occurred
/// @brief Main interface to parsing a bytecode buffer.
bool ParseBytecode(
volatile BufPtr Buf, ///< Beginning of the bytecode buffer
unsigned Length, ///< Length of the bytecode buffer
const std::string &ModuleID, ///< An identifier for the module constructed.
BCDecompressor_t *Decompressor = 0, ///< Optional decompressor.
std::string* ErrMsg = 0 ///< Optional place for error message
);
/// @brief Parse all function bodies
bool ParseAllFunctionBodies(std::string* ErrMsg);
/// @brief Parse the next function of specific type
bool ParseFunction(Function* Func, std::string* ErrMsg);
/// This method is abstract in the parent ModuleProvider class. Its
/// implementation is identical to the ParseFunction method.
/// @see ParseFunction
/// @brief Make a specific function materialize.
virtual bool materializeFunction(Function *F, std::string *ErrMsg = 0) {
// If it already is material, ignore the request.
if (!F->hasNotBeenReadFromBytecode()) return false;
assert(LazyFunctionLoadMap.count(F) &&
"not materialized but I don't know about it?");
if (ParseFunction(F,ErrMsg))
return true;
return false;
}
/// dematerializeFunction - If the given function is read in, and if the
/// module provider supports it, release the memory for the function, and set
/// it up to be materialized lazily. If the provider doesn't support this
/// capability, this method is a noop.
///
virtual void dematerializeFunction(Function *F) {
// If the function is not materialized, or if it is a prototype, ignore.
if (F->hasNotBeenReadFromBytecode() ||
F->isDeclaration())
return;
// Just forget the function body, we can remat it later.
F->deleteBody();
F->setLinkage(GlobalValue::GhostLinkage);
}
/// This method is abstract in the parent ModuleProvider class. Its
/// implementation is identical to ParseAllFunctionBodies.
/// @see ParseAllFunctionBodies
/// @brief Make the whole module materialize
virtual Module* materializeModule(std::string *ErrMsg = 0) {
if (ParseAllFunctionBodies(ErrMsg))
return 0;
return TheModule;
}
/// This method is provided by the parent ModuleProvde class and overriden
/// here. It simply releases the module from its provided and frees up our
/// state.
/// @brief Release our hold on the generated module
Module* releaseModule(std::string *ErrInfo = 0) {
// Since we're losing control of this Module, we must hand it back complete
Module *M = ModuleProvider::releaseModule(ErrInfo);
freeState();
return M;
}
/// @}
/// @name Parsing Units For Subclasses
/// @{
protected:
/// @brief Parse whole module scope
void ParseModule();
/// @brief Parse the version information block
void ParseVersionInfo();
/// @brief Parse the ModuleGlobalInfo block
void ParseModuleGlobalInfo();
/// @brief Parse a value symbol table
void ParseTypeSymbolTable(TypeSymbolTable *ST);
/// @brief Parse a value symbol table
void ParseValueSymbolTable(Function* Func, ValueSymbolTable *ST);
/// @brief Parse functions lazily.
void ParseFunctionLazily();
/// @brief Parse a function body
void ParseFunctionBody(Function* Func);
/// @brief Parse global types
void ParseGlobalTypes();
/// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
BasicBlock* ParseBasicBlock(unsigned BlockNo);
/// @brief parse an instruction list (for post LLVM 1.0 instruction lists
/// with blocks differentiated by terminating instructions.
unsigned ParseInstructionList(
Function* F ///< The function into which BBs will be inserted
);
/// @brief Parse a single instruction.
void ParseInstruction(
SmallVector <unsigned, 8>& Args, ///< The arguments to be filled in
BasicBlock* BB ///< The BB the instruction goes in
);
/// @brief Parse the whole constant pool
void ParseConstantPool(ValueTable& Values, TypeListTy& Types,
bool isFunction);
/// @brief Parse a single constant pool value
Value *ParseConstantPoolValue(unsigned TypeID);
/// @brief Parse a block of types constants
void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
/// @brief Parse a single type constant
const Type *ParseType();
/// @brief Parse a list of parameter attributes
ParamAttrsList *ParseParamAttrsList();
/// @brief Parse a string constants block
void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
/// @brief Release our memory.
void freeState() {
freeTable(FunctionValues);
freeTable(ModuleValues);
}
/// @}
/// @name Data
/// @{
private:
std::string ErrorMsg; ///< A place to hold an error message through longjmp
jmp_buf context; ///< Where to return to if an error occurs.
char* decompressedBlock; ///< Result of decompression
BufPtr MemStart; ///< Start of the memory buffer
BufPtr MemEnd; ///< End of the memory buffer
BufPtr BlockStart; ///< Start of current block being parsed
BufPtr BlockEnd; ///< End of current block being parsed
BufPtr At; ///< Where we're currently parsing at
/// Information about the module, extracted from the bytecode revision number.
///
unsigned char RevisionNum; // The rev # itself
/// @brief This vector is used to deal with forward references to types in
/// a module.
TypeListTy ModuleTypes;
/// @brief This is an inverse mapping of ModuleTypes from the type to an
/// index. Because refining types causes the index of this map to be
/// invalidated, any time we refine a type, we clear this cache and recompute
/// it next time we need it. These entries are ordered by the pointer value.
std::vector<std::pair<const Type*, unsigned> > ModuleTypeIDCache;
/// @brief This vector is used to deal with forward references to types in
/// a function.
TypeListTy FunctionTypes;
/// When the ModuleGlobalInfo section is read, we create a Function object
/// for each function in the module. When the function is loaded, after the
/// module global info is read, this Function is populated. Until then, the
/// functions in this vector just hold the function signature.
std::vector<Function*> FunctionSignatureList;
/// @brief This is the table of values belonging to the current function
ValueTable FunctionValues;
/// @brief This is the table of values belonging to the module (global)
ValueTable ModuleValues;
/// @brief This keeps track of function level forward references.
ForwardReferenceMap ForwardReferences;
/// @brief The basic blocks we've parsed, while parsing a function.
std::vector<BasicBlock*> ParsedBasicBlocks;
/// This maintains a mapping between <Type, Slot #>'s and forward references
/// to constants. Such values may be referenced before they are defined, and
/// if so, the temporary object that they represent is held here. @brief
/// Temporary place for forward references to constants.
ConstantRefsType ConstantFwdRefs;
/// Constant values are read in after global variables. Because of this, we
/// must defer setting the initializers on global variables until after module
/// level constants have been read. In the mean time, this list keeps track
/// of what we must do.
GlobalInitsList GlobalInits;
/// Constant values are read in after global aliases. Because of this, we must
/// defer setting the constant aliasees until after module level constants
/// have been read. In the mean time, this list keeps track of what we must
/// do.
AliaseeList Aliasees;
// For lazy reading-in of functions, we need to save away several pieces of
// information about each function: its begin and end pointer in the buffer
// and its FunctionSlot.
LazyFunctionMap LazyFunctionLoadMap;
/// This stores the parser's handler which is used for handling tasks other
/// just than reading bytecode into the IR. If this is non-null, calls on
/// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h)
/// will be made to report the logical structure of the bytecode file. What
/// the handler does with the events it receives is completely orthogonal to
/// the business of parsing the bytecode and building the IR. This is used,
/// for example, by the llvm-abcd tool for analysis of byte code.
/// @brief Handler for parsing events.
BytecodeHandler* Handler;
/// @}
/// @name Implementation Details
/// @{
private:
/// @brief Determines if this module has a function or not.
bool hasFunctions() { return ! FunctionSignatureList.empty(); }
/// @brief Determines if the type id has an implicit null value.
bool hasImplicitNull(unsigned TyID );
/// @brief Converts a type slot number to its Type*
const Type *getType(unsigned ID);
/// @brief Read in a type id and turn it into a Type*
inline const Type* readType();
/// @brief Converts a Type* to its type slot number
unsigned getTypeSlot(const Type *Ty);
/// @brief Gets the global type corresponding to the TypeId
const Type *getGlobalTableType(unsigned TypeId);
/// @brief Get a value from its typeid and slot number
Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
/// @brief Get a basic block for current function
BasicBlock *getBasicBlock(unsigned ID);
/// @brief Get a constant value from its typeid and value slot.
Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
/// @brief Convenience function for getting a constant value when
/// the Type has already been resolved.
Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
return getConstantValue(getTypeSlot(Ty), valSlot);
}
/// @brief Insert a newly created value
unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
/// @brief Insert the arguments of a function.
void insertArguments(Function* F );
/// @brief Resolve all references to the placeholder (if any) for the
/// given constant.
void ResolveReferencesToConstant(Constant *C, unsigned Typ, unsigned Slot);
/// @brief Free a table, making sure to free the ValueList in the table.
void freeTable(ValueTable &Tab) {
while (!Tab.empty()) {
delete Tab.back();
Tab.pop_back();
}
}
inline void error(const std::string& errmsg);
BytecodeReader(const BytecodeReader &); // DO NOT IMPLEMENT
void operator=(const BytecodeReader &); // DO NOT IMPLEMENT
// This enum provides the values of the well-known type slots that are always
// emitted as the first few types in the table by the BytecodeWriter class.
enum WellKnownTypeSlots {
VoidTypeSlot = 0, ///< TypeID == VoidTyID
FloatTySlot = 1, ///< TypeID == FloatTyID
DoubleTySlot = 2, ///< TypeID == DoubleTyID
LabelTySlot = 3, ///< TypeID == LabelTyID
BoolTySlot = 4, ///< TypeID == IntegerTyID, width = 1
Int8TySlot = 5, ///< TypeID == IntegerTyID, width = 8
Int16TySlot = 6, ///< TypeID == IntegerTyID, width = 16
Int32TySlot = 7, ///< TypeID == IntegerTyID, width = 32
Int64TySlot = 8 ///< TypeID == IntegerTyID, width = 64
};
/// @}
/// @name Reader Primitives
/// @{
private:
/// @brief Is there more to parse in the current block?
inline bool moreInBlock();
/// @brief Have we read past the end of the block
inline void checkPastBlockEnd(const char * block_name);
/// @brief Align to 32 bits
inline void align32();
/// @brief Read an unsigned integer as 32-bits
inline unsigned read_uint();
/// @brief Read an unsigned integer with variable bit rate encoding
inline unsigned read_vbr_uint();
/// @brief Read an unsigned integer of no more than 24-bits with variable
/// bit rate encoding.
inline unsigned read_vbr_uint24();
/// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
inline uint64_t read_vbr_uint64();
/// @brief Read a signed 64-bit integer with variable bit rate encoding.
inline int64_t read_vbr_int64();
/// @brief Read a string
inline std::string read_str();
inline void read_str(SmallVectorImpl<char> &StrData);
/// @brief Read a float value
inline void read_float(float& FloatVal);
/// @brief Read a double value
inline void read_double(double& DoubleVal);
/// @brief Read an arbitrary data chunk of fixed length
inline void read_data(void *Ptr, void *End);
/// @brief Read a bytecode block header
inline void read_block(unsigned &Type, unsigned &Size);
/// @}
};
} // End llvm namespace
// vim: sw=2
#endif

View File

@ -1,256 +0,0 @@
//===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Analyzer.h"
#include "llvm/Bytecode/Reader.h"
#include "Reader.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/System/MappedFile.h"
#include "llvm/System/Program.h"
#include <cerrno>
#include <memory>
using namespace llvm;
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// BytecodeFileReader - parses a bytecode file from a file
///
class BytecodeFileReader : public BytecodeReader {
private:
std::string fileName;
BCDecompressor_t *Decompressor;
sys::MappedFile mapFile;
BytecodeFileReader(const BytecodeFileReader&); // Do not implement
void operator=(const BytecodeFileReader &BFR); // Do not implement
public:
BytecodeFileReader(const std::string &Filename, BCDecompressor_t *BCDC,
llvm::BytecodeHandler* H=0);
bool read(std::string* ErrMsg);
void freeState() {
BytecodeReader::freeState();
mapFile.close();
}
};
}
BytecodeFileReader::BytecodeFileReader(const std::string &Filename,
BCDecompressor_t *BCDC,
llvm::BytecodeHandler* H)
: BytecodeReader(H), fileName(Filename), Decompressor(BCDC) {
}
bool BytecodeFileReader::read(std::string* ErrMsg) {
if (mapFile.open(sys::Path(fileName), sys::MappedFile::READ_ACCESS, ErrMsg))
return true;
if (!mapFile.map(ErrMsg)) {
mapFile.close();
return true;
}
unsigned char* buffer = reinterpret_cast<unsigned char*>(mapFile.base());
return ParseBytecode(buffer, mapFile.size(), fileName,
Decompressor, ErrMsg);
}
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
///
class BytecodeBufferReader : public BytecodeReader {
private:
const unsigned char *Buffer;
const unsigned char *Buf;
unsigned Length;
std::string ModuleID;
BCDecompressor_t *Decompressor;
bool MustDelete;
BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
void operator=(const BytecodeBufferReader &BFR); // Do not implement
public:
BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID, BCDecompressor_t *BCDC,
llvm::BytecodeHandler* Handler = 0);
~BytecodeBufferReader();
bool read(std::string* ErrMsg);
};
}
BytecodeBufferReader::BytecodeBufferReader(const unsigned char *buf,
unsigned len,
const std::string &modID,
BCDecompressor_t *BCDC,
llvm::BytecodeHandler *H)
: BytecodeReader(H), Buffer(0), Buf(buf), Length(len), ModuleID(modID)
, Decompressor(BCDC), MustDelete(false) {
}
BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
bool
BytecodeBufferReader::read(std::string* ErrMsg) {
// If not aligned, allocate a new buffer to hold the bytecode...
const unsigned char *ParseBegin = 0;
if (reinterpret_cast<uint64_t>(Buf) & 3) {
Buffer = new unsigned char[Length+4];
unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
ParseBegin = Buffer + Offset;
memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
MustDelete = true;
} else {
// If we don't need to copy it over, just use the caller's copy
ParseBegin = Buffer = Buf;
MustDelete = false;
}
if (ParseBytecode(ParseBegin, Length, ModuleID, Decompressor, ErrMsg)) {
if (MustDelete) delete [] Buffer;
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
///
class BytecodeStdinReader : public BytecodeReader {
private:
std::vector<unsigned char> FileData;
BCDecompressor_t *Decompressor;
unsigned char *FileBuf;
BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
void operator=(const BytecodeStdinReader &BFR); // Do not implement
public:
BytecodeStdinReader(BCDecompressor_t *BCDC, llvm::BytecodeHandler* H = 0);
bool read(std::string* ErrMsg);
};
}
BytecodeStdinReader::BytecodeStdinReader(BCDecompressor_t *BCDC,
BytecodeHandler* H)
: BytecodeReader(H), Decompressor(BCDC) {
}
bool BytecodeStdinReader::read(std::string* ErrMsg) {
sys::Program::ChangeStdinToBinary();
char Buffer[4096*4];
// Read in all of the data from stdin, we cannot mmap stdin...
while (cin.stream()->good()) {
cin.stream()->read(Buffer, 4096*4);
int BlockSize = cin.stream()->gcount();
if (0 >= BlockSize)
break;
FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
}
if (FileData.empty()) {
if (ErrMsg)
*ErrMsg = "Standard Input is empty!";
return true;
}
FileBuf = &FileData[0];
if (ParseBytecode(FileBuf, FileData.size(), "<stdin>", Decompressor, ErrMsg))
return true;
return false;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
unsigned Length,
const std::string &ModuleID,
BCDecompressor_t *BCDC,
std::string *ErrMsg,
BytecodeHandler *H) {
BytecodeBufferReader *rdr =
new BytecodeBufferReader(Buffer, Length, ModuleID, BCDC, H);
if (rdr->read(ErrMsg))
return 0;
return rdr;
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID,
BCDecompressor_t *BCDC,
std::string *ErrMsg) {
ModuleProvider *MP =
getBytecodeBufferModuleProvider(Buffer, Length, ModuleID, BCDC, ErrMsg, 0);
if (!MP) return 0;
Module *M = MP->releaseModule(ErrMsg);
delete MP;
return M;
}
/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *
llvm::getBytecodeModuleProvider(const std::string &Filename,
BCDecompressor_t *BCDC,
std::string* ErrMsg,
BytecodeHandler* H) {
// Read from a file
if (Filename != std::string("-")) {
BytecodeFileReader *rdr = new BytecodeFileReader(Filename, BCDC, H);
if (rdr->read(ErrMsg))
return 0;
return rdr;
}
// Read from stdin
BytecodeStdinReader *rdr = new BytecodeStdinReader(BCDC, H);
if (rdr->read(ErrMsg))
return 0;
return rdr;
}
/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
BCDecompressor_t *BCDC,
std::string *ErrMsg) {
ModuleProvider* MP = getBytecodeModuleProvider(Filename, BCDC, ErrMsg);
if (!MP) return 0;
Module *M = MP->releaseModule(ErrMsg);
delete MP;
return M;
}