LLVM API Documentation

Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | Directories | File List | Namespace Members | Class Members | File Members | Related Pages

lib/Bytecode/Reader/Reader.h

Go to the documentation of this file.
00001 //===-- Reader.h - Interface To Bytecode Reading ----------------*- C++ -*-===//
00002 // 
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by Reid Spencer and is distributed under the 
00006 // University of Illinois Open Source License. See LICENSE.TXT for details.
00007 // 
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This header file defines the interface to the Bytecode Reader which is 
00011 //  responsible for correctly interpreting bytecode files (backwards compatible)
00012 //  and materializing a module from the bytecode read.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #ifndef BYTECODE_PARSER_H
00017 #define BYTECODE_PARSER_H
00018 
00019 #include "llvm/Constants.h"
00020 #include "llvm/DerivedTypes.h"
00021 #include "llvm/GlobalValue.h"
00022 #include "llvm/Function.h"
00023 #include "llvm/ModuleProvider.h"
00024 #include "llvm/Bytecode/Analyzer.h"
00025 #include <utility>
00026 #include <map>
00027 
00028 namespace llvm {
00029 
00030 class BytecodeHandler; ///< Forward declare the handler interface
00031 
00032 /// This class defines the interface for parsing a buffer of bytecode. The
00033 /// parser itself takes no action except to call the various functions of
00034 /// the handler interface. The parser's sole responsibility is the correct
00035 /// interpretation of the bytecode buffer. The handler is responsible for 
00036 /// instantiating and keeping track of all values. As a convenience, the parser 
00037 /// is responsible for materializing types and will pass them through the
00038 /// handler interface as necessary.
00039 /// @see BytecodeHandler
00040 /// @brief Bytecode Reader interface
00041 class BytecodeReader : public ModuleProvider {
00042 
00043 /// @name Constructors
00044 /// @{
00045 public:
00046   /// @brief Default constructor. By default, no handler is used.
00047   BytecodeReader(BytecodeHandler* h = 0) { 
00048     decompressedBlock = 0;
00049     Handler = h;
00050   }
00051 
00052   ~BytecodeReader() { 
00053     freeState(); 
00054     if (decompressedBlock) {
00055       ::free(decompressedBlock);
00056       decompressedBlock = 0;
00057     }
00058   }
00059 
00060 /// @}
00061 /// @name Types
00062 /// @{
00063 public:
00064 
00065   /// @brief A convenience type for the buffer pointer
00066   typedef const unsigned char* BufPtr;
00067 
00068   /// @brief The type used for a vector of potentially abstract types
00069   typedef std::vector<PATypeHolder> TypeListTy;
00070 
00071   /// This type provides a vector of Value* via the User class for
00072   /// storage of Values that have been constructed when reading the
00073   /// bytecode. Because of forward referencing, constant replacement
00074   /// can occur so we ensure that our list of Value* is updated
00075   /// properly through those transitions. This ensures that the
00076   /// correct Value* is in our list when it comes time to associate
00077   /// constants with global variables at the end of reading the
00078   /// globals section.
00079   /// @brief A list of values as a User of those Values.
00080   struct ValueList : public User {
00081     ValueList() : User(Type::VoidTy, Value::ValueListVal) {}
00082 
00083     // vector compatibility methods
00084     unsigned size() const { return getNumOperands(); }
00085     void push_back(Value *V) { Operands.push_back(Use(V, this)); }
00086     Value *back() const { return Operands.back(); }
00087     void pop_back() { Operands.pop_back(); }
00088     bool empty() const { return Operands.empty(); }
00089     // must override this 
00090     virtual void print(std::ostream& os) const {
00091       for ( unsigned i = 0; i < size(); i++ ) {
00092         os << i << " ";
00093         getOperand(i)->print(os);
00094         os << "\n";
00095       }
00096     }
00097   };
00098 
00099   /// @brief A 2 dimensional table of values
00100   typedef std::vector<ValueList*> ValueTable;
00101 
00102   /// This map is needed so that forward references to constants can be looked 
00103   /// up by Type and slot number when resolving those references.
00104   /// @brief A mapping of a Type/slot pair to a Constant*.
00105   typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
00106 
00107   /// For lazy read-in of functions, we need to save the location in the
00108   /// data stream where the function is located. This structure provides that
00109   /// information. Lazy read-in is used mostly by the JIT which only wants to
00110   /// resolve functions as it needs them. 
00111   /// @brief Keeps pointers to function contents for later use.
00112   struct LazyFunctionInfo {
00113     const unsigned char *Buf, *EndBuf;
00114     LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
00115       : Buf(B), EndBuf(EB) {}
00116   };
00117 
00118   /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
00119   typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
00120 
00121   /// @brief A list of global variables and the slot number that initializes
00122   /// them.
00123   typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
00124 
00125   /// This type maps a typeslot/valueslot pair to the corresponding Value*.
00126   /// It is used for dealing with forward references as values are read in.
00127   /// @brief A map for dealing with forward references of values.
00128   typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
00129 
00130 /// @}
00131 /// @name Methods
00132 /// @{
00133 public:
00134   /// @brief Main interface to parsing a bytecode buffer.
00135   void ParseBytecode(
00136      const unsigned char *Buf,    ///< Beginning of the bytecode buffer
00137      unsigned Length,             ///< Length of the bytecode buffer
00138      const std::string &ModuleID  ///< An identifier for the module constructed.
00139   );
00140 
00141   /// @brief Parse all function bodies
00142   void ParseAllFunctionBodies();
00143 
00144   /// @brief Parse the next function of specific type
00145   void ParseFunction(Function* Func) ;
00146 
00147   /// This method is abstract in the parent ModuleProvider class. Its
00148   /// implementation is identical to the ParseFunction method.
00149   /// @see ParseFunction
00150   /// @brief Make a specific function materialize.
00151   virtual void materializeFunction(Function *F) {
00152     LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
00153     if (Fi == LazyFunctionLoadMap.end()) return;
00154     ParseFunction(F);
00155   }
00156 
00157   /// This method is abstract in the parent ModuleProvider class. Its
00158   /// implementation is identical to ParseAllFunctionBodies. 
00159   /// @see ParseAllFunctionBodies
00160   /// @brief Make the whole module materialize
00161   virtual Module* materializeModule() {
00162     ParseAllFunctionBodies();
00163     return TheModule;
00164   }
00165 
00166   /// This method is provided by the parent ModuleProvde class and overriden
00167   /// here. It simply releases the module from its provided and frees up our
00168   /// state.
00169   /// @brief Release our hold on the generated module
00170   Module* releaseModule() {
00171     // Since we're losing control of this Module, we must hand it back complete
00172     Module *M = ModuleProvider::releaseModule();
00173     freeState();
00174     return M;
00175   }
00176 
00177 /// @}
00178 /// @name Parsing Units For Subclasses
00179 /// @{
00180 protected:
00181   /// @brief Parse whole module scope
00182   void ParseModule();
00183 
00184   /// @brief Parse the version information block
00185   void ParseVersionInfo();
00186 
00187   /// @brief Parse the ModuleGlobalInfo block
00188   void ParseModuleGlobalInfo();
00189 
00190   /// @brief Parse a symbol table
00191   void ParseSymbolTable( Function* Func, SymbolTable *ST);
00192 
00193   /// @brief Parse functions lazily.
00194   void ParseFunctionLazily();
00195 
00196   ///  @brief Parse a function body
00197   void ParseFunctionBody(Function* Func);
00198 
00199   /// @brief Parse the type list portion of a compaction table
00200   void ParseCompactionTypes(unsigned NumEntries);
00201 
00202   /// @brief Parse a compaction table
00203   void ParseCompactionTable();
00204 
00205   /// @brief Parse global types
00206   void ParseGlobalTypes();
00207 
00208   /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
00209   BasicBlock* ParseBasicBlock(unsigned BlockNo);
00210 
00211   /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
00212   /// with blocks differentiated by terminating instructions.
00213   unsigned ParseInstructionList(
00214     Function* F   ///< The function into which BBs will be inserted
00215   );
00216   
00217   /// @brief Parse a single instruction.
00218   void ParseInstruction(
00219     std::vector<unsigned>& Args,   ///< The arguments to be filled in
00220     BasicBlock* BB             ///< The BB the instruction goes in
00221   );
00222 
00223   /// @brief Parse the whole constant pool
00224   void ParseConstantPool(ValueTable& Values, TypeListTy& Types, 
00225                          bool isFunction);
00226 
00227   /// @brief Parse a single constant value
00228   Constant* ParseConstantValue(unsigned TypeID);
00229 
00230   /// @brief Parse a block of types constants
00231   void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
00232 
00233   /// @brief Parse a single type constant
00234   const Type *ParseType();
00235 
00236   /// @brief Parse a string constants block
00237   void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
00238 
00239 /// @}
00240 /// @name Data
00241 /// @{
00242 private:
00243   char*  decompressedBlock; ///< Result of decompression 
00244   BufPtr MemStart;     ///< Start of the memory buffer
00245   BufPtr MemEnd;       ///< End of the memory buffer
00246   BufPtr BlockStart;   ///< Start of current block being parsed
00247   BufPtr BlockEnd;     ///< End of current block being parsed
00248   BufPtr At;           ///< Where we're currently parsing at
00249 
00250   /// Information about the module, extracted from the bytecode revision number.
00251   ///
00252   unsigned char RevisionNum;        // The rev # itself
00253 
00254   /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
00255 
00256   /// Revision #0 had an explicit alignment of data only for the
00257   /// ModuleGlobalInfo block.  This was fixed to be like all other blocks in 1.2
00258   bool hasInconsistentModuleGlobalInfo;
00259 
00260   /// Revision #0 also explicitly encoded zero values for primitive types like
00261   /// int/sbyte/etc.
00262   bool hasExplicitPrimitiveZeros;
00263 
00264   // Flags to control features specific the LLVM 1.2 and before (revision #1)
00265 
00266   /// LLVM 1.2 and earlier required that getelementptr structure indices were
00267   /// ubyte constants and that sequential type indices were longs.
00268   bool hasRestrictedGEPTypes;
00269 
00270   /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
00271   /// objects were located in the "Type Type" plane of various lists in read
00272   /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
00273   /// completely distinct from Values. Consequently, Types are written in fixed
00274   /// locations in LLVM 1.3. This flag indicates that the older Type derived
00275   /// from Value style of bytecode file is being read.
00276   bool hasTypeDerivedFromValue;
00277 
00278   /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
00279   /// the size and one for the type. This is a bit wasteful, especially for
00280   /// small files where the 8 bytes per block is a large fraction of the total
00281   /// block size. In LLVM 1.3, the block type and length are encoded into a
00282   /// single uint32 by restricting the number of block types (limit 31) and the
00283   /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
00284   /// block still uses the 8-byte format so the maximum size of a file can be
00285   /// 2^32-1 bytes long.
00286   bool hasLongBlockHeaders;
00287 
00288   /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
00289   /// this has been reduced to vbr_uint24. It shouldn't make much difference 
00290   /// since we haven't run into a module with > 24 million types, but for safety
00291   /// the 24-bit restriction has been enforced in 1.3 to free some bits in
00292   /// various places and to ensure consistency. In particular, global vars are
00293   /// restricted to 24-bits.
00294   bool has32BitTypes;
00295 
00296   /// LLVM 1.2 and earlier did not provide a target triple nor a list of 
00297   /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
00298   /// features, for use in future versions of LLVM.
00299   bool hasNoDependentLibraries;
00300 
00301   /// LLVM 1.3 and earlier caused blocks and other fields to start on 32-bit
00302   /// aligned boundaries. This can lead to as much as 30% bytecode size overhead
00303   /// in various corner cases (lots of long instructions). In LLVM 1.4,
00304   /// alignment of bytecode fields was done away with completely.
00305   bool hasAlignment;
00306 
00307   // In version 4 and earlier, the bytecode format did not support the 'undef'
00308   // constant.
00309   bool hasNoUndefValue;
00310 
00311   // In version 4 and earlier, the bytecode format did not save space for flags
00312   // in the global info block for functions.
00313   bool hasNoFlagsForFunctions;
00314 
00315   // In version 4 and earlier, there was no opcode space reserved for the
00316   // unreachable instruction.
00317   bool hasNoUnreachableInst;
00318 
00319   // In version 5, basic blocks have a minimum index of 0 whereas all the 
00320   // other primitives have a minimum index of 1 (because 0 is the "null" 
00321   // value. In version 5, we made this consistent.
00322   bool hasInconsistentBBSlotNums;
00323 
00324   // In version 5, the types SByte and UByte were encoded as vbr_uint so that
00325   // signed values > 63 and unsigned values >127 would be encoded as two
00326   // bytes. In version 5, they are encoded directly in a single byte.
00327   bool hasVBRByteTypes;
00328 
00329   // In version 5, modules begin with a "Module Block" which encodes a 4-byte
00330   // integer value 0x01 to identify the module block. This is unnecessary and
00331   // removed in version 5.
00332   bool hasUnnecessaryModuleBlockId;
00333 
00334   /// CompactionTypes - If a compaction table is active in the current function,
00335   /// this is the mapping that it contains.  We keep track of what resolved type
00336   /// it is as well as what global type entry it is.
00337   std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
00338 
00339   /// @brief If a compaction table is active in the current function,
00340   /// this is the mapping that it contains.
00341   std::vector<std::vector<Value*> > CompactionValues;
00342 
00343   /// @brief This vector is used to deal with forward references to types in
00344   /// a module.
00345   TypeListTy ModuleTypes;
00346 
00347   /// @brief This vector is used to deal with forward references to types in
00348   /// a function.
00349   TypeListTy FunctionTypes;
00350 
00351   /// When the ModuleGlobalInfo section is read, we create a Function object
00352   /// for each function in the module. When the function is loaded, after the
00353   /// module global info is read, this Function is populated. Until then, the
00354   /// functions in this vector just hold the function signature.
00355   std::vector<Function*> FunctionSignatureList;
00356 
00357   /// @brief This is the table of values belonging to the current function
00358   ValueTable FunctionValues;
00359 
00360   /// @brief This is the table of values belonging to the module (global)
00361   ValueTable ModuleValues;
00362 
00363   /// @brief This keeps track of function level forward references.
00364   ForwardReferenceMap ForwardReferences;
00365 
00366   /// @brief The basic blocks we've parsed, while parsing a function.
00367   std::vector<BasicBlock*> ParsedBasicBlocks;
00368 
00369   /// This maintains a mapping between <Type, Slot #>'s and forward references
00370   /// to constants.  Such values may be referenced before they are defined, and
00371   /// if so, the temporary object that they represent is held here.  @brief
00372   /// Temporary place for forward references to constants.
00373   ConstantRefsType ConstantFwdRefs;
00374 
00375   /// Constant values are read in after global variables.  Because of this, we
00376   /// must defer setting the initializers on global variables until after module
00377   /// level constants have been read.  In the mean time, this list keeps track
00378   /// of what we must do.
00379   GlobalInitsList GlobalInits;
00380 
00381   // For lazy reading-in of functions, we need to save away several pieces of
00382   // information about each function: its begin and end pointer in the buffer
00383   // and its FunctionSlot.
00384   LazyFunctionMap LazyFunctionLoadMap;
00385 
00386   /// This stores the parser's handler which is used for handling tasks other 
00387   /// just than reading bytecode into the IR. If this is non-null, calls on 
00388   /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h) 
00389   /// will be made to report the logical structure of the bytecode file. What 
00390   /// the handler does with the events it receives is completely orthogonal to 
00391   /// the business of parsing the bytecode and building the IR.  This is used,
00392   /// for example, by the llvm-abcd tool for analysis of byte code.
00393   /// @brief Handler for parsing events.
00394   BytecodeHandler* Handler;
00395 
00396 /// @}
00397 /// @name Implementation Details
00398 /// @{
00399 private:
00400   /// @brief Determines if this module has a function or not.
00401   bool hasFunctions() { return ! FunctionSignatureList.empty(); }
00402 
00403   /// @brief Determines if the type id has an implicit null value.
00404   bool hasImplicitNull(unsigned TyID );
00405 
00406   /// @brief Converts a type slot number to its Type*
00407   const Type *getType(unsigned ID);
00408 
00409   /// @brief Converts a pre-sanitized type slot number to its Type* and
00410   /// sanitizes the type id.
00411   inline const Type* getSanitizedType(unsigned& ID );
00412 
00413   /// @brief Read in and get a sanitized type id
00414   inline const Type* readSanitizedType();
00415 
00416   /// @brief Converts a Type* to its type slot number
00417   unsigned getTypeSlot(const Type *Ty);
00418 
00419   /// @brief Converts a normal type slot number to a compacted type slot num.
00420   unsigned getCompactionTypeSlot(unsigned type);
00421 
00422   /// @brief Gets the global type corresponding to the TypeId
00423   const Type *getGlobalTableType(unsigned TypeId);
00424 
00425   /// This is just like getTypeSlot, but when a compaction table is in use,
00426   /// it is ignored. 
00427   unsigned getGlobalTableTypeSlot(const Type *Ty);
00428   
00429   /// @brief Get a value from its typeid and slot number
00430   Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
00431 
00432   /// @brief Get a value from its type and slot number, ignoring compaction
00433   /// tables.
00434   Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
00435 
00436   /// @brief Get a basic block for current function
00437   BasicBlock *getBasicBlock(unsigned ID);
00438 
00439   /// @brief Get a constant value from its typeid and value slot.
00440   Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
00441 
00442   /// @brief Convenience function for getting a constant value when
00443   /// the Type has already been resolved.
00444   Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
00445     return getConstantValue(getTypeSlot(Ty), valSlot);
00446   }
00447 
00448   /// @brief Insert a newly created value
00449   unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
00450 
00451   /// @brief Insert the arguments of a function.
00452   void insertArguments(Function* F );
00453 
00454   /// @brief Resolve all references to the placeholder (if any) for the 
00455   /// given constant.
00456   void ResolveReferencesToConstant(Constant *C, unsigned Slot);
00457 
00458   /// @brief Release our memory.
00459   void freeState() {
00460     freeTable(FunctionValues);
00461     freeTable(ModuleValues);
00462   }
00463 
00464   /// @brief Free a table, making sure to free the ValueList in the table.
00465   void freeTable(ValueTable &Tab) {
00466     while (!Tab.empty()) {
00467       delete Tab.back();
00468       Tab.pop_back();
00469     }
00470   }
00471 
00472   inline void error(std::string errmsg);
00473 
00474   BytecodeReader(const BytecodeReader &);  // DO NOT IMPLEMENT
00475   void operator=(const BytecodeReader &);  // DO NOT IMPLEMENT
00476 
00477 /// @}
00478 /// @name Reader Primitives
00479 /// @{
00480 private:
00481 
00482   /// @brief Is there more to parse in the current block?
00483   inline bool moreInBlock();
00484 
00485   /// @brief Have we read past the end of the block
00486   inline void checkPastBlockEnd(const char * block_name);
00487 
00488   /// @brief Align to 32 bits
00489   inline void align32();
00490 
00491   /// @brief Read an unsigned integer as 32-bits
00492   inline unsigned read_uint();
00493 
00494   /// @brief Read an unsigned integer with variable bit rate encoding
00495   inline unsigned read_vbr_uint();
00496 
00497   /// @brief Read an unsigned integer of no more than 24-bits with variable
00498   /// bit rate encoding.
00499   inline unsigned read_vbr_uint24();
00500 
00501   /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
00502   inline uint64_t read_vbr_uint64();
00503 
00504   /// @brief Read a signed 64-bit integer with variable bit rate encoding.
00505   inline int64_t read_vbr_int64();
00506 
00507   /// @brief Read a string
00508   inline std::string read_str();
00509 
00510   /// @brief Read a float value
00511   inline void read_float(float& FloatVal);
00512 
00513   /// @brief Read a double value
00514   inline void read_double(double& DoubleVal);
00515 
00516   /// @brief Read an arbitrary data chunk of fixed length
00517   inline void read_data(void *Ptr, void *End);
00518 
00519   /// @brief Read a bytecode block header
00520   inline void read_block(unsigned &Type, unsigned &Size);
00521 
00522   /// @brief Read a type identifier and sanitize it.
00523   inline bool read_typeid(unsigned &TypeId);
00524 
00525   /// @brief Recalculate type ID for pre 1.3 bytecode files.
00526   inline bool sanitizeTypeId(unsigned &TypeId );
00527 /// @}
00528 };
00529 
00530 /// @brief A function for creating a BytecodeAnalzer as a handler
00531 /// for the Bytecode reader.
00532 BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca, 
00533                                                std::ostream* output );
00534 
00535 
00536 } // End llvm namespace
00537 
00538 // vim: sw=2
00539 #endif