Pass a vector around to reduce dynamic allocation
[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 = ForwardReferences.begin();
389     unsigned type = I->first.first;
390     unsigned Slot = I->first.second;
391     Value *PlaceHolder = I->second;
392     ForwardReferences.erase(I);
393
394     Value *NewVal = getValue(type, Slot, false);
395     if (NewVal == 0)
396       throw std::string("Unresolvable reference found: <" +
397                         PlaceHolder->getType()->getDescription() + ">:" + 
398                         utostr(Slot) + ".");
399
400     // Fixup all of the uses of this placeholder def...
401     PlaceHolder->replaceAllUsesWith(NewVal);
402       
403     // Now that all the uses are gone, delete the placeholder...
404     // If we couldn't find a def (error case), then leak a little
405     // memory, because otherwise we can't remove all uses!
406     delete PlaceHolder;
407   }
408
409   // Clear out function-level types...
410   FunctionTypeValues.clear();
411
412   freeTable(Values);
413 }
414
415 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
416                                            const unsigned char *End) {
417   if (!FunctionSignatureList.empty())
418     throw std::string("Two ModuleGlobalInfo packets found!");
419
420   // Read global variables...
421   unsigned VarType;
422   if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
423   while (VarType != Type::VoidTyID) { // List is terminated by Void
424     unsigned SlotNo;
425     GlobalValue::LinkageTypes Linkage;
426
427     if (!hasInternalMarkerOnly) {
428       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
429       // bit2,3 = Linkage, bit4+ = slot#
430       SlotNo = VarType >> 4;
431       Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
432     } else {
433       // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
434       // bit2 = isInternal, bit3+ = slot#
435       SlotNo = VarType >> 3;
436       Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
437         GlobalValue::ExternalLinkage;
438     }
439
440     const Type *Ty = getType(SlotNo);
441     if (!isa<PointerType>(Ty))
442       throw std::string("Global not pointer type!  Ty = " + 
443                         Ty->getDescription());
444
445     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
446
447     // Create the global variable...
448     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
449                                             0, "", TheModule);
450     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
451     ResolveReferencesToValue(GV, insertValue(GV, ModuleValues));
452
453     if (VarType & 2) { // Does it have an initializer?
454       unsigned InitSlot;
455       if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
456       GlobalInits.push_back(std::make_pair(GV, InitSlot));
457     }
458     if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
459   }
460
461   // Read the function objects for all of the functions that are coming
462   unsigned FnSignature;
463   if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
464   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
465     const Type *Ty = getType(FnSignature);
466     if (!isa<PointerType>(Ty) ||
467         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
468       throw std::string("Function not ptr to func type!  Ty = " +
469                         Ty->getDescription());
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     unsigned DestSlot = insertValue(Func, ModuleValues);
483     ResolveReferencesToValue(Func, DestSlot);
484
485     // Keep track of this information in a list that is emptied as functions are
486     // loaded...
487     //
488     FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
489
490     if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
491     BCR_TRACE(2, "Function of type: " << Ty << "\n");
492   }
493
494   ALIGN32(Buf, End);
495
496   // Now that the function signature list is set up, reverse it so that we can 
497   // remove elements efficiently from the back of the vector.
498   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
499
500   // This is for future proofing... in the future extra fields may be added that
501   // we don't understand, so we transparently ignore them.
502   //
503   Buf = End;
504 }
505
506 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
507                                       const unsigned char *EndBuf) {
508   unsigned Version;
509   if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
510
511   // Unpack version number: low four bits are for flags, top bits = version
512   Module::Endianness  Endianness;
513   Module::PointerSize PointerSize;
514   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
515   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
516
517   bool hasNoEndianness = Version & 4;
518   bool hasNoPointerSize = Version & 8;
519   
520   RevisionNum = Version >> 4;
521
522   // Default values for the current bytecode version
523   HasImplicitZeroInitializer = true;
524   hasInternalMarkerOnly = false;
525   FirstDerivedTyID = 14;
526
527   switch (RevisionNum) {
528   case 0:                  // Initial revision
529     // Version #0 didn't have any of the flags stored correctly, and in fact as
530     // only valid with a 14 in the flags values.  Also, it does not support
531     // encoding zero initializers for arrays compactly.
532     //
533     if (Version != 14) throw std::string("Unknown revision 0 flags?");
534     HasImplicitZeroInitializer = false;
535     Endianness  = Module::BigEndian;
536     PointerSize = Module::Pointer64;
537     hasInternalMarkerOnly = true;
538     hasNoEndianness = hasNoPointerSize = false;
539     break;
540   case 1:
541     // Version #1 has four bit fields: isBigEndian, hasLongPointers,
542     // hasNoEndianness, and hasNoPointerSize.
543     hasInternalMarkerOnly = true;
544     break;
545   case 2:
546     // Version #2 added information about all 4 linkage types instead of just
547     // having internal and external.
548     break;
549   default:
550     throw std::string("Unknown bytecode version number!");
551   }
552
553   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
554   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
555
556   TheModule->setEndianness(Endianness);
557   TheModule->setPointerSize(PointerSize);
558   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
559   BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
560                << PointerSize << "\n");
561   BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
562 }
563
564 void BytecodeParser::ParseModule(const unsigned char *Buf,
565                                  const unsigned char *EndBuf) {
566   unsigned Type, Size;
567   readBlock(Buf, EndBuf, Type, Size);
568   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
569     throw std::string("Expected Module packet! B: "+
570         utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
571         " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
572
573   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
574   FunctionSignatureList.clear();                 // Just in case...
575
576   // Read into instance variables...
577   ParseVersionInfo(Buf, EndBuf);
578   ALIGN32(Buf, EndBuf);
579
580   while (Buf < EndBuf) {
581     const unsigned char *OldBuf = Buf;
582     readBlock(Buf, EndBuf, Type, Size);
583     switch (Type) {
584     case BytecodeFormat::GlobalTypePlane:
585       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
586       ParseGlobalTypes(Buf, Buf+Size);
587       break;
588
589     case BytecodeFormat::ModuleGlobalInfo:
590       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
591       ParseModuleGlobalInfo(Buf, Buf+Size);
592       break;
593
594     case BytecodeFormat::ConstantPool:
595       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
596       ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
597       break;
598
599     case BytecodeFormat::Function: {
600       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
601       ParseFunction(Buf, Buf+Size);
602       break;
603     }
604
605     case BytecodeFormat::SymbolTable:
606       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
607       ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
608       break;
609
610     default:
611       Buf += Size;
612       if (OldBuf > Buf) throw std::string("Expected Module Block!");
613       break;
614     }
615     BCR_TRACE(1, "} end block\n");
616     ALIGN32(Buf, EndBuf);
617   }
618
619   // After the module constant pool has been read, we can safely initialize
620   // global variables...
621   while (!GlobalInits.empty()) {
622     GlobalVariable *GV = GlobalInits.back().first;
623     unsigned Slot = GlobalInits.back().second;
624     GlobalInits.pop_back();
625
626     // Look up the initializer value...
627     if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
628       if (GV->hasInitializer()) 
629         throw std::string("Global *already* has an initializer?!");
630       GV->setInitializer(cast<Constant>(V));
631     } else
632       throw std::string("Cannot find initializer value.");
633   }
634
635   if (!FunctionSignatureList.empty())
636     throw std::string("Function expected, but bytecode stream ended!");
637
638   BCR_TRACE(0, "} end block\n\n");
639 }
640
641 void
642 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
643                               const std::string &ModuleID) {
644
645   unsigned char *EndBuf = (unsigned char*)(Buf + Length);
646
647   // Read and check signature...
648   unsigned Sig;
649   if (read(Buf, EndBuf, Sig) ||
650       Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
651     throw std::string("Invalid bytecode signature!");
652
653   TheModule = new Module(ModuleID);
654   try { 
655     ParseModule(Buf, EndBuf);
656   } catch (std::string &Error) {
657     freeState();       // Must destroy handles before deleting module!
658     delete TheModule;
659     TheModule = 0;
660     throw;
661   }
662 }