1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // This library implements the functionality defined in llvm/Bytecode/Reader.h
5 // Note that this library should be as fast as possible, reentrant, and
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
11 //===----------------------------------------------------------------------===//
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"
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.");
34 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35 if (Ty->isPrimitiveType())
36 return Ty->getPrimitiveID();
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]);
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]);
51 const Type *BytecodeParser::getType(unsigned ID) {
52 if (ID < Type::NumPrimitiveIDs)
53 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
56 //cerr << "Looking up Type ID: " << ID << "\n";
58 if (ID < Type::NumPrimitiveIDs)
59 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
60 return T; // Asked for a primitive type...
62 // Otherwise, derived types need offset...
63 ID -= FirstDerivedTyID;
65 // Is it a module-level type?
66 if (ID < ModuleTypeValues.size())
67 return ModuleTypeValues[ID].get();
69 // Nope, is it a function-level type?
70 ID -= ModuleTypeValues.size();
71 if (ID < FunctionTypeValues.size())
72 return FunctionTypeValues[ID].get();
74 throw std::string("Illegal type reference!");
77 unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
78 return insertValue(Val, getTypeSlot(Val->getType()), ValueTab);
81 unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
82 ValueTable &ValueTab) {
83 assert((!isa<Constant>(Val) || Val->getType()->isPrimitiveType() ||
84 !cast<Constant>(Val)->isNullValue()) &&
85 "Cannot read null values from bytecode!");
86 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
88 if (ValueTab.size() <= type) {
89 unsigned OldSize = ValueTab.size();
90 ValueTab.resize(type+1);
91 while (OldSize != type+1)
92 ValueTab[OldSize++] = new ValueList();
95 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
96 // << "] = " << Val << "\n";
97 ValueTab[type]->push_back(Val);
99 bool HasOffset = !Val->getType()->isPrimitiveType();
100 return ValueTab[type]->size()-1 + HasOffset;
104 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
105 return getValue(getTypeSlot(Ty), oNum, Create);
108 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
109 assert(type != Type::TypeTyID && "getValue() cannot get types!");
110 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
113 if (type >= FirstDerivedTyID) {
115 return Constant::getNullValue(getType(type));
119 if (type < ModuleValues.size()) {
120 if (Num < ModuleValues[type]->size())
121 return ModuleValues[type]->getOperand(Num);
122 Num -= ModuleValues[type]->size();
125 if (Values.size() > type && Values[type]->size() > Num)
126 return Values[type]->getOperand(Num);
128 if (!Create) return 0; // Do not create a placeholder?
130 std::pair<unsigned,unsigned> KeyValue(type, oNum);
131 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
132 ForwardReferences.lower_bound(KeyValue);
133 if (I != ForwardReferences.end() && I->first == KeyValue)
134 return I->second; // We have already created this placeholder
136 Value *Val = new Argument(getType(type));
137 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
141 /// getBasicBlock - Get a particular numbered basic block, which might be a
142 /// forward reference. This works together with ParseBasicBlock to handle these
143 /// forward references in a clean manner.
145 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
146 // Make sure there is room in the table...
147 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
149 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
150 // has already created this block, or if the forward reference has already
152 if (ParsedBasicBlocks[ID])
153 return ParsedBasicBlocks[ID];
155 // Otherwise, the basic block has not yet been created. Do so and add it to
156 // the ParsedBasicBlocks list.
157 return ParsedBasicBlocks[ID] = new BasicBlock();
160 /// getConstantValue - Just like getValue, except that it returns a null pointer
161 /// only on error. It always returns a constant (meaning that if the value is
162 /// defined, but is not a constant, that is an error). If the specified
163 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
164 /// after the real value is parsed, the placeholder is eliminated.
166 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
167 if (Value *V = getValue(Ty, Slot, false))
168 if (Constant *C = dyn_cast<Constant>(V))
169 return C; // If we already have the value parsed, just return it
171 throw std::string("Reference of a value is expected to be a constant!");
173 std::pair<const Type*, unsigned> Key(Ty, Slot);
174 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
176 if (I != GlobalRefs.end() && I->first == Key) {
177 BCR_TRACE(5, "Previous forward ref found!\n");
178 return cast<Constant>(I->second);
180 // Create a placeholder for the constant reference and
181 // keep track of the fact that we have a forward ref to recycle it
182 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
183 Constant *C = new ConstPHolder(Ty, Slot);
185 // Keep track of the fact that we have a forward ref to recycle it
186 GlobalRefs.insert(I, std::make_pair(Key, C));
192 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
193 const unsigned char *EndBuf,
196 if (ParsedBasicBlocks.size() == BlockNo)
197 ParsedBasicBlocks.push_back(BB = new BasicBlock());
198 else if (ParsedBasicBlocks[BlockNo] == 0)
199 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
201 BB = ParsedBasicBlocks[BlockNo];
203 std::vector<unsigned> Args;
205 ParseInstruction(Buf, EndBuf, Args, BB);
210 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
211 const unsigned char *EndBuf,
213 Function *CurrentFunction) {
214 // Allow efficient basic block lookup by number.
215 std::vector<BasicBlock*> BBMap;
217 for (Function::iterator I = CurrentFunction->begin(),
218 E = CurrentFunction->end(); I != E; ++I)
221 while (Buf < EndBuf) {
222 // Symtab block header: [num entries][type id number]
223 unsigned NumEntries, Typ;
224 if (read_vbr(Buf, EndBuf, NumEntries) ||
225 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
226 const Type *Ty = getType(Typ);
227 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
230 for (unsigned i = 0; i != NumEntries; ++i) {
231 // Symtab entry: [def slot #][name]
233 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
235 if (read(Buf, EndBuf, Name, false)) // Not aligned...
236 throw std::string("Failed reading symbol name.");
239 if (Typ == Type::TypeTyID)
240 V = (Value*)getType(slot);
241 else if (Typ == Type::LabelTyID) {
242 if (slot < BBMap.size())
245 V = getValue(Typ, slot, false); // Find mapping...
247 if (V == 0) throw std::string("Failed value look-up.");
248 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
249 if (!isa<Instruction>(V)) std::cerr << "\n");
251 V->setName(Name, ST);
255 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
258 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
259 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
261 if (I == GlobalRefs.end()) return; // Never forward referenced?
263 BCR_TRACE(3, "Mutating forward refs!\n");
264 Value *VPH = I->second; // Get the placeholder...
265 VPH->replaceAllUsesWith(NewV);
267 // If this is a global variable being resolved, remove the placeholder from
269 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
270 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
272 delete VPH; // Delete the old placeholder
273 GlobalRefs.erase(I); // Remove the map entry for it
276 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
277 const unsigned char *EndBuf) {
278 if (FunctionSignatureList.empty())
279 throw std::string("FunctionSignatureList empty!");
281 Function *F = FunctionSignatureList.back().first;
282 unsigned FunctionSlot = FunctionSignatureList.back().second;
283 FunctionSignatureList.pop_back();
285 // Save the information for future reading of the function
286 LazyFunctionInfo *LFI = new LazyFunctionInfo();
287 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
288 LazyFunctionLoadMap[F] = LFI;
289 // Pretend we've `parsed' this function
293 void BytecodeParser::materializeFunction(Function* F) {
294 // Find {start, end} pointers and slot in the map. If not there, we're done.
295 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
296 LazyFunctionLoadMap.find(F);
297 if (Fi == LazyFunctionLoadMap.end()) return;
299 LazyFunctionInfo *LFI = Fi->second;
300 const unsigned char *Buf = LFI->Buf;
301 const unsigned char *EndBuf = LFI->EndBuf;
302 unsigned FunctionSlot = LFI->FunctionSlot;
303 LazyFunctionLoadMap.erase(Fi);
306 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
308 if (!hasInternalMarkerOnly) {
309 // We didn't support weak linkage explicitly.
310 unsigned LinkageType;
311 if (read_vbr(Buf, EndBuf, LinkageType))
312 throw std::string("ParseFunction: Error reading from buffer.");
313 if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
314 ( hasExtendedLinkageSpecs && LinkageType > 4))
315 throw std::string("Invalid linkage type for Function.");
316 switch (LinkageType) {
317 case 0: Linkage = GlobalValue::ExternalLinkage; break;
318 case 1: Linkage = GlobalValue::WeakLinkage; break;
319 case 2: Linkage = GlobalValue::AppendingLinkage; break;
320 case 3: Linkage = GlobalValue::InternalLinkage; break;
321 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
324 // We used to only support two linkage models: internal and external
326 if (read_vbr(Buf, EndBuf, isInternal))
327 throw std::string("ParseFunction: Error reading from buffer.");
328 if (isInternal) Linkage = GlobalValue::InternalLinkage;
331 F->setLinkage(Linkage);
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);
339 // Keep track of how many basic blocks we have read in...
340 unsigned BlockNum = 0;
342 while (Buf < EndBuf) {
344 const unsigned char *OldBuf = Buf;
345 readBlock(Buf, EndBuf, Type, Size);
348 case BytecodeFormat::ConstantPool: {
349 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
350 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
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);
361 case BytecodeFormat::SymbolTable: {
362 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
363 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
368 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
371 throw std::string("Wrapped around reading bytecode.");
374 BCR_TRACE(2, "} end block\n");
376 // Malformed bc file if read past end of block.
377 ALIGN32(Buf, EndBuf);
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();
385 // Resolve forward references. Replace any uses of a forward reference value
386 // with the real value.
388 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
389 // number of operands. PHI nodes often have forward references, and can also
390 // often have a very large number of operands.
391 std::map<Value*, Value*> ForwardRefMapping;
392 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
393 I = ForwardReferences.begin(), E = ForwardReferences.end();
395 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
398 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
399 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
400 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
401 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
402 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
403 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
406 while (!ForwardReferences.empty()) {
407 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
408 ForwardReferences.begin();
409 Value *PlaceHolder = I->second;
410 ForwardReferences.erase(I);
412 // Now that all the uses are gone, delete the placeholder...
413 // If we couldn't find a def (error case), then leak a little
414 // memory, because otherwise we can't remove all uses!
418 // Clear out function-level types...
419 FunctionTypeValues.clear();
424 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
425 const unsigned char *End) {
426 if (!FunctionSignatureList.empty())
427 throw std::string("Two ModuleGlobalInfo packets found!");
429 // Read global variables...
431 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
432 while (VarType != Type::VoidTyID) { // List is terminated by Void
434 GlobalValue::LinkageTypes Linkage;
436 if (!hasInternalMarkerOnly) {
438 if (hasExtendedLinkageSpecs) {
439 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
440 // bit2,3,4 = Linkage, bit4+ = slot#
441 SlotNo = VarType >> 5;
442 LinkageID = (VarType >> 2) & 7;
444 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
445 // bit2,3 = Linkage, bit4+ = slot#
446 SlotNo = VarType >> 4;
447 LinkageID = (VarType >> 2) & 3;
450 default: assert(0 && "Unknown linkage type!");
451 case 0: Linkage = GlobalValue::ExternalLinkage; break;
452 case 1: Linkage = GlobalValue::WeakLinkage; break;
453 case 2: Linkage = GlobalValue::AppendingLinkage; break;
454 case 3: Linkage = GlobalValue::InternalLinkage; break;
455 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
458 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
459 // bit2 = isInternal, bit3+ = slot#
460 SlotNo = VarType >> 3;
461 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
462 GlobalValue::ExternalLinkage;
465 const Type *Ty = getType(SlotNo);
466 if (!isa<PointerType>(Ty))
467 throw std::string("Global not pointer type! Ty = " +
468 Ty->getDescription());
470 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
472 // Create the global variable...
473 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
475 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
476 ResolveReferencesToValue(GV, insertValue(GV, SlotNo, ModuleValues));
478 if (VarType & 2) { // Does it have an initializer?
480 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
481 GlobalInits.push_back(std::make_pair(GV, InitSlot));
483 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
486 // Read the function objects for all of the functions that are coming
487 unsigned FnSignature;
488 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
489 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
490 const Type *Ty = getType(FnSignature);
491 if (!isa<PointerType>(Ty) ||
492 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
493 throw std::string("Function not ptr to func type! Ty = " +
494 Ty->getDescription());
496 // We create functions by passing the underlying FunctionType to create...
497 Ty = cast<PointerType>(Ty)->getElementType();
499 // When the ModuleGlobalInfo section is read, we load the type of each
500 // function and the 'ModuleValues' slot that it lands in. We then load a
501 // placeholder into its slot to reserve it. When the function is loaded,
502 // this placeholder is replaced.
504 // Insert the placeholder...
505 Function *Func = new Function(cast<FunctionType>(Ty),
506 GlobalValue::InternalLinkage, "", TheModule);
507 unsigned DestSlot = insertValue(Func, FnSignature, ModuleValues);
508 ResolveReferencesToValue(Func, DestSlot);
510 // Keep track of this information in a list that is emptied as functions are
513 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
515 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
516 BCR_TRACE(2, "Function of type: " << Ty << "\n");
521 // Now that the function signature list is set up, reverse it so that we can
522 // remove elements efficiently from the back of the vector.
523 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
525 // This is for future proofing... in the future extra fields may be added that
526 // we don't understand, so we transparently ignore them.
531 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
532 const unsigned char *EndBuf) {
534 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
536 // Unpack version number: low four bits are for flags, top bits = version
537 Module::Endianness Endianness;
538 Module::PointerSize PointerSize;
539 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
540 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
542 bool hasNoEndianness = Version & 4;
543 bool hasNoPointerSize = Version & 8;
545 RevisionNum = Version >> 4;
547 // Default values for the current bytecode version
548 hasInternalMarkerOnly = false;
549 hasExtendedLinkageSpecs = true;
550 hasOldStyleVarargs = false;
551 hasVarArgCallPadding = false;
552 FirstDerivedTyID = 14;
554 switch (RevisionNum) {
555 case 1: // LLVM pre-1.0 release: will be deleted on the next rev
556 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
557 // hasNoEndianness, and hasNoPointerSize.
558 hasInternalMarkerOnly = true;
559 hasExtendedLinkageSpecs = false;
560 hasOldStyleVarargs = true;
561 hasVarArgCallPadding = true;
563 case 2: // LLVM pre-1.0 release:
564 // Version #2 added information about all 4 linkage types instead of just
565 // having internal and external.
566 hasExtendedLinkageSpecs = false;
567 hasOldStyleVarargs = true;
568 hasVarArgCallPadding = true;
570 case 0: // LLVM 1.0 release version
571 // Compared to rev #2, we added support for weak linkage, a more dense
572 // encoding, and better varargs support.
574 // FIXME: densify the encoding!
577 throw std::string("Unknown bytecode version number!");
580 if (hasNoEndianness) Endianness = Module::AnyEndianness;
581 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
583 TheModule->setEndianness(Endianness);
584 TheModule->setPointerSize(PointerSize);
585 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
586 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
587 << PointerSize << "\n");
590 void BytecodeParser::ParseModule(const unsigned char *Buf,
591 const unsigned char *EndBuf) {
593 readBlock(Buf, EndBuf, Type, Size);
594 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
595 throw std::string("Expected Module packet! B: "+
596 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
597 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
599 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
600 FunctionSignatureList.clear(); // Just in case...
602 // Read into instance variables...
603 ParseVersionInfo(Buf, EndBuf);
604 ALIGN32(Buf, EndBuf);
606 while (Buf < EndBuf) {
607 const unsigned char *OldBuf = Buf;
608 readBlock(Buf, EndBuf, Type, Size);
610 case BytecodeFormat::GlobalTypePlane:
611 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
612 ParseGlobalTypes(Buf, Buf+Size);
615 case BytecodeFormat::ModuleGlobalInfo:
616 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
617 ParseModuleGlobalInfo(Buf, Buf+Size);
620 case BytecodeFormat::ConstantPool:
621 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
622 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
625 case BytecodeFormat::Function: {
626 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
627 ParseFunction(Buf, Buf+Size);
631 case BytecodeFormat::SymbolTable:
632 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
633 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
638 if (OldBuf > Buf) throw std::string("Expected Module Block!");
641 BCR_TRACE(1, "} end block\n");
642 ALIGN32(Buf, EndBuf);
645 // After the module constant pool has been read, we can safely initialize
646 // global variables...
647 while (!GlobalInits.empty()) {
648 GlobalVariable *GV = GlobalInits.back().first;
649 unsigned Slot = GlobalInits.back().second;
650 GlobalInits.pop_back();
652 // Look up the initializer value...
653 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
654 if (GV->hasInitializer())
655 throw std::string("Global *already* has an initializer?!");
656 GV->setInitializer(cast<Constant>(V));
658 throw std::string("Cannot find initializer value.");
661 if (!FunctionSignatureList.empty())
662 throw std::string("Function expected, but bytecode stream ended!");
664 BCR_TRACE(0, "} end block\n\n");
667 void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
668 const std::string &ModuleID) {
670 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
672 // Read and check signature...
674 if (read(Buf, EndBuf, Sig) ||
675 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
676 throw std::string("Invalid bytecode signature!");
678 TheModule = new Module(ModuleID);
680 usesOldStyleVarargs = false;
681 ParseModule(Buf, EndBuf);
682 } catch (std::string &Error) {
683 freeState(); // Must destroy handles before deleting module!