1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
12 // Note that this library should be as fast as possible, reentrant, and
15 // TODO: Allow passing in an option to ignore the symbol table
17 //===----------------------------------------------------------------------===//
19 #include "ReaderInternals.h"
20 #include "llvm/Bytecode/Reader.h"
21 #include "llvm/Bytecode/Format.h"
22 #include "llvm/Module.h"
23 #include "Support/StringExtras.h"
26 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
27 if (Ty->isPrimitiveType())
28 return Ty->getPrimitiveID();
30 // Scan the compaction table for the type if needed.
31 if (CompactionTable.size() > Type::TypeTyID) {
32 std::vector<Value*> &Plane = CompactionTable[Type::TypeTyID];
34 std::vector<Value*>::iterator I = find(Plane.begin(), Plane.end(),
35 const_cast<Type*>(Ty));
37 throw std::string("Couldn't find type specified in compaction table!");
38 return Type::FirstDerivedTyID + (&*I - &Plane[0]);
42 // Check the function level types first...
43 TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
44 FunctionTypeValues.end(), Ty);
45 if (I != FunctionTypeValues.end())
46 return Type::FirstDerivedTyID + ModuleTypeValues.size() +
47 (&*I - &FunctionTypeValues[0]);
49 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
50 if (I == ModuleTypeValues.end())
51 throw std::string("Didn't find type in ModuleTypeValues.");
52 return Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
55 const Type *BytecodeParser::getType(unsigned ID) {
56 //cerr << "Looking up Type ID: " << ID << "\n";
58 if (ID < Type::FirstDerivedTyID)
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 -= Type::FirstDerivedTyID;
65 if (CompactionTable.size() > Type::TypeTyID &&
66 !CompactionTable[Type::TypeTyID].empty()) {
67 if (ID >= CompactionTable[Type::TypeTyID].size())
68 throw std::string("Type ID out of range for compaction table!");
69 return cast<Type>(CompactionTable[Type::TypeTyID][ID]);
72 // Is it a module-level type?
73 if (ID < ModuleTypeValues.size())
74 return ModuleTypeValues[ID].get();
76 // Nope, is it a function-level type?
77 ID -= ModuleTypeValues.size();
78 if (ID < FunctionTypeValues.size())
79 return FunctionTypeValues[ID].get();
81 throw std::string("Illegal type reference!");
84 static inline bool hasImplicitNull(unsigned TyID, bool EncodesPrimitiveZeros) {
85 if (!EncodesPrimitiveZeros)
86 return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
87 TyID != Type::VoidTyID;
88 return TyID >= Type::FirstDerivedTyID;
91 unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
92 ValueTable &ValueTab) {
93 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
94 !hasImplicitNull(type, hasExplicitPrimitiveZeros) &&
95 "Cannot read null values from bytecode!");
96 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
98 if (ValueTab.size() <= type)
99 ValueTab.resize(type+1);
101 if (!ValueTab[type]) ValueTab[type] = new ValueList();
103 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
104 // << "] = " << Val << "\n";
105 ValueTab[type]->push_back(Val);
107 bool HasOffset = hasImplicitNull(type, hasExplicitPrimitiveZeros);
108 return ValueTab[type]->size()-1 + HasOffset;
111 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
112 assert(type != Type::TypeTyID && "getValue() cannot get types!");
113 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
116 // If there is a compaction table active, it defines the low-level numbers.
117 // If not, the module values define the low-level numbers.
118 if (CompactionTable.size() > type && !CompactionTable[type].empty()) {
119 if (Num < CompactionTable[type].size())
120 return CompactionTable[type][Num];
121 Num -= CompactionTable[type].size();
123 // If the type plane was compactified, figure out the global type ID.
124 unsigned GlobalTyID = type;
125 if (CompactionTable.size() > Type::TypeTyID &&
126 !CompactionTable[Type::TypeTyID].empty() &&
127 type >= Type::FirstDerivedTyID) {
128 std::vector<Value*> &TypePlane = CompactionTable[Type::TypeTyID];
129 const Type *Ty = cast<Type>(TypePlane[type-Type::FirstDerivedTyID]);
130 TypeValuesListTy::iterator I =
131 find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
132 assert(I != ModuleTypeValues.end());
133 GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
136 if (hasImplicitNull(GlobalTyID, hasExplicitPrimitiveZeros)) {
138 return Constant::getNullValue(getType(type));
142 if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
143 if (Num < ModuleValues[GlobalTyID]->size())
144 return ModuleValues[GlobalTyID]->getOperand(Num);
145 Num -= ModuleValues[GlobalTyID]->size();
149 if (Values.size() > type && Values[type] && Num < Values[type]->size())
150 return Values[type]->getOperand(Num);
152 if (!Create) return 0; // Do not create a placeholder?
154 std::pair<unsigned,unsigned> KeyValue(type, oNum);
155 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
156 ForwardReferences.lower_bound(KeyValue);
157 if (I != ForwardReferences.end() && I->first == KeyValue)
158 return I->second; // We have already created this placeholder
160 Value *Val = new Argument(getType(type));
161 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
165 /// getBasicBlock - Get a particular numbered basic block, which might be a
166 /// forward reference. This works together with ParseBasicBlock to handle these
167 /// forward references in a clean manner.
169 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
170 // Make sure there is room in the table...
171 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
173 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
174 // has already created this block, or if the forward reference has already
176 if (ParsedBasicBlocks[ID])
177 return ParsedBasicBlocks[ID];
179 // Otherwise, the basic block has not yet been created. Do so and add it to
180 // the ParsedBasicBlocks list.
181 return ParsedBasicBlocks[ID] = new BasicBlock();
184 /// getConstantValue - Just like getValue, except that it returns a null pointer
185 /// only on error. It always returns a constant (meaning that if the value is
186 /// defined, but is not a constant, that is an error). If the specified
187 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
188 /// after the real value is parsed, the placeholder is eliminated.
190 Constant *BytecodeParser::getConstantValue(unsigned TypeSlot, unsigned Slot) {
191 if (Value *V = getValue(TypeSlot, Slot, false))
192 if (Constant *C = dyn_cast<Constant>(V))
193 return C; // If we already have the value parsed, just return it
194 else if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
195 // ConstantPointerRef's are an abomination, but at least they don't have
196 // to infest bytecode files.
197 return ConstantPointerRef::get(GV);
199 throw std::string("Reference of a value is expected to be a constant!");
201 const Type *Ty = getType(TypeSlot);
202 std::pair<const Type*, unsigned> Key(Ty, Slot);
203 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
205 if (I != ConstantFwdRefs.end() && I->first == Key) {
206 BCR_TRACE(5, "Previous forward ref found!\n");
209 // Create a placeholder for the constant reference and
210 // keep track of the fact that we have a forward ref to recycle it
211 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
212 Constant *C = new ConstPHolder(Ty, Slot);
214 // Keep track of the fact that we have a forward ref to recycle it
215 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
220 /// ParseBasicBlock - In LLVM 1.0 bytecode files, we used to output one
221 /// basicblock at a time. This method reads in one of the basicblock packets.
222 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
223 const unsigned char *EndBuf,
226 if (ParsedBasicBlocks.size() == BlockNo)
227 ParsedBasicBlocks.push_back(BB = new BasicBlock());
228 else if (ParsedBasicBlocks[BlockNo] == 0)
229 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
231 BB = ParsedBasicBlocks[BlockNo];
233 std::vector<unsigned> Args;
235 ParseInstruction(Buf, EndBuf, Args, BB);
241 /// ParseInstructionList - Parse all of the BasicBlock's & Instruction's in the
242 /// body of a function. In post 1.0 bytecode files, we no longer emit basic
243 /// block individually, in order to avoid per-basic-block overhead.
244 unsigned BytecodeParser::ParseInstructionList(Function *F,
245 const unsigned char *&Buf,
246 const unsigned char *EndBuf) {
247 unsigned BlockNo = 0;
248 std::vector<unsigned> Args;
250 while (Buf < EndBuf) {
252 if (ParsedBasicBlocks.size() == BlockNo)
253 ParsedBasicBlocks.push_back(BB = new BasicBlock());
254 else if (ParsedBasicBlocks[BlockNo] == 0)
255 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
257 BB = ParsedBasicBlocks[BlockNo];
259 F->getBasicBlockList().push_back(BB);
261 // Read instructions into this basic block until we get to a terminator
262 while (Buf < EndBuf && !BB->getTerminator())
263 ParseInstruction(Buf, EndBuf, Args, BB);
265 if (!BB->getTerminator())
266 throw std::string("Non-terminated basic block found!");
272 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
273 const unsigned char *EndBuf,
275 Function *CurrentFunction) {
276 // Allow efficient basic block lookup by number.
277 std::vector<BasicBlock*> BBMap;
279 for (Function::iterator I = CurrentFunction->begin(),
280 E = CurrentFunction->end(); I != E; ++I)
283 while (Buf < EndBuf) {
284 // Symtab block header: [num entries][type id number]
285 unsigned NumEntries = read_vbr_uint(Buf, EndBuf);
286 unsigned Typ = read_vbr_uint(Buf, EndBuf);
287 const Type *Ty = getType(Typ);
288 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
291 for (unsigned i = 0; i != NumEntries; ++i) {
292 // Symtab entry: [def slot #][name]
293 unsigned slot = read_vbr_uint(Buf, EndBuf);
294 std::string Name = read_str(Buf, EndBuf);
297 if (Typ == Type::TypeTyID)
298 V = (Value*)getType(slot);
299 else if (Typ == Type::LabelTyID) {
300 if (slot < BBMap.size())
303 V = getValue(Typ, slot, false); // Find mapping...
306 throw "Failed value look-up for name '" + Name + "'";
307 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
308 if (!isa<Instruction>(V)) std::cerr << "\n");
310 V->setName(Name, ST);
314 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
317 void BytecodeParser::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
318 ConstantRefsType::iterator I =
319 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
320 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
322 BCR_TRACE(3, "Mutating forward refs!\n");
323 Value *PH = I->second; // Get the placeholder...
324 PH->replaceAllUsesWith(NewV);
325 delete PH; // Delete the old placeholder
326 ConstantFwdRefs.erase(I); // Remove the map entry for it
329 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
330 const unsigned char *EndBuf) {
331 if (FunctionSignatureList.empty())
332 throw std::string("FunctionSignatureList empty!");
334 Function *F = FunctionSignatureList.back();
335 FunctionSignatureList.pop_back();
337 // Save the information for future reading of the function
338 LazyFunctionLoadMap[F] = LazyFunctionInfo(Buf, EndBuf);
339 // Pretend we've `parsed' this function
343 void BytecodeParser::materializeFunction(Function* F) {
344 // Find {start, end} pointers and slot in the map. If not there, we're done.
345 std::map<Function*, LazyFunctionInfo>::iterator Fi =
346 LazyFunctionLoadMap.find(F);
347 if (Fi == LazyFunctionLoadMap.end()) return;
349 const unsigned char *Buf = Fi->second.Buf;
350 const unsigned char *EndBuf = Fi->second.EndBuf;
351 LazyFunctionLoadMap.erase(Fi);
353 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
355 unsigned LinkageType = read_vbr_uint(Buf, EndBuf);
356 if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
357 ( hasExtendedLinkageSpecs && LinkageType > 4))
358 throw std::string("Invalid linkage type for Function.");
359 switch (LinkageType) {
360 case 0: Linkage = GlobalValue::ExternalLinkage; break;
361 case 1: Linkage = GlobalValue::WeakLinkage; break;
362 case 2: Linkage = GlobalValue::AppendingLinkage; break;
363 case 3: Linkage = GlobalValue::InternalLinkage; break;
364 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
367 F->setLinkage(Linkage);
369 // Keep track of how many basic blocks we have read in...
370 unsigned BlockNum = 0;
371 bool InsertedArguments = false;
373 while (Buf < EndBuf) {
375 const unsigned char *OldBuf = Buf;
376 readBlock(Buf, EndBuf, Type, Size);
379 case BytecodeFormat::ConstantPool:
380 if (!InsertedArguments) {
381 // Insert arguments into the value table before we parse the first basic
382 // block in the function, but after we potentially read in the
384 const FunctionType *FT = F->getFunctionType();
385 Function::aiterator AI = F->abegin();
386 for (FunctionType::param_iterator It = FT->param_begin();
387 It != FT->param_end(); ++It, ++AI)
388 insertValue(AI, getTypeSlot(AI->getType()), Values);
389 InsertedArguments = true;
392 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
393 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
396 case BytecodeFormat::CompactionTable:
397 BCR_TRACE(2, "BLOCK BytecodeFormat::CompactionTable: {\n");
398 ParseCompactionTable(Buf, Buf+Size);
401 case BytecodeFormat::BasicBlock: {
402 if (!InsertedArguments) {
403 // Insert arguments into the value table before we parse the first basic
404 // block in the function, but after we potentially read in the
406 const FunctionType *FT = F->getFunctionType();
407 Function::aiterator AI = F->abegin();
408 for (FunctionType::param_iterator It = FT->param_begin();
409 It != FT->param_end(); ++It, ++AI)
410 insertValue(AI, getTypeSlot(AI->getType()), Values);
411 InsertedArguments = true;
414 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
415 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
416 F->getBasicBlockList().push_back(BB);
420 case BytecodeFormat::InstructionList: {
421 // Insert arguments into the value table before we parse the instruction
422 // list for the function, but after we potentially read in the compaction
424 if (!InsertedArguments) {
425 const FunctionType *FT = F->getFunctionType();
426 Function::aiterator AI = F->abegin();
427 for (FunctionType::param_iterator It = FT->param_begin();
428 It != FT->param_end(); ++It, ++AI)
429 insertValue(AI, getTypeSlot(AI->getType()), Values);
430 InsertedArguments = true;
433 BCR_TRACE(2, "BLOCK BytecodeFormat::InstructionList: {\n");
434 if (BlockNum) throw std::string("Already parsed basic blocks!");
435 BlockNum = ParseInstructionList(F, Buf, Buf+Size);
439 case BytecodeFormat::SymbolTable:
440 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
441 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
445 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
448 throw std::string("Wrapped around reading bytecode.");
451 BCR_TRACE(2, "} end block\n");
453 // Malformed bc file if read past end of block.
454 align32(Buf, EndBuf);
457 // Make sure there were no references to non-existant basic blocks.
458 if (BlockNum != ParsedBasicBlocks.size())
459 throw std::string("Illegal basic block operand reference");
460 ParsedBasicBlocks.clear();
462 // Resolve forward references. Replace any uses of a forward reference value
463 // with the real value.
465 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
466 // number of operands. PHI nodes often have forward references, and can also
467 // often have a very large number of operands.
469 // FIXME: REEVALUATE. replaceAllUsesWith is _much_ faster now, and this code
470 // should be simplified back to using it!
472 std::map<Value*, Value*> ForwardRefMapping;
473 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
474 I = ForwardReferences.begin(), E = ForwardReferences.end();
476 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
479 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
480 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
482 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
483 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
484 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
487 while (!ForwardReferences.empty()) {
488 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
489 ForwardReferences.begin();
490 Value *PlaceHolder = I->second;
491 ForwardReferences.erase(I);
493 // Now that all the uses are gone, delete the placeholder...
494 // If we couldn't find a def (error case), then leak a little
495 // memory, because otherwise we can't remove all uses!
499 // Clear out function-level types...
500 FunctionTypeValues.clear();
501 CompactionTable.clear();
505 void BytecodeParser::ParseCompactionTable(const unsigned char *&Buf,
506 const unsigned char *End) {
509 unsigned NumEntries = read_vbr_uint(Buf, End);
512 if ((NumEntries & 3) == 3) {
514 Ty = read_vbr_uint(Buf, End);
516 Ty = NumEntries >> 2;
520 if (Ty >= CompactionTable.size())
521 CompactionTable.resize(Ty+1);
523 if (!CompactionTable[Ty].empty())
524 throw std::string("Compaction table plane contains multiple entries!");
526 if (Ty == Type::TypeTyID) {
527 for (unsigned i = 0; i != NumEntries; ++i) {
528 const Type *Typ = getGlobalTableType(read_vbr_uint(Buf, End));
529 CompactionTable[Type::TypeTyID].push_back(const_cast<Type*>(Typ));
532 CompactionTable.resize(NumEntries+Type::FirstDerivedTyID);
534 const Type *Typ = getType(Ty);
535 // Push the implicit zero
536 CompactionTable[Ty].push_back(Constant::getNullValue(Typ));
537 for (unsigned i = 0; i != NumEntries; ++i) {
538 Value *V = getGlobalTableValue(Typ, read_vbr_uint(Buf, End));
539 CompactionTable[Ty].push_back(V);
548 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
549 const unsigned char *End) {
550 if (!FunctionSignatureList.empty())
551 throw std::string("Two ModuleGlobalInfo packets found!");
553 // Read global variables...
554 unsigned VarType = read_vbr_uint(Buf, End);
555 while (VarType != Type::VoidTyID) { // List is terminated by Void
557 GlobalValue::LinkageTypes Linkage;
560 if (hasExtendedLinkageSpecs) {
561 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
562 // bit2,3,4 = Linkage, bit4+ = slot#
563 SlotNo = VarType >> 5;
564 LinkageID = (VarType >> 2) & 7;
566 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
567 // bit2,3 = Linkage, bit4+ = slot#
568 SlotNo = VarType >> 4;
569 LinkageID = (VarType >> 2) & 3;
572 default: assert(0 && "Unknown linkage type!");
573 case 0: Linkage = GlobalValue::ExternalLinkage; break;
574 case 1: Linkage = GlobalValue::WeakLinkage; break;
575 case 2: Linkage = GlobalValue::AppendingLinkage; break;
576 case 3: Linkage = GlobalValue::InternalLinkage; break;
577 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
580 const Type *Ty = getType(SlotNo);
581 if (!isa<PointerType>(Ty))
582 throw std::string("Global not pointer type! Ty = " +
583 Ty->getDescription());
585 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
587 // Create the global variable...
588 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
590 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
591 insertValue(GV, SlotNo, ModuleValues);
593 if (VarType & 2) // Does it have an initializer?
594 GlobalInits.push_back(std::make_pair(GV, read_vbr_uint(Buf, End)));
595 VarType = read_vbr_uint(Buf, End);
598 // Read the function objects for all of the functions that are coming
599 unsigned FnSignature = read_vbr_uint(Buf, End);
600 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
601 const Type *Ty = getType(FnSignature);
602 if (!isa<PointerType>(Ty) ||
603 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
604 throw std::string("Function not ptr to func type! Ty = " +
605 Ty->getDescription());
607 // We create functions by passing the underlying FunctionType to create...
608 Ty = cast<PointerType>(Ty)->getElementType();
610 // When the ModuleGlobalInfo section is read, we load the type of each
611 // function and the 'ModuleValues' slot that it lands in. We then load a
612 // placeholder into its slot to reserve it. When the function is loaded,
613 // this placeholder is replaced.
615 // Insert the placeholder...
616 Function *Func = new Function(cast<FunctionType>(Ty),
617 GlobalValue::InternalLinkage, "", TheModule);
618 insertValue(Func, FnSignature, ModuleValues);
620 // Keep track of this information in a list that is emptied as functions are
623 FunctionSignatureList.push_back(Func);
625 FnSignature = read_vbr_uint(Buf, End);
626 BCR_TRACE(2, "Function of type: " << Ty << "\n");
629 if (hasInconsistentModuleGlobalInfo)
632 // Now that the function signature list is set up, reverse it so that we can
633 // remove elements efficiently from the back of the vector.
634 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
636 // This is for future proofing... in the future extra fields may be added that
637 // we don't understand, so we transparently ignore them.
642 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
643 const unsigned char *EndBuf) {
644 unsigned Version = read_vbr_uint(Buf, EndBuf);
646 // Unpack version number: low four bits are for flags, top bits = version
647 Module::Endianness Endianness;
648 Module::PointerSize PointerSize;
649 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
650 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
652 bool hasNoEndianness = Version & 4;
653 bool hasNoPointerSize = Version & 8;
655 RevisionNum = Version >> 4;
657 // Default values for the current bytecode version
658 hasExtendedLinkageSpecs = true;
659 hasOldStyleVarargs = false;
660 hasVarArgCallPadding = false;
661 hasInconsistentModuleGlobalInfo = false;
662 hasExplicitPrimitiveZeros = false;
664 switch (RevisionNum) {
665 case 2: // LLVM pre-1.0 release: will be deleted on the next rev
666 // Version #2 only supported 4 linkage types. It didn't support weak
668 hasExtendedLinkageSpecs = false;
669 hasOldStyleVarargs = true;
670 hasVarArgCallPadding = true;
672 case 0: // LLVM 1.0, 1.1 release version
673 // Compared to rev #2, we added support for weak linkage, a more dense
674 // encoding, and better varargs support.
676 // Base LLVM 1.0 bytecode format.
677 hasInconsistentModuleGlobalInfo = true;
678 hasExplicitPrimitiveZeros = true;
680 case 1: // LLVM 1.2 release version
681 // LLVM 1.2 added explicit support for emitting strings efficiently.
683 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
684 // included the size for the alignment at the end, where the rest of the
689 throw std::string("Unknown bytecode version number!");
692 if (hasNoEndianness) Endianness = Module::AnyEndianness;
693 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
695 TheModule->setEndianness(Endianness);
696 TheModule->setPointerSize(PointerSize);
697 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
698 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
699 << PointerSize << "\n");
702 void BytecodeParser::ParseModule(const unsigned char *Buf,
703 const unsigned char *EndBuf) {
705 readBlock(Buf, EndBuf, Type, Size);
706 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
707 throw std::string("Expected Module packet! B: "+
708 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
709 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
711 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
712 FunctionSignatureList.clear(); // Just in case...
714 // Read into instance variables...
715 ParseVersionInfo(Buf, EndBuf);
716 align32(Buf, EndBuf);
718 while (Buf < EndBuf) {
719 const unsigned char *OldBuf = Buf;
720 readBlock(Buf, EndBuf, Type, Size);
722 case BytecodeFormat::GlobalTypePlane:
723 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
724 ParseGlobalTypes(Buf, Buf+Size);
727 case BytecodeFormat::ModuleGlobalInfo:
728 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
729 ParseModuleGlobalInfo(Buf, Buf+Size);
732 case BytecodeFormat::ConstantPool:
733 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
734 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
737 case BytecodeFormat::Function: {
738 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
739 ParseFunction(Buf, Buf+Size);
743 case BytecodeFormat::SymbolTable:
744 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
745 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
749 if (OldBuf > Buf) throw std::string("Expected Module Block!");
752 BCR_TRACE(1, "} end block\n");
753 align32(Buf, EndBuf);
756 // After the module constant pool has been read, we can safely initialize
757 // global variables...
758 while (!GlobalInits.empty()) {
759 GlobalVariable *GV = GlobalInits.back().first;
760 unsigned Slot = GlobalInits.back().second;
761 GlobalInits.pop_back();
763 // Look up the initializer value...
764 // FIXME: Preserve this type ID!
765 unsigned TypeSlot = getTypeSlot(GV->getType()->getElementType());
766 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
767 if (GV->hasInitializer())
768 throw std::string("Global *already* has an initializer?!");
769 GV->setInitializer(CV);
771 throw std::string("Cannot find initializer value.");
774 if (!FunctionSignatureList.empty())
775 throw std::string("Function expected, but bytecode stream ended!");
777 BCR_TRACE(0, "} end block\n\n");
780 void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
781 const std::string &ModuleID) {
783 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
785 // Read and check signature...
786 unsigned Sig = read(Buf, EndBuf);
787 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
788 throw std::string("Invalid bytecode signature!");
790 TheModule = new Module(ModuleID);
792 usesOldStyleVarargs = false;
793 ParseModule(Buf, EndBuf);
794 } catch (std::string &Error) {
795 freeState(); // Must destroy handles before deleting module!