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