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 if (Stream.ReadBlockEnd())
165 return Error("Error at end of type table block");
169 if (Code == bitc::ENTER_SUBBLOCK) {
170 // No known subblocks, always skip them.
171 Stream.ReadSubBlockID();
172 if (Stream.SkipBlock())
173 return Error("Malformed block record");
177 if (Code == bitc::DEFINE_ABBREV) {
178 Stream.ReadAbbrevRecord();
184 const Type *ResultTy = 0;
185 switch (Stream.ReadRecord(Code, Record)) {
186 default: // Default behavior: unknown type.
189 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
190 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
191 // type list. This allows us to reserve space.
192 if (Record.size() < 1)
193 return Error("Invalid TYPE_CODE_NUMENTRY record");
194 TypeList.reserve(Record[0]);
196 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
197 // No metadata supported yet.
198 if (Record.size() < 1)
199 return Error("Invalid TYPE_CODE_META record");
202 case bitc::TYPE_CODE_VOID: // VOID
203 ResultTy = Type::VoidTy;
205 case bitc::TYPE_CODE_FLOAT: // FLOAT
206 ResultTy = Type::FloatTy;
208 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
209 ResultTy = Type::DoubleTy;
211 case bitc::TYPE_CODE_LABEL: // LABEL
212 ResultTy = Type::LabelTy;
214 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
217 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
218 if (Record.size() < 1)
219 return Error("Invalid Integer type record");
221 ResultTy = IntegerType::get(Record[0]);
223 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
224 if (Record.size() < 1)
225 return Error("Invalid POINTER type record");
226 ResultTy = PointerType::get(getTypeByID(Record[0], true));
228 case bitc::TYPE_CODE_FUNCTION: {
229 // FUNCTION: [vararg, retty, #pararms, paramty N]
230 if (Record.size() < 3 || Record.size() < Record[2]+3)
231 return Error("Invalid FUNCTION type record");
232 std::vector<const Type*> ArgTys;
233 for (unsigned i = 0, e = Record[2]; i != e; ++i)
234 ArgTys.push_back(getTypeByID(Record[3+i], true));
237 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
241 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
242 if (Record.size() < 2 || Record.size() < Record[1]+2)
243 return Error("Invalid STRUCT type record");
244 std::vector<const Type*> EltTys;
245 for (unsigned i = 0, e = Record[1]; i != e; ++i)
246 EltTys.push_back(getTypeByID(Record[2+i], true));
247 ResultTy = StructType::get(EltTys, Record[0]);
250 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
251 if (Record.size() < 2)
252 return Error("Invalid ARRAY type record");
253 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
255 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
256 if (Record.size() < 2)
257 return Error("Invalid VECTOR type record");
258 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
262 if (NumRecords == TypeList.size()) {
263 // If this is a new type slot, just append it.
264 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
266 } else if (ResultTy == 0) {
267 // Otherwise, this was forward referenced, so an opaque type was created,
268 // but the result type is actually just an opaque. Leave the one we
269 // created previously.
272 // Otherwise, this was forward referenced, so an opaque type was created.
273 // Resolve the opaque type to the real type now.
274 assert(NumRecords < TypeList.size() && "Typelist imbalance");
275 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
277 // Don't directly push the new type on the Tab. Instead we want to replace
278 // the opaque type we previously inserted with the new concrete value. The
279 // refinement from the abstract (opaque) type to the new type causes all
280 // uses of the abstract type to use the concrete type (NewTy). This will
281 // also cause the opaque type to be deleted.
282 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
284 // This should have replaced the old opaque type with the new type in the
285 // value table... or with a preexisting type that was already in the
286 // system. Let's just make sure it did.
287 assert(TypeList[NumRecords-1].get() != OldTy &&
288 "refineAbstractType didn't work!");
294 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
295 if (Stream.EnterSubBlock())
296 return Error("Malformed block record");
298 SmallVector<uint64_t, 64> Record;
300 // Read all the records for this type table.
301 std::string TypeName;
303 unsigned Code = Stream.ReadCode();
304 if (Code == bitc::END_BLOCK) {
305 if (Stream.ReadBlockEnd())
306 return Error("Error at end of type symbol table block");
310 if (Code == bitc::ENTER_SUBBLOCK) {
311 // No known subblocks, always skip them.
312 Stream.ReadSubBlockID();
313 if (Stream.SkipBlock())
314 return Error("Malformed block record");
318 if (Code == bitc::DEFINE_ABBREV) {
319 Stream.ReadAbbrevRecord();
325 switch (Stream.ReadRecord(Code, Record)) {
326 default: // Default behavior: unknown type.
328 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
329 if (ConvertToString(Record, 1, TypeName))
330 return Error("Invalid TST_ENTRY record");
331 unsigned TypeID = Record[0];
332 if (TypeID >= TypeList.size())
333 return Error("Invalid Type ID in TST_ENTRY record");
335 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
342 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
343 if (Stream.EnterSubBlock())
344 return Error("Malformed block record");
346 SmallVector<uint64_t, 64> Record;
348 // Read all the records for this value table.
349 SmallString<128> ValueName;
351 unsigned Code = Stream.ReadCode();
352 if (Code == bitc::END_BLOCK) {
353 if (Stream.ReadBlockEnd())
354 return Error("Error at end of value symbol table block");
357 if (Code == bitc::ENTER_SUBBLOCK) {
358 // No known subblocks, always skip them.
359 Stream.ReadSubBlockID();
360 if (Stream.SkipBlock())
361 return Error("Malformed block record");
365 if (Code == bitc::DEFINE_ABBREV) {
366 Stream.ReadAbbrevRecord();
372 switch (Stream.ReadRecord(Code, Record)) {
373 default: // Default behavior: unknown type.
375 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
376 if (ConvertToString(Record, 1, ValueName))
377 return Error("Invalid TST_ENTRY record");
378 unsigned ValueID = Record[0];
379 if (ValueID >= ValueList.size())
380 return Error("Invalid Value ID in VST_ENTRY record");
381 Value *V = ValueList[ValueID];
383 V->setName(&ValueName[0], ValueName.size());
390 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
391 /// the LSB for dense VBR encoding.
392 static uint64_t DecodeSignRotatedValue(uint64_t V) {
397 // There is no such thing as -0 with integers. "-0" really means MININT.
401 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
402 /// values and aliases that we can.
403 bool BitcodeReader::ResolveGlobalAndAliasInits() {
404 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
405 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
407 GlobalInitWorklist.swap(GlobalInits);
408 AliasInitWorklist.swap(AliasInits);
410 while (!GlobalInitWorklist.empty()) {
411 unsigned ValID = GlobalInitWorklist.back().second;
412 if (ValID >= ValueList.size()) {
413 // Not ready to resolve this yet, it requires something later in the file.
414 GlobalInits.push_back(GlobalInitWorklist.back());
416 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
417 GlobalInitWorklist.back().first->setInitializer(C);
419 return Error("Global variable initializer is not a constant!");
421 GlobalInitWorklist.pop_back();
424 while (!AliasInitWorklist.empty()) {
425 unsigned ValID = AliasInitWorklist.back().second;
426 if (ValID >= ValueList.size()) {
427 AliasInits.push_back(AliasInitWorklist.back());
429 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
430 AliasInitWorklist.back().first->setAliasee(C);
432 return Error("Alias initializer is not a constant!");
434 AliasInitWorklist.pop_back();
440 bool BitcodeReader::ParseConstants(BitstreamReader &Stream) {
441 if (Stream.EnterSubBlock())
442 return Error("Malformed block record");
444 SmallVector<uint64_t, 64> Record;
446 // Read all the records for this value table.
447 const Type *CurTy = Type::Int32Ty;
448 unsigned NextCstNo = ValueList.size();
450 unsigned Code = Stream.ReadCode();
451 if (Code == bitc::END_BLOCK) {
452 if (NextCstNo != ValueList.size())
453 return Error("Invalid constant reference!");
455 if (Stream.ReadBlockEnd())
456 return Error("Error at end of constants block");
460 if (Code == bitc::ENTER_SUBBLOCK) {
461 // No known subblocks, always skip them.
462 Stream.ReadSubBlockID();
463 if (Stream.SkipBlock())
464 return Error("Malformed block record");
468 if (Code == bitc::DEFINE_ABBREV) {
469 Stream.ReadAbbrevRecord();
476 switch (Stream.ReadRecord(Code, Record)) {
477 default: // Default behavior: unknown constant
478 case bitc::CST_CODE_UNDEF: // UNDEF
479 V = UndefValue::get(CurTy);
481 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
483 return Error("Malformed CST_SETTYPE record");
484 if (Record[0] >= TypeList.size())
485 return Error("Invalid Type ID in CST_SETTYPE record");
486 CurTy = TypeList[Record[0]];
487 continue; // Skip the ValueList manipulation.
488 case bitc::CST_CODE_NULL: // NULL
489 V = Constant::getNullValue(CurTy);
491 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
492 if (!isa<IntegerType>(CurTy) || Record.empty())
493 return Error("Invalid CST_INTEGER record");
494 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
496 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
497 if (!isa<IntegerType>(CurTy) || Record.empty() ||
498 Record.size() < Record[0]+1)
499 return Error("Invalid WIDE_INTEGER record");
501 unsigned NumWords = Record[0];
502 SmallVector<uint64_t, 8> Words;
503 Words.resize(NumWords);
504 for (unsigned i = 0; i != NumWords; ++i)
505 Words[i] = DecodeSignRotatedValue(Record[i+1]);
506 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
507 NumWords, &Words[0]));
510 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
512 return Error("Invalid FLOAT record");
513 if (CurTy == Type::FloatTy)
514 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
515 else if (CurTy == Type::DoubleTy)
516 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
518 V = UndefValue::get(CurTy);
521 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
522 if (Record.empty() || Record.size() < Record[0]+1)
523 return Error("Invalid CST_AGGREGATE record");
525 unsigned Size = Record[0];
526 std::vector<Constant*> Elts;
528 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
529 for (unsigned i = 0; i != Size; ++i)
530 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
531 STy->getElementType(i)));
532 V = ConstantStruct::get(STy, Elts);
533 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
534 const Type *EltTy = ATy->getElementType();
535 for (unsigned i = 0; i != Size; ++i)
536 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
537 V = ConstantArray::get(ATy, Elts);
538 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
539 const Type *EltTy = VTy->getElementType();
540 for (unsigned i = 0; i != Size; ++i)
541 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
542 V = ConstantVector::get(Elts);
544 V = UndefValue::get(CurTy);
549 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
550 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
551 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
553 V = UndefValue::get(CurTy); // Unknown binop.
555 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
556 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
557 V = ConstantExpr::get(Opc, LHS, RHS);
561 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
562 if (Record.size() < 3) return Error("Invalid CE_CAST record");
563 int Opc = GetDecodedCastOpcode(Record[0]);
565 V = UndefValue::get(CurTy); // Unknown cast.
567 const Type *OpTy = getTypeByID(Record[1]);
568 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
569 V = ConstantExpr::getCast(Opc, Op, CurTy);
573 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
574 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
575 SmallVector<Constant*, 16> Elts;
576 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
577 const Type *ElTy = getTypeByID(Record[i]);
578 if (!ElTy) return Error("Invalid CE_GEP record");
579 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
581 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
584 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
585 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
586 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
588 ValueList.getConstantFwdRef(Record[1],CurTy),
589 ValueList.getConstantFwdRef(Record[2],CurTy));
591 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
592 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
593 const VectorType *OpTy =
594 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
595 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
596 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
597 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
598 OpTy->getElementType());
599 V = ConstantExpr::getExtractElement(Op0, Op1);
602 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
603 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
604 if (Record.size() < 3 || OpTy == 0)
605 return Error("Invalid CE_INSERTELT record");
606 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
607 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
608 OpTy->getElementType());
609 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
610 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
613 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
614 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
615 if (Record.size() < 3 || OpTy == 0)
616 return Error("Invalid CE_INSERTELT record");
617 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
618 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
619 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
620 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
621 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
624 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
625 if (Record.size() < 4) return Error("Invalid CE_CMP record");
626 const Type *OpTy = getTypeByID(Record[0]);
627 if (OpTy == 0) return Error("Invalid CE_CMP record");
628 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
629 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
631 if (OpTy->isFloatingPoint())
632 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
634 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
639 if (NextCstNo == ValueList.size())
640 ValueList.push_back(V);
641 else if (ValueList[NextCstNo] == 0)
642 ValueList.initVal(NextCstNo, V);
644 // If there was a forward reference to this constant,
645 Value *OldV = ValueList[NextCstNo];
646 ValueList.setOperand(NextCstNo, V);
647 OldV->replaceAllUsesWith(V);
655 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
656 const std::string &ModuleID) {
657 // Reject multiple MODULE_BLOCK's in a single bitstream.
659 return Error("Multiple MODULE_BLOCKs in same stream");
661 if (Stream.EnterSubBlock())
662 return Error("Malformed block record");
664 // Otherwise, create the module.
665 TheModule = new Module(ModuleID);
667 SmallVector<uint64_t, 64> Record;
668 std::vector<std::string> SectionTable;
670 // Read all the records for this module.
671 while (!Stream.AtEndOfStream()) {
672 unsigned Code = Stream.ReadCode();
673 if (Code == bitc::END_BLOCK) {
674 ResolveGlobalAndAliasInits();
675 if (!GlobalInits.empty() || !AliasInits.empty())
676 return Error("Malformed global initializer set");
677 if (Stream.ReadBlockEnd())
678 return Error("Error at end of module block");
682 if (Code == bitc::ENTER_SUBBLOCK) {
683 switch (Stream.ReadSubBlockID()) {
684 default: // Skip unknown content.
685 if (Stream.SkipBlock())
686 return Error("Malformed block record");
688 case bitc::TYPE_BLOCK_ID:
689 if (ParseTypeTable(Stream))
692 case bitc::TYPE_SYMTAB_BLOCK_ID:
693 if (ParseTypeSymbolTable(Stream))
696 case bitc::VALUE_SYMTAB_BLOCK_ID:
697 if (ParseValueSymbolTable(Stream))
700 case bitc::CONSTANTS_BLOCK_ID:
701 if (ParseConstants(Stream) || ResolveGlobalAndAliasInits())
708 if (Code == bitc::DEFINE_ABBREV) {
709 Stream.ReadAbbrevRecord();
714 switch (Stream.ReadRecord(Code, Record)) {
715 default: break; // Default behavior, ignore unknown content.
716 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
717 if (Record.size() < 1)
718 return Error("Malformed MODULE_CODE_VERSION");
719 // Only version #0 is supported so far.
721 return Error("Unknown bitstream version!");
723 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
725 if (ConvertToString(Record, 0, S))
726 return Error("Invalid MODULE_CODE_TRIPLE record");
727 TheModule->setTargetTriple(S);
730 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
732 if (ConvertToString(Record, 0, S))
733 return Error("Invalid MODULE_CODE_DATALAYOUT record");
734 TheModule->setDataLayout(S);
737 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
739 if (ConvertToString(Record, 0, S))
740 return Error("Invalid MODULE_CODE_ASM record");
741 TheModule->setModuleInlineAsm(S);
744 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
746 if (ConvertToString(Record, 0, S))
747 return Error("Invalid MODULE_CODE_DEPLIB record");
748 TheModule->addLibrary(S);
751 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
753 if (ConvertToString(Record, 0, S))
754 return Error("Invalid MODULE_CODE_SECTIONNAME record");
755 SectionTable.push_back(S);
758 // GLOBALVAR: [type, isconst, initid,
759 // linkage, alignment, section, visibility, threadlocal]
760 case bitc::MODULE_CODE_GLOBALVAR: {
761 if (Record.size() < 6)
762 return Error("Invalid MODULE_CODE_GLOBALVAR record");
763 const Type *Ty = getTypeByID(Record[0]);
764 if (!isa<PointerType>(Ty))
765 return Error("Global not a pointer type!");
766 Ty = cast<PointerType>(Ty)->getElementType();
768 bool isConstant = Record[1];
769 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
770 unsigned Alignment = (1 << Record[4]) >> 1;
773 if (Record[5]-1 >= SectionTable.size())
774 return Error("Invalid section ID");
775 Section = SectionTable[Record[5]-1];
777 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
778 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
779 bool isThreadLocal = false;
780 if (Record.size() >= 7) isThreadLocal = Record[7];
782 GlobalVariable *NewGV =
783 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
784 NewGV->setAlignment(Alignment);
785 if (!Section.empty())
786 NewGV->setSection(Section);
787 NewGV->setVisibility(Visibility);
788 NewGV->setThreadLocal(isThreadLocal);
790 ValueList.push_back(NewGV);
792 // Remember which value to use for the global initializer.
793 if (unsigned InitID = Record[2])
794 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
797 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
799 case bitc::MODULE_CODE_FUNCTION: {
800 if (Record.size() < 7)
801 return Error("Invalid MODULE_CODE_FUNCTION record");
802 const Type *Ty = getTypeByID(Record[0]);
803 if (!isa<PointerType>(Ty))
804 return Error("Function not a pointer type!");
805 const FunctionType *FTy =
806 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
808 return Error("Function not a pointer to function type!");
810 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
813 Func->setCallingConv(Record[1]);
814 Func->setLinkage(GetDecodedLinkage(Record[3]));
815 Func->setAlignment((1 << Record[4]) >> 1);
817 if (Record[5]-1 >= SectionTable.size())
818 return Error("Invalid section ID");
819 Func->setSection(SectionTable[Record[5]-1]);
821 Func->setVisibility(GetDecodedVisibility(Record[6]));
823 ValueList.push_back(Func);
826 // ALIAS: [alias type, aliasee val#, linkage]
827 case bitc::MODULE_CODE_ALIAS: {
828 if (Record.size() < 3)
829 return Error("Invalid MODULE_ALIAS record");
830 const Type *Ty = getTypeByID(Record[0]);
831 if (!isa<PointerType>(Ty))
832 return Error("Function not a pointer type!");
834 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
836 ValueList.push_back(NewGA);
837 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
840 /// MODULE_CODE_PURGEVALS: [numvals]
841 case bitc::MODULE_CODE_PURGEVALS:
842 // Trim down the value list to the specified size.
843 if (Record.size() < 1 || Record[0] > ValueList.size())
844 return Error("Invalid MODULE_PURGEVALS record");
845 ValueList.shrinkTo(Record[0]);
851 return Error("Premature end of bitstream");
855 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
856 const std::string &ModuleID) {
860 return Error("Bitcode stream should be a multiple of 4 bytes in length");
862 BitstreamReader Stream(Buf, Buf+Length);
864 // Sniff for the signature.
865 if (Stream.Read(8) != 'B' ||
866 Stream.Read(8) != 'C' ||
867 Stream.Read(4) != 0x0 ||
868 Stream.Read(4) != 0xC ||
869 Stream.Read(4) != 0xE ||
870 Stream.Read(4) != 0xD)
871 return Error("Invalid bitcode signature");
873 // We expect a number of well-defined blocks, though we don't necessarily
874 // need to understand them all.
875 while (!Stream.AtEndOfStream()) {
876 unsigned Code = Stream.ReadCode();
878 if (Code != bitc::ENTER_SUBBLOCK)
879 return Error("Invalid record at top-level");
881 unsigned BlockID = Stream.ReadSubBlockID();
883 // We only know the MODULE subblock ID.
884 if (BlockID == bitc::MODULE_BLOCK_ID) {
885 if (ParseModule(Stream, ModuleID))
887 } else if (Stream.SkipBlock()) {
888 return Error("Malformed block record");