llvm.org GIT mirror llvm / 68016e0
Use the DiagnosticHandler to print diagnostics when reading bitcode. The bitcode reading interface used std::error_code to report an error to the callers and it is the callers job to print diagnostics. This is not ideal for error handling or diagnostic reporting: * For error handling, all that the callers care about is 3 possibilities: * It worked * The bitcode file is corrupted/invalid. * The file is not bitcode at all. * For diagnostic, it is user friendly to include far more information about the invalid case so the user can find out what is wrong with the bitcode file. This comes up, for example, when a developer introduces a bug while extending the format. The compromise we had was to have a lot of error codes. With this patch we use the DiagnosticHandler to communicate with the human and std::error_code to communicate with the caller. This allows us to have far fewer error codes and adds the infrastructure to print better diagnostics. This is so because the diagnostics are printed when he issue is found. The code that detected the problem in alive in the stack and can pass down as much context as needed. As an example the patch updates test/Bitcode/invalid.ll. Using a DiagnosticHandler also moves the fatal/non-fatal error decision to the caller. A simple one like llvm-dis can just use fatal errors. The gold plugin needs a bit more complex treatment because of being passed non-bitcode files. An hypothetical interactive tool would make all bitcode errors non-fatal. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@225562 91177308-0d34-0410-b5e6-96231b3b80d8 Rafael Espindola 4 years ago
11 changed file(s) with 429 addition(s) and 369 deletion(s). Raw diff Collapse all Expand all
1313 #ifndef LLVM_BITCODE_READERWRITER_H
1414 #define LLVM_BITCODE_READERWRITER_H
1515
16 #include "llvm/IR/DiagnosticInfo.h"
1617 #include "llvm/Support/ErrorOr.h"
1718 #include "llvm/Support/MemoryBuffer.h"
1819 #include
2930 /// Read the header of the specified bitcode buffer and prepare for lazy
3031 /// deserialization of function bodies. If successful, this moves Buffer. On
3132 /// error, this *does not* move Buffer.
32 ErrorOr getLazyBitcodeModule(std::unique_ptr &&Buffer,
33 LLVMContext &Context);
33 ErrorOr
34 getLazyBitcodeModule(std::unique_ptr &&Buffer,
35 LLVMContext &Context,
36 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
3437
3538 /// Read the header of the specified stream and prepare for lazy
3639 /// deserialization and streaming of function bodies.
37 ErrorOr>
38 getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
39 LLVMContext &Context);
40 ErrorOr> getStreamedBitcodeModule(
41 StringRef Name, DataStreamer *Streamer, LLVMContext &Context,
42 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
4043
4144 /// Read the header of the specified bitcode buffer and extract just the
4245 /// triple information. If successful, this returns a string. On error, this
4346 /// returns "".
44 std::string getBitcodeTargetTriple(MemoryBufferRef Buffer,
45 LLVMContext &Context);
47 std::string
48 getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
49 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
4650
4751 /// Read the specified bitcode file, returning the module.
48 ErrorOr parseBitcodeFile(MemoryBufferRef Buffer,
49 LLVMContext &Context);
52 ErrorOr
53 parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
54 DiagnosticHandlerFunction DiagnosticHandler = nullptr);
5055
5156 /// WriteBitcodeToFile - Write the specified module to the specified
5257 /// raw output stream. For streams where it matters, the given stream
137142 }
138143
139144 const std::error_category &BitcodeErrorCategory();
140 enum class BitcodeError {
141 ConflictingMETADATA_KINDRecords,
142 CouldNotFindFunctionInStream,
143 ExpectedConstant,
144 InsufficientFunctionProtos,
145 InvalidBitcodeSignature,
146 InvalidBitcodeWrapperHeader,
147 InvalidConstantReference,
148 InvalidID, // A read identifier is not found in the table it should be in.
149 InvalidInstructionWithNoBB,
150 InvalidRecord, // A read record doesn't have the expected size or structure
151 InvalidTypeForValue, // Type read OK, but is invalid for its use
152 InvalidTYPETable,
153 InvalidType, // We were unable to read a type
154 MalformedBlock, // We are unable to advance in the stream.
155 MalformedGlobalInitializerSet,
156 InvalidMultipleBlocks, // We found multiple blocks of a kind that should
157 // have only one
158 NeverResolvedValueFoundInFunction,
159 NeverResolvedFunctionFromBlockAddress,
160 InvalidValue // Invalid version, inst number, attr number, etc
161 };
145 enum class BitcodeError { InvalidBitcodeSignature, CorruptedBitcode };
162146 inline std::error_code make_error_code(BitcodeError E) {
163147 return std::error_code(static_cast(E), BitcodeErrorCategory());
164148 }
149
150 class BitcodeDiagnosticInfo : public DiagnosticInfo {
151 const Twine &Msg;
152 std::error_code EC;
153
154 public:
155 BitcodeDiagnosticInfo(std::error_code EC, DiagnosticSeverity Severity,
156 const Twine &Msg);
157 void print(DiagnosticPrinter &DP) const override;
158 std::error_code getError() const { return EC; };
159
160 static bool classof(const DiagnosticInfo *DI) {
161 return DI->getKind() == DK_Bitcode;
162 }
163 };
165164
166165 } // End llvm namespace
167166
4444 /// \brief Defines the different supported kind of a diagnostic.
4545 /// This enum should be extended with a new ID for each added concrete subclass.
4646 enum DiagnosticKind {
47 DK_Bitcode,
4748 DK_InlineAsm,
4849 DK_StackSize,
4950 DK_Linker,
9596 /// keyword.
9697 virtual void print(DiagnosticPrinter &DP) const = 0;
9798 };
99
100 typedef std::function DiagnosticHandlerFunction;
98101
99102 /// Diagnostic information for inline asm reporting.
100103 /// This is basically a message and an optional location.
1212 #include "llvm/ADT/ArrayRef.h"
1313 #include "llvm/ADT/DenseMap.h"
1414 #include "llvm/ADT/DenseSet.h"
15
16 #include
15 #include "llvm/IR/DiagnosticInfo.h"
1716
1817 namespace llvm {
19 class DiagnosticInfo;
2018 class Module;
2119 class StructType;
2220 class Type;
2725 /// something with it after the linking.
2826 class Linker {
2927 public:
30 typedef std::function DiagnosticHandlerFunction;
31
3228 struct StructTypeKeyInfo {
3329 struct KeyTy {
3430 ArrayRef ETypes;
1414 #include "llvm/IR/AutoUpgrade.h"
1515 #include "llvm/IR/Constants.h"
1616 #include "llvm/IR/DerivedTypes.h"
17 #include "llvm/IR/DiagnosticPrinter.h"
1718 #include "llvm/IR/InlineAsm.h"
1819 #include "llvm/IR/IntrinsicInst.h"
1920 #include "llvm/IR/LLVMContext.h"
3233 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
3334 };
3435
36 BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
37 DiagnosticSeverity Severity,
38 const Twine &Msg)
39 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
40
41 void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
42
43 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
44 std::error_code EC, const Twine &Message) {
45 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
46 DiagnosticHandler(DI);
47 return EC;
48 }
49
50 static std::error_code Error(DiagnosticHandlerFunction DiagnosticHandler,
51 std::error_code EC) {
52 return Error(DiagnosticHandler, EC, EC.message());
53 }
54
55 std::error_code BitcodeReader::Error(BitcodeError E, const Twine &Message) {
56 return ::Error(DiagnosticHandler, make_error_code(E), Message);
57 }
58
59 std::error_code BitcodeReader::Error(const Twine &Message) {
60 return ::Error(DiagnosticHandler,
61 make_error_code(BitcodeError::CorruptedBitcode), Message);
62 }
63
64 std::error_code BitcodeReader::Error(BitcodeError E) {
65 return ::Error(DiagnosticHandler, make_error_code(E));
66 }
67
68 static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
69 LLVMContext &C) {
70 if (F)
71 return F;
72 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
73 }
74
75 BitcodeReader::BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
76 DiagnosticHandlerFunction DiagnosticHandler)
77 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
78 TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
79 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
80 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
81 WillMaterializeAllForwardRefs(false) {}
82
83 BitcodeReader::BitcodeReader(DataStreamer *streamer, LLVMContext &C,
84 DiagnosticHandlerFunction DiagnosticHandler)
85 : Context(C), DiagnosticHandler(getDiagHandler(DiagnosticHandler, C)),
86 TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
87 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
88 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
89 WillMaterializeAllForwardRefs(false) {}
90
3591 std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
3692 if (WillMaterializeAllForwardRefs)
3793 return std::error_code();
52108 // isn't a trivial way to check if a function will have a body without a
53109 // linear search through FunctionsWithBodies, so just check it here.
54110 if (!F->isMaterializable())
55 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
111 return Error("Never resolved function from blockaddress");
56112
57113 // Try to materialize F.
58114 if (std::error_code EC = materialize(F))
559615
560616 std::error_code BitcodeReader::ParseAttributeBlock() {
561617 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
562 return Error(BitcodeError::InvalidRecord);
618 return Error("Invalid record");
563619
564620 if (!MAttributes.empty())
565 return Error(BitcodeError::InvalidMultipleBlocks);
621 return Error("Invalid multiple blocks");
566622
567623 SmallVector Record;
568624
575631 switch (Entry.Kind) {
576632 case BitstreamEntry::SubBlock: // Handled for us already.
577633 case BitstreamEntry::Error:
578 return Error(BitcodeError::MalformedBlock);
634 return Error("Malformed block");
579635 case BitstreamEntry::EndBlock:
580636 return std::error_code();
581637 case BitstreamEntry::Record:
591647 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
592648 // FIXME: Remove in 4.0.
593649 if (Record.size() & 1)
594 return Error(BitcodeError::InvalidRecord);
650 return Error("Invalid record");
595651
596652 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
597653 AttrBuilder B;
709765 Attribute::AttrKind *Kind) {
710766 *Kind = GetAttrFromCode(Code);
711767 if (*Kind == Attribute::None)
712 return Error(BitcodeError::InvalidValue);
768 return Error(BitcodeError::CorruptedBitcode,
769 "Unknown attribute kind (" + Twine(Code) + ")");
713770 return std::error_code();
714771 }
715772
716773 std::error_code BitcodeReader::ParseAttributeGroupBlock() {
717774 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
718 return Error(BitcodeError::InvalidRecord);
775 return Error("Invalid record");
719776
720777 if (!MAttributeGroups.empty())
721 return Error(BitcodeError::InvalidMultipleBlocks);
778 return Error("Invalid multiple blocks");
722779
723780 SmallVector Record;
724781
729786 switch (Entry.Kind) {
730787 case BitstreamEntry::SubBlock: // Handled for us already.
731788 case BitstreamEntry::Error:
732 return Error(BitcodeError::MalformedBlock);
789 return Error("Malformed block");
733790 case BitstreamEntry::EndBlock:
734791 return std::error_code();
735792 case BitstreamEntry::Record:
744801 break;
745802 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
746803 if (Record.size() < 3)
747 return Error(BitcodeError::InvalidRecord);
804 return Error("Invalid record");
748805
749806 uint64_t GrpID = Record[0];
750807 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
799856
800857 std::error_code BitcodeReader::ParseTypeTable() {
801858 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
802 return Error(BitcodeError::InvalidRecord);
859 return Error("Invalid record");
803860
804861 return ParseTypeTableBody();
805862 }
806863
807864 std::error_code BitcodeReader::ParseTypeTableBody() {
808865 if (!TypeList.empty())
809 return Error(BitcodeError::InvalidMultipleBlocks);
866 return Error("Invalid multiple blocks");
810867
811868 SmallVector Record;
812869 unsigned NumRecords = 0;
820877 switch (Entry.Kind) {
821878 case BitstreamEntry::SubBlock: // Handled for us already.
822879 case BitstreamEntry::Error:
823 return Error(BitcodeError::MalformedBlock);
880 return Error("Malformed block");
824881 case BitstreamEntry::EndBlock:
825882 if (NumRecords != TypeList.size())
826 return Error(BitcodeError::MalformedBlock);
883 return Error("Malformed block");
827884 return std::error_code();
828885 case BitstreamEntry::Record:
829886 // The interesting case.
835892 Type *ResultTy = nullptr;
836893 switch (Stream.readRecord(Entry.ID, Record)) {
837894 default:
838 return Error(BitcodeError::InvalidValue);
895 return Error("Invalid value");
839896 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
840897 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
841898 // type list. This allows us to reserve space.
842899 if (Record.size() < 1)
843 return Error(BitcodeError::InvalidRecord);
900 return Error("Invalid record");
844901 TypeList.resize(Record[0]);
845902 continue;
846903 case bitc::TYPE_CODE_VOID: // VOID
875932 break;
876933 case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
877934 if (Record.size() < 1)
878 return Error(BitcodeError::InvalidRecord);
935 return Error("Invalid record");
879936
880937 ResultTy = IntegerType::get(Context, Record[0]);
881938 break;
882939 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
883940 // [pointee type, address space]
884941 if (Record.size() < 1)
885 return Error(BitcodeError::InvalidRecord);
942 return Error("Invalid record");
886943 unsigned AddressSpace = 0;
887944 if (Record.size() == 2)
888945 AddressSpace = Record[1];
889946 ResultTy = getTypeByID(Record[0]);
890947 if (!ResultTy)
891 return Error(BitcodeError::InvalidType);
948 return Error("Invalid type");
892949 ResultTy = PointerType::get(ResultTy, AddressSpace);
893950 break;
894951 }
896953 // FIXME: attrid is dead, remove it in LLVM 4.0
897954 // FUNCTION: [vararg, attrid, retty, paramty x N]
898955 if (Record.size() < 3)
899 return Error(BitcodeError::InvalidRecord);
956 return Error("Invalid record");
900957 SmallVector ArgTys;
901958 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
902959 if (Type *T = getTypeByID(Record[i]))
907964
908965 ResultTy = getTypeByID(Record[2]);
909966 if (!ResultTy || ArgTys.size() < Record.size()-3)
910 return Error(BitcodeError::InvalidType);
967 return Error("Invalid type");
911968
912969 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
913970 break;
915972 case bitc::TYPE_CODE_FUNCTION: {
916973 // FUNCTION: [vararg, retty, paramty x N]
917974 if (Record.size() < 2)
918 return Error(BitcodeError::InvalidRecord);
975 return Error("Invalid record");
919976 SmallVector ArgTys;
920977 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
921978 if (Type *T = getTypeByID(Record[i]))
926983
927984 ResultTy = getTypeByID(Record[1]);
928985 if (!ResultTy || ArgTys.size() < Record.size()-2)
929 return Error(BitcodeError::InvalidType);
986 return Error("Invalid type");
930987
931988 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
932989 break;
933990 }
934991 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
935992 if (Record.size() < 1)
936 return Error(BitcodeError::InvalidRecord);
993 return Error("Invalid record");
937994 SmallVector EltTys;
938995 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
939996 if (Type *T = getTypeByID(Record[i]))
942999 break;
9431000 }
9441001 if (EltTys.size() != Record.size()-1)
945 return Error(BitcodeError::InvalidType);
1002 return Error("Invalid type");
9461003 ResultTy = StructType::get(Context, EltTys, Record[0]);
9471004 break;
9481005 }
9491006 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
9501007 if (ConvertToString(Record, 0, TypeName))
951 return Error(BitcodeError::InvalidRecord);
1008 return Error("Invalid record");
9521009 continue;
9531010
9541011 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
9551012 if (Record.size() < 1)
956 return Error(BitcodeError::InvalidRecord);
1013 return Error("Invalid record");
9571014
9581015 if (NumRecords >= TypeList.size())
959 return Error(BitcodeError::InvalidTYPETable);
1016 return Error("Invalid TYPE table");
9601017
9611018 // Check to see if this was forward referenced, if so fill in the temp.
9621019 StructType *Res = cast_or_null(TypeList[NumRecords]);
9751032 break;
9761033 }
9771034 if (EltTys.size() != Record.size()-1)
978 return Error(BitcodeError::InvalidRecord);
1035 return Error("Invalid record");
9791036 Res->setBody(EltTys, Record[0]);
9801037 ResultTy = Res;
9811038 break;
9821039 }
9831040 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
9841041 if (Record.size() != 1)
985 return Error(BitcodeError::InvalidRecord);
1042 return Error("Invalid record");
9861043
9871044 if (NumRecords >= TypeList.size())
988 return Error(BitcodeError::InvalidTYPETable);
1045 return Error("Invalid TYPE table");
9891046
9901047 // Check to see if this was forward referenced, if so fill in the temp.
9911048 StructType *Res = cast_or_null(TypeList[NumRecords]);
10001057 }
10011058 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
10021059 if (Record.size() < 2)
1003 return Error(BitcodeError::InvalidRecord);
1060 return Error("Invalid record");
10041061 if ((ResultTy = getTypeByID(Record[1])))
10051062 ResultTy = ArrayType::get(ResultTy, Record[0]);
10061063 else
1007 return Error(BitcodeError::InvalidType);
1064 return Error("Invalid type");
10081065 break;
10091066 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
10101067 if (Record.size() < 2)
1011 return Error(BitcodeError::InvalidRecord);
1068 return Error("Invalid record");
10121069 if ((ResultTy = getTypeByID(Record[1])))
10131070 ResultTy = VectorType::get(ResultTy, Record[0]);
10141071 else
1015 return Error(BitcodeError::InvalidType);
1072 return Error("Invalid type");
10161073 break;
10171074 }
10181075
10191076 if (NumRecords >= TypeList.size())
1020 return Error(BitcodeError::InvalidTYPETable);
1077 return Error("Invalid TYPE table");
10211078 assert(ResultTy && "Didn't read a type?");
10221079 assert(!TypeList[NumRecords] && "Already read type?");
10231080 TypeList[NumRecords++] = ResultTy;
10261083
10271084 std::error_code BitcodeReader::ParseValueSymbolTable() {
10281085 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
1029 return Error(BitcodeError::InvalidRecord);
1086 return Error("Invalid record");
10301087
10311088 SmallVector Record;
10321089
10381095 switch (Entry.Kind) {
10391096 case BitstreamEntry::SubBlock: // Handled for us already.
10401097 case BitstreamEntry::Error:
1041 return Error(BitcodeError::MalformedBlock);
1098 return Error("Malformed block");
10421099 case BitstreamEntry::EndBlock:
10431100 return std::error_code();
10441101 case BitstreamEntry::Record:
10531110 break;
10541111 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
10551112 if (ConvertToString(Record, 1, ValueName))
1056 return Error(BitcodeError::InvalidRecord);
1113 return Error("Invalid record");
10571114 unsigned ValueID = Record[0];
10581115 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1059 return Error(BitcodeError::InvalidRecord);
1116 return Error("Invalid record");
10601117 Value *V = ValueList[ValueID];
10611118
10621119 V->setName(StringRef(ValueName.data(), ValueName.size()));
10651122 }
10661123 case bitc::VST_CODE_BBENTRY: {
10671124 if (ConvertToString(Record, 1, ValueName))
1068 return Error(BitcodeError::InvalidRecord);
1125 return Error("Invalid record");
10691126 BasicBlock *BB = getBasicBlock(Record[0]);
10701127 if (!BB)
1071 return Error(BitcodeError::InvalidRecord);
1128 return Error("Invalid record");
10721129
10731130 BB->setName(StringRef(ValueName.data(), ValueName.size()));
10741131 ValueName.clear();
10821139 unsigned NextMDValueNo = MDValueList.size();
10831140
10841141 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
1085 return Error(BitcodeError::InvalidRecord);
1142 return Error("Invalid record");
10861143
10871144 SmallVector Record;
10881145
10931150 switch (Entry.Kind) {
10941151 case BitstreamEntry::SubBlock: // Handled for us already.
10951152 case BitstreamEntry::Error:
1096 return Error(BitcodeError::MalformedBlock);
1153 return Error("Malformed block");
10971154 case BitstreamEntry::EndBlock:
10981155 MDValueList.tryToResolveCycles();
10991156 return std::error_code();
11251182 for (unsigned i = 0; i != Size; ++i) {
11261183 MDNode *MD = dyn_cast_or_null(MDValueList.getValueFwdRef(Record[i]));
11271184 if (!MD)
1128 return Error(BitcodeError::InvalidRecord);
1185 return Error("Invalid record");
11291186 NMD->addOperand(MD);
11301187 }
11311188 break;
11351192 // This is a LocalAsMetadata record, the only type of function-local
11361193 // metadata.
11371194 if (Record.size() % 2 == 1)
1138 return Error(BitcodeError::InvalidRecord);
1195 return Error("Invalid record");
11391196
11401197 // If this isn't a LocalAsMetadata record, we're dropping it. This used
11411198 // to be legal, but there's no upgrade path.
11611218 case bitc::METADATA_OLD_NODE: {
11621219 // FIXME: Remove in 4.0.
11631220 if (Record.size() % 2 == 1)
1164 return Error(BitcodeError::InvalidRecord);
1221 return Error("Invalid record");
11651222
11661223 unsigned Size = Record.size();
11671224 SmallVector Elts;
11681225 for (unsigned i = 0; i != Size; i += 2) {
11691226 Type *Ty = getTypeByID(Record[i]);
11701227 if (!Ty)
1171 return Error(BitcodeError::InvalidRecord);
1228 return Error("Invalid record");
11721229 if (Ty->isMetadataTy())
11731230 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
11741231 else if (!Ty->isVoidTy()) {
11851242 }
11861243 case bitc::METADATA_VALUE: {
11871244 if (Record.size() != 2)
1188 return Error(BitcodeError::InvalidRecord);
1245 return Error("Invalid record");
11891246
11901247 Type *Ty = getTypeByID(Record[0]);
11911248 if (Ty->isMetadataTy() || Ty->isVoidTy())
1192 return Error(BitcodeError::InvalidRecord);
1249 return Error("Invalid record");
11931250
11941251 MDValueList.AssignValue(
11951252 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
12181275 }
12191276 case bitc::METADATA_KIND: {
12201277 if (Record.size() < 2)
1221 return Error(BitcodeError::InvalidRecord);
1278 return Error("Invalid record");
12221279
12231280 unsigned Kind = Record[0];
12241281 SmallString<8> Name(Record.begin()+1, Record.end());
12251282
12261283 unsigned NewKind = TheModule->getMDKindID(Name.str());
12271284 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1228 return Error(BitcodeError::ConflictingMETADATA_KINDRecords);
1285 return Error("Conflicting METADATA_KIND records");
12291286 break;
12301287 }
12311288 }
12651322 if (Constant *C = dyn_cast_or_null(ValueList[ValID]))
12661323 GlobalInitWorklist.back().first->setInitializer(C);
12671324 else
1268 return Error(BitcodeError::ExpectedConstant);
1325 return Error("Expected a constant");
12691326 }
12701327 GlobalInitWorklist.pop_back();
12711328 }
12781335 if (Constant *C = dyn_cast_or_null(ValueList[ValID]))
12791336 AliasInitWorklist.back().first->setAliasee(C);
12801337 else
1281 return Error(BitcodeError::ExpectedConstant);
1338 return Error("Expected a constant");
12821339 }
12831340 AliasInitWorklist.pop_back();
12841341 }
12911348 if (Constant *C = dyn_cast_or_null(ValueList[ValID]))
12921349 FunctionPrefixWorklist.back().first->setPrefixData(C);
12931350 else
1294 return Error(BitcodeError::ExpectedConstant);
1351 return Error("Expected a constant");
12951352 }
12961353 FunctionPrefixWorklist.pop_back();
12971354 }
13041361 if (Constant *C = dyn_cast_or_null(ValueList[ValID]))
13051362 FunctionPrologueWorklist.back().first->setPrologueData(C);
13061363 else
1307 return Error(BitcodeError::ExpectedConstant);
1364 return Error("Expected a constant");
13081365 }
13091366 FunctionPrologueWorklist.pop_back();
13101367 }
13221379
13231380 std::error_code BitcodeReader::ParseConstants() {
13241381 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1325 return Error(BitcodeError::InvalidRecord);
1382 return Error("Invalid record");
13261383
13271384 SmallVector Record;
13281385
13351392 switch (Entry.Kind) {
13361393 case BitstreamEntry::SubBlock: // Handled for us already.
13371394 case BitstreamEntry::Error:
1338 return Error(BitcodeError::MalformedBlock);
1395 return Error("Malformed block");
13391396 case BitstreamEntry::EndBlock:
13401397 if (NextCstNo != ValueList.size())
1341 return Error(BitcodeError::InvalidConstantReference);
1398 return Error("Invalid ronstant reference");
13421399
13431400 // Once all the constants have been read, go through and resolve forward
13441401 // references.
13601417 break;
13611418 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
13621419 if (Record.empty())
1363 return Error(BitcodeError::InvalidRecord);
1420 return Error("Invalid record");
13641421 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
1365 return Error(BitcodeError::InvalidRecord);
1422 return Error("Invalid record");
13661423 CurTy = TypeList[Record[0]];
13671424 continue; // Skip the ValueList manipulation.
13681425 case bitc::CST_CODE_NULL: // NULL
13701427 break;
13711428 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
13721429 if (!CurTy->isIntegerTy() || Record.empty())
1373 return Error(BitcodeError::InvalidRecord);
1430 return Error("Invalid record");
13741431 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
13751432 break;
13761433 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
13771434 if (!CurTy->isIntegerTy() || Record.empty())
1378 return Error(BitcodeError::InvalidRecord);
1435 return Error("Invalid record");
13791436
13801437 APInt VInt = ReadWideAPInt(Record,
13811438 cast(CurTy)->getBitWidth());
13851442 }
13861443 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
13871444 if (Record.empty())
1388 return Error(BitcodeError::InvalidRecord);
1445 return Error("Invalid record");
13891446 if (CurTy->isHalfTy())
13901447 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
13911448 APInt(16, (uint16_t)Record[0])));
14151472
14161473 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
14171474 if (Record.empty())
1418 return Error(BitcodeError::InvalidRecord);
1475 return Error("Invalid record");
14191476
14201477 unsigned Size = Record.size();
14211478 SmallVector Elts;
14431500 case bitc::CST_CODE_STRING: // STRING: [values]
14441501 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
14451502 if (Record.empty())
1446 return Error(BitcodeError::InvalidRecord);
1503 return Error("Invalid record");
14471504
14481505 SmallString<16> Elts(Record.begin(), Record.end());
14491506 V = ConstantDataArray::getString(Context, Elts,
14521509 }
14531510 case bitc::CST_CODE_DATA: {// DATA: [n x value]
14541511 if (Record.empty())
1455 return Error(BitcodeError::InvalidRecord);
1512 return Error("Invalid record");
14561513
14571514 Type *EltTy = cast(CurTy)->getElementType();
14581515 unsigned Size = Record.size();
14971554 else
14981555 V = ConstantDataArray::get(Context, Elts);
14991556 } else {
1500 return Error(BitcodeError::InvalidTypeForValue);
1557 return Error("Invalid type for value");
15011558 }
15021559 break;
15031560 }
15041561
15051562 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
15061563 if (Record.size() < 3)
1507 return Error(BitcodeError::InvalidRecord);
1564 return Error("Invalid record");
15081565 int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
15091566 if (Opc < 0) {
15101567 V = UndefValue::get(CurTy); // Unknown binop.
15351592 }
15361593 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
15371594 if (Record.size() < 3)
1538 return Error(BitcodeError::InvalidRecord);
1595 return Error("Invalid record");
15391596 int Opc = GetDecodedCastOpcode(Record[0]);
15401597 if (Opc < 0) {
15411598 V = UndefValue::get(CurTy); // Unknown cast.
15421599 } else {
15431600 Type *OpTy = getTypeByID(Record[1]);
15441601 if (!OpTy)
1545 return Error(BitcodeError::InvalidRecord);
1602 return Error("Invalid record");
15461603 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
15471604 V = UpgradeBitCastExpr(Opc, Op, CurTy);
15481605 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
15521609 case bitc::CST_CODE_CE_INBOUNDS_GEP:
15531610 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
15541611 if (Record.size() & 1)
1555 return Error(BitcodeError::InvalidRecord);
1612 return Error("Invalid record");
15561613 SmallVector Elts;
15571614 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
15581615 Type *ElTy = getTypeByID(Record[i]);
15591616 if (!ElTy)
1560 return Error(BitcodeError::InvalidRecord);
1617 return Error("Invalid record");
15611618 Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
15621619 }
15631620 ArrayRef Indices(Elts.begin() + 1, Elts.end());
15681625 }
15691626 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
15701627 if (Record.size() < 3)
1571 return Error(BitcodeError::InvalidRecord);
1628 return Error("Invalid record");
15721629
15731630 Type *SelectorTy = Type::getInt1Ty(Context);
15741631
15871644 case bitc::CST_CODE_CE_EXTRACTELT
15881645 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
15891646 if (Record.size() < 3)
1590 return Error(BitcodeError::InvalidRecord);
1647 return Error("Invalid record");
15911648 VectorType *OpTy =
15921649 dyn_cast_or_null(getTypeByID(Record[0]));
15931650 if (!OpTy)
1594 return Error(BitcodeError::InvalidRecord);
1651 return Error("Invalid record");
15951652 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
15961653 Constant *Op1 = nullptr;
15971654 if (Record.size() == 4) {
15981655 Type *IdxTy = getTypeByID(Record[2]);
15991656 if (!IdxTy)
1600 return Error(BitcodeError::InvalidRecord);
1657 return Error("Invalid record");
16011658 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
16021659 } else // TODO: Remove with llvm 4.0
16031660 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
16041661 if (!Op1)
1605 return Error(BitcodeError::InvalidRecord);
1662 return Error("Invalid record");
16061663 V = ConstantExpr::getExtractElement(Op0, Op1);
16071664 break;
16081665 }
16101667 : { // CE_INSERTELT: [opval, opval, opty, opval]
16111668 VectorType *OpTy = dyn_cast(CurTy);
16121669 if (Record.size() < 3 || !OpTy)
1613 return Error(BitcodeError::InvalidRecord);
1670 return Error("Invalid record");
16141671 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
16151672 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
16161673 OpTy->getElementType());
16181675 if (Record.size() == 4) {
16191676 Type *IdxTy = getTypeByID(Record[2]);
16201677 if (!IdxTy)
1621 return Error(BitcodeError::InvalidRecord);
1678 return Error("Invalid record");
16221679 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
16231680 } else // TODO: Remove with llvm 4.0
16241681 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
16251682 if (!Op2)
1626 return Error(BitcodeError::InvalidRecord);
1683 return Error("Invalid record");
16271684 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
16281685 break;
16291686 }
16301687 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
16311688 VectorType *OpTy = dyn_cast(CurTy);
16321689 if (Record.size() < 3 || !OpTy)
1633 return Error(BitcodeError::InvalidRecord);
1690 return Error("Invalid record");
16341691 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
16351692 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
16361693 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
16441701 VectorType *OpTy =
16451702 dyn_cast_or_null(getTypeByID(Record[0]));
16461703 if (Record.size() < 4 || !RTy || !OpTy)
1647 return Error(BitcodeError::InvalidRecord);
1704 return Error("Invalid record");
16481705 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
16491706 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
16501707 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
16551712 }
16561713 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
16571714 if (Record.size() < 4)
1658 return Error(BitcodeError::InvalidRecord);
1715 return Error("Invalid record");
16591716 Type *OpTy = getTypeByID(Record[0]);
16601717 if (!OpTy)
1661 return Error(BitcodeError::InvalidRecord);
1718 return Error("Invalid record");
16621719 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
16631720 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
16641721
16721729 // FIXME: Remove with the 4.0 release.
16731730 case bitc::CST_CODE_INLINEASM_OLD: {
16741731 if (Record.size() < 2)
1675 return Error(BitcodeError::InvalidRecord);
1732 return Error("Invalid record");
16761733 std::string AsmStr, ConstrStr;
16771734 bool HasSideEffects = Record[0] & 1;
16781735 bool IsAlignStack = Record[0] >> 1;
16791736 unsigned AsmStrSize = Record[1];
16801737 if (2+AsmStrSize >= Record.size())
1681 return Error(BitcodeError::InvalidRecord);
1738 return Error("Invalid record");
16821739 unsigned ConstStrSize = Record[2+AsmStrSize];
16831740 if (3+AsmStrSize+ConstStrSize > Record.size())
1684 return Error(BitcodeError::InvalidRecord);
1741 return Error("Invalid record");
16851742
16861743 for (unsigned i = 0; i != AsmStrSize; ++i)
16871744 AsmStr += (char)Record[2+i];
16961753 // inteldialect).
16971754 case bitc::CST_CODE_INLINEASM: {
16981755 if (Record.size() < 2)
1699 return Error(BitcodeError::InvalidRecord);
1756 return Error("Invalid record");
17001757 std::string AsmStr, ConstrStr;
17011758 bool HasSideEffects = Record[0] & 1;
17021759 bool IsAlignStack = (Record[0] >> 1) & 1;
17031760 unsigned AsmDialect = Record[0] >> 2;
17041761 unsigned AsmStrSize = Record[1];
17051762 if (2+AsmStrSize >= Record.size())
1706 return Error(BitcodeError::InvalidRecord);
1763 return Error("Invalid record");
17071764 unsigned ConstStrSize = Record[2+AsmStrSize];
17081765 if (3+AsmStrSize+ConstStrSize > Record.size())
1709 return Error(BitcodeError::InvalidRecord);
1766 return Error("Invalid record");
17101767
17111768 for (unsigned i = 0; i != AsmStrSize; ++i)
17121769 AsmStr += (char)Record[2+i];
17201777 }
17211778 case bitc::CST_CODE_BLOCKADDRESS:{
17221779 if (Record.size() < 3)
1723 return Error(BitcodeError::InvalidRecord);
1780 return Error("Invalid record");
17241781 Type *FnTy = getTypeByID(Record[0]);
17251782 if (!FnTy)
1726 return Error(BitcodeError::InvalidRecord);
1783 return Error("Invalid record");
17271784 Function *Fn =
17281785 dyn_cast_or_null(ValueList.getConstantFwdRef(Record[1],FnTy));
17291786 if (!Fn)
1730 return Error(BitcodeError::InvalidRecord);
1787 return Error("Invalid record");
17311788
17321789 // Don't let Fn get dematerialized.
17331790 BlockAddressesTaken.insert(Fn);
17381795 unsigned BBID = Record[2];
17391796 if (!BBID)
17401797 // Invalid reference to entry block.
1741 return Error(BitcodeError::InvalidID);
1798 return Error("Invalid ID");
17421799 if (!Fn->empty()) {
17431800 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
17441801 for (size_t I = 0, E = BBID; I != E; ++I) {
17451802 if (BBI == BBE)
1746 return Error(BitcodeError::InvalidID);
1803 return Error("Invalid ID");
17471804 ++BBI;
17481805 }
17491806 BB = BBI;
17711828
17721829 std::error_code BitcodeReader::ParseUseLists() {
17731830 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1774 return Error(BitcodeError::InvalidRecord);
1831 return Error("Invalid record");
17751832
17761833 // Read all the records.
17771834 SmallVector Record;
17811838 switch (Entry.Kind) {
17821839 case BitstreamEntry::SubBlock: // Handled for us already.
17831840 case BitstreamEntry::Error:
1784 return Error(BitcodeError::MalformedBlock);
1841 return Error("Malformed block");
17851842 case BitstreamEntry::EndBlock:
17861843 return std::error_code();
17871844 case BitstreamEntry::Record:
18021859 unsigned RecordLength = Record.size();
18031860 if (RecordLength < 3)
18041861 // Records should have at least an ID and two indexes.
1805 return Error(BitcodeError::InvalidRecord);
1862 return Error("Invalid record");
18061863 unsigned ID = Record.back();
18071864 Record.pop_back();
18081865
18391896 std::error_code BitcodeReader::RememberAndSkipFunctionBody() {
18401897 // Get the function we are talking about.
18411898 if (FunctionsWithBodies.empty())
1842 return Error(BitcodeError::InsufficientFunctionProtos);
1899 return Error("Insufficient function protos");
18431900
18441901 Function *Fn = FunctionsWithBodies.back();
18451902 FunctionsWithBodies.pop_back();
18501907
18511908 // Skip over the function block for now.
18521909 if (Stream.SkipBlock())
1853 return Error(BitcodeError::InvalidRecord);
1910 return Error("Invalid record");
18541911 return std::error_code();
18551912 }
18561913
18581915 // Patch the initializers for globals and aliases up.
18591916 ResolveGlobalAndAliasInits();
18601917 if (!GlobalInits.empty() || !AliasInits.empty())
1861 return Error(BitcodeError::MalformedGlobalInitializerSet);
1918 return Error("Malformed global initializer set");
18621919
18631920 // Look for intrinsic functions which need to be upgraded at some point
18641921 for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
18871944 if (Resume)
18881945 Stream.JumpToBit(NextUnreadBit);
18891946 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1890 return Error(BitcodeError::InvalidRecord);
1947 return Error("Invalid record");
18911948
18921949 SmallVector Record;
18931950 std::vector SectionTable;
18991956
19001957 switch (Entry.Kind) {
19011958 case BitstreamEntry::Error:
1902 return Error(BitcodeError::MalformedBlock);
1959 return Error("Malformed block");
19031960 case BitstreamEntry::EndBlock:
19041961 return GlobalCleanup();
19051962
19071964 switch (Entry.ID) {
19081965 default: // Skip unknown content.
19091966 if (Stream.SkipBlock())
1910 return Error(BitcodeError::InvalidRecord);
1967 return Error("Invalid record");
19111968 break;
19121969 case bitc::BLOCKINFO_BLOCK_ID:
19131970 if (Stream.ReadBlockInfoBlock())
1914 return Error(BitcodeError::MalformedBlock);
1971 return Error("Malformed block");
19151972 break;
19161973 case bitc::PARAMATTR_BLOCK_ID:
19171974 if (std::error_code EC = ParseAttributeBlock())
19812038 default: break; // Default behavior, ignore unknown content.
19822039 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
19832040 if (Record.size() < 1)
1984 return Error(BitcodeError::InvalidRecord);
2041 return Error("Invalid record");
19852042 // Only version #0 and #1 are supported so far.
19862043 unsigned module_version = Record[0];
19872044 switch (module_version) {
19882045 default:
1989 return Error(BitcodeError::InvalidValue);
2046 return Error("Invalid value");
19902047 case 0:
19912048 UseRelativeIDs = false;
19922049 break;
19992056 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
20002057 std::string S;
20012058 if (ConvertToString(Record, 0, S))
2002 return Error(BitcodeError::InvalidRecord);
2059 return Error("Invalid record");
20032060 TheModule->setTargetTriple(S);
20042061 break;
20052062 }
20062063 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
20072064 std::string S;
20082065 if (ConvertToString(Record, 0, S))
2009 return Error(BitcodeError::InvalidRecord);
2066 return Error("Invalid record");
20102067 TheModule->setDataLayout(S);
20112068 break;
20122069 }
20132070 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
20142071 std::string S;
20152072 if (ConvertToString(Record, 0, S))
2016 return Error(BitcodeError::InvalidRecord);
2073 return Error("Invalid record");
20172074 TheModule->setModuleInlineAsm(S);
20182075 break;
20192076 }
20212078 // FIXME: Remove in 4.0.
20222079 std::string S;
20232080 if (ConvertToString(Record, 0, S))
2024 return Error(BitcodeError::InvalidRecord);
2081 return Error("Invalid record");
20252082 // Ignore value.
20262083 break;
20272084 }
20282085 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
20292086 std::string S;
20302087 if (ConvertToString(Record, 0, S))
2031 return Error(BitcodeError::InvalidRecord);
2088 return Error("Invalid record");
20322089 SectionTable.push_back(S);
20332090 break;
20342091 }
20352092 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
20362093 std::string S;
20372094 if (ConvertToString(Record, 0, S))
2038 return Error(BitcodeError::InvalidRecord);
2095 return Error("Invalid record");
20392096 GCTable.push_back(S);
20402097 break;
20412098 }
20422099 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
20432100 if (Record.size() < 2)
2044 return Error(BitcodeError::InvalidRecord);
2101 return Error("Invalid record");
20452102 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
20462103 unsigned ComdatNameSize = Record[1];
20472104 std::string ComdatName;
20582115 // unnamed_addr, dllstorageclass]
20592116 case bitc::MODULE_CODE_GLOBALVAR: {
20602117 if (Record.size() < 6)
2061 return Error(BitcodeError::InvalidRecord);
2118 return Error("Invalid record");
20622119 Type *Ty = getTypeByID(Record[0]);
20632120 if (!Ty)
2064 return Error(BitcodeError::InvalidRecord);
2121 return Error("Invalid record");
20652122 if (!Ty->isPointerTy())
2066 return Error(BitcodeError::InvalidTypeForValue);
2123 return Error("Invalid type for value");
20672124 unsigned AddressSpace = cast(Ty)->getAddressSpace();
20682125 Ty = cast(Ty)->getElementType();
20692126
20732130 std::string Section;
20742131 if (Record[5]) {
20752132 if (Record[5]-1 >= SectionTable.size())
2076 return Error(BitcodeError::InvalidID);
2133 return Error("Invalid ID");
20772134 Section = SectionTable[Record[5]-1];
20782135 }
20792136 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
21262183 // prologuedata, dllstorageclass, comdat, prefixdata]
21272184 case bitc::MODULE_CODE_FUNCTION: {
21282185 if (Record.size() < 8)
2129 return Error(BitcodeError::InvalidRecord);
2186 return Error("Invalid record");
21302187 Type *Ty = getTypeByID(Record[0]);
21312188 if (!Ty)
2132 return Error(BitcodeError::InvalidRecord);
2189 return Error("Invalid record");
21332190 if (!Ty->isPointerTy())
2134 return Error(BitcodeError::InvalidTypeForValue);
2191 return Error("Invalid type for value");
21352192 FunctionType *FTy =
21362193 dyn_cast(cast(Ty)->getElementType());
21372194 if (!FTy)
2138 return Error(BitcodeError::InvalidTypeForValue);
2195 return Error("Invalid type for value");
21392196
21402197 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
21412198 "", TheModule);
21482205 Func->setAlignment((1 << Record[5]) >> 1);
21492206 if (Record[6]) {
21502207 if (Record[6]-1 >= SectionTable.size())
2151 return Error(BitcodeError::InvalidID);
2208 return Error("Invalid ID");
21522209 Func->setSection(SectionTable[Record[6]-1]);
21532210 }
21542211 // Local linkage must have default visibility.
21572214 Func->setVisibility(GetDecodedVisibility(Record[7]));
21582215 if (Record.size() > 8 && Record[8]) {
21592216 if (Record[8]-1 > GCTable.size())
2160 return Error(BitcodeError::InvalidID);
2217 return Error("Invalid ID");
21612218 Func->setGC(GCTable[Record[8]-1].c_str());
21622219 }
21632220 bool UnnamedAddr = false;
21972254 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
21982255 case bitc::MODULE_CODE_ALIAS: {
21992256 if (Record.size() < 3)
2200 return Error(BitcodeError::InvalidRecord);
2257 return Error("Invalid record");
22012258 Type *Ty = getTypeByID(Record[0]);
22022259 if (!Ty)
2203 return Error(BitcodeError::InvalidRecord);
2260 return Error("Invalid record");
22042261 auto *PTy = dyn_cast(Ty);
22052262 if (!PTy)
2206 return Error(BitcodeError::InvalidTypeForValue);
2263 return Error("Invalid type for value");
22072264
22082265 auto *NewGA =
22092266 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
22292286 case bitc::MODULE_CODE_PURGEVALS:
22302287 // Trim down the value list to the specified size.
22312288 if (Record.size() < 1 || Record[0] > ValueList.size())
2232 return Error(BitcodeError::InvalidRecord);
2289 return Error("Invalid record");
22332290 ValueList.shrinkTo(Record[0]);
22342291 break;
22352292 }
22502307 Stream.Read(4) != 0xC ||
22512308 Stream.Read(4) != 0xE ||
22522309 Stream.Read(4) != 0xD)
2253 return Error(BitcodeError::InvalidBitcodeSignature);
2310 return Error("Invalid bitcode signature");
22542311
22552312 // We expect a number of well-defined blocks, though we don't necessarily
22562313 // need to understand them all.
22632320
22642321 switch (Entry.Kind) {
22652322 case BitstreamEntry::Error:
2266 return Error(BitcodeError::MalformedBlock);
2323 return Error("Malformed block");
22672324 case BitstreamEntry::EndBlock:
22682325 return std::error_code();
22692326
22712328 switch (Entry.ID) {
22722329 case bitc::BLOCKINFO_BLOCK_ID:
22732330 if (Stream.ReadBlockInfoBlock())
2274 return Error(BitcodeError::MalformedBlock);
2331 return Error("Malformed block");
22752332 break;
22762333 case bitc::MODULE_BLOCK_ID:
22772334 // Reject multiple MODULE_BLOCK's in a single bitstream.
22782335 if (TheModule)
2279 return Error(BitcodeError::InvalidMultipleBlocks);
2336 return Error("Invalid multiple blocks");
22802337 TheModule = M;
22812338 if (std::error_code EC = ParseModule(false))
22822339 return EC;
22852342 break;
22862343 default:
22872344 if (Stream.SkipBlock())
2288 return Error(BitcodeError::InvalidRecord);
2345 return Error("Invalid record");
22892346 break;
22902347 }
22912348 continue;
23002357 Stream.AtEndOfStream())
23012358 return std::error_code();
23022359
2303 return Error(BitcodeError::InvalidRecord);
2360 return Error("Invalid record");
23042361 }
23052362 }
23062363 }
23072364
23082365 ErrorOr BitcodeReader::parseModuleTriple() {
23092366 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
2310 return Error(BitcodeError::InvalidRecord);
2367 return Error("Invalid record");
23112368
23122369 SmallVector Record;
23132370
23192376 switch (Entry.Kind) {
23202377 case BitstreamEntry::SubBlock: // Handled for us already.
23212378 case BitstreamEntry::Error:
2322 return Error(BitcodeError::MalformedBlock);
2379 return Error("Malformed block");
23232380 case BitstreamEntry::EndBlock:
23242381 return Triple;
23252382 case BitstreamEntry::Record:
23332390 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
23342391 std::string S;
23352392 if (ConvertToString(Record, 0, S))
2336 return Error(BitcodeError::InvalidRecord);
2393 return Error("Invalid record");
23372394 Triple = S;
23382395 break;
23392396 }
23542411 Stream.Read(4) != 0xC ||
23552412 Stream.Read(4) != 0xE ||
23562413 Stream.Read(4) != 0xD)
2357 return Error(BitcodeError::InvalidBitcodeSignature);
2414 return Error("Invalid bitcode signature");
23582415
23592416 // We expect a number of well-defined blocks, though we don't necessarily
23602417 // need to understand them all.
23632420
23642421 switch (Entry.Kind) {
23652422 case BitstreamEntry::Error:
2366 return Error(BitcodeError::MalformedBlock);
2423 return Error("Malformed block");
23672424 case BitstreamEntry::EndBlock:
23682425 return std::error_code();
23692426
23732430
23742431 // Ignore other sub-blocks.
23752432 if (Stream.SkipBlock())
2376 return Error(BitcodeError::MalformedBlock);
2433 return Error("Malformed block");
23772434 continue;
23782435
23792436 case BitstreamEntry::Record:
23862443 /// ParseMetadataAttachment - Parse metadata attachments.
23872444 std::error_code BitcodeReader::ParseMetadataAttachment() {
23882445 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
2389 return Error(BitcodeError::InvalidRecord);
2446 return Error("Invalid record");
23902447
23912448 SmallVector Record;
23922449 while (1) {
23952452 switch (Entry.Kind) {
23962453 case BitstreamEntry::SubBlock: // Handled for us already.
23972454 case BitstreamEntry::Error:
2398 return Error(BitcodeError::MalformedBlock);
2455 return Error("Malformed block");
23992456 case BitstreamEntry::EndBlock:
24002457 return std::error_code();
24012458 case BitstreamEntry::Record:
24112468 case bitc::METADATA_ATTACHMENT: {
24122469 unsigned RecordLength = Record.size();
24132470 if (Record.empty() || (RecordLength - 1) % 2 == 1)
2414 return Error(BitcodeError::InvalidRecord);
2471 return Error("Invalid record");
24152472 Instruction *Inst = InstructionList[Record[0]];
24162473 for (unsigned i = 1; i != RecordLength; i = i+2) {
24172474 unsigned Kind = Record[i];
24182475 DenseMap::iterator I =
24192476 MDKindMap.find(Kind);
24202477 if (I == MDKindMap.end())
2421 return Error(BitcodeError::InvalidID);
2478 return Error("Invalid ID");
24222479 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
24232480 if (isa(Node))
24242481 // Drop the attachment. This used to be legal, but there's no
24372494 /// ParseFunctionBody - Lazily parse the specified function body block.
24382495 std::error_code BitcodeReader::ParseFunctionBody(Function *F) {
24392496 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
2440 return Error(BitcodeError::InvalidRecord);
2497 return Error("Invalid record");
24412498
24422499 InstructionList.clear();
24432500 unsigned ModuleValueListSize = ValueList.size();
24682525
24692526 switch (Entry.Kind) {
24702527 case BitstreamEntry::Error:
2471 return Error(BitcodeError::MalformedBlock);
2528 return Error("Malformed block");
24722529 case BitstreamEntry::EndBlock:
24732530 goto OutOfRecordLoop;
24742531
24762533 switch (Entry.ID) {
24772534 default: // Skip unknown content.
24782535 if (Stream.SkipBlock())
2479 return Error(BitcodeError::InvalidRecord);
2536 return Error("Invalid record");
24802537 break;
24812538 case bitc::CONSTANTS_BLOCK_ID:
24822539 if (std::error_code EC = ParseConstants())
25132570 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
25142571 switch (BitCode) {
25152572 default: // Default behavior: reject
2516 return Error(BitcodeError::InvalidValue);
2573 return Error("Invalid value");
25172574 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
25182575 if (Record.size() < 1 || Record[0] == 0)
2519 return Error(BitcodeError::InvalidRecord);
2576 return Error("Invalid record");
25202577 // Create all the basic blocks for the function.
25212578 FunctionBBs.resize(Record[0]);
25222579
25292586 auto &BBRefs = BBFRI->second;
25302587 // Check for invalid basic block references.
25312588 if (BBRefs.size() > FunctionBBs.size())
2532 return Error(BitcodeError::InvalidID);
2589 return Error("Invalid ID");
25332590 assert(!BBRefs.empty() && "Unexpected empty array");
25342591 assert(!BBRefs.front() && "Invalid reference to entry block");
25352592 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
25552612 I = getLastInstruction();
25562613
25572614 if (!I)
2558 return Error(BitcodeError::InvalidRecord);
2615 return Error("Invalid record");
25592616 I->setDebugLoc(LastLoc);
25602617 I = nullptr;
25612618 continue;
25632620 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
25642621 I = getLastInstruction();
25652622 if (!I || Record.size() < 4)
2566 return Error(BitcodeError::InvalidRecord);
2623 return Error("Invalid record");
25672624
25682625 unsigned Line = Record[0], Col = Record[1];
25692626 unsigned ScopeID = Record[2], IAID = Record[3];
25832640 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
25842641 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
25852642 OpNum+1 > Record.size())
2586 return Error(BitcodeError::InvalidRecord);
2643 return Error("Invalid record");
25872644
25882645 int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
25892646 if (Opc == -1)
2590 return Error(BitcodeError::InvalidRecord);
2647 return Error("Invalid record");
25912648 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
25922649 InstructionList.push_back(I);
25932650 if (OpNum < Record.size()) {
26292686 Value *Op;
26302687 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
26312688 OpNum+2 != Record.size())
2632 return Error(BitcodeError::InvalidRecord);
2689 return Error("Invalid record");
26332690
26342691 Type *ResTy = getTypeByID(Record[OpNum]);
26352692 int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
26362693 if (Opc == -1 || !ResTy)
2637 return Error(BitcodeError::InvalidRecord);
2694 return Error("Invalid record");
26382695 Instruction *Temp = nullptr;
26392696 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
26402697 if (Temp) {
26522709 unsigned OpNum = 0;
26532710 Value *BasePtr;
26542711 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2655 return Error(BitcodeError::InvalidRecord);
2712 return Error("Invalid record");
26562713
26572714 SmallVector GEPIdx;
26582715 while (OpNum != Record.size()) {
26592716 Value *Op;
26602717 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2661 return Error(BitcodeError::InvalidRecord);
2718 return Error("Invalid record");
26622719 GEPIdx.push_back(Op);
26632720 }
26642721
26742731 unsigned OpNum = 0;
26752732 Value *Agg;
26762733 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2677 return Error(BitcodeError::InvalidRecord);
2734 return Error("Invalid record");
26782735
26792736 SmallVector EXTRACTVALIdx;
26802737 for (unsigned RecSize = Record.size();
26812738 OpNum != RecSize; ++OpNum) {
26822739 uint64_t Index = Record[OpNum];
26832740 if ((unsigned)Index != Index)
2684 return Error(BitcodeError::InvalidValue);
2741 return Error("Invalid value");
26852742 EXTRACTVALIdx.push_back((unsigned)Index);
26862743 }
26872744
26952752 unsigned OpNum = 0;
26962753 Value *Agg;
26972754 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2698 return Error(BitcodeError::InvalidRecord);
2755 return Error("Invalid record");
26992756 Value *Val;
27002757 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2701 return Error(BitcodeError::InvalidRecord);
2758 return Error("Invalid record");
27022759
27032760 SmallVector INSERTVALIdx;
27042761 for (unsigned RecSize = Record.size();
27052762 OpNum != RecSize; ++OpNum) {
27062763 uint64_t Index = Record[OpNum];
27072764 if ((unsigned)Index != Index)
2708 return Error(BitcodeError::InvalidValue);
2765 return Error("Invalid value");
27092766 INSERTVALIdx.push_back((unsigned)Index);
27102767 }
27112768
27222779 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
27232780 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
27242781 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2725 return Error(BitcodeError::InvalidRecord);
2782 return Error("Invalid record");
27262783
27272784 I = SelectInst::Create(Cond, TrueVal, FalseVal);
27282785 InstructionList.push_back(I);
27372794 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
27382795 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
27392796 getValueTypePair(Record, OpNum, NextValueNo, Cond))
2740 return Error(BitcodeError::InvalidRecord);
2797 return Error("Invalid record");
27412798
27422799 // select condition can be either i1 or [N x i1]
27432800 if (VectorType* vector_type =
27442801 dyn_cast(Cond->getType())) {
27452802 // expect
27462803 if (vector_type->getElementType() != Type::getInt1Ty(Context))
2747 return Error(BitcodeError::InvalidTypeForValue);
2804 return Error("Invalid type for value");
27482805 } else {
27492806 // expect i1
27502807 if (Cond->getType() != Type::getInt1Ty(Context))
2751 return Error(BitcodeError::InvalidTypeForValue);
2808 return Error("Invalid type for value");
27522809 }
27532810
27542811 I = SelectInst::Create(Cond, TrueVal, FalseVal);
27612818 Value *Vec, *Idx;
27622819 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
27632820 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2764 return Error(BitcodeError::InvalidRecord);
2821 return Error("Invalid record");
27652822 I = ExtractElementInst::Create(Vec, Idx);
27662823 InstructionList.push_back(I);
27672824 break;
27742831 popValue(Record, OpNum, NextValueNo,
27752832 cast(Vec->getType())->getElementType(), Elt) ||
27762833 getValueTypePair(Record, OpNum, NextValueNo, Idx))
2777 return Error(BitcodeError::InvalidRecord);
2834 return Error("Invalid record");
27782835 I = InsertElementInst::Create(Vec, Elt, Idx);
27792836 InstructionList.push_back(I);
27802837 break;
27852842 Value *Vec1, *Vec2, *Mask;
27862843 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
27872844 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2788 return Error(BitcodeError::InvalidRecord);
2845 return Error("Invalid record");
27892846
27902847 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2791 return Error(BitcodeError::InvalidRecord);
2848 return Error("Invalid record");
27922849 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
27932850 InstructionList.push_back(I);
27942851 break;
28062863 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
28072864 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
28082865 OpNum+1 != Record.size())
2809 return Error(BitcodeError::InvalidRecord);
2866 return Error("Invalid record");
28102867
28112868 if (LHS->getType()->isFPOrFPVectorTy())
28122869 I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
28282885 unsigned OpNum = 0;
28292886 Value *Op = nullptr;
28302887 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2831 return Error(BitcodeError::InvalidRecord);
2888 return Error("Invalid record");
28322889 if (OpNum != Record.size())
2833 return Error(BitcodeError::InvalidRecord);
2890 return Error("Invalid record");
28342891
28352892 I = ReturnInst::Create(Context, Op);
28362893 InstructionList.push_back(I);
28382895 }
28392896 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
28402897 if (Record.size() != 1 && Record.size() != 3)
2841 return Error(BitcodeError::InvalidRecord);
2898 return Error("Invalid record");
28422899 BasicBlock *TrueDest = getBasicBlock(Record[0]);
28432900 if (!TrueDest)
2844 return Error(BitcodeError::InvalidRecord);
2901 return Error("Invalid record");
28452902
28462903 if (Record.size() == 1) {
28472904 I = BranchInst::Create(TrueDest);
28522909 Value *Cond = getValue(Record, 2, NextValueNo,
28532910 Type::getInt1Ty(Context));
28542911 if (!FalseDest || !Cond)
2855 return Error(BitcodeError::InvalidRecord);
2912 return Error("Invalid record");
28562913 I = BranchInst::Create(TrueDest, FalseDest, Cond);
28572914 InstructionList.push_back(I);
28582915 }
28722929 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
28732930 BasicBlock *Default = getBasicBlock(Record[3]);
28742931 if (!OpTy || !Cond || !Default)
2875 return Error(BitcodeError::InvalidRecord);
2932 return Error("Invalid record");
28762933
28772934 unsigned NumCases = Record[4];
28782935
29242981 // Old SwitchInst format without case ranges.
29252982
29262983 if (Record.size() < 3 || (Record.size() & 1) == 0)
2927 return Error(BitcodeError::InvalidRecord);
2984 return Error("Invalid record");
29282985 Type *OpTy = getTypeByID(Record[0]);
29292986 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
29302987 BasicBlock *Default = getBasicBlock(Record[2]);
29312988 if (!OpTy || !Cond || !Default)
2932 return Error(BitcodeError::InvalidRecord);
2989 return Error("Invalid record");
29332990 unsigned NumCases = (Record.size()-3)/2;
29342991 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
29352992 InstructionList.push_back(SI);
29392996 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
29402997 if (!CaseVal || !DestBB) {
29412998 delete SI;
2942 return Error(BitcodeError::InvalidRecord);
2999 return Error("Invalid record");
29433000 }
29443001 SI->addCase(CaseVal, DestBB);
29453002 }
29483005 }
29493006 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
29503007 if (Record.size() < 2)
2951 return Error(BitcodeError::InvalidRecord);
3008 return Error("Invalid record");
29523009 Type *OpTy = getTypeByID(Record[0]);
29533010 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
29543011 if (!OpTy || !Address)
2955 return Error(BitcodeError::InvalidRecord);
3012 return Error("Invalid record");
29563013 unsigned NumDests = Record.size()-2;
29573014 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
29583015 InstructionList.push_back(IBI);
29613018 IBI->addDestination(DestBB);
29623019 } else {
29633020 delete IBI;
2964 return Error(BitcodeError::InvalidRecord);
3021 return Error("Invalid record");
29653022 }
29663023 }
29673024 I = IBI;
29713028 case bitc::FUNC_CODE_INST_INVOKE: {
29723029 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
29733030 if (Record.size() < 4)
2974 return Error(BitcodeError::InvalidRecord);
3031 return Error("Invalid record");
29753032 AttributeSet PAL = getAttributes(Record[0]);
29763033 unsigned CCInfo = Record[1];
29773034 BasicBlock *NormalBB = getBasicBlock(Record[2]);
29803037 unsigned OpNum = 4;
29813038 Value *Callee;
29823039 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2983 return Error(BitcodeError::InvalidRecord);
3040 return Error("Invalid record");
29843041
29853042 PointerType *CalleeTy = dyn_cast(Callee->getType());
29863043 FunctionType *FTy = !CalleeTy ? nullptr :
29893046 // Check that the right number of fixed parameters are here.
29903047 if (!FTy || !NormalBB || !UnwindBB ||
29913048 Record.size() < OpNum+FTy->getNumParams())
2992 return Error(BitcodeError::InvalidRecord);
3049 return Error("Invalid record");
29933050
29943051 SmallVector Ops;
29953052 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
29963053 Ops.push_back(getValue(Record, OpNum, NextValueNo,
29973054 FTy->getParamType(i)));
29983055 if (!Ops.back())
2999 return Error(BitcodeError::InvalidRecord);
3056 return Error("Invalid record");
30003057 }
30013058
30023059 if (!FTy->isVarArg()) {
30033060 if (Record.size() != OpNum)
3004 return Error(BitcodeError::InvalidRecord);
3061 return Error("Invalid record");
30053062 } else {
30063063 // Read type/value pairs for varargs params.
30073064 while (OpNum != Record.size()) {
30083065 Value *Op;
30093066 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3010 return Error(BitcodeError::InvalidRecord);
3067 return Error("Invalid record");
30113068 Ops.push_back(Op);
30123069 }
30133070 }
30233080 unsigned Idx = 0;
30243081 Value *Val = nullptr;
30253082 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3026 return Error(BitcodeError::InvalidRecord);
3083 return Error("Invalid record");
30273084 I = ResumeInst::Create(Val);
30283085 InstructionList.push_back(I);
30293086 break;
30343091 break;
30353092 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
30363093 if (Record.size() < 1 || ((Record.size()-1)&1))
3037 return Error(BitcodeError::InvalidRecord);
3094 return Error("Invalid record");
30383095 Type *Ty = getTypeByID(Record[0]);
30393096 if (!Ty)
3040 return Error(BitcodeError::InvalidRecord);
3097 return Error("Invalid record");
30413098
30423099 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
30433100 InstructionList.push_back(PN);
30533110 V = getValue(Record, 1+i, NextValueNo, Ty);
30543111 BasicBlock *BB = getBasicBlock(Record[2+i]);
30553112 if (!V || !BB)
3056 return Error(BitcodeError::InvalidRecord);
3113 return Error("Invalid record");
30573114 PN->addIncoming(V, BB);
30583115 }
30593116 I = PN;
30643121 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
30653122 unsigned Idx = 0;
30663123 if (Record.size() < 4)
3067 return Error(BitcodeError::InvalidRecord);
3124 return Error("Invalid record");
30683125 Type *Ty = getTypeByID(Record[Idx++]);
30693126 if (!Ty)
3070 return Error(BitcodeError::InvalidRecord);
3127 return Error("Invalid record");
30713128 Value *PersFn = nullptr;
30723129 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
3073 return Error(BitcodeError::InvalidRecord);
3130 return Error("Invalid record");
30743131
30753132 bool IsCleanup = !!Record[Idx++];
30763133 unsigned NumClauses = Record[Idx++];
30833140
30843141 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
30853142 delete LP;
3086 return Error(BitcodeError::InvalidRecord);
3143 return Error("Invalid record");
30873144 }
30883145
30893146 assert((CT != LandingPadInst::Catch ||
31023159
31033160 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
31043161 if (Record.size() != 4)
3105 return Error(BitcodeError::InvalidRecord);
3162 return Error("Invalid record");
31063163 PointerType *Ty =
31073164 dyn_cast_or_null(getTypeByID(Record[0]));
31083165 Type *OpTy = getTypeByID(Record[1]);
31113168 bool InAlloca = AlignRecord & (1 << 5);
31123169 unsigned Align = AlignRecord & ((1 << 5) - 1);
31133170 if (!Ty || !Size)
3114 return Error(BitcodeError::InvalidRecord);
3171 return Error("Invalid record");
31153172 AllocaInst *AI = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
31163173 AI->setUsedWithInAlloca(InAlloca);
31173174 I = AI;
31233180 Value *Op;
31243181 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
31253182 OpNum+2 != Record.size())
3126 return Error(BitcodeError::InvalidRecord);
3183 return Error("Invalid record");
31273184
31283185 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
31293186 InstructionList.push_back(I);
31353192 Value *Op;
31363193 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
31373194 OpNum+4 != Record.size())
3138 return Error(BitcodeError::InvalidRecord);
3195 return Error("Invalid record");
31393196
31403197 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
31413198 if (Ordering == NotAtomic || Ordering == Release ||
31423199 Ordering == AcquireRelease)
3143 return Error(BitcodeError::InvalidRecord);
3200 return Error("Invalid record");
31443201 if (Ordering != NotAtomic && Record[OpNum] == 0)
3145 return Error(BitcodeError::InvalidRecord);
3202 return Error("Invalid record");
31463203 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
31473204
31483205 I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
31573214 popValue(Record, OpNum, NextValueNo,
31583215 cast(Ptr->getType())->getElementType(), Val) ||
31593216 OpNum+2 != Record.size())
3160 return Error(BitcodeError::InvalidRecord);
3217 return Error("Invalid record");
31613218
31623219 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
31633220 InstructionList.push_back(I);
31713228 popValue(Record, OpNum, NextValueNo,
31723229 cast(Ptr->getType())->getElementType(), Val) ||
31733230 OpNum+4 != Record.size())
3174 return Error(BitcodeError::InvalidRecord);
3231 return Error("Invalid record");
31753232
31763233 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
31773234 if (Ordering == NotAtomic || Ordering == Acquire ||
31783235 Ordering == AcquireRelease)
3179 return Error(BitcodeError::InvalidRecord);
3236 return Error("Invalid record");
31803237 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
31813238 if (Ordering != NotAtomic && Record[OpNum] == 0)
3182 return Error(BitcodeError::InvalidRecord);
3239 return Error("Invalid record");
31833240
31843241 I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
31853242 Ordering, SynchScope);
31973254 popValue(Record, OpNum, NextValueNo,
31983255 cast(Ptr->getType())->getElementType(), New) ||
31993256 (Record.size() < OpNum + 3 || Record.size() > OpNum + 5))
3200 return Error(BitcodeError::InvalidRecord);
3257 return Error("Invalid record");
32013258 AtomicOrdering SuccessOrdering = GetDecodedOrdering(Record[OpNum+1]);
32023259 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
3203 return Error(BitcodeError::InvalidRecord);
3260 return Error("Invalid record");
32043261 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
32053262
32063263 AtomicOrdering FailureOrdering;
32353292 popValue(Record, OpNum, NextValueNo,
32363293 cast(Ptr->getType())->getElementType(), Val) ||
32373294 OpNum+4 != Record.size())
3238 return Error(BitcodeError::InvalidRecord);
3295 return Error("Invalid record");
32393296 AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
32403297 if (Operation < AtomicRMWInst::FIRST_BINOP ||
32413298 Operation > AtomicRMWInst::LAST_BINOP)
3242 return Error(BitcodeError::InvalidRecord);
3299 return Error("Invalid record");
32433300 AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
32443301 if (Ordering == NotAtomic || Ordering == Unordered)
3245 return Error(BitcodeError::InvalidRecord);
3302 return Error("Invalid record");
32463303 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
32473304 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
32483305 cast(I)->setVolatile(Record[OpNum+1]);
32513308 }
32523309 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
32533310 if (2 != Record.size())
3254 return Error(BitcodeError::InvalidRecord);
3311 return Error("Invalid record");
32553312 AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
32563313 if (Ordering == NotAtomic || Ordering == Unordered ||
32573314 Ordering == Monotonic)
3258 return Error(BitcodeError::InvalidRecord);
3315 return Error("Invalid record");
32593316 SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
32603317 I = new FenceInst(Context, Ordering, SynchScope);
32613318 InstructionList.push_back(I);
32643321 case bitc::FUNC_CODE_INST_CALL: {
32653322 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
32663323 if (Record.size() < 3)
3267 return Error(BitcodeError::InvalidRecord);
3324 return Error("Invalid record");
32683325
32693326 AttributeSet PAL = getAttributes(Record[0]);
32703327 unsigned CCInfo = Record[1];
32723329 unsigned OpNum = 2;
32733330 Value *Callee;
32743331 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
3275 return Error(BitcodeError::InvalidRecord);
3332 return Error("Invalid record");
32763333
32773334 PointerType *OpTy = dyn_cast(Callee->getType());
32783335 FunctionType *FTy = nullptr;
32793336 if (OpTy) FTy = dyn_cast(OpTy->getElementType());
32803337 if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
3281 return Error(BitcodeError::InvalidRecord);
3338 return Error("Invalid record");
32823339
32833340 SmallVector Args;
32843341 // Read the fixed params.
32893346 Args.push_back(getValue(Record, OpNum, NextValueNo,
32903347 FTy->getParamType(i)));
32913348 if (!Args.back())
3292 return Error(BitcodeError::InvalidRecord);
3349 return Error("Invalid record");
32933350 }
32943351
32953352 // Read type/value pairs for varargs params.
32963353 if (!FTy->isVarArg()) {
32973354 if (OpNum != Record.size())
3298 return Error(BitcodeError::InvalidRecord);
3355 return Error("Invalid record");
32993356 } else {
33003357 while (OpNum != Record.size()) {
33013358 Value *Op;
33023359 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
3303 return Error(BitcodeError::InvalidRecord);
3360 return Error("Invalid record");
33043361 Args.push_back(Op);
33053362 }
33063363 }
33203377 }
33213378 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
33223379 if (Record.size() < 3)
3323 return Error(BitcodeError::InvalidRecord);
3380 return Error("Invalid record");
33243381 Type *OpTy = getTypeByID(Record[0]);
33253382 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
33263383 Type *ResTy = getTypeByID(Record[2]);
33273384 if (!OpTy || !Op || !ResTy)
3328 return Error(BitcodeError::InvalidRecord);
3385 return Error("Invalid record");
33293386 I = new VAArgInst(Op, ResTy);
33303387 InstructionList.push_back(I);
33313388 break;
33363393 // this file.
33373394 if (!CurBB) {
33383395 delete I;
3339 return Error(BitcodeError::InvalidInstructionWithNoBB);
3396 return Error("Invalid instruction with no BB");
33403397 }
33413398 CurBB->getInstList().push_back(I);
33423399
33633420 delete A;
33643421 }
33653422 }
3366 return Error(BitcodeError::NeverResolvedValueFoundInFunction);
3423 return Error("Never resolved value found in function");
33673424 }
33683425 }
33693426
33833440 DenseMap::iterator DeferredFunctionInfoIterator) {
33843441 while (DeferredFunctionInfoIterator->second == 0) {
33853442 if (Stream.AtEndOfStream())
3386 return Error(BitcodeError::CouldNotFindFunctionInStream);
3443 return Error("Could not find function in stream");
33873444 // ParseModule will parse the next body in the stream and set its
33883445 // position in the DeferredFunctionInfo map.
33893446 if (std::error_code EC = ParseModule(true))
34853542 // Check that all block address forward references got resolved (as we
34863543 // promised above).
34873544 if (!BasicBlockFwdRefs.empty())
3488 return Error(BitcodeError::NeverResolvedFunctionFromBlockAddress);
3545 return Error("Never resolved function from blockaddress");
34893546
34903547 // Upgrade any intrinsic calls that slipped through (should not happen!) and
34913548 // delete the old functions to clean up. We can't do this unless the entire
35283585 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
35293586
35303587 if (Buffer->getBufferSize() & 3)
3531 return Error(BitcodeError::InvalidBitcodeSignature);
3588 return Error("Invalid bitcode signature");
35323589
35333590 // If we have a wrapper header, parse it and ignore the non-bc file contents.
35343591 // The magic number is 0x0B17C0DE stored in little endian.
35353592 if (isBitcodeWrapper(BufPtr, BufEnd))
35363593 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
3537 return Error(BitcodeError::InvalidBitcodeWrapperHeader);
3594 return Error("Invalid bitcode wrapper header");
35383595
35393596 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
35403597 Stream.init(&*StreamFile);
35523609
35533610 unsigned char buf[16];
35543611 if (Bytes.readBytes(buf, 16, 0) != 16)
3555 return Error(BitcodeError::InvalidBitcodeSignature);
3612 return Error("Invalid bitcode signature");
35563613
35573614 if (!isBitcode(buf, buf + 16))
3558 return Error(BitcodeError::InvalidBitcodeSignature);
3615 return Error("Invalid bitcode signature");
35593616
35603617 if (isBitcodeWrapper(buf, buf + 4)) {
35613618 const unsigned char *bitcodeStart = buf;
35753632 std::string message(int IE) const override {
35763633 BitcodeError E = static_cast(IE);
35773634 switch (E) {
3578 case BitcodeError::ConflictingMETADATA_KINDRecords:
3579 return "Conflicting METADATA_KIND records";
3580 case BitcodeError::CouldNotFindFunctionInStream:
3581 return "Could not find function in stream";
3582 case BitcodeError::ExpectedConstant:
3583 return "Expected a constant";
3584 case BitcodeError::InsufficientFunctionProtos:
3585 return "Insufficient function protos";
35863635 case BitcodeError::InvalidBitcodeSignature:
35873636 return "Invalid bitcode signature";
3588 case BitcodeError::InvalidBitcodeWrapperHeader:
3589 return "Invalid bitcode wrapper header";
3590 case BitcodeError::InvalidConstantReference:
3591 return "Invalid ronstant reference";
3592 case BitcodeError::InvalidID:
3593 return "Invalid ID";
3594 case BitcodeError::InvalidInstructionWithNoBB:
3595 return "Invalid instruction with no BB";
3596 case BitcodeError::InvalidRecord:
3597 return "Invalid record";
3598 case BitcodeError::InvalidTypeForValue:
3599 return "Invalid type for value";
3600 case BitcodeError::InvalidTYPETable:
3601 return "Invalid TYPE table";
3602 case BitcodeError::InvalidType:
3603 return "Invalid type";
3604 case BitcodeError::MalformedBlock:
3605 return "Malformed block";
3606 case BitcodeError::MalformedGlobalInitializerSet:
3607 return "Malformed global initializer set";
3608 case BitcodeError::InvalidMultipleBlocks:
3609 return "Invalid multiple blocks";
3610 case BitcodeError::NeverResolvedValueFoundInFunction:
3611 return "Never resolved value found in function";
3612 case BitcodeError::NeverResolvedFunctionFromBlockAddress:
3613 return "Never resolved function from blockaddress";
3614 case BitcodeError::InvalidValue:
3615 return "Invalid value";
3637 case BitcodeError::CorruptedBitcode:
3638 return "Corrupted bitcode";
36163639 }
36173640 llvm_unreachable("Unknown error type!");
36183641 }
36393662 /// materialize everything -- in particular, if this isn't truly lazy.
36403663 static ErrorOr
36413664 getLazyBitcodeModuleImpl(std::unique_ptr &&Buffer,
3642 LLVMContext &Context, bool WillMaterializeAll) {
3665 LLVMContext &Context, bool WillMaterializeAll,
3666 DiagnosticHandlerFunction DiagnosticHandler) {
36433667 Module *M = new Module(Buffer->getBufferIdentifier(), Context);
3644 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
3668 BitcodeReader *R =
3669 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
36453670 M->setMaterializer(R);
36463671
36473672 auto cleanupOnError = [&](std::error_code EC) {
36643689
36653690 ErrorOr
36663691 llvm::getLazyBitcodeModule(std::unique_ptr &&Buffer,
3667 LLVMContext &Context) {
3668 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false);
3692 LLVMContext &Context,
3693 DiagnosticHandlerFunction DiagnosticHandler) {
3694 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
3695 DiagnosticHandler);
36693696 }
36703697
36713698 ErrorOr>
36723699 llvm::getStreamedBitcodeModule(StringRef Name, DataStreamer *Streamer,
3673 LLVMContext &Context) {
3700 LLVMContext &Context,
3701 DiagnosticHandlerFunction DiagnosticHandler) {
36743702 std::unique_ptr M = make_unique(Name, Context);
3675 BitcodeReader *R = new BitcodeReader(Streamer, Context);
3703 BitcodeReader *R = new BitcodeReader(Streamer, Context, DiagnosticHandler);
36763704 M->setMaterializer(R);
36773705 if (std::error_code EC = R->ParseBitcodeInto(M.get()))
36783706 return EC;
36793707 return std::move(M);
36803708 }
36813709
3682 ErrorOr llvm::parseBitcodeFile(MemoryBufferRef Buffer,
3683 LLVMContext &Context) {
3710 ErrorOr
3711 llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
3712 DiagnosticHandlerFunction DiagnosticHandler) {
36843713 std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3685 ErrorOr ModuleOrErr =
3686 getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
3714 ErrorOr ModuleOrErr = getLazyBitcodeModuleImpl(
3715 std::move(Buf), Context, true, DiagnosticHandler);
36873716 if (!ModuleOrErr)
36883717 return ModuleOrErr;
36893718 Module *M = ModuleOrErr.get();
36993728 return M;
37003729 }
37013730
3702 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
3703 LLVMContext &Context) {
3731 std::string
3732 llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
3733 DiagnosticHandlerFunction DiagnosticHandler) {
37043734 std::unique_ptr Buf = MemoryBuffer::getMemBuffer(Buffer, false);
3705 auto R = llvm::make_unique(Buf.release(), Context);
3735 auto R = llvm::make_unique(Buf.release(), Context,
3736 DiagnosticHandler);
37063737 ErrorOr Triple = R->parseTriple();
37073738 if (Triple.getError())
37083739 return "";
131131
132132 class BitcodeReader : public GVMaterializer {
133133 LLVMContext &Context;
134 DiagnosticHandlerFunction DiagnosticHandler;
134135 Module *TheModule;
135136 std::unique_ptr Buffer;
136137 std::unique_ptr StreamFile;
209210 SmallPtrSet BlockAddressesTaken;
210211
211212 public:
212 std::error_code Error(BitcodeError E) { return make_error_code(E); }
213
214 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
215 : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
216 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
217 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
218 WillMaterializeAllForwardRefs(false) {}
219 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
220 : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
221 NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
222 MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
223 WillMaterializeAllForwardRefs(false) {}
213 std::error_code Error(BitcodeError E, const Twine &Message);
214 std::error_code Error(BitcodeError E);
215 std::error_code Error(const Twine &Message);
216
217 explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C,
218 DiagnosticHandlerFunction DiagnosticHandler);
219 explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C,
220 DiagnosticHandlerFunction DiagnosticHandler);
224221 ~BitcodeReader() { FreeState(); }
225222
226223 std::error_code materializeForwardReferencedFunctions();
1616 #include "llvm/Bitcode/ReaderWriter.h"
1717 #include "llvm/CodeGen/Analysis.h"
1818 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DiagnosticPrinter.h"
1920 #include "llvm/IR/LLVMContext.h"
2021 #include "llvm/IR/Metadata.h"
2122 #include "llvm/IR/Module.h"
145146 return makeLTOModule(Buffer, options, errMsg, Context);
146147 }
147148
148 static ErrorOr parseBitcodeFileImpl(MemoryBufferRef Buffer,
149 LLVMContext &Context,
150 bool ShouldBeLazy) {
149 static Module *parseBitcodeFileImpl(MemoryBufferRef Buffer,
150 LLVMContext &Context, bool ShouldBeLazy,
151 std::string &ErrMsg) {
152
151153 // Find the buffer.
152154 ErrorOr MBOrErr =
153155 IRObjectFile::findBitcodeInMemBuffer(Buffer);
154 if (std::error_code EC = MBOrErr.getError())
155 return EC;
156
157 if (!ShouldBeLazy)
156 if (std::error_code EC = MBOrErr.getError()) {
157 ErrMsg = EC.message();
158 return nullptr;
159 }
160
161 std::function DiagnosticHandler =
162 [&ErrMsg](const DiagnosticInfo &DI) {
163 raw_string_ostream Stream(ErrMsg);
164 DiagnosticPrinterRawOStream DP(Stream);
165 DI.print(DP);
166 };
167
168 if (!ShouldBeLazy) {
158169 // Parse the full file.
159 return parseBitcodeFile(*MBOrErr, Context);
170 ErrorOr M =
171 parseBitcodeFile(*MBOrErr, Context, DiagnosticHandler);
172 if (!M)
173 return nullptr;
174 return *M;
175 }
160176
161177 // Parse lazily.
162178 std::unique_ptr LightweightBuf =
163179 MemoryBuffer::getMemBuffer(*MBOrErr, false);
164 return getLazyBitcodeModule(std::move(LightweightBuf), Context);
180 ErrorOr M = getLazyBitcodeModule(std::move(LightweightBuf), Context,
181 DiagnosticHandler);
182 if (!M)
183 return nullptr;
184 return *M;
165185 }
166186
167187 LTOModule *LTOModule::makeLTOModule(MemoryBufferRef Buffer,
175195
176196 // If we own a context, we know this is being used only for symbol
177197 // extraction, not linking. Be lazy in that case.
178 ErrorOr MOrErr = parseBitcodeFileImpl(
179 Buffer, *Context, /* ShouldBeLazy */ static_cast(OwnedContext));
180 if (std::error_code EC = MOrErr.getError()) {
181 errMsg = EC.message();
198 std::unique_ptr M(parseBitcodeFileImpl(
199 Buffer, *Context,
200 /* ShouldBeLazy */ static_cast(OwnedContext), errMsg));
201 if (!M)
182202 return nullptr;
183 }
184 std::unique_ptr M(MOrErr.get());
185203
186204 std::string TripleStr = M->getTargetTriple();
187205 if (TripleStr.empty())
419419 /// Functions that have replaced other functions.
420420 SmallPtrSet OverridingFunctions;
421421
422 Linker::DiagnosticHandlerFunction DiagnosticHandler;
422 DiagnosticHandlerFunction DiagnosticHandler;
423423
424424 public:
425425 ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
426 Linker::DiagnosticHandlerFunction DiagnosticHandler)
426 DiagnosticHandlerFunction DiagnosticHandler)
427427 : DstM(dstM), SrcM(srcM), TypeMap(Set),
428428 ValMaterializer(TypeMap, DstM, LazilyLinkGlobalValues),
429429 DiagnosticHandler(DiagnosticHandler) {}
0 ; RUN: not llvm-dis < %s.bc 2>&1 | FileCheck %s
11
2 ; CHECK: llvm-dis{{(\.EXE|\.exe)?}}: Invalid value
2 ; CHECK: llvm-dis{{(\.EXE|\.exe)?}}: Unknown attribute kind (48)
33
44 ; invalid.ll.bc has an invalid attribute number.
55 ; The test checks that LLVM reports the error and doesn't access freed memory
0 ; RUN: not llvm-lto %S/../Bitcode/invalid.ll.bc 2>&1 | FileCheck %s
11
22
3 ; CHECK: llvm-lto{{.*}}: error loading file '{{.*}}/../Bitcode/invalid.ll.bc': Invalid value
3 ; CHECK: llvm-lto{{.*}}: error loading file '{{.*}}/../Bitcode/invalid.ll.bc': Unknown attribute kind (48)
1818 #include "llvm/CodeGen/Analysis.h"
1919 #include "llvm/CodeGen/CommandFlags.h"
2020 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DiagnosticInfo.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
2123 #include "llvm/IR/LLVMContext.h"
2224 #include "llvm/IR/Module.h"
2325 #include "llvm/IR/Verifier.h"
268270 return false;
269271 }
270272
273 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
274 assert(DI.getSeverity() == DS_Error && "Only expecting errors");
275 const auto &BDI = cast(DI);
276 std::error_code EC = BDI.getError();
277 if (EC == BitcodeError::InvalidBitcodeSignature)
278 return;
279
280 std::string ErrStorage;
281 {
282 raw_string_ostream OS(ErrStorage);
283 DiagnosticPrinterRawOStream DP(OS);
284 DI.print(DP);
285 }
286 message(LDPL_FATAL, "LLVM gold plugin has failed to create LTO module: %s",
287 ErrStorage.c_str());
288 }
289
271290 /// Called by gold to see whether this file is one that our plugin can handle.
272291 /// We'll try to open it and register all the symbols with add_symbol if
273292 /// possible.
301320 BufferRef = Buffer->getMemBufferRef();
302321 }
303322
323 Context.setDiagnosticHandler(diagnosticHandler);
304324 ErrorOr> ObjOrErr =
305325 object::IRObjectFile::create(BufferRef, Context);
306326 std::error_code EC = ObjOrErr.getError();
307 if (EC == BitcodeError::InvalidBitcodeSignature ||
308 EC == object::object_error::invalid_file_type ||
327 if (EC == object::object_error::invalid_file_type ||
309328 EC == object::object_error::bitcode_section_not_found)
310329 return LDPS_OK;
311330
1919 #include "llvm/Bitcode/ReaderWriter.h"
2020 #include "llvm/IR/AssemblyAnnotationWriter.h"
2121 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/DiagnosticInfo.h"
23 #include "llvm/IR/DiagnosticPrinter.h"
2224 #include "llvm/IR/IntrinsicInst.h"
2325 #include "llvm/IR/Module.h"
2426 #include "llvm/IR/Type.h"
111113
112114 } // end anon namespace
113115
116 static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
117 assert(DI.getSeverity() == DS_Error && "Only expecting errors");
118
119 raw_ostream &OS = errs();
120 OS << (char *)Context << ": ";
121 DiagnosticPrinterRawOStream DP(OS);
122 DI.print(DP);
123 OS << '\n';
124 exit(1);
125 }
126
114127 int main(int argc, char **argv) {
115128 // Print a stack trace if we signal out.
116129 sys::PrintStackTraceOnErrorSignal();
119132 LLVMContext &Context = getGlobalContext();
120133 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
121134
135 Context.setDiagnosticHandler(diagnosticHandler, argv[0]);
122136
123137 cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");
124138
135149 DisplayFilename = InputFilename;
136150 ErrorOr> MOrErr =
137151 getStreamedBitcodeModule(DisplayFilename, Streamer, Context);
138 if (std::error_code EC = MOrErr.getError())
139 ErrorMessage = EC.message();
140 else
141 M = std::move(*MOrErr);
142 if(M.get()) {
143 if (std::error_code EC = M->materializeAllPermanently()) {
144 ErrorMessage = EC.message();
145 M.reset();
146 }
147 }
148 }
149
150 if (!M.get()) {
151 errs() << argv[0] << ": ";
152 if (ErrorMessage.size())
153 errs() << ErrorMessage << "\n";
154 else
155 errs() << "bitcode didn't read correctly.\n";
156 return 1;
152 M = std::move(*MOrErr);
153 M->materializeAllPermanently();
157154 }
158155
159156 // Just use stdout. We won't actually print anything on it.