LLVM API Documentation
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 00010 #include "llvm/Bitcode/ReaderWriter.h" 00011 #include "BitcodeReader.h" 00012 #include "llvm/ADT/SmallString.h" 00013 #include "llvm/ADT/SmallVector.h" 00014 #include "llvm/AutoUpgrade.h" 00015 #include "llvm/IR/Constants.h" 00016 #include "llvm/IR/DerivedTypes.h" 00017 #include "llvm/IR/InlineAsm.h" 00018 #include "llvm/IR/IntrinsicInst.h" 00019 #include "llvm/IR/Module.h" 00020 #include "llvm/IR/OperandTraits.h" 00021 #include "llvm/IR/Operator.h" 00022 #include "llvm/Support/DataStream.h" 00023 #include "llvm/Support/MathExtras.h" 00024 #include "llvm/Support/MemoryBuffer.h" 00025 using namespace llvm; 00026 00027 enum { 00028 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 00029 }; 00030 00031 void BitcodeReader::materializeForwardReferencedFunctions() { 00032 while (!BlockAddrFwdRefs.empty()) { 00033 Function *F = BlockAddrFwdRefs.begin()->first; 00034 F->Materialize(); 00035 } 00036 } 00037 00038 void BitcodeReader::FreeState() { 00039 if (BufferOwned) 00040 delete Buffer; 00041 Buffer = 0; 00042 std::vector<Type*>().swap(TypeList); 00043 ValueList.clear(); 00044 MDValueList.clear(); 00045 00046 std::vector<AttributeSet>().swap(MAttributes); 00047 std::vector<BasicBlock*>().swap(FunctionBBs); 00048 std::vector<Function*>().swap(FunctionsWithBodies); 00049 DeferredFunctionInfo.clear(); 00050 MDKindMap.clear(); 00051 00052 assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references"); 00053 } 00054 00055 //===----------------------------------------------------------------------===// 00056 // Helper functions to implement forward reference resolution, etc. 00057 //===----------------------------------------------------------------------===// 00058 00059 /// ConvertToString - Convert a string from a record into an std::string, return 00060 /// true on failure. 00061 template<typename StrTy> 00062 static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx, 00063 StrTy &Result) { 00064 if (Idx > Record.size()) 00065 return true; 00066 00067 for (unsigned i = Idx, e = Record.size(); i != e; ++i) 00068 Result += (char)Record[i]; 00069 return false; 00070 } 00071 00072 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) { 00073 switch (Val) { 00074 default: // Map unknown/new linkages to external 00075 case 0: return GlobalValue::ExternalLinkage; 00076 case 1: return GlobalValue::WeakAnyLinkage; 00077 case 2: return GlobalValue::AppendingLinkage; 00078 case 3: return GlobalValue::InternalLinkage; 00079 case 4: return GlobalValue::LinkOnceAnyLinkage; 00080 case 5: return GlobalValue::DLLImportLinkage; 00081 case 6: return GlobalValue::DLLExportLinkage; 00082 case 7: return GlobalValue::ExternalWeakLinkage; 00083 case 8: return GlobalValue::CommonLinkage; 00084 case 9: return GlobalValue::PrivateLinkage; 00085 case 10: return GlobalValue::WeakODRLinkage; 00086 case 11: return GlobalValue::LinkOnceODRLinkage; 00087 case 12: return GlobalValue::AvailableExternallyLinkage; 00088 case 13: return GlobalValue::LinkerPrivateLinkage; 00089 case 14: return GlobalValue::LinkerPrivateWeakLinkage; 00090 case 15: return GlobalValue::LinkOnceODRAutoHideLinkage; 00091 } 00092 } 00093 00094 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) { 00095 switch (Val) { 00096 default: // Map unknown visibilities to default. 00097 case 0: return GlobalValue::DefaultVisibility; 00098 case 1: return GlobalValue::HiddenVisibility; 00099 case 2: return GlobalValue::ProtectedVisibility; 00100 } 00101 } 00102 00103 static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) { 00104 switch (Val) { 00105 case 0: return GlobalVariable::NotThreadLocal; 00106 default: // Map unknown non-zero value to general dynamic. 00107 case 1: return GlobalVariable::GeneralDynamicTLSModel; 00108 case 2: return GlobalVariable::LocalDynamicTLSModel; 00109 case 3: return GlobalVariable::InitialExecTLSModel; 00110 case 4: return GlobalVariable::LocalExecTLSModel; 00111 } 00112 } 00113 00114 static int GetDecodedCastOpcode(unsigned Val) { 00115 switch (Val) { 00116 default: return -1; 00117 case bitc::CAST_TRUNC : return Instruction::Trunc; 00118 case bitc::CAST_ZEXT : return Instruction::ZExt; 00119 case bitc::CAST_SEXT : return Instruction::SExt; 00120 case bitc::CAST_FPTOUI : return Instruction::FPToUI; 00121 case bitc::CAST_FPTOSI : return Instruction::FPToSI; 00122 case bitc::CAST_UITOFP : return Instruction::UIToFP; 00123 case bitc::CAST_SITOFP : return Instruction::SIToFP; 00124 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; 00125 case bitc::CAST_FPEXT : return Instruction::FPExt; 00126 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; 00127 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; 00128 case bitc::CAST_BITCAST : return Instruction::BitCast; 00129 } 00130 } 00131 static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) { 00132 switch (Val) { 00133 default: return -1; 00134 case bitc::BINOP_ADD: 00135 return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add; 00136 case bitc::BINOP_SUB: 00137 return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub; 00138 case bitc::BINOP_MUL: 00139 return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul; 00140 case bitc::BINOP_UDIV: return Instruction::UDiv; 00141 case bitc::BINOP_SDIV: 00142 return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv; 00143 case bitc::BINOP_UREM: return Instruction::URem; 00144 case bitc::BINOP_SREM: 00145 return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem; 00146 case bitc::BINOP_SHL: return Instruction::Shl; 00147 case bitc::BINOP_LSHR: return Instruction::LShr; 00148 case bitc::BINOP_ASHR: return Instruction::AShr; 00149 case bitc::BINOP_AND: return Instruction::And; 00150 case bitc::BINOP_OR: return Instruction::Or; 00151 case bitc::BINOP_XOR: return Instruction::Xor; 00152 } 00153 } 00154 00155 static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) { 00156 switch (Val) { 00157 default: return AtomicRMWInst::BAD_BINOP; 00158 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; 00159 case bitc::RMW_ADD: return AtomicRMWInst::Add; 00160 case bitc::RMW_SUB: return AtomicRMWInst::Sub; 00161 case bitc::RMW_AND: return AtomicRMWInst::And; 00162 case bitc::RMW_NAND: return AtomicRMWInst::Nand; 00163 case bitc::RMW_OR: return AtomicRMWInst::Or; 00164 case bitc::RMW_XOR: return AtomicRMWInst::Xor; 00165 case bitc::RMW_MAX: return AtomicRMWInst::Max; 00166 case bitc::RMW_MIN: return AtomicRMWInst::Min; 00167 case bitc::RMW_UMAX: return AtomicRMWInst::UMax; 00168 case bitc::RMW_UMIN: return AtomicRMWInst::UMin; 00169 } 00170 } 00171 00172 static AtomicOrdering GetDecodedOrdering(unsigned Val) { 00173 switch (Val) { 00174 case bitc::ORDERING_NOTATOMIC: return NotAtomic; 00175 case bitc::ORDERING_UNORDERED: return Unordered; 00176 case bitc::ORDERING_MONOTONIC: return Monotonic; 00177 case bitc::ORDERING_ACQUIRE: return Acquire; 00178 case bitc::ORDERING_RELEASE: return Release; 00179 case bitc::ORDERING_ACQREL: return AcquireRelease; 00180 default: // Map unknown orderings to sequentially-consistent. 00181 case bitc::ORDERING_SEQCST: return SequentiallyConsistent; 00182 } 00183 } 00184 00185 static SynchronizationScope GetDecodedSynchScope(unsigned Val) { 00186 switch (Val) { 00187 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread; 00188 default: // Map unknown scopes to cross-thread. 00189 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread; 00190 } 00191 } 00192 00193 namespace llvm { 00194 namespace { 00195 /// @brief A class for maintaining the slot number definition 00196 /// as a placeholder for the actual definition for forward constants defs. 00197 class ConstantPlaceHolder : public ConstantExpr { 00198 void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION; 00199 public: 00200 // allocate space for exactly one operand 00201 void *operator new(size_t s) { 00202 return User::operator new(s, 1); 00203 } 00204 explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context) 00205 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) { 00206 Op<0>() = UndefValue::get(Type::getInt32Ty(Context)); 00207 } 00208 00209 /// @brief Methods to support type inquiry through isa, cast, and dyn_cast. 00210 static bool classof(const Value *V) { 00211 return isa<ConstantExpr>(V) && 00212 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1; 00213 } 00214 00215 00216 /// Provide fast operand accessors 00217 //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value); 00218 }; 00219 } 00220 00221 // FIXME: can we inherit this from ConstantExpr? 00222 template <> 00223 struct OperandTraits<ConstantPlaceHolder> : 00224 public FixedNumOperandTraits<ConstantPlaceHolder, 1> { 00225 }; 00226 } 00227 00228 00229 void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) { 00230 if (Idx == size()) { 00231 push_back(V); 00232 return; 00233 } 00234 00235 if (Idx >= size()) 00236 resize(Idx+1); 00237 00238 WeakVH &OldV = ValuePtrs[Idx]; 00239 if (OldV == 0) { 00240 OldV = V; 00241 return; 00242 } 00243 00244 // Handle constants and non-constants (e.g. instrs) differently for 00245 // efficiency. 00246 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) { 00247 ResolveConstants.push_back(std::make_pair(PHC, Idx)); 00248 OldV = V; 00249 } else { 00250 // If there was a forward reference to this value, replace it. 00251 Value *PrevVal = OldV; 00252 OldV->replaceAllUsesWith(V); 00253 delete PrevVal; 00254 } 00255 } 00256 00257 00258 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx, 00259 Type *Ty) { 00260 if (Idx >= size()) 00261 resize(Idx + 1); 00262 00263 if (Value *V = ValuePtrs[Idx]) { 00264 assert(Ty == V->getType() && "Type mismatch in constant table!"); 00265 return cast<Constant>(V); 00266 } 00267 00268 // Create and return a placeholder, which will later be RAUW'd. 00269 Constant *C = new ConstantPlaceHolder(Ty, Context); 00270 ValuePtrs[Idx] = C; 00271 return C; 00272 } 00273 00274 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) { 00275 if (Idx >= size()) 00276 resize(Idx + 1); 00277 00278 if (Value *V = ValuePtrs[Idx]) { 00279 assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!"); 00280 return V; 00281 } 00282 00283 // No type specified, must be invalid reference. 00284 if (Ty == 0) return 0; 00285 00286 // Create and return a placeholder, which will later be RAUW'd. 00287 Value *V = new Argument(Ty); 00288 ValuePtrs[Idx] = V; 00289 return V; 00290 } 00291 00292 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk 00293 /// resolves any forward references. The idea behind this is that we sometimes 00294 /// get constants (such as large arrays) which reference *many* forward ref 00295 /// constants. Replacing each of these causes a lot of thrashing when 00296 /// building/reuniquing the constant. Instead of doing this, we look at all the 00297 /// uses and rewrite all the place holders at once for any constant that uses 00298 /// a placeholder. 00299 void BitcodeReaderValueList::ResolveConstantForwardRefs() { 00300 // Sort the values by-pointer so that they are efficient to look up with a 00301 // binary search. 00302 std::sort(ResolveConstants.begin(), ResolveConstants.end()); 00303 00304 SmallVector<Constant*, 64> NewOps; 00305 00306 while (!ResolveConstants.empty()) { 00307 Value *RealVal = operator[](ResolveConstants.back().second); 00308 Constant *Placeholder = ResolveConstants.back().first; 00309 ResolveConstants.pop_back(); 00310 00311 // Loop over all users of the placeholder, updating them to reference the 00312 // new value. If they reference more than one placeholder, update them all 00313 // at once. 00314 while (!Placeholder->use_empty()) { 00315 Value::use_iterator UI = Placeholder->use_begin(); 00316 User *U = *UI; 00317 00318 // If the using object isn't uniqued, just update the operands. This 00319 // handles instructions and initializers for global variables. 00320 if (!isa<Constant>(U) || isa<GlobalValue>(U)) { 00321 UI.getUse().set(RealVal); 00322 continue; 00323 } 00324 00325 // Otherwise, we have a constant that uses the placeholder. Replace that 00326 // constant with a new constant that has *all* placeholder uses updated. 00327 Constant *UserC = cast<Constant>(U); 00328 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end(); 00329 I != E; ++I) { 00330 Value *NewOp; 00331 if (!isa<ConstantPlaceHolder>(*I)) { 00332 // Not a placeholder reference. 00333 NewOp = *I; 00334 } else if (*I == Placeholder) { 00335 // Common case is that it just references this one placeholder. 00336 NewOp = RealVal; 00337 } else { 00338 // Otherwise, look up the placeholder in ResolveConstants. 00339 ResolveConstantsTy::iterator It = 00340 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 00341 std::pair<Constant*, unsigned>(cast<Constant>(*I), 00342 0)); 00343 assert(It != ResolveConstants.end() && It->first == *I); 00344 NewOp = operator[](It->second); 00345 } 00346 00347 NewOps.push_back(cast<Constant>(NewOp)); 00348 } 00349 00350 // Make the new constant. 00351 Constant *NewC; 00352 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) { 00353 NewC = ConstantArray::get(UserCA->getType(), NewOps); 00354 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) { 00355 NewC = ConstantStruct::get(UserCS->getType(), NewOps); 00356 } else if (isa<ConstantVector>(UserC)) { 00357 NewC = ConstantVector::get(NewOps); 00358 } else { 00359 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr."); 00360 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps); 00361 } 00362 00363 UserC->replaceAllUsesWith(NewC); 00364 UserC->destroyConstant(); 00365 NewOps.clear(); 00366 } 00367 00368 // Update all ValueHandles, they should be the only users at this point. 00369 Placeholder->replaceAllUsesWith(RealVal); 00370 delete Placeholder; 00371 } 00372 } 00373 00374 void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) { 00375 if (Idx == size()) { 00376 push_back(V); 00377 return; 00378 } 00379 00380 if (Idx >= size()) 00381 resize(Idx+1); 00382 00383 WeakVH &OldV = MDValuePtrs[Idx]; 00384 if (OldV == 0) { 00385 OldV = V; 00386 return; 00387 } 00388 00389 // If there was a forward reference to this value, replace it. 00390 MDNode *PrevVal = cast<MDNode>(OldV); 00391 OldV->replaceAllUsesWith(V); 00392 MDNode::deleteTemporary(PrevVal); 00393 // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new 00394 // value for Idx. 00395 MDValuePtrs[Idx] = V; 00396 } 00397 00398 Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) { 00399 if (Idx >= size()) 00400 resize(Idx + 1); 00401 00402 if (Value *V = MDValuePtrs[Idx]) { 00403 assert(V->getType()->isMetadataTy() && "Type mismatch in value table!"); 00404 return V; 00405 } 00406 00407 // Create and return a placeholder, which will later be RAUW'd. 00408 Value *V = MDNode::getTemporary(Context, None); 00409 MDValuePtrs[Idx] = V; 00410 return V; 00411 } 00412 00413 Type *BitcodeReader::getTypeByID(unsigned ID) { 00414 // The type table size is always specified correctly. 00415 if (ID >= TypeList.size()) 00416 return 0; 00417 00418 if (Type *Ty = TypeList[ID]) 00419 return Ty; 00420 00421 // If we have a forward reference, the only possible case is when it is to a 00422 // named struct. Just create a placeholder for now. 00423 return TypeList[ID] = StructType::create(Context); 00424 } 00425 00426 00427 //===----------------------------------------------------------------------===// 00428 // Functions for parsing blocks from the bitcode file 00429 //===----------------------------------------------------------------------===// 00430 00431 00432 /// \brief This fills an AttrBuilder object with the LLVM attributes that have 00433 /// been decoded from the given integer. This function must stay in sync with 00434 /// 'encodeLLVMAttributesForBitcode'. 00435 static void decodeLLVMAttributesForBitcode(AttrBuilder &B, 00436 uint64_t EncodedAttrs) { 00437 // FIXME: Remove in 4.0. 00438 00439 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift 00440 // the bits above 31 down by 11 bits. 00441 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16; 00442 assert((!Alignment || isPowerOf2_32(Alignment)) && 00443 "Alignment must be a power of two."); 00444 00445 if (Alignment) 00446 B.addAlignmentAttr(Alignment); 00447 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) | 00448 (EncodedAttrs & 0xffff)); 00449 } 00450 00451 bool BitcodeReader::ParseAttributeBlock() { 00452 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID)) 00453 return Error("Malformed block record"); 00454 00455 if (!MAttributes.empty()) 00456 return Error("Multiple PARAMATTR blocks found!"); 00457 00458 SmallVector<uint64_t, 64> Record; 00459 00460 SmallVector<AttributeSet, 8> Attrs; 00461 00462 // Read all the records. 00463 while (1) { 00464 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 00465 00466 switch (Entry.Kind) { 00467 case BitstreamEntry::SubBlock: // Handled for us already. 00468 case BitstreamEntry::Error: 00469 return Error("Error at end of PARAMATTR block"); 00470 case BitstreamEntry::EndBlock: 00471 return false; 00472 case BitstreamEntry::Record: 00473 // The interesting case. 00474 break; 00475 } 00476 00477 // Read a record. 00478 Record.clear(); 00479 switch (Stream.readRecord(Entry.ID, Record)) { 00480 default: // Default behavior: ignore. 00481 break; 00482 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...] 00483 // FIXME: Remove in 4.0. 00484 if (Record.size() & 1) 00485 return Error("Invalid ENTRY record"); 00486 00487 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 00488 AttrBuilder B; 00489 decodeLLVMAttributesForBitcode(B, Record[i+1]); 00490 Attrs.push_back(AttributeSet::get(Context, Record[i], B)); 00491 } 00492 00493 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 00494 Attrs.clear(); 00495 break; 00496 } 00497 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...] 00498 for (unsigned i = 0, e = Record.size(); i != e; ++i) 00499 Attrs.push_back(MAttributeGroups[Record[i]]); 00500 00501 MAttributes.push_back(AttributeSet::get(Context, Attrs)); 00502 Attrs.clear(); 00503 break; 00504 } 00505 } 00506 } 00507 } 00508 00509 bool BitcodeReader::ParseAttributeGroupBlock() { 00510 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID)) 00511 return Error("Malformed block record"); 00512 00513 if (!MAttributeGroups.empty()) 00514 return Error("Multiple PARAMATTR_GROUP blocks found!"); 00515 00516 SmallVector<uint64_t, 64> Record; 00517 00518 // Read all the records. 00519 while (1) { 00520 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 00521 00522 switch (Entry.Kind) { 00523 case BitstreamEntry::SubBlock: // Handled for us already. 00524 case BitstreamEntry::Error: 00525 return Error("Error at end of PARAMATTR_GROUP block"); 00526 case BitstreamEntry::EndBlock: 00527 return false; 00528 case BitstreamEntry::Record: 00529 // The interesting case. 00530 break; 00531 } 00532 00533 // Read a record. 00534 Record.clear(); 00535 switch (Stream.readRecord(Entry.ID, Record)) { 00536 default: // Default behavior: ignore. 00537 break; 00538 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] 00539 if (Record.size() < 3) 00540 return Error("Invalid ENTRY record"); 00541 00542 uint64_t GrpID = Record[0]; 00543 uint64_t Idx = Record[1]; // Index of the object this attribute refers to. 00544 00545 AttrBuilder B; 00546 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 00547 if (Record[i] == 0) { // Enum attribute 00548 B.addAttribute(Attribute::AttrKind(Record[++i])); 00549 } else if (Record[i] == 1) { // Align attribute 00550 if (Attribute::AttrKind(Record[++i]) == Attribute::Alignment) 00551 B.addAlignmentAttr(Record[++i]); 00552 else 00553 B.addStackAlignmentAttr(Record[++i]); 00554 } else { // String attribute 00555 assert((Record[i] == 3 || Record[i] == 4) && 00556 "Invalid attribute group entry"); 00557 bool HasValue = (Record[i++] == 4); 00558 SmallString<64> KindStr; 00559 SmallString<64> ValStr; 00560 00561 while (Record[i] != 0 && i != e) 00562 KindStr += Record[i++]; 00563 assert(Record[i] == 0 && "Kind string not null terminated"); 00564 00565 if (HasValue) { 00566 // Has a value associated with it. 00567 ++i; // Skip the '0' that terminates the "kind" string. 00568 while (Record[i] != 0 && i != e) 00569 ValStr += Record[i++]; 00570 assert(Record[i] == 0 && "Value string not null terminated"); 00571 } 00572 00573 B.addAttribute(KindStr.str(), ValStr.str()); 00574 } 00575 } 00576 00577 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B); 00578 break; 00579 } 00580 } 00581 } 00582 } 00583 00584 bool BitcodeReader::ParseTypeTable() { 00585 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW)) 00586 return Error("Malformed block record"); 00587 00588 return ParseTypeTableBody(); 00589 } 00590 00591 bool BitcodeReader::ParseTypeTableBody() { 00592 if (!TypeList.empty()) 00593 return Error("Multiple TYPE_BLOCKs found!"); 00594 00595 SmallVector<uint64_t, 64> Record; 00596 unsigned NumRecords = 0; 00597 00598 SmallString<64> TypeName; 00599 00600 // Read all the records for this type table. 00601 while (1) { 00602 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 00603 00604 switch (Entry.Kind) { 00605 case BitstreamEntry::SubBlock: // Handled for us already. 00606 case BitstreamEntry::Error: 00607 Error("Error in the type table block"); 00608 return true; 00609 case BitstreamEntry::EndBlock: 00610 if (NumRecords != TypeList.size()) 00611 return Error("Invalid type forward reference in TYPE_BLOCK"); 00612 return false; 00613 case BitstreamEntry::Record: 00614 // The interesting case. 00615 break; 00616 } 00617 00618 // Read a record. 00619 Record.clear(); 00620 Type *ResultTy = 0; 00621 switch (Stream.readRecord(Entry.ID, Record)) { 00622 default: return Error("unknown type in type table"); 00623 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] 00624 // TYPE_CODE_NUMENTRY contains a count of the number of types in the 00625 // type list. This allows us to reserve space. 00626 if (Record.size() < 1) 00627 return Error("Invalid TYPE_CODE_NUMENTRY record"); 00628 TypeList.resize(Record[0]); 00629 continue; 00630 case bitc::TYPE_CODE_VOID: // VOID 00631 ResultTy = Type::getVoidTy(Context); 00632 break; 00633 case bitc::TYPE_CODE_HALF: // HALF 00634 ResultTy = Type::getHalfTy(Context); 00635 break; 00636 case bitc::TYPE_CODE_FLOAT: // FLOAT 00637 ResultTy = Type::getFloatTy(Context); 00638 break; 00639 case bitc::TYPE_CODE_DOUBLE: // DOUBLE 00640 ResultTy = Type::getDoubleTy(Context); 00641 break; 00642 case bitc::TYPE_CODE_X86_FP80: // X86_FP80 00643 ResultTy = Type::getX86_FP80Ty(Context); 00644 break; 00645 case bitc::TYPE_CODE_FP128: // FP128 00646 ResultTy = Type::getFP128Ty(Context); 00647 break; 00648 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 00649 ResultTy = Type::getPPC_FP128Ty(Context); 00650 break; 00651 case bitc::TYPE_CODE_LABEL: // LABEL 00652 ResultTy = Type::getLabelTy(Context); 00653 break; 00654 case bitc::TYPE_CODE_METADATA: // METADATA 00655 ResultTy = Type::getMetadataTy(Context); 00656 break; 00657 case bitc::TYPE_CODE_X86_MMX: // X86_MMX 00658 ResultTy = Type::getX86_MMXTy(Context); 00659 break; 00660 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width] 00661 if (Record.size() < 1) 00662 return Error("Invalid Integer type record"); 00663 00664 ResultTy = IntegerType::get(Context, Record[0]); 00665 break; 00666 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 00667 // [pointee type, address space] 00668 if (Record.size() < 1) 00669 return Error("Invalid POINTER type record"); 00670 unsigned AddressSpace = 0; 00671 if (Record.size() == 2) 00672 AddressSpace = Record[1]; 00673 ResultTy = getTypeByID(Record[0]); 00674 if (ResultTy == 0) return Error("invalid element type in pointer type"); 00675 ResultTy = PointerType::get(ResultTy, AddressSpace); 00676 break; 00677 } 00678 case bitc::TYPE_CODE_FUNCTION_OLD: { 00679 // FIXME: attrid is dead, remove it in LLVM 4.0 00680 // FUNCTION: [vararg, attrid, retty, paramty x N] 00681 if (Record.size() < 3) 00682 return Error("Invalid FUNCTION type record"); 00683 SmallVector<Type*, 8> ArgTys; 00684 for (unsigned i = 3, e = Record.size(); i != e; ++i) { 00685 if (Type *T = getTypeByID(Record[i])) 00686 ArgTys.push_back(T); 00687 else 00688 break; 00689 } 00690 00691 ResultTy = getTypeByID(Record[2]); 00692 if (ResultTy == 0 || ArgTys.size() < Record.size()-3) 00693 return Error("invalid type in function type"); 00694 00695 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 00696 break; 00697 } 00698 case bitc::TYPE_CODE_FUNCTION: { 00699 // FUNCTION: [vararg, retty, paramty x N] 00700 if (Record.size() < 2) 00701 return Error("Invalid FUNCTION type record"); 00702 SmallVector<Type*, 8> ArgTys; 00703 for (unsigned i = 2, e = Record.size(); i != e; ++i) { 00704 if (Type *T = getTypeByID(Record[i])) 00705 ArgTys.push_back(T); 00706 else 00707 break; 00708 } 00709 00710 ResultTy = getTypeByID(Record[1]); 00711 if (ResultTy == 0 || ArgTys.size() < Record.size()-2) 00712 return Error("invalid type in function type"); 00713 00714 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); 00715 break; 00716 } 00717 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] 00718 if (Record.size() < 1) 00719 return Error("Invalid STRUCT type record"); 00720 SmallVector<Type*, 8> EltTys; 00721 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 00722 if (Type *T = getTypeByID(Record[i])) 00723 EltTys.push_back(T); 00724 else 00725 break; 00726 } 00727 if (EltTys.size() != Record.size()-1) 00728 return Error("invalid type in struct type"); 00729 ResultTy = StructType::get(Context, EltTys, Record[0]); 00730 break; 00731 } 00732 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] 00733 if (ConvertToString(Record, 0, TypeName)) 00734 return Error("Invalid STRUCT_NAME record"); 00735 continue; 00736 00737 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] 00738 if (Record.size() < 1) 00739 return Error("Invalid STRUCT type record"); 00740 00741 if (NumRecords >= TypeList.size()) 00742 return Error("invalid TYPE table"); 00743 00744 // Check to see if this was forward referenced, if so fill in the temp. 00745 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 00746 if (Res) { 00747 Res->setName(TypeName); 00748 TypeList[NumRecords] = 0; 00749 } else // Otherwise, create a new struct. 00750 Res = StructType::create(Context, TypeName); 00751 TypeName.clear(); 00752 00753 SmallVector<Type*, 8> EltTys; 00754 for (unsigned i = 1, e = Record.size(); i != e; ++i) { 00755 if (Type *T = getTypeByID(Record[i])) 00756 EltTys.push_back(T); 00757 else 00758 break; 00759 } 00760 if (EltTys.size() != Record.size()-1) 00761 return Error("invalid STRUCT type record"); 00762 Res->setBody(EltTys, Record[0]); 00763 ResultTy = Res; 00764 break; 00765 } 00766 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] 00767 if (Record.size() != 1) 00768 return Error("Invalid OPAQUE type record"); 00769 00770 if (NumRecords >= TypeList.size()) 00771 return Error("invalid TYPE table"); 00772 00773 // Check to see if this was forward referenced, if so fill in the temp. 00774 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]); 00775 if (Res) { 00776 Res->setName(TypeName); 00777 TypeList[NumRecords] = 0; 00778 } else // Otherwise, create a new struct with no body. 00779 Res = StructType::create(Context, TypeName); 00780 TypeName.clear(); 00781 ResultTy = Res; 00782 break; 00783 } 00784 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] 00785 if (Record.size() < 2) 00786 return Error("Invalid ARRAY type record"); 00787 if ((ResultTy = getTypeByID(Record[1]))) 00788 ResultTy = ArrayType::get(ResultTy, Record[0]); 00789 else 00790 return Error("Invalid ARRAY type element"); 00791 break; 00792 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] 00793 if (Record.size() < 2) 00794 return Error("Invalid VECTOR type record"); 00795 if ((ResultTy = getTypeByID(Record[1]))) 00796 ResultTy = VectorType::get(ResultTy, Record[0]); 00797 else 00798 return Error("Invalid ARRAY type element"); 00799 break; 00800 } 00801 00802 if (NumRecords >= TypeList.size()) 00803 return Error("invalid TYPE table"); 00804 assert(ResultTy && "Didn't read a type?"); 00805 assert(TypeList[NumRecords] == 0 && "Already read type?"); 00806 TypeList[NumRecords++] = ResultTy; 00807 } 00808 } 00809 00810 bool BitcodeReader::ParseValueSymbolTable() { 00811 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID)) 00812 return Error("Malformed block record"); 00813 00814 SmallVector<uint64_t, 64> Record; 00815 00816 // Read all the records for this value table. 00817 SmallString<128> ValueName; 00818 while (1) { 00819 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 00820 00821 switch (Entry.Kind) { 00822 case BitstreamEntry::SubBlock: // Handled for us already. 00823 case BitstreamEntry::Error: 00824 return Error("malformed value symbol table block"); 00825 case BitstreamEntry::EndBlock: 00826 return false; 00827 case BitstreamEntry::Record: 00828 // The interesting case. 00829 break; 00830 } 00831 00832 // Read a record. 00833 Record.clear(); 00834 switch (Stream.readRecord(Entry.ID, Record)) { 00835 default: // Default behavior: unknown type. 00836 break; 00837 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N] 00838 if (ConvertToString(Record, 1, ValueName)) 00839 return Error("Invalid VST_ENTRY record"); 00840 unsigned ValueID = Record[0]; 00841 if (ValueID >= ValueList.size()) 00842 return Error("Invalid Value ID in VST_ENTRY record"); 00843 Value *V = ValueList[ValueID]; 00844 00845 V->setName(StringRef(ValueName.data(), ValueName.size())); 00846 ValueName.clear(); 00847 break; 00848 } 00849 case bitc::VST_CODE_BBENTRY: { 00850 if (ConvertToString(Record, 1, ValueName)) 00851 return Error("Invalid VST_BBENTRY record"); 00852 BasicBlock *BB = getBasicBlock(Record[0]); 00853 if (BB == 0) 00854 return Error("Invalid BB ID in VST_BBENTRY record"); 00855 00856 BB->setName(StringRef(ValueName.data(), ValueName.size())); 00857 ValueName.clear(); 00858 break; 00859 } 00860 } 00861 } 00862 } 00863 00864 bool BitcodeReader::ParseMetadata() { 00865 unsigned NextMDValueNo = MDValueList.size(); 00866 00867 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 00868 return Error("Malformed block record"); 00869 00870 SmallVector<uint64_t, 64> Record; 00871 00872 // Read all the records. 00873 while (1) { 00874 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 00875 00876 switch (Entry.Kind) { 00877 case BitstreamEntry::SubBlock: // Handled for us already. 00878 case BitstreamEntry::Error: 00879 Error("malformed metadata block"); 00880 return true; 00881 case BitstreamEntry::EndBlock: 00882 return false; 00883 case BitstreamEntry::Record: 00884 // The interesting case. 00885 break; 00886 } 00887 00888 bool IsFunctionLocal = false; 00889 // Read a record. 00890 Record.clear(); 00891 unsigned Code = Stream.readRecord(Entry.ID, Record); 00892 switch (Code) { 00893 default: // Default behavior: ignore. 00894 break; 00895 case bitc::METADATA_NAME: { 00896 // Read name of the named metadata. 00897 SmallString<8> Name(Record.begin(), Record.end()); 00898 Record.clear(); 00899 Code = Stream.ReadCode(); 00900 00901 // METADATA_NAME is always followed by METADATA_NAMED_NODE. 00902 unsigned NextBitCode = Stream.readRecord(Code, Record); 00903 assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode; 00904 00905 // Read named metadata elements. 00906 unsigned Size = Record.size(); 00907 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name); 00908 for (unsigned i = 0; i != Size; ++i) { 00909 MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i])); 00910 if (MD == 0) 00911 return Error("Malformed metadata record"); 00912 NMD->addOperand(MD); 00913 } 00914 break; 00915 } 00916 case bitc::METADATA_FN_NODE: 00917 IsFunctionLocal = true; 00918 // fall-through 00919 case bitc::METADATA_NODE: { 00920 if (Record.size() % 2 == 1) 00921 return Error("Invalid METADATA_NODE record"); 00922 00923 unsigned Size = Record.size(); 00924 SmallVector<Value*, 8> Elts; 00925 for (unsigned i = 0; i != Size; i += 2) { 00926 Type *Ty = getTypeByID(Record[i]); 00927 if (!Ty) return Error("Invalid METADATA_NODE record"); 00928 if (Ty->isMetadataTy()) 00929 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1])); 00930 else if (!Ty->isVoidTy()) 00931 Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty)); 00932 else 00933 Elts.push_back(NULL); 00934 } 00935 Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal); 00936 IsFunctionLocal = false; 00937 MDValueList.AssignValue(V, NextMDValueNo++); 00938 break; 00939 } 00940 case bitc::METADATA_STRING: { 00941 SmallString<8> String(Record.begin(), Record.end()); 00942 Value *V = MDString::get(Context, String); 00943 MDValueList.AssignValue(V, NextMDValueNo++); 00944 break; 00945 } 00946 case bitc::METADATA_KIND: { 00947 if (Record.size() < 2) 00948 return Error("Invalid METADATA_KIND record"); 00949 00950 unsigned Kind = Record[0]; 00951 SmallString<8> Name(Record.begin()+1, Record.end()); 00952 00953 unsigned NewKind = TheModule->getMDKindID(Name.str()); 00954 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 00955 return Error("Conflicting METADATA_KIND records"); 00956 break; 00957 } 00958 } 00959 } 00960 } 00961 00962 /// decodeSignRotatedValue - Decode a signed value stored with the sign bit in 00963 /// the LSB for dense VBR encoding. 00964 uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) { 00965 if ((V & 1) == 0) 00966 return V >> 1; 00967 if (V != 1) 00968 return -(V >> 1); 00969 // There is no such thing as -0 with integers. "-0" really means MININT. 00970 return 1ULL << 63; 00971 } 00972 00973 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global 00974 /// values and aliases that we can. 00975 bool BitcodeReader::ResolveGlobalAndAliasInits() { 00976 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist; 00977 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist; 00978 00979 GlobalInitWorklist.swap(GlobalInits); 00980 AliasInitWorklist.swap(AliasInits); 00981 00982 while (!GlobalInitWorklist.empty()) { 00983 unsigned ValID = GlobalInitWorklist.back().second; 00984 if (ValID >= ValueList.size()) { 00985 // Not ready to resolve this yet, it requires something later in the file. 00986 GlobalInits.push_back(GlobalInitWorklist.back()); 00987 } else { 00988 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 00989 GlobalInitWorklist.back().first->setInitializer(C); 00990 else 00991 return Error("Global variable initializer is not a constant!"); 00992 } 00993 GlobalInitWorklist.pop_back(); 00994 } 00995 00996 while (!AliasInitWorklist.empty()) { 00997 unsigned ValID = AliasInitWorklist.back().second; 00998 if (ValID >= ValueList.size()) { 00999 AliasInits.push_back(AliasInitWorklist.back()); 01000 } else { 01001 if (Constant *C = dyn_cast<Constant>(ValueList[ValID])) 01002 AliasInitWorklist.back().first->setAliasee(C); 01003 else 01004 return Error("Alias initializer is not a constant!"); 01005 } 01006 AliasInitWorklist.pop_back(); 01007 } 01008 return false; 01009 } 01010 01011 static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) { 01012 SmallVector<uint64_t, 8> Words(Vals.size()); 01013 std::transform(Vals.begin(), Vals.end(), Words.begin(), 01014 BitcodeReader::decodeSignRotatedValue); 01015 01016 return APInt(TypeBits, Words); 01017 } 01018 01019 bool BitcodeReader::ParseConstants() { 01020 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID)) 01021 return Error("Malformed block record"); 01022 01023 SmallVector<uint64_t, 64> Record; 01024 01025 // Read all the records for this value table. 01026 Type *CurTy = Type::getInt32Ty(Context); 01027 unsigned NextCstNo = ValueList.size(); 01028 while (1) { 01029 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 01030 01031 switch (Entry.Kind) { 01032 case BitstreamEntry::SubBlock: // Handled for us already. 01033 case BitstreamEntry::Error: 01034 return Error("malformed block record in AST file"); 01035 case BitstreamEntry::EndBlock: 01036 if (NextCstNo != ValueList.size()) 01037 return Error("Invalid constant reference!"); 01038 01039 // Once all the constants have been read, go through and resolve forward 01040 // references. 01041 ValueList.ResolveConstantForwardRefs(); 01042 return false; 01043 case BitstreamEntry::Record: 01044 // The interesting case. 01045 break; 01046 } 01047 01048 // Read a record. 01049 Record.clear(); 01050 Value *V = 0; 01051 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 01052 switch (BitCode) { 01053 default: // Default behavior: unknown constant 01054 case bitc::CST_CODE_UNDEF: // UNDEF 01055 V = UndefValue::get(CurTy); 01056 break; 01057 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] 01058 if (Record.empty()) 01059 return Error("Malformed CST_SETTYPE record"); 01060 if (Record[0] >= TypeList.size()) 01061 return Error("Invalid Type ID in CST_SETTYPE record"); 01062 CurTy = TypeList[Record[0]]; 01063 continue; // Skip the ValueList manipulation. 01064 case bitc::CST_CODE_NULL: // NULL 01065 V = Constant::getNullValue(CurTy); 01066 break; 01067 case bitc::CST_CODE_INTEGER: // INTEGER: [intval] 01068 if (!CurTy->isIntegerTy() || Record.empty()) 01069 return Error("Invalid CST_INTEGER record"); 01070 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); 01071 break; 01072 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] 01073 if (!CurTy->isIntegerTy() || Record.empty()) 01074 return Error("Invalid WIDE_INTEGER record"); 01075 01076 APInt VInt = ReadWideAPInt(Record, 01077 cast<IntegerType>(CurTy)->getBitWidth()); 01078 V = ConstantInt::get(Context, VInt); 01079 01080 break; 01081 } 01082 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] 01083 if (Record.empty()) 01084 return Error("Invalid FLOAT record"); 01085 if (CurTy->isHalfTy()) 01086 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf, 01087 APInt(16, (uint16_t)Record[0]))); 01088 else if (CurTy->isFloatTy()) 01089 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle, 01090 APInt(32, (uint32_t)Record[0]))); 01091 else if (CurTy->isDoubleTy()) 01092 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble, 01093 APInt(64, Record[0]))); 01094 else if (CurTy->isX86_FP80Ty()) { 01095 // Bits are not stored the same way as a normal i80 APInt, compensate. 01096 uint64_t Rearrange[2]; 01097 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16); 01098 Rearrange[1] = Record[0] >> 48; 01099 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended, 01100 APInt(80, Rearrange))); 01101 } else if (CurTy->isFP128Ty()) 01102 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad, 01103 APInt(128, Record))); 01104 else if (CurTy->isPPC_FP128Ty()) 01105 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble, 01106 APInt(128, Record))); 01107 else 01108 V = UndefValue::get(CurTy); 01109 break; 01110 } 01111 01112 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] 01113 if (Record.empty()) 01114 return Error("Invalid CST_AGGREGATE record"); 01115 01116 unsigned Size = Record.size(); 01117 SmallVector<Constant*, 16> Elts; 01118 01119 if (StructType *STy = dyn_cast<StructType>(CurTy)) { 01120 for (unsigned i = 0; i != Size; ++i) 01121 Elts.push_back(ValueList.getConstantFwdRef(Record[i], 01122 STy->getElementType(i))); 01123 V = ConstantStruct::get(STy, Elts); 01124 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) { 01125 Type *EltTy = ATy->getElementType(); 01126 for (unsigned i = 0; i != Size; ++i) 01127 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 01128 V = ConstantArray::get(ATy, Elts); 01129 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) { 01130 Type *EltTy = VTy->getElementType(); 01131 for (unsigned i = 0; i != Size; ++i) 01132 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy)); 01133 V = ConstantVector::get(Elts); 01134 } else { 01135 V = UndefValue::get(CurTy); 01136 } 01137 break; 01138 } 01139 case bitc::CST_CODE_STRING: // STRING: [values] 01140 case bitc::CST_CODE_CSTRING: { // CSTRING: [values] 01141 if (Record.empty()) 01142 return Error("Invalid CST_STRING record"); 01143 01144 SmallString<16> Elts(Record.begin(), Record.end()); 01145 V = ConstantDataArray::getString(Context, Elts, 01146 BitCode == bitc::CST_CODE_CSTRING); 01147 break; 01148 } 01149 case bitc::CST_CODE_DATA: {// DATA: [n x value] 01150 if (Record.empty()) 01151 return Error("Invalid CST_DATA record"); 01152 01153 Type *EltTy = cast<SequentialType>(CurTy)->getElementType(); 01154 unsigned Size = Record.size(); 01155 01156 if (EltTy->isIntegerTy(8)) { 01157 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end()); 01158 if (isa<VectorType>(CurTy)) 01159 V = ConstantDataVector::get(Context, Elts); 01160 else 01161 V = ConstantDataArray::get(Context, Elts); 01162 } else if (EltTy->isIntegerTy(16)) { 01163 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end()); 01164 if (isa<VectorType>(CurTy)) 01165 V = ConstantDataVector::get(Context, Elts); 01166 else 01167 V = ConstantDataArray::get(Context, Elts); 01168 } else if (EltTy->isIntegerTy(32)) { 01169 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end()); 01170 if (isa<VectorType>(CurTy)) 01171 V = ConstantDataVector::get(Context, Elts); 01172 else 01173 V = ConstantDataArray::get(Context, Elts); 01174 } else if (EltTy->isIntegerTy(64)) { 01175 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end()); 01176 if (isa<VectorType>(CurTy)) 01177 V = ConstantDataVector::get(Context, Elts); 01178 else 01179 V = ConstantDataArray::get(Context, Elts); 01180 } else if (EltTy->isFloatTy()) { 01181 SmallVector<float, 16> Elts(Size); 01182 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat); 01183 if (isa<VectorType>(CurTy)) 01184 V = ConstantDataVector::get(Context, Elts); 01185 else 01186 V = ConstantDataArray::get(Context, Elts); 01187 } else if (EltTy->isDoubleTy()) { 01188 SmallVector<double, 16> Elts(Size); 01189 std::transform(Record.begin(), Record.end(), Elts.begin(), 01190 BitsToDouble); 01191 if (isa<VectorType>(CurTy)) 01192 V = ConstantDataVector::get(Context, Elts); 01193 else 01194 V = ConstantDataArray::get(Context, Elts); 01195 } else { 01196 return Error("Unknown element type in CE_DATA"); 01197 } 01198 break; 01199 } 01200 01201 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] 01202 if (Record.size() < 3) return Error("Invalid CE_BINOP record"); 01203 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy); 01204 if (Opc < 0) { 01205 V = UndefValue::get(CurTy); // Unknown binop. 01206 } else { 01207 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); 01208 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); 01209 unsigned Flags = 0; 01210 if (Record.size() >= 4) { 01211 if (Opc == Instruction::Add || 01212 Opc == Instruction::Sub || 01213 Opc == Instruction::Mul || 01214 Opc == Instruction::Shl) { 01215 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 01216 Flags |= OverflowingBinaryOperator::NoSignedWrap; 01217 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 01218 Flags |= OverflowingBinaryOperator::NoUnsignedWrap; 01219 } else if (Opc == Instruction::SDiv || 01220 Opc == Instruction::UDiv || 01221 Opc == Instruction::LShr || 01222 Opc == Instruction::AShr) { 01223 if (Record[3] & (1 << bitc::PEO_EXACT)) 01224 Flags |= SDivOperator::IsExact; 01225 } 01226 } 01227 V = ConstantExpr::get(Opc, LHS, RHS, Flags); 01228 } 01229 break; 01230 } 01231 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] 01232 if (Record.size() < 3) return Error("Invalid CE_CAST record"); 01233 int Opc = GetDecodedCastOpcode(Record[0]); 01234 if (Opc < 0) { 01235 V = UndefValue::get(CurTy); // Unknown cast. 01236 } else { 01237 Type *OpTy = getTypeByID(Record[1]); 01238 if (!OpTy) return Error("Invalid CE_CAST record"); 01239 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); 01240 V = ConstantExpr::getCast(Opc, Op, CurTy); 01241 } 01242 break; 01243 } 01244 case bitc::CST_CODE_CE_INBOUNDS_GEP: 01245 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands] 01246 if (Record.size() & 1) return Error("Invalid CE_GEP record"); 01247 SmallVector<Constant*, 16> Elts; 01248 for (unsigned i = 0, e = Record.size(); i != e; i += 2) { 01249 Type *ElTy = getTypeByID(Record[i]); 01250 if (!ElTy) return Error("Invalid CE_GEP record"); 01251 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy)); 01252 } 01253 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end()); 01254 V = ConstantExpr::getGetElementPtr(Elts[0], Indices, 01255 BitCode == 01256 bitc::CST_CODE_CE_INBOUNDS_GEP); 01257 break; 01258 } 01259 case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#] 01260 if (Record.size() < 3) return Error("Invalid CE_SELECT record"); 01261 V = ConstantExpr::getSelect( 01262 ValueList.getConstantFwdRef(Record[0], 01263 Type::getInt1Ty(Context)), 01264 ValueList.getConstantFwdRef(Record[1],CurTy), 01265 ValueList.getConstantFwdRef(Record[2],CurTy)); 01266 break; 01267 case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval] 01268 if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record"); 01269 VectorType *OpTy = 01270 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 01271 if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record"); 01272 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01273 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], 01274 Type::getInt32Ty(Context)); 01275 V = ConstantExpr::getExtractElement(Op0, Op1); 01276 break; 01277 } 01278 case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval] 01279 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 01280 if (Record.size() < 3 || OpTy == 0) 01281 return Error("Invalid CE_INSERTELT record"); 01282 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 01283 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], 01284 OpTy->getElementType()); 01285 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], 01286 Type::getInt32Ty(Context)); 01287 V = ConstantExpr::getInsertElement(Op0, Op1, Op2); 01288 break; 01289 } 01290 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval] 01291 VectorType *OpTy = dyn_cast<VectorType>(CurTy); 01292 if (Record.size() < 3 || OpTy == 0) 01293 return Error("Invalid CE_SHUFFLEVEC record"); 01294 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); 01295 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); 01296 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 01297 OpTy->getNumElements()); 01298 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); 01299 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 01300 break; 01301 } 01302 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] 01303 VectorType *RTy = dyn_cast<VectorType>(CurTy); 01304 VectorType *OpTy = 01305 dyn_cast_or_null<VectorType>(getTypeByID(Record[0])); 01306 if (Record.size() < 4 || RTy == 0 || OpTy == 0) 01307 return Error("Invalid CE_SHUFVEC_EX record"); 01308 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01309 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 01310 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), 01311 RTy->getNumElements()); 01312 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); 01313 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); 01314 break; 01315 } 01316 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] 01317 if (Record.size() < 4) return Error("Invalid CE_CMP record"); 01318 Type *OpTy = getTypeByID(Record[0]); 01319 if (OpTy == 0) return Error("Invalid CE_CMP record"); 01320 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); 01321 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); 01322 01323 if (OpTy->isFPOrFPVectorTy()) 01324 V = ConstantExpr::getFCmp(Record[3], Op0, Op1); 01325 else 01326 V = ConstantExpr::getICmp(Record[3], Op0, Op1); 01327 break; 01328 } 01329 // This maintains backward compatibility, pre-asm dialect keywords. 01330 // FIXME: Remove with the 4.0 release. 01331 case bitc::CST_CODE_INLINEASM_OLD: { 01332 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 01333 std::string AsmStr, ConstrStr; 01334 bool HasSideEffects = Record[0] & 1; 01335 bool IsAlignStack = Record[0] >> 1; 01336 unsigned AsmStrSize = Record[1]; 01337 if (2+AsmStrSize >= Record.size()) 01338 return Error("Invalid INLINEASM record"); 01339 unsigned ConstStrSize = Record[2+AsmStrSize]; 01340 if (3+AsmStrSize+ConstStrSize > Record.size()) 01341 return Error("Invalid INLINEASM record"); 01342 01343 for (unsigned i = 0; i != AsmStrSize; ++i) 01344 AsmStr += (char)Record[2+i]; 01345 for (unsigned i = 0; i != ConstStrSize; ++i) 01346 ConstrStr += (char)Record[3+AsmStrSize+i]; 01347 PointerType *PTy = cast<PointerType>(CurTy); 01348 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 01349 AsmStr, ConstrStr, HasSideEffects, IsAlignStack); 01350 break; 01351 } 01352 // This version adds support for the asm dialect keywords (e.g., 01353 // inteldialect). 01354 case bitc::CST_CODE_INLINEASM: { 01355 if (Record.size() < 2) return Error("Invalid INLINEASM record"); 01356 std::string AsmStr, ConstrStr; 01357 bool HasSideEffects = Record[0] & 1; 01358 bool IsAlignStack = (Record[0] >> 1) & 1; 01359 unsigned AsmDialect = Record[0] >> 2; 01360 unsigned AsmStrSize = Record[1]; 01361 if (2+AsmStrSize >= Record.size()) 01362 return Error("Invalid INLINEASM record"); 01363 unsigned ConstStrSize = Record[2+AsmStrSize]; 01364 if (3+AsmStrSize+ConstStrSize > Record.size()) 01365 return Error("Invalid INLINEASM record"); 01366 01367 for (unsigned i = 0; i != AsmStrSize; ++i) 01368 AsmStr += (char)Record[2+i]; 01369 for (unsigned i = 0; i != ConstStrSize; ++i) 01370 ConstrStr += (char)Record[3+AsmStrSize+i]; 01371 PointerType *PTy = cast<PointerType>(CurTy); 01372 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()), 01373 AsmStr, ConstrStr, HasSideEffects, IsAlignStack, 01374 InlineAsm::AsmDialect(AsmDialect)); 01375 break; 01376 } 01377 case bitc::CST_CODE_BLOCKADDRESS:{ 01378 if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record"); 01379 Type *FnTy = getTypeByID(Record[0]); 01380 if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record"); 01381 Function *Fn = 01382 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy)); 01383 if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record"); 01384 01385 // If the function is already parsed we can insert the block address right 01386 // away. 01387 if (!Fn->empty()) { 01388 Function::iterator BBI = Fn->begin(), BBE = Fn->end(); 01389 for (size_t I = 0, E = Record[2]; I != E; ++I) { 01390 if (BBI == BBE) 01391 return Error("Invalid blockaddress block #"); 01392 ++BBI; 01393 } 01394 V = BlockAddress::get(Fn, BBI); 01395 } else { 01396 // Otherwise insert a placeholder and remember it so it can be inserted 01397 // when the function is parsed. 01398 GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(), 01399 Type::getInt8Ty(Context), 01400 false, GlobalValue::InternalLinkage, 01401 0, ""); 01402 BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef)); 01403 V = FwdRef; 01404 } 01405 break; 01406 } 01407 } 01408 01409 ValueList.AssignValue(V, NextCstNo); 01410 ++NextCstNo; 01411 } 01412 } 01413 01414 bool BitcodeReader::ParseUseLists() { 01415 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID)) 01416 return Error("Malformed block record"); 01417 01418 SmallVector<uint64_t, 64> Record; 01419 01420 // Read all the records. 01421 while (1) { 01422 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 01423 01424 switch (Entry.Kind) { 01425 case BitstreamEntry::SubBlock: // Handled for us already. 01426 case BitstreamEntry::Error: 01427 return Error("malformed use list block"); 01428 case BitstreamEntry::EndBlock: 01429 return false; 01430 case BitstreamEntry::Record: 01431 // The interesting case. 01432 break; 01433 } 01434 01435 // Read a use list record. 01436 Record.clear(); 01437 switch (Stream.readRecord(Entry.ID, Record)) { 01438 default: // Default behavior: unknown type. 01439 break; 01440 case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD. 01441 unsigned RecordLength = Record.size(); 01442 if (RecordLength < 1) 01443 return Error ("Invalid UseList reader!"); 01444 UseListRecords.push_back(Record); 01445 break; 01446 } 01447 } 01448 } 01449 } 01450 01451 /// RememberAndSkipFunctionBody - When we see the block for a function body, 01452 /// remember where it is and then skip it. This lets us lazily deserialize the 01453 /// functions. 01454 bool BitcodeReader::RememberAndSkipFunctionBody() { 01455 // Get the function we are talking about. 01456 if (FunctionsWithBodies.empty()) 01457 return Error("Insufficient function protos"); 01458 01459 Function *Fn = FunctionsWithBodies.back(); 01460 FunctionsWithBodies.pop_back(); 01461 01462 // Save the current stream state. 01463 uint64_t CurBit = Stream.GetCurrentBitNo(); 01464 DeferredFunctionInfo[Fn] = CurBit; 01465 01466 // Skip over the function block for now. 01467 if (Stream.SkipBlock()) 01468 return Error("Malformed block record"); 01469 return false; 01470 } 01471 01472 bool BitcodeReader::GlobalCleanup() { 01473 // Patch the initializers for globals and aliases up. 01474 ResolveGlobalAndAliasInits(); 01475 if (!GlobalInits.empty() || !AliasInits.empty()) 01476 return Error("Malformed global initializer set"); 01477 01478 // Look for intrinsic functions which need to be upgraded at some point 01479 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end(); 01480 FI != FE; ++FI) { 01481 Function *NewFn; 01482 if (UpgradeIntrinsicFunction(FI, NewFn)) 01483 UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn)); 01484 } 01485 01486 // Look for global variables which need to be renamed. 01487 for (Module::global_iterator 01488 GI = TheModule->global_begin(), GE = TheModule->global_end(); 01489 GI != GE; ++GI) 01490 UpgradeGlobalVariable(GI); 01491 // Force deallocation of memory for these vectors to favor the client that 01492 // want lazy deserialization. 01493 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits); 01494 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits); 01495 return false; 01496 } 01497 01498 bool BitcodeReader::ParseModule(bool Resume) { 01499 if (Resume) 01500 Stream.JumpToBit(NextUnreadBit); 01501 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 01502 return Error("Malformed block record"); 01503 01504 SmallVector<uint64_t, 64> Record; 01505 std::vector<std::string> SectionTable; 01506 std::vector<std::string> GCTable; 01507 01508 // Read all the records for this module. 01509 while (1) { 01510 BitstreamEntry Entry = Stream.advance(); 01511 01512 switch (Entry.Kind) { 01513 case BitstreamEntry::Error: 01514 Error("malformed module block"); 01515 return true; 01516 case BitstreamEntry::EndBlock: 01517 return GlobalCleanup(); 01518 01519 case BitstreamEntry::SubBlock: 01520 switch (Entry.ID) { 01521 default: // Skip unknown content. 01522 if (Stream.SkipBlock()) 01523 return Error("Malformed block record"); 01524 break; 01525 case bitc::BLOCKINFO_BLOCK_ID: 01526 if (Stream.ReadBlockInfoBlock()) 01527 return Error("Malformed BlockInfoBlock"); 01528 break; 01529 case bitc::PARAMATTR_BLOCK_ID: 01530 if (ParseAttributeBlock()) 01531 return true; 01532 break; 01533 case bitc::PARAMATTR_GROUP_BLOCK_ID: 01534 if (ParseAttributeGroupBlock()) 01535 return true; 01536 break; 01537 case bitc::TYPE_BLOCK_ID_NEW: 01538 if (ParseTypeTable()) 01539 return true; 01540 break; 01541 case bitc::VALUE_SYMTAB_BLOCK_ID: 01542 if (ParseValueSymbolTable()) 01543 return true; 01544 SeenValueSymbolTable = true; 01545 break; 01546 case bitc::CONSTANTS_BLOCK_ID: 01547 if (ParseConstants() || ResolveGlobalAndAliasInits()) 01548 return true; 01549 break; 01550 case bitc::METADATA_BLOCK_ID: 01551 if (ParseMetadata()) 01552 return true; 01553 break; 01554 case bitc::FUNCTION_BLOCK_ID: 01555 // If this is the first function body we've seen, reverse the 01556 // FunctionsWithBodies list. 01557 if (!SeenFirstFunctionBody) { 01558 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end()); 01559 if (GlobalCleanup()) 01560 return true; 01561 SeenFirstFunctionBody = true; 01562 } 01563 01564 if (RememberAndSkipFunctionBody()) 01565 return true; 01566 // For streaming bitcode, suspend parsing when we reach the function 01567 // bodies. Subsequent materialization calls will resume it when 01568 // necessary. For streaming, the function bodies must be at the end of 01569 // the bitcode. If the bitcode file is old, the symbol table will be 01570 // at the end instead and will not have been seen yet. In this case, 01571 // just finish the parse now. 01572 if (LazyStreamer && SeenValueSymbolTable) { 01573 NextUnreadBit = Stream.GetCurrentBitNo(); 01574 return false; 01575 } 01576 break; 01577 case bitc::USELIST_BLOCK_ID: 01578 if (ParseUseLists()) 01579 return true; 01580 break; 01581 } 01582 continue; 01583 01584 case BitstreamEntry::Record: 01585 // The interesting case. 01586 break; 01587 } 01588 01589 01590 // Read a record. 01591 switch (Stream.readRecord(Entry.ID, Record)) { 01592 default: break; // Default behavior, ignore unknown content. 01593 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#] 01594 if (Record.size() < 1) 01595 return Error("Malformed MODULE_CODE_VERSION"); 01596 // Only version #0 and #1 are supported so far. 01597 unsigned module_version = Record[0]; 01598 switch (module_version) { 01599 default: return Error("Unknown bitstream version!"); 01600 case 0: 01601 UseRelativeIDs = false; 01602 break; 01603 case 1: 01604 UseRelativeIDs = true; 01605 break; 01606 } 01607 break; 01608 } 01609 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 01610 std::string S; 01611 if (ConvertToString(Record, 0, S)) 01612 return Error("Invalid MODULE_CODE_TRIPLE record"); 01613 TheModule->setTargetTriple(S); 01614 break; 01615 } 01616 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] 01617 std::string S; 01618 if (ConvertToString(Record, 0, S)) 01619 return Error("Invalid MODULE_CODE_DATALAYOUT record"); 01620 TheModule->setDataLayout(S); 01621 break; 01622 } 01623 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] 01624 std::string S; 01625 if (ConvertToString(Record, 0, S)) 01626 return Error("Invalid MODULE_CODE_ASM record"); 01627 TheModule->setModuleInlineAsm(S); 01628 break; 01629 } 01630 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] 01631 // FIXME: Remove in 4.0. 01632 std::string S; 01633 if (ConvertToString(Record, 0, S)) 01634 return Error("Invalid MODULE_CODE_DEPLIB record"); 01635 // Ignore value. 01636 break; 01637 } 01638 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] 01639 std::string S; 01640 if (ConvertToString(Record, 0, S)) 01641 return Error("Invalid MODULE_CODE_SECTIONNAME record"); 01642 SectionTable.push_back(S); 01643 break; 01644 } 01645 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] 01646 std::string S; 01647 if (ConvertToString(Record, 0, S)) 01648 return Error("Invalid MODULE_CODE_GCNAME record"); 01649 GCTable.push_back(S); 01650 break; 01651 } 01652 // GLOBALVAR: [pointer type, isconst, initid, 01653 // linkage, alignment, section, visibility, threadlocal, 01654 // unnamed_addr] 01655 case bitc::MODULE_CODE_GLOBALVAR: { 01656 if (Record.size() < 6) 01657 return Error("Invalid MODULE_CODE_GLOBALVAR record"); 01658 Type *Ty = getTypeByID(Record[0]); 01659 if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record"); 01660 if (!Ty->isPointerTy()) 01661 return Error("Global not a pointer type!"); 01662 unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace(); 01663 Ty = cast<PointerType>(Ty)->getElementType(); 01664 01665 bool isConstant = Record[1]; 01666 GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]); 01667 unsigned Alignment = (1 << Record[4]) >> 1; 01668 std::string Section; 01669 if (Record[5]) { 01670 if (Record[5]-1 >= SectionTable.size()) 01671 return Error("Invalid section ID"); 01672 Section = SectionTable[Record[5]-1]; 01673 } 01674 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility; 01675 if (Record.size() > 6) 01676 Visibility = GetDecodedVisibility(Record[6]); 01677 01678 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal; 01679 if (Record.size() > 7) 01680 TLM = GetDecodedThreadLocalMode(Record[7]); 01681 01682 bool UnnamedAddr = false; 01683 if (Record.size() > 8) 01684 UnnamedAddr = Record[8]; 01685 01686 bool ExternallyInitialized = false; 01687 if (Record.size() > 9) 01688 ExternallyInitialized = Record[9]; 01689 01690 GlobalVariable *NewGV = 01691 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0, 01692 TLM, AddressSpace, ExternallyInitialized); 01693 NewGV->setAlignment(Alignment); 01694 if (!Section.empty()) 01695 NewGV->setSection(Section); 01696 NewGV->setVisibility(Visibility); 01697 NewGV->setUnnamedAddr(UnnamedAddr); 01698 01699 ValueList.push_back(NewGV); 01700 01701 // Remember which value to use for the global initializer. 01702 if (unsigned InitID = Record[2]) 01703 GlobalInits.push_back(std::make_pair(NewGV, InitID-1)); 01704 break; 01705 } 01706 // FUNCTION: [type, callingconv, isproto, linkage, paramattr, 01707 // alignment, section, visibility, gc, unnamed_addr] 01708 case bitc::MODULE_CODE_FUNCTION: { 01709 if (Record.size() < 8) 01710 return Error("Invalid MODULE_CODE_FUNCTION record"); 01711 Type *Ty = getTypeByID(Record[0]); 01712 if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record"); 01713 if (!Ty->isPointerTy()) 01714 return Error("Function not a pointer type!"); 01715 FunctionType *FTy = 01716 dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType()); 01717 if (!FTy) 01718 return Error("Function not a pointer to function type!"); 01719 01720 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage, 01721 "", TheModule); 01722 01723 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1])); 01724 bool isProto = Record[2]; 01725 Func->setLinkage(GetDecodedLinkage(Record[3])); 01726 Func->setAttributes(getAttributes(Record[4])); 01727 01728 Func->setAlignment((1 << Record[5]) >> 1); 01729 if (Record[6]) { 01730 if (Record[6]-1 >= SectionTable.size()) 01731 return Error("Invalid section ID"); 01732 Func->setSection(SectionTable[Record[6]-1]); 01733 } 01734 Func->setVisibility(GetDecodedVisibility(Record[7])); 01735 if (Record.size() > 8 && Record[8]) { 01736 if (Record[8]-1 > GCTable.size()) 01737 return Error("Invalid GC ID"); 01738 Func->setGC(GCTable[Record[8]-1].c_str()); 01739 } 01740 bool UnnamedAddr = false; 01741 if (Record.size() > 9) 01742 UnnamedAddr = Record[9]; 01743 Func->setUnnamedAddr(UnnamedAddr); 01744 ValueList.push_back(Func); 01745 01746 // If this is a function with a body, remember the prototype we are 01747 // creating now, so that we can match up the body with them later. 01748 if (!isProto) { 01749 FunctionsWithBodies.push_back(Func); 01750 if (LazyStreamer) DeferredFunctionInfo[Func] = 0; 01751 } 01752 break; 01753 } 01754 // ALIAS: [alias type, aliasee val#, linkage] 01755 // ALIAS: [alias type, aliasee val#, linkage, visibility] 01756 case bitc::MODULE_CODE_ALIAS: { 01757 if (Record.size() < 3) 01758 return Error("Invalid MODULE_ALIAS record"); 01759 Type *Ty = getTypeByID(Record[0]); 01760 if (!Ty) return Error("Invalid MODULE_ALIAS record"); 01761 if (!Ty->isPointerTy()) 01762 return Error("Function not a pointer type!"); 01763 01764 GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]), 01765 "", 0, TheModule); 01766 // Old bitcode files didn't have visibility field. 01767 if (Record.size() > 3) 01768 NewGA->setVisibility(GetDecodedVisibility(Record[3])); 01769 ValueList.push_back(NewGA); 01770 AliasInits.push_back(std::make_pair(NewGA, Record[1])); 01771 break; 01772 } 01773 /// MODULE_CODE_PURGEVALS: [numvals] 01774 case bitc::MODULE_CODE_PURGEVALS: 01775 // Trim down the value list to the specified size. 01776 if (Record.size() < 1 || Record[0] > ValueList.size()) 01777 return Error("Invalid MODULE_PURGEVALS record"); 01778 ValueList.shrinkTo(Record[0]); 01779 break; 01780 } 01781 Record.clear(); 01782 } 01783 } 01784 01785 bool BitcodeReader::ParseBitcodeInto(Module *M) { 01786 TheModule = 0; 01787 01788 if (InitStream()) return true; 01789 01790 // Sniff for the signature. 01791 if (Stream.Read(8) != 'B' || 01792 Stream.Read(8) != 'C' || 01793 Stream.Read(4) != 0x0 || 01794 Stream.Read(4) != 0xC || 01795 Stream.Read(4) != 0xE || 01796 Stream.Read(4) != 0xD) 01797 return Error("Invalid bitcode signature"); 01798 01799 // We expect a number of well-defined blocks, though we don't necessarily 01800 // need to understand them all. 01801 while (1) { 01802 if (Stream.AtEndOfStream()) 01803 return false; 01804 01805 BitstreamEntry Entry = 01806 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs); 01807 01808 switch (Entry.Kind) { 01809 case BitstreamEntry::Error: 01810 Error("malformed module file"); 01811 return true; 01812 case BitstreamEntry::EndBlock: 01813 return false; 01814 01815 case BitstreamEntry::SubBlock: 01816 switch (Entry.ID) { 01817 case bitc::BLOCKINFO_BLOCK_ID: 01818 if (Stream.ReadBlockInfoBlock()) 01819 return Error("Malformed BlockInfoBlock"); 01820 break; 01821 case bitc::MODULE_BLOCK_ID: 01822 // Reject multiple MODULE_BLOCK's in a single bitstream. 01823 if (TheModule) 01824 return Error("Multiple MODULE_BLOCKs in same stream"); 01825 TheModule = M; 01826 if (ParseModule(false)) 01827 return true; 01828 if (LazyStreamer) return false; 01829 break; 01830 default: 01831 if (Stream.SkipBlock()) 01832 return Error("Malformed block record"); 01833 break; 01834 } 01835 continue; 01836 case BitstreamEntry::Record: 01837 // There should be no records in the top-level of blocks. 01838 01839 // The ranlib in Xcode 4 will align archive members by appending newlines 01840 // to the end of them. If this file size is a multiple of 4 but not 8, we 01841 // have to read and ignore these final 4 bytes :-( 01842 if (Stream.getAbbrevIDWidth() == 2 && Entry.ID == 2 && 01843 Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a && 01844 Stream.AtEndOfStream()) 01845 return false; 01846 01847 return Error("Invalid record at top-level"); 01848 } 01849 } 01850 } 01851 01852 bool BitcodeReader::ParseModuleTriple(std::string &Triple) { 01853 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID)) 01854 return Error("Malformed block record"); 01855 01856 SmallVector<uint64_t, 64> Record; 01857 01858 // Read all the records for this module. 01859 while (1) { 01860 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 01861 01862 switch (Entry.Kind) { 01863 case BitstreamEntry::SubBlock: // Handled for us already. 01864 case BitstreamEntry::Error: 01865 return Error("malformed module block"); 01866 case BitstreamEntry::EndBlock: 01867 return false; 01868 case BitstreamEntry::Record: 01869 // The interesting case. 01870 break; 01871 } 01872 01873 // Read a record. 01874 switch (Stream.readRecord(Entry.ID, Record)) { 01875 default: break; // Default behavior, ignore unknown content. 01876 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] 01877 std::string S; 01878 if (ConvertToString(Record, 0, S)) 01879 return Error("Invalid MODULE_CODE_TRIPLE record"); 01880 Triple = S; 01881 break; 01882 } 01883 } 01884 Record.clear(); 01885 } 01886 } 01887 01888 bool BitcodeReader::ParseTriple(std::string &Triple) { 01889 if (InitStream()) return true; 01890 01891 // Sniff for the signature. 01892 if (Stream.Read(8) != 'B' || 01893 Stream.Read(8) != 'C' || 01894 Stream.Read(4) != 0x0 || 01895 Stream.Read(4) != 0xC || 01896 Stream.Read(4) != 0xE || 01897 Stream.Read(4) != 0xD) 01898 return Error("Invalid bitcode signature"); 01899 01900 // We expect a number of well-defined blocks, though we don't necessarily 01901 // need to understand them all. 01902 while (1) { 01903 BitstreamEntry Entry = Stream.advance(); 01904 01905 switch (Entry.Kind) { 01906 case BitstreamEntry::Error: 01907 Error("malformed module file"); 01908 return true; 01909 case BitstreamEntry::EndBlock: 01910 return false; 01911 01912 case BitstreamEntry::SubBlock: 01913 if (Entry.ID == bitc::MODULE_BLOCK_ID) 01914 return ParseModuleTriple(Triple); 01915 01916 // Ignore other sub-blocks. 01917 if (Stream.SkipBlock()) { 01918 Error("malformed block record in AST file"); 01919 return true; 01920 } 01921 continue; 01922 01923 case BitstreamEntry::Record: 01924 Stream.skipRecord(Entry.ID); 01925 continue; 01926 } 01927 } 01928 } 01929 01930 /// ParseMetadataAttachment - Parse metadata attachments. 01931 bool BitcodeReader::ParseMetadataAttachment() { 01932 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 01933 return Error("Malformed block record"); 01934 01935 SmallVector<uint64_t, 64> Record; 01936 while (1) { 01937 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 01938 01939 switch (Entry.Kind) { 01940 case BitstreamEntry::SubBlock: // Handled for us already. 01941 case BitstreamEntry::Error: 01942 return Error("malformed metadata block"); 01943 case BitstreamEntry::EndBlock: 01944 return false; 01945 case BitstreamEntry::Record: 01946 // The interesting case. 01947 break; 01948 } 01949 01950 // Read a metadata attachment record. 01951 Record.clear(); 01952 switch (Stream.readRecord(Entry.ID, Record)) { 01953 default: // Default behavior: ignore. 01954 break; 01955 case bitc::METADATA_ATTACHMENT: { 01956 unsigned RecordLength = Record.size(); 01957 if (Record.empty() || (RecordLength - 1) % 2 == 1) 01958 return Error ("Invalid METADATA_ATTACHMENT reader!"); 01959 Instruction *Inst = InstructionList[Record[0]]; 01960 for (unsigned i = 1; i != RecordLength; i = i+2) { 01961 unsigned Kind = Record[i]; 01962 DenseMap<unsigned, unsigned>::iterator I = 01963 MDKindMap.find(Kind); 01964 if (I == MDKindMap.end()) 01965 return Error("Invalid metadata kind ID"); 01966 Value *Node = MDValueList.getValueFwdRef(Record[i+1]); 01967 Inst->setMetadata(I->second, cast<MDNode>(Node)); 01968 } 01969 break; 01970 } 01971 } 01972 } 01973 } 01974 01975 /// ParseFunctionBody - Lazily parse the specified function body block. 01976 bool BitcodeReader::ParseFunctionBody(Function *F) { 01977 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID)) 01978 return Error("Malformed block record"); 01979 01980 InstructionList.clear(); 01981 unsigned ModuleValueListSize = ValueList.size(); 01982 unsigned ModuleMDValueListSize = MDValueList.size(); 01983 01984 // Add all the function arguments to the value table. 01985 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 01986 ValueList.push_back(I); 01987 01988 unsigned NextValueNo = ValueList.size(); 01989 BasicBlock *CurBB = 0; 01990 unsigned CurBBNo = 0; 01991 01992 DebugLoc LastLoc; 01993 01994 // Read all the records. 01995 SmallVector<uint64_t, 64> Record; 01996 while (1) { 01997 BitstreamEntry Entry = Stream.advance(); 01998 01999 switch (Entry.Kind) { 02000 case BitstreamEntry::Error: 02001 return Error("Bitcode error in function block"); 02002 case BitstreamEntry::EndBlock: 02003 goto OutOfRecordLoop; 02004 02005 case BitstreamEntry::SubBlock: 02006 switch (Entry.ID) { 02007 default: // Skip unknown content. 02008 if (Stream.SkipBlock()) 02009 return Error("Malformed block record"); 02010 break; 02011 case bitc::CONSTANTS_BLOCK_ID: 02012 if (ParseConstants()) return true; 02013 NextValueNo = ValueList.size(); 02014 break; 02015 case bitc::VALUE_SYMTAB_BLOCK_ID: 02016 if (ParseValueSymbolTable()) return true; 02017 break; 02018 case bitc::METADATA_ATTACHMENT_ID: 02019 if (ParseMetadataAttachment()) return true; 02020 break; 02021 case bitc::METADATA_BLOCK_ID: 02022 if (ParseMetadata()) return true; 02023 break; 02024 } 02025 continue; 02026 02027 case BitstreamEntry::Record: 02028 // The interesting case. 02029 break; 02030 } 02031 02032 // Read a record. 02033 Record.clear(); 02034 Instruction *I = 0; 02035 unsigned BitCode = Stream.readRecord(Entry.ID, Record); 02036 switch (BitCode) { 02037 default: // Default behavior: reject 02038 return Error("Unknown instruction"); 02039 case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks] 02040 if (Record.size() < 1 || Record[0] == 0) 02041 return Error("Invalid DECLAREBLOCKS record"); 02042 // Create all the basic blocks for the function. 02043 FunctionBBs.resize(Record[0]); 02044 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i) 02045 FunctionBBs[i] = BasicBlock::Create(Context, "", F); 02046 CurBB = FunctionBBs[0]; 02047 continue; 02048 02049 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN 02050 // This record indicates that the last instruction is at the same 02051 // location as the previous instruction with a location. 02052 I = 0; 02053 02054 // Get the last instruction emitted. 02055 if (CurBB && !CurBB->empty()) 02056 I = &CurBB->back(); 02057 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 02058 !FunctionBBs[CurBBNo-1]->empty()) 02059 I = &FunctionBBs[CurBBNo-1]->back(); 02060 02061 if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record"); 02062 I->setDebugLoc(LastLoc); 02063 I = 0; 02064 continue; 02065 02066 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] 02067 I = 0; // Get the last instruction emitted. 02068 if (CurBB && !CurBB->empty()) 02069 I = &CurBB->back(); 02070 else if (CurBBNo && FunctionBBs[CurBBNo-1] && 02071 !FunctionBBs[CurBBNo-1]->empty()) 02072 I = &FunctionBBs[CurBBNo-1]->back(); 02073 if (I == 0 || Record.size() < 4) 02074 return Error("Invalid FUNC_CODE_DEBUG_LOC record"); 02075 02076 unsigned Line = Record[0], Col = Record[1]; 02077 unsigned ScopeID = Record[2], IAID = Record[3]; 02078 02079 MDNode *Scope = 0, *IA = 0; 02080 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1)); 02081 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1)); 02082 LastLoc = DebugLoc::get(Line, Col, Scope, IA); 02083 I->setDebugLoc(LastLoc); 02084 I = 0; 02085 continue; 02086 } 02087 02088 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] 02089 unsigned OpNum = 0; 02090 Value *LHS, *RHS; 02091 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 02092 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 02093 OpNum+1 > Record.size()) 02094 return Error("Invalid BINOP record"); 02095 02096 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); 02097 if (Opc == -1) return Error("Invalid BINOP record"); 02098 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); 02099 InstructionList.push_back(I); 02100 if (OpNum < Record.size()) { 02101 if (Opc == Instruction::Add || 02102 Opc == Instruction::Sub || 02103 Opc == Instruction::Mul || 02104 Opc == Instruction::Shl) { 02105 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) 02106 cast<BinaryOperator>(I)->setHasNoSignedWrap(true); 02107 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) 02108 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true); 02109 } else if (Opc == Instruction::SDiv || 02110 Opc == Instruction::UDiv || 02111 Opc == Instruction::LShr || 02112 Opc == Instruction::AShr) { 02113 if (Record[OpNum] & (1 << bitc::PEO_EXACT)) 02114 cast<BinaryOperator>(I)->setIsExact(true); 02115 } else if (isa<FPMathOperator>(I)) { 02116 FastMathFlags FMF; 02117 if (0 != (Record[OpNum] & FastMathFlags::UnsafeAlgebra)) 02118 FMF.setUnsafeAlgebra(); 02119 if (0 != (Record[OpNum] & FastMathFlags::NoNaNs)) 02120 FMF.setNoNaNs(); 02121 if (0 != (Record[OpNum] & FastMathFlags::NoInfs)) 02122 FMF.setNoInfs(); 02123 if (0 != (Record[OpNum] & FastMathFlags::NoSignedZeros)) 02124 FMF.setNoSignedZeros(); 02125 if (0 != (Record[OpNum] & FastMathFlags::AllowReciprocal)) 02126 FMF.setAllowReciprocal(); 02127 if (FMF.any()) 02128 I->setFastMathFlags(FMF); 02129 } 02130 02131 } 02132 break; 02133 } 02134 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] 02135 unsigned OpNum = 0; 02136 Value *Op; 02137 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 02138 OpNum+2 != Record.size()) 02139 return Error("Invalid CAST record"); 02140 02141 Type *ResTy = getTypeByID(Record[OpNum]); 02142 int Opc = GetDecodedCastOpcode(Record[OpNum+1]); 02143 if (Opc == -1 || ResTy == 0) 02144 return Error("Invalid CAST record"); 02145 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy); 02146 InstructionList.push_back(I); 02147 break; 02148 } 02149 case bitc::FUNC_CODE_INST_INBOUNDS_GEP: 02150 case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands] 02151 unsigned OpNum = 0; 02152 Value *BasePtr; 02153 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr)) 02154 return Error("Invalid GEP record"); 02155 02156 SmallVector<Value*, 16> GEPIdx; 02157 while (OpNum != Record.size()) { 02158 Value *Op; 02159 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 02160 return Error("Invalid GEP record"); 02161 GEPIdx.push_back(Op); 02162 } 02163 02164 I = GetElementPtrInst::Create(BasePtr, GEPIdx); 02165 InstructionList.push_back(I); 02166 if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP) 02167 cast<GetElementPtrInst>(I)->setIsInBounds(true); 02168 break; 02169 } 02170 02171 case bitc::FUNC_CODE_INST_EXTRACTVAL: { 02172 // EXTRACTVAL: [opty, opval, n x indices] 02173 unsigned OpNum = 0; 02174 Value *Agg; 02175 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 02176 return Error("Invalid EXTRACTVAL record"); 02177 02178 SmallVector<unsigned, 4> EXTRACTVALIdx; 02179 for (unsigned RecSize = Record.size(); 02180 OpNum != RecSize; ++OpNum) { 02181 uint64_t Index = Record[OpNum]; 02182 if ((unsigned)Index != Index) 02183 return Error("Invalid EXTRACTVAL index"); 02184 EXTRACTVALIdx.push_back((unsigned)Index); 02185 } 02186 02187 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx); 02188 InstructionList.push_back(I); 02189 break; 02190 } 02191 02192 case bitc::FUNC_CODE_INST_INSERTVAL: { 02193 // INSERTVAL: [opty, opval, opty, opval, n x indices] 02194 unsigned OpNum = 0; 02195 Value *Agg; 02196 if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) 02197 return Error("Invalid INSERTVAL record"); 02198 Value *Val; 02199 if (getValueTypePair(Record, OpNum, NextValueNo, Val)) 02200 return Error("Invalid INSERTVAL record"); 02201 02202 SmallVector<unsigned, 4> INSERTVALIdx; 02203 for (unsigned RecSize = Record.size(); 02204 OpNum != RecSize; ++OpNum) { 02205 uint64_t Index = Record[OpNum]; 02206 if ((unsigned)Index != Index) 02207 return Error("Invalid INSERTVAL index"); 02208 INSERTVALIdx.push_back((unsigned)Index); 02209 } 02210 02211 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx); 02212 InstructionList.push_back(I); 02213 break; 02214 } 02215 02216 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval] 02217 // obsolete form of select 02218 // handles select i1 ... in old bitcode 02219 unsigned OpNum = 0; 02220 Value *TrueVal, *FalseVal, *Cond; 02221 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 02222 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 02223 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond)) 02224 return Error("Invalid SELECT record"); 02225 02226 I = SelectInst::Create(Cond, TrueVal, FalseVal); 02227 InstructionList.push_back(I); 02228 break; 02229 } 02230 02231 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] 02232 // new form of select 02233 // handles select i1 or select [N x i1] 02234 unsigned OpNum = 0; 02235 Value *TrueVal, *FalseVal, *Cond; 02236 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) || 02237 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) || 02238 getValueTypePair(Record, OpNum, NextValueNo, Cond)) 02239 return Error("Invalid SELECT record"); 02240 02241 // select condition can be either i1 or [N x i1] 02242 if (VectorType* vector_type = 02243 dyn_cast<VectorType>(Cond->getType())) { 02244 // expect <n x i1> 02245 if (vector_type->getElementType() != Type::getInt1Ty(Context)) 02246 return Error("Invalid SELECT condition type"); 02247 } else { 02248 // expect i1 02249 if (Cond->getType() != Type::getInt1Ty(Context)) 02250 return Error("Invalid SELECT condition type"); 02251 } 02252 02253 I = SelectInst::Create(Cond, TrueVal, FalseVal); 02254 InstructionList.push_back(I); 02255 break; 02256 } 02257 02258 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval] 02259 unsigned OpNum = 0; 02260 Value *Vec, *Idx; 02261 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 02262 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 02263 return Error("Invalid EXTRACTELT record"); 02264 I = ExtractElementInst::Create(Vec, Idx); 02265 InstructionList.push_back(I); 02266 break; 02267 } 02268 02269 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval] 02270 unsigned OpNum = 0; 02271 Value *Vec, *Elt, *Idx; 02272 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) || 02273 popValue(Record, OpNum, NextValueNo, 02274 cast<VectorType>(Vec->getType())->getElementType(), Elt) || 02275 popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx)) 02276 return Error("Invalid INSERTELT record"); 02277 I = InsertElementInst::Create(Vec, Elt, Idx); 02278 InstructionList.push_back(I); 02279 break; 02280 } 02281 02282 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] 02283 unsigned OpNum = 0; 02284 Value *Vec1, *Vec2, *Mask; 02285 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || 02286 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2)) 02287 return Error("Invalid SHUFFLEVEC record"); 02288 02289 if (getValueTypePair(Record, OpNum, NextValueNo, Mask)) 02290 return Error("Invalid SHUFFLEVEC record"); 02291 I = new ShuffleVectorInst(Vec1, Vec2, Mask); 02292 InstructionList.push_back(I); 02293 break; 02294 } 02295 02296 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] 02297 // Old form of ICmp/FCmp returning bool 02298 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were 02299 // both legal on vectors but had different behaviour. 02300 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] 02301 // FCmp/ICmp returning bool or vector of bool 02302 02303 unsigned OpNum = 0; 02304 Value *LHS, *RHS; 02305 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || 02306 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || 02307 OpNum+1 != Record.size()) 02308 return Error("Invalid CMP record"); 02309 02310 if (LHS->getType()->isFPOrFPVectorTy()) 02311 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS); 02312 else 02313 I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS); 02314 InstructionList.push_back(I); 02315 break; 02316 } 02317 02318 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>] 02319 { 02320 unsigned Size = Record.size(); 02321 if (Size == 0) { 02322 I = ReturnInst::Create(Context); 02323 InstructionList.push_back(I); 02324 break; 02325 } 02326 02327 unsigned OpNum = 0; 02328 Value *Op = NULL; 02329 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 02330 return Error("Invalid RET record"); 02331 if (OpNum != Record.size()) 02332 return Error("Invalid RET record"); 02333 02334 I = ReturnInst::Create(Context, Op); 02335 InstructionList.push_back(I); 02336 break; 02337 } 02338 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] 02339 if (Record.size() != 1 && Record.size() != 3) 02340 return Error("Invalid BR record"); 02341 BasicBlock *TrueDest = getBasicBlock(Record[0]); 02342 if (TrueDest == 0) 02343 return Error("Invalid BR record"); 02344 02345 if (Record.size() == 1) { 02346 I = BranchInst::Create(TrueDest); 02347 InstructionList.push_back(I); 02348 } 02349 else { 02350 BasicBlock *FalseDest = getBasicBlock(Record[1]); 02351 Value *Cond = getValue(Record, 2, NextValueNo, 02352 Type::getInt1Ty(Context)); 02353 if (FalseDest == 0 || Cond == 0) 02354 return Error("Invalid BR record"); 02355 I = BranchInst::Create(TrueDest, FalseDest, Cond); 02356 InstructionList.push_back(I); 02357 } 02358 break; 02359 } 02360 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...] 02361 // Check magic 02362 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) { 02363 // New SwitchInst format with case ranges. 02364 02365 Type *OpTy = getTypeByID(Record[1]); 02366 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth(); 02367 02368 Value *Cond = getValue(Record, 2, NextValueNo, OpTy); 02369 BasicBlock *Default = getBasicBlock(Record[3]); 02370 if (OpTy == 0 || Cond == 0 || Default == 0) 02371 return Error("Invalid SWITCH record"); 02372 02373 unsigned NumCases = Record[4]; 02374 02375 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 02376 InstructionList.push_back(SI); 02377 02378 unsigned CurIdx = 5; 02379 for (unsigned i = 0; i != NumCases; ++i) { 02380 IntegersSubsetToBB CaseBuilder; 02381 unsigned NumItems = Record[CurIdx++]; 02382 for (unsigned ci = 0; ci != NumItems; ++ci) { 02383 bool isSingleNumber = Record[CurIdx++]; 02384 02385 APInt Low; 02386 unsigned ActiveWords = 1; 02387 if (ValueBitWidth > 64) 02388 ActiveWords = Record[CurIdx++]; 02389 Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 02390 ValueBitWidth); 02391 CurIdx += ActiveWords; 02392 02393 if (!isSingleNumber) { 02394 ActiveWords = 1; 02395 if (ValueBitWidth > 64) 02396 ActiveWords = Record[CurIdx++]; 02397 APInt High = 02398 ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords), 02399 ValueBitWidth); 02400 02401 CaseBuilder.add(IntItem::fromType(OpTy, Low), 02402 IntItem::fromType(OpTy, High)); 02403 CurIdx += ActiveWords; 02404 } else 02405 CaseBuilder.add(IntItem::fromType(OpTy, Low)); 02406 } 02407 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); 02408 IntegersSubset Case = CaseBuilder.getCase(); 02409 SI->addCase(Case, DestBB); 02410 } 02411 uint16_t Hash = SI->hash(); 02412 if (Hash != (Record[0] & 0xFFFF)) 02413 return Error("Invalid SWITCH record"); 02414 I = SI; 02415 break; 02416 } 02417 02418 // Old SwitchInst format without case ranges. 02419 02420 if (Record.size() < 3 || (Record.size() & 1) == 0) 02421 return Error("Invalid SWITCH record"); 02422 Type *OpTy = getTypeByID(Record[0]); 02423 Value *Cond = getValue(Record, 1, NextValueNo, OpTy); 02424 BasicBlock *Default = getBasicBlock(Record[2]); 02425 if (OpTy == 0 || Cond == 0 || Default == 0) 02426 return Error("Invalid SWITCH record"); 02427 unsigned NumCases = (Record.size()-3)/2; 02428 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); 02429 InstructionList.push_back(SI); 02430 for (unsigned i = 0, e = NumCases; i != e; ++i) { 02431 ConstantInt *CaseVal = 02432 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy)); 02433 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); 02434 if (CaseVal == 0 || DestBB == 0) { 02435 delete SI; 02436 return Error("Invalid SWITCH record!"); 02437 } 02438 SI->addCase(CaseVal, DestBB); 02439 } 02440 I = SI; 02441 break; 02442 } 02443 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...] 02444 if (Record.size() < 2) 02445 return Error("Invalid INDIRECTBR record"); 02446 Type *OpTy = getTypeByID(Record[0]); 02447 Value *Address = getValue(Record, 1, NextValueNo, OpTy); 02448 if (OpTy == 0 || Address == 0) 02449 return Error("Invalid INDIRECTBR record"); 02450 unsigned NumDests = Record.size()-2; 02451 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); 02452 InstructionList.push_back(IBI); 02453 for (unsigned i = 0, e = NumDests; i != e; ++i) { 02454 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { 02455 IBI->addDestination(DestBB); 02456 } else { 02457 delete IBI; 02458 return Error("Invalid INDIRECTBR record!"); 02459 } 02460 } 02461 I = IBI; 02462 break; 02463 } 02464 02465 case bitc::FUNC_CODE_INST_INVOKE: { 02466 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...] 02467 if (Record.size() < 4) return Error("Invalid INVOKE record"); 02468 AttributeSet PAL = getAttributes(Record[0]); 02469 unsigned CCInfo = Record[1]; 02470 BasicBlock *NormalBB = getBasicBlock(Record[2]); 02471 BasicBlock *UnwindBB = getBasicBlock(Record[3]); 02472 02473 unsigned OpNum = 4; 02474 Value *Callee; 02475 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 02476 return Error("Invalid INVOKE record"); 02477 02478 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType()); 02479 FunctionType *FTy = !CalleeTy ? 0 : 02480 dyn_cast<FunctionType>(CalleeTy->getElementType()); 02481 02482 // Check that the right number of fixed parameters are here. 02483 if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 || 02484 Record.size() < OpNum+FTy->getNumParams()) 02485 return Error("Invalid INVOKE record"); 02486 02487 SmallVector<Value*, 16> Ops; 02488 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 02489 Ops.push_back(getValue(Record, OpNum, NextValueNo, 02490 FTy->getParamType(i))); 02491 if (Ops.back() == 0) return Error("Invalid INVOKE record"); 02492 } 02493 02494 if (!FTy->isVarArg()) { 02495 if (Record.size() != OpNum) 02496 return Error("Invalid INVOKE record"); 02497 } else { 02498 // Read type/value pairs for varargs params. 02499 while (OpNum != Record.size()) { 02500 Value *Op; 02501 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 02502 return Error("Invalid INVOKE record"); 02503 Ops.push_back(Op); 02504 } 02505 } 02506 02507 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops); 02508 InstructionList.push_back(I); 02509 cast<InvokeInst>(I)->setCallingConv( 02510 static_cast<CallingConv::ID>(CCInfo)); 02511 cast<InvokeInst>(I)->setAttributes(PAL); 02512 break; 02513 } 02514 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval] 02515 unsigned Idx = 0; 02516 Value *Val = 0; 02517 if (getValueTypePair(Record, Idx, NextValueNo, Val)) 02518 return Error("Invalid RESUME record"); 02519 I = ResumeInst::Create(Val); 02520 InstructionList.push_back(I); 02521 break; 02522 } 02523 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE 02524 I = new UnreachableInst(Context); 02525 InstructionList.push_back(I); 02526 break; 02527 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] 02528 if (Record.size() < 1 || ((Record.size()-1)&1)) 02529 return Error("Invalid PHI record"); 02530 Type *Ty = getTypeByID(Record[0]); 02531 if (!Ty) return Error("Invalid PHI record"); 02532 02533 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); 02534 InstructionList.push_back(PN); 02535 02536 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { 02537 Value *V; 02538 // With the new function encoding, it is possible that operands have 02539 // negative IDs (for forward references). Use a signed VBR 02540 // representation to keep the encoding small. 02541 if (UseRelativeIDs) 02542 V = getValueSigned(Record, 1+i, NextValueNo, Ty); 02543 else 02544 V = getValue(Record, 1+i, NextValueNo, Ty); 02545 BasicBlock *BB = getBasicBlock(Record[2+i]); 02546 if (!V || !BB) return Error("Invalid PHI record"); 02547 PN->addIncoming(V, BB); 02548 } 02549 I = PN; 02550 break; 02551 } 02552 02553 case bitc::FUNC_CODE_INST_LANDINGPAD: { 02554 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?] 02555 unsigned Idx = 0; 02556 if (Record.size() < 4) 02557 return Error("Invalid LANDINGPAD record"); 02558 Type *Ty = getTypeByID(Record[Idx++]); 02559 if (!Ty) return Error("Invalid LANDINGPAD record"); 02560 Value *PersFn = 0; 02561 if (getValueTypePair(Record, Idx, NextValueNo, PersFn)) 02562 return Error("Invalid LANDINGPAD record"); 02563 02564 bool IsCleanup = !!Record[Idx++]; 02565 unsigned NumClauses = Record[Idx++]; 02566 LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses); 02567 LP->setCleanup(IsCleanup); 02568 for (unsigned J = 0; J != NumClauses; ++J) { 02569 LandingPadInst::ClauseType CT = 02570 LandingPadInst::ClauseType(Record[Idx++]); (void)CT; 02571 Value *Val; 02572 02573 if (getValueTypePair(Record, Idx, NextValueNo, Val)) { 02574 delete LP; 02575 return Error("Invalid LANDINGPAD record"); 02576 } 02577 02578 assert((CT != LandingPadInst::Catch || 02579 !isa<ArrayType>(Val->getType())) && 02580 "Catch clause has a invalid type!"); 02581 assert((CT != LandingPadInst::Filter || 02582 isa<ArrayType>(Val->getType())) && 02583 "Filter clause has invalid type!"); 02584 LP->addClause(Val); 02585 } 02586 02587 I = LP; 02588 InstructionList.push_back(I); 02589 break; 02590 } 02591 02592 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align] 02593 if (Record.size() != 4) 02594 return Error("Invalid ALLOCA record"); 02595 PointerType *Ty = 02596 dyn_cast_or_null<PointerType>(getTypeByID(Record[0])); 02597 Type *OpTy = getTypeByID(Record[1]); 02598 Value *Size = getFnValueByID(Record[2], OpTy); 02599 unsigned Align = Record[3]; 02600 if (!Ty || !Size) return Error("Invalid ALLOCA record"); 02601 I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1); 02602 InstructionList.push_back(I); 02603 break; 02604 } 02605 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol] 02606 unsigned OpNum = 0; 02607 Value *Op; 02608 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 02609 OpNum+2 != Record.size()) 02610 return Error("Invalid LOAD record"); 02611 02612 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1); 02613 InstructionList.push_back(I); 02614 break; 02615 } 02616 case bitc::FUNC_CODE_INST_LOADATOMIC: { 02617 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope] 02618 unsigned OpNum = 0; 02619 Value *Op; 02620 if (getValueTypePair(Record, OpNum, NextValueNo, Op) || 02621 OpNum+4 != Record.size()) 02622 return Error("Invalid LOADATOMIC record"); 02623 02624 02625 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 02626 if (Ordering == NotAtomic || Ordering == Release || 02627 Ordering == AcquireRelease) 02628 return Error("Invalid LOADATOMIC record"); 02629 if (Ordering != NotAtomic && Record[OpNum] == 0) 02630 return Error("Invalid LOADATOMIC record"); 02631 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 02632 02633 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1, 02634 Ordering, SynchScope); 02635 InstructionList.push_back(I); 02636 break; 02637 } 02638 case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol] 02639 unsigned OpNum = 0; 02640 Value *Val, *Ptr; 02641 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 02642 popValue(Record, OpNum, NextValueNo, 02643 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 02644 OpNum+2 != Record.size()) 02645 return Error("Invalid STORE record"); 02646 02647 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1); 02648 InstructionList.push_back(I); 02649 break; 02650 } 02651 case bitc::FUNC_CODE_INST_STOREATOMIC: { 02652 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope] 02653 unsigned OpNum = 0; 02654 Value *Val, *Ptr; 02655 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 02656 popValue(Record, OpNum, NextValueNo, 02657 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 02658 OpNum+4 != Record.size()) 02659 return Error("Invalid STOREATOMIC record"); 02660 02661 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 02662 if (Ordering == NotAtomic || Ordering == Acquire || 02663 Ordering == AcquireRelease) 02664 return Error("Invalid STOREATOMIC record"); 02665 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 02666 if (Ordering != NotAtomic && Record[OpNum] == 0) 02667 return Error("Invalid STOREATOMIC record"); 02668 02669 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1, 02670 Ordering, SynchScope); 02671 InstructionList.push_back(I); 02672 break; 02673 } 02674 case bitc::FUNC_CODE_INST_CMPXCHG: { 02675 // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope] 02676 unsigned OpNum = 0; 02677 Value *Ptr, *Cmp, *New; 02678 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 02679 popValue(Record, OpNum, NextValueNo, 02680 cast<PointerType>(Ptr->getType())->getElementType(), Cmp) || 02681 popValue(Record, OpNum, NextValueNo, 02682 cast<PointerType>(Ptr->getType())->getElementType(), New) || 02683 OpNum+3 != Record.size()) 02684 return Error("Invalid CMPXCHG record"); 02685 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]); 02686 if (Ordering == NotAtomic || Ordering == Unordered) 02687 return Error("Invalid CMPXCHG record"); 02688 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]); 02689 I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope); 02690 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]); 02691 InstructionList.push_back(I); 02692 break; 02693 } 02694 case bitc::FUNC_CODE_INST_ATOMICRMW: { 02695 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope] 02696 unsigned OpNum = 0; 02697 Value *Ptr, *Val; 02698 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || 02699 popValue(Record, OpNum, NextValueNo, 02700 cast<PointerType>(Ptr->getType())->getElementType(), Val) || 02701 OpNum+4 != Record.size()) 02702 return Error("Invalid ATOMICRMW record"); 02703 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]); 02704 if (Operation < AtomicRMWInst::FIRST_BINOP || 02705 Operation > AtomicRMWInst::LAST_BINOP) 02706 return Error("Invalid ATOMICRMW record"); 02707 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]); 02708 if (Ordering == NotAtomic || Ordering == Unordered) 02709 return Error("Invalid ATOMICRMW record"); 02710 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]); 02711 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope); 02712 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]); 02713 InstructionList.push_back(I); 02714 break; 02715 } 02716 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope] 02717 if (2 != Record.size()) 02718 return Error("Invalid FENCE record"); 02719 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]); 02720 if (Ordering == NotAtomic || Ordering == Unordered || 02721 Ordering == Monotonic) 02722 return Error("Invalid FENCE record"); 02723 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]); 02724 I = new FenceInst(Context, Ordering, SynchScope); 02725 InstructionList.push_back(I); 02726 break; 02727 } 02728 case bitc::FUNC_CODE_INST_CALL: { 02729 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...] 02730 if (Record.size() < 3) 02731 return Error("Invalid CALL record"); 02732 02733 AttributeSet PAL = getAttributes(Record[0]); 02734 unsigned CCInfo = Record[1]; 02735 02736 unsigned OpNum = 2; 02737 Value *Callee; 02738 if (getValueTypePair(Record, OpNum, NextValueNo, Callee)) 02739 return Error("Invalid CALL record"); 02740 02741 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType()); 02742 FunctionType *FTy = 0; 02743 if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType()); 02744 if (!FTy || Record.size() < FTy->getNumParams()+OpNum) 02745 return Error("Invalid CALL record"); 02746 02747 SmallVector<Value*, 16> Args; 02748 // Read the fixed params. 02749 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { 02750 if (FTy->getParamType(i)->isLabelTy()) 02751 Args.push_back(getBasicBlock(Record[OpNum])); 02752 else 02753 Args.push_back(getValue(Record, OpNum, NextValueNo, 02754 FTy->getParamType(i))); 02755 if (Args.back() == 0) return Error("Invalid CALL record"); 02756 } 02757 02758 // Read type/value pairs for varargs params. 02759 if (!FTy->isVarArg()) { 02760 if (OpNum != Record.size()) 02761 return Error("Invalid CALL record"); 02762 } else { 02763 while (OpNum != Record.size()) { 02764 Value *Op; 02765 if (getValueTypePair(Record, OpNum, NextValueNo, Op)) 02766 return Error("Invalid CALL record"); 02767 Args.push_back(Op); 02768 } 02769 } 02770 02771 I = CallInst::Create(Callee, Args); 02772 InstructionList.push_back(I); 02773 cast<CallInst>(I)->setCallingConv( 02774 static_cast<CallingConv::ID>(CCInfo>>1)); 02775 cast<CallInst>(I)->setTailCall(CCInfo & 1); 02776 cast<CallInst>(I)->setAttributes(PAL); 02777 break; 02778 } 02779 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty] 02780 if (Record.size() < 3) 02781 return Error("Invalid VAARG record"); 02782 Type *OpTy = getTypeByID(Record[0]); 02783 Value *Op = getValue(Record, 1, NextValueNo, OpTy); 02784 Type *ResTy = getTypeByID(Record[2]); 02785 if (!OpTy || !Op || !ResTy) 02786 return Error("Invalid VAARG record"); 02787 I = new VAArgInst(Op, ResTy); 02788 InstructionList.push_back(I); 02789 break; 02790 } 02791 } 02792 02793 // Add instruction to end of current BB. If there is no current BB, reject 02794 // this file. 02795 if (CurBB == 0) { 02796 delete I; 02797 return Error("Invalid instruction with no BB"); 02798 } 02799 CurBB->getInstList().push_back(I); 02800 02801 // If this was a terminator instruction, move to the next block. 02802 if (isa<TerminatorInst>(I)) { 02803 ++CurBBNo; 02804 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0; 02805 } 02806 02807 // Non-void values get registered in the value table for future use. 02808 if (I && !I->getType()->isVoidTy()) 02809 ValueList.AssignValue(I, NextValueNo++); 02810 } 02811 02812 OutOfRecordLoop: 02813 02814 // Check the function list for unresolved values. 02815 if (Argument *A = dyn_cast<Argument>(ValueList.back())) { 02816 if (A->getParent() == 0) { 02817 // We found at least one unresolved value. Nuke them all to avoid leaks. 02818 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ 02819 if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) { 02820 A->replaceAllUsesWith(UndefValue::get(A->getType())); 02821 delete A; 02822 } 02823 } 02824 return Error("Never resolved value found in function!"); 02825 } 02826 } 02827 02828 // FIXME: Check for unresolved forward-declared metadata references 02829 // and clean up leaks. 02830 02831 // See if anything took the address of blocks in this function. If so, 02832 // resolve them now. 02833 DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI = 02834 BlockAddrFwdRefs.find(F); 02835 if (BAFRI != BlockAddrFwdRefs.end()) { 02836 std::vector<BlockAddrRefTy> &RefList = BAFRI->second; 02837 for (unsigned i = 0, e = RefList.size(); i != e; ++i) { 02838 unsigned BlockIdx = RefList[i].first; 02839 if (BlockIdx >= FunctionBBs.size()) 02840 return Error("Invalid blockaddress block #"); 02841 02842 GlobalVariable *FwdRef = RefList[i].second; 02843 FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx])); 02844 FwdRef->eraseFromParent(); 02845 } 02846 02847 BlockAddrFwdRefs.erase(BAFRI); 02848 } 02849 02850 // Trim the value list down to the size it was before we parsed this function. 02851 ValueList.shrinkTo(ModuleValueListSize); 02852 MDValueList.shrinkTo(ModuleMDValueListSize); 02853 std::vector<BasicBlock*>().swap(FunctionBBs); 02854 return false; 02855 } 02856 02857 /// FindFunctionInStream - Find the function body in the bitcode stream 02858 bool BitcodeReader::FindFunctionInStream(Function *F, 02859 DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) { 02860 while (DeferredFunctionInfoIterator->second == 0) { 02861 if (Stream.AtEndOfStream()) 02862 return Error("Could not find Function in stream"); 02863 // ParseModule will parse the next body in the stream and set its 02864 // position in the DeferredFunctionInfo map. 02865 if (ParseModule(true)) return true; 02866 } 02867 return false; 02868 } 02869 02870 //===----------------------------------------------------------------------===// 02871 // GVMaterializer implementation 02872 //===----------------------------------------------------------------------===// 02873 02874 02875 bool BitcodeReader::isMaterializable(const GlobalValue *GV) const { 02876 if (const Function *F = dyn_cast<Function>(GV)) { 02877 return F->isDeclaration() && 02878 DeferredFunctionInfo.count(const_cast<Function*>(F)); 02879 } 02880 return false; 02881 } 02882 02883 bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) { 02884 Function *F = dyn_cast<Function>(GV); 02885 // If it's not a function or is already material, ignore the request. 02886 if (!F || !F->isMaterializable()) return false; 02887 02888 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F); 02889 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); 02890 // If its position is recorded as 0, its body is somewhere in the stream 02891 // but we haven't seen it yet. 02892 if (DFII->second == 0) 02893 if (LazyStreamer && FindFunctionInStream(F, DFII)) return true; 02894 02895 // Move the bit stream to the saved position of the deferred function body. 02896 Stream.JumpToBit(DFII->second); 02897 02898 if (ParseFunctionBody(F)) { 02899 if (ErrInfo) *ErrInfo = ErrorString; 02900 return true; 02901 } 02902 02903 // Upgrade any old intrinsic calls in the function. 02904 for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(), 02905 E = UpgradedIntrinsics.end(); I != E; ++I) { 02906 if (I->first != I->second) { 02907 for (Value::use_iterator UI = I->first->use_begin(), 02908 UE = I->first->use_end(); UI != UE; ) { 02909 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 02910 UpgradeIntrinsicCall(CI, I->second); 02911 } 02912 } 02913 } 02914 02915 return false; 02916 } 02917 02918 bool BitcodeReader::isDematerializable(const GlobalValue *GV) const { 02919 const Function *F = dyn_cast<Function>(GV); 02920 if (!F || F->isDeclaration()) 02921 return false; 02922 return DeferredFunctionInfo.count(const_cast<Function*>(F)); 02923 } 02924 02925 void BitcodeReader::Dematerialize(GlobalValue *GV) { 02926 Function *F = dyn_cast<Function>(GV); 02927 // If this function isn't dematerializable, this is a noop. 02928 if (!F || !isDematerializable(F)) 02929 return; 02930 02931 assert(DeferredFunctionInfo.count(F) && "No info to read function later?"); 02932 02933 // Just forget the function body, we can remat it later. 02934 F->deleteBody(); 02935 } 02936 02937 02938 bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) { 02939 assert(M == TheModule && 02940 "Can only Materialize the Module this BitcodeReader is attached to."); 02941 // Iterate over the module, deserializing any functions that are still on 02942 // disk. 02943 for (Module::iterator F = TheModule->begin(), E = TheModule->end(); 02944 F != E; ++F) 02945 if (F->isMaterializable() && 02946 Materialize(F, ErrInfo)) 02947 return true; 02948 02949 // At this point, if there are any function bodies, the current bit is 02950 // pointing to the END_BLOCK record after them. Now make sure the rest 02951 // of the bits in the module have been read. 02952 if (NextUnreadBit) 02953 ParseModule(true); 02954 02955 // Upgrade any intrinsic calls that slipped through (should not happen!) and 02956 // delete the old functions to clean up. We can't do this unless the entire 02957 // module is materialized because there could always be another function body 02958 // with calls to the old function. 02959 for (std::vector<std::pair<Function*, Function*> >::iterator I = 02960 UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) { 02961 if (I->first != I->second) { 02962 for (Value::use_iterator UI = I->first->use_begin(), 02963 UE = I->first->use_end(); UI != UE; ) { 02964 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) 02965 UpgradeIntrinsicCall(CI, I->second); 02966 } 02967 if (!I->first->use_empty()) 02968 I->first->replaceAllUsesWith(I->second); 02969 I->first->eraseFromParent(); 02970 } 02971 } 02972 std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics); 02973 02974 return false; 02975 } 02976 02977 bool BitcodeReader::InitStream() { 02978 if (LazyStreamer) return InitLazyStream(); 02979 return InitStreamFromBuffer(); 02980 } 02981 02982 bool BitcodeReader::InitStreamFromBuffer() { 02983 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart(); 02984 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize(); 02985 02986 if (Buffer->getBufferSize() & 3) { 02987 if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd)) 02988 return Error("Invalid bitcode signature"); 02989 else 02990 return Error("Bitcode stream should be a multiple of 4 bytes in length"); 02991 } 02992 02993 // If we have a wrapper header, parse it and ignore the non-bc file contents. 02994 // The magic number is 0x0B17C0DE stored in little endian. 02995 if (isBitcodeWrapper(BufPtr, BufEnd)) 02996 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true)) 02997 return Error("Invalid bitcode wrapper header"); 02998 02999 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd)); 03000 Stream.init(*StreamFile); 03001 03002 return false; 03003 } 03004 03005 bool BitcodeReader::InitLazyStream() { 03006 // Check and strip off the bitcode wrapper; BitstreamReader expects never to 03007 // see it. 03008 StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer); 03009 StreamFile.reset(new BitstreamReader(Bytes)); 03010 Stream.init(*StreamFile); 03011 03012 unsigned char buf[16]; 03013 if (Bytes->readBytes(0, 16, buf) == -1) 03014 return Error("Bitcode stream must be at least 16 bytes in length"); 03015 03016 if (!isBitcode(buf, buf + 16)) 03017 return Error("Invalid bitcode signature"); 03018 03019 if (isBitcodeWrapper(buf, buf + 4)) { 03020 const unsigned char *bitcodeStart = buf; 03021 const unsigned char *bitcodeEnd = buf + 16; 03022 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false); 03023 Bytes->dropLeadingBytes(bitcodeStart - buf); 03024 Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart); 03025 } 03026 return false; 03027 } 03028 03029 //===----------------------------------------------------------------------===// 03030 // External interface 03031 //===----------------------------------------------------------------------===// 03032 03033 /// getLazyBitcodeModule - lazy function-at-a-time loading from a file. 03034 /// 03035 Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer, 03036 LLVMContext& Context, 03037 std::string *ErrMsg) { 03038 Module *M = new Module(Buffer->getBufferIdentifier(), Context); 03039 BitcodeReader *R = new BitcodeReader(Buffer, Context); 03040 M->setMaterializer(R); 03041 if (R->ParseBitcodeInto(M)) { 03042 if (ErrMsg) 03043 *ErrMsg = R->getErrorString(); 03044 03045 delete M; // Also deletes R. 03046 return 0; 03047 } 03048 // Have the BitcodeReader dtor delete 'Buffer'. 03049 R->setBufferOwned(true); 03050 03051 R->materializeForwardReferencedFunctions(); 03052 03053 return M; 03054 } 03055 03056 03057 Module *llvm::getStreamedBitcodeModule(const std::string &name, 03058 DataStreamer *streamer, 03059 LLVMContext &Context, 03060 std::string *ErrMsg) { 03061 Module *M = new Module(name, Context); 03062 BitcodeReader *R = new BitcodeReader(streamer, Context); 03063 M->setMaterializer(R); 03064 if (R->ParseBitcodeInto(M)) { 03065 if (ErrMsg) 03066 *ErrMsg = R->getErrorString(); 03067 delete M; // Also deletes R. 03068 return 0; 03069 } 03070 R->setBufferOwned(false); // no buffer to delete 03071 return M; 03072 } 03073 03074 /// ParseBitcodeFile - Read the specified bitcode file, returning the module. 03075 /// If an error occurs, return null and fill in *ErrMsg if non-null. 03076 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context, 03077 std::string *ErrMsg){ 03078 Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg); 03079 if (!M) return 0; 03080 03081 // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether 03082 // there was an error. 03083 static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false); 03084 03085 // Read in the entire module, and destroy the BitcodeReader. 03086 if (M->MaterializeAllPermanently(ErrMsg)) { 03087 delete M; 03088 return 0; 03089 } 03090 03091 // TODO: Restore the use-lists to the in-memory state when the bitcode was 03092 // written. We must defer until the Module has been fully materialized. 03093 03094 return M; 03095 } 03096 03097 std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer, 03098 LLVMContext& Context, 03099 std::string *ErrMsg) { 03100 BitcodeReader *R = new BitcodeReader(Buffer, Context); 03101 // Don't let the BitcodeReader dtor delete 'Buffer'. 03102 R->setBufferOwned(false); 03103 03104 std::string Triple(""); 03105 if (R->ParseTriple(Triple)) 03106 if (ErrMsg) 03107 *ErrMsg = R->getErrorString(); 03108 03109 delete R; 03110 return Triple; 03111 }