Inline the postResolveValues method. It was poorly named anyway
[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 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
106                                 Value *Val) {
107   assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
108   assert((!HasImplicitZeroInitializer || Slot != 0) &&
109          "Cannot change zero init");
110   unsigned type = getTypeSlot(Val->getType());
111   assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
112   ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
113 }
114
115
116 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
117   return getValue(getTypeSlot(Ty), oNum, Create);
118 }
119
120 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
121   assert(type != Type::TypeTyID && "getValue() cannot get types!");
122   unsigned Num = oNum;
123
124   if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
125     if (Num == 0)
126       return Constant::getNullValue(getType(type));
127     --Num;
128   }
129
130   if (type < ModuleValues.size()) {
131     if (Num < ModuleValues[type]->size())
132       return ModuleValues[type]->getOperand(Num);
133     Num -= ModuleValues[type]->size();
134   }
135
136   if (Values.size() > type && Values[type]->size() > Num)
137     return Values[type]->getOperand(Num);
138
139   if (!Create) return 0;  // Do not create a placeholder?
140
141   const Type *Ty = getType(type);
142   Value *Val = type == Type::LabelTyID ? (Value*)new BBPHolder(Ty, oNum) : 
143                                          (Value*)new ValPHolder(Ty, oNum);
144
145   assert(Val != 0 && "How did we not make something?");
146   if (insertValue(Val, LateResolveValues) == -1) return 0;
147   return Val;
148 }
149
150 /// getConstantValue - Just like getValue, except that it returns a null pointer
151 /// only on error.  It always returns a constant (meaning that if the value is
152 /// defined, but is not a constant, that is an error).  If the specified
153 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
154 /// after the real value is parsed, the placeholder is eliminated.
155 ///
156 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
157   if (Value *V = getValue(Ty, Slot, false))
158     return dyn_cast<Constant>(V);      // If we already have the value parsed...
159
160   std::pair<const Type*, unsigned> Key(Ty, Slot);
161   GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
162
163   if (I != GlobalRefs.end() && I->first == Key) {
164     BCR_TRACE(5, "Previous forward ref found!\n");
165     return cast<Constant>(I->second);
166   } else {
167     // Create a placeholder for the constant reference and
168     // keep track of the fact that we have a forward ref to recycle it
169     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
170     Constant *C = new ConstPHolder(Ty, Slot);
171     
172     // Keep track of the fact that we have a forward ref to recycle it
173     GlobalRefs.insert(I, std::make_pair(Key, C));
174     return C;
175   }
176 }
177
178
179 std::auto_ptr<BasicBlock>
180 BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
181                                 const unsigned char *EndBuf) {
182   std::auto_ptr<BasicBlock> BB(new BasicBlock());
183
184   while (Buf < EndBuf) {
185     Instruction *Inst;
186     ParseInstruction(Buf, EndBuf, Inst);
187
188     if (Inst == 0) { throw std::string("Could not parse Instruction."); }
189     if (insertValue(Inst, Values) == -1) { 
190       throw std::string("Could not insert value.");
191     }
192
193     BB->getInstList().push_back(Inst);
194     BCR_TRACE(4, Inst);
195   }
196
197   return BB;
198 }
199
200 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
201                                       const unsigned char *EndBuf,
202                                       SymbolTable *ST) {
203   while (Buf < EndBuf) {
204     // Symtab block header: [num entries][type id number]
205     unsigned NumEntries, Typ;
206     if (read_vbr(Buf, EndBuf, NumEntries) ||
207         read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
208     const Type *Ty = getType(Typ);
209     if (Ty == 0) throw std::string("Invalid type read in symbol table.");
210
211     BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
212                  " entries\n");
213
214     for (unsigned i = 0; i < NumEntries; ++i) {
215       // Symtab entry: [def slot #][name]
216       unsigned slot;
217       if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
218       std::string Name;
219       if (read(Buf, EndBuf, Name, false))  // Not aligned...
220         throw std::string("Buffer not aligned.");
221
222       Value *V;
223       if (Typ == Type::TypeTyID)
224         V = (Value*)getType(slot);
225       else
226         V = getValue(Typ, slot, false); // Find mapping...
227       if (V == 0) throw std::string("Failed value look-up.");
228       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
229                 if (!isa<Instruction>(V)) std::cerr << "\n");
230
231       V->setName(Name, ST);
232     }
233   }
234
235   if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
236 }
237
238 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
239   GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
240                                                               Slot));
241   if (I == GlobalRefs.end()) return;   // Never forward referenced?
242
243   BCR_TRACE(3, "Mutating forward refs!\n");
244   Value *VPH = I->second;   // Get the placeholder...
245
246   VPH->replaceAllUsesWith(NewV);
247
248   // If this is a global variable being resolved, remove the placeholder from
249   // the module...
250   if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
251     GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
252
253   delete VPH;                         // Delete the old placeholder
254   GlobalRefs.erase(I);                // Remove the map entry for it
255 }
256
257 void
258 BytecodeParser::ParseFunction(const unsigned char *&Buf,
259                               const unsigned char *EndBuf) {
260   if (FunctionSignatureList.empty())
261     throw std::string("FunctionSignatureList empty!");
262
263   Function *F = FunctionSignatureList.back().first;
264   unsigned FunctionSlot = FunctionSignatureList.back().second;
265   FunctionSignatureList.pop_back();
266
267   // Save the information for future reading of the function
268   LazyFunctionInfo *LFI = new LazyFunctionInfo();
269   LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
270   LazyFunctionLoadMap[F] = LFI;
271   // Pretend we've `parsed' this function
272   Buf = EndBuf;
273 }
274
275 void BytecodeParser::materializeFunction(Function* F) {
276   // Find {start, end} pointers and slot in the map. If not there, we're done.
277   std::map<Function*, LazyFunctionInfo*>::iterator Fi =
278     LazyFunctionLoadMap.find(F);
279   if (Fi == LazyFunctionLoadMap.end()) return;
280   
281   LazyFunctionInfo *LFI = Fi->second;
282   const unsigned char *Buf = LFI->Buf;
283   const unsigned char *EndBuf = LFI->EndBuf;
284   unsigned FunctionSlot = LFI->FunctionSlot;
285   LazyFunctionLoadMap.erase(Fi);
286   delete LFI;
287
288   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
289
290   if (!hasInternalMarkerOnly) {
291     unsigned LinkageType;
292     if (read_vbr(Buf, EndBuf, LinkageType)) 
293       throw std::string("ParseFunction: Error reading from buffer.");
294     if (LinkageType & ~0x3) 
295       throw std::string("Invalid linkage type for Function.");
296     Linkage = (GlobalValue::LinkageTypes)LinkageType;
297   } else {
298     // We used to only support two linkage models: internal and external
299     unsigned isInternal;
300     if (read_vbr(Buf, EndBuf, isInternal)) 
301       throw std::string("ParseFunction: Error reading from buffer.");
302     if (isInternal) Linkage = GlobalValue::InternalLinkage;
303   }
304
305   F->setLinkage(Linkage);
306
307   const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
308   Function::aiterator AI = F->abegin();
309   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
310        It != Params.end(); ++It, ++AI) {
311     if (insertValue(AI, Values) == -1)
312       throw std::string("Error reading function arguments!");
313   }
314
315   while (Buf < EndBuf) {
316     unsigned Type, Size;
317     const unsigned char *OldBuf = Buf;
318     readBlock(Buf, EndBuf, Type, Size);
319
320     switch (Type) {
321     case BytecodeFormat::ConstantPool: {
322       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
323       ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
324       break;
325     }
326
327     case BytecodeFormat::BasicBlock: {
328       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
329       std::auto_ptr<BasicBlock> BB = ParseBasicBlock(Buf, Buf+Size);
330       if (!BB.get() || insertValue(BB.get(), Values) == -1)
331         throw std::string("Parse error: BasicBlock");
332
333       F->getBasicBlockList().push_back(BB.release());
334       break;
335     }
336
337     case BytecodeFormat::SymbolTable: {
338       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
339       ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable());
340       break;
341     }
342
343     default:
344       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
345       Buf += Size;
346       if (OldBuf > Buf) 
347         throw std::string("Wrapped around reading bytecode.");
348       break;
349     }
350     BCR_TRACE(2, "} end block\n");
351
352     // Malformed bc file if read past end of block.
353     ALIGN32(Buf, EndBuf);
354   }
355
356   // Check for unresolvable references
357   while (!LateResolveValues.empty()) {
358     ValueList &VL = *LateResolveValues.back();
359     LateResolveValues.pop_back();    
360
361     while (!VL.empty()) {
362       Value *V = VL.back();
363       unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
364       VL.pop_back();
365
366       Value *NewVal = getValue(V->getType(), IDNumber, false);
367       if (NewVal == 0)
368         throw std::string("Unresolvable reference found: <" +
369                           V->getType()->getDescription() + ">:" + 
370                           utostr(IDNumber) + ".");
371
372       // Fixup all of the uses of this placeholder def...
373       V->replaceAllUsesWith(NewVal);
374       
375       // Now that all the uses are gone, delete the placeholder...
376       // If we couldn't find a def (error case), then leak a little
377       // memory, because otherwise we can't remove all uses!
378       delete V;
379     }
380     delete &VL;
381   }
382
383   // Clear out function-level types...
384   FunctionTypeValues.clear();
385
386   freeTable(Values);
387 }
388
389 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
390                                            const unsigned char *End) {
391   if (!FunctionSignatureList.empty())
392     throw std::string("Two ModuleGlobalInfo packets found!");
393
394   // Read global variables...
395   unsigned VarType;
396   if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
397   while (VarType != Type::VoidTyID) { // List is terminated by Void
398     unsigned SlotNo;
399     GlobalValue::LinkageTypes Linkage;
400
401     if (!hasInternalMarkerOnly) {
402       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
403       // bit2,3 = Linkage, bit4+ = slot#
404       SlotNo = VarType >> 4;
405       Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
406     } else {
407       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
408       // bit2 = isInternal, bit3+ = slot#
409       SlotNo = VarType >> 3;
410       Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
411         GlobalValue::ExternalLinkage;
412     }
413
414     const Type *Ty = getType(SlotNo);
415     if (!Ty || !isa<PointerType>(Ty))
416       throw std::string("Global not pointer type!  Ty = " + 
417                         Ty->getDescription());
418
419     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
420
421     // Create the global variable...
422     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
423                                             0, "", TheModule);
424     int DestSlot = insertValue(GV, ModuleValues);
425     if (DestSlot == -1) throw Error_DestSlot;
426     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
427     ResolveReferencesToValue(GV, (unsigned)DestSlot);
428
429     if (VarType & 2) { // Does it have an initializer?
430       unsigned InitSlot;
431       if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
432       GlobalInits.push_back(std::make_pair(GV, InitSlot));
433     }
434     if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
435   }
436
437   // Read the function objects for all of the functions that are coming
438   unsigned FnSignature;
439   if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
440   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
441     const Type *Ty = getType(FnSignature);
442     if (!Ty || !isa<PointerType>(Ty) ||
443         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) { 
444       throw std::string("Function not ptr to func type!  Ty = " +
445                         Ty->getDescription());
446     }
447
448     // We create functions by passing the underlying FunctionType to create...
449     Ty = cast<PointerType>(Ty)->getElementType();
450
451     // When the ModuleGlobalInfo section is read, we load the type of each
452     // function and the 'ModuleValues' slot that it lands in.  We then load a
453     // placeholder into its slot to reserve it.  When the function is loaded,
454     // this placeholder is replaced.
455
456     // Insert the placeholder...
457     Function *Func = new Function(cast<FunctionType>(Ty),
458                                   GlobalValue::InternalLinkage, "", TheModule);
459     int DestSlot = insertValue(Func, ModuleValues);
460     if (DestSlot == -1) throw Error_DestSlot;
461     ResolveReferencesToValue(Func, (unsigned)DestSlot);
462
463     // Keep track of this information in a list that is emptied as functions are
464     // loaded...
465     //
466     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
467
468     if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
469     BCR_TRACE(2, "Function of type: " << Ty << "\n");
470   }
471
472   ALIGN32(Buf, End);
473
474   // Now that the function signature list is set up, reverse it so that we can 
475   // remove elements efficiently from the back of the vector.
476   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
477
478   // This is for future proofing... in the future extra fields may be added that
479   // we don't understand, so we transparently ignore them.
480   //
481   Buf = End;
482 }
483
484 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
485                                       const unsigned char *EndBuf) {
486   unsigned Version;
487   if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
488
489   // Unpack version number: low four bits are for flags, top bits = version
490   Module::Endianness  Endianness;
491   Module::PointerSize PointerSize;
492   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
493   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
494
495   bool hasNoEndianness = Version & 4;
496   bool hasNoPointerSize = Version & 8;
497   
498   RevisionNum = Version >> 4;
499
500   // Default values for the current bytecode version
501   HasImplicitZeroInitializer = true;
502   hasInternalMarkerOnly = false;
503   FirstDerivedTyID = 14;
504
505   switch (RevisionNum) {
506   case 0:                  // Initial revision
507     // Version #0 didn't have any of the flags stored correctly, and in fact as
508     // only valid with a 14 in the flags values.  Also, it does not support
509     // encoding zero initializers for arrays compactly.
510     //
511     if (Version != 14) throw std::string("Unknown revision 0 flags?");
512     HasImplicitZeroInitializer = false;
513     Endianness  = Module::BigEndian;
514     PointerSize = Module::Pointer64;
515     hasInternalMarkerOnly = true;
516     hasNoEndianness = hasNoPointerSize = false;
517     break;
518   case 1:
519     // Version #1 has four bit fields: isBigEndian, hasLongPointers,
520     // hasNoEndianness, and hasNoPointerSize.
521     hasInternalMarkerOnly = true;
522     break;
523   case 2:
524     // Version #2 added information about all 4 linkage types instead of just
525     // having internal and external.
526     break;
527   default:
528     throw std::string("Unknown bytecode version number!");
529   }
530
531   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
532   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
533
534   TheModule->setEndianness(Endianness);
535   TheModule->setPointerSize(PointerSize);
536   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
537   BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
538                << PointerSize << "\n");
539   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
540 }
541
542 void BytecodeParser::ParseModule(const unsigned char *Buf,
543                                  const unsigned char *EndBuf) {
544   unsigned Type, Size;
545   readBlock(Buf, EndBuf, Type, Size);
546   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
547     throw std::string("Expected Module packet! B: "+
548         utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
549         " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
550
551   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
552   FunctionSignatureList.clear();                 // Just in case...
553
554   // Read into instance variables...
555   ParseVersionInfo(Buf, EndBuf);
556   ALIGN32(Buf, EndBuf);
557
558   while (Buf < EndBuf) {
559     const unsigned char *OldBuf = Buf;
560     readBlock(Buf, EndBuf, Type, Size);
561     switch (Type) {
562     case BytecodeFormat::GlobalTypePlane:
563       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
564       ParseGlobalTypes(Buf, Buf+Size);
565       break;
566
567     case BytecodeFormat::ModuleGlobalInfo:
568       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
569       ParseModuleGlobalInfo(Buf, Buf+Size);
570       break;
571
572     case BytecodeFormat::ConstantPool:
573       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
574       ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
575       break;
576
577     case BytecodeFormat::Function: {
578       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
579       ParseFunction(Buf, Buf+Size);
580       break;
581     }
582
583     case BytecodeFormat::SymbolTable:
584       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
585       ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable());
586       break;
587
588     default:
589       Buf += Size;
590       if (OldBuf > Buf) throw std::string("Expected Module Block!");
591       break;
592     }
593     BCR_TRACE(1, "} end block\n");
594     ALIGN32(Buf, EndBuf);
595   }
596
597   // After the module constant pool has been read, we can safely initialize
598   // global variables...
599   while (!GlobalInits.empty()) {
600     GlobalVariable *GV = GlobalInits.back().first;
601     unsigned Slot = GlobalInits.back().second;
602     GlobalInits.pop_back();
603
604     // Look up the initializer value...
605     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
606       if (GV->hasInitializer()) 
607         throw std::string("Global *already* has an initializer?!");
608       GV->setInitializer(cast<Constant>(V));
609     } else
610       throw std::string("Cannot find initializer value.");
611   }
612
613   if (!FunctionSignatureList.empty())
614     throw std::string("Function expected, but bytecode stream ended!");
615
616   BCR_TRACE(0, "} end block\n\n");
617 }
618
619 void
620 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
621                               const std::string &ModuleID) {
622
623   unsigned char *EndBuf = (unsigned char*)(Buf + Length);
624
625   // Read and check signature...
626   unsigned Sig;
627   if (read(Buf, EndBuf, Sig) ||
628       Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
629     throw std::string("Invalid bytecode signature!");
630
631   TheModule = new Module(ModuleID);
632   try { 
633     ParseModule(Buf, EndBuf);
634   } catch (std::string &Error) {
635     freeState();       // Must destroy handles before deleting module!
636     delete TheModule;
637     TheModule = 0;
638     throw;
639   }
640 }