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