Use the version of getValue that takes the type plane instead of the type
[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     if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
54       return T;
55   
56   //cerr << "Looking up Type ID: " << ID << "\n";
57
58   if (ID < Type::NumPrimitiveIDs)
59     if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
60       return T;   // Asked for a primitive type...
61
62   // Otherwise, derived types need offset...
63   ID -= FirstDerivedTyID;
64
65   // Is it a module-level type?
66   if (ID < ModuleTypeValues.size())
67     return ModuleTypeValues[ID].get();
68
69   // Nope, is it a function-level type?
70   ID -= ModuleTypeValues.size();
71   if (ID < FunctionTypeValues.size())
72     return FunctionTypeValues[ID].get();
73
74   throw std::string("Illegal type reference!");
75 }
76
77 unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
78   assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
79           Val->getType()->isPrimitiveType() ||
80           !cast<Constant>(Val)->isNullValue()) &&
81          "Cannot read null values from bytecode!");
82   unsigned type = getTypeSlot(Val->getType());
83   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
84  
85   if (ValueTab.size() <= type) {
86     unsigned OldSize = ValueTab.size();
87     ValueTab.resize(type+1);
88     while (OldSize != type+1)
89       ValueTab[OldSize++] = new ValueList();
90   }
91
92   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
93   //   << "] = " << Val << "\n";
94   ValueTab[type]->push_back(Val);
95
96   bool HasOffset = HasImplicitZeroInitializer &&
97     !Val->getType()->isPrimitiveType();
98
99   return ValueTab[type]->size()-1 + HasOffset;
100 }
101
102
103 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
104   return getValue(getTypeSlot(Ty), oNum, Create);
105 }
106
107 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
108   assert(type != Type::TypeTyID && "getValue() cannot get types!");
109   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
110   unsigned Num = oNum;
111
112   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
113     if (Num == 0)
114       return Constant::getNullValue(getType(type));
115     --Num;
116   }
117
118   if (type < ModuleValues.size()) {
119     if (Num < ModuleValues[type]->size())
120       return ModuleValues[type]->getOperand(Num);
121     Num -= ModuleValues[type]->size();
122   }
123
124   if (Values.size() > type && Values[type]->size() > Num)
125     return Values[type]->getOperand(Num);
126
127   if (!Create) return 0;  // Do not create a placeholder?
128
129   std::pair<unsigned,unsigned> KeyValue(type, oNum);
130   std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = 
131     ForwardReferences.lower_bound(KeyValue);
132   if (I != ForwardReferences.end() && I->first == KeyValue)
133     return I->second;   // We have already created this placeholder
134
135   Value *Val = new Argument(getType(type));
136   ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
137   return Val;
138 }
139
140 /// getBasicBlock - Get a particular numbered basic block, which might be a
141 /// forward reference.  This works together with ParseBasicBlock to handle these
142 /// forward references in a clean manner.
143 ///
144 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
145   // Make sure there is room in the table...
146   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
147
148   // First check to see if this is a backwards reference, i.e., ParseBasicBlock
149   // has already created this block, or if the forward reference has already
150   // been created.
151   if (ParsedBasicBlocks[ID])
152     return ParsedBasicBlocks[ID];
153
154   // Otherwise, the basic block has not yet been created.  Do so and add it to
155   // the ParsedBasicBlocks list.
156   return ParsedBasicBlocks[ID] = new BasicBlock();
157 }
158
159 /// getConstantValue - Just like getValue, except that it returns a null pointer
160 /// only on error.  It always returns a constant (meaning that if the value is
161 /// defined, but is not a constant, that is an error).  If the specified
162 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
163 /// after the real value is parsed, the placeholder is eliminated.
164 ///
165 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
166   if (Value *V = getValue(Ty, Slot, false))
167     if (Constant *C = dyn_cast<Constant>(V))
168       return C;   // If we already have the value parsed, just return it
169     else
170       throw std::string("Reference of a value is expected to be a constant!");
171
172   std::pair<const Type*, unsigned> Key(Ty, Slot);
173   GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
174
175   if (I != GlobalRefs.end() && I->first == Key) {
176     BCR_TRACE(5, "Previous forward ref found!\n");
177     return cast<Constant>(I->second);
178   } else {
179     // Create a placeholder for the constant reference and
180     // keep track of the fact that we have a forward ref to recycle it
181     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
182     Constant *C = new ConstPHolder(Ty, Slot);
183     
184     // Keep track of the fact that we have a forward ref to recycle it
185     GlobalRefs.insert(I, std::make_pair(Key, C));
186     return C;
187   }
188 }
189
190
191 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
192                                             const unsigned char *EndBuf,
193                                             unsigned BlockNo) {
194   BasicBlock *BB;
195   if (ParsedBasicBlocks.size() == BlockNo)
196     ParsedBasicBlocks.push_back(BB = new BasicBlock());
197   else if (ParsedBasicBlocks[BlockNo] == 0)
198     BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
199   else
200     BB = ParsedBasicBlocks[BlockNo];
201
202   while (Buf < EndBuf) {
203     std::vector<unsigned> Args;
204     Instruction *Inst = ParseInstruction(Buf, EndBuf, Args);
205     insertValue(Inst, Values);
206     BB->getInstList().push_back(Inst);
207     BCR_TRACE(4, Inst);
208   }
209
210   return BB;
211 }
212
213 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
214                                       const unsigned char *EndBuf,
215                                       SymbolTable *ST,
216                                       Function *CurrentFunction) {
217   while (Buf < EndBuf) {
218     // Symtab block header: [num entries][type id number]
219     unsigned NumEntries, Typ;
220     if (read_vbr(Buf, EndBuf, NumEntries) ||
221         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
222     const Type *Ty = getType(Typ);
223     BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
224                  " entries\n");
225
226     Function::iterator BlockIterator;
227     unsigned CurBlockIteratorIdx = ~0;
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           throw std::string("Basic blocks don't exist at global scope!");
243
244         if (slot < CurBlockIteratorIdx) {
245           CurBlockIteratorIdx = 0;
246           BlockIterator = CurrentFunction->begin();
247         }
248
249         std::advance(BlockIterator, slot-CurBlockIteratorIdx);
250         CurBlockIteratorIdx = slot;
251         V = BlockIterator;
252       } else
253         V = getValue(Typ, slot, false); // Find mapping...
254       if (V == 0) throw std::string("Failed value look-up.");
255       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
256                 if (!isa<Instruction>(V)) std::cerr << "\n");
257
258       V->setName(Name, ST);
259     }
260   }
261
262   if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
263 }
264
265 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
266   GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
267                                                               Slot));
268   if (I == GlobalRefs.end()) return;   // Never forward referenced?
269
270   BCR_TRACE(3, "Mutating forward refs!\n");
271   Value *VPH = I->second;   // Get the placeholder...
272
273   VPH->replaceAllUsesWith(NewV);
274
275   // If this is a global variable being resolved, remove the placeholder from
276   // the module...
277   if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
278     GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
279
280   delete VPH;                         // Delete the old placeholder
281   GlobalRefs.erase(I);                // Remove the map entry for it
282 }
283
284 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
285                                    const unsigned char *EndBuf) {
286   if (FunctionSignatureList.empty())
287     throw std::string("FunctionSignatureList empty!");
288
289   Function *F = FunctionSignatureList.back().first;
290   unsigned FunctionSlot = FunctionSignatureList.back().second;
291   FunctionSignatureList.pop_back();
292
293   // Save the information for future reading of the function
294   LazyFunctionInfo *LFI = new LazyFunctionInfo();
295   LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
296   LazyFunctionLoadMap[F] = LFI;
297   // Pretend we've `parsed' this function
298   Buf = EndBuf;
299 }
300
301 void BytecodeParser::materializeFunction(Function* F) {
302   // Find {start, end} pointers and slot in the map. If not there, we're done.
303   std::map<Function*, LazyFunctionInfo*>::iterator Fi =
304     LazyFunctionLoadMap.find(F);
305   if (Fi == LazyFunctionLoadMap.end()) return;
306   
307   LazyFunctionInfo *LFI = Fi->second;
308   const unsigned char *Buf = LFI->Buf;
309   const unsigned char *EndBuf = LFI->EndBuf;
310   unsigned FunctionSlot = LFI->FunctionSlot;
311   LazyFunctionLoadMap.erase(Fi);
312   delete LFI;
313
314   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
315
316   if (!hasInternalMarkerOnly) {
317     unsigned LinkageType;
318     if (read_vbr(Buf, EndBuf, LinkageType)) 
319       throw std::string("ParseFunction: Error reading from buffer.");
320     if (LinkageType & ~0x3) 
321       throw std::string("Invalid linkage type for Function.");
322     Linkage = (GlobalValue::LinkageTypes)LinkageType;
323   } else {
324     // We used to only support two linkage models: internal and external
325     unsigned isInternal;
326     if (read_vbr(Buf, EndBuf, isInternal)) 
327       throw std::string("ParseFunction: Error reading from buffer.");
328     if (isInternal) Linkage = GlobalValue::InternalLinkage;
329   }
330
331   F->setLinkage(Linkage);
332
333   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
334   Function::aiterator AI = F->abegin();
335   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
336        It != Params.end(); ++It, ++AI)
337     insertValue(AI, Values);
338
339   // Keep track of how many basic blocks we have read in...
340   unsigned BlockNum = 0;
341
342   while (Buf < EndBuf) {
343     unsigned Type, Size;
344     const unsigned char *OldBuf = Buf;
345     readBlock(Buf, EndBuf, Type, Size);
346
347     switch (Type) {
348     case BytecodeFormat::ConstantPool: {
349       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
350       ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
351       break;
352     }
353
354     case BytecodeFormat::BasicBlock: {
355       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
356       BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
357       F->getBasicBlockList().push_back(BB);
358       break;
359     }
360
361     case BytecodeFormat::SymbolTable: {
362       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
363       ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
364       break;
365     }
366
367     default:
368       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
369       Buf += Size;
370       if (OldBuf > Buf) 
371         throw std::string("Wrapped around reading bytecode.");
372       break;
373     }
374     BCR_TRACE(2, "} end block\n");
375
376     // Malformed bc file if read past end of block.
377     ALIGN32(Buf, EndBuf);
378   }
379
380   // Make sure there were no references to non-existant basic blocks.
381   if (BlockNum != ParsedBasicBlocks.size())
382     throw std::string("Illegal basic block operand reference");
383   ParsedBasicBlocks.clear();
384
385
386   // Resolve forward references
387   while (!ForwardReferences.empty()) {
388     std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
389       ForwardReferences.begin();
390     unsigned type = I->first.first;
391     unsigned Slot = I->first.second;
392     Value *PlaceHolder = I->second;
393     ForwardReferences.erase(I);
394
395     Value *NewVal = getValue(type, Slot, false);
396     if (NewVal == 0)
397       throw std::string("Unresolvable reference found: <" +
398                         PlaceHolder->getType()->getDescription() + ">:" + 
399                         utostr(Slot) + ".");
400
401     // Fixup all of the uses of this placeholder def...
402     PlaceHolder->replaceAllUsesWith(NewVal);
403       
404     // Now that all the uses are gone, delete the placeholder...
405     // If we couldn't find a def (error case), then leak a little
406     // memory, because otherwise we can't remove all uses!
407     delete PlaceHolder;
408   }
409
410   // Clear out function-level types...
411   FunctionTypeValues.clear();
412
413   freeTable(Values);
414 }
415
416 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
417                                            const unsigned char *End) {
418   if (!FunctionSignatureList.empty())
419     throw std::string("Two ModuleGlobalInfo packets found!");
420
421   // Read global variables...
422   unsigned VarType;
423   if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
424   while (VarType != Type::VoidTyID) { // List is terminated by Void
425     unsigned SlotNo;
426     GlobalValue::LinkageTypes Linkage;
427
428     if (!hasInternalMarkerOnly) {
429       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
430       // bit2,3 = Linkage, bit4+ = slot#
431       SlotNo = VarType >> 4;
432       Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
433     } else {
434       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
435       // bit2 = isInternal, bit3+ = slot#
436       SlotNo = VarType >> 3;
437       Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
438         GlobalValue::ExternalLinkage;
439     }
440
441     const Type *Ty = getType(SlotNo);
442     if (!isa<PointerType>(Ty))
443       throw std::string("Global not pointer type!  Ty = " + 
444                         Ty->getDescription());
445
446     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
447
448     // Create the global variable...
449     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
450                                             0, "", TheModule);
451     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
452     ResolveReferencesToValue(GV, insertValue(GV, ModuleValues));
453
454     if (VarType & 2) { // Does it have an initializer?
455       unsigned InitSlot;
456       if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
457       GlobalInits.push_back(std::make_pair(GV, InitSlot));
458     }
459     if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
460   }
461
462   // Read the function objects for all of the functions that are coming
463   unsigned FnSignature;
464   if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
465   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
466     const Type *Ty = getType(FnSignature);
467     if (!isa<PointerType>(Ty) ||
468         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
469       throw std::string("Function not ptr to func type!  Ty = " +
470                         Ty->getDescription());
471
472     // We create functions by passing the underlying FunctionType to create...
473     Ty = cast<PointerType>(Ty)->getElementType();
474
475     // When the ModuleGlobalInfo section is read, we load the type of each
476     // function and the 'ModuleValues' slot that it lands in.  We then load a
477     // placeholder into its slot to reserve it.  When the function is loaded,
478     // this placeholder is replaced.
479
480     // Insert the placeholder...
481     Function *Func = new Function(cast<FunctionType>(Ty),
482                                   GlobalValue::InternalLinkage, "", TheModule);
483     unsigned DestSlot = insertValue(Func, ModuleValues);
484     ResolveReferencesToValue(Func, 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 }