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 "llvm/Bitcode/ReaderWriter.h"
15 #include "BitcodeReader.h"
16 #include "llvm/Bitcode/BitstreamReader.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/MemoryBuffer.h"
25 BitcodeReader::~BitcodeReader() {
30 /// ConvertToString - Convert a string from a record into an std::string, return
32 template<typename StrTy>
33 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
35 if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
38 for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
39 Result += (char)Record[Idx+i+1];
43 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
45 default: // Map unknown/new linkages to external
46 case 0: return GlobalValue::ExternalLinkage;
47 case 1: return GlobalValue::WeakLinkage;
48 case 2: return GlobalValue::AppendingLinkage;
49 case 3: return GlobalValue::InternalLinkage;
50 case 4: return GlobalValue::LinkOnceLinkage;
51 case 5: return GlobalValue::DLLImportLinkage;
52 case 6: return GlobalValue::DLLExportLinkage;
53 case 7: return GlobalValue::ExternalWeakLinkage;
57 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
59 default: // Map unknown visibilities to default.
60 case 0: return GlobalValue::DefaultVisibility;
61 case 1: return GlobalValue::HiddenVisibility;
62 case 2: return GlobalValue::ProtectedVisibility;
66 static int GetDecodedCastOpcode(unsigned Val) {
69 case bitc::CAST_TRUNC : return Instruction::Trunc;
70 case bitc::CAST_ZEXT : return Instruction::ZExt;
71 case bitc::CAST_SEXT : return Instruction::SExt;
72 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
73 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
74 case bitc::CAST_UITOFP : return Instruction::UIToFP;
75 case bitc::CAST_SITOFP : return Instruction::SIToFP;
76 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
77 case bitc::CAST_FPEXT : return Instruction::FPExt;
78 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
79 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
80 case bitc::CAST_BITCAST : return Instruction::BitCast;
83 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
86 case bitc::BINOP_ADD: return Instruction::Add;
87 case bitc::BINOP_SUB: return Instruction::Sub;
88 case bitc::BINOP_MUL: return Instruction::Mul;
89 case bitc::BINOP_UDIV: return Instruction::UDiv;
90 case bitc::BINOP_SDIV:
91 return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
92 case bitc::BINOP_UREM: return Instruction::URem;
93 case bitc::BINOP_SREM:
94 return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
95 case bitc::BINOP_SHL: return Instruction::Shl;
96 case bitc::BINOP_LSHR: return Instruction::LShr;
97 case bitc::BINOP_ASHR: return Instruction::AShr;
98 case bitc::BINOP_AND: return Instruction::And;
99 case bitc::BINOP_OR: return Instruction::Or;
100 case bitc::BINOP_XOR: return Instruction::Xor;
106 /// @brief A class for maintaining the slot number definition
107 /// as a placeholder for the actual definition for forward constants defs.
108 class ConstantPlaceHolder : public ConstantExpr {
109 ConstantPlaceHolder(); // DO NOT IMPLEMENT
110 void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
113 ConstantPlaceHolder(const Type *Ty)
114 : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
115 Op(UndefValue::get(Type::Int32Ty), this) {
120 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
123 // Insert a bunch of null values.
125 OperandList = &Uses[0];
130 assert(Ty == getOperand(Idx)->getType() &&
131 "Type mismatch in constant table!");
132 return cast<Constant>(getOperand(Idx));
135 // Create and return a placeholder, which will later be RAUW'd.
136 Constant *C = new ConstantPlaceHolder(Ty);
137 Uses[Idx].init(C, this);
142 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
143 // If the TypeID is in range, return it.
144 if (ID < TypeList.size())
145 return TypeList[ID].get();
146 if (!isTypeTable) return 0;
148 // The type table allows forward references. Push as many Opaque types as
149 // needed to get up to ID.
150 while (TypeList.size() <= ID)
151 TypeList.push_back(OpaqueType::get());
152 return TypeList.back().get();
156 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
157 if (Stream.EnterSubBlock())
158 return Error("Malformed block record");
160 if (!TypeList.empty())
161 return Error("Multiple TYPE_BLOCKs found!");
163 SmallVector<uint64_t, 64> Record;
164 unsigned NumRecords = 0;
166 // Read all the records for this type table.
168 unsigned Code = Stream.ReadCode();
169 if (Code == bitc::END_BLOCK) {
170 if (NumRecords != TypeList.size())
171 return Error("Invalid type forward reference in TYPE_BLOCK");
172 if (Stream.ReadBlockEnd())
173 return Error("Error at end of type table block");
177 if (Code == bitc::ENTER_SUBBLOCK) {
178 // No known subblocks, always skip them.
179 Stream.ReadSubBlockID();
180 if (Stream.SkipBlock())
181 return Error("Malformed block record");
185 if (Code == bitc::DEFINE_ABBREV) {
186 Stream.ReadAbbrevRecord();
192 const Type *ResultTy = 0;
193 switch (Stream.ReadRecord(Code, Record)) {
194 default: // Default behavior: unknown type.
197 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
198 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
199 // type list. This allows us to reserve space.
200 if (Record.size() < 1)
201 return Error("Invalid TYPE_CODE_NUMENTRY record");
202 TypeList.reserve(Record[0]);
204 case bitc::TYPE_CODE_META: // TYPE_CODE_META: [metacode]...
205 // No metadata supported yet.
206 if (Record.size() < 1)
207 return Error("Invalid TYPE_CODE_META record");
210 case bitc::TYPE_CODE_VOID: // VOID
211 ResultTy = Type::VoidTy;
213 case bitc::TYPE_CODE_FLOAT: // FLOAT
214 ResultTy = Type::FloatTy;
216 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
217 ResultTy = Type::DoubleTy;
219 case bitc::TYPE_CODE_LABEL: // LABEL
220 ResultTy = Type::LabelTy;
222 case bitc::TYPE_CODE_OPAQUE: // OPAQUE
225 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
226 if (Record.size() < 1)
227 return Error("Invalid Integer type record");
229 ResultTy = IntegerType::get(Record[0]);
231 case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
232 if (Record.size() < 1)
233 return Error("Invalid POINTER type record");
234 ResultTy = PointerType::get(getTypeByID(Record[0], true));
236 case bitc::TYPE_CODE_FUNCTION: {
237 // FUNCTION: [vararg, retty, #pararms, paramty N]
238 if (Record.size() < 3 || Record.size() < Record[2]+3)
239 return Error("Invalid FUNCTION type record");
240 std::vector<const Type*> ArgTys;
241 for (unsigned i = 0, e = Record[2]; i != e; ++i)
242 ArgTys.push_back(getTypeByID(Record[3+i], true));
245 ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
249 case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
250 if (Record.size() < 2 || Record.size() < Record[1]+2)
251 return Error("Invalid STRUCT type record");
252 std::vector<const Type*> EltTys;
253 for (unsigned i = 0, e = Record[1]; i != e; ++i)
254 EltTys.push_back(getTypeByID(Record[2+i], true));
255 ResultTy = StructType::get(EltTys, Record[0]);
258 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
259 if (Record.size() < 2)
260 return Error("Invalid ARRAY type record");
261 ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
263 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
264 if (Record.size() < 2)
265 return Error("Invalid VECTOR type record");
266 ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
270 if (NumRecords == TypeList.size()) {
271 // If this is a new type slot, just append it.
272 TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
274 } else if (ResultTy == 0) {
275 // Otherwise, this was forward referenced, so an opaque type was created,
276 // but the result type is actually just an opaque. Leave the one we
277 // created previously.
280 // Otherwise, this was forward referenced, so an opaque type was created.
281 // Resolve the opaque type to the real type now.
282 assert(NumRecords < TypeList.size() && "Typelist imbalance");
283 const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
285 // Don't directly push the new type on the Tab. Instead we want to replace
286 // the opaque type we previously inserted with the new concrete value. The
287 // refinement from the abstract (opaque) type to the new type causes all
288 // uses of the abstract type to use the concrete type (NewTy). This will
289 // also cause the opaque type to be deleted.
290 const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
292 // This should have replaced the old opaque type with the new type in the
293 // value table... or with a preexisting type that was already in the
294 // system. Let's just make sure it did.
295 assert(TypeList[NumRecords-1].get() != OldTy &&
296 "refineAbstractType didn't work!");
302 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
303 if (Stream.EnterSubBlock())
304 return Error("Malformed block record");
306 SmallVector<uint64_t, 64> Record;
308 // Read all the records for this type table.
309 std::string TypeName;
311 unsigned Code = Stream.ReadCode();
312 if (Code == bitc::END_BLOCK) {
313 if (Stream.ReadBlockEnd())
314 return Error("Error at end of type symbol table block");
318 if (Code == bitc::ENTER_SUBBLOCK) {
319 // No known subblocks, always skip them.
320 Stream.ReadSubBlockID();
321 if (Stream.SkipBlock())
322 return Error("Malformed block record");
326 if (Code == bitc::DEFINE_ABBREV) {
327 Stream.ReadAbbrevRecord();
333 switch (Stream.ReadRecord(Code, Record)) {
334 default: // Default behavior: unknown type.
336 case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
337 if (ConvertToString(Record, 1, TypeName))
338 return Error("Invalid TST_ENTRY record");
339 unsigned TypeID = Record[0];
340 if (TypeID >= TypeList.size())
341 return Error("Invalid Type ID in TST_ENTRY record");
343 TheModule->addTypeName(TypeName, TypeList[TypeID].get());
350 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
351 if (Stream.EnterSubBlock())
352 return Error("Malformed block record");
354 SmallVector<uint64_t, 64> Record;
356 // Read all the records for this value table.
357 SmallString<128> ValueName;
359 unsigned Code = Stream.ReadCode();
360 if (Code == bitc::END_BLOCK) {
361 if (Stream.ReadBlockEnd())
362 return Error("Error at end of value symbol table block");
365 if (Code == bitc::ENTER_SUBBLOCK) {
366 // No known subblocks, always skip them.
367 Stream.ReadSubBlockID();
368 if (Stream.SkipBlock())
369 return Error("Malformed block record");
373 if (Code == bitc::DEFINE_ABBREV) {
374 Stream.ReadAbbrevRecord();
380 switch (Stream.ReadRecord(Code, Record)) {
381 default: // Default behavior: unknown type.
383 case bitc::TST_CODE_ENTRY: // VST_ENTRY: [valueid, namelen, namechar x N]
384 if (ConvertToString(Record, 1, ValueName))
385 return Error("Invalid TST_ENTRY record");
386 unsigned ValueID = Record[0];
387 if (ValueID >= ValueList.size())
388 return Error("Invalid Value ID in VST_ENTRY record");
389 Value *V = ValueList[ValueID];
391 V->setName(&ValueName[0], ValueName.size());
398 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
399 /// the LSB for dense VBR encoding.
400 static uint64_t DecodeSignRotatedValue(uint64_t V) {
405 // There is no such thing as -0 with integers. "-0" really means MININT.
409 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
410 /// values and aliases that we can.
411 bool BitcodeReader::ResolveGlobalAndAliasInits() {
412 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
413 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
415 GlobalInitWorklist.swap(GlobalInits);
416 AliasInitWorklist.swap(AliasInits);
418 while (!GlobalInitWorklist.empty()) {
419 unsigned ValID = GlobalInitWorklist.back().second;
420 if (ValID >= ValueList.size()) {
421 // Not ready to resolve this yet, it requires something later in the file.
422 GlobalInits.push_back(GlobalInitWorklist.back());
424 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
425 GlobalInitWorklist.back().first->setInitializer(C);
427 return Error("Global variable initializer is not a constant!");
429 GlobalInitWorklist.pop_back();
432 while (!AliasInitWorklist.empty()) {
433 unsigned ValID = AliasInitWorklist.back().second;
434 if (ValID >= ValueList.size()) {
435 AliasInits.push_back(AliasInitWorklist.back());
437 if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
438 AliasInitWorklist.back().first->setAliasee(C);
440 return Error("Alias initializer is not a constant!");
442 AliasInitWorklist.pop_back();
448 bool BitcodeReader::ParseConstants(BitstreamReader &Stream) {
449 if (Stream.EnterSubBlock())
450 return Error("Malformed block record");
452 SmallVector<uint64_t, 64> Record;
454 // Read all the records for this value table.
455 const Type *CurTy = Type::Int32Ty;
456 unsigned NextCstNo = ValueList.size();
458 unsigned Code = Stream.ReadCode();
459 if (Code == bitc::END_BLOCK) {
460 if (NextCstNo != ValueList.size())
461 return Error("Invalid constant reference!");
463 if (Stream.ReadBlockEnd())
464 return Error("Error at end of constants block");
468 if (Code == bitc::ENTER_SUBBLOCK) {
469 // No known subblocks, always skip them.
470 Stream.ReadSubBlockID();
471 if (Stream.SkipBlock())
472 return Error("Malformed block record");
476 if (Code == bitc::DEFINE_ABBREV) {
477 Stream.ReadAbbrevRecord();
484 switch (Stream.ReadRecord(Code, Record)) {
485 default: // Default behavior: unknown constant
486 case bitc::CST_CODE_UNDEF: // UNDEF
487 V = UndefValue::get(CurTy);
489 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
491 return Error("Malformed CST_SETTYPE record");
492 if (Record[0] >= TypeList.size())
493 return Error("Invalid Type ID in CST_SETTYPE record");
494 CurTy = TypeList[Record[0]];
495 continue; // Skip the ValueList manipulation.
496 case bitc::CST_CODE_NULL: // NULL
497 V = Constant::getNullValue(CurTy);
499 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
500 if (!isa<IntegerType>(CurTy) || Record.empty())
501 return Error("Invalid CST_INTEGER record");
502 V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
504 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
505 if (!isa<IntegerType>(CurTy) || Record.empty() ||
506 Record.size() < Record[0]+1)
507 return Error("Invalid WIDE_INTEGER record");
509 unsigned NumWords = Record[0];
510 SmallVector<uint64_t, 8> Words;
511 Words.resize(NumWords);
512 for (unsigned i = 0; i != NumWords; ++i)
513 Words[i] = DecodeSignRotatedValue(Record[i+1]);
514 V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
515 NumWords, &Words[0]));
518 case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
520 return Error("Invalid FLOAT record");
521 if (CurTy == Type::FloatTy)
522 V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
523 else if (CurTy == Type::DoubleTy)
524 V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
526 V = UndefValue::get(CurTy);
529 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
530 if (Record.empty() || Record.size() < Record[0]+1)
531 return Error("Invalid CST_AGGREGATE record");
533 unsigned Size = Record[0];
534 std::vector<Constant*> Elts;
536 if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
537 for (unsigned i = 0; i != Size; ++i)
538 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
539 STy->getElementType(i)));
540 V = ConstantStruct::get(STy, Elts);
541 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
542 const Type *EltTy = ATy->getElementType();
543 for (unsigned i = 0; i != Size; ++i)
544 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
545 V = ConstantArray::get(ATy, Elts);
546 } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
547 const Type *EltTy = VTy->getElementType();
548 for (unsigned i = 0; i != Size; ++i)
549 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
550 V = ConstantVector::get(Elts);
552 V = UndefValue::get(CurTy);
557 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
558 if (Record.size() < 3) return Error("Invalid CE_BINOP record");
559 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
561 V = UndefValue::get(CurTy); // Unknown binop.
563 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
564 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
565 V = ConstantExpr::get(Opc, LHS, RHS);
569 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
570 if (Record.size() < 3) return Error("Invalid CE_CAST record");
571 int Opc = GetDecodedCastOpcode(Record[0]);
573 V = UndefValue::get(CurTy); // Unknown cast.
575 const Type *OpTy = getTypeByID(Record[1]);
576 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
577 V = ConstantExpr::getCast(Opc, Op, CurTy);
581 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
582 if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
583 SmallVector<Constant*, 16> Elts;
584 for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
585 const Type *ElTy = getTypeByID(Record[i]);
586 if (!ElTy) return Error("Invalid CE_GEP record");
587 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
589 V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
592 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
593 if (Record.size() < 3) return Error("Invalid CE_SELECT record");
594 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
596 ValueList.getConstantFwdRef(Record[1],CurTy),
597 ValueList.getConstantFwdRef(Record[2],CurTy));
599 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
600 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
601 const VectorType *OpTy =
602 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
603 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
604 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
605 Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
606 OpTy->getElementType());
607 V = ConstantExpr::getExtractElement(Op0, Op1);
610 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
611 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
612 if (Record.size() < 3 || OpTy == 0)
613 return Error("Invalid CE_INSERTELT record");
614 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
615 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
616 OpTy->getElementType());
617 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
618 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
621 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
622 const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
623 if (Record.size() < 3 || OpTy == 0)
624 return Error("Invalid CE_INSERTELT record");
625 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
626 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
627 const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
628 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
629 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
632 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
633 if (Record.size() < 4) return Error("Invalid CE_CMP record");
634 const Type *OpTy = getTypeByID(Record[0]);
635 if (OpTy == 0) return Error("Invalid CE_CMP record");
636 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
637 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
639 if (OpTy->isFloatingPoint())
640 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
642 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
647 if (NextCstNo == ValueList.size())
648 ValueList.push_back(V);
649 else if (ValueList[NextCstNo] == 0)
650 ValueList.initVal(NextCstNo, V);
652 // If there was a forward reference to this constant,
653 Value *OldV = ValueList[NextCstNo];
654 ValueList.setOperand(NextCstNo, V);
655 OldV->replaceAllUsesWith(V);
663 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
664 const std::string &ModuleID) {
665 // Reject multiple MODULE_BLOCK's in a single bitstream.
667 return Error("Multiple MODULE_BLOCKs in same stream");
669 if (Stream.EnterSubBlock())
670 return Error("Malformed block record");
672 // Otherwise, create the module.
673 TheModule = new Module(ModuleID);
675 SmallVector<uint64_t, 64> Record;
676 std::vector<std::string> SectionTable;
678 // Read all the records for this module.
679 while (!Stream.AtEndOfStream()) {
680 unsigned Code = Stream.ReadCode();
681 if (Code == bitc::END_BLOCK) {
682 ResolveGlobalAndAliasInits();
683 if (!GlobalInits.empty() || !AliasInits.empty())
684 return Error("Malformed global initializer set");
685 if (Stream.ReadBlockEnd())
686 return Error("Error at end of module block");
690 if (Code == bitc::ENTER_SUBBLOCK) {
691 switch (Stream.ReadSubBlockID()) {
692 default: // Skip unknown content.
693 if (Stream.SkipBlock())
694 return Error("Malformed block record");
696 case bitc::TYPE_BLOCK_ID:
697 if (ParseTypeTable(Stream))
700 case bitc::TYPE_SYMTAB_BLOCK_ID:
701 if (ParseTypeSymbolTable(Stream))
704 case bitc::VALUE_SYMTAB_BLOCK_ID:
705 if (ParseValueSymbolTable(Stream))
708 case bitc::CONSTANTS_BLOCK_ID:
709 if (ParseConstants(Stream) || ResolveGlobalAndAliasInits())
716 if (Code == bitc::DEFINE_ABBREV) {
717 Stream.ReadAbbrevRecord();
722 switch (Stream.ReadRecord(Code, Record)) {
723 default: break; // Default behavior, ignore unknown content.
724 case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
725 if (Record.size() < 1)
726 return Error("Malformed MODULE_CODE_VERSION");
727 // Only version #0 is supported so far.
729 return Error("Unknown bitstream version!");
731 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
733 if (ConvertToString(Record, 0, S))
734 return Error("Invalid MODULE_CODE_TRIPLE record");
735 TheModule->setTargetTriple(S);
738 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
740 if (ConvertToString(Record, 0, S))
741 return Error("Invalid MODULE_CODE_DATALAYOUT record");
742 TheModule->setDataLayout(S);
745 case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
747 if (ConvertToString(Record, 0, S))
748 return Error("Invalid MODULE_CODE_ASM record");
749 TheModule->setModuleInlineAsm(S);
752 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
754 if (ConvertToString(Record, 0, S))
755 return Error("Invalid MODULE_CODE_DEPLIB record");
756 TheModule->addLibrary(S);
759 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
761 if (ConvertToString(Record, 0, S))
762 return Error("Invalid MODULE_CODE_SECTIONNAME record");
763 SectionTable.push_back(S);
766 // GLOBALVAR: [type, isconst, initid,
767 // linkage, alignment, section, visibility, threadlocal]
768 case bitc::MODULE_CODE_GLOBALVAR: {
769 if (Record.size() < 6)
770 return Error("Invalid MODULE_CODE_GLOBALVAR record");
771 const Type *Ty = getTypeByID(Record[0]);
772 if (!isa<PointerType>(Ty))
773 return Error("Global not a pointer type!");
774 Ty = cast<PointerType>(Ty)->getElementType();
776 bool isConstant = Record[1];
777 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
778 unsigned Alignment = (1 << Record[4]) >> 1;
781 if (Record[5]-1 >= SectionTable.size())
782 return Error("Invalid section ID");
783 Section = SectionTable[Record[5]-1];
785 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
786 if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
787 bool isThreadLocal = false;
788 if (Record.size() >= 7) isThreadLocal = Record[7];
790 GlobalVariable *NewGV =
791 new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
792 NewGV->setAlignment(Alignment);
793 if (!Section.empty())
794 NewGV->setSection(Section);
795 NewGV->setVisibility(Visibility);
796 NewGV->setThreadLocal(isThreadLocal);
798 ValueList.push_back(NewGV);
800 // Remember which value to use for the global initializer.
801 if (unsigned InitID = Record[2])
802 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
805 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
807 case bitc::MODULE_CODE_FUNCTION: {
808 if (Record.size() < 7)
809 return Error("Invalid MODULE_CODE_FUNCTION record");
810 const Type *Ty = getTypeByID(Record[0]);
811 if (!isa<PointerType>(Ty))
812 return Error("Function not a pointer type!");
813 const FunctionType *FTy =
814 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
816 return Error("Function not a pointer to function type!");
818 Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
821 Func->setCallingConv(Record[1]);
822 Func->setLinkage(GetDecodedLinkage(Record[3]));
823 Func->setAlignment((1 << Record[4]) >> 1);
825 if (Record[5]-1 >= SectionTable.size())
826 return Error("Invalid section ID");
827 Func->setSection(SectionTable[Record[5]-1]);
829 Func->setVisibility(GetDecodedVisibility(Record[6]));
831 ValueList.push_back(Func);
834 // ALIAS: [alias type, aliasee val#, linkage]
835 case bitc::MODULE_CODE_ALIAS: {
836 if (Record.size() < 3)
837 return Error("Invalid MODULE_ALIAS record");
838 const Type *Ty = getTypeByID(Record[0]);
839 if (!isa<PointerType>(Ty))
840 return Error("Function not a pointer type!");
842 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
844 ValueList.push_back(NewGA);
845 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
848 /// MODULE_CODE_PURGEVALS: [numvals]
849 case bitc::MODULE_CODE_PURGEVALS:
850 // Trim down the value list to the specified size.
851 if (Record.size() < 1 || Record[0] > ValueList.size())
852 return Error("Invalid MODULE_PURGEVALS record");
853 ValueList.shrinkTo(Record[0]);
859 return Error("Premature end of bitstream");
863 bool BitcodeReader::ParseBitcode() {
866 if (Buffer->getBufferSize() & 3)
867 return Error("Bitcode stream should be a multiple of 4 bytes in length");
869 unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
870 BitstreamReader Stream(BufPtr, BufPtr+Buffer->getBufferSize());
872 // Sniff for the signature.
873 if (Stream.Read(8) != 'B' ||
874 Stream.Read(8) != 'C' ||
875 Stream.Read(4) != 0x0 ||
876 Stream.Read(4) != 0xC ||
877 Stream.Read(4) != 0xE ||
878 Stream.Read(4) != 0xD)
879 return Error("Invalid bitcode signature");
881 // We expect a number of well-defined blocks, though we don't necessarily
882 // need to understand them all.
883 while (!Stream.AtEndOfStream()) {
884 unsigned Code = Stream.ReadCode();
886 if (Code != bitc::ENTER_SUBBLOCK)
887 return Error("Invalid record at top-level");
889 unsigned BlockID = Stream.ReadSubBlockID();
891 // We only know the MODULE subblock ID.
892 if (BlockID == bitc::MODULE_BLOCK_ID) {
893 if (ParseModule(Stream, Buffer->getBufferIdentifier()))
895 } else if (Stream.SkipBlock()) {
896 return Error("Malformed block record");
903 //===----------------------------------------------------------------------===//
904 // External interface
905 //===----------------------------------------------------------------------===//
907 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
909 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
910 std::string *ErrMsg) {
911 BitcodeReader *R = new BitcodeReader(Buffer);
912 if (R->ParseBitcode()) {
914 *ErrMsg = R->getErrorString();
916 // Don't let the BitcodeReader dtor delete 'Buffer'.
917 R->releaseMemoryBuffer();
924 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
925 /// If an error occurs, return null and fill in *ErrMsg if non-null.
926 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
928 R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
931 // Read the whole module, get a pointer to it, tell ModuleProvider not to
932 // delete it when its dtor is run.
933 Module *M = R->releaseModule(ErrMsg);
935 // Don't let the BitcodeReader dtor delete 'Buffer'.
936 R->releaseMemoryBuffer();