1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This header defines the BitcodeReader class.
12 //===----------------------------------------------------------------------===//
14 #include "BitcodeReader.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/MathExtras.h"
23 /// ConvertToString - Convert a string from a record into an std::string, return
25 template<typename StrTy>
26 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
28 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
31 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
32 Result += (char)Record[Idx+i+1];
36 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
38 default: // Map unknown/new linkages to external
39 case 0: return GlobalValue::ExternalLinkage;
40 case 1: return GlobalValue::WeakLinkage;
41 case 2: return GlobalValue::AppendingLinkage;
42 case 3: return GlobalValue::InternalLinkage;
43 case 4: return GlobalValue::LinkOnceLinkage;
44 case 5: return GlobalValue::DLLImportLinkage;
45 case 6: return GlobalValue::DLLExportLinkage;
46 case 7: return GlobalValue::ExternalWeakLinkage;
50 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
52 default: // Map unknown visibilities to default.
53 case 0: return GlobalValue::DefaultVisibility;
54 case 1: return GlobalValue::HiddenVisibility;
58 static int GetDecodedCastOpcode(unsigned Val) {
61 case bitc::CAST_TRUNC : return Instruction::Trunc;
62 case bitc::CAST_ZEXT : return Instruction::ZExt;
63 case bitc::CAST_SEXT : return Instruction::SExt;
64 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
65 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
66 case bitc::CAST_UITOFP : return Instruction::UIToFP;
67 case bitc::CAST_SITOFP : return Instruction::SIToFP;
68 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
69 case bitc::CAST_FPEXT : return Instruction::FPExt;
70 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
71 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
72 case bitc::CAST_BITCAST : return Instruction::BitCast;
75 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
78 case bitc::BINOP_ADD: return Instruction::Add;
79 case bitc::BINOP_SUB: return Instruction::Sub;
80 case bitc::BINOP_MUL: return Instruction::Mul;
81 case bitc::BINOP_UDIV: return Instruction::UDiv;
82 case bitc::BINOP_SDIV:
83 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
84 case bitc::BINOP_UREM: return Instruction::URem;
85 case bitc::BINOP_SREM:
86 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
87 case bitc::BINOP_SHL: return Instruction::Shl;
88 case bitc::BINOP_LSHR: return Instruction::LShr;
89 case bitc::BINOP_ASHR: return Instruction::AShr;
90 case bitc::BINOP_AND: return Instruction::And;
91 case bitc::BINOP_OR: return Instruction::Or;
92 case bitc::BINOP_XOR: return Instruction::Xor;
98 /// @brief A class for maintaining the slot number definition
99 /// as a placeholder for the actual definition for forward constants defs.
100 class ConstantPlaceHolder : public ConstantExpr {
101 ConstantPlaceHolder(); // DO NOT IMPLEMENT
102 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
105 ConstantPlaceHolder(const Type *Ty)
106 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
107 Op(UndefValue::get(Type::Int32Ty), this) {
112 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
115 // Insert a bunch of null values.
117 OperandList = &Uses[0];
122 assert(Ty == getOperand(Idx)->getType() &&
123 "Type mismatch in constant table!");
124 return cast<Constant>(getOperand(Idx));
127 // Create and return a placeholder, which will later be RAUW'd.
128 Constant *C = new ConstantPlaceHolder(Ty);
129 Uses[Idx].init(C, this);
134 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
135 // If the TypeID is in range, return it.
136 if (ID < TypeList.size())
137 return TypeList[ID].get();
138 if (!isTypeTable) return 0;
140 // The type table allows forward references. Push as many Opaque types as
141 // needed to get up to ID.
142 while (TypeList.size() <= ID)
143 TypeList.push_back(OpaqueType::get());
144 return TypeList.back().get();
148 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
149 if (Stream.EnterSubBlock())
150 return Error("Malformed block record");
152 if (!TypeList.empty())
153 return Error("Multiple TYPE_BLOCKs found!");
155 SmallVector<uint64_t, 64> Record;
156 unsigned NumRecords = 0;
158 // Read all the records for this type table.
160 unsigned Code = Stream.ReadCode();
161 if (Code == bitc::END_BLOCK) {
162 if (NumRecords != TypeList.size())
163 return Error("Invalid type forward reference in TYPE_BLOCK");
164 return Stream.ReadBlockEnd();
167 if (Code == bitc::ENTER_SUBBLOCK) {
168 // No known subblocks, always skip them.
169 Stream.ReadSubBlockID();
170 if (Stream.SkipBlock())
171 return Error("Malformed block record");
175 if (Code == bitc::DEFINE_ABBREV) {
176 Stream.ReadAbbrevRecord();
182 const Type *ResultTy = 0;
183 switch (Stream.ReadRecord(Code, Record)) {
184 default: // Default behavior: unknown type.
187 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
188 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
189 // type list. This allows us to reserve space.
190 if (Record.size() < 1)
191 return Error("Invalid TYPE_CODE_NUMENTRY record");
192 TypeList.reserve(Record[0]);
194 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
195 // No metadata supported yet.
196 if (Record.size() < 1)
197 return Error("Invalid TYPE_CODE_META record");
200 case bitc::TYPE_CODE_VOID: // VOID
201 ResultTy = Type::VoidTy;
203 case bitc::TYPE_CODE_FLOAT: // FLOAT
204 ResultTy = Type::FloatTy;
206 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
207 ResultTy = Type::DoubleTy;
209 case bitc::TYPE_CODE_LABEL: // LABEL
210 ResultTy = Type::LabelTy;
212 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
215 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
216 if (Record.size() < 1)
217 return Error("Invalid Integer type record");
219 ResultTy = IntegerType::get(Record[0]);
221 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
222 if (Record.size() < 1)
223 return Error("Invalid POINTER type record");
224 ResultTy = PointerType::get(getTypeByID(Record[0], true));
226 case bitc::TYPE_CODE_FUNCTION: {
227 // FUNCTION: [vararg, retty, #pararms, paramty N]
228 if (Record.size() < 3 || Record.size() < Record[2]+3)
229 return Error("Invalid FUNCTION type record");
230 std::vector<const Type*> ArgTys;
231 for (unsigned i = 0, e = Record[2]; i != e; ++i)
232 ArgTys.push_back(getTypeByID(Record[3+i], true));
235 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
239 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
240 if (Record.size() < 2 || Record.size() < Record[1]+2)
241 return Error("Invalid STRUCT type record");
242 std::vector<const Type*> EltTys;
243 for (unsigned i = 0, e = Record[1]; i != e; ++i)
244 EltTys.push_back(getTypeByID(Record[2+i], true));
245 ResultTy = StructType::get(EltTys, Record[0]);
248 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
249 if (Record.size() < 2)
250 return Error("Invalid ARRAY type record");
251 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
253 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
254 if (Record.size() < 2)
255 return Error("Invalid VECTOR type record");
256 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
260 if (NumRecords == TypeList.size()) {
261 // If this is a new type slot, just append it.
262 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
264 } else if (ResultTy == 0) {
265 // Otherwise, this was forward referenced, so an opaque type was created,
266 // but the result type is actually just an opaque. Leave the one we
267 // created previously.
270 // Otherwise, this was forward referenced, so an opaque type was created.
271 // Resolve the opaque type to the real type now.
272 assert(NumRecords < TypeList.size() && "Typelist imbalance");
273 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
275 // Don't directly push the new type on the Tab. Instead we want to replace
276 // the opaque type we previously inserted with the new concrete value. The
277 // refinement from the abstract (opaque) type to the new type causes all
278 // uses of the abstract type to use the concrete type (NewTy). This will
279 // also cause the opaque type to be deleted.
280 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
282 // This should have replaced the old opaque type with the new type in the
283 // value table... or with a preexisting type that was already in the
284 // system. Let's just make sure it did.
285 assert(TypeList[NumRecords-1].get() != OldTy &&
286 "refineAbstractType didn't work!");
292 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
293 if (Stream.EnterSubBlock())
294 return Error("Malformed block record");
296 SmallVector<uint64_t, 64> Record;
298 // Read all the records for this type table.
299 std::string TypeName;
301 unsigned Code = Stream.ReadCode();
302 if (Code == bitc::END_BLOCK)
303 return Stream.ReadBlockEnd();
305 if (Code == bitc::ENTER_SUBBLOCK) {
306 // No known subblocks, always skip them.
307 Stream.ReadSubBlockID();
308 if (Stream.SkipBlock())
309 return Error("Malformed block record");
313 if (Code == bitc::DEFINE_ABBREV) {
314 Stream.ReadAbbrevRecord();
320 switch (Stream.ReadRecord(Code, Record)) {
321 default: // Default behavior: unknown type.
323 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
324 if (ConvertToString(Record, 1, TypeName))
325 return Error("Invalid TST_ENTRY record");
326 unsigned TypeID = Record[0];
327 if (TypeID >= TypeList.size())
328 return Error("Invalid Type ID in TST_ENTRY record");
330 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
337 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
338 if (Stream.EnterSubBlock())
339 return Error("Malformed block record");
341 SmallVector<uint64_t, 64> Record;
343 // Read all the records for this value table.
344 SmallString<128> ValueName;
346 unsigned Code = Stream.ReadCode();
347 if (Code == bitc::END_BLOCK)
348 return Stream.ReadBlockEnd();
350 if (Code == bitc::ENTER_SUBBLOCK) {
351 // No known subblocks, always skip them.
352 Stream.ReadSubBlockID();
353 if (Stream.SkipBlock())
354 return Error("Malformed block record");
358 if (Code == bitc::DEFINE_ABBREV) {
359 Stream.ReadAbbrevRecord();
365 switch (Stream.ReadRecord(Code, Record)) {
366 default: // Default behavior: unknown type.
368 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
369 if (ConvertToString(Record, 1, ValueName))
370 return Error("Invalid TST_ENTRY record");
371 unsigned ValueID = Record[0];
372 if (ValueID >= ValueList.size())
373 return Error("Invalid Value ID in VST_ENTRY record");
374 Value *V = ValueList[ValueID];
376 V->setName(&ValueName[0], ValueName.size());
383 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
384 /// the LSB for dense VBR encoding.
385 static uint64_t DecodeSignRotatedValue(uint64_t V) {
390 // There is no such thing as -0 with integers. "-0" really means MININT.
394 bool BitcodeReader::ParseConstants(BitstreamReader &Stream) {
395 if (Stream.EnterSubBlock())
396 return Error("Malformed block record");
398 SmallVector<uint64_t, 64> Record;
400 // Read all the records for this value table.
401 const Type *CurTy = Type::Int32Ty;
402 unsigned NextCstNo = ValueList.size();
404 unsigned Code = Stream.ReadCode();
405 if (Code == bitc::END_BLOCK) {
406 // If there are global var inits to process, do so now.
407 if (!GlobalInits.empty()) {
408 while (!GlobalInits.empty()) {
409 unsigned ValID = GlobalInits.back().second;
410 if (ValID >= ValueList.size())
411 return Error("Invalid value ID for global var init!");
412 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
413 GlobalInits.back().first->setInitializer(C);
415 return Error("Global variable initializer is not a constant!");
416 GlobalInits.pop_back();
420 if (NextCstNo != ValueList.size())
421 return Error("Invalid constant reference!");
423 return Stream.ReadBlockEnd();
426 if (Code == bitc::ENTER_SUBBLOCK) {
427 // No known subblocks, always skip them.
428 Stream.ReadSubBlockID();
429 if (Stream.SkipBlock())
430 return Error("Malformed block record");
434 if (Code == bitc::DEFINE_ABBREV) {
435 Stream.ReadAbbrevRecord();
442 switch (Stream.ReadRecord(Code, Record)) {
443 default: // Default behavior: unknown constant
444 case bitc::CST_CODE_UNDEF: // UNDEF
445 V = UndefValue::get(CurTy);
447 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
449 return Error("Malformed CST_SETTYPE record");
450 if (Record[0] >= TypeList.size())
451 return Error("Invalid Type ID in CST_SETTYPE record");
452 CurTy = TypeList[Record[0]];
453 continue; // Skip the ValueList manipulation.
454 case bitc::CST_CODE_NULL: // NULL
455 V = Constant::getNullValue(CurTy);
457 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
458 if (!isa<IntegerType>(CurTy) || Record.empty())
459 return Error("Invalid CST_INTEGER record");
460 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
462 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
463 if (!isa<IntegerType>(CurTy) || Record.empty() ||
464 Record.size() < Record[0]+1)
465 return Error("Invalid WIDE_INTEGER record");
467 unsigned NumWords = Record[0];
468 SmallVector<uint64_t, 8> Words;
469 Words.resize(NumWords);
470 for (unsigned i = 0; i != NumWords; ++i)
471 Words[i] = DecodeSignRotatedValue(Record[i+1]);
472 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
473 NumWords, &Words[0]));
476 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
478 return Error("Invalid FLOAT record");
479 if (CurTy == Type::FloatTy)
480 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
481 else if (CurTy == Type::DoubleTy)
482 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
484 V = UndefValue::get(CurTy);
487 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
488 if (Record.empty() || Record.size() < Record[0]+1)
489 return Error("Invalid CST_AGGREGATE record");
491 unsigned Size = Record[0];
492 std::vector<Constant*> Elts;
494 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
495 for (unsigned i = 0; i != Size; ++i)
496 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
497 STy->getElementType(i)));
498 V = ConstantStruct::get(STy, Elts);
499 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
500 const Type *EltTy = ATy->getElementType();
501 for (unsigned i = 0; i != Size; ++i)
502 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
503 V = ConstantArray::get(ATy, Elts);
504 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
505 const Type *EltTy = VTy->getElementType();
506 for (unsigned i = 0; i != Size; ++i)
507 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
508 V = ConstantVector::get(Elts);
510 V = UndefValue::get(CurTy);
515 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
516 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
517 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
518 if (Opc < 0) return UndefValue::get(CurTy); // Unknown binop.
520 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
521 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
522 V = ConstantExpr::get(Opc, LHS, RHS);
525 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
526 if (Record.size() < 3) return Error("Invalid CE_CAST record");
527 int Opc = GetDecodedCastOpcode(Record[0]);
528 if (Opc < 0) return UndefValue::get(CurTy); // Unknown cast.
530 const Type *OpTy = getTypeByID(Record[1]);
531 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
532 V = ConstantExpr::getCast(Opc, Op, CurTy);
535 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
536 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
537 SmallVector<Constant*, 16> Elts;
538 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
539 const Type *ElTy = getTypeByID(Record[i]);
540 if (!ElTy) return Error("Invalid CE_GEP record");
541 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
543 return ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
545 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
546 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
547 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
549 ValueList.getConstantFwdRef(Record[1],CurTy),
550 ValueList.getConstantFwdRef(Record[2],CurTy));
552 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
553 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
554 const VectorType *OpTy =
555 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
556 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
557 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
558 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
559 OpTy->getElementType());
560 V = ConstantExpr::getExtractElement(Op0, Op1);
563 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
564 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
565 if (Record.size() < 3 || OpTy == 0)
566 return Error("Invalid CE_INSERTELT record");
567 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
568 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
569 OpTy->getElementType());
570 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
571 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
574 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
575 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
576 if (Record.size() < 3 || OpTy == 0)
577 return Error("Invalid CE_INSERTELT record");
578 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
579 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
580 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
581 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
582 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
585 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
586 if (Record.size() < 4) return Error("Invalid CE_CMP record");
587 const Type *OpTy = getTypeByID(Record[0]);
588 if (OpTy == 0) return Error("Invalid CE_CMP record");
589 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
590 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
592 if (OpTy->isFloatingPoint())
593 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
595 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
600 if (NextCstNo == ValueList.size())
601 ValueList.push_back(V);
602 else if (ValueList[NextCstNo] == 0)
603 ValueList.initVal(NextCstNo, V);
605 // If there was a forward reference to this constant,
606 Value *OldV = ValueList[NextCstNo];
607 ValueList.setOperand(NextCstNo, V);
608 OldV->replaceAllUsesWith(V);
616 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
617 const std::string &ModuleID) {
618 // Reject multiple MODULE_BLOCK's in a single bitstream.
620 return Error("Multiple MODULE_BLOCKs in same stream");
622 if (Stream.EnterSubBlock())
623 return Error("Malformed block record");
625 // Otherwise, create the module.
626 TheModule = new Module(ModuleID);
628 SmallVector<uint64_t, 64> Record;
629 std::vector<std::string> SectionTable;
631 // Read all the records for this module.
632 while (!Stream.AtEndOfStream()) {
633 unsigned Code = Stream.ReadCode();
634 if (Code == bitc::END_BLOCK) {
635 if (!GlobalInits.empty())
636 return Error("Malformed global initializer set");
637 return Stream.ReadBlockEnd();
640 if (Code == bitc::ENTER_SUBBLOCK) {
641 switch (Stream.ReadSubBlockID()) {
642 default: // Skip unknown content.
643 if (Stream.SkipBlock())
644 return Error("Malformed block record");
646 case bitc::TYPE_BLOCK_ID:
647 if (ParseTypeTable(Stream))
650 case bitc::TYPE_SYMTAB_BLOCK_ID:
651 if (ParseTypeSymbolTable(Stream))
654 case bitc::VALUE_SYMTAB_BLOCK_ID:
655 if (ParseValueSymbolTable(Stream))
658 case bitc::CONSTANTS_BLOCK_ID:
659 if (ParseConstants(Stream))
666 if (Code == bitc::DEFINE_ABBREV) {
667 Stream.ReadAbbrevRecord();
672 switch (Stream.ReadRecord(Code, Record)) {
673 default: break; // Default behavior, ignore unknown content.
674 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
675 if (Record.size() < 1)
676 return Error("Malformed MODULE_CODE_VERSION");
677 // Only version #0 is supported so far.
679 return Error("Unknown bitstream version!");
681 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
683 if (ConvertToString(Record, 0, S))
684 return Error("Invalid MODULE_CODE_TRIPLE record");
685 TheModule->setTargetTriple(S);
688 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
690 if (ConvertToString(Record, 0, S))
691 return Error("Invalid MODULE_CODE_DATALAYOUT record");
692 TheModule->setDataLayout(S);
695 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
697 if (ConvertToString(Record, 0, S))
698 return Error("Invalid MODULE_CODE_ASM record");
699 TheModule->setModuleInlineAsm(S);
702 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
704 if (ConvertToString(Record, 0, S))
705 return Error("Invalid MODULE_CODE_DEPLIB record");
706 TheModule->addLibrary(S);
709 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
711 if (ConvertToString(Record, 0, S))
712 return Error("Invalid MODULE_CODE_SECTIONNAME record");
713 SectionTable.push_back(S);
716 // GLOBALVAR: [type, isconst, initid,
717 // linkage, alignment, section, visibility, threadlocal]
718 case bitc::MODULE_CODE_GLOBALVAR: {
719 if (Record.size() < 6)
720 return Error("Invalid MODULE_CODE_GLOBALVAR record");
721 const Type *Ty = getTypeByID(Record[0]);
722 if (!isa<PointerType>(Ty))
723 return Error("Global not a pointer type!");
724 Ty = cast<PointerType>(Ty)->getElementType();
726 bool isConstant = Record[1];
727 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
728 unsigned Alignment = (1 << Record[4]) >> 1;
731 if (Record[5]-1 >= SectionTable.size())
732 return Error("Invalid section ID");
733 Section = SectionTable[Record[5]-1];
735 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
736 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
737 bool isThreadLocal = false;
738 if (Record.size() >= 7) isThreadLocal = Record[7];
740 GlobalVariable *NewGV =
741 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
742 NewGV->setAlignment(Alignment);
743 if (!Section.empty())
744 NewGV->setSection(Section);
745 NewGV->setVisibility(Visibility);
746 NewGV->setThreadLocal(isThreadLocal);
748 ValueList.push_back(NewGV);
750 // Remember which value to use for the global initializer.
751 if (unsigned InitID = Record[2])
752 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
755 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
757 case bitc::MODULE_CODE_FUNCTION: {
758 if (Record.size() < 7)
759 return Error("Invalid MODULE_CODE_FUNCTION record");
760 const Type *Ty = getTypeByID(Record[0]);
761 if (!isa<PointerType>(Ty))
762 return Error("Function not a pointer type!");
763 const FunctionType *FTy =
764 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
766 return Error("Function not a pointer to function type!");
768 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
771 Func->setCallingConv(Record[1]);
772 Func->setLinkage(GetDecodedLinkage(Record[3]));
773 Func->setAlignment((1 << Record[4]) >> 1);
775 if (Record[5]-1 >= SectionTable.size())
776 return Error("Invalid section ID");
777 Func->setSection(SectionTable[Record[5]-1]);
779 Func->setVisibility(GetDecodedVisibility(Record[6]));
781 ValueList.push_back(Func);
782 // TODO: remember initializer/global pair for later substitution.
789 return Error("Premature end of bitstream");
793 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
794 const std::string &ModuleID) {
798 return Error("Bitcode stream should be a multiple of 4 bytes in length");
800 BitstreamReader Stream(Buf, Buf+Length);
802 // Sniff for the signature.
803 if (Stream.Read(8) != 'B' ||
804 Stream.Read(8) != 'C' ||
805 Stream.Read(4) != 0x0 ||
806 Stream.Read(4) != 0xC ||
807 Stream.Read(4) != 0xE ||
808 Stream.Read(4) != 0xD)
809 return Error("Invalid bitcode signature");
811 // We expect a number of well-defined blocks, though we don't necessarily
812 // need to understand them all.
813 while (!Stream.AtEndOfStream()) {
814 unsigned Code = Stream.ReadCode();
816 if (Code != bitc::ENTER_SUBBLOCK)
817 return Error("Invalid record at top-level");
819 unsigned BlockID = Stream.ReadSubBlockID();
821 // We only know the MODULE subblock ID.
822 if (BlockID == bitc::MODULE_BLOCK_ID) {
823 if (ParseModule(Stream, ModuleID))
825 } else if (Stream.SkipBlock()) {
826 return Error("Malformed block record");