Added bytecode support for the extractelement operation.
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
11 //
12 // Note that this library should be as fast as possible, reentrant, and
13 // threadsafe!!
14 //
15 // TODO: Allow passing in an option to ignore the symbol table
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "Reader.h"
20 #include "llvm/Bytecode/BytecodeHandler.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/SymbolTable.h"
26 #include "llvm/Bytecode/Format.h"
27 #include "llvm/Config/alloca.h"
28 #include "llvm/Support/GetElementPtrTypeIterator.h"
29 #include "llvm/Support/Compressor.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include <sstream>
33 #include <algorithm>
34 using namespace llvm;
35
36 namespace {
37   /// @brief A class for maintaining the slot number definition
38   /// as a placeholder for the actual definition for forward constants defs.
39   class ConstantPlaceHolder : public ConstantExpr {
40     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
41     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
42   public:
43     Use Op;
44     ConstantPlaceHolder(const Type *Ty)
45       : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
46         Op(UndefValue::get(Type::IntTy), this) {
47     }
48   };
49 }
50
51 // Provide some details on error
52 inline void BytecodeReader::error(std::string err) {
53   err +=  " (Vers=" ;
54   err += itostr(RevisionNum) ;
55   err += ", Pos=" ;
56   err += itostr(At-MemStart);
57   err += ")";
58   throw err;
59 }
60
61 //===----------------------------------------------------------------------===//
62 // Bytecode Reading Methods
63 //===----------------------------------------------------------------------===//
64
65 /// Determine if the current block being read contains any more data.
66 inline bool BytecodeReader::moreInBlock() {
67   return At < BlockEnd;
68 }
69
70 /// Throw an error if we've read past the end of the current block
71 inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
72   if (At > BlockEnd)
73     error(std::string("Attempt to read past the end of ") + block_name +
74           " block.");
75 }
76
77 /// Align the buffer position to a 32 bit boundary
78 inline void BytecodeReader::align32() {
79   if (hasAlignment) {
80     BufPtr Save = At;
81     At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
82     if (At > Save)
83       if (Handler) Handler->handleAlignment(At - Save);
84     if (At > BlockEnd)
85       error("Ran out of data while aligning!");
86   }
87 }
88
89 /// Read a whole unsigned integer
90 inline unsigned BytecodeReader::read_uint() {
91   if (At+4 > BlockEnd)
92     error("Ran out of data reading uint!");
93   At += 4;
94   return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
95 }
96
97 /// Read a variable-bit-rate encoded unsigned integer
98 inline unsigned BytecodeReader::read_vbr_uint() {
99   unsigned Shift = 0;
100   unsigned Result = 0;
101   BufPtr Save = At;
102
103   do {
104     if (At == BlockEnd)
105       error("Ran out of data reading vbr_uint!");
106     Result |= (unsigned)((*At++) & 0x7F) << Shift;
107     Shift += 7;
108   } while (At[-1] & 0x80);
109   if (Handler) Handler->handleVBR32(At-Save);
110   return Result;
111 }
112
113 /// Read a variable-bit-rate encoded unsigned 64-bit integer.
114 inline uint64_t BytecodeReader::read_vbr_uint64() {
115   unsigned Shift = 0;
116   uint64_t Result = 0;
117   BufPtr Save = At;
118
119   do {
120     if (At == BlockEnd)
121       error("Ran out of data reading vbr_uint64!");
122     Result |= (uint64_t)((*At++) & 0x7F) << Shift;
123     Shift += 7;
124   } while (At[-1] & 0x80);
125   if (Handler) Handler->handleVBR64(At-Save);
126   return Result;
127 }
128
129 /// Read a variable-bit-rate encoded signed 64-bit integer.
130 inline int64_t BytecodeReader::read_vbr_int64() {
131   uint64_t R = read_vbr_uint64();
132   if (R & 1) {
133     if (R != 1)
134       return -(int64_t)(R >> 1);
135     else   // There is no such thing as -0 with integers.  "-0" really means
136            // 0x8000000000000000.
137       return 1LL << 63;
138   } else
139     return  (int64_t)(R >> 1);
140 }
141
142 /// Read a pascal-style string (length followed by text)
143 inline std::string BytecodeReader::read_str() {
144   unsigned Size = read_vbr_uint();
145   const unsigned char *OldAt = At;
146   At += Size;
147   if (At > BlockEnd)             // Size invalid?
148     error("Ran out of data reading a string!");
149   return std::string((char*)OldAt, Size);
150 }
151
152 /// Read an arbitrary block of data
153 inline void BytecodeReader::read_data(void *Ptr, void *End) {
154   unsigned char *Start = (unsigned char *)Ptr;
155   unsigned Amount = (unsigned char *)End - Start;
156   if (At+Amount > BlockEnd)
157     error("Ran out of data!");
158   std::copy(At, At+Amount, Start);
159   At += Amount;
160 }
161
162 /// Read a float value in little-endian order
163 inline void BytecodeReader::read_float(float& FloatVal) {
164   /// FIXME: This isn't optimal, it has size problems on some platforms
165   /// where FP is not IEEE.
166   FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
167   At+=sizeof(uint32_t);
168 }
169
170 /// Read a double value in little-endian order
171 inline void BytecodeReader::read_double(double& DoubleVal) {
172   /// FIXME: This isn't optimal, it has size problems on some platforms
173   /// where FP is not IEEE.
174   DoubleVal = BitsToDouble((uint64_t(At[0]) <<  0) | (uint64_t(At[1]) << 8) |
175                            (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
176                            (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
177                            (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
178   At+=sizeof(uint64_t);
179 }
180
181 /// Read a block header and obtain its type and size
182 inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
183   if ( hasLongBlockHeaders ) {
184     Type = read_uint();
185     Size = read_uint();
186     switch (Type) {
187     case BytecodeFormat::Reserved_DoNotUse :
188       error("Reserved_DoNotUse used as Module Type?");
189       Type = BytecodeFormat::ModuleBlockID; break;
190     case BytecodeFormat::Module:
191       Type = BytecodeFormat::ModuleBlockID; break;
192     case BytecodeFormat::Function:
193       Type = BytecodeFormat::FunctionBlockID; break;
194     case BytecodeFormat::ConstantPool:
195       Type = BytecodeFormat::ConstantPoolBlockID; break;
196     case BytecodeFormat::SymbolTable:
197       Type = BytecodeFormat::SymbolTableBlockID; break;
198     case BytecodeFormat::ModuleGlobalInfo:
199       Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
200     case BytecodeFormat::GlobalTypePlane:
201       Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
202     case BytecodeFormat::InstructionList:
203       Type = BytecodeFormat::InstructionListBlockID; break;
204     case BytecodeFormat::CompactionTable:
205       Type = BytecodeFormat::CompactionTableBlockID; break;
206     case BytecodeFormat::BasicBlock:
207       /// This block type isn't used after version 1.1. However, we have to
208       /// still allow the value in case this is an old bc format file.
209       /// We just let its value creep thru.
210       break;
211     default:
212       error("Invalid block id found: " + utostr(Type));
213       break;
214     }
215   } else {
216     Size = read_uint();
217     Type = Size & 0x1F; // mask low order five bits
218     Size >>= 5; // get rid of five low order bits, leaving high 27
219   }
220   BlockStart = At;
221   if (At + Size > BlockEnd)
222     error("Attempt to size a block past end of memory");
223   BlockEnd = At + Size;
224   if (Handler) Handler->handleBlock(Type, BlockStart, Size);
225 }
226
227
228 /// In LLVM 1.2 and before, Types were derived from Value and so they were
229 /// written as part of the type planes along with any other Value. In LLVM
230 /// 1.3 this changed so that Type does not derive from Value. Consequently,
231 /// the BytecodeReader's containers for Values can't contain Types because
232 /// there's no inheritance relationship. This means that the "Type Type"
233 /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
234 /// whenever a bytecode construct must have both types and values together,
235 /// the types are always read/written first and then the Values. Furthermore
236 /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
237 /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
238 /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
239 /// For LLVM 1.2 and before, this function will decrement the type id by
240 /// one to account for the missing Type::TypeTyID enumerator if the value is
241 /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
242 /// function returns true, otherwise false. This helps detect situations
243 /// where the pre 1.3 bytecode is indicating that what follows is a type.
244 /// @returns true iff type id corresponds to pre 1.3 "type type"
245 inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
246   if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
247     if (TypeId == Type::LabelTyID) {
248       TypeId = Type::VoidTyID; // sanitize it
249       return true; // indicate we got TypeTyID in pre 1.3 bytecode
250     } else if (TypeId > Type::LabelTyID)
251       --TypeId; // shift all planes down because type type plane is missing
252   }
253   return false;
254 }
255
256 /// Reads a vbr uint to read in a type id and does the necessary
257 /// conversion on it by calling sanitizeTypeId.
258 /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
259 /// @see sanitizeTypeId
260 inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
261   TypeId = read_vbr_uint();
262   if ( !has32BitTypes )
263     if ( TypeId == 0x00FFFFFF )
264       TypeId = read_vbr_uint();
265   return sanitizeTypeId(TypeId);
266 }
267
268 //===----------------------------------------------------------------------===//
269 // IR Lookup Methods
270 //===----------------------------------------------------------------------===//
271
272 /// Determine if a type id has an implicit null value
273 inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
274   if (!hasExplicitPrimitiveZeros)
275     return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
276   return TyID >= Type::FirstDerivedTyID;
277 }
278
279 /// Obtain a type given a typeid and account for things like compaction tables,
280 /// function level vs module level, and the offsetting for the primitive types.
281 const Type *BytecodeReader::getType(unsigned ID) {
282   if (ID < Type::FirstDerivedTyID)
283     if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
284       return T;   // Asked for a primitive type...
285
286   // Otherwise, derived types need offset...
287   ID -= Type::FirstDerivedTyID;
288
289   if (!CompactionTypes.empty()) {
290     if (ID >= CompactionTypes.size())
291       error("Type ID out of range for compaction table!");
292     return CompactionTypes[ID].first;
293   }
294
295   // Is it a module-level type?
296   if (ID < ModuleTypes.size())
297     return ModuleTypes[ID].get();
298
299   // Nope, is it a function-level type?
300   ID -= ModuleTypes.size();
301   if (ID < FunctionTypes.size())
302     return FunctionTypes[ID].get();
303
304   error("Illegal type reference!");
305   return Type::VoidTy;
306 }
307
308 /// Get a sanitized type id. This just makes sure that the \p ID
309 /// is both sanitized and not the "type type" of pre-1.3 bytecode.
310 /// @see sanitizeTypeId
311 inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
312   if (sanitizeTypeId(ID))
313     error("Invalid type id encountered");
314   return getType(ID);
315 }
316
317 /// This method just saves some coding. It uses read_typeid to read
318 /// in a sanitized type id, errors that its not the type type, and
319 /// then calls getType to return the type value.
320 inline const Type* BytecodeReader::readSanitizedType() {
321   unsigned ID;
322   if (read_typeid(ID))
323     error("Invalid type id encountered");
324   return getType(ID);
325 }
326
327 /// Get the slot number associated with a type accounting for primitive
328 /// types, compaction tables, and function level vs module level.
329 unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
330   if (Ty->isPrimitiveType())
331     return Ty->getTypeID();
332
333   // Scan the compaction table for the type if needed.
334   if (!CompactionTypes.empty()) {
335     for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
336       if (CompactionTypes[i].first == Ty)
337         return Type::FirstDerivedTyID + i;
338
339     error("Couldn't find type specified in compaction table!");
340   }
341
342   // Check the function level types first...
343   TypeListTy::iterator I = std::find(FunctionTypes.begin(),
344                                      FunctionTypes.end(), Ty);
345
346   if (I != FunctionTypes.end())
347     return Type::FirstDerivedTyID + ModuleTypes.size() +
348            (&*I - &FunctionTypes[0]);
349
350   // If we don't have our cache yet, build it now.
351   if (ModuleTypeIDCache.empty()) {
352     unsigned N = 0;
353     ModuleTypeIDCache.reserve(ModuleTypes.size());
354     for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
355          I != E; ++I, ++N)
356       ModuleTypeIDCache.push_back(std::make_pair(*I, N));
357     
358     std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
359   }
360   
361   // Binary search the cache for the entry.
362   std::vector<std::pair<const Type*, unsigned> >::iterator IT =
363     std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
364                      std::make_pair(Ty, 0U));
365   if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
366     error("Didn't find type in ModuleTypes.");
367     
368   return Type::FirstDerivedTyID + IT->second;
369 }
370
371 /// This is just like getType, but when a compaction table is in use, it is
372 /// ignored.  It also ignores function level types.
373 /// @see getType
374 const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
375   if (Slot < Type::FirstDerivedTyID) {
376     const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
377     if (!Ty)
378       error("Not a primitive type ID?");
379     return Ty;
380   }
381   Slot -= Type::FirstDerivedTyID;
382   if (Slot >= ModuleTypes.size())
383     error("Illegal compaction table type reference!");
384   return ModuleTypes[Slot];
385 }
386
387 /// This is just like getTypeSlot, but when a compaction table is in use, it
388 /// is ignored. It also ignores function level types.
389 unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
390   if (Ty->isPrimitiveType())
391     return Ty->getTypeID();
392   
393   // If we don't have our cache yet, build it now.
394   if (ModuleTypeIDCache.empty()) {
395     unsigned N = 0;
396     ModuleTypeIDCache.reserve(ModuleTypes.size());
397     for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
398          I != E; ++I, ++N)
399       ModuleTypeIDCache.push_back(std::make_pair(*I, N));
400     
401     std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
402   }
403   
404   // Binary search the cache for the entry.
405   std::vector<std::pair<const Type*, unsigned> >::iterator IT =
406     std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
407                      std::make_pair(Ty, 0U));
408   if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
409     error("Didn't find type in ModuleTypes.");
410   
411   return Type::FirstDerivedTyID + IT->second;
412 }
413
414 /// Retrieve a value of a given type and slot number, possibly creating
415 /// it if it doesn't already exist.
416 Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
417   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
418   unsigned Num = oNum;
419
420   // If there is a compaction table active, it defines the low-level numbers.
421   // If not, the module values define the low-level numbers.
422   if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
423     if (Num < CompactionValues[type].size())
424       return CompactionValues[type][Num];
425     Num -= CompactionValues[type].size();
426   } else {
427     // By default, the global type id is the type id passed in
428     unsigned GlobalTyID = type;
429
430     // If the type plane was compactified, figure out the global type ID by
431     // adding the derived type ids and the distance.
432     if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
433       GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
434
435     if (hasImplicitNull(GlobalTyID)) {
436       const Type *Ty = getType(type);
437       if (!isa<OpaqueType>(Ty)) {
438         if (Num == 0)
439           return Constant::getNullValue(Ty);
440         --Num;
441       }
442     }
443
444     if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
445       if (Num < ModuleValues[GlobalTyID]->size())
446         return ModuleValues[GlobalTyID]->getOperand(Num);
447       Num -= ModuleValues[GlobalTyID]->size();
448     }
449   }
450
451   if (FunctionValues.size() > type &&
452       FunctionValues[type] &&
453       Num < FunctionValues[type]->size())
454     return FunctionValues[type]->getOperand(Num);
455
456   if (!Create) return 0;  // Do not create a placeholder?
457
458   // Did we already create a place holder?
459   std::pair<unsigned,unsigned> KeyValue(type, oNum);
460   ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
461   if (I != ForwardReferences.end() && I->first == KeyValue)
462     return I->second;   // We have already created this placeholder
463
464   // If the type exists (it should)
465   if (const Type* Ty = getType(type)) {
466     // Create the place holder
467     Value *Val = new Argument(Ty);
468     ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
469     return Val;
470   }
471   throw "Can't create placeholder for value of type slot #" + utostr(type);
472 }
473
474 /// This is just like getValue, but when a compaction table is in use, it
475 /// is ignored.  Also, no forward references or other fancy features are
476 /// supported.
477 Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
478   if (SlotNo == 0)
479     return Constant::getNullValue(getType(TyID));
480
481   if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
482     TyID -= Type::FirstDerivedTyID;
483     if (TyID >= CompactionTypes.size())
484       error("Type ID out of range for compaction table!");
485     TyID = CompactionTypes[TyID].second;
486   }
487
488   --SlotNo;
489
490   if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
491       SlotNo >= ModuleValues[TyID]->size()) {
492     if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
493       error("Corrupt compaction table entry!"
494             + utostr(TyID) + ", " + utostr(SlotNo) + ": "
495             + utostr(ModuleValues.size()));
496     else
497       error("Corrupt compaction table entry!"
498             + utostr(TyID) + ", " + utostr(SlotNo) + ": "
499             + utostr(ModuleValues.size()) + ", "
500             + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
501             + ", "
502             + utostr(ModuleValues[TyID]->size()));
503   }
504   return ModuleValues[TyID]->getOperand(SlotNo);
505 }
506
507 /// Just like getValue, except that it returns a null pointer
508 /// only on error.  It always returns a constant (meaning that if the value is
509 /// defined, but is not a constant, that is an error).  If the specified
510 /// constant hasn't been parsed yet, a placeholder is defined and used.
511 /// Later, after the real value is parsed, the placeholder is eliminated.
512 Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
513   if (Value *V = getValue(TypeSlot, Slot, false))
514     if (Constant *C = dyn_cast<Constant>(V))
515       return C;   // If we already have the value parsed, just return it
516     else
517       error("Value for slot " + utostr(Slot) +
518             " is expected to be a constant!");
519
520   std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
521   ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
522
523   if (I != ConstantFwdRefs.end() && I->first == Key) {
524     return I->second;
525   } else {
526     // Create a placeholder for the constant reference and
527     // keep track of the fact that we have a forward ref to recycle it
528     Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
529
530     // Keep track of the fact that we have a forward ref to recycle it
531     ConstantFwdRefs.insert(I, std::make_pair(Key, C));
532     return C;
533   }
534 }
535
536 //===----------------------------------------------------------------------===//
537 // IR Construction Methods
538 //===----------------------------------------------------------------------===//
539
540 /// As values are created, they are inserted into the appropriate place
541 /// with this method. The ValueTable argument must be one of ModuleValues
542 /// or FunctionValues data members of this class.
543 unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
544                                       ValueTable &ValueTab) {
545   assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
546           !hasImplicitNull(type) &&
547          "Cannot read null values from bytecode!");
548
549   if (ValueTab.size() <= type)
550     ValueTab.resize(type+1);
551
552   if (!ValueTab[type]) ValueTab[type] = new ValueList();
553
554   ValueTab[type]->push_back(Val);
555
556   bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
557   return ValueTab[type]->size()-1 + HasOffset;
558 }
559
560 /// Insert the arguments of a function as new values in the reader.
561 void BytecodeReader::insertArguments(Function* F) {
562   const FunctionType *FT = F->getFunctionType();
563   Function::arg_iterator AI = F->arg_begin();
564   for (FunctionType::param_iterator It = FT->param_begin();
565        It != FT->param_end(); ++It, ++AI)
566     insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
567 }
568
569 //===----------------------------------------------------------------------===//
570 // Bytecode Parsing Methods
571 //===----------------------------------------------------------------------===//
572
573 /// This method parses a single instruction. The instruction is
574 /// inserted at the end of the \p BB provided. The arguments of
575 /// the instruction are provided in the \p Oprnds vector.
576 void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
577                                       BasicBlock* BB) {
578   BufPtr SaveAt = At;
579
580   // Clear instruction data
581   Oprnds.clear();
582   unsigned iType = 0;
583   unsigned Opcode = 0;
584   unsigned Op = read_uint();
585
586   // bits   Instruction format:        Common to all formats
587   // --------------------------
588   // 01-00: Opcode type, fixed to 1.
589   // 07-02: Opcode
590   Opcode    = (Op >> 2) & 63;
591   Oprnds.resize((Op >> 0) & 03);
592
593   // Extract the operands
594   switch (Oprnds.size()) {
595   case 1:
596     // bits   Instruction format:
597     // --------------------------
598     // 19-08: Resulting type plane
599     // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
600     //
601     iType   = (Op >>  8) & 4095;
602     Oprnds[0] = (Op >> 20) & 4095;
603     if (Oprnds[0] == 4095)    // Handle special encoding for 0 operands...
604       Oprnds.resize(0);
605     break;
606   case 2:
607     // bits   Instruction format:
608     // --------------------------
609     // 15-08: Resulting type plane
610     // 23-16: Operand #1
611     // 31-24: Operand #2
612     //
613     iType   = (Op >>  8) & 255;
614     Oprnds[0] = (Op >> 16) & 255;
615     Oprnds[1] = (Op >> 24) & 255;
616     break;
617   case 3:
618     // bits   Instruction format:
619     // --------------------------
620     // 13-08: Resulting type plane
621     // 19-14: Operand #1
622     // 25-20: Operand #2
623     // 31-26: Operand #3
624     //
625     iType   = (Op >>  8) & 63;
626     Oprnds[0] = (Op >> 14) & 63;
627     Oprnds[1] = (Op >> 20) & 63;
628     Oprnds[2] = (Op >> 26) & 63;
629     break;
630   case 0:
631     At -= 4;  // Hrm, try this again...
632     Opcode = read_vbr_uint();
633     Opcode >>= 2;
634     iType = read_vbr_uint();
635
636     unsigned NumOprnds = read_vbr_uint();
637     Oprnds.resize(NumOprnds);
638
639     if (NumOprnds == 0)
640       error("Zero-argument instruction found; this is invalid.");
641
642     for (unsigned i = 0; i != NumOprnds; ++i)
643       Oprnds[i] = read_vbr_uint();
644     align32();
645     break;
646   }
647
648   const Type *InstTy = getSanitizedType(iType);
649
650   // We have enough info to inform the handler now.
651   if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
652
653   // Declare the resulting instruction we'll build.
654   Instruction *Result = 0;
655
656   // If this is a bytecode format that did not include the unreachable
657   // instruction, bump up all opcodes numbers to make space.
658   if (hasNoUnreachableInst) {
659     if (Opcode >= Instruction::Unreachable &&
660         Opcode < 62) {
661       ++Opcode;
662     }
663   }
664
665   // Handle binary operators
666   if (Opcode >= Instruction::BinaryOpsBegin &&
667       Opcode <  Instruction::BinaryOpsEnd  && Oprnds.size() == 2)
668     Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
669                                     getValue(iType, Oprnds[0]),
670                                     getValue(iType, Oprnds[1]));
671
672   switch (Opcode) {
673   default:
674     if (Result == 0)
675       error("Illegal instruction read!");
676     break;
677   case Instruction::VAArg:
678     Result = new VAArgInst(getValue(iType, Oprnds[0]),
679                            getSanitizedType(Oprnds[1]));
680     break;
681   case 32: { //VANext_old
682     const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
683     Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
684                                                   (Type *)0);
685
686     //b = vanext a, t ->
687     //foo = alloca 1 of t
688     //bar = vacopy a
689     //store bar -> foo
690     //tmp = vaarg foo, t
691     //b = load foo
692     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
693     BB->getInstList().push_back(foo);
694     CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
695     BB->getInstList().push_back(bar);
696     BB->getInstList().push_back(new StoreInst(bar, foo));
697     Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
698     BB->getInstList().push_back(tmp);
699     Result = new LoadInst(foo);
700     break;
701   }
702   case 33: { //VAArg_old
703     const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
704     Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
705                                                   (Type *)0);
706
707     //b = vaarg a, t ->
708     //foo = alloca 1 of t
709     //bar = vacopy a
710     //store bar -> foo
711     //b = vaarg foo, t
712     AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
713     BB->getInstList().push_back(foo);
714     CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
715     BB->getInstList().push_back(bar);
716     BB->getInstList().push_back(new StoreInst(bar, foo));
717     Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
718     break;
719   }
720   case Instruction::ExtractElement: {
721     if (Oprnds.size() != 2)
722       throw std::string("Invalid extractelement instruction!");
723     Result = new ExtractElementInst(getValue(iType, Oprnds[0]), 
724                                     getValue(Type::UIntTyID, Oprnds[1]));
725     break;
726   }
727   case Instruction::Cast:
728     Result = new CastInst(getValue(iType, Oprnds[0]),
729                           getSanitizedType(Oprnds[1]));
730     break;
731   case Instruction::Select:
732     Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
733                             getValue(iType, Oprnds[1]),
734                             getValue(iType, Oprnds[2]));
735     break;
736   case Instruction::PHI: {
737     if (Oprnds.size() == 0 || (Oprnds.size() & 1))
738       error("Invalid phi node encountered!");
739
740     PHINode *PN = new PHINode(InstTy);
741     PN->reserveOperandSpace(Oprnds.size());
742     for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
743       PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
744     Result = PN;
745     break;
746   }
747
748   case Instruction::Shl:
749   case Instruction::Shr:
750     Result = new ShiftInst((Instruction::OtherOps)Opcode,
751                            getValue(iType, Oprnds[0]),
752                            getValue(Type::UByteTyID, Oprnds[1]));
753     break;
754   case Instruction::Ret:
755     if (Oprnds.size() == 0)
756       Result = new ReturnInst();
757     else if (Oprnds.size() == 1)
758       Result = new ReturnInst(getValue(iType, Oprnds[0]));
759     else
760       error("Unrecognized instruction!");
761     break;
762
763   case Instruction::Br:
764     if (Oprnds.size() == 1)
765       Result = new BranchInst(getBasicBlock(Oprnds[0]));
766     else if (Oprnds.size() == 3)
767       Result = new BranchInst(getBasicBlock(Oprnds[0]),
768           getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
769     else
770       error("Invalid number of operands for a 'br' instruction!");
771     break;
772   case Instruction::Switch: {
773     if (Oprnds.size() & 1)
774       error("Switch statement with odd number of arguments!");
775
776     SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
777                                    getBasicBlock(Oprnds[1]),
778                                    Oprnds.size()/2-1);
779     for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
780       I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
781                  getBasicBlock(Oprnds[i+1]));
782     Result = I;
783     break;
784   }
785
786   case 58:                   // Call with extra operand for calling conv
787   case 59:                   // tail call, Fast CC
788   case 60:                   // normal call, Fast CC
789   case 61:                   // tail call, C Calling Conv
790   case Instruction::Call: {  // Normal Call, C Calling Convention
791     if (Oprnds.size() == 0)
792       error("Invalid call instruction encountered!");
793
794     Value *F = getValue(iType, Oprnds[0]);
795
796     unsigned CallingConv = CallingConv::C;
797     bool isTailCall = false;
798
799     if (Opcode == 61 || Opcode == 59)
800       isTailCall = true;
801
802     // Check to make sure we have a pointer to function type
803     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
804     if (PTy == 0) error("Call to non function pointer value!");
805     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
806     if (FTy == 0) error("Call to non function pointer value!");
807
808     std::vector<Value *> Params;
809     if (!FTy->isVarArg()) {
810       FunctionType::param_iterator It = FTy->param_begin();
811
812       if (Opcode == 58) {
813         isTailCall = Oprnds.back() & 1;
814         CallingConv = Oprnds.back() >> 1;
815         Oprnds.pop_back();
816       } else if (Opcode == 59 || Opcode == 60)
817         CallingConv = CallingConv::Fast;
818
819       for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
820         if (It == FTy->param_end())
821           error("Invalid call instruction!");
822         Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
823       }
824       if (It != FTy->param_end())
825         error("Invalid call instruction!");
826     } else {
827       Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
828
829       unsigned FirstVariableOperand;
830       if (Oprnds.size() < FTy->getNumParams())
831         error("Call instruction missing operands!");
832
833       // Read all of the fixed arguments
834       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
835         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
836
837       FirstVariableOperand = FTy->getNumParams();
838
839       if ((Oprnds.size()-FirstVariableOperand) & 1)
840         error("Invalid call instruction!");   // Must be pairs of type/value
841
842       for (unsigned i = FirstVariableOperand, e = Oprnds.size();
843            i != e; i += 2)
844         Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
845     }
846
847     Result = new CallInst(F, Params);
848     if (isTailCall) cast<CallInst>(Result)->setTailCall();
849     if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
850     break;
851   }
852   case 56:                     // Invoke with encoded CC
853   case 57:                     // Invoke Fast CC
854   case Instruction::Invoke: {  // Invoke C CC
855     if (Oprnds.size() < 3)
856       error("Invalid invoke instruction!");
857     Value *F = getValue(iType, Oprnds[0]);
858
859     // Check to make sure we have a pointer to function type
860     const PointerType *PTy = dyn_cast<PointerType>(F->getType());
861     if (PTy == 0)
862       error("Invoke to non function pointer value!");
863     const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
864     if (FTy == 0)
865       error("Invoke to non function pointer value!");
866
867     std::vector<Value *> Params;
868     BasicBlock *Normal, *Except;
869     unsigned CallingConv = CallingConv::C;
870
871     if (Opcode == 57)
872       CallingConv = CallingConv::Fast;
873     else if (Opcode == 56) {
874       CallingConv = Oprnds.back();
875       Oprnds.pop_back();
876     }
877
878     if (!FTy->isVarArg()) {
879       Normal = getBasicBlock(Oprnds[1]);
880       Except = getBasicBlock(Oprnds[2]);
881
882       FunctionType::param_iterator It = FTy->param_begin();
883       for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
884         if (It == FTy->param_end())
885           error("Invalid invoke instruction!");
886         Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
887       }
888       if (It != FTy->param_end())
889         error("Invalid invoke instruction!");
890     } else {
891       Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
892
893       Normal = getBasicBlock(Oprnds[0]);
894       Except = getBasicBlock(Oprnds[1]);
895
896       unsigned FirstVariableArgument = FTy->getNumParams()+2;
897       for (unsigned i = 2; i != FirstVariableArgument; ++i)
898         Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
899                                   Oprnds[i]));
900
901       if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
902         error("Invalid invoke instruction!");
903
904       for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
905         Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
906     }
907
908     Result = new InvokeInst(F, Normal, Except, Params);
909     if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
910     break;
911   }
912   case Instruction::Malloc: {
913     unsigned Align = 0;
914     if (Oprnds.size() == 2)
915       Align = (1 << Oprnds[1]) >> 1;
916     else if (Oprnds.size() > 2)
917       error("Invalid malloc instruction!");
918     if (!isa<PointerType>(InstTy))
919       error("Invalid malloc instruction!");
920
921     Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
922                             getValue(Type::UIntTyID, Oprnds[0]), Align);
923     break;
924   }
925
926   case Instruction::Alloca: {
927     unsigned Align = 0;
928     if (Oprnds.size() == 2)
929       Align = (1 << Oprnds[1]) >> 1;
930     else if (Oprnds.size() > 2)
931       error("Invalid alloca instruction!");
932     if (!isa<PointerType>(InstTy))
933       error("Invalid alloca instruction!");
934
935     Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
936                             getValue(Type::UIntTyID, Oprnds[0]), Align);
937     break;
938   }
939   case Instruction::Free:
940     if (!isa<PointerType>(InstTy))
941       error("Invalid free instruction!");
942     Result = new FreeInst(getValue(iType, Oprnds[0]));
943     break;
944   case Instruction::GetElementPtr: {
945     if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
946       error("Invalid getelementptr instruction!");
947
948     std::vector<Value*> Idx;
949
950     const Type *NextTy = InstTy;
951     for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
952       const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
953       if (!TopTy)
954         error("Invalid getelementptr instruction!");
955
956       unsigned ValIdx = Oprnds[i];
957       unsigned IdxTy = 0;
958       if (!hasRestrictedGEPTypes) {
959         // Struct indices are always uints, sequential type indices can be any
960         // of the 32 or 64-bit integer types.  The actual choice of type is
961         // encoded in the low two bits of the slot number.
962         if (isa<StructType>(TopTy))
963           IdxTy = Type::UIntTyID;
964         else {
965           switch (ValIdx & 3) {
966           default:
967           case 0: IdxTy = Type::UIntTyID; break;
968           case 1: IdxTy = Type::IntTyID; break;
969           case 2: IdxTy = Type::ULongTyID; break;
970           case 3: IdxTy = Type::LongTyID; break;
971           }
972           ValIdx >>= 2;
973         }
974       } else {
975         IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
976       }
977
978       Idx.push_back(getValue(IdxTy, ValIdx));
979
980       // Convert ubyte struct indices into uint struct indices.
981       if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
982         if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
983           Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
984
985       NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
986     }
987
988     Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
989     break;
990   }
991
992   case 62:   // volatile load
993   case Instruction::Load:
994     if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
995       error("Invalid load instruction!");
996     Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
997     break;
998
999   case 63:   // volatile store
1000   case Instruction::Store: {
1001     if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
1002       error("Invalid store instruction!");
1003
1004     Value *Ptr = getValue(iType, Oprnds[1]);
1005     const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
1006     Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
1007                            Opcode == 63);
1008     break;
1009   }
1010   case Instruction::Unwind:
1011     if (Oprnds.size() != 0) error("Invalid unwind instruction!");
1012     Result = new UnwindInst();
1013     break;
1014   case Instruction::Unreachable:
1015     if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
1016     Result = new UnreachableInst();
1017     break;
1018   }  // end switch(Opcode)
1019
1020   unsigned TypeSlot;
1021   if (Result->getType() == InstTy)
1022     TypeSlot = iType;
1023   else
1024     TypeSlot = getTypeSlot(Result->getType());
1025
1026   insertValue(Result, TypeSlot, FunctionValues);
1027   BB->getInstList().push_back(Result);
1028 }
1029
1030 /// Get a particular numbered basic block, which might be a forward reference.
1031 /// This works together with ParseBasicBlock to handle these forward references
1032 /// in a clean manner.  This function is used when constructing phi, br, switch,
1033 /// and other instructions that reference basic blocks. Blocks are numbered
1034 /// sequentially as they appear in the function.
1035 BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
1036   // Make sure there is room in the table...
1037   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
1038
1039   // First check to see if this is a backwards reference, i.e., ParseBasicBlock
1040   // has already created this block, or if the forward reference has already
1041   // been created.
1042   if (ParsedBasicBlocks[ID])
1043     return ParsedBasicBlocks[ID];
1044
1045   // Otherwise, the basic block has not yet been created.  Do so and add it to
1046   // the ParsedBasicBlocks list.
1047   return ParsedBasicBlocks[ID] = new BasicBlock();
1048 }
1049
1050 /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
1051 /// This method reads in one of the basicblock packets. This method is not used
1052 /// for bytecode files after LLVM 1.0
1053 /// @returns The basic block constructed.
1054 BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
1055   if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1056
1057   BasicBlock *BB = 0;
1058
1059   if (ParsedBasicBlocks.size() == BlockNo)
1060     ParsedBasicBlocks.push_back(BB = new BasicBlock());
1061   else if (ParsedBasicBlocks[BlockNo] == 0)
1062     BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1063   else
1064     BB = ParsedBasicBlocks[BlockNo];
1065
1066   std::vector<unsigned> Operands;
1067   while (moreInBlock())
1068     ParseInstruction(Operands, BB);
1069
1070   if (Handler) Handler->handleBasicBlockEnd(BlockNo);
1071   return BB;
1072 }
1073
1074 /// Parse all of the BasicBlock's & Instruction's in the body of a function.
1075 /// In post 1.0 bytecode files, we no longer emit basic block individually,
1076 /// in order to avoid per-basic-block overhead.
1077 /// @returns Rhe number of basic blocks encountered.
1078 unsigned BytecodeReader::ParseInstructionList(Function* F) {
1079   unsigned BlockNo = 0;
1080   std::vector<unsigned> Args;
1081
1082   while (moreInBlock()) {
1083     if (Handler) Handler->handleBasicBlockBegin(BlockNo);
1084     BasicBlock *BB;
1085     if (ParsedBasicBlocks.size() == BlockNo)
1086       ParsedBasicBlocks.push_back(BB = new BasicBlock());
1087     else if (ParsedBasicBlocks[BlockNo] == 0)
1088       BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
1089     else
1090       BB = ParsedBasicBlocks[BlockNo];
1091     ++BlockNo;
1092     F->getBasicBlockList().push_back(BB);
1093
1094     // Read instructions into this basic block until we get to a terminator
1095     while (moreInBlock() && !BB->getTerminator())
1096       ParseInstruction(Args, BB);
1097
1098     if (!BB->getTerminator())
1099       error("Non-terminated basic block found!");
1100
1101     if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
1102   }
1103
1104   return BlockNo;
1105 }
1106
1107 /// Parse a symbol table. This works for both module level and function
1108 /// level symbol tables.  For function level symbol tables, the CurrentFunction
1109 /// parameter must be non-zero and the ST parameter must correspond to
1110 /// CurrentFunction's symbol table. For Module level symbol tables, the
1111 /// CurrentFunction argument must be zero.
1112 void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
1113                                       SymbolTable *ST) {
1114   if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
1115
1116   // Allow efficient basic block lookup by number.
1117   std::vector<BasicBlock*> BBMap;
1118   if (CurrentFunction)
1119     for (Function::iterator I = CurrentFunction->begin(),
1120            E = CurrentFunction->end(); I != E; ++I)
1121       BBMap.push_back(I);
1122
1123   /// In LLVM 1.3 we write types separately from values so
1124   /// The types are always first in the symbol table. This is
1125   /// because Type no longer derives from Value.
1126   if (!hasTypeDerivedFromValue) {
1127     // Symtab block header: [num entries]
1128     unsigned NumEntries = read_vbr_uint();
1129     for (unsigned i = 0; i < NumEntries; ++i) {
1130       // Symtab entry: [def slot #][name]
1131       unsigned slot = read_vbr_uint();
1132       std::string Name = read_str();
1133       const Type* T = getType(slot);
1134       ST->insert(Name, T);
1135     }
1136   }
1137
1138   while (moreInBlock()) {
1139     // Symtab block header: [num entries][type id number]
1140     unsigned NumEntries = read_vbr_uint();
1141     unsigned Typ = 0;
1142     bool isTypeType = read_typeid(Typ);
1143     const Type *Ty = getType(Typ);
1144
1145     for (unsigned i = 0; i != NumEntries; ++i) {
1146       // Symtab entry: [def slot #][name]
1147       unsigned slot = read_vbr_uint();
1148       std::string Name = read_str();
1149
1150       // if we're reading a pre 1.3 bytecode file and the type plane
1151       // is the "type type", handle it here
1152       if (isTypeType) {
1153         const Type* T = getType(slot);
1154         if (T == 0)
1155           error("Failed type look-up for name '" + Name + "'");
1156         ST->insert(Name, T);
1157         continue; // code below must be short circuited
1158       } else {
1159         Value *V = 0;
1160         if (Typ == Type::LabelTyID) {
1161           if (slot < BBMap.size())
1162             V = BBMap[slot];
1163         } else {
1164           V = getValue(Typ, slot, false); // Find mapping...
1165         }
1166         if (V == 0)
1167           error("Failed value look-up for name '" + Name + "'");
1168         V->setName(Name);
1169       }
1170     }
1171   }
1172   checkPastBlockEnd("Symbol Table");
1173   if (Handler) Handler->handleSymbolTableEnd();
1174 }
1175
1176 /// Read in the types portion of a compaction table.
1177 void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
1178   for (unsigned i = 0; i != NumEntries; ++i) {
1179     unsigned TypeSlot = 0;
1180     if (read_typeid(TypeSlot))
1181       error("Invalid type in compaction table: type type");
1182     const Type *Typ = getGlobalTableType(TypeSlot);
1183     CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
1184     if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
1185   }
1186 }
1187
1188 /// Parse a compaction table.
1189 void BytecodeReader::ParseCompactionTable() {
1190
1191   // Notify handler that we're beginning a compaction table.
1192   if (Handler) Handler->handleCompactionTableBegin();
1193
1194   // In LLVM 1.3 Type no longer derives from Value. So,
1195   // we always write them first in the compaction table
1196   // because they can't occupy a "type plane" where the
1197   // Values reside.
1198   if (! hasTypeDerivedFromValue) {
1199     unsigned NumEntries = read_vbr_uint();
1200     ParseCompactionTypes(NumEntries);
1201   }
1202
1203   // Compaction tables live in separate blocks so we have to loop
1204   // until we've read the whole thing.
1205   while (moreInBlock()) {
1206     // Read the number of Value* entries in the compaction table
1207     unsigned NumEntries = read_vbr_uint();
1208     unsigned Ty = 0;
1209     unsigned isTypeType = false;
1210
1211     // Decode the type from value read in. Most compaction table
1212     // planes will have one or two entries in them. If that's the
1213     // case then the length is encoded in the bottom two bits and
1214     // the higher bits encode the type. This saves another VBR value.
1215     if ((NumEntries & 3) == 3) {
1216       // In this case, both low-order bits are set (value 3). This
1217       // is a signal that the typeid follows.
1218       NumEntries >>= 2;
1219       isTypeType = read_typeid(Ty);
1220     } else {
1221       // In this case, the low-order bits specify the number of entries
1222       // and the high order bits specify the type.
1223       Ty = NumEntries >> 2;
1224       isTypeType = sanitizeTypeId(Ty);
1225       NumEntries &= 3;
1226     }
1227
1228     // if we're reading a pre 1.3 bytecode file and the type plane
1229     // is the "type type", handle it here
1230     if (isTypeType) {
1231       ParseCompactionTypes(NumEntries);
1232     } else {
1233       // Make sure we have enough room for the plane.
1234       if (Ty >= CompactionValues.size())
1235         CompactionValues.resize(Ty+1);
1236
1237       // Make sure the plane is empty or we have some kind of error.
1238       if (!CompactionValues[Ty].empty())
1239         error("Compaction table plane contains multiple entries!");
1240
1241       // Notify handler about the plane.
1242       if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
1243
1244       // Push the implicit zero.
1245       CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
1246
1247       // Read in each of the entries, put them in the compaction table
1248       // and notify the handler that we have a new compaction table value.
1249       for (unsigned i = 0; i != NumEntries; ++i) {
1250         unsigned ValSlot = read_vbr_uint();
1251         Value *V = getGlobalTableValue(Ty, ValSlot);
1252         CompactionValues[Ty].push_back(V);
1253         if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
1254       }
1255     }
1256   }
1257   // Notify handler that the compaction table is done.
1258   if (Handler) Handler->handleCompactionTableEnd();
1259 }
1260
1261 // Parse a single type. The typeid is read in first. If its a primitive type
1262 // then nothing else needs to be read, we know how to instantiate it. If its
1263 // a derived type, then additional data is read to fill out the type
1264 // definition.
1265 const Type *BytecodeReader::ParseType() {
1266   unsigned PrimType = 0;
1267   if (read_typeid(PrimType))
1268     error("Invalid type (type type) in type constants!");
1269
1270   const Type *Result = 0;
1271   if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
1272     return Result;
1273
1274   switch (PrimType) {
1275   case Type::FunctionTyID: {
1276     const Type *RetType = readSanitizedType();
1277
1278     unsigned NumParams = read_vbr_uint();
1279
1280     std::vector<const Type*> Params;
1281     while (NumParams--)
1282       Params.push_back(readSanitizedType());
1283
1284     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1285     if (isVarArg) Params.pop_back();
1286
1287     Result = FunctionType::get(RetType, Params, isVarArg);
1288     break;
1289   }
1290   case Type::ArrayTyID: {
1291     const Type *ElementType = readSanitizedType();
1292     unsigned NumElements = read_vbr_uint();
1293     Result =  ArrayType::get(ElementType, NumElements);
1294     break;
1295   }
1296   case Type::PackedTyID: {
1297     const Type *ElementType = readSanitizedType();
1298     unsigned NumElements = read_vbr_uint();
1299     Result =  PackedType::get(ElementType, NumElements);
1300     break;
1301   }
1302   case Type::StructTyID: {
1303     std::vector<const Type*> Elements;
1304     unsigned Typ = 0;
1305     if (read_typeid(Typ))
1306       error("Invalid element type (type type) for structure!");
1307
1308     while (Typ) {         // List is terminated by void/0 typeid
1309       Elements.push_back(getType(Typ));
1310       if (read_typeid(Typ))
1311         error("Invalid element type (type type) for structure!");
1312     }
1313
1314     Result = StructType::get(Elements);
1315     break;
1316   }
1317   case Type::PointerTyID: {
1318     Result = PointerType::get(readSanitizedType());
1319     break;
1320   }
1321
1322   case Type::OpaqueTyID: {
1323     Result = OpaqueType::get();
1324     break;
1325   }
1326
1327   default:
1328     error("Don't know how to deserialize primitive type " + utostr(PrimType));
1329     break;
1330   }
1331   if (Handler) Handler->handleType(Result);
1332   return Result;
1333 }
1334
1335 // ParseTypes - We have to use this weird code to handle recursive
1336 // types.  We know that recursive types will only reference the current slab of
1337 // values in the type plane, but they can forward reference types before they
1338 // have been read.  For example, Type #0 might be '{ Ty#1 }' and Type #1 might
1339 // be 'Ty#0*'.  When reading Type #0, type number one doesn't exist.  To fix
1340 // this ugly problem, we pessimistically insert an opaque type for each type we
1341 // are about to read.  This means that forward references will resolve to
1342 // something and when we reread the type later, we can replace the opaque type
1343 // with a new resolved concrete type.
1344 //
1345 void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
1346   assert(Tab.size() == 0 && "should not have read type constants in before!");
1347
1348   // Insert a bunch of opaque types to be resolved later...
1349   Tab.reserve(NumEntries);
1350   for (unsigned i = 0; i != NumEntries; ++i)
1351     Tab.push_back(OpaqueType::get());
1352
1353   if (Handler)
1354     Handler->handleTypeList(NumEntries);
1355
1356   // If we are about to resolve types, make sure the type cache is clear.
1357   if (NumEntries)
1358     ModuleTypeIDCache.clear();
1359   
1360   // Loop through reading all of the types.  Forward types will make use of the
1361   // opaque types just inserted.
1362   //
1363   for (unsigned i = 0; i != NumEntries; ++i) {
1364     const Type* NewTy = ParseType();
1365     const Type* OldTy = Tab[i].get();
1366     if (NewTy == 0)
1367       error("Couldn't parse type!");
1368
1369     // Don't directly push the new type on the Tab. Instead we want to replace
1370     // the opaque type we previously inserted with the new concrete value. This
1371     // approach helps with forward references to types. The refinement from the
1372     // abstract (opaque) type to the new type causes all uses of the abstract
1373     // type to use the concrete type (NewTy). This will also cause the opaque
1374     // type to be deleted.
1375     cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
1376
1377     // This should have replaced the old opaque type with the new type in the
1378     // value table... or with a preexisting type that was already in the system.
1379     // Let's just make sure it did.
1380     assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
1381   }
1382 }
1383
1384 /// Parse a single constant value
1385 Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
1386   // We must check for a ConstantExpr before switching by type because
1387   // a ConstantExpr can be of any type, and has no explicit value.
1388   //
1389   // 0 if not expr; numArgs if is expr
1390   unsigned isExprNumArgs = read_vbr_uint();
1391
1392   if (isExprNumArgs) {
1393     // 'undef' is encoded with 'exprnumargs' == 1.
1394     if (!hasNoUndefValue)
1395       if (--isExprNumArgs == 0)
1396         return UndefValue::get(getType(TypeID));
1397
1398     // FIXME: Encoding of constant exprs could be much more compact!
1399     std::vector<Constant*> ArgVec;
1400     ArgVec.reserve(isExprNumArgs);
1401     unsigned Opcode = read_vbr_uint();
1402
1403     // Bytecode files before LLVM 1.4 need have a missing terminator inst.
1404     if (hasNoUnreachableInst) Opcode++;
1405
1406     // Read the slot number and types of each of the arguments
1407     for (unsigned i = 0; i != isExprNumArgs; ++i) {
1408       unsigned ArgValSlot = read_vbr_uint();
1409       unsigned ArgTypeSlot = 0;
1410       if (read_typeid(ArgTypeSlot))
1411         error("Invalid argument type (type type) for constant value");
1412
1413       // Get the arg value from its slot if it exists, otherwise a placeholder
1414       ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
1415     }
1416
1417     // Construct a ConstantExpr of the appropriate kind
1418     if (isExprNumArgs == 1) {           // All one-operand expressions
1419       if (Opcode != Instruction::Cast)
1420         error("Only cast instruction has one argument for ConstantExpr");
1421
1422       Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
1423       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1424       return Result;
1425     } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
1426       std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
1427
1428       if (hasRestrictedGEPTypes) {
1429         const Type *BaseTy = ArgVec[0]->getType();
1430         generic_gep_type_iterator<std::vector<Constant*>::iterator>
1431           GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
1432           E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
1433         for (unsigned i = 0; GTI != E; ++GTI, ++i)
1434           if (isa<StructType>(*GTI)) {
1435             if (IdxList[i]->getType() != Type::UByteTy)
1436               error("Invalid index for getelementptr!");
1437             IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
1438           }
1439       }
1440
1441       Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
1442       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1443       return Result;
1444     } else if (Opcode == Instruction::Select) {
1445       if (ArgVec.size() != 3)
1446         error("Select instruction must have three arguments.");
1447       Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
1448                                                  ArgVec[2]);
1449       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1450       return Result;
1451     } else if (Opcode == Instruction::ExtractElement) {
1452       if (ArgVec.size() != 2)
1453         error("ExtractElement instruction must have two arguments.");
1454       Constant* Result = ConstantExpr::getExtractElement(ArgVec[0], ArgVec[1]);
1455       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1456       return Result;
1457     } else {                            // All other 2-operand expressions
1458       Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
1459       if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
1460       return Result;
1461     }
1462   }
1463
1464   // Ok, not an ConstantExpr.  We now know how to read the given type...
1465   const Type *Ty = getType(TypeID);
1466   switch (Ty->getTypeID()) {
1467   case Type::BoolTyID: {
1468     unsigned Val = read_vbr_uint();
1469     if (Val != 0 && Val != 1)
1470       error("Invalid boolean value read.");
1471     Constant* Result = ConstantBool::get(Val == 1);
1472     if (Handler) Handler->handleConstantValue(Result);
1473     return Result;
1474   }
1475
1476   case Type::UByteTyID:   // Unsigned integer types...
1477   case Type::UShortTyID:
1478   case Type::UIntTyID: {
1479     unsigned Val = read_vbr_uint();
1480     if (!ConstantUInt::isValueValidForType(Ty, Val))
1481       error("Invalid unsigned byte/short/int read.");
1482     Constant* Result =  ConstantUInt::get(Ty, Val);
1483     if (Handler) Handler->handleConstantValue(Result);
1484     return Result;
1485   }
1486
1487   case Type::ULongTyID: {
1488     Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
1489     if (Handler) Handler->handleConstantValue(Result);
1490     return Result;
1491   }
1492
1493   case Type::SByteTyID:   // Signed integer types...
1494   case Type::ShortTyID:
1495   case Type::IntTyID: {
1496   case Type::LongTyID:
1497     int64_t Val = read_vbr_int64();
1498     if (!ConstantSInt::isValueValidForType(Ty, Val))
1499       error("Invalid signed byte/short/int/long read.");
1500     Constant* Result = ConstantSInt::get(Ty, Val);
1501     if (Handler) Handler->handleConstantValue(Result);
1502     return Result;
1503   }
1504
1505   case Type::FloatTyID: {
1506     float Val;
1507     read_float(Val);
1508     Constant* Result = ConstantFP::get(Ty, Val);
1509     if (Handler) Handler->handleConstantValue(Result);
1510     return Result;
1511   }
1512
1513   case Type::DoubleTyID: {
1514     double Val;
1515     read_double(Val);
1516     Constant* Result = ConstantFP::get(Ty, Val);
1517     if (Handler) Handler->handleConstantValue(Result);
1518     return Result;
1519   }
1520
1521   case Type::ArrayTyID: {
1522     const ArrayType *AT = cast<ArrayType>(Ty);
1523     unsigned NumElements = AT->getNumElements();
1524     unsigned TypeSlot = getTypeSlot(AT->getElementType());
1525     std::vector<Constant*> Elements;
1526     Elements.reserve(NumElements);
1527     while (NumElements--)     // Read all of the elements of the constant.
1528       Elements.push_back(getConstantValue(TypeSlot,
1529                                           read_vbr_uint()));
1530     Constant* Result = ConstantArray::get(AT, Elements);
1531     if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
1532     return Result;
1533   }
1534
1535   case Type::StructTyID: {
1536     const StructType *ST = cast<StructType>(Ty);
1537
1538     std::vector<Constant *> Elements;
1539     Elements.reserve(ST->getNumElements());
1540     for (unsigned i = 0; i != ST->getNumElements(); ++i)
1541       Elements.push_back(getConstantValue(ST->getElementType(i),
1542                                           read_vbr_uint()));
1543
1544     Constant* Result = ConstantStruct::get(ST, Elements);
1545     if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
1546     return Result;
1547   }
1548
1549   case Type::PackedTyID: {
1550     const PackedType *PT = cast<PackedType>(Ty);
1551     unsigned NumElements = PT->getNumElements();
1552     unsigned TypeSlot = getTypeSlot(PT->getElementType());
1553     std::vector<Constant*> Elements;
1554     Elements.reserve(NumElements);
1555     while (NumElements--)     // Read all of the elements of the constant.
1556       Elements.push_back(getConstantValue(TypeSlot,
1557                                           read_vbr_uint()));
1558     Constant* Result = ConstantPacked::get(PT, Elements);
1559     if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
1560     return Result;
1561   }
1562
1563   case Type::PointerTyID: {  // ConstantPointerRef value (backwards compat).
1564     const PointerType *PT = cast<PointerType>(Ty);
1565     unsigned Slot = read_vbr_uint();
1566
1567     // Check to see if we have already read this global variable...
1568     Value *Val = getValue(TypeID, Slot, false);
1569     if (Val) {
1570       GlobalValue *GV = dyn_cast<GlobalValue>(Val);
1571       if (!GV) error("GlobalValue not in ValueTable!");
1572       if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
1573       return GV;
1574     } else {
1575       error("Forward references are not allowed here.");
1576     }
1577   }
1578
1579   default:
1580     error("Don't know how to deserialize constant value of type '" +
1581                       Ty->getDescription());
1582     break;
1583   }
1584   return 0;
1585 }
1586
1587 /// Resolve references for constants. This function resolves the forward
1588 /// referenced constants in the ConstantFwdRefs map. It uses the
1589 /// replaceAllUsesWith method of Value class to substitute the placeholder
1590 /// instance with the actual instance.
1591 void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
1592                                                  unsigned Slot) {
1593   ConstantRefsType::iterator I =
1594     ConstantFwdRefs.find(std::make_pair(Typ, Slot));
1595   if (I == ConstantFwdRefs.end()) return;   // Never forward referenced?
1596
1597   Value *PH = I->second;   // Get the placeholder...
1598   PH->replaceAllUsesWith(NewV);
1599   delete PH;                               // Delete the old placeholder
1600   ConstantFwdRefs.erase(I);                // Remove the map entry for it
1601 }
1602
1603 /// Parse the constant strings section.
1604 void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
1605   for (; NumEntries; --NumEntries) {
1606     unsigned Typ = 0;
1607     if (read_typeid(Typ))
1608       error("Invalid type (type type) for string constant");
1609     const Type *Ty = getType(Typ);
1610     if (!isa<ArrayType>(Ty))
1611       error("String constant data invalid!");
1612
1613     const ArrayType *ATy = cast<ArrayType>(Ty);
1614     if (ATy->getElementType() != Type::SByteTy &&
1615         ATy->getElementType() != Type::UByteTy)
1616       error("String constant data invalid!");
1617
1618     // Read character data.  The type tells us how long the string is.
1619     char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
1620     read_data(Data, Data+ATy->getNumElements());
1621
1622     std::vector<Constant*> Elements(ATy->getNumElements());
1623     if (ATy->getElementType() == Type::SByteTy)
1624       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1625         Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
1626     else
1627       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
1628         Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
1629
1630     // Create the constant, inserting it as needed.
1631     Constant *C = ConstantArray::get(ATy, Elements);
1632     unsigned Slot = insertValue(C, Typ, Tab);
1633     ResolveReferencesToConstant(C, Typ, Slot);
1634     if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
1635   }
1636 }
1637
1638 /// Parse the constant pool.
1639 void BytecodeReader::ParseConstantPool(ValueTable &Tab,
1640                                        TypeListTy &TypeTab,
1641                                        bool isFunction) {
1642   if (Handler) Handler->handleGlobalConstantsBegin();
1643
1644   /// In LLVM 1.3 Type does not derive from Value so the types
1645   /// do not occupy a plane. Consequently, we read the types
1646   /// first in the constant pool.
1647   if (isFunction && !hasTypeDerivedFromValue) {
1648     unsigned NumEntries = read_vbr_uint();
1649     ParseTypes(TypeTab, NumEntries);
1650   }
1651
1652   while (moreInBlock()) {
1653     unsigned NumEntries = read_vbr_uint();
1654     unsigned Typ = 0;
1655     bool isTypeType = read_typeid(Typ);
1656
1657     /// In LLVM 1.2 and before, Types were written to the
1658     /// bytecode file in the "Type Type" plane (#12).
1659     /// In 1.3 plane 12 is now the label plane.  Handle this here.
1660     if (isTypeType) {
1661       ParseTypes(TypeTab, NumEntries);
1662     } else if (Typ == Type::VoidTyID) {
1663       /// Use of Type::VoidTyID is a misnomer. It actually means
1664       /// that the following plane is constant strings
1665       assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
1666       ParseStringConstants(NumEntries, Tab);
1667     } else {
1668       for (unsigned i = 0; i < NumEntries; ++i) {
1669         Constant *C = ParseConstantValue(Typ);
1670         assert(C && "ParseConstantValue returned NULL!");
1671         unsigned Slot = insertValue(C, Typ, Tab);
1672
1673         // If we are reading a function constant table, make sure that we adjust
1674         // the slot number to be the real global constant number.
1675         //
1676         if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
1677             ModuleValues[Typ])
1678           Slot += ModuleValues[Typ]->size();
1679         ResolveReferencesToConstant(C, Typ, Slot);
1680       }
1681     }
1682   }
1683
1684   // After we have finished parsing the constant pool, we had better not have
1685   // any dangling references left.
1686   if (!ConstantFwdRefs.empty()) {
1687     ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
1688     Constant* missingConst = I->second;
1689     error(utostr(ConstantFwdRefs.size()) +
1690           " unresolved constant reference exist. First one is '" +
1691           missingConst->getName() + "' of type '" +
1692           missingConst->getType()->getDescription() + "'.");
1693   }
1694
1695   checkPastBlockEnd("Constant Pool");
1696   if (Handler) Handler->handleGlobalConstantsEnd();
1697 }
1698
1699 /// Parse the contents of a function. Note that this function can be
1700 /// called lazily by materializeFunction
1701 /// @see materializeFunction
1702 void BytecodeReader::ParseFunctionBody(Function* F) {
1703
1704   unsigned FuncSize = BlockEnd - At;
1705   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
1706
1707   unsigned LinkageType = read_vbr_uint();
1708   switch (LinkageType) {
1709   case 0: Linkage = GlobalValue::ExternalLinkage; break;
1710   case 1: Linkage = GlobalValue::WeakLinkage; break;
1711   case 2: Linkage = GlobalValue::AppendingLinkage; break;
1712   case 3: Linkage = GlobalValue::InternalLinkage; break;
1713   case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
1714   default:
1715     error("Invalid linkage type for Function.");
1716     Linkage = GlobalValue::InternalLinkage;
1717     break;
1718   }
1719
1720   F->setLinkage(Linkage);
1721   if (Handler) Handler->handleFunctionBegin(F,FuncSize);
1722
1723   // Keep track of how many basic blocks we have read in...
1724   unsigned BlockNum = 0;
1725   bool InsertedArguments = false;
1726
1727   BufPtr MyEnd = BlockEnd;
1728   while (At < MyEnd) {
1729     unsigned Type, Size;
1730     BufPtr OldAt = At;
1731     read_block(Type, Size);
1732
1733     switch (Type) {
1734     case BytecodeFormat::ConstantPoolBlockID:
1735       if (!InsertedArguments) {
1736         // Insert arguments into the value table before we parse the first basic
1737         // block in the function, but after we potentially read in the
1738         // compaction table.
1739         insertArguments(F);
1740         InsertedArguments = true;
1741       }
1742
1743       ParseConstantPool(FunctionValues, FunctionTypes, true);
1744       break;
1745
1746     case BytecodeFormat::CompactionTableBlockID:
1747       ParseCompactionTable();
1748       break;
1749
1750     case BytecodeFormat::BasicBlock: {
1751       if (!InsertedArguments) {
1752         // Insert arguments into the value table before we parse the first basic
1753         // block in the function, but after we potentially read in the
1754         // compaction table.
1755         insertArguments(F);
1756         InsertedArguments = true;
1757       }
1758
1759       BasicBlock *BB = ParseBasicBlock(BlockNum++);
1760       F->getBasicBlockList().push_back(BB);
1761       break;
1762     }
1763
1764     case BytecodeFormat::InstructionListBlockID: {
1765       // Insert arguments into the value table before we parse the instruction
1766       // list for the function, but after we potentially read in the compaction
1767       // table.
1768       if (!InsertedArguments) {
1769         insertArguments(F);
1770         InsertedArguments = true;
1771       }
1772
1773       if (BlockNum)
1774         error("Already parsed basic blocks!");
1775       BlockNum = ParseInstructionList(F);
1776       break;
1777     }
1778
1779     case BytecodeFormat::SymbolTableBlockID:
1780       ParseSymbolTable(F, &F->getSymbolTable());
1781       break;
1782
1783     default:
1784       At += Size;
1785       if (OldAt > At)
1786         error("Wrapped around reading bytecode.");
1787       break;
1788     }
1789     BlockEnd = MyEnd;
1790
1791     // Malformed bc file if read past end of block.
1792     align32();
1793   }
1794
1795   // Make sure there were no references to non-existant basic blocks.
1796   if (BlockNum != ParsedBasicBlocks.size())
1797     error("Illegal basic block operand reference");
1798
1799   ParsedBasicBlocks.clear();
1800
1801   // Resolve forward references.  Replace any uses of a forward reference value
1802   // with the real value.
1803   while (!ForwardReferences.empty()) {
1804     std::map<std::pair<unsigned,unsigned>, Value*>::iterator
1805       I = ForwardReferences.begin();
1806     Value *V = getValue(I->first.first, I->first.second, false);
1807     Value *PlaceHolder = I->second;
1808     PlaceHolder->replaceAllUsesWith(V);
1809     ForwardReferences.erase(I);
1810     delete PlaceHolder;
1811   }
1812
1813   // Clear out function-level types...
1814   FunctionTypes.clear();
1815   CompactionTypes.clear();
1816   CompactionValues.clear();
1817   freeTable(FunctionValues);
1818
1819   if (Handler) Handler->handleFunctionEnd(F);
1820 }
1821
1822 /// This function parses LLVM functions lazily. It obtains the type of the
1823 /// function and records where the body of the function is in the bytecode
1824 /// buffer. The caller can then use the ParseNextFunction and
1825 /// ParseAllFunctionBodies to get handler events for the functions.
1826 void BytecodeReader::ParseFunctionLazily() {
1827   if (FunctionSignatureList.empty())
1828     error("FunctionSignatureList empty!");
1829
1830   Function *Func = FunctionSignatureList.back();
1831   FunctionSignatureList.pop_back();
1832
1833   // Save the information for future reading of the function
1834   LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
1835
1836   // This function has a body but it's not loaded so it appears `External'.
1837   // Mark it as a `Ghost' instead to notify the users that it has a body.
1838   Func->setLinkage(GlobalValue::GhostLinkage);
1839
1840   // Pretend we've `parsed' this function
1841   At = BlockEnd;
1842 }
1843
1844 /// The ParserFunction method lazily parses one function. Use this method to
1845 /// casue the parser to parse a specific function in the module. Note that
1846 /// this will remove the function from what is to be included by
1847 /// ParseAllFunctionBodies.
1848 /// @see ParseAllFunctionBodies
1849 /// @see ParseBytecode
1850 void BytecodeReader::ParseFunction(Function* Func) {
1851   // Find {start, end} pointers and slot in the map. If not there, we're done.
1852   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
1853
1854   // Make sure we found it
1855   if (Fi == LazyFunctionLoadMap.end()) {
1856     error("Unrecognized function of type " + Func->getType()->getDescription());
1857     return;
1858   }
1859
1860   BlockStart = At = Fi->second.Buf;
1861   BlockEnd = Fi->second.EndBuf;
1862   assert(Fi->first == Func && "Found wrong function?");
1863
1864   LazyFunctionLoadMap.erase(Fi);
1865
1866   this->ParseFunctionBody(Func);
1867 }
1868
1869 /// The ParseAllFunctionBodies method parses through all the previously
1870 /// unparsed functions in the bytecode file. If you want to completely parse
1871 /// a bytecode file, this method should be called after Parsebytecode because
1872 /// Parsebytecode only records the locations in the bytecode file of where
1873 /// the function definitions are located. This function uses that information
1874 /// to materialize the functions.
1875 /// @see ParseBytecode
1876 void BytecodeReader::ParseAllFunctionBodies() {
1877   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
1878   LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
1879
1880   while (Fi != Fe) {
1881     Function* Func = Fi->first;
1882     BlockStart = At = Fi->second.Buf;
1883     BlockEnd = Fi->second.EndBuf;
1884     ParseFunctionBody(Func);
1885     ++Fi;
1886   }
1887   LazyFunctionLoadMap.clear();
1888 }
1889
1890 /// Parse the global type list
1891 void BytecodeReader::ParseGlobalTypes() {
1892   // Read the number of types
1893   unsigned NumEntries = read_vbr_uint();
1894
1895   // Ignore the type plane identifier for types if the bc file is pre 1.3
1896   if (hasTypeDerivedFromValue)
1897     read_vbr_uint();
1898
1899   ParseTypes(ModuleTypes, NumEntries);
1900 }
1901
1902 /// Parse the Global info (types, global vars, constants)
1903 void BytecodeReader::ParseModuleGlobalInfo() {
1904
1905   if (Handler) Handler->handleModuleGlobalsBegin();
1906
1907   // SectionID - If a global has an explicit section specified, this map
1908   // remembers the ID until we can translate it into a string.
1909   std::map<GlobalValue*, unsigned> SectionID;
1910   
1911   // Read global variables...
1912   unsigned VarType = read_vbr_uint();
1913   while (VarType != Type::VoidTyID) { // List is terminated by Void
1914     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
1915     // Linkage, bit4+ = slot#
1916     unsigned SlotNo = VarType >> 5;
1917     if (sanitizeTypeId(SlotNo))
1918       error("Invalid type (type type) for global var!");
1919     unsigned LinkageID = (VarType >> 2) & 7;
1920     bool isConstant = VarType & 1;
1921     bool hasInitializer = (VarType & 2) != 0;
1922     unsigned Alignment = 0;
1923     unsigned GlobalSectionID = 0;
1924     
1925     // An extension word is present when linkage = 3 (internal) and hasinit = 0.
1926     if (LinkageID == 3 && !hasInitializer) {
1927       unsigned ExtWord = read_vbr_uint();
1928       // The extension word has this format: bit 0 = has initializer, bit 1-3 =
1929       // linkage, bit 4-8 = alignment (log2), bits 10+ = future use.
1930       hasInitializer = ExtWord & 1;
1931       LinkageID = (ExtWord >> 1) & 7;
1932       Alignment = (1 << ((ExtWord >> 4) & 31)) >> 1;
1933       
1934       if (ExtWord & (1 << 9))  // Has a section ID.
1935         GlobalSectionID = read_vbr_uint();
1936     }
1937
1938     GlobalValue::LinkageTypes Linkage;
1939     switch (LinkageID) {
1940     case 0: Linkage = GlobalValue::ExternalLinkage;  break;
1941     case 1: Linkage = GlobalValue::WeakLinkage;      break;
1942     case 2: Linkage = GlobalValue::AppendingLinkage; break;
1943     case 3: Linkage = GlobalValue::InternalLinkage;  break;
1944     case 4: Linkage = GlobalValue::LinkOnceLinkage;  break;
1945     default:
1946       error("Unknown linkage type: " + utostr(LinkageID));
1947       Linkage = GlobalValue::InternalLinkage;
1948       break;
1949     }
1950
1951     const Type *Ty = getType(SlotNo);
1952     if (!Ty)
1953       error("Global has no type! SlotNo=" + utostr(SlotNo));
1954
1955     if (!isa<PointerType>(Ty))
1956       error("Global not a pointer type! Ty= " + Ty->getDescription());
1957
1958     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
1959
1960     // Create the global variable...
1961     GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
1962                                             0, "", TheModule);
1963     GV->setAlignment(Alignment);
1964     insertValue(GV, SlotNo, ModuleValues);
1965
1966     if (GlobalSectionID != 0)
1967       SectionID[GV] = GlobalSectionID;
1968
1969     unsigned initSlot = 0;
1970     if (hasInitializer) {
1971       initSlot = read_vbr_uint();
1972       GlobalInits.push_back(std::make_pair(GV, initSlot));
1973     }
1974
1975     // Notify handler about the global value.
1976     if (Handler)
1977       Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
1978
1979     // Get next item
1980     VarType = read_vbr_uint();
1981   }
1982
1983   // Read the function objects for all of the functions that are coming
1984   unsigned FnSignature = read_vbr_uint();
1985
1986   if (hasNoFlagsForFunctions)
1987     FnSignature = (FnSignature << 5) + 1;
1988
1989   // List is terminated by VoidTy.
1990   while (((FnSignature & (~0U >> 1)) >> 5) != Type::VoidTyID) {
1991     const Type *Ty = getType((FnSignature & (~0U >> 1)) >> 5);
1992     if (!isa<PointerType>(Ty) ||
1993         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
1994       error("Function not a pointer to function type! Ty = " +
1995             Ty->getDescription());
1996     }
1997
1998     // We create functions by passing the underlying FunctionType to create...
1999     const FunctionType* FTy =
2000       cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
2001
2002     // Insert the place holder.
2003     Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
2004                                   "", TheModule);
2005     insertValue(Func, (FnSignature & (~0U >> 1)) >> 5, ModuleValues);
2006
2007     // Flags are not used yet.
2008     unsigned Flags = FnSignature & 31;
2009
2010     // Save this for later so we know type of lazily instantiated functions.
2011     // Note that known-external functions do not have FunctionInfo blocks, so we
2012     // do not add them to the FunctionSignatureList.
2013     if ((Flags & (1 << 4)) == 0)
2014       FunctionSignatureList.push_back(Func);
2015
2016     // Get the calling convention from the low bits.
2017     unsigned CC = Flags & 15;
2018     unsigned Alignment = 0;
2019     if (FnSignature & (1 << 31)) {  // Has extension word?
2020       unsigned ExtWord = read_vbr_uint();
2021       Alignment = (1 << (ExtWord & 31)) >> 1;
2022       CC |= ((ExtWord >> 5) & 15) << 4;
2023       
2024       if (ExtWord & (1 << 10))  // Has a section ID.
2025         SectionID[Func] = read_vbr_uint();
2026     }
2027     
2028     Func->setCallingConv(CC-1);
2029     Func->setAlignment(Alignment);
2030
2031     if (Handler) Handler->handleFunctionDeclaration(Func);
2032
2033     // Get the next function signature.
2034     FnSignature = read_vbr_uint();
2035     if (hasNoFlagsForFunctions)
2036       FnSignature = (FnSignature << 5) + 1;
2037   }
2038
2039   // Now that the function signature list is set up, reverse it so that we can
2040   // remove elements efficiently from the back of the vector.
2041   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
2042
2043   /// SectionNames - This contains the list of section names encoded in the
2044   /// moduleinfoblock.  Functions and globals with an explicit section index
2045   /// into this to get their section name.
2046   std::vector<std::string> SectionNames;
2047   
2048   if (hasInconsistentModuleGlobalInfo) {
2049     align32();
2050   } else if (!hasNoDependentLibraries) {
2051     // If this bytecode format has dependent library information in it, read in
2052     // the number of dependent library items that follow.
2053     unsigned num_dep_libs = read_vbr_uint();
2054     std::string dep_lib;
2055     while (num_dep_libs--) {
2056       dep_lib = read_str();
2057       TheModule->addLibrary(dep_lib);
2058       if (Handler)
2059         Handler->handleDependentLibrary(dep_lib);
2060     }
2061
2062     // Read target triple and place into the module.
2063     std::string triple = read_str();
2064     TheModule->setTargetTriple(triple);
2065     if (Handler)
2066       Handler->handleTargetTriple(triple);
2067     
2068     if (At != BlockEnd && !hasAlignment) {
2069       // If the file has section info in it, read the section names now.
2070       unsigned NumSections = read_vbr_uint();
2071       while (NumSections--)
2072         SectionNames.push_back(read_str());
2073     }
2074   }
2075
2076   // If any globals are in specified sections, assign them now.
2077   for (std::map<GlobalValue*, unsigned>::iterator I = SectionID.begin(), E =
2078        SectionID.end(); I != E; ++I)
2079     if (I->second) {
2080       if (I->second > SectionID.size())
2081         error("SectionID out of range for global!");
2082       I->first->setSection(SectionNames[I->second-1]);
2083     }
2084
2085   // This is for future proofing... in the future extra fields may be added that
2086   // we don't understand, so we transparently ignore them.
2087   //
2088   At = BlockEnd;
2089
2090   if (Handler) Handler->handleModuleGlobalsEnd();
2091 }
2092
2093 /// Parse the version information and decode it by setting flags on the
2094 /// Reader that enable backward compatibility of the reader.
2095 void BytecodeReader::ParseVersionInfo() {
2096   unsigned Version = read_vbr_uint();
2097
2098   // Unpack version number: low four bits are for flags, top bits = version
2099   Module::Endianness  Endianness;
2100   Module::PointerSize PointerSize;
2101   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
2102   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
2103
2104   bool hasNoEndianness = Version & 4;
2105   bool hasNoPointerSize = Version & 8;
2106
2107   RevisionNum = Version >> 4;
2108
2109   // Default values for the current bytecode version
2110   hasInconsistentModuleGlobalInfo = false;
2111   hasExplicitPrimitiveZeros = false;
2112   hasRestrictedGEPTypes = false;
2113   hasTypeDerivedFromValue = false;
2114   hasLongBlockHeaders = false;
2115   has32BitTypes = false;
2116   hasNoDependentLibraries = false;
2117   hasAlignment = false;
2118   hasNoUndefValue = false;
2119   hasNoFlagsForFunctions = false;
2120   hasNoUnreachableInst = false;
2121
2122   switch (RevisionNum) {
2123   case 0:               //  LLVM 1.0, 1.1 (Released)
2124     // Base LLVM 1.0 bytecode format.
2125     hasInconsistentModuleGlobalInfo = true;
2126     hasExplicitPrimitiveZeros = true;
2127
2128     // FALL THROUGH
2129
2130   case 1:               // LLVM 1.2 (Released)
2131     // LLVM 1.2 added explicit support for emitting strings efficiently.
2132
2133     // Also, it fixed the problem where the size of the ModuleGlobalInfo block
2134     // included the size for the alignment at the end, where the rest of the
2135     // blocks did not.
2136
2137     // LLVM 1.2 and before required that GEP indices be ubyte constants for
2138     // structures and longs for sequential types.
2139     hasRestrictedGEPTypes = true;
2140
2141     // LLVM 1.2 and before had the Type class derive from Value class. This
2142     // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
2143     // written differently because Types can no longer be part of the
2144     // type planes for Values.
2145     hasTypeDerivedFromValue = true;
2146
2147     // FALL THROUGH
2148
2149   case 2:                // 1.2.5 (Not Released)
2150
2151     // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
2152     // especially for small files where the 8 bytes per block is a large
2153     // fraction of the total block size. In LLVM 1.3, the block type and length
2154     // are compressed into a single 32-bit unsigned integer. 27 bits for length,
2155     // 5 bits for block type.
2156     hasLongBlockHeaders = true;
2157
2158     // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
2159     // this has been reduced to vbr_uint24. It shouldn't make much difference
2160     // since we haven't run into a module with > 24 million types, but for
2161     // safety the 24-bit restriction has been enforced in 1.3 to free some bits
2162     // in various places and to ensure consistency.
2163     has32BitTypes = true;
2164
2165     // LLVM 1.2 and earlier did not provide a target triple nor a list of
2166     // libraries on which the bytecode is dependent. LLVM 1.3 provides these
2167     // features, for use in future versions of LLVM.
2168     hasNoDependentLibraries = true;
2169
2170     // FALL THROUGH
2171
2172   case 3:               // LLVM 1.3 (Released)
2173     // LLVM 1.3 and earlier caused alignment bytes to be written on some block
2174     // boundaries and at the end of some strings. In extreme cases (e.g. lots
2175     // of GEP references to a constant array), this can increase the file size
2176     // by 30% or more. In version 1.4 alignment is done away with completely.
2177     hasAlignment = true;
2178
2179     // FALL THROUGH
2180
2181   case 4:               // 1.3.1 (Not Released)
2182     // In version 4, we did not support the 'undef' constant.
2183     hasNoUndefValue = true;
2184
2185     // In version 4 and above, we did not include space for flags for functions
2186     // in the module info block.
2187     hasNoFlagsForFunctions = true;
2188
2189     // In version 4 and above, we did not include the 'unreachable' instruction
2190     // in the opcode numbering in the bytecode file.
2191     hasNoUnreachableInst = true;
2192     break;
2193
2194     // FALL THROUGH
2195
2196   case 5:               // 1.4 (Released)
2197     break;
2198
2199   default:
2200     error("Unknown bytecode version number: " + itostr(RevisionNum));
2201   }
2202
2203   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
2204   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
2205
2206   TheModule->setEndianness(Endianness);
2207   TheModule->setPointerSize(PointerSize);
2208
2209   if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
2210 }
2211
2212 /// Parse a whole module.
2213 void BytecodeReader::ParseModule() {
2214   unsigned Type, Size;
2215
2216   FunctionSignatureList.clear(); // Just in case...
2217
2218   // Read into instance variables...
2219   ParseVersionInfo();
2220   align32();
2221
2222   bool SeenModuleGlobalInfo = false;
2223   bool SeenGlobalTypePlane = false;
2224   BufPtr MyEnd = BlockEnd;
2225   while (At < MyEnd) {
2226     BufPtr OldAt = At;
2227     read_block(Type, Size);
2228
2229     switch (Type) {
2230
2231     case BytecodeFormat::GlobalTypePlaneBlockID:
2232       if (SeenGlobalTypePlane)
2233         error("Two GlobalTypePlane Blocks Encountered!");
2234
2235       if (Size > 0)
2236         ParseGlobalTypes();
2237       SeenGlobalTypePlane = true;
2238       break;
2239
2240     case BytecodeFormat::ModuleGlobalInfoBlockID:
2241       if (SeenModuleGlobalInfo)
2242         error("Two ModuleGlobalInfo Blocks Encountered!");
2243       ParseModuleGlobalInfo();
2244       SeenModuleGlobalInfo = true;
2245       break;
2246
2247     case BytecodeFormat::ConstantPoolBlockID:
2248       ParseConstantPool(ModuleValues, ModuleTypes,false);
2249       break;
2250
2251     case BytecodeFormat::FunctionBlockID:
2252       ParseFunctionLazily();
2253       break;
2254
2255     case BytecodeFormat::SymbolTableBlockID:
2256       ParseSymbolTable(0, &TheModule->getSymbolTable());
2257       break;
2258
2259     default:
2260       At += Size;
2261       if (OldAt > At) {
2262         error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
2263       }
2264       break;
2265     }
2266     BlockEnd = MyEnd;
2267     align32();
2268   }
2269
2270   // After the module constant pool has been read, we can safely initialize
2271   // global variables...
2272   while (!GlobalInits.empty()) {
2273     GlobalVariable *GV = GlobalInits.back().first;
2274     unsigned Slot = GlobalInits.back().second;
2275     GlobalInits.pop_back();
2276
2277     // Look up the initializer value...
2278     // FIXME: Preserve this type ID!
2279
2280     const llvm::PointerType* GVType = GV->getType();
2281     unsigned TypeSlot = getTypeSlot(GVType->getElementType());
2282     if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
2283       if (GV->hasInitializer())
2284         error("Global *already* has an initializer?!");
2285       if (Handler) Handler->handleGlobalInitializer(GV,CV);
2286       GV->setInitializer(CV);
2287     } else
2288       error("Cannot find initializer value.");
2289   }
2290
2291   if (!ConstantFwdRefs.empty())
2292     error("Use of undefined constants in a module");
2293
2294   /// Make sure we pulled them all out. If we didn't then there's a declaration
2295   /// but a missing body. That's not allowed.
2296   if (!FunctionSignatureList.empty())
2297     error("Function declared, but bytecode stream ended before definition");
2298 }
2299
2300 /// This function completely parses a bytecode buffer given by the \p Buf
2301 /// and \p Length parameters.
2302 void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
2303                                    const std::string &ModuleID) {
2304
2305   try {
2306     RevisionNum = 0;
2307     At = MemStart = BlockStart = Buf;
2308     MemEnd = BlockEnd = Buf + Length;
2309
2310     // Create the module
2311     TheModule = new Module(ModuleID);
2312
2313     if (Handler) Handler->handleStart(TheModule, Length);
2314
2315     // Read the four bytes of the signature.
2316     unsigned Sig = read_uint();
2317
2318     // If this is a compressed file
2319     if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
2320
2321       // Invoke the decompression of the bytecode. Note that we have to skip the
2322       // file's magic number which is not part of the compressed block. Hence,
2323       // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
2324       // member for retention until BytecodeReader is destructed.
2325       unsigned decompressedLength = Compressor::decompressToNewBuffer(
2326           (char*)Buf+4,Length-4,decompressedBlock);
2327
2328       // We must adjust the buffer pointers used by the bytecode reader to point
2329       // into the new decompressed block. After decompression, the
2330       // decompressedBlock will point to a contiguous memory area that has
2331       // the decompressed data.
2332       At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
2333       MemEnd = BlockEnd = Buf + decompressedLength;
2334
2335     // else if this isn't a regular (uncompressed) bytecode file, then its
2336     // and error, generate that now.
2337     } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
2338       error("Invalid bytecode signature: " + utohexstr(Sig));
2339     }
2340
2341     // Tell the handler we're starting a module
2342     if (Handler) Handler->handleModuleBegin(ModuleID);
2343
2344     // Get the module block and size and verify. This is handled specially
2345     // because the module block/size is always written in long format. Other
2346     // blocks are written in short format so the read_block method is used.
2347     unsigned Type, Size;
2348     Type = read_uint();
2349     Size = read_uint();
2350     if (Type != BytecodeFormat::ModuleBlockID) {
2351       error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
2352             + utostr(Size));
2353     }
2354
2355     // It looks like the darwin ranlib program is broken, and adds trailing
2356     // garbage to the end of some bytecode files.  This hack allows the bc
2357     // reader to ignore trailing garbage on bytecode files.
2358     if (At + Size < MemEnd)
2359       MemEnd = BlockEnd = At+Size;
2360
2361     if (At + Size != MemEnd)
2362       error("Invalid Top Level Block Length! Type:" + utostr(Type)
2363             + ", Size:" + utostr(Size));
2364
2365     // Parse the module contents
2366     this->ParseModule();
2367
2368     // Check for missing functions
2369     if (hasFunctions())
2370       error("Function expected, but bytecode stream ended!");
2371
2372     // Tell the handler we're done with the module
2373     if (Handler)
2374       Handler->handleModuleEnd(ModuleID);
2375
2376     // Tell the handler we're finished the parse
2377     if (Handler) Handler->handleFinish();
2378
2379   } catch (std::string& errstr) {
2380     if (Handler) Handler->handleError(errstr);
2381     freeState();
2382     delete TheModule;
2383     TheModule = 0;
2384     if (decompressedBlock != 0 ) {
2385       ::free(decompressedBlock);
2386       decompressedBlock = 0;
2387     }
2388     throw;
2389   } catch (...) {
2390     std::string msg("Unknown Exception Occurred");
2391     if (Handler) Handler->handleError(msg);
2392     freeState();
2393     delete TheModule;
2394     TheModule = 0;
2395     if (decompressedBlock != 0) {
2396       ::free(decompressedBlock);
2397       decompressedBlock = 0;
2398     }
2399     throw msg;
2400   }
2401 }
2402
2403 //===----------------------------------------------------------------------===//
2404 //=== Default Implementations of Handler Methods
2405 //===----------------------------------------------------------------------===//
2406
2407 BytecodeHandler::~BytecodeHandler() {}
2408