BitcodeReader.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 BITCODE_READER_H
  14. #define BITCODE_READER_H
  15. #include "llvm/ModuleProvider.h"
  16. #include "llvm/ParameterAttributes.h"
  17. #include "llvm/Type.h"
  18. #include "llvm/OperandTraits.h"
  19. #include "llvm/Bitcode/BitstreamReader.h"
  20. #include "llvm/Bitcode/LLVMBitCodes.h"
  21. #include "llvm/ADT/DenseMap.h"
  22. #include <vector>
  23. namespace llvm {
  24. class MemoryBuffer;
  25. //===----------------------------------------------------------------------===//
  26. // BitcodeReaderValueList Class
  27. //===----------------------------------------------------------------------===//
  28. class BitcodeReaderValueList : public User {
  29. unsigned Capacity;
  30. /// ResolveConstants - As we resolve forward-referenced constants, we add
  31. /// information about them to this vector. This allows us to resolve them in
  32. /// bulk instead of resolving each reference at a time. See the code in
  33. /// ResolveConstantForwardRefs for more information about this.
  34. ///
  35. /// The key of this vector is the placeholder constant, the value is the slot
  36. /// number that holds the resolved value.
  37. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  38. ResolveConstantsTy ResolveConstants;
  39. public:
  40. BitcodeReaderValueList() : User(Type::VoidTy, Value::ArgumentVal, 0, 0)
  41. , Capacity(0) {}
  42. ~BitcodeReaderValueList() {
  43. assert(ResolveConstants.empty() && "Constants not resolved?");
  44. }
  45. /// Provide fast operand accessors
  46. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  47. // vector compatibility methods
  48. unsigned size() const { return getNumOperands(); }
  49. void resize(unsigned);
  50. void push_back(Value *V) {
  51. unsigned OldOps(NumOperands), NewOps(NumOperands + 1);
  52. resize(NewOps);
  53. NumOperands = NewOps;
  54. OperandList[OldOps] = V;
  55. }
  56. void clear() {
  57. assert(ResolveConstants.empty() && "Constants not resolved?");
  58. if (OperandList) dropHungoffUses(OperandList);
  59. Capacity = 0;
  60. }
  61. Value *operator[](unsigned i) const { return getOperand(i); }
  62. Value *back() const { return getOperand(size() - 1); }
  63. void pop_back() { setOperand(size() - 1, 0); --NumOperands; }
  64. bool empty() const { return NumOperands == 0; }
  65. void shrinkTo(unsigned N) {
  66. assert(N <= NumOperands && "Invalid shrinkTo request!");
  67. while (NumOperands > N)
  68. pop_back();
  69. }
  70. virtual void print(std::ostream&) const {}
  71. Constant *getConstantFwdRef(unsigned Idx, const Type *Ty);
  72. Value *getValueFwdRef(unsigned Idx, const Type *Ty);
  73. void AssignValue(Value *V, unsigned Idx) {
  74. if (Idx == size()) {
  75. push_back(V);
  76. } else if (Value *OldV = getOperand(Idx)) {
  77. // Handle constants and non-constants (e.g. instrs) differently for
  78. // efficiency.
  79. if (Constant *PHC = dyn_cast<Constant>(OldV)) {
  80. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  81. setOperand(Idx, V);
  82. } else {
  83. // If there was a forward reference to this value, replace it.
  84. setOperand(Idx, V);
  85. OldV->replaceAllUsesWith(V);
  86. delete OldV;
  87. }
  88. } else {
  89. initVal(Idx, V);
  90. }
  91. }
  92. /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
  93. /// resolves any forward references.
  94. void ResolveConstantForwardRefs();
  95. private:
  96. void initVal(unsigned Idx, Value *V) {
  97. if (Idx >= size()) {
  98. // Insert a bunch of null values.
  99. resize(Idx * 2 + 1);
  100. }
  101. assert(getOperand(Idx) == 0 && "Cannot init an already init'd Use!");
  102. OperandList[Idx] = V;
  103. }
  104. };
  105. template <>
  106. struct OperandTraits<BitcodeReaderValueList>
  107. : HungoffOperandTraits</*16 FIXME*/> {
  108. };
  109. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BitcodeReaderValueList, Value)
  110. class BitcodeReader : public ModuleProvider {
  111. MemoryBuffer *Buffer;
  112. BitstreamReader Stream;
  113. const char *ErrorString;
  114. std::vector<PATypeHolder> TypeList;
  115. BitcodeReaderValueList ValueList;
  116. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  117. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  118. /// ParamAttrs - The set of parameter attributes by index. Index zero in the
  119. /// file is for null, and is thus not represented here. As such all indices
  120. /// are off by one.
  121. std::vector<PAListPtr> ParamAttrs;
  122. /// FunctionBBs - While parsing a function body, this is a list of the basic
  123. /// blocks for the function.
  124. std::vector<BasicBlock*> FunctionBBs;
  125. // When reading the module header, this list is populated with functions that
  126. // have bodies later in the file.
  127. std::vector<Function*> FunctionsWithBodies;
  128. // When intrinsic functions are encountered which require upgrading they are
  129. // stored here with their replacement function.
  130. typedef std::vector<std::pair<Function*, Function*> > UpgradedIntrinsicMap;
  131. UpgradedIntrinsicMap UpgradedIntrinsics;
  132. // After the module header has been read, the FunctionsWithBodies list is
  133. // reversed. This keeps track of whether we've done this yet.
  134. bool HasReversedFunctionsWithBodies;
  135. /// DeferredFunctionInfo - When function bodies are initially scanned, this
  136. /// map contains info about where to find deferred function body (in the
  137. /// stream) and what linkage the original function had.
  138. DenseMap<Function*, std::pair<uint64_t, unsigned> > DeferredFunctionInfo;
  139. public:
  140. explicit BitcodeReader(MemoryBuffer *buffer)
  141. : Buffer(buffer), ErrorString(0) {
  142. HasReversedFunctionsWithBodies = false;
  143. }
  144. ~BitcodeReader() {
  145. FreeState();
  146. }
  147. void FreeState();
  148. /// releaseMemoryBuffer - This causes the reader to completely forget about
  149. /// the memory buffer it contains, which prevents the buffer from being
  150. /// destroyed when it is deleted.
  151. void releaseMemoryBuffer() {
  152. Buffer = 0;
  153. }
  154. virtual bool materializeFunction(Function *F, std::string *ErrInfo = 0);
  155. virtual Module *materializeModule(std::string *ErrInfo = 0);
  156. virtual void dematerializeFunction(Function *F);
  157. virtual Module *releaseModule(std::string *ErrInfo = 0);
  158. bool Error(const char *Str) {
  159. ErrorString = Str;
  160. return true;
  161. }
  162. const char *getErrorString() const { return ErrorString; }
  163. /// @brief Main interface to parsing a bitcode buffer.
  164. /// @returns true if an error occurred.
  165. bool ParseBitcode();
  166. private:
  167. const Type *getTypeByID(unsigned ID, bool isTypeTable = false);
  168. Value *getFnValueByID(unsigned ID, const Type *Ty) {
  169. return ValueList.getValueFwdRef(ID, Ty);
  170. }
  171. BasicBlock *getBasicBlock(unsigned ID) const {
  172. if (ID >= FunctionBBs.size()) return 0; // Invalid ID
  173. return FunctionBBs[ID];
  174. }
  175. PAListPtr getParamAttrs(unsigned i) const {
  176. if (i-1 < ParamAttrs.size())
  177. return ParamAttrs[i-1];
  178. return PAListPtr();
  179. }
  180. /// getValueTypePair - Read a value/type pair out of the specified record from
  181. /// slot 'Slot'. Increment Slot past the number of slots used in the record.
  182. /// Return true on failure.
  183. bool getValueTypePair(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
  184. unsigned InstNum, Value *&ResVal) {
  185. if (Slot == Record.size()) return true;
  186. unsigned ValNo = (unsigned)Record[Slot++];
  187. if (ValNo < InstNum) {
  188. // If this is not a forward reference, just return the value we already
  189. // have.
  190. ResVal = getFnValueByID(ValNo, 0);
  191. return ResVal == 0;
  192. } else if (Slot == Record.size()) {
  193. return true;
  194. }
  195. unsigned TypeNo = (unsigned)Record[Slot++];
  196. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  197. return ResVal == 0;
  198. }
  199. bool getValue(SmallVector<uint64_t, 64> &Record, unsigned &Slot,
  200. const Type *Ty, Value *&ResVal) {
  201. if (Slot == Record.size()) return true;
  202. unsigned ValNo = (unsigned)Record[Slot++];
  203. ResVal = getFnValueByID(ValNo, Ty);
  204. return ResVal == 0;
  205. }
  206. bool ParseModule(const std::string &ModuleID);
  207. bool ParseParamAttrBlock();
  208. bool ParseTypeTable();
  209. bool ParseTypeSymbolTable();
  210. bool ParseValueSymbolTable();
  211. bool ParseConstants();
  212. bool RememberAndSkipFunctionBody();
  213. bool ParseFunctionBody(Function *F);
  214. bool ResolveGlobalAndAliasInits();
  215. };
  216. } // End llvm namespace
  217. #endif