blob: 5e7a439d7d1032bd23c3d8f4422b54ee7c08b276 [file] [log] [blame]
Reid Spencerf4ec6382004-06-29 23:31:01 +00001//===-- Reader.h - Interface To Bytecode Reading ----------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header file defines the interface to the Bytecode Reader which is
11// responsible for correctly interpreting bytecode files (backwards compatible)
12// and materializing a module from the bytecode read.
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef BYTECODE_PARSER_H
17#define BYTECODE_PARSER_H
18
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/GlobalValue.h"
22#include "llvm/Function.h"
23#include "llvm/ModuleProvider.h"
Reid Spencere6c95492004-07-04 11:04:56 +000024#include "llvm/Bytecode/Analyzer.h"
Reid Spencerf4ec6382004-06-29 23:31:01 +000025#include <utility>
26#include <map>
27
28namespace llvm {
29
30class BytecodeHandler; ///< Forward declare the handler interface
31
32/// This class defines the interface for parsing a buffer of bytecode. The
33/// parser itself takes no action except to call the various functions of
34/// the handler interface. The parser's sole responsibility is the correct
35/// interpretation of the bytecode buffer. The handler is responsible for
36/// instantiating and keeping track of all values. As a convenience, the parser
37/// is responsible for materializing types and will pass them through the
38/// handler interface as necessary.
39/// @see BytecodeHandler
40/// @brief Bytecode Reader interface
41class BytecodeReader : public ModuleProvider {
42
43/// @name Constructors
44/// @{
45public:
46 /// @brief Default constructor. By default, no handler is used.
47 BytecodeReader(
48 BytecodeHandler* h = 0
49 ) {
50 Handler = h;
51 }
52
53 ~BytecodeReader() { freeState(); }
54
55/// @}
56/// @name Types
57/// @{
58public:
Reid Spencerb2bdb942004-07-25 18:07:36 +000059
Reid Spencerf4ec6382004-06-29 23:31:01 +000060 /// @brief A convenience type for the buffer pointer
61 typedef const unsigned char* BufPtr;
62
63 /// @brief The type used for a vector of potentially abstract types
64 typedef std::vector<PATypeHolder> TypeListTy;
65
66 /// This type provides a vector of Value* via the User class for
67 /// storage of Values that have been constructed when reading the
68 /// bytecode. Because of forward referencing, constant replacement
69 /// can occur so we ensure that our list of Value* is updated
70 /// properly through those transitions. This ensures that the
71 /// correct Value* is in our list when it comes time to associate
72 /// constants with global variables at the end of reading the
73 /// globals section.
74 /// @brief A list of values as a User of those Values.
75 struct ValueList : public User {
Reid Spencer1d8d08f2004-07-18 00:13:12 +000076 ValueList() : User(Type::VoidTy, Value::ValueListVal) {}
Reid Spencerf4ec6382004-06-29 23:31:01 +000077
78 // vector compatibility methods
79 unsigned size() const { return getNumOperands(); }
80 void push_back(Value *V) { Operands.push_back(Use(V, this)); }
81 Value *back() const { return Operands.back(); }
82 void pop_back() { Operands.pop_back(); }
83 bool empty() const { return Operands.empty(); }
84 // must override this
85 virtual void print(std::ostream& os) const {
86 for ( unsigned i = 0; i < size(); i++ ) {
Reid Spencere6c95492004-07-04 11:04:56 +000087 os << i << " ";
88 getOperand(i)->print(os);
89 os << "\n";
Reid Spencerf4ec6382004-06-29 23:31:01 +000090 }
91 }
92 };
93
94 /// @brief A 2 dimensional table of values
95 typedef std::vector<ValueList*> ValueTable;
96
97 /// This map is needed so that forward references to constants can be looked
98 /// up by Type and slot number when resolving those references.
99 /// @brief A mapping of a Type/slot pair to a Constant*.
100 typedef std::map<std::pair<const Type*,unsigned>, Constant*> ConstantRefsType;
101
102 /// For lazy read-in of functions, we need to save the location in the
103 /// data stream where the function is located. This structure provides that
104 /// information. Lazy read-in is used mostly by the JIT which only wants to
105 /// resolve functions as it needs them.
106 /// @brief Keeps pointers to function contents for later use.
107 struct LazyFunctionInfo {
108 const unsigned char *Buf, *EndBuf;
109 LazyFunctionInfo(const unsigned char *B = 0, const unsigned char *EB = 0)
110 : Buf(B), EndBuf(EB) {}
111 };
112
113 /// @brief A mapping of functions to their LazyFunctionInfo for lazy reading.
114 typedef std::map<Function*, LazyFunctionInfo> LazyFunctionMap;
115
116 /// @brief A list of global variables and the slot number that initializes
117 /// them.
118 typedef std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitsList;
119
120 /// This type maps a typeslot/valueslot pair to the corresponding Value*.
121 /// It is used for dealing with forward references as values are read in.
122 /// @brief A map for dealing with forward references of values.
123 typedef std::map<std::pair<unsigned,unsigned>,Value*> ForwardReferenceMap;
124
125/// @}
126/// @name Methods
127/// @{
128public:
Reid Spencerf4ec6382004-06-29 23:31:01 +0000129 /// @brief Main interface to parsing a bytecode buffer.
130 void ParseBytecode(
Reid Spencer02b67082004-07-05 00:57:50 +0000131 const unsigned char *Buf, ///< Beginning of the bytecode buffer
132 unsigned Length, ///< Length of the bytecode buffer
133 const std::string &ModuleID, ///< An identifier for the module constructed.
134 bool processFunctions=false ///< Process all function bodies fully.
Reid Spencerf4ec6382004-06-29 23:31:01 +0000135 );
136
Reid Spencerf4ec6382004-06-29 23:31:01 +0000137 /// @brief Parse all function bodies
Reid Spencere6c95492004-07-04 11:04:56 +0000138 void ParseAllFunctionBodies();
Reid Spencerf4ec6382004-06-29 23:31:01 +0000139
Reid Spencerf4ec6382004-06-29 23:31:01 +0000140 /// @brief Parse the next function of specific type
Reid Spencere6c95492004-07-04 11:04:56 +0000141 void ParseFunction(Function* Func) ;
Reid Spencerf4ec6382004-06-29 23:31:01 +0000142
143 /// This method is abstract in the parent ModuleProvider class. Its
144 /// implementation is identical to the ParseFunction method.
145 /// @see ParseFunction
146 /// @brief Make a specific function materialize.
147 virtual void materializeFunction(Function *F) {
148 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(F);
149 if (Fi == LazyFunctionLoadMap.end()) return;
150 ParseFunction(F);
151 }
152
153 /// This method is abstract in the parent ModuleProvider class. Its
154 /// implementation is identical to ParseAllFunctionBodies.
155 /// @see ParseAllFunctionBodies
156 /// @brief Make the whole module materialize
157 virtual Module* materializeModule() {
158 ParseAllFunctionBodies();
159 return TheModule;
160 }
161
162 /// This method is provided by the parent ModuleProvde class and overriden
163 /// here. It simply releases the module from its provided and frees up our
164 /// state.
165 /// @brief Release our hold on the generated module
166 Module* releaseModule() {
167 // Since we're losing control of this Module, we must hand it back complete
168 Module *M = ModuleProvider::releaseModule();
169 freeState();
170 return M;
171 }
172
173/// @}
174/// @name Parsing Units For Subclasses
175/// @{
176protected:
177 /// @brief Parse whole module scope
178 void ParseModule();
179
180 /// @brief Parse the version information block
181 void ParseVersionInfo();
182
183 /// @brief Parse the ModuleGlobalInfo block
184 void ParseModuleGlobalInfo();
185
186 /// @brief Parse a symbol table
187 void ParseSymbolTable( Function* Func, SymbolTable *ST);
188
Reid Spencerf4ec6382004-06-29 23:31:01 +0000189 /// @brief Parse functions lazily.
190 void ParseFunctionLazily();
191
192 /// @brief Parse a function body
193 void ParseFunctionBody(Function* Func);
194
Reid Spencere6c95492004-07-04 11:04:56 +0000195 /// @brief Parse the type list portion of a compaction table
Chris Lattnercd843962004-08-03 23:41:28 +0000196 void ParseCompactionTypes(unsigned NumEntries);
Reid Spencere6c95492004-07-04 11:04:56 +0000197
Reid Spencerf4ec6382004-06-29 23:31:01 +0000198 /// @brief Parse a compaction table
199 void ParseCompactionTable();
200
201 /// @brief Parse global types
202 void ParseGlobalTypes();
203
Reid Spencerf4ec6382004-06-29 23:31:01 +0000204 /// @brief Parse a basic block (for LLVM 1.0 basic block blocks)
205 BasicBlock* ParseBasicBlock(unsigned BlockNo);
206
Reid Spencerf4ec6382004-06-29 23:31:01 +0000207 /// @brief parse an instruction list (for post LLVM 1.0 instruction lists
208 /// with blocks differentiated by terminating instructions.
209 unsigned ParseInstructionList(
210 Function* F ///< The function into which BBs will be inserted
211 );
212
Reid Spencerf4ec6382004-06-29 23:31:01 +0000213 /// @brief Parse a single instruction.
214 void ParseInstruction(
215 std::vector<unsigned>& Args, ///< The arguments to be filled in
216 BasicBlock* BB ///< The BB the instruction goes in
217 );
218
219 /// @brief Parse the whole constant pool
Reid Spencere6c95492004-07-04 11:04:56 +0000220 void ParseConstantPool(ValueTable& Values, TypeListTy& Types,
221 bool isFunction);
Reid Spencerf4ec6382004-06-29 23:31:01 +0000222
223 /// @brief Parse a single constant value
224 Constant* ParseConstantValue(unsigned TypeID);
225
226 /// @brief Parse a block of types constants
Reid Spencerdb3bf192004-07-11 17:24:05 +0000227 void ParseTypes(TypeListTy &Tab, unsigned NumEntries);
Reid Spencerf4ec6382004-06-29 23:31:01 +0000228
229 /// @brief Parse a single type constant
Reid Spencerdb3bf192004-07-11 17:24:05 +0000230 const Type *ParseType();
Reid Spencerf4ec6382004-06-29 23:31:01 +0000231
232 /// @brief Parse a string constants block
233 void ParseStringConstants(unsigned NumEntries, ValueTable &Tab);
234
235/// @}
236/// @name Data
237/// @{
238private:
239 BufPtr MemStart; ///< Start of the memory buffer
240 BufPtr MemEnd; ///< End of the memory buffer
241 BufPtr BlockStart; ///< Start of current block being parsed
242 BufPtr BlockEnd; ///< End of current block being parsed
243 BufPtr At; ///< Where we're currently parsing at
244
Reid Spencere6c95492004-07-04 11:04:56 +0000245 /// Information about the module, extracted from the bytecode revision number.
Chris Lattnercd843962004-08-03 23:41:28 +0000246 ///
Reid Spencerf4ec6382004-06-29 23:31:01 +0000247 unsigned char RevisionNum; // The rev # itself
248
Reid Spencere6c95492004-07-04 11:04:56 +0000249 /// Flags to distinguish LLVM 1.0 & 1.1 bytecode formats (revision #0)
Reid Spencerf4ec6382004-06-29 23:31:01 +0000250
Chris Lattnercd843962004-08-03 23:41:28 +0000251 /// Revision #0 had an explicit alignment of data only for the
252 /// ModuleGlobalInfo block. This was fixed to be like all other blocks in 1.2
Reid Spencerf4ec6382004-06-29 23:31:01 +0000253 bool hasInconsistentModuleGlobalInfo;
254
Reid Spencere6c95492004-07-04 11:04:56 +0000255 /// Revision #0 also explicitly encoded zero values for primitive types like
256 /// int/sbyte/etc.
Reid Spencerf4ec6382004-06-29 23:31:01 +0000257 bool hasExplicitPrimitiveZeros;
258
259 // Flags to control features specific the LLVM 1.2 and before (revision #1)
260
Reid Spencere6c95492004-07-04 11:04:56 +0000261 /// LLVM 1.2 and earlier required that getelementptr structure indices were
262 /// ubyte constants and that sequential type indices were longs.
Reid Spencerf4ec6382004-06-29 23:31:01 +0000263 bool hasRestrictedGEPTypes;
264
Reid Spencere6c95492004-07-04 11:04:56 +0000265 /// LLVM 1.2 and earlier had class Type deriving from Value and the Type
266 /// objects were located in the "Type Type" plane of various lists in read
267 /// by the bytecode reader. In LLVM 1.3 this is no longer the case. Types are
268 /// completely distinct from Values. Consequently, Types are written in fixed
269 /// locations in LLVM 1.3. This flag indicates that the older Type derived
270 /// from Value style of bytecode file is being read.
271 bool hasTypeDerivedFromValue;
272
Reid Spencerb2bdb942004-07-25 18:07:36 +0000273 /// LLVM 1.2 and earlier encoded block headers as two uint (8 bytes), one for
Chris Lattnercd843962004-08-03 23:41:28 +0000274 /// the size and one for the type. This is a bit wasteful, especially for
275 /// small files where the 8 bytes per block is a large fraction of the total
276 /// block size. In LLVM 1.3, the block type and length are encoded into a
277 /// single uint32 by restricting the number of block types (limit 31) and the
278 /// maximum size of a block (limit 2^27-1=134,217,727). Note that the module
279 /// block still uses the 8-byte format so the maximum size of a file can be
Reid Spencerb2bdb942004-07-25 18:07:36 +0000280 /// 2^32-1 bytes long.
281 bool hasLongBlockHeaders;
282
Reid Spencerb2bdb942004-07-25 18:07:36 +0000283 /// LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
284 /// this has been reduced to vbr_uint24. It shouldn't make much difference
285 /// since we haven't run into a module with > 24 million types, but for safety
286 /// the 24-bit restriction has been enforced in 1.3 to free some bits in
287 /// various places and to ensure consistency. In particular, global vars are
288 /// restricted to 24-bits.
289 bool has32BitTypes;
290
291 /// LLVM 1.2 and earlier did not provide a target triple nor a list of
292 /// libraries on which the bytecode is dependent. LLVM 1.3 provides these
293 /// features, for use in future versions of LLVM.
294 bool hasNoDependentLibraries;
295
Reid Spencerc3e43642004-08-17 07:45:14 +0000296 /// LLVM 1.3 and earlier caused blocks and other fields to start on 32-bit
297 /// aligned boundaries. This can lead to as much as 30% bytecode size overhead
298 /// in various corner cases (lots of long instructions). In LLVM 1.4,
299 /// alignment of bytecode fields was done away with completely.
300 bool hasAlignment;
Reid Spencerb2bdb942004-07-25 18:07:36 +0000301
Chris Lattnercd843962004-08-03 23:41:28 +0000302 /// CompactionTypes - If a compaction table is active in the current function,
303 /// this is the mapping that it contains. We keep track of what resolved type
304 /// it is as well as what global type entry it is.
305 std::vector<std::pair<const Type*, unsigned> > CompactionTypes;
Reid Spencerf4ec6382004-06-29 23:31:01 +0000306
307 /// @brief If a compaction table is active in the current function,
308 /// this is the mapping that it contains.
309 std::vector<std::vector<Value*> > CompactionValues;
310
311 /// @brief This vector is used to deal with forward references to types in
312 /// a module.
313 TypeListTy ModuleTypes;
314
315 /// @brief This vector is used to deal with forward references to types in
316 /// a function.
317 TypeListTy FunctionTypes;
318
319 /// When the ModuleGlobalInfo section is read, we create a Function object
320 /// for each function in the module. When the function is loaded, after the
321 /// module global info is read, this Function is populated. Until then, the
322 /// functions in this vector just hold the function signature.
323 std::vector<Function*> FunctionSignatureList;
324
325 /// @brief This is the table of values belonging to the current function
326 ValueTable FunctionValues;
327
328 /// @brief This is the table of values belonging to the module (global)
329 ValueTable ModuleValues;
330
331 /// @brief This keeps track of function level forward references.
332 ForwardReferenceMap ForwardReferences;
333
334 /// @brief The basic blocks we've parsed, while parsing a function.
335 std::vector<BasicBlock*> ParsedBasicBlocks;
336
337 /// This maintains a mapping between <Type, Slot #>'s and
338 /// forward references to constants. Such values may be referenced before they
339 /// are defined, and if so, the temporary object that they represent is held
340 /// here.
341 /// @brief Temporary place for forward references to constants.
342 ConstantRefsType ConstantFwdRefs;
343
344 /// Constant values are read in after global variables. Because of this, we
345 /// must defer setting the initializers on global variables until after module
346 /// level constants have been read. In the mean time, this list keeps track of
347 /// what we must do.
348 GlobalInitsList GlobalInits;
349
350 // For lazy reading-in of functions, we need to save away several pieces of
351 // information about each function: its begin and end pointer in the buffer
352 // and its FunctionSlot.
353 LazyFunctionMap LazyFunctionLoadMap;
354
355 /// This stores the parser's handler which is used for handling tasks other
356 /// just than reading bytecode into the IR. If this is non-null, calls on
357 /// the (polymorphic) BytecodeHandler interface (see llvm/Bytecode/Handler.h)
358 /// will be made to report the logical structure of the bytecode file. What
359 /// the handler does with the events it receives is completely orthogonal to
360 /// the business of parsing the bytecode and building the IR. This is used,
361 /// for example, by the llvm-abcd tool for analysis of byte code.
362 /// @brief Handler for parsing events.
363 BytecodeHandler* Handler;
364
365/// @}
366/// @name Implementation Details
367/// @{
368private:
369 /// @brief Determines if this module has a function or not.
370 bool hasFunctions() { return ! FunctionSignatureList.empty(); }
371
372 /// @brief Determines if the type id has an implicit null value.
373 bool hasImplicitNull(unsigned TyID );
374
375 /// @brief Converts a type slot number to its Type*
376 const Type *getType(unsigned ID);
377
Reid Spencere6c95492004-07-04 11:04:56 +0000378 /// @brief Converts a pre-sanitized type slot number to its Type* and
379 /// sanitizes the type id.
380 inline const Type* getSanitizedType(unsigned& ID );
381
382 /// @brief Read in and get a sanitized type id
383 inline const Type* BytecodeReader::readSanitizedType();
384
Reid Spencerf4ec6382004-06-29 23:31:01 +0000385 /// @brief Converts a Type* to its type slot number
386 unsigned getTypeSlot(const Type *Ty);
387
388 /// @brief Converts a normal type slot number to a compacted type slot num.
389 unsigned getCompactionTypeSlot(unsigned type);
390
Reid Spencere6c95492004-07-04 11:04:56 +0000391 /// @brief Gets the global type corresponding to the TypeId
392 const Type *getGlobalTableType(unsigned TypeId);
Reid Spencerf4ec6382004-06-29 23:31:01 +0000393
394 /// This is just like getTypeSlot, but when a compaction table is in use,
395 /// it is ignored.
396 unsigned getGlobalTableTypeSlot(const Type *Ty);
397
Reid Spencere6c95492004-07-04 11:04:56 +0000398 /// @brief Get a value from its typeid and slot number
Reid Spencerf4ec6382004-06-29 23:31:01 +0000399 Value* getValue(unsigned TypeID, unsigned num, bool Create = true);
400
Chris Lattnerbba09b32004-08-04 00:19:23 +0000401 /// @brief Get a value from its type and slot number, ignoring compaction
402 /// tables.
403 Value *getGlobalTableValue(unsigned TyID, unsigned SlotNo);
Reid Spencerf4ec6382004-06-29 23:31:01 +0000404
Reid Spencerf4ec6382004-06-29 23:31:01 +0000405 /// @brief Get a basic block for current function
406 BasicBlock *getBasicBlock(unsigned ID);
407
Reid Spencere6c95492004-07-04 11:04:56 +0000408 /// @brief Get a constant value from its typeid and value slot.
Reid Spencerf4ec6382004-06-29 23:31:01 +0000409 Constant* getConstantValue(unsigned typeSlot, unsigned valSlot);
410
411 /// @brief Convenience function for getting a constant value when
412 /// the Type has already been resolved.
413 Constant* getConstantValue(const Type *Ty, unsigned valSlot) {
414 return getConstantValue(getTypeSlot(Ty), valSlot);
415 }
416
Reid Spencerf4ec6382004-06-29 23:31:01 +0000417 /// @brief Insert a newly created value
418 unsigned insertValue(Value *V, unsigned Type, ValueTable &Table);
419
420 /// @brief Insert the arguments of a function.
421 void insertArguments(Function* F );
422
423 /// @brief Resolve all references to the placeholder (if any) for the
424 /// given constant.
425 void ResolveReferencesToConstant(Constant *C, unsigned Slot);
426
427 /// @brief Release our memory.
428 void freeState() {
429 freeTable(FunctionValues);
430 freeTable(ModuleValues);
431 }
432
433 /// @brief Free a table, making sure to free the ValueList in the table.
434 void freeTable(ValueTable &Tab) {
435 while (!Tab.empty()) {
436 delete Tab.back();
437 Tab.pop_back();
438 }
439 }
440
Reid Spencerf3905c82004-07-09 22:21:33 +0000441 inline void error(std::string errmsg);
442
Reid Spencerf4ec6382004-06-29 23:31:01 +0000443 BytecodeReader(const BytecodeReader &); // DO NOT IMPLEMENT
444 void operator=(const BytecodeReader &); // DO NOT IMPLEMENT
445
446/// @}
447/// @name Reader Primitives
448/// @{
449private:
450
451 /// @brief Is there more to parse in the current block?
452 inline bool moreInBlock();
453
454 /// @brief Have we read past the end of the block
455 inline void checkPastBlockEnd(const char * block_name);
456
457 /// @brief Align to 32 bits
458 inline void align32();
459
460 /// @brief Read an unsigned integer as 32-bits
461 inline unsigned read_uint();
462
463 /// @brief Read an unsigned integer with variable bit rate encoding
464 inline unsigned read_vbr_uint();
465
Reid Spencerb2bdb942004-07-25 18:07:36 +0000466 /// @brief Read an unsigned integer of no more than 24-bits with variable
467 /// bit rate encoding.
468 inline unsigned read_vbr_uint24();
469
Reid Spencerf4ec6382004-06-29 23:31:01 +0000470 /// @brief Read an unsigned 64-bit integer with variable bit rate encoding.
471 inline uint64_t read_vbr_uint64();
472
473 /// @brief Read a signed 64-bit integer with variable bit rate encoding.
474 inline int64_t read_vbr_int64();
475
476 /// @brief Read a string
477 inline std::string read_str();
478
Reid Spencerdb3bf192004-07-11 17:24:05 +0000479 /// @brief Read a float value
480 inline void read_float(float& FloatVal);
481
482 /// @brief Read a double value
483 inline void read_double(double& DoubleVal);
484
Reid Spencerf4ec6382004-06-29 23:31:01 +0000485 /// @brief Read an arbitrary data chunk of fixed length
486 inline void read_data(void *Ptr, void *End);
487
Reid Spencere6c95492004-07-04 11:04:56 +0000488 /// @brief Read a bytecode block header
Reid Spencerf4ec6382004-06-29 23:31:01 +0000489 inline void read_block(unsigned &Type, unsigned &Size);
490
Reid Spencere6c95492004-07-04 11:04:56 +0000491 /// @brief Read a type identifier and sanitize it.
492 inline bool read_typeid(unsigned &TypeId);
493
494 /// @brief Recalculate type ID for pre 1.3 bytecode files.
495 inline bool sanitizeTypeId(unsigned &TypeId );
Reid Spencerf4ec6382004-06-29 23:31:01 +0000496/// @}
497};
498
Reid Spencere6c95492004-07-04 11:04:56 +0000499/// @brief A function for creating a BytecodeAnalzer as a handler
500/// for the Bytecode reader.
501BytecodeHandler* createBytecodeAnalyzerHandler(BytecodeAnalysis& bca );
502
503
Reid Spencerf4ec6382004-06-29 23:31:01 +0000504} // End llvm namespace
505
506// vim: sw=2
507#endif