[llvm] r286323 - Bitcode: Change the BitcodeReader to use llvm::Error internally.

Peter Collingbourne via llvm-commits llvm-commits at lists.llvm.org
Tue Nov 8 16:51:04 PST 2016


Author: pcc
Date: Tue Nov  8 18:51:04 2016
New Revision: 286323

URL: http://llvm.org/viewvc/llvm-project?rev=286323&view=rev
Log:
Bitcode: Change the BitcodeReader to use llvm::Error internally.

Differential Revision: https://reviews.llvm.org/D26430

Modified:
    llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp
    llvm/trunk/test/Bitcode/invalid.test

Modified: llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp?rev=286323&r1=286322&r2=286323&view=diff
==============================================================================
--- llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp (original)
+++ llvm/trunk/lib/Bitcode/Reader/BitcodeReader.cpp Tue Nov  8 18:51:04 2016
@@ -62,8 +62,8 @@
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Debug.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/ErrorHandling.h"
-#include "llvm/Support/ErrorOr.h"
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/MemoryBuffer.h"
 #include "llvm/Support/raw_ostream.h"
@@ -236,14 +236,25 @@ protected:
   BitstreamBlockInfo BlockInfo;
   BitstreamCursor Stream;
 
-  std::error_code initStream();
+  Error initStream();
   bool readBlockInfo();
 
-  virtual std::error_code error(const Twine &Message) = 0;
-  virtual ~BitcodeReaderBase() = default;
+  // Contains an arbitrary and optional string identifying the bitcode producer
+  std::string ProducerIdentification;
+
+  Error error(const Twine &Message);
 };
 
-std::error_code BitcodeReaderBase::initStream() {
+Error BitcodeReaderBase::error(const Twine &Message) {
+  std::string FullMsg = Message.str();
+  if (!ProducerIdentification.empty())
+    FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
+               LLVM_VERSION_STRING "')";
+  return make_error<StringError>(
+      FullMsg, make_error_code(BitcodeError::CorruptedBitcode));
+}
+
+Error BitcodeReaderBase::initStream() {
   const unsigned char *BufPtr = (const unsigned char*)Buffer.getBufferStart();
   const unsigned char *BufEnd = BufPtr+Buffer.getBufferSize();
 
@@ -259,7 +270,7 @@ std::error_code BitcodeReaderBase::initS
   Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, BufEnd));
   Stream.setBlockInfo(&BlockInfo);
 
-  return std::error_code();
+  return Error::success();
 }
 
 class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
@@ -271,8 +282,6 @@ class BitcodeReader : public BitcodeRead
   uint64_t LastFunctionBlockBit = 0;
   bool SeenValueSymbolTable = false;
   uint64_t VSTOffset = 0;
-  // Contains an arbitrary and optional string identifying the bitcode producer
-  std::string ProducerIdentification;
 
   std::vector<Type*> TypeList;
   BitcodeReaderValueList ValueList;
@@ -357,37 +366,36 @@ class BitcodeReader : public BitcodeRead
   std::vector<std::string> BundleTags;
 
 public:
-  std::error_code error(BitcodeError E, const Twine &Message);
-  std::error_code error(const Twine &Message) override;
-
   BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context);
 
-  std::error_code materializeForwardReferencedFunctions();
+  Error materializeForwardReferencedFunctions();
 
   std::error_code materialize(GlobalValue *GV) override;
+  Error materializeImpl(GlobalValue *GV);
   std::error_code materializeModule() override;
+  Error materializeModuleImpl();
   std::vector<StructType *> getIdentifiedStructTypes() const override;
 
   /// \brief Main interface to parsing a bitcode buffer.
   /// \returns true if an error occurred.
-  std::error_code parseBitcodeInto(Module *M,
-                                   bool ShouldLazyLoadMetadata = false);
+  Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata = false);
 
   /// \brief Cheap mechanism to just extract module triple
   /// \returns true if an error occurred.
-  ErrorOr<std::string> parseTriple();
+  Expected<std::string> parseTriple();
 
   /// Cheap mechanism to just extract the identification block out of bitcode.
-  ErrorOr<std::string> parseIdentificationBlock();
+  Expected<std::string> parseIdentificationBlock();
 
   /// Peak at the module content and return true if any ObjC category or class
   /// is found.
-  ErrorOr<bool> hasObjCCategory();
+  Expected<bool> hasObjCCategory();
 
   static uint64_t decodeSignRotatedValue(uint64_t V);
 
   /// Materialize any deferred Metadata block.
   std::error_code materializeMetadata() override;
+  Error materializeMetadataImpl();
 
   void setStripDebugInfo() override;
 
@@ -395,7 +403,7 @@ private:
   /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
   // ProducerIdentification data member, and do some basic enforcement on the
   // "epoch" encoded in the bitcode.
-  std::error_code parseBitcodeVersion();
+  Error parseBitcodeVersion();
 
   std::vector<StructType *> IdentifiedStructTypes;
   StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
@@ -493,41 +501,39 @@ private:
   /// Converts alignment exponent (i.e. power of two (or zero)) to the
   /// corresponding alignment to use. If alignment is too large, returns
   /// a corresponding error code.
-  std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
-  std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
-  std::error_code parseModule(uint64_t ResumeBit,
-                              bool ShouldLazyLoadMetadata = false);
-  std::error_code parseAttributeBlock();
-  std::error_code parseAttributeGroupBlock();
-  std::error_code parseTypeTable();
-  std::error_code parseTypeTableBody();
-  std::error_code parseOperandBundleTags();
-
-  ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
-                               unsigned NameIndex, Triple &TT);
-  std::error_code parseValueSymbolTable(uint64_t Offset = 0);
-  std::error_code parseConstants();
-  std::error_code rememberAndSkipFunctionBodies();
-  std::error_code rememberAndSkipFunctionBody();
+  Error parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
+  Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
+  Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false);
+  Error parseAttributeBlock();
+  Error parseAttributeGroupBlock();
+  Error parseTypeTable();
+  Error parseTypeTableBody();
+  Error parseOperandBundleTags();
+
+  Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
+                                unsigned NameIndex, Triple &TT);
+  Error parseValueSymbolTable(uint64_t Offset = 0);
+  Error parseConstants();
+  Error rememberAndSkipFunctionBodies();
+  Error rememberAndSkipFunctionBody();
   /// Save the positions of the Metadata blocks and skip parsing the blocks.
-  std::error_code rememberAndSkipMetadata();
-  std::error_code parseFunctionBody(Function *F);
-  std::error_code globalCleanup();
-  std::error_code resolveGlobalAndIndirectSymbolInits();
-  std::error_code parseMetadata(bool ModuleLevel = false);
-  std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
-                                       StringRef Blob,
-                                       unsigned &NextMetadataNo);
-  std::error_code parseMetadataKinds();
-  std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
-  std::error_code
-  parseGlobalObjectAttachment(GlobalObject &GO,
-                              ArrayRef<uint64_t> Record);
-  std::error_code parseMetadataAttachment(Function &F);
-  ErrorOr<std::string> parseModuleTriple();
-  ErrorOr<bool> hasObjCCategoryInModule();
-  std::error_code parseUseLists();
-  std::error_code findFunctionInStream(
+  Error rememberAndSkipMetadata();
+  Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
+  Error parseFunctionBody(Function *F);
+  Error globalCleanup();
+  Error resolveGlobalAndIndirectSymbolInits();
+  Error parseMetadata(bool ModuleLevel = false);
+  Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
+                             unsigned &NextMetadataNo);
+  Error parseMetadataKinds();
+  Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
+  Error parseGlobalObjectAttachment(GlobalObject &GO,
+                                    ArrayRef<uint64_t> Record);
+  Error parseMetadataAttachment(Function &F);
+  Expected<std::string> parseModuleTriple();
+  Expected<bool> hasObjCCategoryInModule();
+  Error parseUseLists();
+  Error findFunctionInStream(
       Function *F,
       DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
 };
@@ -535,8 +541,6 @@ private:
 /// Class to manage reading and parsing function summary index bitcode
 /// files/sections.
 class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
-  DiagnosticHandlerFunction DiagnosticHandler;
-
   /// Eventually points to the module index built during parsing.
   ModuleSummaryIndex *TheIndex = nullptr;
 
@@ -577,26 +581,23 @@ class ModuleSummaryIndexBitcodeReader :
   std::string SourceFileName;
 
 public:
-  std::error_code error(const Twine &Message);
-
   ModuleSummaryIndexBitcodeReader(
-      MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
-      bool CheckGlobalValSummaryPresenceOnly = false);
+      MemoryBufferRef Buffer, bool CheckGlobalValSummaryPresenceOnly = false);
 
   /// Check if the parser has encountered a summary section.
   bool foundGlobalValSummary() { return SeenGlobalValSummary; }
 
   /// \brief Main interface to parsing a bitcode buffer.
   /// \returns true if an error occurred.
-  std::error_code parseSummaryIndexInto(ModuleSummaryIndex *I);
+  Error parseSummaryIndexInto(ModuleSummaryIndex *I);
 
 private:
-  std::error_code parseModule();
-  std::error_code parseValueSymbolTable(
+  Error parseModule();
+  Error parseValueSymbolTable(
       uint64_t Offset,
       DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
-  std::error_code parseEntireSummary();
-  std::error_code parseModuleStringTable();
+  Error parseEntireSummary();
+  Error parseModuleStringTable();
   std::pair<GlobalValue::GUID, GlobalValue::GUID>
 
   getGUIDFromValueId(unsigned ValueId);
@@ -605,59 +606,57 @@ private:
                     bool IsOldProfileFormat, bool HasProfile);
 };
 
-} // end anonymous namespace
-
-BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
-                                             DiagnosticSeverity Severity,
-                                             const Twine &Msg)
-    : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
-
-void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
-
-static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
-                             std::error_code EC, const Twine &Message) {
-  BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
-  DiagnosticHandler(DI);
-  return EC;
+std::error_code errorToErrorCodeAndEmitErrors(LLVMContext &Ctx, Error Err) {
+  if (Err) {
+    std::error_code EC;
+    handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
+      EC = EIB.convertToErrorCode();
+      Ctx.emitError(EIB.message());
+    });
+    return EC;
+  }
+  return std::error_code();
 }
 
-static std::error_code error(LLVMContext &Context, std::error_code EC,
-                             const Twine &Message) {
-  return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
-               Message);
+std::error_code
+errorToErrorCodeAndEmitErrors(const DiagnosticHandlerFunction &DiagHandler,
+                              Error Err) {
+  if (Err) {
+    std::error_code EC;
+    handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
+      EC = EIB.convertToErrorCode();
+      DiagHandler(DiagnosticInfoInlineAsm(EIB.message()));
+    });
+    return EC;
+  }
+  return std::error_code();
 }
 
-static std::error_code error(LLVMContext &Context, const Twine &Message) {
-  return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
-               Message);
+template <typename T>
+ErrorOr<T> expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected<T> Val) {
+  if (!Val)
+    return errorToErrorCodeAndEmitErrors(Ctx, Val.takeError());
+  return std::move(*Val);
 }
 
-std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
-  if (!ProducerIdentification.empty()) {
-    return ::error(Context, make_error_code(E),
-                   Message + " (Producer: '" + ProducerIdentification +
-                       "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
-  }
-  return ::error(Context, make_error_code(E), Message);
+template <typename T>
+static ErrorOr<T>
+expectedToErrorOrAndEmitErrors(const DiagnosticHandlerFunction &DiagHandler,
+                               Expected<T> Val) {
+  if (!Val)
+    return errorToErrorCodeAndEmitErrors(DiagHandler, Val.takeError());
+  return std::move(*Val);
 }
 
-std::error_code BitcodeReader::error(const Twine &Message) {
-  if (!ProducerIdentification.empty()) {
-    return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
-                   Message + " (Producer: '" + ProducerIdentification +
-                       "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
-  }
-  return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
-                 Message);
-}
+} // end anonymous namespace
 
 BitcodeReader::BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context)
     : BitcodeReaderBase(Buffer), Context(Context), ValueList(Context),
       MetadataList(Context) {}
 
-std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
+Error BitcodeReader::materializeForwardReferencedFunctions() {
   if (WillMaterializeAllForwardRefs)
-    return std::error_code();
+    return Error::success();
 
   // Prevent recursion.
   WillMaterializeAllForwardRefs = true;
@@ -678,14 +677,14 @@ std::error_code BitcodeReader::materiali
       return error("Never resolved function from blockaddress");
 
     // Try to materialize F.
-    if (std::error_code EC = materialize(F))
-      return EC;
+    if (Error Err = materializeImpl(F))
+      return Err;
   }
   assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
 
   // Reset state.
   WillMaterializeAllForwardRefs = false;
-  return std::error_code();
+  return Error::success();
 }
 
 //===----------------------------------------------------------------------===//
@@ -1439,7 +1438,7 @@ static void decodeLLVMAttributesForBitco
                           (EncodedAttrs & 0xffff));
 }
 
-std::error_code BitcodeReader::parseAttributeBlock() {
+Error BitcodeReader::parseAttributeBlock() {
   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
     return error("Invalid record");
 
@@ -1459,7 +1458,7 @@ std::error_code BitcodeReader::parseAttr
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -1609,26 +1608,24 @@ static Attribute::AttrKind getAttrFromCo
   }
 }
 
-std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
-                                                   unsigned &Alignment) {
+Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
+                                         unsigned &Alignment) {
   // Note: Alignment in bitcode files is incremented by 1, so that zero
   // can be used for default alignment.
   if (Exponent > Value::MaxAlignmentExponent + 1)
     return error("Invalid alignment value");
   Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
-  return std::error_code();
+  return Error::success();
 }
 
-std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
-                                             Attribute::AttrKind *Kind) {
+Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
   *Kind = getAttrFromCode(Code);
   if (*Kind == Attribute::None)
-    return error(BitcodeError::CorruptedBitcode,
-                 "Unknown attribute kind (" + Twine(Code) + ")");
-  return std::error_code();
+    return error("Unknown attribute kind (" + Twine(Code) + ")");
+  return Error::success();
 }
 
-std::error_code BitcodeReader::parseAttributeGroupBlock() {
+Error BitcodeReader::parseAttributeGroupBlock() {
   if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
     return error("Invalid record");
 
@@ -1646,7 +1643,7 @@ std::error_code BitcodeReader::parseAttr
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -1668,14 +1665,14 @@ std::error_code BitcodeReader::parseAttr
       for (unsigned i = 2, e = Record.size(); i != e; ++i) {
         if (Record[i] == 0) {        // Enum attribute
           Attribute::AttrKind Kind;
-          if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
-            return EC;
+          if (Error Err = parseAttrKind(Record[++i], &Kind))
+            return Err;
 
           B.addAttribute(Kind);
         } else if (Record[i] == 1) { // Integer attribute
           Attribute::AttrKind Kind;
-          if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
-            return EC;
+          if (Error Err = parseAttrKind(Record[++i], &Kind))
+            return Err;
           if (Kind == Attribute::Alignment)
             B.addAlignmentAttr(Record[++i]);
           else if (Kind == Attribute::StackAlignment)
@@ -1716,14 +1713,14 @@ std::error_code BitcodeReader::parseAttr
   }
 }
 
-std::error_code BitcodeReader::parseTypeTable() {
+Error BitcodeReader::parseTypeTable() {
   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
     return error("Invalid record");
 
   return parseTypeTableBody();
 }
 
-std::error_code BitcodeReader::parseTypeTableBody() {
+Error BitcodeReader::parseTypeTableBody() {
   if (!TypeList.empty())
     return error("Invalid multiple blocks");
 
@@ -1743,7 +1740,7 @@ std::error_code BitcodeReader::parseType
     case BitstreamEntry::EndBlock:
       if (NumRecords != TypeList.size())
         return error("Malformed block");
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -1959,7 +1956,7 @@ std::error_code BitcodeReader::parseType
   }
 }
 
-std::error_code BitcodeReader::parseOperandBundleTags() {
+Error BitcodeReader::parseOperandBundleTags() {
   if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
     return error("Invalid record");
 
@@ -1976,7 +1973,7 @@ std::error_code BitcodeReader::parseOper
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -1996,8 +1993,8 @@ std::error_code BitcodeReader::parseOper
 }
 
 /// Associate a value with its name from the given index in the provided record.
-ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
-                                            unsigned NameIndex, Triple &TT) {
+Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
+                                             unsigned NameIndex, Triple &TT) {
   SmallString<128> ValueName;
   if (convertToString(Record, NameIndex, ValueName))
     return error("Invalid record");
@@ -2045,7 +2042,7 @@ static uint64_t jumpToValueSymbolTable(u
 
 /// Parse the value symbol table at either the current parsing location or
 /// at the given bit offset if provided.
-std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
+Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
   uint64_t CurrentBit;
   // Pass in the Offset to distinguish between calling for the module-level
   // VST (where we want to jump to the VST offset) and the function-level
@@ -2087,7 +2084,7 @@ std::error_code BitcodeReader::parseValu
     case BitstreamEntry::EndBlock:
       if (Offset > 0)
         Stream.JumpToBit(CurrentBit);
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -2099,17 +2096,17 @@ std::error_code BitcodeReader::parseValu
     default:  // Default behavior: unknown type.
       break;
     case bitc::VST_CODE_ENTRY: {  // VST_CODE_ENTRY: [valueid, namechar x N]
-      ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
-      if (std::error_code EC = ValOrErr.getError())
-        return EC;
+      Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
+      if (Error Err = ValOrErr.takeError())
+        return Err;
       ValOrErr.get();
       break;
     }
     case bitc::VST_CODE_FNENTRY: {
       // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
-      ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
-      if (std::error_code EC = ValOrErr.getError())
-        return EC;
+      Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
+      if (Error Err = ValOrErr.takeError())
+        return Err;
       Value *V = ValOrErr.get();
 
       auto *GO = dyn_cast<GlobalObject>(V);
@@ -2150,8 +2147,8 @@ std::error_code BitcodeReader::parseValu
 }
 
 /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
-std::error_code
-BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
+Error BitcodeReader::parseMetadataKindRecord(
+    SmallVectorImpl<uint64_t> &Record) {
   if (Record.size() < 2)
     return error("Invalid record");
 
@@ -2161,14 +2158,14 @@ BitcodeReader::parseMetadataKindRecord(S
   unsigned NewKind = TheModule->getMDKindID(Name.str());
   if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
     return error("Conflicting METADATA_KIND records");
-  return std::error_code();
+  return Error::success();
 }
 
 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
 
-std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
-                                                    StringRef Blob,
-                                                    unsigned &NextMetadataNo) {
+Error BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
+                                          StringRef Blob,
+                                          unsigned &NextMetadataNo) {
   // All the MDStrings in the block are emitted together in a single
   // record.  The strings are concatenated and stored in a blob along with
   // their sizes.
@@ -2199,7 +2196,7 @@ std::error_code BitcodeReader::parseMeta
     Strings = Strings.drop_front(Size);
   } while (--NumStrings);
 
-  return std::error_code();
+  return Error::success();
 }
 
 namespace {
@@ -2231,7 +2228,7 @@ void PlaceholderQueue::flush(BitcodeRead
 
 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
 /// module level metadata.
-std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
+Error BitcodeReader::parseMetadata(bool ModuleLevel) {
   assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
          "Must read all module-level metadata before function-level");
 
@@ -2298,7 +2295,7 @@ std::error_code BitcodeReader::parseMeta
 
       MetadataList.tryToResolveCycles();
       Placeholders.flush(MetadataList);
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -2870,9 +2867,8 @@ std::error_code BitcodeReader::parseMeta
       break;
     }
     case bitc::METADATA_STRINGS:
-      if (std::error_code EC =
-              parseMetadataStrings(Record, Blob, NextMetadataNo))
-        return EC;
+      if (Error Err = parseMetadataStrings(Record, Blob, NextMetadataNo))
+        return Err;
       break;
     case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
       if (Record.size() % 2 == 0)
@@ -2881,14 +2877,16 @@ std::error_code BitcodeReader::parseMeta
       if (ValueID >= ValueList.size())
         return error("Invalid record");
       if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
-        parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
+        if (Error Err = parseGlobalObjectAttachment(
+                *GO, ArrayRef<uint64_t>(Record).slice(1)))
+          return Err;
       break;
     }
     case bitc::METADATA_KIND: {
       // Support older bitcode files that had METADATA_KIND records in a
       // block with METADATA_BLOCK_ID.
-      if (std::error_code EC = parseMetadataKindRecord(Record))
-        return EC;
+      if (Error Err = parseMetadataKindRecord(Record))
+        return Err;
       break;
     }
     }
@@ -2898,7 +2896,7 @@ std::error_code BitcodeReader::parseMeta
 }
 
 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
-std::error_code BitcodeReader::parseMetadataKinds() {
+Error BitcodeReader::parseMetadataKinds() {
   if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
     return error("Invalid record");
 
@@ -2913,7 +2911,7 @@ std::error_code BitcodeReader::parseMeta
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -2926,8 +2924,8 @@ std::error_code BitcodeReader::parseMeta
     default: // Default behavior: ignore.
       break;
     case bitc::METADATA_KIND: {
-      if (std::error_code EC = parseMetadataKindRecord(Record))
-        return EC;
+      if (Error Err = parseMetadataKindRecord(Record))
+        return Err;
       break;
     }
     }
@@ -2946,7 +2944,7 @@ uint64_t BitcodeReader::decodeSignRotate
 }
 
 /// Resolve all of the initializers for global values and aliases that we can.
-std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
+Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
       IndirectSymbolInitWorklist;
@@ -3029,7 +3027,7 @@ std::error_code BitcodeReader::resolveGl
     FunctionPersonalityFnWorklist.pop_back();
   }
 
-  return std::error_code();
+  return Error::success();
 }
 
 static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
@@ -3040,7 +3038,7 @@ static APInt readWideAPInt(ArrayRef<uint
   return APInt(TypeBits, Words);
 }
 
-std::error_code BitcodeReader::parseConstants() {
+Error BitcodeReader::parseConstants() {
   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
     return error("Invalid record");
 
@@ -3064,7 +3062,7 @@ std::error_code BitcodeReader::parseCons
       // Once all the constants have been read, go through and resolve forward
       // references.
       ValueList.resolveConstantForwardRefs();
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -3504,7 +3502,7 @@ std::error_code BitcodeReader::parseCons
   }
 }
 
-std::error_code BitcodeReader::parseUseLists() {
+Error BitcodeReader::parseUseLists() {
   if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
     return error("Invalid record");
 
@@ -3519,7 +3517,7 @@ std::error_code BitcodeReader::parseUseL
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -3571,7 +3569,7 @@ std::error_code BitcodeReader::parseUseL
 
 /// When we see the block for metadata, remember where it is and then skip it.
 /// This lets us lazily deserialize the metadata.
-std::error_code BitcodeReader::rememberAndSkipMetadata() {
+Error BitcodeReader::rememberAndSkipMetadata() {
   // Save the current stream state.
   uint64_t CurBit = Stream.GetCurrentBitNo();
   DeferredMetadataInfo.push_back(CurBit);
@@ -3579,25 +3577,29 @@ std::error_code BitcodeReader::rememberA
   // Skip over the block for now.
   if (Stream.SkipBlock())
     return error("Invalid record");
-  return std::error_code();
+  return Error::success();
 }
 
 std::error_code BitcodeReader::materializeMetadata() {
+  return errorToErrorCodeAndEmitErrors(Context, materializeMetadataImpl());
+}
+
+Error BitcodeReader::materializeMetadataImpl() {
   for (uint64_t BitPos : DeferredMetadataInfo) {
     // Move the bit stream to the saved position.
     Stream.JumpToBit(BitPos);
-    if (std::error_code EC = parseMetadata(true))
-      return EC;
+    if (Error Err = parseMetadata(true))
+      return Err;
   }
   DeferredMetadataInfo.clear();
-  return std::error_code();
+  return Error::success();
 }
 
 void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
 
 /// When we see the block for a function body, remember where it is and then
 /// skip it.  This lets us lazily deserialize the functions.
-std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
+Error BitcodeReader::rememberAndSkipFunctionBody() {
   // Get the function we are talking about.
   if (FunctionsWithBodies.empty())
     return error("Insufficient function protos");
@@ -3615,12 +3617,13 @@ std::error_code BitcodeReader::rememberA
   // Skip over the function block for now.
   if (Stream.SkipBlock())
     return error("Invalid record");
-  return std::error_code();
+  return Error::success();
 }
 
-std::error_code BitcodeReader::globalCleanup() {
+Error BitcodeReader::globalCleanup() {
   // Patch the initializers for globals and aliases up.
-  resolveGlobalAndIndirectSymbolInits();
+  if (Error Err = resolveGlobalAndIndirectSymbolInits())
+    return Err;
   if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
     return error("Malformed global initializer set");
 
@@ -3645,14 +3648,14 @@ std::error_code BitcodeReader::globalCle
   std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
   std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
       IndirectSymbolInits);
-  return std::error_code();
+  return Error::success();
 }
 
 /// Support for lazy parsing of function bodies. This is required if we
 /// either have an old bitcode file without a VST forward declaration record,
 /// or if we have an anonymous function being materialized, since anonymous
 /// functions do not have a name and are therefore not in the VST.
-std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
+Error BitcodeReader::rememberAndSkipFunctionBodies() {
   Stream.JumpToBit(NextUnreadBit);
 
   if (Stream.AtEndOfStream())
@@ -3677,16 +3680,16 @@ std::error_code BitcodeReader::rememberA
       default:
         return error("Expect function block");
       case bitc::FUNCTION_BLOCK_ID:
-        if (std::error_code EC = rememberAndSkipFunctionBody())
-          return EC;
+        if (Error Err = rememberAndSkipFunctionBody())
+          return Err;
         NextUnreadBit = Stream.GetCurrentBitNo();
-        return std::error_code();
+        return Error::success();
       }
     }
   }
 }
 
-std::error_code BitcodeReader::parseBitcodeVersion() {
+Error BitcodeReader::parseBitcodeVersion() {
   if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
     return error("Invalid record");
 
@@ -3701,7 +3704,7 @@ std::error_code BitcodeReader::parseBitc
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -3738,8 +3741,8 @@ bool BitcodeReaderBase::readBlockInfo()
   return false;
 }
 
-std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
-                                           bool ShouldLazyLoadMetadata) {
+Error BitcodeReader::parseModule(uint64_t ResumeBit,
+                                 bool ShouldLazyLoadMetadata) {
   if (ResumeBit)
     Stream.JumpToBit(ResumeBit);
   else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
@@ -3770,16 +3773,16 @@ std::error_code BitcodeReader::parseModu
           return error("Malformed block");
         break;
       case bitc::PARAMATTR_BLOCK_ID:
-        if (std::error_code EC = parseAttributeBlock())
-          return EC;
+        if (Error Err = parseAttributeBlock())
+          return Err;
         break;
       case bitc::PARAMATTR_GROUP_BLOCK_ID:
-        if (std::error_code EC = parseAttributeGroupBlock())
-          return EC;
+        if (Error Err = parseAttributeGroupBlock())
+          return Err;
         break;
       case bitc::TYPE_BLOCK_ID_NEW:
-        if (std::error_code EC = parseTypeTable())
-          return EC;
+        if (Error Err = parseTypeTable())
+          return Err;
         break;
       case bitc::VALUE_SYMTAB_BLOCK_ID:
         if (!SeenValueSymbolTable) {
@@ -3789,8 +3792,8 @@ std::error_code BitcodeReader::parseModu
           // normally in the stream), or there were no function blocks to
           // trigger an earlier parsing of the VST.
           assert(VSTOffset == 0 || FunctionsWithBodies.empty());
-          if (std::error_code EC = parseValueSymbolTable())
-            return EC;
+          if (Error Err = parseValueSymbolTable())
+            return Err;
           SeenValueSymbolTable = true;
         } else {
           // We must have had a VST forward declaration record, which caused
@@ -3801,32 +3804,32 @@ std::error_code BitcodeReader::parseModu
         }
         break;
       case bitc::CONSTANTS_BLOCK_ID:
-        if (std::error_code EC = parseConstants())
-          return EC;
-        if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
-          return EC;
+        if (Error Err = parseConstants())
+          return Err;
+        if (Error Err = resolveGlobalAndIndirectSymbolInits())
+          return Err;
         break;
       case bitc::METADATA_BLOCK_ID:
         if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
-          if (std::error_code EC = rememberAndSkipMetadata())
-            return EC;
+          if (Error Err = rememberAndSkipMetadata())
+            return Err;
           break;
         }
         assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
-        if (std::error_code EC = parseMetadata(true))
-          return EC;
+        if (Error Err = parseMetadata(true))
+          return Err;
         break;
       case bitc::METADATA_KIND_BLOCK_ID:
-        if (std::error_code EC = parseMetadataKinds())
-          return EC;
+        if (Error Err = parseMetadataKinds())
+          return Err;
         break;
       case bitc::FUNCTION_BLOCK_ID:
         // If this is the first function body we've seen, reverse the
         // FunctionsWithBodies list.
         if (!SeenFirstFunctionBody) {
           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
-          if (std::error_code EC = globalCleanup())
-            return EC;
+          if (Error Err = globalCleanup())
+            return Err;
           SeenFirstFunctionBody = true;
         }
 
@@ -3835,9 +3838,8 @@ std::error_code BitcodeReader::parseModu
           // parse the VST now if we haven't already. It is needed to
           // set up the DeferredFunctionInfo vector for lazy reading.
           if (!SeenValueSymbolTable) {
-            if (std::error_code EC =
-                    BitcodeReader::parseValueSymbolTable(VSTOffset))
-              return EC;
+            if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
+              return Err;
             SeenValueSymbolTable = true;
             // Fall through so that we record the NextUnreadBit below.
             // This is necessary in case we have an anonymous function that
@@ -3860,8 +3862,8 @@ std::error_code BitcodeReader::parseModu
         // index in the VST, nor a VST forward declaration record, as
         // well as anonymous functions that do not have VST entries.
         // Build the DeferredFunctionInfo vector on the fly.
-        if (std::error_code EC = rememberAndSkipFunctionBody())
-          return EC;
+        if (Error Err = rememberAndSkipFunctionBody())
+          return Err;
 
         // Suspend parsing when we reach the function bodies. Subsequent
         // materialization calls will resume it when necessary. If the bitcode
@@ -3875,12 +3877,12 @@ std::error_code BitcodeReader::parseModu
         }
         break;
       case bitc::USELIST_BLOCK_ID:
-        if (std::error_code EC = parseUseLists())
-          return EC;
+        if (Error Err = parseUseLists())
+          return Err;
         break;
       case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
-        if (std::error_code EC = parseOperandBundleTags())
-          return EC;
+        if (Error Err = parseOperandBundleTags())
+          return Err;
         break;
       }
       continue;
@@ -3993,8 +3995,8 @@ std::error_code BitcodeReader::parseModu
       uint64_t RawLinkage = Record[3];
       GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
       unsigned Alignment;
-      if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[4], Alignment))
+        return Err;
       std::string Section;
       if (Record[5]) {
         if (Record[5]-1 >= SectionTable.size())
@@ -4079,8 +4081,8 @@ std::error_code BitcodeReader::parseModu
       Func->setAttributes(getAttributes(Record[4]));
 
       unsigned Alignment;
-      if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[5], Alignment))
+        return Err;
       Func->setAlignment(Alignment);
       if (Record[6]) {
         if (Record[6]-1 >= SectionTable.size())
@@ -4229,12 +4231,11 @@ static bool hasValidBitcodeHeader(Bitstr
   return true;
 }
 
-std::error_code BitcodeReader::parseBitcodeInto(Module *M,
-                                                bool ShouldLazyLoadMetadata) {
+Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata) {
   TheModule = M;
 
-  if (std::error_code EC = initStream())
-    return EC;
+  if (Error Err = initStream())
+    return Err;
 
   // Sniff for the signature.
   if (!hasValidBitcodeHeader(Stream))
@@ -4255,7 +4256,8 @@ std::error_code BitcodeReader::parseBitc
       return error("Malformed block");
 
     if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
-      parseBitcodeVersion();
+      if (Error Err = parseBitcodeVersion())
+        return Err;
       continue;
     }
 
@@ -4267,7 +4269,7 @@ std::error_code BitcodeReader::parseBitc
   }
 }
 
-ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
+Expected<std::string> BitcodeReader::parseModuleTriple() {
   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
     return error("Invalid record");
 
@@ -4306,9 +4308,9 @@ ErrorOr<std::string> BitcodeReader::pars
   llvm_unreachable("Exit infinite loop");
 }
 
-ErrorOr<std::string> BitcodeReader::parseTriple() {
-  if (std::error_code EC = initStream())
-    return EC;
+Expected<std::string> BitcodeReader::parseTriple() {
+  if (Error Err = initStream())
+    return std::move(Err);
 
   // Sniff for the signature.
   if (!hasValidBitcodeHeader(Stream))
@@ -4323,7 +4325,7 @@ ErrorOr<std::string> BitcodeReader::pars
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
 
     case BitstreamEntry::SubBlock:
       if (Entry.ID == bitc::MODULE_BLOCK_ID)
@@ -4341,9 +4343,9 @@ ErrorOr<std::string> BitcodeReader::pars
   }
 }
 
-ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
-  if (std::error_code EC = initStream())
-    return EC;
+Expected<std::string> BitcodeReader::parseIdentificationBlock() {
+  if (Error Err = initStream())
+    return std::move(Err);
 
   // Sniff for the signature.
   if (!hasValidBitcodeHeader(Stream))
@@ -4357,12 +4359,12 @@ ErrorOr<std::string> BitcodeReader::pars
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
 
     case BitstreamEntry::SubBlock:
       if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
-        if (std::error_code EC = parseBitcodeVersion())
-          return EC;
+        if (Error Err = parseBitcodeVersion())
+          return std::move(Err);
         return ProducerIdentification;
       }
       // Ignore other sub-blocks.
@@ -4376,8 +4378,8 @@ ErrorOr<std::string> BitcodeReader::pars
   }
 }
 
-std::error_code BitcodeReader::parseGlobalObjectAttachment(
-    GlobalObject &GO, ArrayRef<uint64_t> Record) {
+Error BitcodeReader::parseGlobalObjectAttachment(GlobalObject &GO,
+                                                 ArrayRef<uint64_t> Record) {
   assert(Record.size() % 2 == 0);
   for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
     auto K = MDKindMap.find(Record[I]);
@@ -4388,12 +4390,12 @@ std::error_code BitcodeReader::parseGlob
       return error("Invalid metadata attachment");
     GO.addMetadata(K->second, *MD);
   }
-  return std::error_code();
+  return Error::success();
 }
 
-ErrorOr<bool> BitcodeReader::hasObjCCategory() {
-  if (std::error_code EC = initStream())
-    return EC;
+Expected<bool> BitcodeReader::hasObjCCategory() {
+  if (Error Err = initStream())
+    return std::move(Err);
 
   // Sniff for the signature.
   if (!hasValidBitcodeHeader(Stream))
@@ -4408,7 +4410,7 @@ ErrorOr<bool> BitcodeReader::hasObjCCate
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
 
     case BitstreamEntry::SubBlock:
       if (Entry.ID == bitc::MODULE_BLOCK_ID)
@@ -4426,7 +4428,7 @@ ErrorOr<bool> BitcodeReader::hasObjCCate
   }
 }
 
-ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
+Expected<bool> BitcodeReader::hasObjCCategoryInModule() {
   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
     return error("Invalid record");
 
@@ -4468,7 +4470,7 @@ ErrorOr<bool> BitcodeReader::hasObjCCate
 }
 
 /// Parse metadata attachments.
-std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
+Error BitcodeReader::parseMetadataAttachment(Function &F) {
   if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
     return error("Invalid record");
 
@@ -4482,7 +4484,7 @@ std::error_code BitcodeReader::parseMeta
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -4499,8 +4501,8 @@ std::error_code BitcodeReader::parseMeta
         return error("Invalid record");
       if (RecordLength % 2 == 0) {
         // A function attachment.
-        if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
-          return EC;
+        if (Error Err = parseGlobalObjectAttachment(F, Record))
+          return Err;
         continue;
       }
 
@@ -4536,22 +4538,21 @@ std::error_code BitcodeReader::parseMeta
   }
 }
 
-static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
-  LLVMContext &Context = PtrType->getContext();
+Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
   if (!isa<PointerType>(PtrType))
-    return error(Context, "Load/Store operand is not a pointer type");
+    return error("Load/Store operand is not a pointer type");
   Type *ElemType = cast<PointerType>(PtrType)->getElementType();
 
   if (ValType && ValType != ElemType)
-    return error(Context, "Explicit load/store type does not match pointee "
-                          "type of pointer operand");
+    return error("Explicit load/store type does not match pointee "
+                 "type of pointer operand");
   if (!PointerType::isLoadableOrStorableType(ElemType))
-    return error(Context, "Cannot load/store from pointer");
-  return std::error_code();
+    return error("Cannot load/store from pointer");
+  return Error::success();
 }
 
 /// Lazily parse the specified function body block.
-std::error_code BitcodeReader::parseFunctionBody(Function *F) {
+Error BitcodeReader::parseFunctionBody(Function *F) {
   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
     return error("Invalid record");
 
@@ -4602,25 +4603,25 @@ std::error_code BitcodeReader::parseFunc
           return error("Invalid record");
         break;
       case bitc::CONSTANTS_BLOCK_ID:
-        if (std::error_code EC = parseConstants())
-          return EC;
+        if (Error Err = parseConstants())
+          return Err;
         NextValueNo = ValueList.size();
         break;
       case bitc::VALUE_SYMTAB_BLOCK_ID:
-        if (std::error_code EC = parseValueSymbolTable())
-          return EC;
+        if (Error Err = parseValueSymbolTable())
+          return Err;
         break;
       case bitc::METADATA_ATTACHMENT_ID:
-        if (std::error_code EC = parseMetadataAttachment(*F))
-          return EC;
+        if (Error Err = parseMetadataAttachment(*F))
+          return Err;
         break;
       case bitc::METADATA_BLOCK_ID:
-        if (std::error_code EC = parseMetadata())
-          return EC;
+        if (Error Err = parseMetadata())
+          return Err;
         break;
       case bitc::USELIST_BLOCK_ID:
-        if (std::error_code EC = parseUseLists())
-          return EC;
+        if (Error Err = parseUseLists())
+          return Err;
         break;
       }
       continue;
@@ -5452,9 +5453,8 @@ std::error_code BitcodeReader::parseFunc
       Type *OpTy = getTypeByID(Record[1]);
       Value *Size = getFnValueByID(Record[2], OpTy);
       unsigned Align;
-      if (std::error_code EC =
-              parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
-        return EC;
+      if (Error Err = parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
+        return Err;
       }
       if (!Ty || !Size)
         return error("Invalid record");
@@ -5475,14 +5475,14 @@ std::error_code BitcodeReader::parseFunc
       Type *Ty = nullptr;
       if (OpNum + 3 == Record.size())
         Ty = getTypeByID(Record[OpNum++]);
-      if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
-        return EC;
+      if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
+        return Err;
       if (!Ty)
         Ty = cast<PointerType>(Op->getType())->getElementType();
 
       unsigned Align;
-      if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[OpNum], Align))
+        return Err;
       I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
 
       InstructionList.push_back(I);
@@ -5499,8 +5499,8 @@ std::error_code BitcodeReader::parseFunc
       Type *Ty = nullptr;
       if (OpNum + 5 == Record.size())
         Ty = getTypeByID(Record[OpNum++]);
-      if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
-        return EC;
+      if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
+        return Err;
       if (!Ty)
         Ty = cast<PointerType>(Op->getType())->getElementType();
 
@@ -5514,8 +5514,8 @@ std::error_code BitcodeReader::parseFunc
       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
 
       unsigned Align;
-      if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[OpNum], Align))
+        return Err;
       I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
 
       InstructionList.push_back(I);
@@ -5534,12 +5534,11 @@ std::error_code BitcodeReader::parseFunc
           OpNum + 2 != Record.size())
         return error("Invalid record");
 
-      if (std::error_code EC =
-              typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
-        return EC;
+      if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
+        return Err;
       unsigned Align;
-      if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[OpNum], Align))
+        return Err;
       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
       InstructionList.push_back(I);
       break;
@@ -5559,9 +5558,8 @@ std::error_code BitcodeReader::parseFunc
           OpNum + 4 != Record.size())
         return error("Invalid record");
 
-      if (std::error_code EC =
-              typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
-        return EC;
+      if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
+        return Err;
       AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
       if (Ordering == AtomicOrdering::NotAtomic ||
           Ordering == AtomicOrdering::Acquire ||
@@ -5572,8 +5570,8 @@ std::error_code BitcodeReader::parseFunc
         return error("Invalid record");
 
       unsigned Align;
-      if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
-        return EC;
+      if (Error Err = parseAlignmentValue(Record[OpNum], Align))
+        return Err;
       I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
       InstructionList.push_back(I);
       break;
@@ -5599,9 +5597,8 @@ std::error_code BitcodeReader::parseFunc
         return error("Invalid record");
       SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
 
-      if (std::error_code EC =
-              typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
-        return EC;
+      if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
+        return Err;
       AtomicOrdering FailureOrdering;
       if (Record.size() < 7)
         FailureOrdering =
@@ -5834,11 +5831,11 @@ OutOfRecordLoop:
   ValueList.shrinkTo(ModuleValueListSize);
   MetadataList.shrinkTo(ModuleMetadataListSize);
   std::vector<BasicBlock*>().swap(FunctionBBs);
-  return std::error_code();
+  return Error::success();
 }
 
 /// Find the function body in the bitcode stream
-std::error_code BitcodeReader::findFunctionInStream(
+Error BitcodeReader::findFunctionInStream(
     Function *F,
     DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
   while (DeferredFunctionInfoIterator->second == 0) {
@@ -5849,10 +5846,10 @@ std::error_code BitcodeReader::findFunct
     assert(VSTOffset == 0 || !F->hasName());
     // Parse the next body in the stream and set its position in the
     // DeferredFunctionInfo map.
-    if (std::error_code EC = rememberAndSkipFunctionBodies())
-      return EC;
+    if (Error Err = rememberAndSkipFunctionBodies())
+      return Err;
   }
-  return std::error_code();
+  return Error::success();
 }
 
 //===----------------------------------------------------------------------===//
@@ -5860,28 +5857,32 @@ std::error_code BitcodeReader::findFunct
 //===----------------------------------------------------------------------===//
 
 std::error_code BitcodeReader::materialize(GlobalValue *GV) {
+  return errorToErrorCodeAndEmitErrors(Context, materializeImpl(GV));
+}
+
+Error BitcodeReader::materializeImpl(GlobalValue *GV) {
   Function *F = dyn_cast<Function>(GV);
   // If it's not a function or is already material, ignore the request.
   if (!F || !F->isMaterializable())
-    return std::error_code();
+    return Error::success();
 
   DenseMap<Function*, uint64_t>::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.
   if (DFII->second == 0)
-    if (std::error_code EC = findFunctionInStream(F, DFII))
-      return EC;
+    if (Error Err = findFunctionInStream(F, DFII))
+      return Err;
 
   // Materialize metadata before parsing any function bodies.
-  if (std::error_code EC = materializeMetadata())
-    return EC;
+  if (Error Err = materializeMetadataImpl())
+    return Err;
 
   // Move the bit stream to the saved position of the deferred function body.
   Stream.JumpToBit(DFII->second);
 
-  if (std::error_code EC = parseFunctionBody(F))
-    return EC;
+  if (Error Err = parseFunctionBody(F))
+    return Err;
   F->setIsMaterializable(false);
 
   if (StripDebugInfo)
@@ -5915,8 +5916,12 @@ std::error_code BitcodeReader::materiali
 }
 
 std::error_code BitcodeReader::materializeModule() {
-  if (std::error_code EC = materializeMetadata())
-    return EC;
+  return errorToErrorCodeAndEmitErrors(Context, materializeModuleImpl());
+}
+
+Error BitcodeReader::materializeModuleImpl() {
+  if (Error Err = materializeMetadataImpl())
+    return Err;
 
   // Promise to materialize all forward references.
   WillMaterializeAllForwardRefs = true;
@@ -5924,15 +5929,17 @@ std::error_code BitcodeReader::materiali
   // Iterate over the module, deserializing any functions that are still on
   // disk.
   for (Function &F : *TheModule) {
-    if (std::error_code EC = materialize(&F))
-      return EC;
+    if (Error Err = materializeImpl(&F))
+      return Err;
   }
   // At this point, if there are any function bodies, parse the rest of
   // the bits in the module past the last function block we have recorded
   // through either lazy scanning or the VST.
   if (LastFunctionBlockBit || NextUnreadBit)
-    parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
-                                                     : NextUnreadBit);
+    if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
+                                    ? LastFunctionBlockBit
+                                    : NextUnreadBit))
+      return Err;
 
   // Check that all block address forward references got resolved (as we
   // promised above).
@@ -5963,23 +5970,16 @@ std::error_code BitcodeReader::materiali
   UpgradeDebugInfo(*TheModule);
 
   UpgradeModuleFlags(*TheModule);
-  return std::error_code();
+  return Error::success();
 }
 
 std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
   return IdentifiedStructTypes;
 }
 
-std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
-  return ::error(DiagnosticHandler,
-                 make_error_code(BitcodeError::CorruptedBitcode), Message);
-}
-
 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
-    MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
-    bool CheckGlobalValSummaryPresenceOnly)
+    MemoryBufferRef Buffer, bool CheckGlobalValSummaryPresenceOnly)
     : BitcodeReaderBase(Buffer),
-      DiagnosticHandler(std::move(DiagnosticHandler)),
       CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
 
 std::pair<GlobalValue::GUID, GlobalValue::GUID>
@@ -5992,7 +5992,7 @@ ModuleSummaryIndexBitcodeReader::getGUID
 // Specialized value symbol table parser used when reading module index
 // blocks where we don't actually create global values. The parsed information
 // is saved in the bitcode reader for use when later parsing summaries.
-std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
+Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
     uint64_t Offset,
     DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
   assert(Offset > 0 && "Expected non-zero VST offset");
@@ -6016,7 +6016,7 @@ std::error_code ModuleSummaryIndexBitcod
     case BitstreamEntry::EndBlock:
       // Done parsing VST, jump back to wherever we came from.
       Stream.JumpToBit(CurrentBit);
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -6091,7 +6091,7 @@ std::error_code ModuleSummaryIndexBitcod
 // Parse just the blocks needed for building the index out of the module.
 // At the end of this routine the module Index is populated with a map
 // from global value id to GlobalValueSummary objects.
-std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
+Error ModuleSummaryIndexBitcodeReader::parseModule() {
   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
     return error("Invalid record");
 
@@ -6107,14 +6107,14 @@ std::error_code ModuleSummaryIndexBitcod
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
 
     case BitstreamEntry::SubBlock:
       if (CheckGlobalValSummaryPresenceOnly) {
         if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
           SeenGlobalValSummary = true;
           // No need to parse the rest since we found the summary.
-          return std::error_code();
+          return Error::success();
         }
         if (Stream.SkipBlock())
           return error("Invalid record");
@@ -6147,18 +6147,17 @@ std::error_code ModuleSummaryIndexBitcod
         // performing ThinLTO compiles so we don't later invoke
         // the regular LTO process on them.
         if (VSTOffset > 0) {
-          if (std::error_code EC =
-                  parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
-            return EC;
+          if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
+            return Err;
           SeenValueSymbolTable = true;
         }
         SeenGlobalValSummary = true;
-        if (std::error_code EC = parseEntireSummary())
-          return EC;
+        if (Error Err = parseEntireSummary())
+          return Err;
         break;
       case bitc::MODULE_STRTAB_BLOCK_ID:
-        if (std::error_code EC = parseModuleStringTable())
-          return EC;
+        if (Error Err = parseModuleStringTable())
+          return Err;
         break;
       }
       continue;
@@ -6244,7 +6243,7 @@ std::error_code ModuleSummaryIndexBitcod
 
 // Eagerly parse the entire summary block. This populates the GlobalValueSummary
 // objects in the index.
-std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
+Error ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
   if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
     return error("Invalid record");
   SmallVector<uint64_t, 64> Record;
@@ -6287,7 +6286,7 @@ std::error_code ModuleSummaryIndexBitcod
       // module's index if we merge into that).
       if (!Combined)
         TheIndex->removeEmptySummaryEntries();
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -6514,7 +6513,7 @@ ModuleSummaryIndexBitcodeReader::readCal
 
 // Parse the  module string table block into the Index.
 // This populates the ModulePathStringTable map in the index.
-std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
+Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
   if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
     return error("Invalid record");
 
@@ -6531,7 +6530,7 @@ std::error_code ModuleSummaryIndexBitcod
     case BitstreamEntry::Error:
       return error("Malformed block");
     case BitstreamEntry::EndBlock:
-      return std::error_code();
+      return Error::success();
     case BitstreamEntry::Record:
       // The interesting case.
       break;
@@ -6575,12 +6574,12 @@ std::error_code ModuleSummaryIndexBitcod
 }
 
 // Parse the function info index from the bitcode streamer into the given index.
-std::error_code
+Error
 ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(ModuleSummaryIndex *I) {
   TheIndex = I;
 
-  if (std::error_code EC = initStream())
-    return EC;
+  if (Error Err = initStream())
+    return Err;
 
   // Sniff for the signature.
   if (!hasValidBitcodeHeader(Stream))
@@ -6662,8 +6661,8 @@ getLazyBitcodeModuleImpl(MemoryBufferRef
   M->setMaterializer(R);
 
   // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
-  if (std::error_code EC = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata))
-    return EC;
+  if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata))
+    return errorToErrorCodeAndEmitErrors(Context, std::move(Err));
 
   if (MaterializeAll) {
     // Read in the entire module, and destroy the BitcodeReader.
@@ -6671,8 +6670,8 @@ getLazyBitcodeModuleImpl(MemoryBufferRef
       return EC;
   } else {
     // Resolve forward references from blockaddresses.
-    if (std::error_code EC = R->materializeForwardReferencedFunctions())
-      return EC;
+    if (Error Err = R->materializeForwardReferencedFunctions())
+      return errorToErrorCodeAndEmitErrors(Context, std::move(Err));
   }
   return std::move(M);
 }
@@ -6704,7 +6703,8 @@ ErrorOr<std::unique_ptr<Module>> llvm::p
 std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
                                          LLVMContext &Context) {
   BitcodeReader R(Buffer, Context);
-  ErrorOr<std::string> Triple = R.parseTriple();
+  ErrorOr<std::string> Triple =
+      expectedToErrorOrAndEmitErrors(Context, R.parseTriple());
   if (Triple.getError())
     return "";
   return Triple.get();
@@ -6713,7 +6713,8 @@ std::string llvm::getBitcodeTargetTriple
 bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
                                            LLVMContext &Context) {
   BitcodeReader R(Buffer, Context);
-  ErrorOr<bool> hasObjCCategory = R.hasObjCCategory();
+  ErrorOr<bool> hasObjCCategory =
+      expectedToErrorOrAndEmitErrors(Context, R.hasObjCCategory());
   if (hasObjCCategory.getError())
     return false;
   return hasObjCCategory.get();
@@ -6722,7 +6723,8 @@ bool llvm::isBitcodeContainingObjCCatego
 std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
                                            LLVMContext &Context) {
   BitcodeReader R(Buffer, Context);
-  ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
+  ErrorOr<std::string> ProducerString =
+      expectedToErrorOrAndEmitErrors(Context, R.parseIdentificationBlock());
   if (ProducerString.getError())
     return "";
   return ProducerString.get();
@@ -6732,11 +6734,12 @@ std::string llvm::getBitcodeProducerStri
 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
     MemoryBufferRef Buffer,
     const DiagnosticHandlerFunction &DiagnosticHandler) {
-  ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler);
+  ModuleSummaryIndexBitcodeReader R(Buffer);
 
   auto Index = llvm::make_unique<ModuleSummaryIndex>();
 
-  if (std::error_code EC = R.parseSummaryIndexInto(Index.get()))
+  if (std::error_code EC = errorToErrorCodeAndEmitErrors(
+          DiagnosticHandler, R.parseSummaryIndexInto(Index.get())))
     return EC;
 
   return std::move(Index);
@@ -6746,9 +6749,10 @@ ErrorOr<std::unique_ptr<ModuleSummaryInd
 bool llvm::hasGlobalValueSummary(
     MemoryBufferRef Buffer,
     const DiagnosticHandlerFunction &DiagnosticHandler) {
-  ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler, true);
+  ModuleSummaryIndexBitcodeReader R(Buffer, true);
 
-  if (R.parseSummaryIndexInto(nullptr))
+  if (errorToErrorCodeAndEmitErrors(DiagnosticHandler,
+                                    R.parseSummaryIndexInto(nullptr)))
     return false;
 
   return R.foundGlobalValSummary();

Modified: llvm/trunk/test/Bitcode/invalid.test
URL: http://llvm.org/viewvc/llvm-project/llvm/trunk/test/Bitcode/invalid.test?rev=286323&r1=286322&r2=286323&view=diff
==============================================================================
--- llvm/trunk/test/Bitcode/invalid.test (original)
+++ llvm/trunk/test/Bitcode/invalid.test Tue Nov  8 18:51:04 2016
@@ -209,7 +209,7 @@ ALIAS-TYPE-MISMATCH: Alias and aliasee t
 RUN: not llvm-dis -disable-output %p/Inputs/invalid-no-function-block.bc 2>&1 | \
 RUN:   FileCheck --check-prefix=NO-FUNCTION-BLOCK %s
 
-NO-FUNCTION-BLOCK: Trying to materialize functions before seeing function blocks
+NO-FUNCTION-BLOCK: Trying to materialize functions before seeing function blocks (Producer: 'LLVM3.8.0git' Reader: 'LLVM
 
 RUN: not llvm-dis -disable-output %p/Inputs/invalid-name-with-0-byte.bc 2>&1 | \
 RUN:   FileCheck --check-prefix=NAME-WITH-0 %s




More information about the llvm-commits mailing list