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