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