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";
59 if (ID < Type::NumPrimitiveIDs) {
60 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
61 if (T) return T; // Asked for a primitive type...
64 // Otherwise, derived types need offset...
65 ID -= FirstDerivedTyID;
67 // Is it a module-level type?
68 if (ID < ModuleTypeValues.size())
69 return ModuleTypeValues[ID].get();
71 // Nope, is it a function-level type?
72 ID -= ModuleTypeValues.size();
73 if (ID < FunctionTypeValues.size())
74 return FunctionTypeValues[ID].get();
79 int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
80 assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
81 Val->getType()->isPrimitiveType() ||
82 !cast<Constant>(Val)->isNullValue()) &&
83 "Cannot read null values from bytecode!");
84 unsigned type = getTypeSlot(Val->getType());
85 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
87 if (ValueTab.size() <= type) {
88 unsigned OldSize = ValueTab.size();
89 ValueTab.resize(type+1);
90 while (OldSize != type+1)
91 ValueTab[OldSize++] = new ValueList();
94 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
95 // << "] = " << Val << "\n";
96 ValueTab[type]->push_back(Val);
98 bool HasOffset = HasImplicitZeroInitializer &&
99 !Val->getType()->isPrimitiveType();
101 return ValueTab[type]->size()-1 + HasOffset;
105 void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
107 assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
108 assert((!HasImplicitZeroInitializer || Slot != 0) &&
109 "Cannot change zero init");
110 unsigned type = getTypeSlot(Val->getType());
111 assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
112 ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
116 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
117 return getValue(getTypeSlot(Ty), oNum, Create);
120 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
121 assert(type != Type::TypeTyID && "getValue() cannot get types!");
124 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
126 return Constant::getNullValue(getType(type));
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?
141 const Type *Ty = getType(type);
142 Value *Val = type == Type::LabelTyID ? (Value*)new BBPHolder(Ty, oNum) :
143 (Value*)new ValPHolder(Ty, oNum);
145 assert(Val != 0 && "How did we not make something?");
146 if (insertValue(Val, LateResolveValues) == -1) return 0;
150 /// getConstantValue - Just like getValue, except that it returns a null pointer
151 /// only on error. It always returns a constant (meaning that if the value is
152 /// defined, but is not a constant, that is an error). If the specified
153 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
154 /// after the real value is parsed, the placeholder is eliminated.
156 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
157 if (Value *V = getValue(Ty, Slot, false))
158 return dyn_cast<Constant>(V); // If we already have the value parsed...
160 std::pair<const Type*, unsigned> Key(Ty, Slot);
161 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
163 if (I != GlobalRefs.end() && I->first == Key) {
164 BCR_TRACE(5, "Previous forward ref found!\n");
165 return cast<Constant>(I->second);
167 // Create a placeholder for the constant reference and
168 // keep track of the fact that we have a forward ref to recycle it
169 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
170 Constant *C = new ConstPHolder(Ty, Slot);
172 // Keep track of the fact that we have a forward ref to recycle it
173 GlobalRefs.insert(I, std::make_pair(Key, C));
179 std::auto_ptr<BasicBlock>
180 BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
181 const unsigned char *EndBuf) {
182 std::auto_ptr<BasicBlock> BB(new BasicBlock());
184 while (Buf < EndBuf) {
186 ParseInstruction(Buf, EndBuf, Inst);
188 if (Inst == 0) { throw std::string("Could not parse Instruction."); }
189 if (insertValue(Inst, Values) == -1) {
190 throw std::string("Could not insert value.");
193 BB->getInstList().push_back(Inst);
200 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
201 const unsigned char *EndBuf,
203 while (Buf < EndBuf) {
204 // Symtab block header: [num entries][type id number]
205 unsigned NumEntries, Typ;
206 if (read_vbr(Buf, EndBuf, NumEntries) ||
207 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
208 const Type *Ty = getType(Typ);
209 if (Ty == 0) throw std::string("Invalid type read in symbol table.");
211 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
214 for (unsigned i = 0; i < NumEntries; ++i) {
215 // Symtab entry: [def slot #][name]
217 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
219 if (read(Buf, EndBuf, Name, false)) // Not aligned...
220 throw std::string("Buffer not aligned.");
223 if (Typ == Type::TypeTyID)
224 V = (Value*)getType(slot);
226 V = getValue(Typ, slot, false); // Find mapping...
227 if (V == 0) throw std::string("Failed value look-up.");
228 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
229 if (!isa<Instruction>(V)) std::cerr << "\n");
231 V->setName(Name, ST);
235 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
238 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
239 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
241 if (I == GlobalRefs.end()) return; // Never forward referenced?
243 BCR_TRACE(3, "Mutating forward refs!\n");
244 Value *VPH = I->second; // Get the placeholder...
246 VPH->replaceAllUsesWith(NewV);
248 // If this is a global variable being resolved, remove the placeholder from
250 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
251 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
253 delete VPH; // Delete the old placeholder
254 GlobalRefs.erase(I); // Remove the map entry for it
258 BytecodeParser::ParseFunction(const unsigned char *&Buf,
259 const unsigned char *EndBuf) {
260 if (FunctionSignatureList.empty())
261 throw std::string("FunctionSignatureList empty!");
263 Function *F = FunctionSignatureList.back().first;
264 unsigned FunctionSlot = FunctionSignatureList.back().second;
265 FunctionSignatureList.pop_back();
267 // Save the information for future reading of the function
268 LazyFunctionInfo *LFI = new LazyFunctionInfo();
269 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
270 LazyFunctionLoadMap[F] = LFI;
271 // Pretend we've `parsed' this function
275 void BytecodeParser::materializeFunction(Function* F) {
276 // Find {start, end} pointers and slot in the map. If not there, we're done.
277 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
278 LazyFunctionLoadMap.find(F);
279 if (Fi == LazyFunctionLoadMap.end()) return;
281 LazyFunctionInfo *LFI = Fi->second;
282 const unsigned char *Buf = LFI->Buf;
283 const unsigned char *EndBuf = LFI->EndBuf;
284 unsigned FunctionSlot = LFI->FunctionSlot;
285 LazyFunctionLoadMap.erase(Fi);
288 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
290 if (!hasInternalMarkerOnly) {
291 unsigned LinkageType;
292 if (read_vbr(Buf, EndBuf, LinkageType))
293 throw std::string("ParseFunction: Error reading from buffer.");
294 if (LinkageType & ~0x3)
295 throw std::string("Invalid linkage type for Function.");
296 Linkage = (GlobalValue::LinkageTypes)LinkageType;
298 // We used to only support two linkage models: internal and external
300 if (read_vbr(Buf, EndBuf, isInternal))
301 throw std::string("ParseFunction: Error reading from buffer.");
302 if (isInternal) Linkage = GlobalValue::InternalLinkage;
305 F->setLinkage(Linkage);
307 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
308 Function::aiterator AI = F->abegin();
309 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
310 It != Params.end(); ++It, ++AI) {
311 if (insertValue(AI, Values) == -1)
312 throw std::string("Error reading function arguments!");
315 while (Buf < EndBuf) {
317 const unsigned char *OldBuf = Buf;
318 readBlock(Buf, EndBuf, Type, Size);
321 case BytecodeFormat::ConstantPool: {
322 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
323 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
327 case BytecodeFormat::BasicBlock: {
328 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
329 std::auto_ptr<BasicBlock> BB = ParseBasicBlock(Buf, Buf+Size);
330 if (!BB.get() || insertValue(BB.get(), Values) == -1)
331 throw std::string("Parse error: BasicBlock");
333 F->getBasicBlockList().push_back(BB.release());
337 case BytecodeFormat::SymbolTable: {
338 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
339 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable());
344 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
347 throw std::string("Wrapped around reading bytecode.");
350 BCR_TRACE(2, "} end block\n");
352 // Malformed bc file if read past end of block.
353 ALIGN32(Buf, EndBuf);
356 // Check for unresolvable references
357 while (!LateResolveValues.empty()) {
358 ValueList &VL = *LateResolveValues.back();
359 LateResolveValues.pop_back();
361 while (!VL.empty()) {
362 Value *V = VL.back();
363 unsigned IDNumber = getValueIDNumberFromPlaceHolder(V);
366 Value *NewVal = getValue(V->getType(), IDNumber, false);
368 throw std::string("Unresolvable reference found: <" +
369 V->getType()->getDescription() + ">:" +
370 utostr(IDNumber) + ".");
372 // Fixup all of the uses of this placeholder def...
373 V->replaceAllUsesWith(NewVal);
375 // Now that all the uses are gone, delete the placeholder...
376 // If we couldn't find a def (error case), then leak a little
377 // memory, because otherwise we can't remove all uses!
383 // Clear out function-level types...
384 FunctionTypeValues.clear();
389 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
390 const unsigned char *End) {
391 if (!FunctionSignatureList.empty())
392 throw std::string("Two ModuleGlobalInfo packets found!");
394 // Read global variables...
396 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
397 while (VarType != Type::VoidTyID) { // List is terminated by Void
399 GlobalValue::LinkageTypes Linkage;
401 if (!hasInternalMarkerOnly) {
402 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
403 // bit2,3 = Linkage, bit4+ = slot#
404 SlotNo = VarType >> 4;
405 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
407 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
408 // bit2 = isInternal, bit3+ = slot#
409 SlotNo = VarType >> 3;
410 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
411 GlobalValue::ExternalLinkage;
414 const Type *Ty = getType(SlotNo);
415 if (!Ty || !isa<PointerType>(Ty))
416 throw std::string("Global not pointer type! Ty = " +
417 Ty->getDescription());
419 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
421 // Create the global variable...
422 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
424 int DestSlot = insertValue(GV, ModuleValues);
425 if (DestSlot == -1) throw Error_DestSlot;
426 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
427 ResolveReferencesToValue(GV, (unsigned)DestSlot);
429 if (VarType & 2) { // Does it have an initializer?
431 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
432 GlobalInits.push_back(std::make_pair(GV, InitSlot));
434 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
437 // Read the function objects for all of the functions that are coming
438 unsigned FnSignature;
439 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
440 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
441 const Type *Ty = getType(FnSignature);
442 if (!Ty || !isa<PointerType>(Ty) ||
443 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
444 throw std::string("Function not ptr to func type! Ty = " +
445 Ty->getDescription());
448 // We create functions by passing the underlying FunctionType to create...
449 Ty = cast<PointerType>(Ty)->getElementType();
451 // When the ModuleGlobalInfo section is read, we load the type of each
452 // function and the 'ModuleValues' slot that it lands in. We then load a
453 // placeholder into its slot to reserve it. When the function is loaded,
454 // this placeholder is replaced.
456 // Insert the placeholder...
457 Function *Func = new Function(cast<FunctionType>(Ty),
458 GlobalValue::InternalLinkage, "", TheModule);
459 int DestSlot = insertValue(Func, ModuleValues);
460 if (DestSlot == -1) throw Error_DestSlot;
461 ResolveReferencesToValue(Func, (unsigned)DestSlot);
463 // Keep track of this information in a list that is emptied as functions are
466 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
468 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
469 BCR_TRACE(2, "Function of type: " << Ty << "\n");
474 // Now that the function signature list is set up, reverse it so that we can
475 // remove elements efficiently from the back of the vector.
476 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
478 // This is for future proofing... in the future extra fields may be added that
479 // we don't understand, so we transparently ignore them.
484 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
485 const unsigned char *EndBuf) {
487 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
489 // Unpack version number: low four bits are for flags, top bits = version
490 Module::Endianness Endianness;
491 Module::PointerSize PointerSize;
492 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
493 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
495 bool hasNoEndianness = Version & 4;
496 bool hasNoPointerSize = Version & 8;
498 RevisionNum = Version >> 4;
500 // Default values for the current bytecode version
501 HasImplicitZeroInitializer = true;
502 hasInternalMarkerOnly = false;
503 FirstDerivedTyID = 14;
505 switch (RevisionNum) {
506 case 0: // Initial revision
507 // Version #0 didn't have any of the flags stored correctly, and in fact as
508 // only valid with a 14 in the flags values. Also, it does not support
509 // encoding zero initializers for arrays compactly.
511 if (Version != 14) throw std::string("Unknown revision 0 flags?");
512 HasImplicitZeroInitializer = false;
513 Endianness = Module::BigEndian;
514 PointerSize = Module::Pointer64;
515 hasInternalMarkerOnly = true;
516 hasNoEndianness = hasNoPointerSize = false;
519 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
520 // hasNoEndianness, and hasNoPointerSize.
521 hasInternalMarkerOnly = true;
524 // Version #2 added information about all 4 linkage types instead of just
525 // having internal and external.
528 throw std::string("Unknown bytecode version number!");
531 if (hasNoEndianness) Endianness = Module::AnyEndianness;
532 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
534 TheModule->setEndianness(Endianness);
535 TheModule->setPointerSize(PointerSize);
536 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
537 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
538 << PointerSize << "\n");
539 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
542 void BytecodeParser::ParseModule(const unsigned char *Buf,
543 const unsigned char *EndBuf) {
545 readBlock(Buf, EndBuf, Type, Size);
546 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
547 throw std::string("Expected Module packet! B: "+
548 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
549 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
551 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
552 FunctionSignatureList.clear(); // Just in case...
554 // Read into instance variables...
555 ParseVersionInfo(Buf, EndBuf);
556 ALIGN32(Buf, EndBuf);
558 while (Buf < EndBuf) {
559 const unsigned char *OldBuf = Buf;
560 readBlock(Buf, EndBuf, Type, Size);
562 case BytecodeFormat::GlobalTypePlane:
563 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
564 ParseGlobalTypes(Buf, Buf+Size);
567 case BytecodeFormat::ModuleGlobalInfo:
568 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
569 ParseModuleGlobalInfo(Buf, Buf+Size);
572 case BytecodeFormat::ConstantPool:
573 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
574 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
577 case BytecodeFormat::Function: {
578 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
579 ParseFunction(Buf, Buf+Size);
583 case BytecodeFormat::SymbolTable:
584 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
585 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable());
590 if (OldBuf > Buf) throw std::string("Expected Module Block!");
593 BCR_TRACE(1, "} end block\n");
594 ALIGN32(Buf, EndBuf);
597 // After the module constant pool has been read, we can safely initialize
598 // global variables...
599 while (!GlobalInits.empty()) {
600 GlobalVariable *GV = GlobalInits.back().first;
601 unsigned Slot = GlobalInits.back().second;
602 GlobalInits.pop_back();
604 // Look up the initializer value...
605 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
606 if (GV->hasInitializer())
607 throw std::string("Global *already* has an initializer?!");
608 GV->setInitializer(cast<Constant>(V));
610 throw std::string("Cannot find initializer value.");
613 if (!FunctionSignatureList.empty())
614 throw std::string("Function expected, but bytecode stream ended!");
616 BCR_TRACE(0, "} end block\n\n");
620 BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
621 const std::string &ModuleID) {
623 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
625 // Read and check signature...
627 if (read(Buf, EndBuf, Sig) ||
628 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
629 throw std::string("Invalid bytecode signature!");
631 TheModule = new Module(ModuleID);
633 ParseModule(Buf, EndBuf);
634 } catch (std::string &Error) {
635 freeState(); // Must destroy handles before deleting module!