Index: llvm/include/llvm/IR/DerivedTypes.h =================================================================== --- llvm/include/llvm/IR/DerivedTypes.h +++ llvm/include/llvm/IR/DerivedTypes.h @@ -270,6 +270,10 @@ return create(StructFields, Name); } + /// This static method returns a StructType by that name if one exists, and a + /// null pointer otherwise. + static StructType *getIfExists(LLVMContext &Context, StringRef Name); + /// This static method is the primary way to create a literal StructType. static StructType *get(LLVMContext &Context, ArrayRef Elements, bool isPacked = false); Index: llvm/lib/Bitcode/Reader/BitcodeReader.cpp =================================================================== --- llvm/lib/Bitcode/Reader/BitcodeReader.cpp +++ llvm/lib/Bitcode/Reader/BitcodeReader.cpp @@ -211,9 +211,9 @@ case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#] unsigned epoch = (unsigned)Record[0]; if (epoch != bitc::BITCODE_CURRENT_EPOCH) { - return error( - Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + - "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'"); + return error(Twine("Incompatible epoch: Bitcode '") + Twine(epoch) + + "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + + "'"); } } } @@ -367,8 +367,9 @@ if (!MaybeRecord) return MaybeRecord.takeError(); switch (MaybeRecord.get()) { - default: break; // Default behavior, ignore unknown content. - case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] + default: + break; // Default behavior, ignore unknown content. + case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); @@ -493,7 +494,7 @@ std::vector SectionTable; std::vector GCTable; - std::vector TypeList; + std::vector TypeList; BitcodeReaderValueList ValueList; Optional MDLoader; std::vector ComdatList; @@ -514,11 +515,11 @@ /// While parsing a function body, this is a list of the basic blocks for the /// function. - std::vector FunctionBBs; + std::vector FunctionBBs; // When reading the module header, this list is populated with functions that // have bodies later in the file. - std::vector FunctionsWithBodies; + std::vector FunctionsWithBodies; // When intrinsic functions are encountered which require upgrading they are // stored here with their replacement function. @@ -534,7 +535,7 @@ /// When function bodies are initially scanned, this map contains info about /// where to find deferred function body in the stream. - DenseMap DeferredFunctionInfo; + DenseMap DeferredFunctionInfo; /// When Metadata block is initially scanned when parsing the module, we may /// choose to defer parsing of the metadata. This vector contains info about @@ -589,8 +590,6 @@ private: std::vector IdentifiedStructTypes; - StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name); - StructType *createIdentifiedStructType(LLVMContext &Context); Type *getTypeByID(unsigned ID); @@ -605,13 +604,14 @@ } BasicBlock *getBasicBlock(unsigned ID) const { - if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID + if (ID >= FunctionBBs.size()) + return nullptr; // Invalid ID return FunctionBBs[ID]; } AttributeList getAttributes(unsigned i) const { - if (i-1 < MAttributes.size()) - return MAttributes[i-1]; + if (i - 1 < MAttributes.size()) + return MAttributes[i - 1]; return AttributeList(); } @@ -620,7 +620,8 @@ /// failure. bool getValueTypePair(SmallVectorImpl &Record, unsigned &Slot, unsigned InstNum, Value *&ResVal) { - if (Slot == Record.size()) return true; + if (Slot == Record.size()) + return true; unsigned ValNo = (unsigned)Record[Slot++]; // Adjust the ValNo, if it was encoded relative to the InstNum. if (UseRelativeIDs) @@ -662,7 +663,8 @@ /// error. Value *getValue(SmallVectorImpl &Record, unsigned Slot, unsigned InstNum, Type *Ty) { - if (Slot == Record.size()) return nullptr; + if (Slot == Record.size()) + return nullptr; unsigned ValNo = (unsigned)Record[Slot]; // Adjust the ValNo, if it was encoded relative to the InstNum. if (UseRelativeIDs) @@ -673,7 +675,8 @@ /// Like getValue, but decodes signed VBRs. Value *getValueSigned(SmallVectorImpl &Record, unsigned Slot, unsigned InstNum, Type *Ty) { - if (Slot == Record.size()) return nullptr; + if (Slot == Record.size()) + return nullptr; unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]); // Adjust the ValNo, if it was encoded relative to the InstNum. if (UseRelativeIDs) @@ -901,7 +904,7 @@ return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage case 15: return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage - case 1: // Old value with implicit comdat. + case 1: // Old value with implicit comdat. case 16: return GlobalValue::WeakAnyLinkage; case 10: // Old value with implicit comdat. @@ -942,7 +945,8 @@ bool Local = (RawFlags & 0x4); bool AutoHide = (RawFlags & 0x8); - return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local, AutoHide); + return GlobalValueSummary::GVFlags(Linkage, NotEligibleToImport, Live, Local, + AutoHide); } // Decode the flags for GlobalVariable in the summary @@ -953,9 +957,12 @@ static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) { switch (Val) { default: // Map unknown visibilities to default. - case 0: return GlobalValue::DefaultVisibility; - case 1: return GlobalValue::HiddenVisibility; - case 2: return GlobalValue::ProtectedVisibility; + case 0: + return GlobalValue::DefaultVisibility; + case 1: + return GlobalValue::HiddenVisibility; + case 2: + return GlobalValue::ProtectedVisibility; } } @@ -963,56 +970,83 @@ getDecodedDLLStorageClass(unsigned Val) { switch (Val) { default: // Map unknown values to default. - case 0: return GlobalValue::DefaultStorageClass; - case 1: return GlobalValue::DLLImportStorageClass; - case 2: return GlobalValue::DLLExportStorageClass; + case 0: + return GlobalValue::DefaultStorageClass; + case 1: + return GlobalValue::DLLImportStorageClass; + case 2: + return GlobalValue::DLLExportStorageClass; } } static bool getDecodedDSOLocal(unsigned Val) { - switch(Val) { + switch (Val) { default: // Map unknown values to preemptable. - case 0: return false; - case 1: return true; + case 0: + return false; + case 1: + return true; } } static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) { switch (Val) { - case 0: return GlobalVariable::NotThreadLocal; - default: // Map unknown non-zero value to general dynamic. - case 1: return GlobalVariable::GeneralDynamicTLSModel; - case 2: return GlobalVariable::LocalDynamicTLSModel; - case 3: return GlobalVariable::InitialExecTLSModel; - case 4: return GlobalVariable::LocalExecTLSModel; + case 0: + return GlobalVariable::NotThreadLocal; + default: // Map unknown non-zero value to general dynamic. + case 1: + return GlobalVariable::GeneralDynamicTLSModel; + case 2: + return GlobalVariable::LocalDynamicTLSModel; + case 3: + return GlobalVariable::InitialExecTLSModel; + case 4: + return GlobalVariable::LocalExecTLSModel; } } static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) { switch (Val) { - default: // Map unknown to UnnamedAddr::None. - case 0: return GlobalVariable::UnnamedAddr::None; - case 1: return GlobalVariable::UnnamedAddr::Global; - case 2: return GlobalVariable::UnnamedAddr::Local; + default: // Map unknown to UnnamedAddr::None. + case 0: + return GlobalVariable::UnnamedAddr::None; + case 1: + return GlobalVariable::UnnamedAddr::Global; + case 2: + return GlobalVariable::UnnamedAddr::Local; } } static int getDecodedCastOpcode(unsigned Val) { switch (Val) { - default: return -1; - case bitc::CAST_TRUNC : return Instruction::Trunc; - case bitc::CAST_ZEXT : return Instruction::ZExt; - case bitc::CAST_SEXT : return Instruction::SExt; - case bitc::CAST_FPTOUI : return Instruction::FPToUI; - case bitc::CAST_FPTOSI : return Instruction::FPToSI; - case bitc::CAST_UITOFP : return Instruction::UIToFP; - case bitc::CAST_SITOFP : return Instruction::SIToFP; - case bitc::CAST_FPTRUNC : return Instruction::FPTrunc; - case bitc::CAST_FPEXT : return Instruction::FPExt; - case bitc::CAST_PTRTOINT: return Instruction::PtrToInt; - case bitc::CAST_INTTOPTR: return Instruction::IntToPtr; - case bitc::CAST_BITCAST : return Instruction::BitCast; - case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast; + default: + return -1; + case bitc::CAST_TRUNC: + return Instruction::Trunc; + case bitc::CAST_ZEXT: + return Instruction::ZExt; + case bitc::CAST_SEXT: + return Instruction::SExt; + case bitc::CAST_FPTOUI: + return Instruction::FPToUI; + case bitc::CAST_FPTOSI: + return Instruction::FPToSI; + case bitc::CAST_UITOFP: + return Instruction::UIToFP; + case bitc::CAST_SITOFP: + return Instruction::SIToFP; + case bitc::CAST_FPTRUNC: + return Instruction::FPTrunc; + case bitc::CAST_FPEXT: + return Instruction::FPExt; + case bitc::CAST_PTRTOINT: + return Instruction::PtrToInt; + case bitc::CAST_INTTOPTR: + return Instruction::IntToPtr; + case bitc::CAST_BITCAST: + return Instruction::BitCast; + case bitc::CAST_ADDRSPACECAST: + return Instruction::AddrSpaceCast; } } @@ -1070,33 +1104,54 @@ static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) { switch (Val) { - default: return AtomicRMWInst::BAD_BINOP; - case bitc::RMW_XCHG: return AtomicRMWInst::Xchg; - case bitc::RMW_ADD: return AtomicRMWInst::Add; - case bitc::RMW_SUB: return AtomicRMWInst::Sub; - case bitc::RMW_AND: return AtomicRMWInst::And; - case bitc::RMW_NAND: return AtomicRMWInst::Nand; - case bitc::RMW_OR: return AtomicRMWInst::Or; - case bitc::RMW_XOR: return AtomicRMWInst::Xor; - case bitc::RMW_MAX: return AtomicRMWInst::Max; - case bitc::RMW_MIN: return AtomicRMWInst::Min; - case bitc::RMW_UMAX: return AtomicRMWInst::UMax; - case bitc::RMW_UMIN: return AtomicRMWInst::UMin; - case bitc::RMW_FADD: return AtomicRMWInst::FAdd; - case bitc::RMW_FSUB: return AtomicRMWInst::FSub; + default: + return AtomicRMWInst::BAD_BINOP; + case bitc::RMW_XCHG: + return AtomicRMWInst::Xchg; + case bitc::RMW_ADD: + return AtomicRMWInst::Add; + case bitc::RMW_SUB: + return AtomicRMWInst::Sub; + case bitc::RMW_AND: + return AtomicRMWInst::And; + case bitc::RMW_NAND: + return AtomicRMWInst::Nand; + case bitc::RMW_OR: + return AtomicRMWInst::Or; + case bitc::RMW_XOR: + return AtomicRMWInst::Xor; + case bitc::RMW_MAX: + return AtomicRMWInst::Max; + case bitc::RMW_MIN: + return AtomicRMWInst::Min; + case bitc::RMW_UMAX: + return AtomicRMWInst::UMax; + case bitc::RMW_UMIN: + return AtomicRMWInst::UMin; + case bitc::RMW_FADD: + return AtomicRMWInst::FAdd; + case bitc::RMW_FSUB: + return AtomicRMWInst::FSub; } } static AtomicOrdering getDecodedOrdering(unsigned Val) { switch (Val) { - case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic; - case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered; - case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic; - case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire; - case bitc::ORDERING_RELEASE: return AtomicOrdering::Release; - case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease; + case bitc::ORDERING_NOTATOMIC: + return AtomicOrdering::NotAtomic; + case bitc::ORDERING_UNORDERED: + return AtomicOrdering::Unordered; + case bitc::ORDERING_MONOTONIC: + return AtomicOrdering::Monotonic; + case bitc::ORDERING_ACQUIRE: + return AtomicOrdering::Acquire; + case bitc::ORDERING_RELEASE: + return AtomicOrdering::Release; + case bitc::ORDERING_ACQREL: + return AtomicOrdering::AcquireRelease; default: // Map unknown orderings to sequentially-consistent. - case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent; + case bitc::ORDERING_SEQCST: + return AtomicOrdering::SequentiallyConsistent; } } @@ -1139,8 +1194,12 @@ static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) { switch (Val) { - case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break; - case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break; + case 5: + GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); + break; + case 6: + GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); + break; } } @@ -1149,25 +1208,7 @@ if (ID >= TypeList.size()) return nullptr; - if (Type *Ty = TypeList[ID]) - return Ty; - - // If we have a forward reference, the only possible case is when it is to a - // named struct. Just create a placeholder for now. - return TypeList[ID] = createIdentifiedStructType(Context); -} - -StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context, - StringRef Name) { - auto *Ret = StructType::create(Context, Name); - IdentifiedStructTypes.push_back(Ret); - return Ret; -} - -StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) { - auto *Ret = StructType::create(Context); - IdentifiedStructTypes.push_back(Ret); - return Ret; + return TypeList[ID]; } //===----------------------------------------------------------------------===// @@ -1179,61 +1220,116 @@ case Attribute::EndAttrKinds: llvm_unreachable("Synthetic enumerators which should never get here"); - case Attribute::None: return 0; - case Attribute::ZExt: return 1 << 0; - case Attribute::SExt: return 1 << 1; - case Attribute::NoReturn: return 1 << 2; - case Attribute::InReg: return 1 << 3; - case Attribute::StructRet: return 1 << 4; - case Attribute::NoUnwind: return 1 << 5; - case Attribute::NoAlias: return 1 << 6; - case Attribute::ByVal: return 1 << 7; - case Attribute::Nest: return 1 << 8; - case Attribute::ReadNone: return 1 << 9; - case Attribute::ReadOnly: return 1 << 10; - case Attribute::NoInline: return 1 << 11; - case Attribute::AlwaysInline: return 1 << 12; - case Attribute::OptimizeForSize: return 1 << 13; - case Attribute::StackProtect: return 1 << 14; - case Attribute::StackProtectReq: return 1 << 15; - case Attribute::Alignment: return 31 << 16; - case Attribute::NoCapture: return 1 << 21; - case Attribute::NoRedZone: return 1 << 22; - case Attribute::NoImplicitFloat: return 1 << 23; - case Attribute::Naked: return 1 << 24; - case Attribute::InlineHint: return 1 << 25; - case Attribute::StackAlignment: return 7 << 26; - case Attribute::ReturnsTwice: return 1 << 29; - case Attribute::UWTable: return 1 << 30; - case Attribute::NonLazyBind: return 1U << 31; - case Attribute::SanitizeAddress: return 1ULL << 32; - case Attribute::MinSize: return 1ULL << 33; - case Attribute::NoDuplicate: return 1ULL << 34; - case Attribute::StackProtectStrong: return 1ULL << 35; - case Attribute::SanitizeThread: return 1ULL << 36; - case Attribute::SanitizeMemory: return 1ULL << 37; - case Attribute::NoBuiltin: return 1ULL << 38; - case Attribute::Returned: return 1ULL << 39; - case Attribute::Cold: return 1ULL << 40; - case Attribute::Builtin: return 1ULL << 41; - case Attribute::OptimizeNone: return 1ULL << 42; - case Attribute::InAlloca: return 1ULL << 43; - case Attribute::NonNull: return 1ULL << 44; - case Attribute::JumpTable: return 1ULL << 45; - case Attribute::Convergent: return 1ULL << 46; - case Attribute::SafeStack: return 1ULL << 47; - case Attribute::NoRecurse: return 1ULL << 48; - case Attribute::InaccessibleMemOnly: return 1ULL << 49; - case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50; - case Attribute::SwiftSelf: return 1ULL << 51; - case Attribute::SwiftError: return 1ULL << 52; - case Attribute::WriteOnly: return 1ULL << 53; - case Attribute::Speculatable: return 1ULL << 54; - case Attribute::StrictFP: return 1ULL << 55; - case Attribute::SanitizeHWAddress: return 1ULL << 56; - case Attribute::NoCfCheck: return 1ULL << 57; - case Attribute::OptForFuzzing: return 1ULL << 58; - case Attribute::ShadowCallStack: return 1ULL << 59; + case Attribute::None: + return 0; + case Attribute::ZExt: + return 1 << 0; + case Attribute::SExt: + return 1 << 1; + case Attribute::NoReturn: + return 1 << 2; + case Attribute::InReg: + return 1 << 3; + case Attribute::StructRet: + return 1 << 4; + case Attribute::NoUnwind: + return 1 << 5; + case Attribute::NoAlias: + return 1 << 6; + case Attribute::ByVal: + return 1 << 7; + case Attribute::Nest: + return 1 << 8; + case Attribute::ReadNone: + return 1 << 9; + case Attribute::ReadOnly: + return 1 << 10; + case Attribute::NoInline: + return 1 << 11; + case Attribute::AlwaysInline: + return 1 << 12; + case Attribute::OptimizeForSize: + return 1 << 13; + case Attribute::StackProtect: + return 1 << 14; + case Attribute::StackProtectReq: + return 1 << 15; + case Attribute::Alignment: + return 31 << 16; + case Attribute::NoCapture: + return 1 << 21; + case Attribute::NoRedZone: + return 1 << 22; + case Attribute::NoImplicitFloat: + return 1 << 23; + case Attribute::Naked: + return 1 << 24; + case Attribute::InlineHint: + return 1 << 25; + case Attribute::StackAlignment: + return 7 << 26; + case Attribute::ReturnsTwice: + return 1 << 29; + case Attribute::UWTable: + return 1 << 30; + case Attribute::NonLazyBind: + return 1U << 31; + case Attribute::SanitizeAddress: + return 1ULL << 32; + case Attribute::MinSize: + return 1ULL << 33; + case Attribute::NoDuplicate: + return 1ULL << 34; + case Attribute::StackProtectStrong: + return 1ULL << 35; + case Attribute::SanitizeThread: + return 1ULL << 36; + case Attribute::SanitizeMemory: + return 1ULL << 37; + case Attribute::NoBuiltin: + return 1ULL << 38; + case Attribute::Returned: + return 1ULL << 39; + case Attribute::Cold: + return 1ULL << 40; + case Attribute::Builtin: + return 1ULL << 41; + case Attribute::OptimizeNone: + return 1ULL << 42; + case Attribute::InAlloca: + return 1ULL << 43; + case Attribute::NonNull: + return 1ULL << 44; + case Attribute::JumpTable: + return 1ULL << 45; + case Attribute::Convergent: + return 1ULL << 46; + case Attribute::SafeStack: + return 1ULL << 47; + case Attribute::NoRecurse: + return 1ULL << 48; + case Attribute::InaccessibleMemOnly: + return 1ULL << 49; + case Attribute::InaccessibleMemOrArgMemOnly: + return 1ULL << 50; + case Attribute::SwiftSelf: + return 1ULL << 51; + case Attribute::SwiftError: + return 1ULL << 52; + case Attribute::WriteOnly: + return 1ULL << 53; + case Attribute::Speculatable: + return 1ULL << 54; + case Attribute::StrictFP: + return 1ULL << 55; + case Attribute::SanitizeHWAddress: + return 1ULL << 56; + case Attribute::NoCfCheck: + return 1ULL << 57; + case Attribute::OptForFuzzing: + return 1ULL << 58; + case Attribute::ShadowCallStack: + return 1ULL << 59; case Attribute::SpeculativeLoadHardening: return 1ULL << 60; case Attribute::ImmArg: @@ -1256,20 +1352,20 @@ } static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) { - if (!Val) return; + if (!Val) + return; for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds; I = Attribute::AttrKind(I + 1)) { if (I == Attribute::Dereferenceable || - I == Attribute::DereferenceableOrNull || - I == Attribute::ArgMemOnly || + I == Attribute::DereferenceableOrNull || I == Attribute::ArgMemOnly || I == Attribute::AllocSize) continue; if (uint64_t A = (Val & getRawAttributeMask(I))) { if (I == Attribute::Alignment) B.addAlignmentAttr(1ULL << ((A >> 16) - 1)); else if (I == Attribute::StackAlignment) - B.addStackAlignmentAttr(1ULL << ((A >> 26)-1)); + B.addStackAlignmentAttr(1ULL << ((A >> 26) - 1)); else B.addAttribute(I); } @@ -1292,7 +1388,7 @@ if (Alignment) B.addAlignmentAttr(Alignment); addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) | - (EncodedAttrs & 0xffff)); + (EncodedAttrs & 0xffff)); } Error BitcodeReader::parseAttributeBlock() { @@ -1330,7 +1426,7 @@ if (!MaybeRecord) return MaybeRecord.takeError(); switch (MaybeRecord.get()) { - default: // Default behavior: ignore. + default: // Default behavior: ignore. break; case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...] // FIXME: Remove in 4.0. @@ -1339,7 +1435,7 @@ for (unsigned i = 0, e = Record.size(); i != e; i += 2) { AttrBuilder B; - decodeLLVMAttributesForBitcode(B, Record[i+1]); + decodeLLVMAttributesForBitcode(B, Record[i + 1]); Attrs.push_back(AttributeList::get(Context, Record[i], B)); } @@ -1535,7 +1631,7 @@ if (!MaybeRecord) return MaybeRecord.takeError(); switch (MaybeRecord.get()) { - default: // Default behavior: ignore. + default: // Default behavior: ignore. break; case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...] if (Record.size() < 3) @@ -1546,7 +1642,7 @@ AttrBuilder B; for (unsigned i = 2, e = Record.size(); i != e; ++i) { - if (Record[i] == 0) { // Enum attribute + if (Record[i] == 0) { // Enum attribute Attribute::AttrKind Kind; if (Error Err = parseAttrKind(Record[++i], &Kind)) return Err; @@ -1620,13 +1716,13 @@ if (!TypeList.empty()) return error("Invalid multiple blocks"); - SmallVector Record; - unsigned NumRecords = 0; - SmallString<64> TypeName; + std::vector>>> + TypeRecords; // Read all the records for this type table. - while (true) { + bool Done = false; + while (!Done) { Expected MaybeEntry = Stream.advanceSkippingSubblocks(); if (!MaybeEntry) return MaybeEntry.takeError(); @@ -1637,68 +1733,100 @@ case BitstreamEntry::Error: return error("Malformed block"); case BitstreamEntry::EndBlock: - if (NumRecords != TypeList.size()) + if (TypeRecords.size() != TypeList.size()) return error("Malformed block"); - return Error::success(); + Done = true; + break; case BitstreamEntry::Record: - // The interesting case. + std::shared_ptr> Record( + new SmallVector()); + Expected MaybeCode = Stream.readRecord(Entry.ID, *Record); + if (!MaybeCode) + return MaybeCode.takeError(); + unsigned Code = MaybeCode.get(); + switch (Code) { + case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] + // TYPE_CODE_NUMENTRY contains a count of the number of types in the + // type list. This allows us to reserve space. + if (Record->size() < 1) + return error("Invalid record"); + TypeList.resize((*Record)[0]); + break; + case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] + // TYPE_CODE_STRUCT_NAME provides a name for the next struct type. We + // provide that type already, so forward references can reach it. If + // necessary the type is left opaque for now. + if (convertToString(*Record, 0, TypeName)) + return error("Invalid record"); + break; + case bitc::TYPE_CODE_STRUCT_NAMED: + case bitc::TYPE_CODE_OPAQUE: { + StructType *NamedStructType = nullptr; + if (!TypeName.empty()) + NamedStructType = StructType::getIfExists(Context, TypeName); + if (!NamedStructType) + NamedStructType = StructType::create(Context, TypeName); + TypeList[TypeRecords.size()] = NamedStructType; + IdentifiedStructTypes.push_back(NamedStructType); + TypeName.clear(); + } + LLVM_FALLTHROUGH; + default: + // All other records are left to process once the forward references are + // resolvable. + TypeRecords.push_back(make_pair(Code, Record)); + break; + } break; } + } - // Read a record. - Record.clear(); + unsigned NumRecords = 0; + // Process the deferred type records. + for (auto TypeRecord : TypeRecords) { + auto Record = TypeRecord.second; Type *ResultTy = nullptr; - Expected MaybeRecord = Stream.readRecord(Entry.ID, Record); - if (!MaybeRecord) - return MaybeRecord.takeError(); - switch (MaybeRecord.get()) { + switch (TypeRecord.first) { default: return error("Invalid value"); - case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries] - // TYPE_CODE_NUMENTRY contains a count of the number of types in the - // type list. This allows us to reserve space. - if (Record.size() < 1) - return error("Invalid record"); - TypeList.resize(Record[0]); - continue; - case bitc::TYPE_CODE_VOID: // VOID + case bitc::TYPE_CODE_VOID: // VOID ResultTy = Type::getVoidTy(Context); break; - case bitc::TYPE_CODE_HALF: // HALF + case bitc::TYPE_CODE_HALF: // HALF ResultTy = Type::getHalfTy(Context); break; - case bitc::TYPE_CODE_FLOAT: // FLOAT + case bitc::TYPE_CODE_FLOAT: // FLOAT ResultTy = Type::getFloatTy(Context); break; - case bitc::TYPE_CODE_DOUBLE: // DOUBLE + case bitc::TYPE_CODE_DOUBLE: // DOUBLE ResultTy = Type::getDoubleTy(Context); break; - case bitc::TYPE_CODE_X86_FP80: // X86_FP80 + case bitc::TYPE_CODE_X86_FP80: // X86_FP80 ResultTy = Type::getX86_FP80Ty(Context); break; - case bitc::TYPE_CODE_FP128: // FP128 + case bitc::TYPE_CODE_FP128: // FP128 ResultTy = Type::getFP128Ty(Context); break; case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128 ResultTy = Type::getPPC_FP128Ty(Context); break; - case bitc::TYPE_CODE_LABEL: // LABEL + case bitc::TYPE_CODE_LABEL: // LABEL ResultTy = Type::getLabelTy(Context); break; - case bitc::TYPE_CODE_METADATA: // METADATA + case bitc::TYPE_CODE_METADATA: // METADATA ResultTy = Type::getMetadataTy(Context); break; - case bitc::TYPE_CODE_X86_MMX: // X86_MMX + case bitc::TYPE_CODE_X86_MMX: // X86_MMX ResultTy = Type::getX86_MMXTy(Context); break; - case bitc::TYPE_CODE_TOKEN: // TOKEN + case bitc::TYPE_CODE_TOKEN: // TOKEN ResultTy = Type::getTokenTy(Context); break; case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width] - if (Record.size() < 1) + if (Record->size() < 1) return error("Invalid record"); - uint64_t NumBits = Record[0]; + uint64_t NumBits = (*Record)[0]; if (NumBits < IntegerType::MIN_INT_BITS || NumBits > IntegerType::MAX_INT_BITS) return error("Bitwidth for integer type out of range"); @@ -1707,14 +1835,13 @@ } case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or // [pointee type, address space] - if (Record.size() < 1) + if (Record->size() < 1) return error("Invalid record"); unsigned AddressSpace = 0; - if (Record.size() == 2) - AddressSpace = Record[1]; - ResultTy = getTypeByID(Record[0]); - if (!ResultTy || - !PointerType::isValidElementType(ResultTy)) + if (Record->size() == 2) + AddressSpace = (*Record)[1]; + ResultTy = getTypeByID((*Record)[0]); + if (!ResultTy || !PointerType::isValidElementType(ResultTy)) return error("Invalid type"); ResultTy = PointerType::get(ResultTy, AddressSpace); break; @@ -1722,131 +1849,133 @@ case bitc::TYPE_CODE_FUNCTION_OLD: { // FIXME: attrid is dead, remove it in LLVM 4.0 // FUNCTION: [vararg, attrid, retty, paramty x N] - if (Record.size() < 3) + if (Record->size() < 3) return error("Invalid record"); - SmallVector ArgTys; - for (unsigned i = 3, e = Record.size(); i != e; ++i) { - if (Type *T = getTypeByID(Record[i])) + SmallVector ArgTys; + for (unsigned i = 3, e = Record->size(); i != e; ++i) { + if (Type *T = getTypeByID((*Record)[i])) ArgTys.push_back(T); else break; } - ResultTy = getTypeByID(Record[2]); - if (!ResultTy || ArgTys.size() < Record.size()-3) + ResultTy = getTypeByID((*Record)[2]); + if (!ResultTy || ArgTys.size() < Record->size() - 3) return error("Invalid type"); - ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); + ResultTy = FunctionType::get(ResultTy, ArgTys, (*Record)[0]); break; } case bitc::TYPE_CODE_FUNCTION: { // FUNCTION: [vararg, retty, paramty x N] - if (Record.size() < 2) + if (Record->size() < 2) return error("Invalid record"); - SmallVector ArgTys; - for (unsigned i = 2, e = Record.size(); i != e; ++i) { - if (Type *T = getTypeByID(Record[i])) { + SmallVector ArgTys; + for (unsigned i = 2, e = Record->size(); i != e; ++i) { + if (Type *T = getTypeByID((*Record)[i])) { if (!FunctionType::isValidArgumentType(T)) return error("Invalid function argument type"); ArgTys.push_back(T); - } - else + } else break; } - ResultTy = getTypeByID(Record[1]); - if (!ResultTy || ArgTys.size() < Record.size()-2) + ResultTy = getTypeByID((*Record)[1]); + if (!ResultTy || ArgTys.size() < Record->size() - 2) return error("Invalid type"); - ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]); + ResultTy = FunctionType::get(ResultTy, ArgTys, (*Record)[0]); break; } - case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] - if (Record.size() < 1) + case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N] + if (Record->size() < 1) return error("Invalid record"); - SmallVector EltTys; - for (unsigned i = 1, e = Record.size(); i != e; ++i) { - if (Type *T = getTypeByID(Record[i])) + SmallVector EltTys; + for (unsigned i = 1, e = Record->size(); i != e; ++i) { + if (Type *T = getTypeByID((*Record)[i])) EltTys.push_back(T); else break; } - if (EltTys.size() != Record.size()-1) + if (EltTys.size() != Record->size() - 1) return error("Invalid type"); - ResultTy = StructType::get(Context, EltTys, Record[0]); + ResultTy = StructType::get(Context, EltTys, (*Record)[0]); break; } - case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N] - if (convertToString(Record, 0, TypeName)) - return error("Invalid record"); - continue; - case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N] - if (Record.size() < 1) + if (Record->size() < 1) return error("Invalid record"); if (NumRecords >= TypeList.size()) return error("Invalid TYPE table"); - // Check to see if this was forward referenced, if so fill in the temp. - StructType *Res = cast_or_null(TypeList[NumRecords]); - if (Res) { - Res->setName(TypeName); - TypeList[NumRecords] = nullptr; - } else // Otherwise, create a new struct. - Res = createIdentifiedStructType(Context, TypeName); - TypeName.clear(); - - SmallVector EltTys; - for (unsigned i = 1, e = Record.size(); i != e; ++i) { - if (Type *T = getTypeByID(Record[i])) + SmallVector EltTys; + for (unsigned i = 1, e = Record->size(); i != e; ++i) { + if (Type *T = getTypeByID((*Record)[i])) EltTys.push_back(T); else break; } - if (EltTys.size() != Record.size()-1) + if (EltTys.size() != Record->size() - 1) return error("Invalid record"); - Res->setBody(EltTys, Record[0]); + + StructType *Res = cast(TypeList[NumRecords]); + TypeList[NumRecords] = nullptr; + if (Res->isOpaque()) { + Res->setBody(EltTys, (*Record)[0]); + } else if (!Res->elements().equals(EltTys)) { + // Ouch! The LLVMContext's existing named struct type and the one being + // read have different structures. This must mean that the LLVMContext + // contains more than one module, and there is disagreement. Several + // possibilities: 1a. There are no opaque references to structs. In this + // case renaming either type is safe (but perhaps not desirable). + // 1b. There are opaque references, but no further Modules will be read. + // In this case renaming the type in the new module is safe. 2a. There + // may be opaque references, and all are to the type that's already in + // the Context. In this case renaming the new type is safe. 2b. There + // may be opaque references, and all are to the type that's being + // read. In this case renaming the existing type is safe. 2c. There may + // be opaque references to either. In this case nothing is safe. + + // 3. This kind of conflict should not happen. + return error( + "named struct types match by name and differ by structure"); + } + ResultTy = Res; break; } - case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] - if (Record.size() != 1) + case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: [] + if (Record->size() != 1) return error("Invalid record"); if (NumRecords >= TypeList.size()) return error("Invalid TYPE table"); - // Check to see if this was forward referenced, if so fill in the temp. - StructType *Res = cast_or_null(TypeList[NumRecords]); - if (Res) { - Res->setName(TypeName); - TypeList[NumRecords] = nullptr; - } else // Otherwise, create a new struct with no body. - Res = createIdentifiedStructType(Context, TypeName); - TypeName.clear(); + StructType *Res = cast(TypeList[NumRecords]); + TypeList[NumRecords] = nullptr; ResultTy = Res; break; } - case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] - if (Record.size() < 2) + case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty] + if (Record->size() < 2) return error("Invalid record"); - ResultTy = getTypeByID(Record[1]); + ResultTy = getTypeByID((*Record)[1]); if (!ResultTy || !ArrayType::isValidElementType(ResultTy)) return error("Invalid type"); - ResultTy = ArrayType::get(ResultTy, Record[0]); + ResultTy = ArrayType::get(ResultTy, (*Record)[0]); break; - case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or - // [numelts, eltty, scalable] - if (Record.size() < 2) + case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or + // [numelts, eltty, scalable] + if (Record->size() < 2) return error("Invalid record"); - if (Record[0] == 0) + if ((*Record)[0] == 0) return error("Invalid vector length"); - ResultTy = getTypeByID(Record[1]); + ResultTy = getTypeByID((*Record)[1]); if (!ResultTy || !StructType::isValidElementType(ResultTy)) return error("Invalid type"); - bool Scalable = Record.size() > 2 ? Record[2] : false; - ResultTy = VectorType::get(ResultTy, Record[0], Scalable); + bool Scalable = Record->size() > 2 ? (*Record)[2] : false; + ResultTy = VectorType::get(ResultTy, (*Record)[0], Scalable); break; } @@ -1858,6 +1987,9 @@ assert(ResultTy && "Didn't read a type?"); TypeList[NumRecords++] = ResultTy; } + if (NumRecords < TypeList.size()) + return error("Invalid TYPE table"); + return Error::success(); } Error BitcodeReader::parseOperandBundleTags() { @@ -2119,9 +2251,9 @@ if (!MaybeRecord) return MaybeRecord.takeError(); switch (MaybeRecord.get()) { - default: // Default behavior: unknown type. + default: // Default behavior: unknown type. break; - case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] + case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N] Expected ValOrErr = recordValue(Record, 1, TT); if (Error Err = ValOrErr.takeError()) return Err; @@ -2256,8 +2388,7 @@ static APInt readWideAPInt(ArrayRef Vals, unsigned TypeBits) { SmallVector Words(Vals.size()); - transform(Vals, Words.begin(), - BitcodeReader::decodeSignRotatedValue); + transform(Vals, Words.begin(), BitcodeReader::decodeSignRotatedValue); return APInt(TypeBits, Words); } @@ -2303,11 +2434,11 @@ if (!MaybeBitCode) return MaybeBitCode.takeError(); switch (unsigned BitCode = MaybeBitCode.get()) { - default: // Default behavior: unknown constant - case bitc::CST_CODE_UNDEF: // UNDEF + default: // Default behavior: unknown constant + case bitc::CST_CODE_UNDEF: // UNDEF V = UndefValue::get(CurTy); break; - case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] + case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid] if (Record.empty()) return error("Invalid record"); if (Record[0] >= TypeList.size() || !TypeList[Record[0]]) @@ -2315,16 +2446,16 @@ if (TypeList[Record[0]] == VoidType) return error("Invalid constant type"); CurTy = TypeList[Record[0]]; - continue; // Skip the ValueList manipulation. - case bitc::CST_CODE_NULL: // NULL + continue; // Skip the ValueList manipulation. + case bitc::CST_CODE_NULL: // NULL V = Constant::getNullValue(CurTy); break; - case bitc::CST_CODE_INTEGER: // INTEGER: [intval] + case bitc::CST_CODE_INTEGER: // INTEGER: [intval] if (!CurTy->isIntegerTy() || Record.empty()) return error("Invalid record"); V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0])); break; - case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval] + case bitc::CST_CODE_WIDE_INTEGER: { // WIDE_INTEGER: [n x intval] if (!CurTy->isIntegerTy() || Record.empty()) return error("Invalid record"); @@ -2334,7 +2465,7 @@ break; } - case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] + case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval] if (Record.empty()) return error("Invalid record"); if (CurTy->isHalfTy()) @@ -2344,8 +2475,8 @@ V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(), APInt(32, (uint32_t)Record[0]))); else if (CurTy->isDoubleTy()) - V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(), - APInt(64, Record[0]))); + V = ConstantFP::get( + Context, APFloat(APFloat::IEEEdouble(), APInt(64, Record[0]))); else if (CurTy->isX86_FP80Ty()) { // Bits are not stored the same way as a normal i80 APInt, compensate. uint64_t Rearrange[2]; @@ -2354,27 +2485,27 @@ V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(), APInt(80, Rearrange))); } else if (CurTy->isFP128Ty()) - V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(), - APInt(128, Record))); + V = ConstantFP::get(Context, + APFloat(APFloat::IEEEquad(), APInt(128, Record))); else if (CurTy->isPPC_FP128Ty()) - V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(), - APInt(128, Record))); + V = ConstantFP::get( + Context, APFloat(APFloat::PPCDoubleDouble(), APInt(128, Record))); else V = UndefValue::get(CurTy); break; } - case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number] + case bitc::CST_CODE_AGGREGATE: { // AGGREGATE: [n x value number] if (Record.empty()) return error("Invalid record"); unsigned Size = Record.size(); - SmallVector Elts; + SmallVector Elts; if (StructType *STy = dyn_cast(CurTy)) { for (unsigned i = 0; i != Size; ++i) - Elts.push_back(ValueList.getConstantFwdRef(Record[i], - STy->getElementType(i))); + Elts.push_back( + ValueList.getConstantFwdRef(Record[i], STy->getElementType(i))); V = ConstantStruct::get(STy, Elts); } else if (ArrayType *ATy = dyn_cast(CurTy)) { Type *EltTy = ATy->getElementType(); @@ -2401,7 +2532,7 @@ BitCode == bitc::CST_CODE_CSTRING); break; } - case bitc::CST_CODE_DATA: {// DATA: [n x value] + case bitc::CST_CODE_DATA: { // DATA: [n x value] if (Record.empty()) return error("Invalid record"); @@ -2453,12 +2584,12 @@ } break; } - case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] + case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval] if (Record.size() < 2) return error("Invalid record"); int Opc = getDecodedUnaryOpcode(Record[0], CurTy); if (Opc < 0) { - V = UndefValue::get(CurTy); // Unknown unop. + V = UndefValue::get(CurTy); // Unknown unop. } else { Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); unsigned Flags = 0; @@ -2466,29 +2597,25 @@ } break; } - case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] + case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval] if (Record.size() < 3) return error("Invalid record"); int Opc = getDecodedBinaryOpcode(Record[0], CurTy); if (Opc < 0) { - V = UndefValue::get(CurTy); // Unknown binop. + V = UndefValue::get(CurTy); // Unknown binop. } else { Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy); Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy); unsigned Flags = 0; if (Record.size() >= 4) { - if (Opc == Instruction::Add || - Opc == Instruction::Sub || - Opc == Instruction::Mul || - Opc == Instruction::Shl) { + if (Opc == Instruction::Add || Opc == Instruction::Sub || + Opc == Instruction::Mul || Opc == Instruction::Shl) { if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP)) Flags |= OverflowingBinaryOperator::NoSignedWrap; if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) Flags |= OverflowingBinaryOperator::NoUnsignedWrap; - } else if (Opc == Instruction::SDiv || - Opc == Instruction::UDiv || - Opc == Instruction::LShr || - Opc == Instruction::AShr) { + } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || + Opc == Instruction::LShr || Opc == Instruction::AShr) { if (Record[3] & (1 << bitc::PEO_EXACT)) Flags |= SDivOperator::IsExact; } @@ -2497,24 +2624,25 @@ } break; } - case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] + case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval] if (Record.size() < 3) return error("Invalid record"); int Opc = getDecodedCastOpcode(Record[0]); if (Opc < 0) { - V = UndefValue::get(CurTy); // Unknown cast. + V = UndefValue::get(CurTy); // Unknown cast. } else { Type *OpTy = getTypeByID(Record[1]); if (!OpTy) return error("Invalid record"); Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy); V = UpgradeBitCastExpr(Opc, Op, CurTy); - if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy); + if (!V) + V = ConstantExpr::getCast(Opc, Op, CurTy); } break; } - case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] - case bitc::CST_CODE_CE_GEP: // [ty, n x operands] + case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands] + case bitc::CST_CODE_CE_GEP: // [ty, n x operands] case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x // operands] unsigned OpNum = 0; @@ -2532,7 +2660,7 @@ } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP) InBounds = true; - SmallVector Elts; + SmallVector Elts; while (OpNum != Record.size()) { Type *ElTy = getTypeByID(Record[OpNum++]); if (!ElTy) @@ -2557,7 +2685,7 @@ InBounds, InRangeIndex); break; } - case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] + case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#] if (Record.size() < 3) return error("Invalid record"); @@ -2570,18 +2698,17 @@ if (SelectorTy != V->getType()) SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements()); - V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0], - SelectorTy), - ValueList.getConstantFwdRef(Record[1],CurTy), - ValueList.getConstantFwdRef(Record[2],CurTy)); + V = ConstantExpr::getSelect( + ValueList.getConstantFwdRef(Record[0], SelectorTy), + ValueList.getConstantFwdRef(Record[1], CurTy), + ValueList.getConstantFwdRef(Record[2], CurTy)); break; } - case bitc::CST_CODE_CE_EXTRACTELT - : { // CE_EXTRACTELT: [opty, opval, opty, opval] + case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opty, + // opval] if (Record.size() < 3) return error("Invalid record"); - VectorType *OpTy = - dyn_cast_or_null(getTypeByID(Record[0])); + VectorType *OpTy = dyn_cast_or_null(getTypeByID(Record[0])); if (!OpTy) return error("Invalid record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); @@ -2598,14 +2725,14 @@ V = ConstantExpr::getExtractElement(Op0, Op1); break; } - case bitc::CST_CODE_CE_INSERTELT - : { // CE_INSERTELT: [opval, opval, opty, opval] + case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opty, + // opval] VectorType *OpTy = dyn_cast(CurTy); if (Record.size() < 3 || !OpTy) return error("Invalid record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); - Constant *Op1 = ValueList.getConstantFwdRef(Record[1], - OpTy->getElementType()); + Constant *Op1 = + ValueList.getConstantFwdRef(Record[1], OpTy->getElementType()); Constant *Op2 = nullptr; if (Record.size() == 4) { Type *IdxTy = getTypeByID(Record[2]); @@ -2625,27 +2752,26 @@ return error("Invalid record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy); Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy); - Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), - OpTy->getNumElements()); + Type *ShufTy = + VectorType::get(Type::getInt32Ty(Context), OpTy->getNumElements()); Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); break; } case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval] VectorType *RTy = dyn_cast(CurTy); - VectorType *OpTy = - dyn_cast_or_null(getTypeByID(Record[0])); + VectorType *OpTy = dyn_cast_or_null(getTypeByID(Record[0])); if (Record.size() < 4 || !RTy || !OpTy) return error("Invalid record"); Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy); Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy); - Type *ShufTy = VectorType::get(Type::getInt32Ty(Context), - RTy->getNumElements()); + Type *ShufTy = + VectorType::get(Type::getInt32Ty(Context), RTy->getNumElements()); Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy); V = ConstantExpr::getShuffleVector(Op0, Op1, Op2); break; } - case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] + case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred] if (Record.size() < 4) return error("Invalid record"); Type *OpTy = getTypeByID(Record[0]); @@ -2669,20 +2795,20 @@ bool HasSideEffects = Record[0] & 1; bool IsAlignStack = Record[0] >> 1; unsigned AsmStrSize = Record[1]; - if (2+AsmStrSize >= Record.size()) + if (2 + AsmStrSize >= Record.size()) return error("Invalid record"); - unsigned ConstStrSize = Record[2+AsmStrSize]; - if (3+AsmStrSize+ConstStrSize > Record.size()) + unsigned ConstStrSize = Record[2 + AsmStrSize]; + if (3 + AsmStrSize + ConstStrSize > Record.size()) return error("Invalid record"); for (unsigned i = 0; i != AsmStrSize; ++i) - AsmStr += (char)Record[2+i]; + AsmStr += (char)Record[2 + i]; for (unsigned i = 0; i != ConstStrSize; ++i) - ConstrStr += (char)Record[3+AsmStrSize+i]; + ConstrStr += (char)Record[3 + AsmStrSize + i]; PointerType *PTy = cast(CurTy); UpgradeInlineAsmString(&AsmStr); - V = InlineAsm::get(cast(PTy->getElementType()), - AsmStr, ConstrStr, HasSideEffects, IsAlignStack); + V = InlineAsm::get(cast(PTy->getElementType()), AsmStr, + ConstrStr, HasSideEffects, IsAlignStack); break; } // This version adds support for the asm dialect keywords (e.g., @@ -2695,31 +2821,31 @@ bool IsAlignStack = (Record[0] >> 1) & 1; unsigned AsmDialect = Record[0] >> 2; unsigned AsmStrSize = Record[1]; - if (2+AsmStrSize >= Record.size()) + if (2 + AsmStrSize >= Record.size()) return error("Invalid record"); - unsigned ConstStrSize = Record[2+AsmStrSize]; - if (3+AsmStrSize+ConstStrSize > Record.size()) + unsigned ConstStrSize = Record[2 + AsmStrSize]; + if (3 + AsmStrSize + ConstStrSize > Record.size()) return error("Invalid record"); for (unsigned i = 0; i != AsmStrSize; ++i) - AsmStr += (char)Record[2+i]; + AsmStr += (char)Record[2 + i]; for (unsigned i = 0; i != ConstStrSize; ++i) - ConstrStr += (char)Record[3+AsmStrSize+i]; + ConstrStr += (char)Record[3 + AsmStrSize + i]; PointerType *PTy = cast(CurTy); UpgradeInlineAsmString(&AsmStr); - V = InlineAsm::get(cast(PTy->getElementType()), - AsmStr, ConstrStr, HasSideEffects, IsAlignStack, + V = InlineAsm::get(cast(PTy->getElementType()), AsmStr, + ConstrStr, HasSideEffects, IsAlignStack, InlineAsm::AsmDialect(AsmDialect)); break; } - case bitc::CST_CODE_BLOCKADDRESS:{ + case bitc::CST_CODE_BLOCKADDRESS: { if (Record.size() < 3) return error("Invalid record"); Type *FnTy = getTypeByID(Record[0]); if (!FnTy) return error("Invalid record"); - Function *Fn = - dyn_cast_or_null(ValueList.getConstantFwdRef(Record[1],FnTy)); + Function *Fn = dyn_cast_or_null( + ValueList.getConstantFwdRef(Record[1], FnTy)); if (!Fn) return error("Invalid record"); @@ -2791,7 +2917,7 @@ if (!MaybeRecord) return MaybeRecord.takeError(); switch (MaybeRecord.get()) { - default: // Default behavior: unknown type. + default: // Default behavior: unknown type. break; case bitc::USELIST_CODE_BB: IsBB = true; @@ -2941,7 +3067,8 @@ return error("Could not find function in stream"); if (!SeenFirstFunctionBody) - return error("Trying to materialize functions before seeing function blocks"); + return error( + "Trying to materialize functions before seeing function blocks"); // An old bitcode file with the symbol table at the end would have // finished the parse greedily. @@ -3337,7 +3464,7 @@ case BitstreamEntry::SubBlock: switch (Entry.ID) { - default: // Skip unknown content. + default: // Skip unknown content. if (Error Err = Stream.SkipBlock()) return Err; break; @@ -3474,7 +3601,8 @@ if (!MaybeBitCode) return MaybeBitCode.takeError(); switch (unsigned BitCode = MaybeBitCode.get()) { - default: break; // Default behavior, ignore unknown content. + default: + break; // Default behavior, ignore unknown content. case bitc::MODULE_CODE_VERSION: { Expected VersionOrErr = parseVersionRecord(Record); if (!VersionOrErr) @@ -3482,28 +3610,28 @@ UseRelativeIDs = *VersionOrErr >= 1; break; } - case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] + case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); TheModule->setTargetTriple(S); break; } - case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] + case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); TheModule->setDataLayout(S); break; } - case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] + case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); TheModule->setModuleInlineAsm(S); break; } - case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] + case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N] // FIXME: Remove in 4.0. std::string S; if (convertToString(Record, 0, S)) @@ -3511,14 +3639,14 @@ // Ignore value. break; } - case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] + case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); SectionTable.push_back(S); break; } - case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] + case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N] std::string S; if (convertToString(Record, 0, S)) return error("Invalid record"); @@ -3648,7 +3776,7 @@ case BitstreamEntry::SubBlock: switch (Entry.ID) { - default: // Skip unknown content. + default: // Skip unknown content. if (Error Err = Stream.SkipBlock()) return Err; break; @@ -3692,7 +3820,7 @@ switch (unsigned BitCode = MaybeBitCode.get()) { default: // Default behavior: reject return error("Invalid value"); - case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] + case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks] if (Record.size() < 1 || Record[0] == 0) return error("Invalid record"); // Create all the basic blocks for the function. @@ -3727,7 +3855,7 @@ continue; } - case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN + case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN // This record indicates that the last instruction is at the same // location as the previous instruction with a location. I = getLastInstruction(); @@ -3738,7 +3866,7 @@ I = nullptr; continue; - case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] + case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia] I = getLastInstruction(); if (!I || Record.size() < 4) return error("Invalid record"); @@ -3765,11 +3893,11 @@ I = nullptr; continue; } - case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] + case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode] unsigned OpNum = 0; Value *LHS; if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || - OpNum+1 > Record.size()) + OpNum + 1 > Record.size()) return error("Invalid record"); int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType()); @@ -3786,12 +3914,12 @@ } break; } - case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] + case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode] unsigned OpNum = 0; Value *LHS, *RHS; if (getValueTypePair(Record, OpNum, NextValueNo, LHS) || popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) || - OpNum+1 > Record.size()) + OpNum + 1 > Record.size()) return error("Invalid record"); int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType()); @@ -3800,18 +3928,14 @@ I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS); InstructionList.push_back(I); if (OpNum < Record.size()) { - if (Opc == Instruction::Add || - Opc == Instruction::Sub || - Opc == Instruction::Mul || - Opc == Instruction::Shl) { + if (Opc == Instruction::Add || Opc == Instruction::Sub || + Opc == Instruction::Mul || Opc == Instruction::Shl) { if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP)) cast(I)->setHasNoSignedWrap(true); if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP)) cast(I)->setHasNoUnsignedWrap(true); - } else if (Opc == Instruction::SDiv || - Opc == Instruction::UDiv || - Opc == Instruction::LShr || - Opc == Instruction::AShr) { + } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv || + Opc == Instruction::LShr || Opc == Instruction::AShr) { if (Record[OpNum] & (1 << bitc::PEO_EXACT)) cast(I)->setIsExact(true); } else if (isa(I)) { @@ -3819,15 +3943,14 @@ if (FMF.any()) I->setFastMathFlags(FMF); } - } break; } - case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] + case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc] unsigned OpNum = 0; Value *Op; if (getValueTypePair(Record, OpNum, NextValueNo, Op) || - OpNum+2 != Record.size()) + OpNum + 2 != Record.size()) return error("Invalid record"); Type *ResTy = getTypeByID(Record[OpNum]); @@ -3872,13 +3995,12 @@ if (!Ty) Ty = cast(BasePtr->getType()->getScalarType()) ->getElementType(); - else if (Ty != - cast(BasePtr->getType()->getScalarType()) - ->getElementType()) + else if (Ty != cast(BasePtr->getType()->getScalarType()) + ->getElementType()) return error( "Explicit gep type does not match pointee type of pointer operand"); - SmallVector GEPIdx; + SmallVector GEPIdx; while (OpNum != Record.size()) { Value *Op; if (getValueTypePair(Record, OpNum, NextValueNo, Op)) @@ -3895,7 +4017,7 @@ } case bitc::FUNC_CODE_INST_EXTRACTVAL: { - // EXTRACTVAL: [opty, opval, n x indices] + // EXTRACTVAL: [opty, opval, n x indices] unsigned OpNum = 0; Value *Agg; if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) @@ -3934,7 +4056,7 @@ } case bitc::FUNC_CODE_INST_INSERTVAL: { - // INSERTVAL: [opty, opval, opty, opval, n x indices] + // INSERTVAL: [opty, opval, opty, opval, n x indices] unsigned OpNum = 0; Value *Agg; if (getValueTypePair(Record, OpNum, NextValueNo, Agg)) @@ -3993,7 +4115,8 @@ break; } - case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred] + case bitc::FUNC_CODE_INST_VSELECT: { // VSELECT: + // [ty,opval,opval,predty,pred] // new form of select // handles select i1 or select [N x i1] unsigned OpNum = 0; @@ -4004,8 +4127,7 @@ return error("Invalid record"); // select condition can be either i1 or [N x i1] - if (VectorType* vector_type = - dyn_cast(Cond->getType())) { + if (VectorType *vector_type = dyn_cast(Cond->getType())) { // expect if (vector_type->getElementType() != Type::getInt1Ty(Context)) return error("Invalid type for value"); @@ -4054,7 +4176,8 @@ break; } - case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval] + case bitc::FUNC_CODE_INST_SHUFFLEVEC: { // SHUFFLEVEC: + // [opval,ty,opval,opval] unsigned OpNum = 0; Value *Vec1, *Vec2, *Mask; if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) || @@ -4070,10 +4193,11 @@ break; } - case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] - // Old form of ICmp/FCmp returning bool - // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were - // both legal on vectors but had different behaviour. + case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred] + // Old form of ICmp/FCmp returning bool + // Existed to differentiate between icmp/fcmp + // and vicmp/vfcmp which were both legal on + // vectors but had different behaviour. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred] // FCmp/ICmp returning bool or vector of bool @@ -4086,10 +4210,10 @@ unsigned PredVal = Record[OpNum]; bool IsFP = LHS->getType()->isFPOrFPVectorTy(); FastMathFlags FMF; - if (IsFP && Record.size() > OpNum+1) + if (IsFP && Record.size() > OpNum + 1) FMF = getDecodedFastMathFlags(Record[++OpNum]); - if (OpNum+1 != Record.size()) + if (OpNum + 1 != Record.size()) return error("Invalid record"); if (LHS->getType()->isFPOrFPVectorTy()) @@ -4104,25 +4228,25 @@ } case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval] - { - unsigned Size = Record.size(); - if (Size == 0) { - I = ReturnInst::Create(Context); - InstructionList.push_back(I); - break; - } - - unsigned OpNum = 0; - Value *Op = nullptr; - if (getValueTypePair(Record, OpNum, NextValueNo, Op)) - return error("Invalid record"); - if (OpNum != Record.size()) - return error("Invalid record"); - - I = ReturnInst::Create(Context, Op); + { + unsigned Size = Record.size(); + if (Size == 0) { + I = ReturnInst::Create(Context); InstructionList.push_back(I); break; } + + unsigned OpNum = 0; + Value *Op = nullptr; + if (getValueTypePair(Record, OpNum, NextValueNo, Op)) + return error("Invalid record"); + if (OpNum != Record.size()) + return error("Invalid record"); + + I = ReturnInst::Create(Context, Op); + InstructionList.push_back(I); + break; + } case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#] if (Record.size() != 1 && Record.size() != 3) return error("Invalid record"); @@ -4133,11 +4257,10 @@ if (Record.size() == 1) { I = BranchInst::Create(TrueDest); InstructionList.push_back(I); - } - else { + } else { BasicBlock *FalseDest = getBasicBlock(Record[1]); - Value *Cond = getValue(Record, 2, NextValueNo, - Type::getInt1Ty(Context)); + Value *Cond = + getValue(Record, 2, NextValueNo, Type::getInt1Ty(Context)); if (!FalseDest || !Cond) return error("Invalid record"); I = BranchInst::Create(TrueDest, FalseDest, Cond); @@ -4272,7 +4395,7 @@ unsigned CurIdx = 5; for (unsigned i = 0; i != NumCases; ++i) { - SmallVector CaseVals; + SmallVector CaseVals; unsigned NumItems = Record[CurIdx++]; for (unsigned ci = 0; ci != NumItems; ++ci) { bool isSingleNumber = Record[CurIdx++]; @@ -4297,14 +4420,15 @@ // compared as signed or unsigned values. The partially // implemented changes that used this format in the past used // unsigned comparisons. - for ( ; Low.ule(High); ++Low) + for (; Low.ule(High); ++Low) CaseVals.push_back(ConstantInt::get(Context, Low)); } else CaseVals.push_back(ConstantInt::get(Context, Low)); } BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]); - for (SmallVector::iterator cvi = CaseVals.begin(), - cve = CaseVals.end(); cvi != cve; ++cvi) + for (SmallVector::iterator cvi = CaseVals.begin(), + cve = CaseVals.end(); + cvi != cve; ++cvi) SI->addCase(*cvi, DestBB); } I = SI; @@ -4320,13 +4444,13 @@ BasicBlock *Default = getBasicBlock(Record[2]); if (!OpTy || !Cond || !Default) return error("Invalid record"); - unsigned NumCases = (Record.size()-3)/2; + unsigned NumCases = (Record.size() - 3) / 2; SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases); InstructionList.push_back(SI); for (unsigned i = 0, e = NumCases; i != e; ++i) { - ConstantInt *CaseVal = - dyn_cast_or_null(getFnValueByID(Record[3+i*2], OpTy)); - BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]); + ConstantInt *CaseVal = dyn_cast_or_null( + getFnValueByID(Record[3 + i * 2], OpTy)); + BasicBlock *DestBB = getBasicBlock(Record[1 + 3 + i * 2]); if (!CaseVal || !DestBB) { delete SI; return error("Invalid record"); @@ -4343,11 +4467,11 @@ Value *Address = getValue(Record, 1, NextValueNo, OpTy); if (!OpTy || !Address) return error("Invalid record"); - unsigned NumDests = Record.size()-2; + unsigned NumDests = Record.size() - 2; IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests); InstructionList.push_back(IBI); for (unsigned i = 0, e = NumDests; i != e; ++i) { - if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) { + if (BasicBlock *DestBB = getBasicBlock(Record[2 + i])) { IBI->addDestination(DestBB); } else { delete IBI; @@ -4390,10 +4514,10 @@ if (Record.size() < FTy->getNumParams() + OpNum) return error("Insufficient operands to call"); - SmallVector Ops; + SmallVector Ops; for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { - Ops.push_back(getValue(Record, OpNum, NextValueNo, - FTy->getParamType(i))); + Ops.push_back( + getValue(Record, OpNum, NextValueNo, FTy->getParamType(i))); if (!Ops.back()) return error("Invalid record"); } @@ -4465,14 +4589,14 @@ if (Record.size() < FTy->getNumParams() + OpNum) return error("Insufficient operands to call"); - SmallVector Args; + SmallVector Args; // Read the fixed params. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { if (FTy->getParamType(i)->isLabelTy()) Args.push_back(getBasicBlock(Record[OpNum])); else - Args.push_back(getValue(Record, OpNum, NextValueNo, - FTy->getParamType(i))); + Args.push_back( + getValue(Record, OpNum, NextValueNo, FTy->getParamType(i))); if (!Args.back()) return error("Invalid record"); } @@ -4504,25 +4628,25 @@ InstructionList.push_back(I); break; case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...] - if (Record.size() < 1 || ((Record.size()-1)&1)) + if (Record.size() < 1 || ((Record.size() - 1) & 1)) return error("Invalid record"); Type *Ty = getTypeByID(Record[0]); if (!Ty) return error("Invalid record"); - PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2); + PHINode *PN = PHINode::Create(Ty, (Record.size() - 1) / 2); InstructionList.push_back(PN); - for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) { + for (unsigned i = 0, e = Record.size() - 1; i != e; i += 2) { Value *V; // With the new function encoding, it is possible that operands have // negative IDs (for forward references). Use a signed VBR // representation to keep the encoding small. if (UseRelativeIDs) - V = getValueSigned(Record, 1+i, NextValueNo, Ty); + V = getValueSigned(Record, 1 + i, NextValueNo, Ty); else - V = getValue(Record, 1+i, NextValueNo, Ty); - BasicBlock *BB = getBasicBlock(Record[2+i]); + V = getValue(Record, 1 + i, NextValueNo, Ty); + BasicBlock *BB = getBasicBlock(Record[2 + i]); if (!V || !BB) return error("Invalid record"); PN->addIncoming(V, BB); @@ -4563,7 +4687,8 @@ LP->setCleanup(IsCleanup); for (unsigned J = 0; J != NumClauses; ++J) { LandingPadInst::ClauseType CT = - LandingPadInst::ClauseType(Record[Idx++]); (void)CT; + LandingPadInst::ClauseType(Record[Idx++]); + (void)CT; Value *Val; if (getValueTypePair(Record, Idx, NextValueNo, Val)) { @@ -4571,12 +4696,12 @@ return error("Invalid record"); } - assert((CT != LandingPadInst::Catch || - !isa(Val->getType())) && - "Catch clause has a invalid type!"); - assert((CT != LandingPadInst::Filter || - isa(Val->getType())) && - "Filter clause has invalid type!"); + assert( + (CT != LandingPadInst::Catch || !isa(Val->getType())) && + "Catch clause has a invalid type!"); + assert( + (CT != LandingPadInst::Filter || isa(Val->getType())) && + "Filter clause has invalid type!"); LP->addClause(cast(Val)); } @@ -4592,8 +4717,8 @@ const uint64_t InAllocaMask = uint64_t(1) << 5; const uint64_t ExplicitTypeMask = uint64_t(1) << 6; const uint64_t SwiftErrorMask = uint64_t(1) << 7; - const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask | - SwiftErrorMask; + const uint64_t FlagMask = + InAllocaMask | ExplicitTypeMask | SwiftErrorMask; bool InAlloca = AlignRecord & InAllocaMask; bool SwiftError = AlignRecord & SwiftErrorMask; Type *Ty = getTypeByID(Record[0]); @@ -4647,7 +4772,7 @@ break; } case bitc::FUNC_CODE_INST_LOADATOMIC: { - // LOADATOMIC: [opty, op, align, vol, ordering, ssid] + // LOADATOMIC: [opty, op, align, vol, ordering, ssid] unsigned OpNum = 0; Value *Op; if (getValueTypePair(Record, OpNum, NextValueNo, Op) || @@ -4680,7 +4805,8 @@ break; } case bitc::FUNC_CODE_INST_STORE: - case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol] + case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, + // vol] unsigned OpNum = 0; Value *Val, *Ptr; if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || @@ -4697,7 +4823,7 @@ unsigned Align; if (Error Err = parseAlignmentValue(Record[OpNum], Align)) return Err; - I = new StoreInst(Val, Ptr, Record[OpNum+1], Align); + I = new StoreInst(Val, Ptr, Record[OpNum + 1], Align); InstructionList.push_back(I); break; } @@ -4730,7 +4856,7 @@ unsigned Align; if (Error Err = parseAlignmentValue(Record[OpNum], Align)) return Err; - I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SSID); + I = new StoreInst(Val, Ptr, Record[OpNum + 1], Align, Ordering, SSID); InstructionList.push_back(I); break; } @@ -4775,7 +4901,7 @@ CurBB->getInstList().push_back(I); I = ExtractValueInst::Create(I, 0); } else { - cast(I)->setWeak(Record[OpNum+4]); + cast(I)->setWeak(Record[OpNum + 4]); } InstructionList.push_back(I); @@ -4788,8 +4914,8 @@ if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) || !isa(Ptr->getType()) || popValue(Record, OpNum, NextValueNo, - cast(Ptr->getType())->getElementType(), Val) || - OpNum+4 != Record.size()) + cast(Ptr->getType())->getElementType(), Val) || + OpNum + 4 != Record.size()) return error("Invalid record"); AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]); if (Operation < AtomicRMWInst::FIRST_BINOP || @@ -4801,7 +4927,7 @@ return error("Invalid record"); SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]); I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID); - cast(I)->setVolatile(Record[OpNum+1]); + cast(I)->setVolatile(Record[OpNum + 1]); InstructionList.push_back(I); break; } @@ -4856,14 +4982,14 @@ if (Record.size() < FTy->getNumParams() + OpNum) return error("Insufficient operands to call"); - SmallVector Args; + SmallVector Args; // Read the fixed params. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) { if (FTy->getParamType(i)->isLabelTy()) Args.push_back(getBasicBlock(Record[OpNum])); else - Args.push_back(getValue(Record, OpNum, NextValueNo, - FTy->getParamType(i))); + Args.push_back( + getValue(Record, OpNum, NextValueNo, FTy->getParamType(i))); if (!Args.back()) return error("Invalid record"); } @@ -4972,7 +5098,8 @@ if (Argument *A = dyn_cast(ValueList.back())) { if (!A->getParent()) { // We found at least one unresolved value. Nuke them all to avoid leaks. - for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){ + for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; + ++i) { if ((A = dyn_cast_or_null(ValueList[i])) && !A->getParent()) { A->replaceAllUsesWith(UndefValue::get(A->getType())); delete A; @@ -4989,7 +5116,7 @@ // Trim the value list down to the size it was before we parsed this function. ValueList.shrinkTo(ModuleValueListSize); MDLoader->shrinkTo(ModuleMDLoaderSize); - std::vector().swap(FunctionBBs); + std::vector().swap(FunctionBBs); return Error::success(); } @@ -5029,7 +5156,7 @@ if (!F || !F->isMaterializable()) return Error::success(); - DenseMap::iterator DFII = DeferredFunctionInfo.find(F); + DenseMap::iterator DFII = DeferredFunctionInfo.find(F); assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!"); // If its position is recorded as 0, its body is somewhere in the stream // but we haven't seen it yet. @@ -5190,8 +5317,7 @@ // the index so that the value name can be recorded. ValueIdToValueInfoMap[ValueID] = std::make_pair( TheIndex.getOrInsertValueInfo( - ValueGUID, - UseStrtab ? ValueName : TheIndex.saveString(ValueName)), + ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)), OriginalNameID); } @@ -5360,71 +5486,71 @@ continue; case BitstreamEntry::Record: { - Record.clear(); - Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record); - if (!MaybeBitCode) - return MaybeBitCode.takeError(); - switch (MaybeBitCode.get()) { - default: - break; // Default behavior, ignore unknown content. - case bitc::MODULE_CODE_VERSION: { - if (Error Err = parseVersionRecord(Record).takeError()) - return Err; - break; - } - /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] - case bitc::MODULE_CODE_SOURCE_FILENAME: { - SmallString<128> ValueName; - if (convertToString(Record, 0, ValueName)) - return error("Invalid record"); - SourceFileName = ValueName.c_str(); - break; + Record.clear(); + Expected MaybeBitCode = Stream.readRecord(Entry.ID, Record); + if (!MaybeBitCode) + return MaybeBitCode.takeError(); + switch (MaybeBitCode.get()) { + default: + break; // Default behavior, ignore unknown content. + case bitc::MODULE_CODE_VERSION: { + if (Error Err = parseVersionRecord(Record).takeError()) + return Err; + break; + } + /// MODULE_CODE_SOURCE_FILENAME: [namechar x N] + case bitc::MODULE_CODE_SOURCE_FILENAME: { + SmallString<128> ValueName; + if (convertToString(Record, 0, ValueName)) + return error("Invalid record"); + SourceFileName = ValueName.c_str(); + break; + } + /// MODULE_CODE_HASH: [5*i32] + case bitc::MODULE_CODE_HASH: { + if (Record.size() != 5) + return error("Invalid hash length " + Twine(Record.size()).str()); + auto &Hash = getThisModule()->second.second; + int Pos = 0; + for (auto &Val : Record) { + assert(!(Val >> 32) && "Unexpected high bits set"); + Hash[Pos++] = Val; } - /// MODULE_CODE_HASH: [5*i32] - case bitc::MODULE_CODE_HASH: { - if (Record.size() != 5) - return error("Invalid hash length " + Twine(Record.size()).str()); - auto &Hash = getThisModule()->second.second; - int Pos = 0; - for (auto &Val : Record) { - assert(!(Val >> 32) && "Unexpected high bits set"); - Hash[Pos++] = Val; - } + break; + } + /// MODULE_CODE_VSTOFFSET: [offset] + case bitc::MODULE_CODE_VSTOFFSET: + if (Record.size() < 1) + return error("Invalid record"); + // Note that we subtract 1 here because the offset is relative to one + // word before the start of the identification or module block, which + // was historically always the start of the regular bitcode header. + VSTOffset = Record[0] - 1; + break; + // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] + // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] + // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] + // v2: [strtab offset, strtab size, v1] + case bitc::MODULE_CODE_GLOBALVAR: + case bitc::MODULE_CODE_FUNCTION: + case bitc::MODULE_CODE_ALIAS: { + StringRef Name; + ArrayRef GVRecord; + std::tie(Name, GVRecord) = readNameFromStrtab(Record); + if (GVRecord.size() <= 3) + return error("Invalid record"); + uint64_t RawLinkage = GVRecord[3]; + GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); + if (!UseStrtab) { + ValueIdToLinkageMap[ValueId++] = Linkage; break; } - /// MODULE_CODE_VSTOFFSET: [offset] - case bitc::MODULE_CODE_VSTOFFSET: - if (Record.size() < 1) - return error("Invalid record"); - // Note that we subtract 1 here because the offset is relative to one - // word before the start of the identification or module block, which - // was historically always the start of the regular bitcode header. - VSTOffset = Record[0] - 1; - break; - // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...] - // v1 FUNCTION: [type, callingconv, isproto, linkage, ...] - // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...] - // v2: [strtab offset, strtab size, v1] - case bitc::MODULE_CODE_GLOBALVAR: - case bitc::MODULE_CODE_FUNCTION: - case bitc::MODULE_CODE_ALIAS: { - StringRef Name; - ArrayRef GVRecord; - std::tie(Name, GVRecord) = readNameFromStrtab(Record); - if (GVRecord.size() <= 3) - return error("Invalid record"); - uint64_t RawLinkage = GVRecord[3]; - GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage); - if (!UseStrtab) { - ValueIdToLinkageMap[ValueId++] = Linkage; - break; - } - setValueGUID(ValueId++, Name, Linkage, SourceFileName); - break; - } - } + setValueGUID(ValueId++, Name, Linkage, SourceFileName); + break; } + } + } continue; } } @@ -5592,7 +5718,7 @@ switch (unsigned BitCode = MaybeBitCode.get()) { default: // Default behavior: ignore. break; - case bitc::FS_FLAGS: { // [flags] + case bitc::FS_FLAGS: { // [flags] uint64_t Flags = Record[0]; // Scan flags. assert(Flags <= 0x1f && "Unexpected bits in flag"); @@ -5707,7 +5833,8 @@ AS->setModulePath(getThisModule()->first()); auto AliaseeVI = getValueInfoFromValueId(AliaseeID).first; - auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath); + auto AliaseeInModule = + TheIndex.findSummaryInModule(AliaseeVI, ModulePath); if (!AliaseeInModule) return error("Alias expects aliasee summary to be parsed"); AS->setAliasee(AliaseeVI, AliaseeInModule); @@ -5814,7 +5941,8 @@ AS->setModulePath(ModuleIdMap[ModuleId]); auto AliaseeVI = getValueInfoFromValueId(AliaseeValueId).first; - auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); + auto AliaseeInModule = + TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath()); AS->setAliasee(AliaseeVI, AliaseeInModule); ValueInfo VI = getValueInfoFromValueId(ValueID).first; @@ -5866,13 +5994,13 @@ case bitc::FS_TYPE_TEST_ASSUME_VCALLS: assert(PendingTypeTestAssumeVCalls.empty()); for (unsigned I = 0; I != Record.size(); I += 2) - PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]}); + PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I + 1]}); break; case bitc::FS_TYPE_CHECKED_LOAD_VCALLS: assert(PendingTypeCheckedLoadVCalls.empty()); for (unsigned I = 0; I != Record.size(); I += 2) - PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]}); + PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I + 1]}); break; case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL: @@ -5983,9 +6111,7 @@ // will be removed once this transition is complete. Clients should prefer to // deal with the Error value directly, rather than converting to error_code. class BitcodeErrorCategoryType : public std::error_category { - const char *name() const noexcept override { - return "llvm.bitcode"; - } + const char *name() const noexcept override { return "llvm.bitcode"; } std::string message(int IE) const override { BitcodeError E = static_cast(IE); Index: llvm/lib/IR/Type.cpp =================================================================== --- llvm/lib/IR/Type.cpp +++ llvm/lib/IR/Type.cpp @@ -336,8 +336,16 @@ // StructType Implementation //===----------------------------------------------------------------------===// +StructType *StructType::getIfExists(LLVMContext &Context, StringRef Name) { + auto I = Context.pImpl->NamedStructTypes.find(Name); + if (I == Context.pImpl->NamedStructTypes.end()) + return nullptr; + return I->getValue(); +} + // Primitive Constructors. + StructType *StructType::get(LLVMContext &Context, ArrayRef ETypes, bool isPacked) { LLVMContextImpl *pImpl = Context.pImpl; Index: llvm/unittests/Bitcode/BitReaderTest.cpp =================================================================== --- llvm/unittests/Bitcode/BitReaderTest.cpp +++ llvm/unittests/Bitcode/BitReaderTest.cpp @@ -190,4 +190,130 @@ EXPECT_FALSE(verifyModule(*M, &dbgs())); } +TEST(BitReaderTest, UseExistingNameStructType) { + // Make a module using a struct type, then write that. + LLVMContext C1; + StructType *T1 = StructType::create(C1, "Correct"); + T1->setBody(Type::getInt32Ty(C1)); + std::unique_ptr M1(new Module("M1", C1)); + M1->getOrInsertFunction("F1", T1); + SmallString<1024> Memory; + raw_svector_ostream OS(Memory); + WriteBitcodeToFile(*M1, OS); + + // Define that struct type in a new context. Read the module into that + // context. At this point, the context contains the StructType the module + // uses. + LLVMContext C2; + StructType *T2 = StructType::create(C2, T1->getName()); + T2->setBody(Type::getInt32Ty(C2)); + auto Careful = parseBitcodeFile(MemoryBufferRef(Memory.str(), "test"), C2); + EXPECT_TRUE((bool)Careful); + std::unique_ptr M2(Careful.get().release()); + + // Then one single test: was the already-present struct type used? + Function *F2 = M2->getFunction("F1"); + EXPECT_NE(F2, nullptr); + EXPECT_EQ(cast(F2->getReturnType())->getName(), T1->getName()); + + // Define a different StructType of the same name. Reading the bitcode into + // THAT context should fail. + LLVMContext C3; + StructType *T3 = StructType::create(C3, T1->getName()); + T3->setBody(Type::getFloatTy(C3)); + Careful = parseBitcodeFile(MemoryBufferRef(Memory.str(), "test"), C3); + EXPECT_FALSE((bool)Careful); + handleAllErrors(Careful.takeError(), [&](const ErrorInfoBase &DE) {}); +} + +TEST(BitReaderTest, ResolveForwardStructReferences) { + // This test is intended to resemble reading a subclass and a superclass from + // separate .bc files into the same LLVMContext. Subclasses and superclasses + // often contain functions (or methods if you will) with the same signature. + // This test approximates that using two functions with the same FunctionType. + + // Make a context using two struct types that reference each other. One of the + // types necessarily has to contain a forward reference when written to the + // .bc files. + + LLVMContext C1; + StructType *T1A = StructType::create(C1, "Struct1"); + StructType *T2A = StructType::create(C1, "Struct2"); + T1A->setBody(T2A->getPointerTo()); + T2A->setBody(T1A->getPointerTo()); + + // Make two modules, each containing one function with the same function type. + + std::unique_ptr M1A(new Module("M1", C1)); + std::unique_ptr M2A(new Module("M2", C1)); + M1A->getOrInsertFunction("F1", Type::getVoidTy(C1), T1A->getPointerTo(), + T2A->getPointerTo()); + M2A->getOrInsertFunction("F2", Type::getVoidTy(C1), T1A->getPointerTo(), + T2A->getPointerTo()); + EXPECT_EQ(M1A->getFunction("F1")->getFunctionType(), + M2A->getFunction("F2")->getFunctionType()); + + // Write both modules to separate .bc files, then read the .bc files into the + // same new context. + + SmallString<1024> BC1; + raw_svector_ostream OS1(BC1); + WriteBitcodeToFile(*M1A, OS1); + SmallString<1024> BC2; + raw_svector_ostream OS2(BC2); + WriteBitcodeToFile(*M2A, OS2); + + LLVMContext C2; + auto Careful = parseBitcodeFile(MemoryBufferRef(BC1.str(), "test"), C2); + EXPECT_TRUE((bool)Careful); + std::unique_ptr M1B(Careful.get().release()); + Careful = parseBitcodeFile(MemoryBufferRef(BC2.str(), "test"), C2); + EXPECT_TRUE((bool)Careful); + std::unique_ptr M2B(Careful.get().release()); + + // The two functions should still have the same signature. + + EXPECT_EQ(M1B->getFunction("F1")->getFunctionType(), + M2B->getFunction("F2")->getFunctionType()); + + // I wish I could EXPECT_THAT(BC1->containsForwardTypeReference()) but that + // seems entirely unreasonable. +} + +TEST(BitReaderTest, CreateUnnamedStructTypes) { + // This test checks that two unnamed named struct types aren't inappropriately + // merged. I love it when I write a test just to be safe, and it passes the + // first time I run it. + + LLVMContext C1; + StructType *T1 = StructType::create(C1); + StructType *T2 = StructType::create(C1); + T1->setBody(T2->getPointerTo()); + // T2 intentionally opaque + + std::unique_ptr M(new Module("M", C1)); + M->getOrInsertFunction("F", Type::getVoidTy(C1), T1->getPointerTo(), + T2->getPointerTo()); + + SmallString<1024> BC; + raw_svector_ostream OS(BC); + WriteBitcodeToFile(*M, OS); + + LLVMContext C2; + StructType *T3 = StructType::create(C2); + auto Careful = parseBitcodeFile(MemoryBufferRef(BC.str(), "test"), C2); + EXPECT_TRUE((bool)Careful); + + // There's no reason to believe that T1 or T2 matches T3, and T1 and T2 + // definitely do not match each other. Verify all of that. + + Function *F = Careful.get().release()->getFunction("F"); + EXPECT_NE(nullptr, F); + FunctionType *FT = F->getFunctionType(); + EXPECT_EQ(2U, FT->getNumParams()); + EXPECT_NE(FT->getParamType(0), FT->getParamType(1)); + EXPECT_NE(T3, FT->getParamType(0)); + EXPECT_NE(T3, FT->getParamType(1)); +} + } // end namespace