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: Make error message outputs be configurable depending on an option?
9 // TODO: Allow passing in an option to ignore the symbol table
11 //===------------------------------------------------------------------------===
13 #include "llvm/Bytecode/Reader.h"
14 #include "llvm/Bytecode/Format.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/Module.h"
17 #include "llvm/BasicBlock.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/ConstPoolVals.h"
20 #include "llvm/iOther.h"
21 #include "ReaderInternals.h"
22 #include <sys/types.h>
29 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
30 if (Ty->isPrimitiveType()) {
31 Slot = Ty->getPrimitiveID();
33 // Check the method level types first...
34 TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
35 MethodTypeValues.end(), Ty);
36 if (I != MethodTypeValues.end()) {
37 Slot = FirstDerivedTyID+ModuleTypeValues.size()+
38 (&*I - &MethodTypeValues[0]);
40 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
41 if (I == ModuleTypeValues.end()) return true; // Didn't find type!
42 Slot = FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
45 //cerr << "getTypeSlot '" << Ty->getName() << "' = " << Slot << endl;
49 const Type *BytecodeParser::getType(unsigned ID) {
50 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID);
53 //cerr << "Looking up Type ID: " << ID << endl;
55 const Value *D = getValue(Type::TypeTy, ID, false);
56 if (D == 0) return failure<const Type*>(0);
61 int BytecodeParser::insertValue(Value *Val, vector<ValueList> &ValueTab) {
63 if (getTypeSlot(Val->getType(), type)) return failure<int>(-1);
64 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
66 if (ValueTab.size() <= type)
67 ValueTab.resize(type+1, ValueList());
69 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
70 // << "] = " << Val << endl;
71 ValueTab[type].push_back(Val);
73 return ValueTab[type].size()-1;
76 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
78 unsigned type; // The type plane it lives in...
80 if (getTypeSlot(Ty, type)) return failure<Value*>(0); // TODO: true
82 if (type == Type::TypeTyID) { // The 'type' plane has implicit values
83 assert(Create == false);
84 const Type *T = Type::getPrimitiveType((Type::PrimitiveID)Num);
85 if (T) return (Value*)T; // Asked for a primitive type...
87 // Otherwise, derived types need offset...
88 Num -= FirstDerivedTyID;
90 // Is it a module level type?
91 if (Num < ModuleTypeValues.size())
92 return (Value*)ModuleTypeValues[Num].get();
94 // Nope, is it a method level type?
95 Num -= ModuleTypeValues.size();
96 if (Num < MethodTypeValues.size())
97 return (Value*)MethodTypeValues[Num].get();
102 if (type < ModuleValues.size()) {
103 if (Num < ModuleValues[type].size())
104 return ModuleValues[type][Num];
105 Num -= ModuleValues[type].size();
108 if (Values.size() > type && Values[type].size() > Num)
109 return Values[type][Num];
111 if (!Create) return failure<Value*>(0); // Do not create a placeholder?
114 switch (Ty->getPrimitiveID()) {
115 case Type::LabelTyID: d = new BBPHolder(Ty, oNum); break;
116 case Type::MethodTyID:
117 cerr << "Creating method pholder! : " << type << ":" << oNum << " "
118 << Ty->getName() << endl;
119 d = new MethPHolder(Ty, oNum);
120 if (insertValue(d, LateResolveModuleValues) ==-1) return failure<Value*>(0);
122 default: d = new DefPHolder(Ty, oNum); break;
125 assert(d != 0 && "How did we not make something?");
126 if (insertValue(d, LateResolveValues) == -1) return failure<Value*>(0);
130 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
132 for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
133 ValueList &DL = ValTab[ty];
135 while ((Size = DL.size())) {
136 unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
138 Value *D = DL[Size-1];
141 Value *NewDef = getValue(D->getType(), IDNumber, false);
143 Error = true; // Unresolved thinger
144 cerr << "Unresolvable reference found: <"
145 << D->getType()->getDescription() << ">:" << IDNumber << "!\n";
147 // Fixup all of the uses of this placeholder def...
148 D->replaceAllUsesWith(NewDef);
150 // Now that all the uses are gone, delete the placeholder...
151 // If we couldn't find a def (error case), then leak a little
152 delete D; // memory, 'cause otherwise we can't remove all uses!
160 bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
162 BB = new BasicBlock();
164 while (Buf < EndBuf) {
166 if (ParseInstruction(Buf, EndBuf, Inst)) {
168 return failure(true);
171 if (Inst == 0) { delete BB; return failure(true); }
172 if (insertValue(Inst, Values) == -1) { delete BB; return failure(true); }
174 BB->getInstList().push_back(Inst);
182 bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
184 while (Buf < EndBuf) {
185 // Symtab block header: [num entries][type id number]
186 unsigned NumEntries, Typ;
187 if (read_vbr(Buf, EndBuf, NumEntries) ||
188 read_vbr(Buf, EndBuf, Typ)) return failure(true);
189 const Type *Ty = getType(Typ);
190 if (Ty == 0) return failure(true);
192 BCR_TRACE(3, "Plane Type: '" << Ty << "' with " << NumEntries <<
195 for (unsigned i = 0; i < NumEntries; ++i) {
196 // Symtab entry: [def slot #][name]
198 if (read_vbr(Buf, EndBuf, slot)) return failure(true);
200 if (read(Buf, EndBuf, Name, false)) // Not aligned...
201 return failure(true);
203 Value *D = getValue(Ty, slot, false); // Find mapping...
205 BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << endl);
206 return failure(true);
208 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
209 if (!isa<Instruction>(D)) cerr << endl);
211 D->setName(Name, ST);
215 if (Buf > EndBuf) return failure(true);
219 // DeclareNewGlobalValue - Patch up forward references to global values in the
220 // form of ConstPoolPointerReferences.
222 void BytecodeParser::DeclareNewGlobalValue(GlobalValue *GV, unsigned Slot) {
223 // Check to see if there is a forward reference to this global variable...
224 // if there is, eliminate it and patch the reference to use the new def'n.
225 GlobalRefsType::iterator I = GlobalRefs.find(make_pair(GV->getType(), Slot));
227 if (I != GlobalRefs.end()) {
228 GlobalVariable *OldGV = I->second; // Get the placeholder...
229 BCR_TRACE(3, "Mutating CPPR Forward Ref!\n");
231 // Loop over all of the uses of the GlobalValue. The only thing they are
232 // allowed to be at this point is ConstPoolPointerReference's.
233 assert(OldGV->use_size() == 1 && "Only one reference should exist!");
234 while (!OldGV->use_empty()) {
235 User *U = OldGV->use_back(); // Must be a ConstPoolPointerReference...
236 ConstPoolPointerReference *CPPR = cast<ConstPoolPointerReference>(U);
237 assert(CPPR->getValue() == OldGV && "Something isn't happy");
239 BCR_TRACE(4, "Mutating Forward Ref!\n");
241 // Change the const pool reference to point to the real global variable
242 // now. This should drop a use from the OldGV.
243 CPPR->mutateReference(GV);
246 // Remove GV from the module...
247 GV->getParent()->getGlobalList().remove(OldGV);
248 delete OldGV; // Delete the old placeholder
250 // Remove the map entry for the global now that it has been created...
255 bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
257 // Clear out the local values table...
259 if (MethodSignatureList.empty()) return failure(true); // Unexpected method!
261 const PointerType *PMTy = MethodSignatureList.front().first; // PtrMeth
262 const MethodType *MTy = dyn_cast<const MethodType>(PMTy->getValueType());
263 if (MTy == 0) return failure(true); // Not ptr to method!
265 unsigned MethSlot = MethodSignatureList.front().second;
266 MethodSignatureList.pop_front();
267 Method *M = new Method(MTy);
269 BCR_TRACE(2, "METHOD TYPE: " << MTy << endl);
271 const MethodType::ParamTypes &Params = MTy->getParamTypes();
272 for (MethodType::ParamTypes::const_iterator It = Params.begin();
273 It != Params.end(); ++It) {
274 MethodArgument *MA = new MethodArgument(*It);
275 if (insertValue(MA, Values) == -1) { delete M; return failure(true); }
276 M->getArgumentList().push_back(MA);
279 while (Buf < EndBuf) {
281 const uchar *OldBuf = Buf;
282 if (readBlock(Buf, EndBuf, Type, Size)) { delete M; return failure(true); }
285 case BytecodeFormat::ConstantPool:
286 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
287 if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
288 delete M; return failure(true);
292 case BytecodeFormat::BasicBlock: {
293 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
295 if (ParseBasicBlock(Buf, Buf+Size, BB) ||
296 insertValue(BB, Values) == -1) {
297 delete M; return failure(true); // Parse error... :(
300 M->getBasicBlocks().push_back(BB);
304 case BytecodeFormat::SymbolTable:
305 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
306 if (ParseSymbolTable(Buf, Buf+Size, M->getSymbolTableSure())) {
307 delete M; return failure(true);
312 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
314 if (OldBuf > Buf) return failure(true); // Wrap around!
317 BCR_TRACE(2, "} end block\n");
319 if (align32(Buf, EndBuf)) {
320 delete M; // Malformed bc file, read past end of block.
321 return failure(true);
325 if (postResolveValues(LateResolveValues) ||
326 postResolveValues(LateResolveModuleValues)) {
327 delete M; return failure(true); // Unresolvable references!
330 Value *MethPHolder = getValue(PMTy, MethSlot, false);
331 assert(MethPHolder && "Something is broken no placeholder found!");
332 assert(isa<Method>(MethPHolder) && "Not a method?");
334 unsigned type; // Type slot
335 assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
336 getTypeSlot(PMTy, type);
338 C->getMethodList().push_back(M);
340 // Replace placeholder with the real method pointer...
341 ModuleValues[type][MethSlot] = M;
343 // Clear out method level types...
344 MethodTypeValues.clear();
346 // If anyone is using the placeholder make them use the real method instead
347 MethPHolder->replaceAllUsesWith(M);
349 // We don't need the placeholder anymore!
352 DeclareNewGlobalValue(M, MethSlot);
357 bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
359 if (!MethodSignatureList.empty())
360 return failure(true); // Two ModuleGlobal blocks?
362 // Read global variables...
364 if (read_vbr(Buf, End, VarType)) return failure(true);
365 while (VarType != Type::VoidTyID) { // List is terminated by Void
366 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2+ = slot#
367 const Type *Ty = getType(VarType >> 2);
368 if (!Ty || !Ty->isPointerType()) {
369 cerr << "Global not pointer type! Ty = " << Ty << endl;
370 return failure(true);
373 const PointerType *PTy = cast<const PointerType>(Ty);
374 const Type *ElTy = PTy->getValueType();
376 ConstPoolVal *Initializer = 0;
377 if (VarType & 2) { // Does it have an initalizer?
378 // Do not improvise... values must have been stored in the constant pool,
379 // which should have been read before now.
382 if (read_vbr(Buf, End, InitSlot)) return failure(true);
384 Value *V = getValue(ElTy, InitSlot, false);
385 if (V == 0) return failure(true);
386 Initializer = cast<ConstPoolVal>(V);
389 // Create the global variable...
390 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Initializer);
391 int DestSlot = insertValue(GV, ModuleValues);
392 if (DestSlot == -1) return failure(true);
394 Mod->getGlobalList().push_back(GV);
396 DeclareNewGlobalValue(GV, unsigned(DestSlot));
398 BCR_TRACE(2, "Global Variable of type: " << PTy->getDescription()
399 << " into slot #" << DestSlot << endl);
401 if (read_vbr(Buf, End, VarType)) return failure(true);
404 // Read the method signatures for all of the methods that are coming, and
405 // create fillers in the Value tables.
406 unsigned MethSignature;
407 if (read_vbr(Buf, End, MethSignature)) return failure(true);
408 while (MethSignature != Type::VoidTyID) { // List is terminated by Void
409 const Type *Ty = getType(MethSignature);
410 if (!Ty || !isa<PointerType>(Ty) ||
411 !isa<MethodType>(cast<PointerType>(Ty)->getValueType())) {
412 cerr << "Method not ptr to meth type! Ty = " << Ty << endl;
413 return failure(true);
416 // We create methods by passing the underlying MethodType to create...
417 Ty = cast<PointerType>(Ty)->getValueType();
419 // When the ModuleGlobalInfo section is read, we load the type of each
420 // method and the 'ModuleValues' slot that it lands in. We then load a
421 // placeholder into its slot to reserve it. When the method is loaded, this
422 // placeholder is replaced.
424 // Insert the placeholder...
425 Value *Val = new MethPHolder(Ty, 0);
426 if (insertValue(Val, ModuleValues) == -1) return failure(true);
428 // Figure out which entry of its typeslot it went into...
430 if (getTypeSlot(Val->getType(), TypeSlot)) return failure(true);
432 unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
434 // Keep track of this information in a linked list that is emptied as
435 // methods are loaded...
437 MethodSignatureList.push_back(
438 make_pair(cast<const PointerType>(Val->getType()), SlotNo));
439 if (read_vbr(Buf, End, MethSignature)) return failure(true);
440 BCR_TRACE(2, "Method of type: " << Ty << endl);
443 if (align32(Buf, End)) return failure(true);
445 // This is for future proofing... in the future extra fields may be added that
446 // we don't understand, so we transparently ignore them.
452 bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
456 if (readBlock(Buf, EndBuf, Type, Size)) return failure(true);
457 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
458 return failure(true); // Hrm, not a class?
460 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
461 MethodSignatureList.clear(); // Just in case...
463 // Read into instance variables...
464 if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return failure(true);
465 if (align32(Buf, EndBuf)) return failure(true);
466 BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
468 TheModule = C = new Module();
469 while (Buf < EndBuf) {
470 const uchar *OldBuf = Buf;
471 if (readBlock(Buf, EndBuf, Type, Size)) { delete C; return failure(true); }
473 case BytecodeFormat::ConstantPool:
474 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
475 if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
476 delete C; return failure(true);
480 case BytecodeFormat::ModuleGlobalInfo:
481 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
483 if (ParseModuleGlobalInfo(Buf, Buf+Size, C)) {
484 delete C; return failure(true);
488 case BytecodeFormat::Method: {
489 BCR_TRACE(1, "BLOCK BytecodeFormat::Method: {\n");
490 if (ParseMethod(Buf, Buf+Size, C)) {
491 delete C; return failure(true); // Error parsing method
496 case BytecodeFormat::SymbolTable:
497 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
498 if (ParseSymbolTable(Buf, Buf+Size, C->getSymbolTableSure())) {
499 delete C; return failure(true);
504 cerr << " Unknown class block: " << Type << endl;
506 if (OldBuf > Buf) return failure(true); // Wrap around!
509 BCR_TRACE(1, "} end block\n");
510 if (align32(Buf, EndBuf)) { delete C; return failure(true); }
513 if (!MethodSignatureList.empty()) // Expected more methods!
514 return failure(true);
516 BCR_TRACE(0, "} end block\n\n");
520 Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
521 LateResolveValues.clear();
523 // Read and check signature...
524 if (read(Buf, EndBuf, Sig) ||
525 Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
526 return failure<Module*>(0); // Invalid signature!
529 if (ParseModule(Buf, EndBuf, Result)) return 0;
534 Module *ParseBytecodeBuffer(const uchar *Buffer, unsigned Length) {
535 BytecodeParser Parser;
536 return Parser.ParseBytecode(Buffer, Buffer+Length);
539 // Parse and return a class file...
541 Module *ParseBytecodeFile(const string &Filename) {
545 if (Filename != string("-")) { // Read from a file...
546 int FD = open(Filename.c_str(), O_RDONLY);
547 if (FD == -1) return failure<Module*>(0);
549 if (fstat(FD, &StatBuf) == -1) { close(FD); return failure<Module*>(0); }
551 int Length = StatBuf.st_size;
552 if (Length == 0) { close(FD); return failure<Module*>(0); }
553 uchar *Buffer = (uchar*)mmap(0, Length, PROT_READ,
555 if (Buffer == (uchar*)-1) { close(FD); return failure<Module*>(0); }
557 BytecodeParser Parser;
558 Result = Parser.ParseBytecode(Buffer, Buffer+Length);
560 munmap((char*)Buffer, Length);
562 } else { // Read from stdin
565 uchar Buffer[4096], *FileData = 0;
566 while ((BlockSize = read(0, Buffer, 4))) {
567 if (BlockSize == -1) { free(FileData); return failure<Module*>(0); }
569 FileData = (uchar*)realloc(FileData, FileSize+BlockSize);
570 memcpy(FileData+FileSize, Buffer, BlockSize);
571 FileSize += BlockSize;
574 if (FileSize == 0) { free(FileData); return failure<Module*>(0); }
578 uchar *Buf = (uchar*)mmap(0, FileSize, PROT_READ|PROT_WRITE,
579 MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
580 assert((Buf != (uchar*)-1) && "mmap returned error!");
582 memcpy(Buf, FileData, FileSize);
584 uchar *Buf = FileData;
587 BytecodeParser Parser;
588 Result = Parser.ParseBytecode(Buf, Buf+FileSize);
591 munmap((char*)Buf, FileSize); // Free mmap'd data area
593 free(FileData); // Free realloc'd block of memory