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