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