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