67726eb2c11aa145372cbfc7b0e611ae4ec27b5e
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
2 //
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
4 //
5 // Note that this library should be as fast as possible, reentrant, and 
6 // threadsafe!!
7 //
8 // TODO: Return error messages to caller instead of printing them out directly.
9 // TODO: Allow passing in an option to ignore the symbol table
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "ReaderInternals.h"
14 #include "llvm/Bytecode/Reader.h"
15 #include "llvm/Bytecode/Format.h"
16 #include "llvm/Constants.h"
17 #include "llvm/iPHINode.h"
18 #include "llvm/iOther.h"
19 #include "llvm/Module.h"
20 #include "Support/StringExtras.h"
21 #include "Config/unistd.h"
22 #include "Config/sys/mman.h"
23 #include "Config/sys/stat.h"
24 #include "Config/sys/types.h"
25 #include <algorithm>
26 #include <memory>
27
28 static inline void ALIGN32(const unsigned char *&begin,
29                            const unsigned char *end) {
30   if (align32(begin, end))
31     throw std::string("Alignment error in buffer: read past end of block.");
32 }
33
34 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35   if (Ty->isPrimitiveType())
36     return Ty->getPrimitiveID();
37
38   // Check the function level types first...
39   TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
40                                       FunctionTypeValues.end(), Ty);
41   if (I != FunctionTypeValues.end())
42     return FirstDerivedTyID + ModuleTypeValues.size() +
43              (&*I - &FunctionTypeValues[0]);
44
45   I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
46   if (I == ModuleTypeValues.end())
47     throw std::string("Didn't find type in ModuleTypeValues.");
48   return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
49 }
50
51 const Type *BytecodeParser::getType(unsigned ID) {
52   if (ID < Type::NumPrimitiveIDs) {
53     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
54     if (T) return T;
55   }
56   
57   //cerr << "Looking up Type ID: " << ID << "\n";
58
59   if (ID < Type::NumPrimitiveIDs) {
60     const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
61     if (T) return T;   // Asked for a primitive type...
62   }
63
64   // Otherwise, derived types need offset...
65   ID -= FirstDerivedTyID;
66
67   // Is it a module-level type?
68   if (ID < ModuleTypeValues.size())
69     return ModuleTypeValues[ID].get();
70
71   // Nope, is it a function-level type?
72   ID -= ModuleTypeValues.size();
73   if (ID < FunctionTypeValues.size())
74     return FunctionTypeValues[ID].get();
75
76   return 0;
77 }
78
79 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
80   assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
81           Val->getType()->isPrimitiveType() ||
82           !cast<Constant>(Val)->isNullValue()) &&
83          "Cannot read null values from bytecode!");
84   unsigned type = getTypeSlot(Val->getType());
85   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
86  
87   if (ValueTab.size() <= type) {
88     unsigned OldSize = ValueTab.size();
89     ValueTab.resize(type+1);
90     while (OldSize != type+1)
91       ValueTab[OldSize++] = new ValueList();
92   }
93
94   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
95   //   << "] = " << Val << "\n";
96   ValueTab[type]->push_back(Val);
97
98   bool HasOffset = HasImplicitZeroInitializer &&
99     !Val->getType()->isPrimitiveType();
100
101   return ValueTab[type]->size()-1 + HasOffset;
102 }
103
104
105 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
106   return getValue(getTypeSlot(Ty), oNum, Create);
107 }
108
109 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
110   assert(type != Type::TypeTyID && "getValue() cannot get types!");
111   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
112   unsigned Num = oNum;
113
114   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
115     if (Num == 0)
116       return Constant::getNullValue(getType(type));
117     --Num;
118   }
119
120   if (type < ModuleValues.size()) {
121     if (Num < ModuleValues[type]->size())
122       return ModuleValues[type]->getOperand(Num);
123     Num -= ModuleValues[type]->size();
124   }
125
126   if (Values.size() > type && Values[type]->size() > Num)
127     return Values[type]->getOperand(Num);
128
129   if (!Create) return 0;  // Do not create a placeholder?
130
131   std::pair<unsigned,unsigned> KeyValue(type, oNum);
132   std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = 
133     ForwardReferences.lower_bound(KeyValue);
134   if (I != ForwardReferences.end() && I->first == KeyValue)
135     return I->second;   // We have already created this placeholder
136
137   Value *Val = new Argument(getType(type));
138   ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
139   return Val;
140 }
141
142 /// getBasicBlock - Get a particular numbered basic block, which might be a
143 /// forward reference.  This works together with ParseBasicBlock to handle these
144 /// forward references in a clean manner.
145 ///
146 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
147   // Make sure there is room in the table...
148   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
149
150   // First check to see if this is a backwards reference, i.e., ParseBasicBlock
151   // has already created this block, or if the forward reference has already
152   // been created.
153   if (ParsedBasicBlocks[ID])
154     return ParsedBasicBlocks[ID];
155
156   // Otherwise, the basic block has not yet been created.  Do so and add it to
157   // the ParsedBasicBlocks list.
158   return ParsedBasicBlocks[ID] = new BasicBlock();
159 }
160
161 /// getConstantValue - Just like getValue, except that it returns a null pointer
162 /// only on error.  It always returns a constant (meaning that if the value is
163 /// defined, but is not a constant, that is an error).  If the specified
164 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
165 /// after the real value is parsed, the placeholder is eliminated.
166 ///
167 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
168   if (Value *V = getValue(Ty, Slot, false))
169     return dyn_cast<Constant>(V);      // If we already have the value parsed...
170
171   std::pair<const Type*, unsigned> Key(Ty, Slot);
172   GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
173
174   if (I != GlobalRefs.end() && I->first == Key) {
175     BCR_TRACE(5, "Previous forward ref found!\n");
176     return cast<Constant>(I->second);
177   } else {
178     // Create a placeholder for the constant reference and
179     // keep track of the fact that we have a forward ref to recycle it
180     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
181     Constant *C = new ConstPHolder(Ty, Slot);
182     
183     // Keep track of the fact that we have a forward ref to recycle it
184     GlobalRefs.insert(I, std::make_pair(Key, C));
185     return C;
186   }
187 }
188
189
190 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
191                                             const unsigned char *EndBuf,
192                                             unsigned BlockNo) {
193   BasicBlock *BB;
194   if (ParsedBasicBlocks.size() == BlockNo)
195     ParsedBasicBlocks.push_back(BB = new BasicBlock());
196   else if (ParsedBasicBlocks[BlockNo] == 0)
197     BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
198   else
199     BB = ParsedBasicBlocks[BlockNo];
200
201   while (Buf < EndBuf) {
202     Instruction *Inst = ParseInstruction(Buf, EndBuf);
203     if (insertValue(Inst, Values) == -1) { 
204       throw std::string("Could not insert value.");
205     }
206
207     BB->getInstList().push_back(Inst);
208     BCR_TRACE(4, Inst);
209   }
210
211   return BB;
212 }
213
214 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
215                                       const unsigned char *EndBuf,
216                                       SymbolTable *ST,
217                                       Function *CurrentFunction) {
218   while (Buf < EndBuf) {
219     // Symtab block header: [num entries][type id number]
220     unsigned NumEntries, Typ;
221     if (read_vbr(Buf, EndBuf, NumEntries) ||
222         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
223     const Type *Ty = getType(Typ);
224     if (Ty == 0) throw std::string("Invalid type read in symbol table.");
225
226     BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
227                  " entries\n");
228
229     for (unsigned i = 0; i < NumEntries; ++i) {
230       // Symtab entry: [def slot #][name]
231       unsigned slot;
232       if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
233       std::string Name;
234       if (read(Buf, EndBuf, Name, false))  // Not aligned...
235         throw std::string("Buffer not aligned.");
236
237       Value *V = 0;
238       if (Typ == Type::TypeTyID)
239         V = (Value*)getType(slot);
240       else if (Typ == Type::LabelTyID) {
241         if (CurrentFunction) {
242           // FIXME: THIS IS N^2!!!
243           Function::iterator BlockIterator = CurrentFunction->begin();
244           std::advance(BlockIterator, slot);
245           V = BlockIterator;
246         }
247       } else
248         V = getValue(Typ, slot, false); // Find mapping...
249       if (V == 0) throw std::string("Failed value look-up.");
250       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
251                 if (!isa<Instruction>(V)) std::cerr << "\n");
252
253       V->setName(Name, ST);
254     }
255   }
256
257   if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
258 }
259
260 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
261   GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
262                                                               Slot));
263   if (I == GlobalRefs.end()) return;   // Never forward referenced?
264
265   BCR_TRACE(3, "Mutating forward refs!\n");
266   Value *VPH = I->second;   // Get the placeholder...
267
268   VPH->replaceAllUsesWith(NewV);
269
270   // If this is a global variable being resolved, remove the placeholder from
271   // the module...
272   if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
273     GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
274
275   delete VPH;                         // Delete the old placeholder
276   GlobalRefs.erase(I);                // Remove the map entry for it
277 }
278
279 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
280                                    const unsigned char *EndBuf) {
281   if (FunctionSignatureList.empty())
282     throw std::string("FunctionSignatureList empty!");
283
284   Function *F = FunctionSignatureList.back().first;
285   unsigned FunctionSlot = FunctionSignatureList.back().second;
286   FunctionSignatureList.pop_back();
287
288   // Save the information for future reading of the function
289   LazyFunctionInfo *LFI = new LazyFunctionInfo();
290   LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
291   LazyFunctionLoadMap[F] = LFI;
292   // Pretend we've `parsed' this function
293   Buf = EndBuf;
294 }
295
296 void BytecodeParser::materializeFunction(Function* F) {
297   // Find {start, end} pointers and slot in the map. If not there, we're done.
298   std::map<Function*, LazyFunctionInfo*>::iterator Fi =
299     LazyFunctionLoadMap.find(F);
300   if (Fi == LazyFunctionLoadMap.end()) return;
301   
302   LazyFunctionInfo *LFI = Fi->second;
303   const unsigned char *Buf = LFI->Buf;
304   const unsigned char *EndBuf = LFI->EndBuf;
305   unsigned FunctionSlot = LFI->FunctionSlot;
306   LazyFunctionLoadMap.erase(Fi);
307   delete LFI;
308
309   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
310
311   if (!hasInternalMarkerOnly) {
312     unsigned LinkageType;
313     if (read_vbr(Buf, EndBuf, LinkageType)) 
314       throw std::string("ParseFunction: Error reading from buffer.");
315     if (LinkageType & ~0x3) 
316       throw std::string("Invalid linkage type for Function.");
317     Linkage = (GlobalValue::LinkageTypes)LinkageType;
318   } else {
319     // We used to only support two linkage models: internal and external
320     unsigned isInternal;
321     if (read_vbr(Buf, EndBuf, isInternal)) 
322       throw std::string("ParseFunction: Error reading from buffer.");
323     if (isInternal) Linkage = GlobalValue::InternalLinkage;
324   }
325
326   F->setLinkage(Linkage);
327
328   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
329   Function::aiterator AI = F->abegin();
330   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
331        It != Params.end(); ++It, ++AI) {
332     if (insertValue(AI, Values) == -1)
333       throw std::string("Error reading function arguments!");
334   }
335
336   // Keep track of how many basic blocks we have read in...
337   unsigned BlockNum = 0;
338
339   while (Buf < EndBuf) {
340     unsigned Type, Size;
341     const unsigned char *OldBuf = Buf;
342     readBlock(Buf, EndBuf, Type, Size);
343
344     switch (Type) {
345     case BytecodeFormat::ConstantPool: {
346       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
347       ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
348       break;
349     }
350
351     case BytecodeFormat::BasicBlock: {
352       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
353       BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
354       F->getBasicBlockList().push_back(BB);
355       break;
356     }
357
358     case BytecodeFormat::SymbolTable: {
359       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
360       ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
361       break;
362     }
363
364     default:
365       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
366       Buf += Size;
367       if (OldBuf > Buf) 
368         throw std::string("Wrapped around reading bytecode.");
369       break;
370     }
371     BCR_TRACE(2, "} end block\n");
372
373     // Malformed bc file if read past end of block.
374     ALIGN32(Buf, EndBuf);
375   }
376
377   // Make sure there were no references to non-existant basic blocks.
378   if (BlockNum != ParsedBasicBlocks.size())
379     throw std::string("Illegal basic block operand reference");
380   ParsedBasicBlocks.clear();
381
382
383   // Resolve forward references
384   while (!ForwardReferences.empty()) {
385     std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = ForwardReferences.begin();
386     unsigned type = I->first.first;
387     unsigned Slot = I->first.second;
388     Value *PlaceHolder = I->second;
389     ForwardReferences.erase(I);
390
391     Value *NewVal = getValue(type, Slot, false);
392     if (NewVal == 0)
393       throw std::string("Unresolvable reference found: <" +
394                         PlaceHolder->getType()->getDescription() + ">:" + 
395                         utostr(Slot) + ".");
396
397     // Fixup all of the uses of this placeholder def...
398     PlaceHolder->replaceAllUsesWith(NewVal);
399       
400     // Now that all the uses are gone, delete the placeholder...
401     // If we couldn't find a def (error case), then leak a little
402     // memory, because otherwise we can't remove all uses!
403     delete PlaceHolder;
404   }
405
406   // Clear out function-level types...
407   FunctionTypeValues.clear();
408
409   freeTable(Values);
410 }
411
412 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
413                                            const unsigned char *End) {
414   if (!FunctionSignatureList.empty())
415     throw std::string("Two ModuleGlobalInfo packets found!");
416
417   // Read global variables...
418   unsigned VarType;
419   if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
420   while (VarType != Type::VoidTyID) { // List is terminated by Void
421     unsigned SlotNo;
422     GlobalValue::LinkageTypes Linkage;
423
424     if (!hasInternalMarkerOnly) {
425       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
426       // bit2,3 = Linkage, bit4+ = slot#
427       SlotNo = VarType >> 4;
428       Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
429     } else {
430       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
431       // bit2 = isInternal, bit3+ = slot#
432       SlotNo = VarType >> 3;
433       Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
434         GlobalValue::ExternalLinkage;
435     }
436
437     const Type *Ty = getType(SlotNo);
438     if (!Ty || !isa<PointerType>(Ty))
439       throw std::string("Global not pointer type!  Ty = " + 
440                         Ty->getDescription());
441
442     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
443
444     // Create the global variable...
445     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
446                                             0, "", TheModule);
447     int DestSlot = insertValue(GV, ModuleValues);
448     if (DestSlot == -1) throw Error_DestSlot;
449     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
450     ResolveReferencesToValue(GV, (unsigned)DestSlot);
451
452     if (VarType & 2) { // Does it have an initializer?
453       unsigned InitSlot;
454       if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
455       GlobalInits.push_back(std::make_pair(GV, InitSlot));
456     }
457     if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
458   }
459
460   // Read the function objects for all of the functions that are coming
461   unsigned FnSignature;
462   if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
463   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
464     const Type *Ty = getType(FnSignature);
465     if (!Ty || !isa<PointerType>(Ty) ||
466         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) { 
467       throw std::string("Function not ptr to func type!  Ty = " +
468                         Ty->getDescription());
469     }
470
471     // We create functions by passing the underlying FunctionType to create...
472     Ty = cast<PointerType>(Ty)->getElementType();
473
474     // When the ModuleGlobalInfo section is read, we load the type of each
475     // function and the 'ModuleValues' slot that it lands in.  We then load a
476     // placeholder into its slot to reserve it.  When the function is loaded,
477     // this placeholder is replaced.
478
479     // Insert the placeholder...
480     Function *Func = new Function(cast<FunctionType>(Ty),
481                                   GlobalValue::InternalLinkage, "", TheModule);
482     int DestSlot = insertValue(Func, ModuleValues);
483     if (DestSlot == -1) throw Error_DestSlot;
484     ResolveReferencesToValue(Func, (unsigned)DestSlot);
485
486     // Keep track of this information in a list that is emptied as functions are
487     // loaded...
488     //
489     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
490
491     if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
492     BCR_TRACE(2, "Function of type: " << Ty << "\n");
493   }
494
495   ALIGN32(Buf, End);
496
497   // Now that the function signature list is set up, reverse it so that we can 
498   // remove elements efficiently from the back of the vector.
499   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
500
501   // This is for future proofing... in the future extra fields may be added that
502   // we don't understand, so we transparently ignore them.
503   //
504   Buf = End;
505 }
506
507 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
508                                       const unsigned char *EndBuf) {
509   unsigned Version;
510   if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
511
512   // Unpack version number: low four bits are for flags, top bits = version
513   Module::Endianness  Endianness;
514   Module::PointerSize PointerSize;
515   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
516   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
517
518   bool hasNoEndianness = Version & 4;
519   bool hasNoPointerSize = Version & 8;
520   
521   RevisionNum = Version >> 4;
522
523   // Default values for the current bytecode version
524   HasImplicitZeroInitializer = true;
525   hasInternalMarkerOnly = false;
526   FirstDerivedTyID = 14;
527
528   switch (RevisionNum) {
529   case 0:                  // Initial revision
530     // Version #0 didn't have any of the flags stored correctly, and in fact as
531     // only valid with a 14 in the flags values.  Also, it does not support
532     // encoding zero initializers for arrays compactly.
533     //
534     if (Version != 14) throw std::string("Unknown revision 0 flags?");
535     HasImplicitZeroInitializer = false;
536     Endianness  = Module::BigEndian;
537     PointerSize = Module::Pointer64;
538     hasInternalMarkerOnly = true;
539     hasNoEndianness = hasNoPointerSize = false;
540     break;
541   case 1:
542     // Version #1 has four bit fields: isBigEndian, hasLongPointers,
543     // hasNoEndianness, and hasNoPointerSize.
544     hasInternalMarkerOnly = true;
545     break;
546   case 2:
547     // Version #2 added information about all 4 linkage types instead of just
548     // having internal and external.
549     break;
550   default:
551     throw std::string("Unknown bytecode version number!");
552   }
553
554   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
555   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
556
557   TheModule->setEndianness(Endianness);
558   TheModule->setPointerSize(PointerSize);
559   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
560   BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
561                << PointerSize << "\n");
562   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
563 }
564
565 void BytecodeParser::ParseModule(const unsigned char *Buf,
566                                  const unsigned char *EndBuf) {
567   unsigned Type, Size;
568   readBlock(Buf, EndBuf, Type, Size);
569   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
570     throw std::string("Expected Module packet! B: "+
571         utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
572         " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
573
574   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
575   FunctionSignatureList.clear();                 // Just in case...
576
577   // Read into instance variables...
578   ParseVersionInfo(Buf, EndBuf);
579   ALIGN32(Buf, EndBuf);
580
581   while (Buf < EndBuf) {
582     const unsigned char *OldBuf = Buf;
583     readBlock(Buf, EndBuf, Type, Size);
584     switch (Type) {
585     case BytecodeFormat::GlobalTypePlane:
586       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
587       ParseGlobalTypes(Buf, Buf+Size);
588       break;
589
590     case BytecodeFormat::ModuleGlobalInfo:
591       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
592       ParseModuleGlobalInfo(Buf, Buf+Size);
593       break;
594
595     case BytecodeFormat::ConstantPool:
596       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
597       ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
598       break;
599
600     case BytecodeFormat::Function: {
601       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
602       ParseFunction(Buf, Buf+Size);
603       break;
604     }
605
606     case BytecodeFormat::SymbolTable:
607       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
608       ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
609       break;
610
611     default:
612       Buf += Size;
613       if (OldBuf > Buf) throw std::string("Expected Module Block!");
614       break;
615     }
616     BCR_TRACE(1, "} end block\n");
617     ALIGN32(Buf, EndBuf);
618   }
619
620   // After the module constant pool has been read, we can safely initialize
621   // global variables...
622   while (!GlobalInits.empty()) {
623     GlobalVariable *GV = GlobalInits.back().first;
624     unsigned Slot = GlobalInits.back().second;
625     GlobalInits.pop_back();
626
627     // Look up the initializer value...
628     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
629       if (GV->hasInitializer()) 
630         throw std::string("Global *already* has an initializer?!");
631       GV->setInitializer(cast<Constant>(V));
632     } else
633       throw std::string("Cannot find initializer value.");
634   }
635
636   if (!FunctionSignatureList.empty())
637     throw std::string("Function expected, but bytecode stream ended!");
638
639   BCR_TRACE(0, "} end block\n\n");
640 }
641
642 void
643 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
644                               const std::string &ModuleID) {
645
646   unsigned char *EndBuf = (unsigned char*)(Buf + Length);
647
648   // Read and check signature...
649   unsigned Sig;
650   if (read(Buf, EndBuf, Sig) ||
651       Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
652     throw std::string("Invalid bytecode signature!");
653
654   TheModule = new Module(ModuleID);
655   try { 
656     ParseModule(Buf, EndBuf);
657   } catch (std::string &Error) {
658     freeState();       // Must destroy handles before deleting module!
659     delete TheModule;
660     TheModule = 0;
661     throw;
662   }
663 }