blob: bf2b0118a3556426b7bc35f6f7069b12433b5fc4 [file] [log] [blame]
Chris Lattnerd6b65252001-10-24 01:15:12 +00001//===- Reader.cpp - Code to read bytecode files ---------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00002//
3// This library implements the functionality defined in llvm/Bytecode/Reader.h
4//
5// Note that this library should be as fast as possible, reentrant, and
6// threadsafe!!
7//
Chris Lattner74734132002-08-17 22:01:27 +00008// TODO: Return error messages to caller instead of printing them out directly.
Chris Lattner00950542001-06-06 20:29:01 +00009// TODO: Allow passing in an option to ignore the symbol table
10//
Chris Lattnerd6b65252001-10-24 01:15:12 +000011//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000012
Chris Lattner7061dc52001-12-03 18:02:31 +000013#include "ReaderInternals.h"
Chris Lattner00950542001-06-06 20:29:01 +000014#include "llvm/Bytecode/Reader.h"
15#include "llvm/Bytecode/Format.h"
Chris Lattner31bcdb82002-04-28 19:55:58 +000016#include "llvm/Constants.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000017#include "llvm/iPHINode.h"
Chris Lattner00950542001-06-06 20:29:01 +000018#include "llvm/iOther.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000019#include "llvm/Module.h"
20#include "Support/StringExtras.h"
John Criswell7a73b802003-06-30 21:59:07 +000021#include "Config/unistd.h"
Misha Brukman12c29d12003-09-22 23:38:23 +000022#include "Config/sys/mman.h"
23#include "Config/sys/stat.h"
24#include "Config/sys/types.h"
Chris Lattner00950542001-06-06 20:29:01 +000025#include <algorithm>
Misha Brukman12c29d12003-09-22 23:38:23 +000026#include <memory>
Chris Lattner00950542001-06-06 20:29:01 +000027
Misha Brukmane0dd0d42003-09-23 16:15:29 +000028static 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.");
32}
Misha Brukman12c29d12003-09-22 23:38:23 +000033
Chris Lattner9e460f22003-10-04 20:00:03 +000034unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
35 if (Ty->isPrimitiveType())
36 return Ty->getPrimitiveID();
37
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]);
44
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]);
Chris Lattner00950542001-06-06 20:29:01 +000049}
50
51const Type *BytecodeParser::getType(unsigned ID) {
Chris Lattner927b1852003-10-09 20:22:47 +000052 if (ID < Type::NumPrimitiveIDs)
53 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
54 return T;
Chris Lattner00950542001-06-06 20:29:01 +000055
Chris Lattner697954c2002-01-20 22:54:45 +000056 //cerr << "Looking up Type ID: " << ID << "\n";
Chris Lattner36392bc2003-10-08 21:18:57 +000057
Chris Lattner927b1852003-10-09 20:22:47 +000058 if (ID < Type::NumPrimitiveIDs)
59 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
60 return T; // Asked for a primitive type...
Chris Lattner36392bc2003-10-08 21:18:57 +000061
62 // Otherwise, derived types need offset...
63 ID -= FirstDerivedTyID;
64
65 // Is it a module-level type?
66 if (ID < ModuleTypeValues.size())
67 return ModuleTypeValues[ID].get();
68
69 // Nope, is it a function-level type?
70 ID -= ModuleTypeValues.size();
71 if (ID < FunctionTypeValues.size())
72 return FunctionTypeValues[ID].get();
73
Chris Lattner927b1852003-10-09 20:22:47 +000074 throw std::string("Illegal type reference!");
Chris Lattner00950542001-06-06 20:29:01 +000075}
76
Chris Lattner927b1852003-10-09 20:22:47 +000077unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
Chris Lattner52e20b02003-03-19 20:54:26 +000078 assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
79 Val->getType()->isPrimitiveType() ||
80 !cast<Constant>(Val)->isNullValue()) &&
81 "Cannot read null values from bytecode!");
Chris Lattner9e460f22003-10-04 20:00:03 +000082 unsigned type = getTypeSlot(Val->getType());
Chris Lattner1d670cc2001-09-07 16:37:43 +000083 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
Chris Lattner00950542001-06-06 20:29:01 +000084
Chris Lattner52e20b02003-03-19 20:54:26 +000085 if (ValueTab.size() <= type) {
86 unsigned OldSize = ValueTab.size();
87 ValueTab.resize(type+1);
88 while (OldSize != type+1)
89 ValueTab[OldSize++] = new ValueList();
Chris Lattner036b8aa2003-03-06 17:55:45 +000090 }
Chris Lattner00950542001-06-06 20:29:01 +000091
92 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
Misha Brukman12c29d12003-09-22 23:38:23 +000093 // << "] = " << Val << "\n";
Chris Lattner52e20b02003-03-19 20:54:26 +000094 ValueTab[type]->push_back(Val);
Chris Lattner00950542001-06-06 20:29:01 +000095
Chris Lattner52e20b02003-03-19 20:54:26 +000096 bool HasOffset = HasImplicitZeroInitializer &&
Misha Brukman12c29d12003-09-22 23:38:23 +000097 !Val->getType()->isPrimitiveType();
Chris Lattner52e20b02003-03-19 20:54:26 +000098
99 return ValueTab[type]->size()-1 + HasOffset;
100}
101
102
Chris Lattner00950542001-06-06 20:29:01 +0000103Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
Chris Lattner36392bc2003-10-08 21:18:57 +0000104 return getValue(getTypeSlot(Ty), oNum, Create);
105}
106
107Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
108 assert(type != Type::TypeTyID && "getValue() cannot get types!");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000109 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
Chris Lattner00950542001-06-06 20:29:01 +0000110 unsigned Num = oNum;
Chris Lattner00950542001-06-06 20:29:01 +0000111
Chris Lattner52e20b02003-03-19 20:54:26 +0000112 if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
113 if (Num == 0)
Chris Lattner36392bc2003-10-08 21:18:57 +0000114 return Constant::getNullValue(getType(type));
Chris Lattner52e20b02003-03-19 20:54:26 +0000115 --Num;
Chris Lattner00950542001-06-06 20:29:01 +0000116 }
117
Chris Lattner52e20b02003-03-19 20:54:26 +0000118 if (type < ModuleValues.size()) {
119 if (Num < ModuleValues[type]->size())
120 return ModuleValues[type]->getOperand(Num);
121 Num -= ModuleValues[type]->size();
122 }
123
124 if (Values.size() > type && Values[type]->size() > Num)
125 return Values[type]->getOperand(Num);
Chris Lattner00950542001-06-06 20:29:01 +0000126
Chris Lattner74734132002-08-17 22:01:27 +0000127 if (!Create) return 0; // Do not create a placeholder?
Chris Lattner00950542001-06-06 20:29:01 +0000128
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000129 std::pair<unsigned,unsigned> KeyValue(type, oNum);
130 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
131 ForwardReferences.lower_bound(KeyValue);
132 if (I != ForwardReferences.end() && I->first == KeyValue)
133 return I->second; // We have already created this placeholder
134
Chris Lattnerbf43ac62003-10-09 06:14:26 +0000135 Value *Val = new Argument(getType(type));
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000136 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
Chris Lattner36392bc2003-10-08 21:18:57 +0000137 return Val;
Chris Lattner00950542001-06-06 20:29:01 +0000138}
139
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000140/// getBasicBlock - Get a particular numbered basic block, which might be a
141/// forward reference. This works together with ParseBasicBlock to handle these
142/// forward references in a clean manner.
143///
144BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
145 // Make sure there is room in the table...
146 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
147
148 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
149 // has already created this block, or if the forward reference has already
150 // been created.
151 if (ParsedBasicBlocks[ID])
152 return ParsedBasicBlocks[ID];
153
154 // Otherwise, the basic block has not yet been created. Do so and add it to
155 // the ParsedBasicBlocks list.
156 return ParsedBasicBlocks[ID] = new BasicBlock();
157}
158
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000159/// getConstantValue - Just like getValue, except that it returns a null pointer
160/// only on error. It always returns a constant (meaning that if the value is
161/// defined, but is not a constant, that is an error). If the specified
162/// constant hasn't been parsed yet, a placeholder is defined and used. Later,
163/// after the real value is parsed, the placeholder is eliminated.
164///
165Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
166 if (Value *V = getValue(Ty, Slot, false))
Chris Lattnerc9456ca2003-10-09 20:41:16 +0000167 if (Constant *C = dyn_cast<Constant>(V))
168 return C; // If we already have the value parsed, just return it
169 else
170 throw std::string("Reference of a value is expected to be a constant!");
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000171
Chris Lattner52e20b02003-03-19 20:54:26 +0000172 std::pair<const Type*, unsigned> Key(Ty, Slot);
173 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
174
175 if (I != GlobalRefs.end() && I->first == Key) {
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000176 BCR_TRACE(5, "Previous forward ref found!\n");
177 return cast<Constant>(I->second);
178 } else {
179 // Create a placeholder for the constant reference and
180 // keep track of the fact that we have a forward ref to recycle it
181 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
182 Constant *C = new ConstPHolder(Ty, Slot);
183
184 // Keep track of the fact that we have a forward ref to recycle it
Chris Lattner52e20b02003-03-19 20:54:26 +0000185 GlobalRefs.insert(I, std::make_pair(Key, C));
Chris Lattnerbbd4b302002-10-14 03:33:02 +0000186 return C;
187 }
188}
189
190
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000191BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
192 const unsigned char *EndBuf,
193 unsigned BlockNo) {
194 BasicBlock *BB;
195 if (ParsedBasicBlocks.size() == BlockNo)
196 ParsedBasicBlocks.push_back(BB = new BasicBlock());
197 else if (ParsedBasicBlocks[BlockNo] == 0)
198 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
199 else
200 BB = ParsedBasicBlocks[BlockNo];
Chris Lattner00950542001-06-06 20:29:01 +0000201
202 while (Buf < EndBuf) {
Chris Lattner3483f542003-10-09 18:25:19 +0000203 Instruction *Inst = ParseInstruction(Buf, EndBuf);
Chris Lattner927b1852003-10-09 20:22:47 +0000204 insertValue(Inst, Values);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000205 BB->getInstList().push_back(Inst);
Chris Lattner1d670cc2001-09-07 16:37:43 +0000206 BCR_TRACE(4, Inst);
Chris Lattner00950542001-06-06 20:29:01 +0000207 }
208
Misha Brukman12c29d12003-09-22 23:38:23 +0000209 return BB;
Chris Lattner00950542001-06-06 20:29:01 +0000210}
211
Misha Brukman12c29d12003-09-22 23:38:23 +0000212void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000213 const unsigned char *EndBuf,
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000214 SymbolTable *ST,
215 Function *CurrentFunction) {
Chris Lattner00950542001-06-06 20:29:01 +0000216 while (Buf < EndBuf) {
217 // Symtab block header: [num entries][type id number]
218 unsigned NumEntries, Typ;
219 if (read_vbr(Buf, EndBuf, NumEntries) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000220 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
Chris Lattner00950542001-06-06 20:29:01 +0000221 const Type *Ty = getType(Typ);
Chris Lattner927b1852003-10-09 20:22:47 +0000222 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
Misha Brukman12c29d12003-09-22 23:38:23 +0000223 " entries\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000224
Chris Lattner90736132003-10-09 20:30:04 +0000225 Function::iterator BlockIterator;
226 unsigned CurBlockIteratorIdx = ~0;
227
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000228 for (unsigned i = 0; i < NumEntries; ++i) {
Chris Lattner00950542001-06-06 20:29:01 +0000229 // Symtab entry: [def slot #][name]
230 unsigned slot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000231 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
Chris Lattner697954c2002-01-20 22:54:45 +0000232 std::string Name;
Chris Lattner00950542001-06-06 20:29:01 +0000233 if (read(Buf, EndBuf, Name, false)) // Not aligned...
Misha Brukman12c29d12003-09-22 23:38:23 +0000234 throw std::string("Buffer not aligned.");
Chris Lattner00950542001-06-06 20:29:01 +0000235
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000236 Value *V = 0;
Chris Lattner36392bc2003-10-08 21:18:57 +0000237 if (Typ == Type::TypeTyID)
238 V = (Value*)getType(slot);
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000239 else if (Typ == Type::LabelTyID) {
Chris Lattner90736132003-10-09 20:30:04 +0000240 if (!CurrentFunction)
241 throw std::string("Basic blocks don't exist at global scope!");
242
243 if (slot < CurBlockIteratorIdx) {
244 CurBlockIteratorIdx = 0;
245 BlockIterator = CurrentFunction->begin();
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000246 }
Chris Lattner90736132003-10-09 20:30:04 +0000247
248 std::advance(BlockIterator, slot-CurBlockIteratorIdx);
249 CurBlockIteratorIdx = slot;
250 V = BlockIterator;
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000251 } else
Chris Lattner36392bc2003-10-08 21:18:57 +0000252 V = getValue(Typ, slot, false); // Find mapping...
253 if (V == 0) throw std::string("Failed value look-up.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000254 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
Misha Brukman12c29d12003-09-22 23:38:23 +0000255 if (!isa<Instruction>(V)) std::cerr << "\n");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000256
Chris Lattner52e20b02003-03-19 20:54:26 +0000257 V->setName(Name, ST);
Chris Lattner00950542001-06-06 20:29:01 +0000258 }
259 }
260
Misha Brukman12c29d12003-09-22 23:38:23 +0000261 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
Chris Lattner00950542001-06-06 20:29:01 +0000262}
263
Chris Lattner74734132002-08-17 22:01:27 +0000264void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
Chris Lattner0d75d8d72003-03-06 16:32:25 +0000265 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
266 Slot));
Chris Lattner74734132002-08-17 22:01:27 +0000267 if (I == GlobalRefs.end()) return; // Never forward referenced?
Chris Lattner00950542001-06-06 20:29:01 +0000268
Chris Lattner74734132002-08-17 22:01:27 +0000269 BCR_TRACE(3, "Mutating forward refs!\n");
270 Value *VPH = I->second; // Get the placeholder...
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000271
Chris Lattner52e20b02003-03-19 20:54:26 +0000272 VPH->replaceAllUsesWith(NewV);
273
274 // If this is a global variable being resolved, remove the placeholder from
275 // the module...
276 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
277 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000278
Chris Lattner74734132002-08-17 22:01:27 +0000279 delete VPH; // Delete the old placeholder
280 GlobalRefs.erase(I); // Remove the map entry for it
Vikram S. Advec1e4a812002-07-14 23:04:18 +0000281}
282
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000283void BytecodeParser::ParseFunction(const unsigned char *&Buf,
284 const unsigned char *EndBuf) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000285 if (FunctionSignatureList.empty())
286 throw std::string("FunctionSignatureList empty!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000287
Misha Brukman12c29d12003-09-22 23:38:23 +0000288 Function *F = FunctionSignatureList.back().first;
289 unsigned FunctionSlot = FunctionSignatureList.back().second;
290 FunctionSignatureList.pop_back();
291
292 // Save the information for future reading of the function
293 LazyFunctionInfo *LFI = new LazyFunctionInfo();
294 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
295 LazyFunctionLoadMap[F] = LFI;
296 // Pretend we've `parsed' this function
297 Buf = EndBuf;
298}
299
300void BytecodeParser::materializeFunction(Function* F) {
301 // Find {start, end} pointers and slot in the map. If not there, we're done.
302 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
303 LazyFunctionLoadMap.find(F);
304 if (Fi == LazyFunctionLoadMap.end()) return;
305
306 LazyFunctionInfo *LFI = Fi->second;
307 const unsigned char *Buf = LFI->Buf;
308 const unsigned char *EndBuf = LFI->EndBuf;
309 unsigned FunctionSlot = LFI->FunctionSlot;
310 LazyFunctionLoadMap.erase(Fi);
311 delete LFI;
Chris Lattner00950542001-06-06 20:29:01 +0000312
Chris Lattnere3869c82003-04-16 21:16:05 +0000313 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
314
315 if (!hasInternalMarkerOnly) {
316 unsigned LinkageType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000317 if (read_vbr(Buf, EndBuf, LinkageType))
318 throw std::string("ParseFunction: Error reading from buffer.");
319 if (LinkageType & ~0x3)
320 throw std::string("Invalid linkage type for Function.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000321 Linkage = (GlobalValue::LinkageTypes)LinkageType;
322 } else {
323 // We used to only support two linkage models: internal and external
324 unsigned isInternal;
Misha Brukman12c29d12003-09-22 23:38:23 +0000325 if (read_vbr(Buf, EndBuf, isInternal))
326 throw std::string("ParseFunction: Error reading from buffer.");
Chris Lattnere3869c82003-04-16 21:16:05 +0000327 if (isInternal) Linkage = GlobalValue::InternalLinkage;
328 }
Chris Lattnerd23b1d32001-11-26 18:56:10 +0000329
Chris Lattnere3869c82003-04-16 21:16:05 +0000330 F->setLinkage(Linkage);
Chris Lattner00950542001-06-06 20:29:01 +0000331
Chris Lattner52e20b02003-03-19 20:54:26 +0000332 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
333 Function::aiterator AI = F->abegin();
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000334 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
Chris Lattner927b1852003-10-09 20:22:47 +0000335 It != Params.end(); ++It, ++AI)
336 insertValue(AI, Values);
Chris Lattner00950542001-06-06 20:29:01 +0000337
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000338 // Keep track of how many basic blocks we have read in...
339 unsigned BlockNum = 0;
340
Chris Lattner00950542001-06-06 20:29:01 +0000341 while (Buf < EndBuf) {
342 unsigned Type, Size;
Chris Lattnerb6c46952003-03-06 17:03:28 +0000343 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000344 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000345
346 switch (Type) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000347 case BytecodeFormat::ConstantPool: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000348 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000349 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000350 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000351 }
Chris Lattner00950542001-06-06 20:29:01 +0000352
353 case BytecodeFormat::BasicBlock: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000354 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000355 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
356 F->getBasicBlockList().push_back(BB);
Chris Lattner00950542001-06-06 20:29:01 +0000357 break;
358 }
359
Misha Brukman12c29d12003-09-22 23:38:23 +0000360 case BytecodeFormat::SymbolTable: {
Chris Lattner1d670cc2001-09-07 16:37:43 +0000361 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000362 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
Chris Lattner00950542001-06-06 20:29:01 +0000363 break;
Misha Brukman12c29d12003-09-22 23:38:23 +0000364 }
Chris Lattner00950542001-06-06 20:29:01 +0000365
366 default:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000367 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
Chris Lattner00950542001-06-06 20:29:01 +0000368 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000369 if (OldBuf > Buf)
370 throw std::string("Wrapped around reading bytecode.");
Chris Lattner00950542001-06-06 20:29:01 +0000371 break;
372 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000373 BCR_TRACE(2, "} end block\n");
374
Misha Brukman12c29d12003-09-22 23:38:23 +0000375 // Malformed bc file if read past end of block.
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000376 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000377 }
378
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000379 // Make sure there were no references to non-existant basic blocks.
380 if (BlockNum != ParsedBasicBlocks.size())
381 throw std::string("Illegal basic block operand reference");
382 ParsedBasicBlocks.clear();
383
384
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000385 // Resolve forward references
386 while (!ForwardReferences.empty()) {
387 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = ForwardReferences.begin();
388 unsigned type = I->first.first;
389 unsigned Slot = I->first.second;
390 Value *PlaceHolder = I->second;
391 ForwardReferences.erase(I);
Chris Lattner00950542001-06-06 20:29:01 +0000392
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000393 Value *NewVal = getValue(type, Slot, false);
394 if (NewVal == 0)
395 throw std::string("Unresolvable reference found: <" +
396 PlaceHolder->getType()->getDescription() + ">:" +
397 utostr(Slot) + ".");
Chris Lattner6e448022003-10-08 21:51:46 +0000398
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000399 // Fixup all of the uses of this placeholder def...
400 PlaceHolder->replaceAllUsesWith(NewVal);
Chris Lattner6e448022003-10-08 21:51:46 +0000401
Chris Lattner8eb10ce2003-10-09 06:05:40 +0000402 // Now that all the uses are gone, delete the placeholder...
403 // If we couldn't find a def (error case), then leak a little
404 // memory, because otherwise we can't remove all uses!
405 delete PlaceHolder;
Chris Lattner6e448022003-10-08 21:51:46 +0000406 }
Chris Lattner00950542001-06-06 20:29:01 +0000407
Misha Brukman12c29d12003-09-22 23:38:23 +0000408 // Clear out function-level types...
Chris Lattner6e5a0e42003-03-06 17:18:14 +0000409 FunctionTypeValues.clear();
Chris Lattnere4d71a12001-09-14 22:03:42 +0000410
Chris Lattner52e20b02003-03-19 20:54:26 +0000411 freeTable(Values);
Chris Lattner00950542001-06-06 20:29:01 +0000412}
413
Misha Brukman12c29d12003-09-22 23:38:23 +0000414void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
415 const unsigned char *End) {
416 if (!FunctionSignatureList.empty())
417 throw std::string("Two ModuleGlobalInfo packets found!");
Chris Lattner00950542001-06-06 20:29:01 +0000418
Chris Lattner70cc3392001-09-10 07:58:01 +0000419 // Read global variables...
420 unsigned VarType;
Misha Brukman12c29d12003-09-22 23:38:23 +0000421 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000422 while (VarType != Type::VoidTyID) { // List is terminated by Void
Chris Lattnere3869c82003-04-16 21:16:05 +0000423 unsigned SlotNo;
424 GlobalValue::LinkageTypes Linkage;
425
426 if (!hasInternalMarkerOnly) {
427 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
428 // bit2,3 = Linkage, bit4+ = slot#
429 SlotNo = VarType >> 4;
430 Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
431 } else {
432 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
433 // bit2 = isInternal, bit3+ = slot#
434 SlotNo = VarType >> 3;
435 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
436 GlobalValue::ExternalLinkage;
437 }
438
439 const Type *Ty = getType(SlotNo);
Chris Lattner927b1852003-10-09 20:22:47 +0000440 if (!isa<PointerType>(Ty))
Misha Brukman12c29d12003-09-22 23:38:23 +0000441 throw std::string("Global not pointer type! Ty = " +
442 Ty->getDescription());
Chris Lattner70cc3392001-09-10 07:58:01 +0000443
Chris Lattner52e20b02003-03-19 20:54:26 +0000444 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
Chris Lattnerd70684f2001-09-18 04:01:05 +0000445
Chris Lattner70cc3392001-09-10 07:58:01 +0000446 // Create the global variable...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000447 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
Chris Lattner52e20b02003-03-19 20:54:26 +0000448 0, "", TheModule);
Chris Lattner52e20b02003-03-19 20:54:26 +0000449 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
Chris Lattner927b1852003-10-09 20:22:47 +0000450 ResolveReferencesToValue(GV, insertValue(GV, ModuleValues));
Chris Lattner05950c32001-10-13 06:47:01 +0000451
Misha Brukman37f92e22003-09-11 22:34:13 +0000452 if (VarType & 2) { // Does it have an initializer?
Chris Lattner52e20b02003-03-19 20:54:26 +0000453 unsigned InitSlot;
Misha Brukman12c29d12003-09-22 23:38:23 +0000454 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
Chris Lattner52e20b02003-03-19 20:54:26 +0000455 GlobalInits.push_back(std::make_pair(GV, InitSlot));
456 }
Misha Brukman12c29d12003-09-22 23:38:23 +0000457 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
Chris Lattner70cc3392001-09-10 07:58:01 +0000458 }
459
Chris Lattner52e20b02003-03-19 20:54:26 +0000460 // Read the function objects for all of the functions that are coming
Chris Lattner74734132002-08-17 22:01:27 +0000461 unsigned FnSignature;
Misha Brukman12c29d12003-09-22 23:38:23 +0000462 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattner74734132002-08-17 22:01:27 +0000463 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
464 const Type *Ty = getType(FnSignature);
Chris Lattner927b1852003-10-09 20:22:47 +0000465 if (!isa<PointerType>(Ty) ||
466 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
Misha Brukman12c29d12003-09-22 23:38:23 +0000467 throw std::string("Function not ptr to func type! Ty = " +
468 Ty->getDescription());
Chris Lattner8cdc6b72002-10-23 00:51:54 +0000469
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000470 // We create functions by passing the underlying FunctionType to create...
Chris Lattner7a176752001-12-04 00:03:30 +0000471 Ty = cast<PointerType>(Ty)->getElementType();
Chris Lattner00950542001-06-06 20:29:01 +0000472
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000473 // When the ModuleGlobalInfo section is read, we load the type of each
474 // function and the 'ModuleValues' slot that it lands in. We then load a
475 // placeholder into its slot to reserve it. When the function is loaded,
476 // this placeholder is replaced.
Chris Lattner00950542001-06-06 20:29:01 +0000477
478 // Insert the placeholder...
Chris Lattner4ad02e72003-04-16 20:28:45 +0000479 Function *Func = new Function(cast<FunctionType>(Ty),
480 GlobalValue::InternalLinkage, "", TheModule);
Chris Lattner927b1852003-10-09 20:22:47 +0000481 unsigned DestSlot = insertValue(Func, ModuleValues);
482 ResolveReferencesToValue(Func, DestSlot);
Chris Lattner00950542001-06-06 20:29:01 +0000483
Chris Lattner52e20b02003-03-19 20:54:26 +0000484 // Keep track of this information in a list that is emptied as functions are
485 // loaded...
Chris Lattner00950542001-06-06 20:29:01 +0000486 //
Chris Lattner52e20b02003-03-19 20:54:26 +0000487 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
488
Misha Brukman12c29d12003-09-22 23:38:23 +0000489 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000490 BCR_TRACE(2, "Function of type: " << Ty << "\n");
Chris Lattner00950542001-06-06 20:29:01 +0000491 }
492
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000493 ALIGN32(Buf, End);
Chris Lattner74734132002-08-17 22:01:27 +0000494
495 // Now that the function signature list is set up, reverse it so that we can
496 // remove elements efficiently from the back of the vector.
497 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
Chris Lattner00950542001-06-06 20:29:01 +0000498
499 // This is for future proofing... in the future extra fields may be added that
500 // we don't understand, so we transparently ignore them.
501 //
502 Buf = End;
Chris Lattner00950542001-06-06 20:29:01 +0000503}
504
Misha Brukman12c29d12003-09-22 23:38:23 +0000505void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000506 const unsigned char *EndBuf) {
Chris Lattner036b8aa2003-03-06 17:55:45 +0000507 unsigned Version;
Misha Brukman12c29d12003-09-22 23:38:23 +0000508 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000509
510 // Unpack version number: low four bits are for flags, top bits = version
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000511 Module::Endianness Endianness;
512 Module::PointerSize PointerSize;
513 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
514 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
515
516 bool hasNoEndianness = Version & 4;
517 bool hasNoPointerSize = Version & 8;
518
519 RevisionNum = Version >> 4;
Chris Lattnere3869c82003-04-16 21:16:05 +0000520
521 // Default values for the current bytecode version
Chris Lattner036b8aa2003-03-06 17:55:45 +0000522 HasImplicitZeroInitializer = true;
Chris Lattnere3869c82003-04-16 21:16:05 +0000523 hasInternalMarkerOnly = false;
524 FirstDerivedTyID = 14;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000525
526 switch (RevisionNum) {
527 case 0: // Initial revision
Chris Lattner52e20b02003-03-19 20:54:26 +0000528 // Version #0 didn't have any of the flags stored correctly, and in fact as
529 // only valid with a 14 in the flags values. Also, it does not support
530 // encoding zero initializers for arrays compactly.
531 //
Misha Brukman12c29d12003-09-22 23:38:23 +0000532 if (Version != 14) throw std::string("Unknown revision 0 flags?");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000533 HasImplicitZeroInitializer = false;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000534 Endianness = Module::BigEndian;
535 PointerSize = Module::Pointer64;
Chris Lattnere3869c82003-04-16 21:16:05 +0000536 hasInternalMarkerOnly = true;
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000537 hasNoEndianness = hasNoPointerSize = false;
Chris Lattner036b8aa2003-03-06 17:55:45 +0000538 break;
539 case 1:
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000540 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
541 // hasNoEndianness, and hasNoPointerSize.
Chris Lattnere3869c82003-04-16 21:16:05 +0000542 hasInternalMarkerOnly = true;
543 break;
544 case 2:
545 // Version #2 added information about all 4 linkage types instead of just
546 // having internal and external.
Chris Lattner036b8aa2003-03-06 17:55:45 +0000547 break;
548 default:
Misha Brukman12c29d12003-09-22 23:38:23 +0000549 throw std::string("Unknown bytecode version number!");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000550 }
551
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000552 if (hasNoEndianness) Endianness = Module::AnyEndianness;
553 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
Chris Lattner76e38962003-04-22 18:15:10 +0000554
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000555 TheModule->setEndianness(Endianness);
556 TheModule->setPointerSize(PointerSize);
Chris Lattner036b8aa2003-03-06 17:55:45 +0000557 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
Chris Lattnerd445c6b2003-08-24 13:47:36 +0000558 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
559 << PointerSize << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000560 BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
Chris Lattner036b8aa2003-03-06 17:55:45 +0000561}
562
Misha Brukman12c29d12003-09-22 23:38:23 +0000563void BytecodeParser::ParseModule(const unsigned char *Buf,
Chris Lattner12e64652003-05-22 18:08:30 +0000564 const unsigned char *EndBuf) {
Chris Lattner00950542001-06-06 20:29:01 +0000565 unsigned Type, Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000566 readBlock(Buf, EndBuf, Type, Size);
567 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
568 throw std::string("Expected Module packet! B: "+
569 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
570 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
Chris Lattner00950542001-06-06 20:29:01 +0000571
Chris Lattner1d670cc2001-09-07 16:37:43 +0000572 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
Chris Lattner74734132002-08-17 22:01:27 +0000573 FunctionSignatureList.clear(); // Just in case...
Chris Lattner00950542001-06-06 20:29:01 +0000574
575 // Read into instance variables...
Misha Brukman12c29d12003-09-22 23:38:23 +0000576 ParseVersionInfo(Buf, EndBuf);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000577 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000578
Chris Lattner00950542001-06-06 20:29:01 +0000579 while (Buf < EndBuf) {
Chris Lattnerb6c46952003-03-06 17:03:28 +0000580 const unsigned char *OldBuf = Buf;
Misha Brukman12c29d12003-09-22 23:38:23 +0000581 readBlock(Buf, EndBuf, Type, Size);
Chris Lattner00950542001-06-06 20:29:01 +0000582 switch (Type) {
Chris Lattner52e20b02003-03-19 20:54:26 +0000583 case BytecodeFormat::GlobalTypePlane:
584 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000585 ParseGlobalTypes(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000586 break;
587
588 case BytecodeFormat::ModuleGlobalInfo:
589 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000590 ParseModuleGlobalInfo(Buf, Buf+Size);
Chris Lattner52e20b02003-03-19 20:54:26 +0000591 break;
592
Chris Lattner1d670cc2001-09-07 16:37:43 +0000593 case BytecodeFormat::ConstantPool:
594 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000595 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
Chris Lattner00950542001-06-06 20:29:01 +0000596 break;
597
Chris Lattnerc9aa7df2002-03-29 03:51:11 +0000598 case BytecodeFormat::Function: {
599 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
Misha Brukman12c29d12003-09-22 23:38:23 +0000600 ParseFunction(Buf, Buf+Size);
Chris Lattner00950542001-06-06 20:29:01 +0000601 break;
602 }
603
604 case BytecodeFormat::SymbolTable:
Chris Lattner1d670cc2001-09-07 16:37:43 +0000605 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
Chris Lattner4ee8ef22003-10-08 22:52:54 +0000606 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
Chris Lattner00950542001-06-06 20:29:01 +0000607 break;
608
609 default:
Chris Lattner00950542001-06-06 20:29:01 +0000610 Buf += Size;
Misha Brukman12c29d12003-09-22 23:38:23 +0000611 if (OldBuf > Buf) throw std::string("Expected Module Block!");
Chris Lattner00950542001-06-06 20:29:01 +0000612 break;
613 }
Chris Lattner1d670cc2001-09-07 16:37:43 +0000614 BCR_TRACE(1, "} end block\n");
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000615 ALIGN32(Buf, EndBuf);
Chris Lattner00950542001-06-06 20:29:01 +0000616 }
617
Chris Lattner52e20b02003-03-19 20:54:26 +0000618 // After the module constant pool has been read, we can safely initialize
619 // global variables...
620 while (!GlobalInits.empty()) {
621 GlobalVariable *GV = GlobalInits.back().first;
622 unsigned Slot = GlobalInits.back().second;
623 GlobalInits.pop_back();
624
625 // Look up the initializer value...
626 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
Misha Brukman12c29d12003-09-22 23:38:23 +0000627 if (GV->hasInitializer())
628 throw std::string("Global *already* has an initializer?!");
Chris Lattner52e20b02003-03-19 20:54:26 +0000629 GV->setInitializer(cast<Constant>(V));
630 } else
Misha Brukman12c29d12003-09-22 23:38:23 +0000631 throw std::string("Cannot find initializer value.");
Chris Lattner52e20b02003-03-19 20:54:26 +0000632 }
633
Misha Brukman12c29d12003-09-22 23:38:23 +0000634 if (!FunctionSignatureList.empty())
635 throw std::string("Function expected, but bytecode stream ended!");
Chris Lattner1d670cc2001-09-07 16:37:43 +0000636
637 BCR_TRACE(0, "} end block\n\n");
Chris Lattner00950542001-06-06 20:29:01 +0000638}
639
Misha Brukman12c29d12003-09-22 23:38:23 +0000640void
641BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
642 const std::string &ModuleID) {
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000643
Misha Brukman12c29d12003-09-22 23:38:23 +0000644 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000645
Chris Lattner00950542001-06-06 20:29:01 +0000646 // Read and check signature...
Misha Brukmane0dd0d42003-09-23 16:15:29 +0000647 unsigned Sig;
Chris Lattner00950542001-06-06 20:29:01 +0000648 if (read(Buf, EndBuf, Sig) ||
Misha Brukman12c29d12003-09-22 23:38:23 +0000649 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
650 throw std::string("Invalid bytecode signature!");
Chris Lattner00950542001-06-06 20:29:01 +0000651
Chris Lattner75f20532003-04-22 18:02:52 +0000652 TheModule = new Module(ModuleID);
Misha Brukman12c29d12003-09-22 23:38:23 +0000653 try {
654 ParseModule(Buf, EndBuf);
655 } catch (std::string &Error) {
Chris Lattnera2602f32003-05-22 18:26:48 +0000656 freeState(); // Must destroy handles before deleting module!
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000657 delete TheModule;
658 TheModule = 0;
Chris Lattnerb0b7c0d2003-09-26 14:44:52 +0000659 throw;
Chris Lattner2a7b6ba2003-03-06 17:15:19 +0000660 }
Chris Lattner00950542001-06-06 20:29:01 +0000661}