Read global symtab
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License.  See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitcodeReader class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "BitcodeReader.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/ADT/SmallString.h"
19 using namespace llvm;
20
21 /// ConvertToString - Convert a string from a record into an std::string, return
22 /// true on failure.
23 template<typename StrTy>
24 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
25                             StrTy &Result) {
26   if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
27     return true;
28   
29   for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
30     Result += (char)Record[Idx+i+1];
31   return false;
32 }
33
34 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
35   switch (Val) {
36   default: // Map unknown/new linkages to external
37   case 0: return GlobalValue::ExternalLinkage;
38   case 1: return GlobalValue::WeakLinkage;
39   case 2: return GlobalValue::AppendingLinkage;
40   case 3: return GlobalValue::InternalLinkage;
41   case 4: return GlobalValue::LinkOnceLinkage;
42   case 5: return GlobalValue::DLLImportLinkage;
43   case 6: return GlobalValue::DLLExportLinkage;
44   case 7: return GlobalValue::ExternalWeakLinkage;
45   }
46 }
47
48 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
49   switch (Val) {
50   default: // Map unknown visibilities to default.
51   case 0: return GlobalValue::DefaultVisibility;
52   case 1: return GlobalValue::HiddenVisibility;
53   }
54 }
55
56
57 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
58   // If the TypeID is in range, return it.
59   if (ID < TypeList.size())
60     return TypeList[ID].get();
61   if (!isTypeTable) return 0;
62   
63   // The type table allows forward references.  Push as many Opaque types as
64   // needed to get up to ID.
65   while (TypeList.size() <= ID)
66     TypeList.push_back(OpaqueType::get());
67   return TypeList.back().get();
68 }
69
70
71 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
72   if (Stream.EnterSubBlock())
73     return Error("Malformed block record");
74   
75   if (!TypeList.empty())
76     return Error("Multiple TYPE_BLOCKs found!");
77
78   SmallVector<uint64_t, 64> Record;
79   unsigned NumRecords = 0;
80
81   // Read all the records for this type table.
82   while (1) {
83     unsigned Code = Stream.ReadCode();
84     if (Code == bitc::END_BLOCK) {
85       if (NumRecords != TypeList.size())
86         return Error("Invalid type forward reference in TYPE_BLOCK");
87       return Stream.ReadBlockEnd();
88     }
89     
90     if (Code == bitc::ENTER_SUBBLOCK) {
91       // No known subblocks, always skip them.
92       Stream.ReadSubBlockID();
93       if (Stream.SkipBlock())
94         return Error("Malformed block record");
95       continue;
96     }
97     
98     if (Code == bitc::DEFINE_ABBREV) {
99       Stream.ReadAbbrevRecord();
100       continue;
101     }
102     
103     // Read a record.
104     Record.clear();
105     const Type *ResultTy = 0;
106     switch (Stream.ReadRecord(Code, Record)) {
107     default:  // Default behavior: unknown type.
108       ResultTy = 0;
109       break;
110     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
111       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
112       // type list.  This allows us to reserve space.
113       if (Record.size() < 1)
114         return Error("Invalid TYPE_CODE_NUMENTRY record");
115       TypeList.reserve(Record[0]);
116       continue;
117     case bitc::TYPE_CODE_META:      // TYPE_CODE_META: [metacode]...
118       // No metadata supported yet.
119       if (Record.size() < 1)
120         return Error("Invalid TYPE_CODE_META record");
121       continue;
122       
123     case bitc::TYPE_CODE_VOID:      // VOID
124       ResultTy = Type::VoidTy;
125       break;
126     case bitc::TYPE_CODE_FLOAT:     // FLOAT
127       ResultTy = Type::FloatTy;
128       break;
129     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
130       ResultTy = Type::DoubleTy;
131       break;
132     case bitc::TYPE_CODE_LABEL:     // LABEL
133       ResultTy = Type::LabelTy;
134       break;
135     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
136       ResultTy = 0;
137       break;
138     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
139       if (Record.size() < 1)
140         return Error("Invalid Integer type record");
141       
142       ResultTy = IntegerType::get(Record[0]);
143       break;
144     case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
145       if (Record.size() < 1)
146         return Error("Invalid POINTER type record");
147       ResultTy = PointerType::get(getTypeByID(Record[0], true));
148       break;
149     case bitc::TYPE_CODE_FUNCTION: {
150       // FUNCTION: [vararg, retty, #pararms, paramty N]
151       if (Record.size() < 3 || Record.size() < Record[2]+3)
152         return Error("Invalid FUNCTION type record");
153       std::vector<const Type*> ArgTys;
154       for (unsigned i = 0, e = Record[2]; i != e; ++i)
155         ArgTys.push_back(getTypeByID(Record[3+i], true));
156       
157       // FIXME: PARAM TYS.
158       ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
159                                    Record[0]);
160       break;
161     }
162     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, #elts, eltty x N]
163       if (Record.size() < 2 || Record.size() < Record[1]+2)
164         return Error("Invalid STRUCT type record");
165       std::vector<const Type*> EltTys;
166       for (unsigned i = 0, e = Record[1]; i != e; ++i)
167         EltTys.push_back(getTypeByID(Record[2+i], true));
168       ResultTy = StructType::get(EltTys, Record[0]);
169       break;
170     }
171     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
172       if (Record.size() < 2)
173         return Error("Invalid ARRAY type record");
174       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
175       break;
176     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
177       if (Record.size() < 2)
178         return Error("Invalid VECTOR type record");
179       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
180       break;
181     }
182     
183     if (NumRecords == TypeList.size()) {
184       // If this is a new type slot, just append it.
185       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
186       ++NumRecords;
187     } else if (ResultTy == 0) {
188       // Otherwise, this was forward referenced, so an opaque type was created,
189       // but the result type is actually just an opaque.  Leave the one we
190       // created previously.
191       ++NumRecords;
192     } else {
193       // Otherwise, this was forward referenced, so an opaque type was created.
194       // Resolve the opaque type to the real type now.
195       assert(NumRecords < TypeList.size() && "Typelist imbalance");
196       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
197      
198       // Don't directly push the new type on the Tab. Instead we want to replace
199       // the opaque type we previously inserted with the new concrete value. The
200       // refinement from the abstract (opaque) type to the new type causes all
201       // uses of the abstract type to use the concrete type (NewTy). This will
202       // also cause the opaque type to be deleted.
203       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
204       
205       // This should have replaced the old opaque type with the new type in the
206       // value table... or with a preexisting type that was already in the system.
207       // Let's just make sure it did.
208       assert(TypeList[NumRecords-1].get() != OldTy &&
209              "refineAbstractType didn't work!");
210     }
211   }
212 }
213
214
215 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
216   if (Stream.EnterSubBlock())
217     return Error("Malformed block record");
218   
219   SmallVector<uint64_t, 64> Record;
220   
221   // Read all the records for this type table.
222   std::string TypeName;
223   while (1) {
224     unsigned Code = Stream.ReadCode();
225     if (Code == bitc::END_BLOCK)
226       return Stream.ReadBlockEnd();
227     
228     if (Code == bitc::ENTER_SUBBLOCK) {
229       // No known subblocks, always skip them.
230       Stream.ReadSubBlockID();
231       if (Stream.SkipBlock())
232         return Error("Malformed block record");
233       continue;
234     }
235     
236     if (Code == bitc::DEFINE_ABBREV) {
237       Stream.ReadAbbrevRecord();
238       continue;
239     }
240     
241     // Read a record.
242     Record.clear();
243     switch (Stream.ReadRecord(Code, Record)) {
244     default:  // Default behavior: unknown type.
245       break;
246     case bitc::TST_ENTRY_CODE:    // TST_ENTRY: [typeid, namelen, namechar x N]
247       if (ConvertToString(Record, 1, TypeName))
248         return Error("Invalid TST_ENTRY record");
249       unsigned TypeID = Record[0];
250       if (TypeID >= TypeList.size())
251         return Error("Invalid Type ID in TST_ENTRY record");
252
253       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
254       TypeName.clear();
255       break;
256     }
257   }
258 }
259
260 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
261   if (Stream.EnterSubBlock())
262     return Error("Malformed block record");
263
264   SmallVector<uint64_t, 64> Record;
265   
266   // Read all the records for this value table.
267   SmallString<128> ValueName;
268   while (1) {
269     unsigned Code = Stream.ReadCode();
270     if (Code == bitc::END_BLOCK)
271       return Stream.ReadBlockEnd();
272     
273     if (Code == bitc::ENTER_SUBBLOCK) {
274       // No known subblocks, always skip them.
275       Stream.ReadSubBlockID();
276       if (Stream.SkipBlock())
277         return Error("Malformed block record");
278       continue;
279     }
280     
281     if (Code == bitc::DEFINE_ABBREV) {
282       Stream.ReadAbbrevRecord();
283       continue;
284     }
285     
286     // Read a record.
287     Record.clear();
288     switch (Stream.ReadRecord(Code, Record)) {
289     default:  // Default behavior: unknown type.
290       break;
291     case bitc::VST_ENTRY_CODE:    // VST_ENTRY: [valueid, namelen, namechar x N]
292       if (ConvertToString(Record, 1, ValueName))
293         return Error("Invalid TST_ENTRY record");
294       unsigned ValueID = Record[0];
295       if (ValueID >= ValueList.size())
296         return Error("Invalid Value ID in VST_ENTRY record");
297       Value *V = ValueList[ValueID];
298       
299       V->setName(&ValueName[0], ValueName.size());
300       ValueName.clear();
301       break;
302     }
303   }
304 }
305
306
307 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
308                                 const std::string &ModuleID) {
309   // Reject multiple MODULE_BLOCK's in a single bitstream.
310   if (TheModule)
311     return Error("Multiple MODULE_BLOCKs in same stream");
312   
313   if (Stream.EnterSubBlock())
314     return Error("Malformed block record");
315
316   // Otherwise, create the module.
317   TheModule = new Module(ModuleID);
318   
319   SmallVector<uint64_t, 64> Record;
320   std::vector<std::string> SectionTable;
321
322   // Read all the records for this module.
323   while (!Stream.AtEndOfStream()) {
324     unsigned Code = Stream.ReadCode();
325     if (Code == bitc::END_BLOCK)
326       return Stream.ReadBlockEnd();
327     
328     if (Code == bitc::ENTER_SUBBLOCK) {
329       switch (Stream.ReadSubBlockID()) {
330       default:  // Skip unknown content.
331         if (Stream.SkipBlock())
332           return Error("Malformed block record");
333         break;
334       case bitc::TYPE_BLOCK_ID:
335         if (ParseTypeTable(Stream))
336           return true;
337         break;
338       case bitc::TYPE_SYMTAB_BLOCK_ID:
339         if (ParseTypeSymbolTable(Stream))
340           return true;
341         break;
342       case bitc::VALUE_SYMTAB_BLOCK_ID:
343         if (ParseValueSymbolTable(Stream))
344           return true;
345         break;
346       }
347       continue;
348     }
349     
350     if (Code == bitc::DEFINE_ABBREV) {
351       Stream.ReadAbbrevRecord();
352       continue;
353     }
354     
355     // Read a record.
356     switch (Stream.ReadRecord(Code, Record)) {
357     default: break;  // Default behavior, ignore unknown content.
358     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
359       if (Record.size() < 1)
360         return Error("Malformed MODULE_CODE_VERSION");
361       // Only version #0 is supported so far.
362       if (Record[0] != 0)
363         return Error("Unknown bitstream version!");
364       break;
365     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strlen, strchr x N]
366       std::string S;
367       if (ConvertToString(Record, 0, S))
368         return Error("Invalid MODULE_CODE_TRIPLE record");
369       TheModule->setTargetTriple(S);
370       break;
371     }
372     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strlen, strchr x N]
373       std::string S;
374       if (ConvertToString(Record, 0, S))
375         return Error("Invalid MODULE_CODE_DATALAYOUT record");
376       TheModule->setDataLayout(S);
377       break;
378     }
379     case bitc::MODULE_CODE_ASM: {  // ASM: [strlen, strchr x N]
380       std::string S;
381       if (ConvertToString(Record, 0, S))
382         return Error("Invalid MODULE_CODE_ASM record");
383       TheModule->setModuleInlineAsm(S);
384       break;
385     }
386     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strlen, strchr x N]
387       std::string S;
388       if (ConvertToString(Record, 0, S))
389         return Error("Invalid MODULE_CODE_DEPLIB record");
390       TheModule->addLibrary(S);
391       break;
392     }
393     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strlen, strchr x N]
394       std::string S;
395       if (ConvertToString(Record, 0, S))
396         return Error("Invalid MODULE_CODE_SECTIONNAME record");
397       SectionTable.push_back(S);
398       break;
399     }
400     // GLOBALVAR: [type, isconst, initid, 
401     //             linkage, alignment, section, visibility, threadlocal]
402     case bitc::MODULE_CODE_GLOBALVAR: {
403       if (Record.size() < 6)
404         return Error("Invalid MODULE_CODE_GLOBALVAR record");
405       const Type *Ty = getTypeByID(Record[0]);
406       if (!isa<PointerType>(Ty))
407         return Error("Global not a pointer type!");
408       Ty = cast<PointerType>(Ty)->getElementType();
409       
410       bool isConstant = Record[1];
411       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
412       unsigned Alignment = (1 << Record[4]) >> 1;
413       std::string Section;
414       if (Record[5]) {
415         if (Record[5]-1 >= SectionTable.size())
416           return Error("Invalid section ID");
417         Section = SectionTable[Record[5]-1];
418       }
419       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
420       if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
421       bool isThreadLocal = false;
422       if (Record.size() >= 7) isThreadLocal = Record[7];
423
424       GlobalVariable *NewGV =
425         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
426       NewGV->setAlignment(Alignment);
427       if (!Section.empty())
428         NewGV->setSection(Section);
429       NewGV->setVisibility(Visibility);
430       NewGV->setThreadLocal(isThreadLocal);
431       
432       ValueList.push_back(NewGV);
433       
434       // TODO: remember initializer/global pair for later substitution.
435       break;
436     }
437     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
438     //             visibility]
439     case bitc::MODULE_CODE_FUNCTION: {
440       if (Record.size() < 7)
441         return Error("Invalid MODULE_CODE_FUNCTION record");
442       const Type *Ty = getTypeByID(Record[0]);
443       if (!isa<PointerType>(Ty))
444         return Error("Function not a pointer type!");
445       const FunctionType *FTy =
446         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
447       if (!FTy)
448         return Error("Function not a pointer to function type!");
449
450       Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
451                                     "", TheModule);
452
453       Func->setCallingConv(Record[1]);
454       Func->setLinkage(GetDecodedLinkage(Record[3]));
455       Func->setAlignment((1 << Record[4]) >> 1);
456       if (Record[5]) {
457         if (Record[5]-1 >= SectionTable.size())
458           return Error("Invalid section ID");
459         Func->setSection(SectionTable[Record[5]-1]);
460       }
461       Func->setVisibility(GetDecodedVisibility(Record[6]));
462       
463       ValueList.push_back(Func);
464       // TODO: remember initializer/global pair for later substitution.
465       break;
466     }
467     }
468     Record.clear();
469   }
470   
471   return Error("Premature end of bitstream");
472 }
473
474
475 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
476                                  const std::string &ModuleID) {
477   TheModule = 0;
478   
479   if (Length & 3)
480     return Error("Bitcode stream should be a multiple of 4 bytes in length");
481   
482   BitstreamReader Stream(Buf, Buf+Length);
483   
484   // Sniff for the signature.
485   if (Stream.Read(8) != 'B' ||
486       Stream.Read(8) != 'C' ||
487       Stream.Read(4) != 0x0 ||
488       Stream.Read(4) != 0xC ||
489       Stream.Read(4) != 0xE ||
490       Stream.Read(4) != 0xD)
491     return Error("Invalid bitcode signature");
492   
493   // We expect a number of well-defined blocks, though we don't necessarily
494   // need to understand them all.
495   while (!Stream.AtEndOfStream()) {
496     unsigned Code = Stream.ReadCode();
497     
498     if (Code != bitc::ENTER_SUBBLOCK)
499       return Error("Invalid record at top-level");
500     
501     unsigned BlockID = Stream.ReadSubBlockID();
502     
503     // We only know the MODULE subblock ID.
504     if (BlockID == bitc::MODULE_BLOCK_ID) {
505       if (ParseModule(Stream, ModuleID))
506         return true;
507     } else if (Stream.SkipBlock()) {
508       return Error("Malformed block record");
509     }
510   }
511   
512   return false;
513 }