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 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
57 //cerr << "Looking up Type ID: " << ID << "\n";
58 const Value *V = getValue(Type::TypeTy, ID, false);
59 return cast_or_null<Type>(V);
62 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
63 assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
64 Val->getType()->isPrimitiveType() ||
65 !cast<Constant>(Val)->isNullValue()) &&
66 "Cannot read null values from bytecode!");
67 unsigned type = getTypeSlot(Val->getType());
68 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
70 if (ValueTab.size() <= type) {
71 unsigned OldSize = ValueTab.size();
72 ValueTab.resize(type+1);
73 while (OldSize != type+1)
74 ValueTab[OldSize++] = new ValueList();
77 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
78 // << "] = " << Val << "\n";
79 ValueTab[type]->push_back(Val);
81 bool HasOffset = HasImplicitZeroInitializer &&
82 !Val->getType()->isPrimitiveType();
84 return ValueTab[type]->size()-1 + HasOffset;
88 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
90 assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
91 assert((!HasImplicitZeroInitializer || Slot != 0) &&
92 "Cannot change zero init");
93 unsigned type = getTypeSlot(Val->getType());
94 assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
95 ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
98 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
100 unsigned type = getTypeSlot(Ty); // The type plane it lives in...
102 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
103 assert(Create == false);
104 if (Num < Type::NumPrimitiveIDs) {
105 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
106 if (T) return (Value*)T; // Asked for a primitive type...
109 // Otherwise, derived types need offset...
110 Num -= FirstDerivedTyID;
112 // Is it a module-level type?
113 if (Num < ModuleTypeValues.size())
114 return (Value*)ModuleTypeValues[Num].get();
116 // Nope, is it a function-level type?
117 Num -= ModuleTypeValues.size();
118 if (Num < FunctionTypeValues.size())
119 return (Value*)FunctionTypeValues[Num].get();
124 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
126 return Constant::getNullValue(Ty);
130 if (type < ModuleValues.size()) {
131 if (Num < ModuleValues[type]->size())
132 return ModuleValues[type]->getOperand(Num);
133 Num -= ModuleValues[type]->size();
136 if (Values.size() > type && Values[type]->size() > Num)
137 return Values[type]->getOperand(Num);
139 if (!Create) return 0; // Do not create a placeholder?
142 switch (Ty->getPrimitiveID()) {
143 case Type::LabelTyID:
144 d = new BBPHolder(Ty, oNum);
147 d = new ValPHolder(Ty, oNum);
151 assert(d != 0 && "How did we not make something?");
152 if (insertValue(d, LateResolveValues) == -1) return 0;
156 /// getConstantValue - Just like getValue, except that it returns a null pointer
157 /// only on error. It always returns a constant (meaning that if the value is
158 /// defined, but is not a constant, that is an error). If the specified
159 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
160 /// after the real value is parsed, the placeholder is eliminated.
162 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
163 if (Value *V = getValue(Ty, Slot, false))
164 return dyn_cast<Constant>(V); // If we already have the value parsed...
166 std::pair<const Type*, unsigned> Key(Ty, Slot);
167 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
169 if (I != GlobalRefs.end() && I->first == Key) {
170 BCR_TRACE(5, "Previous forward ref found!\n");
171 return cast<Constant>(I->second);
173 // Create a placeholder for the constant reference and
174 // keep track of the fact that we have a forward ref to recycle it
175 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
176 Constant *C = new ConstPHolder(Ty, Slot);
178 // Keep track of the fact that we have a forward ref to recycle it
179 GlobalRefs.insert(I, std::make_pair(Key, C));
185 void BytecodeParser::postResolveValues(ValueTable &ValTab) {
186 while (!ValTab.empty()) {
187 ValueList &VL = *ValTab.back();
190 while (!VL.empty()) {
191 Value *V = VL.back();
192 unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
195 Value *NewVal = getValue(V->getType(), IDNumber, false);
197 throw std::string("Unresolvable reference found: <" +
198 V->getType()->getDescription() + ">:" +
199 utostr(IDNumber) + ".");
201 // Fixup all of the uses of this placeholder def...
202 V->replaceAllUsesWith(NewVal);
204 // Now that all the uses are gone, delete the placeholder...
205 // If we couldn't find a def (error case), then leak a little
206 delete V; // memory, 'cause otherwise we can't remove all uses!
212 std::auto_ptr<BasicBlock>
213 BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
214 const unsigned char *EndBuf) {
215 std::auto_ptr<BasicBlock> BB(new BasicBlock());
217 while (Buf < EndBuf) {
219 ParseInstruction(Buf, EndBuf, Inst);
221 if (Inst == 0) { throw std::string("Could not parse Instruction."); }
222 if (insertValue(Inst, Values) == -1) {
223 throw std::string("Could not insert value.");
226 BB->getInstList().push_back(Inst);
233 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
234 const unsigned char *EndBuf,
236 while (Buf < EndBuf) {
237 // Symtab block header: [num entries][type id number]
238 unsigned NumEntries, Typ;
239 if (read_vbr(Buf, EndBuf, NumEntries) ||
240 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
241 const Type *Ty = getType(Typ);
242 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
244 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
247 for (unsigned i = 0; i < NumEntries; ++i) {
248 // Symtab entry: [def slot #][name]
250 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
252 if (read(Buf, EndBuf, Name, false)) // Not aligned...
253 throw std::string("Buffer not aligned.");
255 Value *V = getValue(Ty, slot, false); // Find mapping...
257 BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
258 throw std::string("Failed value look-up.");
260 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
261 if (!isa<Instruction>(V)) std::cerr << "\n");
263 V->setName(Name, ST);
267 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
270 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
271 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
273 if (I == GlobalRefs.end()) return; // Never forward referenced?
275 BCR_TRACE(3, "Mutating forward refs!\n");
276 Value *VPH = I->second; // Get the placeholder...
278 VPH->replaceAllUsesWith(NewV);
280 // If this is a global variable being resolved, remove the placeholder from
282 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
283 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
285 delete VPH; // Delete the old placeholder
286 GlobalRefs.erase(I); // Remove the map entry for it
290 BytecodeParser::ParseFunction(const unsigned char *&Buf,
291 const unsigned char *EndBuf) {
292 if (FunctionSignatureList.empty())
293 throw std::string("FunctionSignatureList empty!");
295 Function *F = FunctionSignatureList.back().first;
296 unsigned FunctionSlot = FunctionSignatureList.back().second;
297 FunctionSignatureList.pop_back();
299 // Save the information for future reading of the function
300 LazyFunctionInfo *LFI = new LazyFunctionInfo();
301 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
302 LazyFunctionLoadMap[F] = LFI;
303 // Pretend we've `parsed' this function
307 void BytecodeParser::materializeFunction(Function* F) {
308 // Find {start, end} pointers and slot in the map. If not there, we're done.
309 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
310 LazyFunctionLoadMap.find(F);
311 if (Fi == LazyFunctionLoadMap.end()) return;
313 LazyFunctionInfo *LFI = Fi->second;
314 const unsigned char *Buf = LFI->Buf;
315 const unsigned char *EndBuf = LFI->EndBuf;
316 unsigned FunctionSlot = LFI->FunctionSlot;
317 LazyFunctionLoadMap.erase(Fi);
320 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
322 if (!hasInternalMarkerOnly) {
323 unsigned LinkageType;
324 if (read_vbr(Buf, EndBuf, LinkageType))
325 throw std::string("ParseFunction: Error reading from buffer.");
326 if (LinkageType & ~0x3)
327 throw std::string("Invalid linkage type for Function.");
328 Linkage = (GlobalValue::LinkageTypes)LinkageType;
330 // We used to only support two linkage models: internal and external
332 if (read_vbr(Buf, EndBuf, isInternal))
333 throw std::string("ParseFunction: Error reading from buffer.");
334 if (isInternal) Linkage = GlobalValue::InternalLinkage;
337 F->setLinkage(Linkage);
339 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
340 Function::aiterator AI = F->abegin();
341 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
342 It != Params.end(); ++It, ++AI) {
343 if (insertValue(AI, Values) == -1)
344 throw std::string("Error reading function arguments!");
347 while (Buf < EndBuf) {
349 const unsigned char *OldBuf = Buf;
350 readBlock(Buf, EndBuf, Type, Size);
353 case BytecodeFormat::ConstantPool: {
354 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
355 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
359 case BytecodeFormat::BasicBlock: {
360 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
361 std::auto_ptr<BasicBlock> BB = ParseBasicBlock(Buf, Buf+Size);
362 if (!BB.get() || insertValue(BB.get(), Values) == -1)
363 throw std::string("Parse error: BasicBlock");
365 F->getBasicBlockList().push_back(BB.release());
369 case BytecodeFormat::SymbolTable: {
370 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
371 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable());
376 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
379 throw std::string("Wrapped around reading bytecode.");
382 BCR_TRACE(2, "} end block\n");
384 // Malformed bc file if read past end of block.
385 ALIGN32(Buf, EndBuf);
388 // Check for unresolvable references
389 postResolveValues(LateResolveValues);
391 //ResolveReferencesToValue(F, FunctionSlot);
393 // Clear out function-level types...
394 FunctionTypeValues.clear();
399 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
400 const unsigned char *End) {
401 if (!FunctionSignatureList.empty())
402 throw std::string("Two ModuleGlobalInfo packets found!");
404 // Read global variables...
406 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
407 while (VarType != Type::VoidTyID) { // List is terminated by Void
409 GlobalValue::LinkageTypes Linkage;
411 if (!hasInternalMarkerOnly) {
412 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
413 // bit2,3 = Linkage, bit4+ = slot#
414 SlotNo = VarType >> 4;
415 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
417 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
418 // bit2 = isInternal, bit3+ = slot#
419 SlotNo = VarType >> 3;
420 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
421 GlobalValue::ExternalLinkage;
424 const Type *Ty = getType(SlotNo);
425 if (!Ty || !isa<PointerType>(Ty))
426 throw std::string("Global not pointer type! Ty = " +
427 Ty->getDescription());
429 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
431 // Create the global variable...
432 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
434 int DestSlot = insertValue(GV, ModuleValues);
435 if (DestSlot == -1) throw Error_DestSlot;
436 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
437 ResolveReferencesToValue(GV, (unsigned)DestSlot);
439 if (VarType & 2) { // Does it have an initializer?
441 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
442 GlobalInits.push_back(std::make_pair(GV, InitSlot));
444 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
447 // Read the function objects for all of the functions that are coming
448 unsigned FnSignature;
449 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
450 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
451 const Type *Ty = getType(FnSignature);
452 if (!Ty || !isa<PointerType>(Ty) ||
453 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
454 throw std::string("Function not ptr to func type! Ty = " +
455 Ty->getDescription());
458 // We create functions by passing the underlying FunctionType to create...
459 Ty = cast<PointerType>(Ty)->getElementType();
461 // When the ModuleGlobalInfo section is read, we load the type of each
462 // function and the 'ModuleValues' slot that it lands in. We then load a
463 // placeholder into its slot to reserve it. When the function is loaded,
464 // this placeholder is replaced.
466 // Insert the placeholder...
467 Function *Func = new Function(cast<FunctionType>(Ty),
468 GlobalValue::InternalLinkage, "", TheModule);
469 int DestSlot = insertValue(Func, ModuleValues);
470 if (DestSlot == -1) throw Error_DestSlot;
471 ResolveReferencesToValue(Func, (unsigned)DestSlot);
473 // Keep track of this information in a list that is emptied as functions are
476 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
478 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
479 BCR_TRACE(2, "Function of type: " << Ty << "\n");
484 // Now that the function signature list is set up, reverse it so that we can
485 // remove elements efficiently from the back of the vector.
486 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
488 // This is for future proofing... in the future extra fields may be added that
489 // we don't understand, so we transparently ignore them.
494 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
495 const unsigned char *EndBuf) {
497 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
499 // Unpack version number: low four bits are for flags, top bits = version
500 Module::Endianness Endianness;
501 Module::PointerSize PointerSize;
502 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
503 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
505 bool hasNoEndianness = Version & 4;
506 bool hasNoPointerSize = Version & 8;
508 RevisionNum = Version >> 4;
510 // Default values for the current bytecode version
511 HasImplicitZeroInitializer = true;
512 hasInternalMarkerOnly = false;
513 FirstDerivedTyID = 14;
515 switch (RevisionNum) {
516 case 0: // Initial revision
517 // Version #0 didn't have any of the flags stored correctly, and in fact as
518 // only valid with a 14 in the flags values. Also, it does not support
519 // encoding zero initializers for arrays compactly.
521 if (Version != 14) throw std::string("Unknown revision 0 flags?");
522 HasImplicitZeroInitializer = false;
523 Endianness = Module::BigEndian;
524 PointerSize = Module::Pointer64;
525 hasInternalMarkerOnly = true;
526 hasNoEndianness = hasNoPointerSize = false;
529 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
530 // hasNoEndianness, and hasNoPointerSize.
531 hasInternalMarkerOnly = true;
534 // Version #2 added information about all 4 linkage types instead of just
535 // having internal and external.
538 throw std::string("Unknown bytecode version number!");
541 if (hasNoEndianness) Endianness = Module::AnyEndianness;
542 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
544 TheModule->setEndianness(Endianness);
545 TheModule->setPointerSize(PointerSize);
546 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
547 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
548 << PointerSize << "\n");
549 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
552 void BytecodeParser::ParseModule(const unsigned char *Buf,
553 const unsigned char *EndBuf) {
555 readBlock(Buf, EndBuf, Type, Size);
556 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
557 throw std::string("Expected Module packet! B: "+
558 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
559 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
561 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
562 FunctionSignatureList.clear(); // Just in case...
564 // Read into instance variables...
565 ParseVersionInfo(Buf, EndBuf);
566 ALIGN32(Buf, EndBuf);
568 while (Buf < EndBuf) {
569 const unsigned char *OldBuf = Buf;
570 readBlock(Buf, EndBuf, Type, Size);
572 case BytecodeFormat::GlobalTypePlane:
573 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
574 ParseGlobalTypes(Buf, Buf+Size);
577 case BytecodeFormat::ModuleGlobalInfo:
578 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
579 ParseModuleGlobalInfo(Buf, Buf+Size);
582 case BytecodeFormat::ConstantPool:
583 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
584 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
587 case BytecodeFormat::Function: {
588 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
589 ParseFunction(Buf, Buf+Size);
593 case BytecodeFormat::SymbolTable:
594 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
595 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable());
600 if (OldBuf > Buf) throw std::string("Expected Module Block!");
603 BCR_TRACE(1, "} end block\n");
604 ALIGN32(Buf, EndBuf);
607 // After the module constant pool has been read, we can safely initialize
608 // global variables...
609 while (!GlobalInits.empty()) {
610 GlobalVariable *GV = GlobalInits.back().first;
611 unsigned Slot = GlobalInits.back().second;
612 GlobalInits.pop_back();
614 // Look up the initializer value...
615 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
616 if (GV->hasInitializer())
617 throw std::string("Global *already* has an initializer?!");
618 GV->setInitializer(cast<Constant>(V));
620 throw std::string("Cannot find initializer value.");
623 if (!FunctionSignatureList.empty())
624 throw std::string("Function expected, but bytecode stream ended!");
626 BCR_TRACE(0, "} end block\n\n");
630 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
631 const std::string &ModuleID) {
633 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
635 // Read and check signature...
637 if (read(Buf, EndBuf, Sig) ||
638 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
639 throw std::string("Invalid bytecode signature!");
641 TheModule = new Module(ModuleID);
643 ParseModule(Buf, EndBuf);
644 } catch (std::string &Error) {
645 freeState(); // Must destroy handles before deleting module!