LLVM API Documentation

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