BitcodeReader.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. //===- BitcodeReader.h - Internal BitcodeReader impl ------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_LIB_BITCODE_READER_BITCODEREADER_H
  14. #define LLVM_LIB_BITCODE_READER_BITCODEREADER_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/Bitcode/BitstreamReader.h"
  17. #include "llvm/Bitcode/LLVMBitCodes.h"
  18. #include "llvm/IR/Attributes.h"
  19. #include "llvm/IR/GVMaterializer.h"
  20. #include "llvm/IR/OperandTraits.h"
  21. #include "llvm/IR/Type.h"
  22. #include "llvm/IR/ValueHandle.h"
  23. #include <deque>
  24. #include <system_error>
  25. #include <vector>
  26. namespace llvm {
  27. class Comdat;
  28. class MemoryBuffer;
  29. class LLVMContext;
  30. //===----------------------------------------------------------------------===//
  31. // BitcodeReaderValueList Class
  32. //===----------------------------------------------------------------------===//
  33. class BitcodeReaderValueList {
  34. std::vector<WeakVH> ValuePtrs;
  35. /// ResolveConstants - As we resolve forward-referenced constants, we add
  36. /// information about them to this vector. This allows us to resolve them in
  37. /// bulk instead of resolving each reference at a time. See the code in
  38. /// ResolveConstantForwardRefs for more information about this.
  39. ///
  40. /// The key of this vector is the placeholder constant, the value is the slot
  41. /// number that holds the resolved value.
  42. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  43. ResolveConstantsTy ResolveConstants;
  44. LLVMContext &Context;
  45. public:
  46. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  47. ~BitcodeReaderValueList() {
  48. assert(ResolveConstants.empty() && "Constants not resolved?");
  49. }
  50. // vector compatibility methods
  51. unsigned size() const { return ValuePtrs.size(); }
  52. void resize(unsigned N) { ValuePtrs.resize(N); }
  53. void push_back(Value *V) {
  54. ValuePtrs.push_back(V);
  55. }
  56. void clear() {
  57. assert(ResolveConstants.empty() && "Constants not resolved?");
  58. ValuePtrs.clear();
  59. }
  60. Value *operator[](unsigned i) const {
  61. assert(i < ValuePtrs.size());
  62. return ValuePtrs[i];
  63. }
  64. Value *back() const { return ValuePtrs.back(); }
  65. void pop_back() { ValuePtrs.pop_back(); }
  66. bool empty() const { return ValuePtrs.empty(); }
  67. void shrinkTo(unsigned N) {
  68. assert(N <= size() && "Invalid shrinkTo request!");
  69. ValuePtrs.resize(N);
  70. }
  71. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  72. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  73. void AssignValue(Value *V, unsigned Idx);
  74. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  75. /// resolves any forward references.
  76. void ResolveConstantForwardRefs();
  77. };
  78. //===----------------------------------------------------------------------===//
  79. // BitcodeReaderMDValueList Class
  80. //===----------------------------------------------------------------------===//
  81. class BitcodeReaderMDValueList {
  82. std::vector<WeakVH> MDValuePtrs;
  83. LLVMContext &Context;
  84. public:
  85. BitcodeReaderMDValueList(LLVMContext& C) : Context(C) {}
  86. // vector compatibility methods
  87. unsigned size() const { return MDValuePtrs.size(); }
  88. void resize(unsigned N) { MDValuePtrs.resize(N); }
  89. void push_back(Value *V) { MDValuePtrs.push_back(V); }
  90. void clear() { MDValuePtrs.clear(); }
  91. Value *back() const { return MDValuePtrs.back(); }
  92. void pop_back() { MDValuePtrs.pop_back(); }
  93. bool empty() const { return MDValuePtrs.empty(); }
  94. Value *operator[](unsigned i) const {
  95. assert(i < MDValuePtrs.size());
  96. return MDValuePtrs[i];
  97. }
  98. void shrinkTo(unsigned N) {
  99. assert(N <= size() && "Invalid shrinkTo request!");
  100. MDValuePtrs.resize(N);
  101. }
  102. Value *getValueFwdRef(unsigned Idx);
  103. void AssignValue(Value *V, unsigned Idx);
  104. };
  105. class BitcodeReader : public GVMaterializer {
  106. LLVMContext &Context;
  107. Module *TheModule;
  108. std::unique_ptr<MemoryBuffer> Buffer;
  109. std::unique_ptr<BitstreamReader> StreamFile;
  110. BitstreamCursor Stream;
  111. DataStreamer *LazyStreamer;
  112. uint64_t NextUnreadBit;
  113. bool SeenValueSymbolTable;
  114. std::vector<Type*> TypeList;
  115. BitcodeReaderValueList ValueList;
  116. BitcodeReaderMDValueList MDValueList;
  117. std::vector<Comdat *> ComdatList;
  118. SmallVector<Instruction *, 64> InstructionList;
  119. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  120. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  121. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  122. SmallVector<Instruction*, 64> InstsWithTBAATag;
  123. /// MAttributes - The set of attributes by index. Index zero in the
  124. /// file is for null, and is thus not represented here. As such all indices
  125. /// are off by one.
  126. std::vector<AttributeSet> MAttributes;
  127. /// \brief The set of attribute groups.
  128. std::map<unsigned, AttributeSet> MAttributeGroups;
  129. /// FunctionBBs - While parsing a function body, this is a list of the basic
  130. /// blocks for the function.
  131. std::vector<BasicBlock*> FunctionBBs;
  132. // When reading the module header, this list is populated with functions that
  133. // have bodies later in the file.
  134. std::vector<Function*> FunctionsWithBodies;
  135. // When intrinsic functions are encountered which require upgrading they are
  136. // stored here with their replacement function.
  137. typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
  138. UpgradedIntrinsicMap UpgradedIntrinsics;
  139. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  140. DenseMap<unsigned, unsigned> MDKindMap;
  141. // Several operations happen after the module header has been read, but
  142. // before function bodies are processed. This keeps track of whether
  143. // we've done this yet.
  144. bool SeenFirstFunctionBody;
  145. /// DeferredFunctionInfo - When function bodies are initially scanned, this
  146. /// map contains info about where to find deferred function body in the
  147. /// stream.
  148. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  149. /// These are basic blocks forward-referenced by block addresses. They are
  150. /// inserted lazily into functions when they're loaded. The basic block ID is
  151. /// its index into the vector.
  152. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  153. std::deque<Function *> BasicBlockFwdRefQueue;
  154. /// UseRelativeIDs - Indicates that we are using a new encoding for
  155. /// instruction operands where most operands in the current
  156. /// FUNCTION_BLOCK are encoded relative to the instruction number,
  157. /// for a more compact encoding. Some instruction operands are not
  158. /// relative to the instruction ID: basic block numbers, and types.
  159. /// Once the old style function blocks have been phased out, we would
  160. /// not need this flag.
  161. bool UseRelativeIDs;
  162. /// True if all functions will be materialized, negating the need to process
  163. /// (e.g.) blockaddress forward references.
  164. bool WillMaterializeAllForwardRefs;
  165. /// Functions that have block addresses taken. This is usually empty.
  166. SmallPtrSet<const Function *, 4> BlockAddressesTaken;
  167. public:
  168. std::error_code Error(BitcodeError E) { return make_error_code(E); }
  169. explicit BitcodeReader(MemoryBuffer *buffer, LLVMContext &C)
  170. : Context(C), TheModule(nullptr), Buffer(buffer), LazyStreamer(nullptr),
  171. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  172. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  173. WillMaterializeAllForwardRefs(false) {}
  174. explicit BitcodeReader(DataStreamer *streamer, LLVMContext &C)
  175. : Context(C), TheModule(nullptr), Buffer(nullptr), LazyStreamer(streamer),
  176. NextUnreadBit(0), SeenValueSymbolTable(false), ValueList(C),
  177. MDValueList(C), SeenFirstFunctionBody(false), UseRelativeIDs(false),
  178. WillMaterializeAllForwardRefs(false) {}
  179. ~BitcodeReader() { FreeState(); }
  180. std::error_code materializeForwardReferencedFunctions();
  181. void FreeState();
  182. void releaseBuffer();
  183. bool isDematerializable(const GlobalValue *GV) const override;
  184. std::error_code materialize(GlobalValue *GV) override;
  185. std::error_code MaterializeModule(Module *M) override;
  186. void Dematerialize(GlobalValue *GV) override;
  187. /// @brief Main interface to parsing a bitcode buffer.
  188. /// @returns true if an error occurred.
  189. std::error_code ParseBitcodeInto(Module *M);
  190. /// @brief Cheap mechanism to just extract module triple
  191. /// @returns true if an error occurred.
  192. ErrorOr<std::string> parseTriple();
  193. static uint64_t decodeSignRotatedValue(uint64_t V);
  194. private:
  195. Type *getTypeByID(unsigned ID);
  196. Value *getFnValueByID(unsigned ID, Type *Ty) {
  197. if (Ty && Ty->isMetadataTy())
  198. return MDValueList.getValueFwdRef(ID);
  199. return ValueList.getValueFwdRef(ID, Ty);
  200. }
  201. BasicBlock *getBasicBlock(unsigned ID) const {
  202. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  203. return FunctionBBs[ID];
  204. }
  205. AttributeSet getAttributes(unsigned i) const {
  206. if (i-1 < MAttributes.size())
  207. return MAttributes[i-1];
  208. return AttributeSet();
  209. }
  210. /// getValueTypePair - Read a value/type pair out of the specified record from
  211. /// slot 'Slot'. Increment Slot past the number of slots used in the record.
  212. /// Return true on failure.
  213. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  214. unsigned InstNum, Value *&ResVal) {
  215. if (Slot == Record.size()) return true;
  216. unsigned ValNo = (unsigned)Record[Slot++];
  217. // Adjust the ValNo, if it was encoded relative to the InstNum.
  218. if (UseRelativeIDs)
  219. ValNo = InstNum - ValNo;
  220. if (ValNo < InstNum) {
  221. // If this is not a forward reference, just return the value we already
  222. // have.
  223. ResVal = getFnValueByID(ValNo, nullptr);
  224. return ResVal == nullptr;
  225. } else if (Slot == Record.size()) {
  226. return true;
  227. }
  228. unsigned TypeNo = (unsigned)Record[Slot++];
  229. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  230. return ResVal == nullptr;
  231. }
  232. /// popValue - Read a value out of the specified record from slot 'Slot'.
  233. /// Increment Slot past the number of slots used by the value in the record.
  234. /// Return true if there is an error.
  235. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  236. unsigned InstNum, Type *Ty, Value *&ResVal) {
  237. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  238. return true;
  239. // All values currently take a single record slot.
  240. ++Slot;
  241. return false;
  242. }
  243. /// getValue -- Like popValue, but does not increment the Slot number.
  244. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  245. unsigned InstNum, Type *Ty, Value *&ResVal) {
  246. ResVal = getValue(Record, Slot, InstNum, Ty);
  247. return ResVal == nullptr;
  248. }
  249. /// getValue -- Version of getValue that returns ResVal directly,
  250. /// or 0 if there is an error.
  251. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  252. unsigned InstNum, Type *Ty) {
  253. if (Slot == Record.size()) return nullptr;
  254. unsigned ValNo = (unsigned)Record[Slot];
  255. // Adjust the ValNo, if it was encoded relative to the InstNum.
  256. if (UseRelativeIDs)
  257. ValNo = InstNum - ValNo;
  258. return getFnValueByID(ValNo, Ty);
  259. }
  260. /// getValueSigned -- Like getValue, but decodes signed VBRs.
  261. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  262. unsigned InstNum, Type *Ty) {
  263. if (Slot == Record.size()) return nullptr;
  264. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  265. // Adjust the ValNo, if it was encoded relative to the InstNum.
  266. if (UseRelativeIDs)
  267. ValNo = InstNum - ValNo;
  268. return getFnValueByID(ValNo, Ty);
  269. }
  270. std::error_code ParseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  271. std::error_code ParseModule(bool Resume);
  272. std::error_code ParseAttributeBlock();
  273. std::error_code ParseAttributeGroupBlock();
  274. std::error_code ParseTypeTable();
  275. std::error_code ParseTypeTableBody();
  276. std::error_code ParseValueSymbolTable();
  277. std::error_code ParseConstants();
  278. std::error_code RememberAndSkipFunctionBody();
  279. std::error_code ParseFunctionBody(Function *F);
  280. std::error_code GlobalCleanup();
  281. std::error_code ResolveGlobalAndAliasInits();
  282. std::error_code ParseMetadata();
  283. std::error_code ParseMetadataAttachment();
  284. ErrorOr<std::string> parseModuleTriple();
  285. std::error_code ParseUseLists();
  286. std::error_code InitStream();
  287. std::error_code InitStreamFromBuffer();
  288. std::error_code InitLazyStream();
  289. std::error_code FindFunctionInStream(
  290. Function *F,
  291. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  292. };
  293. } // End llvm namespace
  294. #endif