blob: c767b6c5c17c8a28df90590277ef1222fd70ba7f [file] [log] [blame]
Chris Lattner1314b992007-04-22 06:23:29 +00001//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner1314b992007-04-22 06:23:29 +00007//
8//===----------------------------------------------------------------------===//
Chris Lattner1314b992007-04-22 06:23:29 +00009
Chris Lattner6694f602007-04-29 07:54:31 +000010#include "llvm/Bitcode/ReaderWriter.h"
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000011#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000012#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000014#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000015#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000016#include "llvm/Bitcode/LLVMBitCodes.h"
Chandler Carruth91065212014-03-05 10:34:14 +000017#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/Constants.h"
Rafael Espindola0d68b4c2015-03-30 21:36:43 +000019#include "llvm/IR/DebugInfo.h"
Duncan P. N. Exon Smithd9901ff2015-02-02 18:53:21 +000020#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DerivedTypes.h"
Rafael Espindolad0b23be2015-01-10 00:07:30 +000022#include "llvm/IR/DiagnosticPrinter.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000023#include "llvm/IR/GVMaterializer.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/InlineAsm.h"
25#include "llvm/IR/IntrinsicInst.h"
Manman Ren209b17c2013-09-28 00:22:27 +000026#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Module.h"
28#include "llvm/IR/OperandTraits.h"
29#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000030#include "llvm/IR/ValueHandle.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000031#include "llvm/Support/DataStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000032#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000033#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000034#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000035#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000036#include <deque>
Chris Lattner1314b992007-04-22 06:23:29 +000037using namespace llvm;
38
Benjamin Kramercced8be2015-03-17 20:40:24 +000039namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000040enum {
41 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
42};
43
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000044/// Indicates which operator an operand allows (for the few operands that may
45/// only reference a certain operator).
46enum OperatorConstraint {
47 OC_None = 0, // No constraint
48 OC_CatchPad, // Must be CatchPadInst
49 OC_CleanupPad // Must be CleanupPadInst
50};
51
Benjamin Kramercced8be2015-03-17 20:40:24 +000052class BitcodeReaderValueList {
53 std::vector<WeakVH> ValuePtrs;
54
Rafael Espindolacbdcb502015-06-15 20:55:37 +000055 /// As we resolve forward-referenced constants, we add information about them
56 /// to this vector. This allows us to resolve them in bulk instead of
57 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000058 /// ResolveConstantForwardRefs for more information about this.
59 ///
60 /// The key of this vector is the placeholder constant, the value is the slot
61 /// number that holds the resolved value.
62 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
63 ResolveConstantsTy ResolveConstants;
64 LLVMContext &Context;
65public:
66 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
67 ~BitcodeReaderValueList() {
68 assert(ResolveConstants.empty() && "Constants not resolved?");
69 }
70
71 // vector compatibility methods
72 unsigned size() const { return ValuePtrs.size(); }
73 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000074 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000075
76 void clear() {
77 assert(ResolveConstants.empty() && "Constants not resolved?");
78 ValuePtrs.clear();
79 }
80
81 Value *operator[](unsigned i) const {
82 assert(i < ValuePtrs.size());
83 return ValuePtrs[i];
84 }
85
86 Value *back() const { return ValuePtrs.back(); }
87 void pop_back() { ValuePtrs.pop_back(); }
88 bool empty() const { return ValuePtrs.empty(); }
89 void shrinkTo(unsigned N) {
90 assert(N <= size() && "Invalid shrinkTo request!");
91 ValuePtrs.resize(N);
92 }
93
94 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000095 Value *getValueFwdRef(unsigned Idx, Type *Ty,
96 OperatorConstraint OC = OC_None);
Benjamin Kramercced8be2015-03-17 20:40:24 +000097
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +000098 bool assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000099
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000100 /// Once all constants are read, this method bulk resolves any forward
101 /// references.
102 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000103};
104
105class BitcodeReaderMDValueList {
106 unsigned NumFwdRefs;
107 bool AnyFwdRefs;
108 unsigned MinFwdRef;
109 unsigned MaxFwdRef;
110 std::vector<TrackingMDRef> MDValuePtrs;
111
112 LLVMContext &Context;
113public:
114 BitcodeReaderMDValueList(LLVMContext &C)
115 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
116
117 // vector compatibility methods
118 unsigned size() const { return MDValuePtrs.size(); }
119 void resize(unsigned N) { MDValuePtrs.resize(N); }
120 void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
121 void clear() { MDValuePtrs.clear(); }
122 Metadata *back() const { return MDValuePtrs.back(); }
123 void pop_back() { MDValuePtrs.pop_back(); }
124 bool empty() const { return MDValuePtrs.empty(); }
125
126 Metadata *operator[](unsigned i) const {
127 assert(i < MDValuePtrs.size());
128 return MDValuePtrs[i];
129 }
130
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
133 MDValuePtrs.resize(N);
134 }
135
136 Metadata *getValueFwdRef(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000137 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000138 void tryToResolveCycles();
139};
140
141class BitcodeReader : public GVMaterializer {
142 LLVMContext &Context;
143 DiagnosticHandlerFunction DiagnosticHandler;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000144 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000145 std::unique_ptr<MemoryBuffer> Buffer;
146 std::unique_ptr<BitstreamReader> StreamFile;
147 BitstreamCursor Stream;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000148 uint64_t NextUnreadBit = 0;
149 bool SeenValueSymbolTable = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000150
151 std::vector<Type*> TypeList;
152 BitcodeReaderValueList ValueList;
153 BitcodeReaderMDValueList MDValueList;
154 std::vector<Comdat *> ComdatList;
155 SmallVector<Instruction *, 64> InstructionList;
156
157 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
158 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
159 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
160 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000161 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000162
163 SmallVector<Instruction*, 64> InstsWithTBAATag;
164
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000165 /// The set of attributes by index. Index zero in the file is for null, and
166 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000167 std::vector<AttributeSet> MAttributes;
168
Karl Schimpf36440082015-08-31 16:43:55 +0000169 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000170 std::map<unsigned, AttributeSet> MAttributeGroups;
171
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000172 /// While parsing a function body, this is a list of the basic blocks for the
173 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000174 std::vector<BasicBlock*> FunctionBBs;
175
176 // When reading the module header, this list is populated with functions that
177 // have bodies later in the file.
178 std::vector<Function*> FunctionsWithBodies;
179
180 // When intrinsic functions are encountered which require upgrading they are
181 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000182 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000183 UpgradedIntrinsicMap UpgradedIntrinsics;
184
185 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
186 DenseMap<unsigned, unsigned> MDKindMap;
187
188 // Several operations happen after the module header has been read, but
189 // before function bodies are processed. This keeps track of whether
190 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000191 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000192
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000193 /// When function bodies are initially scanned, this map contains info about
194 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000195 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
196
197 /// When Metadata block is initially scanned when parsing the module, we may
198 /// choose to defer parsing of the metadata. This vector contains info about
199 /// which Metadata blocks are deferred.
200 std::vector<uint64_t> DeferredMetadataInfo;
201
202 /// These are basic blocks forward-referenced by block addresses. They are
203 /// inserted lazily into functions when they're loaded. The basic block ID is
204 /// its index into the vector.
205 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
206 std::deque<Function *> BasicBlockFwdRefQueue;
207
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000208 /// Indicates that we are using a new encoding for instruction operands where
209 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
210 /// instruction number, for a more compact encoding. Some instruction
211 /// operands are not relative to the instruction ID: basic block numbers, and
212 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000213 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000214 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000215
216 /// True if all functions will be materialized, negating the need to process
217 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000218 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000219
220 /// Functions that have block addresses taken. This is usually empty.
221 SmallPtrSet<const Function *, 4> BlockAddressesTaken;
222
223 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000224 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000226 bool StripDebugInfo = false;
227
Benjamin Kramercced8be2015-03-17 20:40:24 +0000228public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000229 std::error_code error(BitcodeError E, const Twine &Message);
230 std::error_code error(BitcodeError E);
231 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000232
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000233 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
234 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindola1aabf982015-06-16 23:29:49 +0000235 BitcodeReader(LLVMContext &Context,
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000236 DiagnosticHandlerFunction DiagnosticHandler);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000237 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000238
239 std::error_code materializeForwardReferencedFunctions();
240
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000241 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000242
243 void releaseBuffer();
244
245 bool isDematerializable(const GlobalValue *GV) const override;
246 std::error_code materialize(GlobalValue *GV) override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000247 std::error_code materializeModule(Module *M) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000248 std::vector<StructType *> getIdentifiedStructTypes() const override;
Eric Christopher97cb5652015-05-15 18:20:14 +0000249 void dematerialize(GlobalValue *GV) override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000250
Rafael Espindola6ace6852015-06-15 21:02:49 +0000251 /// \brief Main interface to parsing a bitcode buffer.
252 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000253 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
254 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000255 bool ShouldLazyLoadMetadata = false);
256
Rafael Espindola6ace6852015-06-15 21:02:49 +0000257 /// \brief Cheap mechanism to just extract module triple
258 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000259 ErrorOr<std::string> parseTriple();
260
261 static uint64_t decodeSignRotatedValue(uint64_t V);
262
263 /// Materialize any deferred Metadata block.
264 std::error_code materializeMetadata() override;
265
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000266 void setStripDebugInfo() override;
267
Benjamin Kramercced8be2015-03-17 20:40:24 +0000268private:
269 std::vector<StructType *> IdentifiedStructTypes;
270 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
271 StructType *createIdentifiedStructType(LLVMContext &Context);
272
273 Type *getTypeByID(unsigned ID);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000274 Value *getFnValueByID(unsigned ID, Type *Ty,
275 OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000276 if (Ty && Ty->isMetadataTy())
277 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000278 return ValueList.getValueFwdRef(ID, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000279 }
280 Metadata *getFnMetadataByID(unsigned ID) {
281 return MDValueList.getValueFwdRef(ID);
282 }
283 BasicBlock *getBasicBlock(unsigned ID) const {
284 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
285 return FunctionBBs[ID];
286 }
287 AttributeSet getAttributes(unsigned i) const {
288 if (i-1 < MAttributes.size())
289 return MAttributes[i-1];
290 return AttributeSet();
291 }
292
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000293 /// Read a value/type pair out of the specified record from slot 'Slot'.
294 /// Increment Slot past the number of slots used in the record. Return true on
295 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000296 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
297 unsigned InstNum, Value *&ResVal) {
298 if (Slot == Record.size()) return true;
299 unsigned ValNo = (unsigned)Record[Slot++];
300 // Adjust the ValNo, if it was encoded relative to the InstNum.
301 if (UseRelativeIDs)
302 ValNo = InstNum - ValNo;
303 if (ValNo < InstNum) {
304 // If this is not a forward reference, just return the value we already
305 // have.
306 ResVal = getFnValueByID(ValNo, nullptr);
307 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000308 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000309 if (Slot == Record.size())
310 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000311
312 unsigned TypeNo = (unsigned)Record[Slot++];
313 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
314 return ResVal == nullptr;
315 }
316
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000317 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
318 /// past the number of slots used by the value in the record. Return true if
319 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000320 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000321 unsigned InstNum, Type *Ty, Value *&ResVal,
322 OperatorConstraint OC = OC_None) {
323 if (getValue(Record, Slot, InstNum, Ty, ResVal, OC))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000324 return true;
325 // All values currently take a single record slot.
326 ++Slot;
327 return false;
328 }
329
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000330 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000331 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000332 unsigned InstNum, Type *Ty, Value *&ResVal,
333 OperatorConstraint OC = OC_None) {
334 ResVal = getValue(Record, Slot, InstNum, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000335 return ResVal == nullptr;
336 }
337
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000338 /// Version of getValue that returns ResVal directly, or 0 if there is an
339 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000340 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000341 unsigned InstNum, Type *Ty, OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000342 if (Slot == Record.size()) return nullptr;
343 unsigned ValNo = (unsigned)Record[Slot];
344 // Adjust the ValNo, if it was encoded relative to the InstNum.
345 if (UseRelativeIDs)
346 ValNo = InstNum - ValNo;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000347 return getFnValueByID(ValNo, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000348 }
349
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000350 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000351 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000352 unsigned InstNum, Type *Ty,
353 OperatorConstraint OC = OC_None) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000354 if (Slot == Record.size()) return nullptr;
355 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
356 // Adjust the ValNo, if it was encoded relative to the InstNum.
357 if (UseRelativeIDs)
358 ValNo = InstNum - ValNo;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000359 return getFnValueByID(ValNo, Ty, OC);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000360 }
361
362 /// Converts alignment exponent (i.e. power of two (or zero)) to the
363 /// corresponding alignment to use. If alignment is too large, returns
364 /// a corresponding error code.
365 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000366 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
367 std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
368 std::error_code parseAttributeBlock();
369 std::error_code parseAttributeGroupBlock();
370 std::error_code parseTypeTable();
371 std::error_code parseTypeTableBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000372
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000373 std::error_code parseValueSymbolTable();
374 std::error_code parseConstants();
375 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000376 /// Save the positions of the Metadata blocks and skip parsing the blocks.
377 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000378 std::error_code parseFunctionBody(Function *F);
379 std::error_code globalCleanup();
380 std::error_code resolveGlobalAndAliasInits();
381 std::error_code parseMetadata();
382 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000383 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000384 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000385 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000386 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000387 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000388 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000389 Function *F,
390 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
391};
392} // namespace
393
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000394BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
395 DiagnosticSeverity Severity,
396 const Twine &Msg)
397 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
398
399void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
400
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000401static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000402 std::error_code EC, const Twine &Message) {
403 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
404 DiagnosticHandler(DI);
405 return EC;
406}
407
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000408static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000409 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000410 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000411}
412
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000413static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000414 const Twine &Message) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000415 return error(DiagnosticHandler,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000416 make_error_code(BitcodeError::CorruptedBitcode), Message);
417}
418
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000419std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
420 return ::error(DiagnosticHandler, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000421}
422
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000423std::error_code BitcodeReader::error(const Twine &Message) {
424 return ::error(DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000425 make_error_code(BitcodeError::CorruptedBitcode), Message);
426}
427
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000428std::error_code BitcodeReader::error(BitcodeError E) {
429 return ::error(DiagnosticHandler, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000430}
431
432static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
433 LLVMContext &C) {
434 if (F)
435 return F;
436 return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
437}
438
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000439BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000440 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000441 : Context(Context),
442 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000443 Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000444
Rafael Espindola1aabf982015-06-16 23:29:49 +0000445BitcodeReader::BitcodeReader(LLVMContext &Context,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000446 DiagnosticHandlerFunction DiagnosticHandler)
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000447 : Context(Context),
448 DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
Rafael Espindola1c863ca2015-06-22 18:06:15 +0000449 Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000450
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000451std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
452 if (WillMaterializeAllForwardRefs)
453 return std::error_code();
454
455 // Prevent recursion.
456 WillMaterializeAllForwardRefs = true;
457
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000458 while (!BasicBlockFwdRefQueue.empty()) {
459 Function *F = BasicBlockFwdRefQueue.front();
460 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000461 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000462 if (!BasicBlockFwdRefs.count(F))
463 // Already materialized.
464 continue;
465
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000466 // Check for a function that isn't materializable to prevent an infinite
467 // loop. When parsing a blockaddress stored in a global variable, there
468 // isn't a trivial way to check if a function will have a body without a
469 // linear search through FunctionsWithBodies, so just check it here.
470 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000471 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000472
473 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000474 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000475 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000476 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000477 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000478
479 // Reset state.
480 WillMaterializeAllForwardRefs = false;
481 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000482}
483
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000484void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000485 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000486 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000487 ValueList.clear();
Devang Patel05eb6172009-08-04 06:00:18 +0000488 MDValueList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000489 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000490
Bill Wendlinge94d8432012-12-07 23:16:57 +0000491 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000492 std::vector<BasicBlock*>().swap(FunctionBBs);
493 std::vector<Function*>().swap(FunctionsWithBodies);
494 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000495 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000496 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000497
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000498 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000499 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000500}
501
Chris Lattnerfee5a372007-05-04 03:30:17 +0000502//===----------------------------------------------------------------------===//
503// Helper functions to implement forward reference resolution, etc.
504//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000505
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000506/// Convert a string from a record into an std::string, return true on failure.
507template <typename StrTy>
508static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000509 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000510 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000511 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000512
Chris Lattnere14cb882007-05-04 19:11:41 +0000513 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
514 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000515 return false;
516}
517
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000518static bool hasImplicitComdat(size_t Val) {
519 switch (Val) {
520 default:
521 return false;
522 case 1: // Old WeakAnyLinkage
523 case 4: // Old LinkOnceAnyLinkage
524 case 10: // Old WeakODRLinkage
525 case 11: // Old LinkOnceODRLinkage
526 return true;
527 }
528}
529
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000530static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000531 switch (Val) {
532 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000533 case 0:
534 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000535 case 2:
536 return GlobalValue::AppendingLinkage;
537 case 3:
538 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000539 case 5:
540 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
541 case 6:
542 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
543 case 7:
544 return GlobalValue::ExternalWeakLinkage;
545 case 8:
546 return GlobalValue::CommonLinkage;
547 case 9:
548 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000549 case 12:
550 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000551 case 13:
552 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
553 case 14:
554 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000555 case 15:
556 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000557 case 1: // Old value with implicit comdat.
558 case 16:
559 return GlobalValue::WeakAnyLinkage;
560 case 10: // Old value with implicit comdat.
561 case 17:
562 return GlobalValue::WeakODRLinkage;
563 case 4: // Old value with implicit comdat.
564 case 18:
565 return GlobalValue::LinkOnceAnyLinkage;
566 case 11: // Old value with implicit comdat.
567 case 19:
568 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000569 }
570}
571
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000572static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000573 switch (Val) {
574 default: // Map unknown visibilities to default.
575 case 0: return GlobalValue::DefaultVisibility;
576 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000577 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000578 }
579}
580
Nico Rieck7157bb72014-01-14 15:22:47 +0000581static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000582getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000583 switch (Val) {
584 default: // Map unknown values to default.
585 case 0: return GlobalValue::DefaultStorageClass;
586 case 1: return GlobalValue::DLLImportStorageClass;
587 case 2: return GlobalValue::DLLExportStorageClass;
588 }
589}
590
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000591static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000592 switch (Val) {
593 case 0: return GlobalVariable::NotThreadLocal;
594 default: // Map unknown non-zero value to general dynamic.
595 case 1: return GlobalVariable::GeneralDynamicTLSModel;
596 case 2: return GlobalVariable::LocalDynamicTLSModel;
597 case 3: return GlobalVariable::InitialExecTLSModel;
598 case 4: return GlobalVariable::LocalExecTLSModel;
599 }
600}
601
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000602static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000603 switch (Val) {
604 default: return -1;
605 case bitc::CAST_TRUNC : return Instruction::Trunc;
606 case bitc::CAST_ZEXT : return Instruction::ZExt;
607 case bitc::CAST_SEXT : return Instruction::SExt;
608 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
609 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
610 case bitc::CAST_UITOFP : return Instruction::UIToFP;
611 case bitc::CAST_SITOFP : return Instruction::SIToFP;
612 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
613 case bitc::CAST_FPEXT : return Instruction::FPExt;
614 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
615 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
616 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000617 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000618 }
619}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000620
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000621static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000622 bool IsFP = Ty->isFPOrFPVectorTy();
623 // BinOps are only valid for int/fp or vector of int/fp types
624 if (!IsFP && !Ty->isIntOrIntVectorTy())
625 return -1;
626
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000627 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000628 default:
629 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000630 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000631 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000632 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000633 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000634 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000635 return IsFP ? Instruction::FMul : Instruction::Mul;
636 case bitc::BINOP_UDIV:
637 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000638 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000639 return IsFP ? Instruction::FDiv : Instruction::SDiv;
640 case bitc::BINOP_UREM:
641 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000642 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000643 return IsFP ? Instruction::FRem : Instruction::SRem;
644 case bitc::BINOP_SHL:
645 return IsFP ? -1 : Instruction::Shl;
646 case bitc::BINOP_LSHR:
647 return IsFP ? -1 : Instruction::LShr;
648 case bitc::BINOP_ASHR:
649 return IsFP ? -1 : Instruction::AShr;
650 case bitc::BINOP_AND:
651 return IsFP ? -1 : Instruction::And;
652 case bitc::BINOP_OR:
653 return IsFP ? -1 : Instruction::Or;
654 case bitc::BINOP_XOR:
655 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000656 }
657}
658
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000659static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000660 switch (Val) {
661 default: return AtomicRMWInst::BAD_BINOP;
662 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
663 case bitc::RMW_ADD: return AtomicRMWInst::Add;
664 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
665 case bitc::RMW_AND: return AtomicRMWInst::And;
666 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
667 case bitc::RMW_OR: return AtomicRMWInst::Or;
668 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
669 case bitc::RMW_MAX: return AtomicRMWInst::Max;
670 case bitc::RMW_MIN: return AtomicRMWInst::Min;
671 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
672 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
673 }
674}
675
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000676static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000677 switch (Val) {
678 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
679 case bitc::ORDERING_UNORDERED: return Unordered;
680 case bitc::ORDERING_MONOTONIC: return Monotonic;
681 case bitc::ORDERING_ACQUIRE: return Acquire;
682 case bitc::ORDERING_RELEASE: return Release;
683 case bitc::ORDERING_ACQREL: return AcquireRelease;
684 default: // Map unknown orderings to sequentially-consistent.
685 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
686 }
687}
688
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000689static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000690 switch (Val) {
691 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
692 default: // Map unknown scopes to cross-thread.
693 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
694 }
695}
696
David Majnemerdad0a642014-06-27 18:19:56 +0000697static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
698 switch (Val) {
699 default: // Map unknown selection kinds to any.
700 case bitc::COMDAT_SELECTION_KIND_ANY:
701 return Comdat::Any;
702 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
703 return Comdat::ExactMatch;
704 case bitc::COMDAT_SELECTION_KIND_LARGEST:
705 return Comdat::Largest;
706 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
707 return Comdat::NoDuplicates;
708 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
709 return Comdat::SameSize;
710 }
711}
712
James Molloy88eb5352015-07-10 12:52:00 +0000713static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
714 FastMathFlags FMF;
715 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
716 FMF.setUnsafeAlgebra();
717 if (0 != (Val & FastMathFlags::NoNaNs))
718 FMF.setNoNaNs();
719 if (0 != (Val & FastMathFlags::NoInfs))
720 FMF.setNoInfs();
721 if (0 != (Val & FastMathFlags::NoSignedZeros))
722 FMF.setNoSignedZeros();
723 if (0 != (Val & FastMathFlags::AllowReciprocal))
724 FMF.setAllowReciprocal();
725 return FMF;
726}
727
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000728static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000729 switch (Val) {
730 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
731 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
732 }
733}
734
Gabor Greiff6caff662008-05-10 08:32:32 +0000735namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000736namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000737/// \brief A class for maintaining the slot number definition
738/// as a placeholder for the actual definition for forward constants defs.
739class ConstantPlaceHolder : public ConstantExpr {
740 void operator=(const ConstantPlaceHolder &) = delete;
741
742public:
743 // allocate space for exactly one operand
744 void *operator new(size_t s) { return User::operator new(s, 1); }
745 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000746 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000747 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
748 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000749
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000750 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
751 static bool classof(const Value *V) {
752 return isa<ConstantExpr>(V) &&
753 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
754 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000755
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000756 /// Provide fast operand accessors
757 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
758};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000759}
Chris Lattner1663cca2007-04-24 05:48:56 +0000760
Chris Lattner2d8cd802009-03-31 22:55:09 +0000761// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000762template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000763struct OperandTraits<ConstantPlaceHolder> :
764 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000765};
Richard Trieue3d126c2014-11-21 02:42:08 +0000766DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000767}
Gabor Greiff6caff662008-05-10 08:32:32 +0000768
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000769bool BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000770 if (Idx == size()) {
771 push_back(V);
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000772 return false;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000773 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000774
Chris Lattner2d8cd802009-03-31 22:55:09 +0000775 if (Idx >= size())
776 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000777
Chris Lattner2d8cd802009-03-31 22:55:09 +0000778 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000779 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000780 OldV = V;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000781 return false;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000782 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000783
Chris Lattner2d8cd802009-03-31 22:55:09 +0000784 // Handle constants and non-constants (e.g. instrs) differently for
785 // efficiency.
786 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
787 ResolveConstants.push_back(std::make_pair(PHC, Idx));
788 OldV = V;
789 } else {
790 // If there was a forward reference to this value, replace it.
791 Value *PrevVal = OldV;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000792 // Check operator constraints. We only put cleanuppads or catchpads in
793 // the forward value map if the value is constrained to match.
794 if (CatchPadInst *CatchPad = dyn_cast<CatchPadInst>(PrevVal)) {
795 if (!isa<CatchPadInst>(V))
796 return true;
797 // Delete the dummy basic block that was created with the sentinel
798 // catchpad.
799 BasicBlock *DummyBlock = CatchPad->getUnwindDest();
800 assert(DummyBlock == CatchPad->getNormalDest());
801 CatchPad->dropAllReferences();
802 delete DummyBlock;
803 } else if (isa<CleanupPadInst>(PrevVal)) {
804 if (!isa<CleanupPadInst>(V))
805 return true;
806 }
Chris Lattner2d8cd802009-03-31 22:55:09 +0000807 OldV->replaceAllUsesWith(V);
808 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000809 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000810
811 return false;
Gabor Greiff6caff662008-05-10 08:32:32 +0000812}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000813
Gabor Greiff6caff662008-05-10 08:32:32 +0000814
Chris Lattner1663cca2007-04-24 05:48:56 +0000815Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000816 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000817 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000818 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000819
Chris Lattner2d8cd802009-03-31 22:55:09 +0000820 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000821 if (Ty != V->getType())
822 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000823 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000824 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000825
826 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000827 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000828 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000829 return C;
830}
831
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000832Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty,
833 OperatorConstraint OC) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000834 // Bail out for a clearly invalid value. This would make us call resize(0)
835 if (Idx == UINT_MAX)
836 return nullptr;
837
Chris Lattner2d8cd802009-03-31 22:55:09 +0000838 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000839 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000840
Chris Lattner2d8cd802009-03-31 22:55:09 +0000841 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000842 // If the types don't match, it's invalid.
843 if (Ty && Ty != V->getType())
844 return nullptr;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000845 if (!OC)
846 return V;
847 // Use dyn_cast to enforce operator constraints
848 switch (OC) {
849 case OC_CatchPad:
850 return dyn_cast<CatchPadInst>(V);
851 case OC_CleanupPad:
852 return dyn_cast<CleanupPadInst>(V);
853 default:
854 llvm_unreachable("Unexpected operator constraint");
855 }
Chris Lattner83930552007-05-01 07:01:57 +0000856 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000857
Chris Lattner1fc27f02007-05-02 05:16:49 +0000858 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000859 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000860
Chris Lattner83930552007-05-01 07:01:57 +0000861 // Create and return a placeholder, which will later be RAUW'd.
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +0000862 Value *V;
863 switch (OC) {
864 case OC_None:
865 V = new Argument(Ty);
866 break;
867 case OC_CatchPad: {
868 BasicBlock *BB = BasicBlock::Create(Context);
869 V = CatchPadInst::Create(BB, BB, {});
870 break;
871 }
872 default:
873 assert(OC == OC_CleanupPad && "unexpected operator constraint");
874 V = CleanupPadInst::Create(Context, {});
875 break;
876 }
877
Chris Lattner2d8cd802009-03-31 22:55:09 +0000878 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000879 return V;
880}
881
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000882/// Once all constants are read, this method bulk resolves any forward
883/// references. The idea behind this is that we sometimes get constants (such
884/// as large arrays) which reference *many* forward ref constants. Replacing
885/// each of these causes a lot of thrashing when building/reuniquing the
886/// constant. Instead of doing this, we look at all the uses and rewrite all
887/// the place holders at once for any constant that uses a placeholder.
888void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000889 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000890 // binary search.
891 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000892
Chris Lattner74429932008-08-21 02:34:16 +0000893 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000894
Chris Lattner74429932008-08-21 02:34:16 +0000895 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000896 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000897 Constant *Placeholder = ResolveConstants.back().first;
898 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000899
Chris Lattner74429932008-08-21 02:34:16 +0000900 // Loop over all users of the placeholder, updating them to reference the
901 // new value. If they reference more than one placeholder, update them all
902 // at once.
903 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000904 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000905 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000906
Chris Lattner74429932008-08-21 02:34:16 +0000907 // If the using object isn't uniqued, just update the operands. This
908 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000909 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000910 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000911 continue;
912 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000913
Chris Lattner74429932008-08-21 02:34:16 +0000914 // Otherwise, we have a constant that uses the placeholder. Replace that
915 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000916 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000917 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
918 I != E; ++I) {
919 Value *NewOp;
920 if (!isa<ConstantPlaceHolder>(*I)) {
921 // Not a placeholder reference.
922 NewOp = *I;
923 } else if (*I == Placeholder) {
924 // Common case is that it just references this one placeholder.
925 NewOp = RealVal;
926 } else {
927 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000928 ResolveConstantsTy::iterator It =
929 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +0000930 std::pair<Constant*, unsigned>(cast<Constant>(*I),
931 0));
932 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000933 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +0000934 }
935
936 NewOps.push_back(cast<Constant>(NewOp));
937 }
938
939 // Make the new constant.
940 Constant *NewC;
941 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +0000942 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000943 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +0000944 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000945 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +0000946 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000947 } else {
948 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +0000949 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +0000950 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000951
Chris Lattner74429932008-08-21 02:34:16 +0000952 UserC->replaceAllUsesWith(NewC);
953 UserC->destroyConstant();
954 NewOps.clear();
955 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000956
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +0000957 // Update all ValueHandles, they should be the only users at this point.
958 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000959 delete Placeholder;
960 }
961}
962
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000963void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000964 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000965 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000966 return;
967 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000968
Devang Patel05eb6172009-08-04 06:00:18 +0000969 if (Idx >= size())
970 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000971
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000972 TrackingMDRef &OldMD = MDValuePtrs[Idx];
973 if (!OldMD) {
974 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +0000975 return;
976 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000977
Devang Patel05eb6172009-08-04 06:00:18 +0000978 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +0000979 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000980 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000981 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +0000982}
983
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000984Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +0000985 if (Idx >= size())
986 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000987
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000988 if (Metadata *MD = MDValuePtrs[Idx])
989 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000990
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +0000991 // Track forward refs to be resolved later.
992 if (AnyFwdRefs) {
993 MinFwdRef = std::min(MinFwdRef, Idx);
994 MaxFwdRef = std::max(MaxFwdRef, Idx);
995 } else {
996 AnyFwdRefs = true;
997 MinFwdRef = MaxFwdRef = Idx;
998 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000999 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001000
1001 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001002 Metadata *MD = MDNode::getTemporary(Context, None).release();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001003 MDValuePtrs[Idx].reset(MD);
1004 return MD;
1005}
1006
1007void BitcodeReaderMDValueList::tryToResolveCycles() {
1008 if (!AnyFwdRefs)
1009 // Nothing to do.
1010 return;
1011
1012 if (NumFwdRefs)
1013 // Still forward references... can't resolve cycles.
1014 return;
1015
1016 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001017 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
1018 auto &MD = MDValuePtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001019 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001020 if (!N)
1021 continue;
1022
1023 assert(!N->isTemporary() && "Unexpected forward reference");
1024 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001025 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001026
1027 // Make sure we return early again until there's another forward ref.
1028 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001029}
Chris Lattner1314b992007-04-22 06:23:29 +00001030
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001031Type *BitcodeReader::getTypeByID(unsigned ID) {
1032 // The type table size is always specified correctly.
1033 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001034 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001035
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001036 if (Type *Ty = TypeList[ID])
1037 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001038
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001039 // If we have a forward reference, the only possible case is when it is to a
1040 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001041 return TypeList[ID] = createIdentifiedStructType(Context);
1042}
1043
1044StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1045 StringRef Name) {
1046 auto *Ret = StructType::create(Context, Name);
1047 IdentifiedStructTypes.push_back(Ret);
1048 return Ret;
1049}
1050
1051StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1052 auto *Ret = StructType::create(Context);
1053 IdentifiedStructTypes.push_back(Ret);
1054 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001055}
1056
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001057
Chris Lattnerfee5a372007-05-04 03:30:17 +00001058//===----------------------------------------------------------------------===//
1059// Functions for parsing blocks from the bitcode file
1060//===----------------------------------------------------------------------===//
1061
Bill Wendling56aeccc2013-02-04 23:32:23 +00001062
1063/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1064/// been decoded from the given integer. This function must stay in sync with
1065/// 'encodeLLVMAttributesForBitcode'.
1066static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1067 uint64_t EncodedAttrs) {
1068 // FIXME: Remove in 4.0.
1069
1070 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1071 // the bits above 31 down by 11 bits.
1072 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1073 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1074 "Alignment must be a power of two.");
1075
1076 if (Alignment)
1077 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001078 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001079 (EncodedAttrs & 0xffff));
1080}
1081
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001082std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001083 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001084 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001085
Devang Patela05633e2008-09-26 22:53:05 +00001086 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001087 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001088
Chris Lattnerfee5a372007-05-04 03:30:17 +00001089 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001090
Bill Wendling71173cb2013-01-27 00:36:48 +00001091 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001092
Chris Lattnerfee5a372007-05-04 03:30:17 +00001093 // Read all the records.
1094 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001095 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001096
Chris Lattner27d38752013-01-20 02:13:19 +00001097 switch (Entry.Kind) {
1098 case BitstreamEntry::SubBlock: // Handled for us already.
1099 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001100 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001101 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001102 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001103 case BitstreamEntry::Record:
1104 // The interesting case.
1105 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001106 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001107
Chris Lattnerfee5a372007-05-04 03:30:17 +00001108 // Read a record.
1109 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001110 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001111 default: // Default behavior: ignore.
1112 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001113 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1114 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001115 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001116 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001117
Chris Lattnerfee5a372007-05-04 03:30:17 +00001118 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001119 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001120 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001121 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001122 }
Devang Patela05633e2008-09-26 22:53:05 +00001123
Bill Wendlinge94d8432012-12-07 23:16:57 +00001124 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001125 Attrs.clear();
1126 break;
1127 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001128 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1129 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1130 Attrs.push_back(MAttributeGroups[Record[i]]);
1131
1132 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1133 Attrs.clear();
1134 break;
1135 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001136 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001137 }
1138}
1139
Reid Klecknere9f36af2013-11-12 01:31:00 +00001140// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001141static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001142 switch (Code) {
1143 default:
1144 return Attribute::None;
1145 case bitc::ATTR_KIND_ALIGNMENT:
1146 return Attribute::Alignment;
1147 case bitc::ATTR_KIND_ALWAYS_INLINE:
1148 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001149 case bitc::ATTR_KIND_ARGMEMONLY:
1150 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001151 case bitc::ATTR_KIND_BUILTIN:
1152 return Attribute::Builtin;
1153 case bitc::ATTR_KIND_BY_VAL:
1154 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001155 case bitc::ATTR_KIND_IN_ALLOCA:
1156 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001157 case bitc::ATTR_KIND_COLD:
1158 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001159 case bitc::ATTR_KIND_CONVERGENT:
1160 return Attribute::Convergent;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001161 case bitc::ATTR_KIND_INLINE_HINT:
1162 return Attribute::InlineHint;
1163 case bitc::ATTR_KIND_IN_REG:
1164 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001165 case bitc::ATTR_KIND_JUMP_TABLE:
1166 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001167 case bitc::ATTR_KIND_MIN_SIZE:
1168 return Attribute::MinSize;
1169 case bitc::ATTR_KIND_NAKED:
1170 return Attribute::Naked;
1171 case bitc::ATTR_KIND_NEST:
1172 return Attribute::Nest;
1173 case bitc::ATTR_KIND_NO_ALIAS:
1174 return Attribute::NoAlias;
1175 case bitc::ATTR_KIND_NO_BUILTIN:
1176 return Attribute::NoBuiltin;
1177 case bitc::ATTR_KIND_NO_CAPTURE:
1178 return Attribute::NoCapture;
1179 case bitc::ATTR_KIND_NO_DUPLICATE:
1180 return Attribute::NoDuplicate;
1181 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1182 return Attribute::NoImplicitFloat;
1183 case bitc::ATTR_KIND_NO_INLINE:
1184 return Attribute::NoInline;
1185 case bitc::ATTR_KIND_NON_LAZY_BIND:
1186 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001187 case bitc::ATTR_KIND_NON_NULL:
1188 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001189 case bitc::ATTR_KIND_DEREFERENCEABLE:
1190 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001191 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1192 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001193 case bitc::ATTR_KIND_NO_RED_ZONE:
1194 return Attribute::NoRedZone;
1195 case bitc::ATTR_KIND_NO_RETURN:
1196 return Attribute::NoReturn;
1197 case bitc::ATTR_KIND_NO_UNWIND:
1198 return Attribute::NoUnwind;
1199 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1200 return Attribute::OptimizeForSize;
1201 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1202 return Attribute::OptimizeNone;
1203 case bitc::ATTR_KIND_READ_NONE:
1204 return Attribute::ReadNone;
1205 case bitc::ATTR_KIND_READ_ONLY:
1206 return Attribute::ReadOnly;
1207 case bitc::ATTR_KIND_RETURNED:
1208 return Attribute::Returned;
1209 case bitc::ATTR_KIND_RETURNS_TWICE:
1210 return Attribute::ReturnsTwice;
1211 case bitc::ATTR_KIND_S_EXT:
1212 return Attribute::SExt;
1213 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1214 return Attribute::StackAlignment;
1215 case bitc::ATTR_KIND_STACK_PROTECT:
1216 return Attribute::StackProtect;
1217 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1218 return Attribute::StackProtectReq;
1219 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1220 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001221 case bitc::ATTR_KIND_SAFESTACK:
1222 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001223 case bitc::ATTR_KIND_STRUCT_RET:
1224 return Attribute::StructRet;
1225 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1226 return Attribute::SanitizeAddress;
1227 case bitc::ATTR_KIND_SANITIZE_THREAD:
1228 return Attribute::SanitizeThread;
1229 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1230 return Attribute::SanitizeMemory;
1231 case bitc::ATTR_KIND_UW_TABLE:
1232 return Attribute::UWTable;
1233 case bitc::ATTR_KIND_Z_EXT:
1234 return Attribute::ZExt;
1235 }
1236}
1237
JF Bastien30bf96b2015-02-22 19:32:03 +00001238std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1239 unsigned &Alignment) {
1240 // Note: Alignment in bitcode files is incremented by 1, so that zero
1241 // can be used for default alignment.
1242 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001243 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001244 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1245 return std::error_code();
1246}
1247
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001248std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001249 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001250 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001251 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001252 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001253 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001254 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001255}
1256
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001257std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001258 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001259 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001260
1261 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001262 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001263
1264 SmallVector<uint64_t, 64> Record;
1265
1266 // Read all the records.
1267 while (1) {
1268 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1269
1270 switch (Entry.Kind) {
1271 case BitstreamEntry::SubBlock: // Handled for us already.
1272 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001273 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001274 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001275 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001276 case BitstreamEntry::Record:
1277 // The interesting case.
1278 break;
1279 }
1280
1281 // Read a record.
1282 Record.clear();
1283 switch (Stream.readRecord(Entry.ID, Record)) {
1284 default: // Default behavior: ignore.
1285 break;
1286 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1287 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001288 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001289
Bill Wendlinge46707e2013-02-11 22:32:29 +00001290 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001291 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1292
1293 AttrBuilder B;
1294 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1295 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001296 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001297 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001298 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001299
1300 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001301 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001302 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001303 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001304 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001305 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001306 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001307 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001308 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001309 else if (Kind == Attribute::Dereferenceable)
1310 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001311 else if (Kind == Attribute::DereferenceableOrNull)
1312 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001313 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001314 assert((Record[i] == 3 || Record[i] == 4) &&
1315 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001316 bool HasValue = (Record[i++] == 4);
1317 SmallString<64> KindStr;
1318 SmallString<64> ValStr;
1319
1320 while (Record[i] != 0 && i != e)
1321 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001322 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001323
1324 if (HasValue) {
1325 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001326 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001327 while (Record[i] != 0 && i != e)
1328 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001329 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001330 }
1331
1332 B.addAttribute(KindStr.str(), ValStr.str());
1333 }
1334 }
1335
Bill Wendlinge46707e2013-02-11 22:32:29 +00001336 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001337 break;
1338 }
1339 }
1340 }
1341}
1342
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001343std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001344 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001345 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001346
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001347 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001348}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001349
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001350std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001351 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001352 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001353
1354 SmallVector<uint64_t, 64> Record;
1355 unsigned NumRecords = 0;
1356
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001357 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001358
Chris Lattner1314b992007-04-22 06:23:29 +00001359 // Read all the records for this type table.
1360 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001361 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001362
Chris Lattner27d38752013-01-20 02:13:19 +00001363 switch (Entry.Kind) {
1364 case BitstreamEntry::SubBlock: // Handled for us already.
1365 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001366 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001367 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001368 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001369 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001370 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001371 case BitstreamEntry::Record:
1372 // The interesting case.
1373 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001375
Chris Lattner1314b992007-04-22 06:23:29 +00001376 // Read a record.
1377 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001378 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001379 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001380 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001381 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001382 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1383 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1384 // type list. This allows us to reserve space.
1385 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001386 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001387 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001388 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001389 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001390 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001391 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001392 case bitc::TYPE_CODE_HALF: // HALF
1393 ResultTy = Type::getHalfTy(Context);
1394 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001395 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001396 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001397 break;
1398 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001399 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001400 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001401 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001402 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001403 break;
1404 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001405 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001406 break;
1407 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001408 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001409 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001410 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001411 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001412 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001413 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001414 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001415 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001416 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1417 ResultTy = Type::getX86_MMXTy(Context);
1418 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001419 case bitc::TYPE_CODE_TOKEN: // TOKEN
1420 ResultTy = Type::getTokenTy(Context);
1421 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001422 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001423 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001424 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001425
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001426 uint64_t NumBits = Record[0];
1427 if (NumBits < IntegerType::MIN_INT_BITS ||
1428 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001429 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001430 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001431 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001432 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001433 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001434 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001435 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001436 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001437 unsigned AddressSpace = 0;
1438 if (Record.size() == 2)
1439 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001440 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001441 if (!ResultTy ||
1442 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001443 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001444 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001445 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001446 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001447 case bitc::TYPE_CODE_FUNCTION_OLD: {
1448 // FIXME: attrid is dead, remove it in LLVM 4.0
1449 // FUNCTION: [vararg, attrid, retty, paramty x N]
1450 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001451 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001452 SmallVector<Type*, 8> ArgTys;
1453 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1454 if (Type *T = getTypeByID(Record[i]))
1455 ArgTys.push_back(T);
1456 else
1457 break;
1458 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001459
Nuno Lopes561dae02012-05-23 15:19:39 +00001460 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001461 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001462 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001463
1464 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1465 break;
1466 }
Chad Rosier95898722011-11-03 00:14:01 +00001467 case bitc::TYPE_CODE_FUNCTION: {
1468 // FUNCTION: [vararg, retty, paramty x N]
1469 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001470 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001471 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001472 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001473 if (Type *T = getTypeByID(Record[i])) {
1474 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001475 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001476 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001477 }
Chad Rosier95898722011-11-03 00:14:01 +00001478 else
1479 break;
1480 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001481
Chad Rosier95898722011-11-03 00:14:01 +00001482 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001483 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001484 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001485
1486 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1487 break;
1488 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001489 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001490 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001491 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001492 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001493 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1494 if (Type *T = getTypeByID(Record[i]))
1495 EltTys.push_back(T);
1496 else
1497 break;
1498 }
1499 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001500 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001501 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001502 break;
1503 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001504 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001505 if (convertToString(Record, 0, TypeName))
1506 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001507 continue;
1508
1509 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1510 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001511 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001512
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001513 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001514 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001515
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001516 // Check to see if this was forward referenced, if so fill in the temp.
1517 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1518 if (Res) {
1519 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001520 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001521 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001522 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001523 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001524
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001525 SmallVector<Type*, 8> EltTys;
1526 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1527 if (Type *T = getTypeByID(Record[i]))
1528 EltTys.push_back(T);
1529 else
1530 break;
1531 }
1532 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001533 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001534 Res->setBody(EltTys, Record[0]);
1535 ResultTy = Res;
1536 break;
1537 }
1538 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1539 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001540 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001541
1542 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001543 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001544
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001545 // Check to see if this was forward referenced, if so fill in the temp.
1546 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1547 if (Res) {
1548 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001549 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001550 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001551 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001552 TypeName.clear();
1553 ResultTy = Res;
1554 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001555 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001556 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1557 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001558 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001559 ResultTy = getTypeByID(Record[1]);
1560 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001561 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001562 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001563 break;
1564 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1565 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001566 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001567 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001568 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001569 ResultTy = getTypeByID(Record[1]);
1570 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001571 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001572 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001573 break;
1574 }
1575
1576 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001578 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001579 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001580 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001581 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001582 TypeList[NumRecords++] = ResultTy;
1583 }
1584}
1585
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586std::error_code BitcodeReader::parseValueSymbolTable() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001587 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001588 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001589
1590 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001591
David Majnemer3087b222015-01-20 05:58:07 +00001592 Triple TT(TheModule->getTargetTriple());
1593
Chris Lattnerccaa4482007-04-23 21:26:05 +00001594 // Read all the records for this value table.
1595 SmallString<128> ValueName;
1596 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001597 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001598
Chris Lattner27d38752013-01-20 02:13:19 +00001599 switch (Entry.Kind) {
1600 case BitstreamEntry::SubBlock: // Handled for us already.
1601 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001603 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001604 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001605 case BitstreamEntry::Record:
1606 // The interesting case.
1607 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001608 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001609
Chris Lattnerccaa4482007-04-23 21:26:05 +00001610 // Read a record.
1611 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001612 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001613 default: // Default behavior: unknown type.
1614 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00001615 case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001616 if (convertToString(Record, 1, ValueName))
1617 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001618 unsigned ValueID = Record[0];
Karthik Bhat82540e92014-03-27 12:08:23 +00001619 if (ValueID >= ValueList.size() || !ValueList[ValueID])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001620 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001621 Value *V = ValueList[ValueID];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001622
Daniel Dunbard786b512009-07-26 00:34:27 +00001623 V->setName(StringRef(ValueName.data(), ValueName.size()));
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001624 if (auto *GO = dyn_cast<GlobalObject>(V)) {
David Majnemer3087b222015-01-20 05:58:07 +00001625 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1626 if (TT.isOSBinFormatMachO())
1627 GO->setComdat(nullptr);
1628 else
1629 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1630 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001631 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001632 ValueName.clear();
1633 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001634 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001635 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001636 if (convertToString(Record, 1, ValueName))
1637 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001638 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001639 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001640 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001641
Daniel Dunbard786b512009-07-26 00:34:27 +00001642 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001643 ValueName.clear();
1644 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001645 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001646 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001647 }
1648}
1649
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001650static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1651
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001652std::error_code BitcodeReader::parseMetadata() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001653 IsMetadataMaterialized = true;
Devang Patel89923232010-01-11 18:52:33 +00001654 unsigned NextMDValueNo = MDValueList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001655
1656 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001657 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001658
Devang Patel7428d8a2009-07-22 17:43:22 +00001659 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001660
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001661 auto getMD =
1662 [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
1663 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1664 if (ID)
1665 return getMD(ID - 1);
1666 return nullptr;
1667 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001668 auto getMDString = [&](unsigned ID) -> MDString *{
1669 // This requires that the ID is not really a forward reference. In
1670 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001671 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001672 };
1673
1674#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1675 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1676
Devang Patel7428d8a2009-07-22 17:43:22 +00001677 // Read all the records.
1678 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001679 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001680
Chris Lattner27d38752013-01-20 02:13:19 +00001681 switch (Entry.Kind) {
1682 case BitstreamEntry::SubBlock: // Handled for us already.
1683 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001684 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001685 case BitstreamEntry::EndBlock:
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001686 MDValueList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001687 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001688 case BitstreamEntry::Record:
1689 // The interesting case.
1690 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001691 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001692
Devang Patel7428d8a2009-07-22 17:43:22 +00001693 // Read a record.
1694 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001695 unsigned Code = Stream.readRecord(Entry.ID, Record);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001696 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001697 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001698 default: // Default behavior: ignore.
1699 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001700 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001701 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001702 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001703 Record.clear();
1704 Code = Stream.ReadCode();
1705
Chris Lattner27d38752013-01-20 02:13:19 +00001706 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001707 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001708 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001709
1710 // Read named metadata elements.
1711 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001712 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001713 for (unsigned i = 0; i != Size; ++i) {
Karthik Bhat82540e92014-03-27 12:08:23 +00001714 MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
Craig Topper2617dcc2014-04-15 06:32:26 +00001715 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001716 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001717 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001718 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001719 break;
1720 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001721 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001722 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001723 // This is a LocalAsMetadata record, the only type of function-local
1724 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001725 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001726 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001727
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001728 // If this isn't a LocalAsMetadata record, we're dropping it. This used
1729 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001730 auto dropRecord = [&] {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001731 MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001732 };
1733 if (Record.size() != 2) {
1734 dropRecord();
1735 break;
1736 }
1737
1738 Type *Ty = getTypeByID(Record[0]);
1739 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
1740 dropRecord();
1741 break;
1742 }
1743
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001744 MDValueList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001745 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1746 NextMDValueNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00001747 break;
1748 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001749 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001750 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00001751 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001752 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001753
Devang Patele059ba6e2009-07-23 01:07:34 +00001754 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001755 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00001756 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00001757 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00001758 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001759 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00001760 if (Ty->isMetadataTy())
Devang Patel05eb6172009-08-04 06:00:18 +00001761 Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001762 else if (!Ty->isVoidTy()) {
1763 auto *MD =
1764 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
1765 assert(isa<ConstantAsMetadata>(MD) &&
1766 "Expected non-function-local metadata");
1767 Elts.push_back(MD);
1768 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00001769 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00001770 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001771 MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00001772 break;
1773 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001774 case bitc::METADATA_VALUE: {
1775 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001776 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001777
1778 Type *Ty = getTypeByID(Record[0]);
1779 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001780 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001781
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001782 MDValueList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001783 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
1784 NextMDValueNo++);
1785 break;
1786 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001787 case bitc::METADATA_DISTINCT_NODE:
1788 IsDistinct = true;
1789 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001790 case bitc::METADATA_NODE: {
1791 SmallVector<Metadata *, 8> Elts;
1792 Elts.reserve(Record.size());
1793 for (unsigned ID : Record)
1794 Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001795 MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001796 : MDNode::get(Context, Elts),
1797 NextMDValueNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00001798 break;
1799 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001800 case bitc::METADATA_LOCATION: {
1801 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001802 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001803
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001804 unsigned Line = Record[1];
1805 unsigned Column = Record[2];
1806 MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
1807 Metadata *InlinedAt =
1808 Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001809 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001810 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00001811 (Context, Line, Column, Scope, InlinedAt)),
1812 NextMDValueNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00001813 break;
1814 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001815 case bitc::METADATA_GENERIC_DEBUG: {
1816 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001817 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001818
1819 unsigned Tag = Record[1];
1820 unsigned Version = Record[2];
1821
1822 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001823 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001824
1825 auto *Header = getMDString(Record[3]);
1826 SmallVector<Metadata *, 8> DwarfOps;
1827 for (unsigned I = 4, E = Record.size(); I != E; ++I)
1828 DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
1829 : nullptr);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001830 MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001831 (Context, Tag, Header, DwarfOps)),
1832 NextMDValueNo++);
1833 break;
1834 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001835 case bitc::METADATA_SUBRANGE: {
1836 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001837 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001838
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001839 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001840 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001841 (Context, Record[1], unrotateSign(Record[2]))),
1842 NextMDValueNo++);
1843 break;
1844 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001845 case bitc::METADATA_ENUMERATOR: {
1846 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001847 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001848
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001849 MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00001850 (Context, unrotateSign(Record[1]),
1851 getMDString(Record[2]))),
1852 NextMDValueNo++);
1853 break;
1854 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001855 case bitc::METADATA_BASIC_TYPE: {
1856 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001857 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001858
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001859 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001860 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00001861 (Context, Record[1], getMDString(Record[2]),
1862 Record[3], Record[4], Record[5])),
1863 NextMDValueNo++);
1864 break;
1865 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001866 case bitc::METADATA_DERIVED_TYPE: {
1867 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001868 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001869
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001870 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001871 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001872 (Context, Record[1], getMDString(Record[2]),
1873 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00001874 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1875 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001876 getMDOrNull(Record[11]))),
1877 NextMDValueNo++);
1878 break;
1879 }
1880 case bitc::METADATA_COMPOSITE_TYPE: {
1881 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001882 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001883
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001884 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001885 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001886 (Context, Record[1], getMDString(Record[2]),
1887 getMDOrNull(Record[3]), Record[4],
1888 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
1889 Record[7], Record[8], Record[9], Record[10],
1890 getMDOrNull(Record[11]), Record[12],
1891 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
1892 getMDString(Record[15]))),
1893 NextMDValueNo++);
1894 break;
1895 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001896 case bitc::METADATA_SUBROUTINE_TYPE: {
1897 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001898 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001899
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001900 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001901 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00001902 (Context, Record[1], getMDOrNull(Record[2]))),
1903 NextMDValueNo++);
1904 break;
1905 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00001906
1907 case bitc::METADATA_MODULE: {
1908 if (Record.size() != 6)
1909 return error("Invalid record");
1910
1911 MDValueList.assignValue(
1912 GET_OR_DISTINCT(DIModule, Record[0],
1913 (Context, getMDOrNull(Record[1]),
1914 getMDString(Record[2]), getMDString(Record[3]),
1915 getMDString(Record[4]), getMDString(Record[5]))),
1916 NextMDValueNo++);
1917 break;
1918 }
1919
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001920 case bitc::METADATA_FILE: {
1921 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001922 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001923
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001924 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001925 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00001926 getMDString(Record[2]))),
1927 NextMDValueNo++);
1928 break;
1929 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001930 case bitc::METADATA_COMPILE_UNIT: {
Adrian Prantl1f599f92015-05-21 20:37:30 +00001931 if (Record.size() < 14 || Record.size() > 15)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001932 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001933
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001934 // Ignore Record[1], which indicates whether this compile unit is
1935 // distinct. It's always distinct.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001936 MDValueList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00001937 DICompileUnit::getDistinct(
1938 Context, Record[1], getMDOrNull(Record[2]),
1939 getMDString(Record[3]), Record[4], getMDString(Record[5]),
1940 Record[6], getMDString(Record[7]), Record[8],
1941 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
1942 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
1943 getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14]),
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00001944 NextMDValueNo++);
1945 break;
1946 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001947 case bitc::METADATA_SUBPROGRAM: {
1948 if (Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001949 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001950
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001951 MDValueList.assignValue(
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001952 GET_OR_DISTINCT(
Duncan P. N. Exon Smith814b8e92015-08-28 20:26:49 +00001953 DISubprogram,
1954 Record[0] || Record[8], // All definitions should be distinct.
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00001955 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
1956 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
1957 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
1958 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
1959 Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
1960 getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
1961 NextMDValueNo++);
1962 break;
1963 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001964 case bitc::METADATA_LEXICAL_BLOCK: {
1965 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001966 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001967
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001968 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001969 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00001970 (Context, getMDOrNull(Record[1]),
1971 getMDOrNull(Record[2]), Record[3], Record[4])),
1972 NextMDValueNo++);
1973 break;
1974 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001975 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
1976 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001977 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001978
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001979 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001980 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00001981 (Context, getMDOrNull(Record[1]),
1982 getMDOrNull(Record[2]), Record[3])),
1983 NextMDValueNo++);
1984 break;
1985 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001986 case bitc::METADATA_NAMESPACE: {
1987 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001988 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001989
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001990 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001991 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00001992 (Context, getMDOrNull(Record[1]),
1993 getMDOrNull(Record[2]), getMDString(Record[3]),
1994 Record[4])),
1995 NextMDValueNo++);
1996 break;
1997 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00001998 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00001999 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002000 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002001
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002002 MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002003 Record[0],
2004 (Context, getMDString(Record[1]),
2005 getMDOrNull(Record[2]))),
2006 NextMDValueNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002007 break;
2008 }
2009 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002010 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002011 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002012
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002013 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002014 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002015 (Context, Record[1], getMDString(Record[2]),
2016 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002017 NextMDValueNo++);
2018 break;
2019 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002020 case bitc::METADATA_GLOBAL_VAR: {
2021 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002022 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002023
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002024 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002025 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002026 (Context, getMDOrNull(Record[1]),
2027 getMDString(Record[2]), getMDString(Record[3]),
2028 getMDOrNull(Record[4]), Record[5],
2029 getMDOrNull(Record[6]), Record[7], Record[8],
2030 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
2031 NextMDValueNo++);
2032 break;
2033 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002034 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002035 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002036 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002037 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002038
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002039 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2040 // DW_TAG_arg_variable.
2041 bool HasTag = Record.size() > 8;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002042 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002043 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002044 (Context, getMDOrNull(Record[1 + HasTag]),
2045 getMDString(Record[2 + HasTag]),
2046 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2047 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2048 Record[7 + HasTag])),
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002049 NextMDValueNo++);
2050 break;
2051 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002052 case bitc::METADATA_EXPRESSION: {
2053 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002054 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002055
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002056 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002057 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002058 (Context, makeArrayRef(Record).slice(1))),
2059 NextMDValueNo++);
2060 break;
2061 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002062 case bitc::METADATA_OBJC_PROPERTY: {
2063 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002064 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002065
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002066 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002067 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002068 (Context, getMDString(Record[1]),
2069 getMDOrNull(Record[2]), Record[3],
2070 getMDString(Record[4]), getMDString(Record[5]),
2071 Record[6], getMDOrNull(Record[7]))),
2072 NextMDValueNo++);
2073 break;
2074 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002075 case bitc::METADATA_IMPORTED_ENTITY: {
2076 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002077 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002078
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002079 MDValueList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002080 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002081 (Context, Record[1], getMDOrNull(Record[2]),
2082 getMDOrNull(Record[3]), Record[4],
2083 getMDString(Record[5]))),
2084 NextMDValueNo++);
2085 break;
2086 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002087 case bitc::METADATA_STRING: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002088 std::string String(Record.begin(), Record.end());
2089 llvm::UpgradeMDStringConstant(String);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002090 Metadata *MD = MDString::get(Context, String);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002091 MDValueList.assignValue(MD, NextMDValueNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002092 break;
2093 }
Devang Patelaf206b82009-09-18 19:26:43 +00002094 case bitc::METADATA_KIND: {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002095 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002096 return error("Invalid record");
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002097
Devang Patelb1a44772009-09-28 21:14:55 +00002098 unsigned Kind = Record[0];
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002099 SmallString<8> Name(Record.begin()+1, Record.end());
2100
Chris Lattnera0566972009-12-29 09:01:33 +00002101 unsigned NewKind = TheModule->getMDKindID(Name.str());
Dan Gohman43aa8f02010-07-20 21:42:28 +00002102 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002103 return error("Conflicting METADATA_KIND records");
Devang Patelaf206b82009-09-18 19:26:43 +00002104 break;
2105 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002106 }
2107 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002108#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002109}
2110
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002111/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2112/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002113uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002114 if ((V & 1) == 0)
2115 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002116 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002117 return -(V >> 1);
2118 // There is no such thing as -0 with integers. "-0" really means MININT.
2119 return 1ULL << 63;
2120}
2121
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002122/// Resolve all of the initializers for global values and aliases that we can.
2123std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002124 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2125 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002126 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002127 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002128 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002129
Chris Lattner44c17072007-04-26 02:46:40 +00002130 GlobalInitWorklist.swap(GlobalInits);
2131 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002132 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002133 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002134 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002135
2136 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002137 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002138 if (ValID >= ValueList.size()) {
2139 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002140 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002141 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002142 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002143 GlobalInitWorklist.back().first->setInitializer(C);
2144 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002145 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002146 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002147 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002148 }
2149
2150 while (!AliasInitWorklist.empty()) {
2151 unsigned ValID = AliasInitWorklist.back().second;
2152 if (ValID >= ValueList.size()) {
2153 AliasInits.push_back(AliasInitWorklist.back());
2154 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002155 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2156 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002157 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002158 GlobalAlias *Alias = AliasInitWorklist.back().first;
2159 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002160 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002161 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002162 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002163 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002164 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002165
2166 while (!FunctionPrefixWorklist.empty()) {
2167 unsigned ValID = FunctionPrefixWorklist.back().second;
2168 if (ValID >= ValueList.size()) {
2169 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2170 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002171 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002172 FunctionPrefixWorklist.back().first->setPrefixData(C);
2173 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002174 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002175 }
2176 FunctionPrefixWorklist.pop_back();
2177 }
2178
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002179 while (!FunctionPrologueWorklist.empty()) {
2180 unsigned ValID = FunctionPrologueWorklist.back().second;
2181 if (ValID >= ValueList.size()) {
2182 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2183 } else {
2184 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2185 FunctionPrologueWorklist.back().first->setPrologueData(C);
2186 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002187 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002188 }
2189 FunctionPrologueWorklist.pop_back();
2190 }
2191
David Majnemer7fddecc2015-06-17 20:52:32 +00002192 while (!FunctionPersonalityFnWorklist.empty()) {
2193 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2194 if (ValID >= ValueList.size()) {
2195 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2196 } else {
2197 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2198 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2199 else
2200 return error("Expected a constant");
2201 }
2202 FunctionPersonalityFnWorklist.pop_back();
2203 }
2204
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002205 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002206}
2207
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002208static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002209 SmallVector<uint64_t, 8> Words(Vals.size());
2210 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002211 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002212
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002213 return APInt(TypeBits, Words);
2214}
2215
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002216std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002217 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002218 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002219
2220 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002221
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002222 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002223 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002224 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002225 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002226 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002227
Chris Lattner27d38752013-01-20 02:13:19 +00002228 switch (Entry.Kind) {
2229 case BitstreamEntry::SubBlock: // Handled for us already.
2230 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002231 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002232 case BitstreamEntry::EndBlock:
2233 if (NextCstNo != ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002234 return error("Invalid ronstant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002235
Chris Lattner27d38752013-01-20 02:13:19 +00002236 // Once all the constants have been read, go through and resolve forward
2237 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002238 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002239 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002240 case BitstreamEntry::Record:
2241 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002242 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002243 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002244
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002245 // Read a record.
2246 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002247 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002248 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002249 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002250 default: // Default behavior: unknown constant
2251 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002252 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002253 break;
2254 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2255 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002256 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002257 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002258 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002259 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002260 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002261 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002262 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002263 break;
2264 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002265 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002266 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002267 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002268 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002269 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002270 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002271 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002272
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002273 APInt VInt =
2274 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002275 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002276
Chris Lattner08feb1e2007-04-24 04:04:35 +00002277 break;
2278 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002279 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002280 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002281 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002282 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002283 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2284 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002285 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002286 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2287 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002288 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002289 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2290 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002291 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002292 // Bits are not stored the same way as a normal i80 APInt, compensate.
2293 uint64_t Rearrange[2];
2294 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2295 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002296 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2297 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002298 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002299 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2300 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002301 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002302 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2303 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002304 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002305 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002306 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002308
Chris Lattnere14cb882007-05-04 19:11:41 +00002309 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2310 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002311 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002312
Chris Lattnere14cb882007-05-04 19:11:41 +00002313 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002314 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002315
Chris Lattner229907c2011-07-18 04:54:35 +00002316 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002317 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002318 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002319 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002320 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002321 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2322 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002323 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002324 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002325 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002326 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2327 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002328 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002329 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002330 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002331 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002332 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002333 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002334 break;
2335 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002336 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002337 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2338 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002339 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002340
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002341 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002342 V = ConstantDataArray::getString(Context, Elts,
2343 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002344 break;
2345 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002346 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2347 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002348 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002349
Chris Lattner372dd1e2012-01-30 00:51:16 +00002350 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
2351 unsigned Size = Record.size();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002352
Chris Lattner372dd1e2012-01-30 00:51:16 +00002353 if (EltTy->isIntegerTy(8)) {
2354 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2355 if (isa<VectorType>(CurTy))
2356 V = ConstantDataVector::get(Context, Elts);
2357 else
2358 V = ConstantDataArray::get(Context, Elts);
2359 } else if (EltTy->isIntegerTy(16)) {
2360 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2361 if (isa<VectorType>(CurTy))
2362 V = ConstantDataVector::get(Context, Elts);
2363 else
2364 V = ConstantDataArray::get(Context, Elts);
2365 } else if (EltTy->isIntegerTy(32)) {
2366 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2367 if (isa<VectorType>(CurTy))
2368 V = ConstantDataVector::get(Context, Elts);
2369 else
2370 V = ConstantDataArray::get(Context, Elts);
2371 } else if (EltTy->isIntegerTy(64)) {
2372 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2373 if (isa<VectorType>(CurTy))
2374 V = ConstantDataVector::get(Context, Elts);
2375 else
2376 V = ConstantDataArray::get(Context, Elts);
2377 } else if (EltTy->isFloatTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002378 SmallVector<float, 16> Elts(Size);
2379 std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002380 if (isa<VectorType>(CurTy))
2381 V = ConstantDataVector::get(Context, Elts);
2382 else
2383 V = ConstantDataArray::get(Context, Elts);
2384 } else if (EltTy->isDoubleTy()) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002385 SmallVector<double, 16> Elts(Size);
2386 std::transform(Record.begin(), Record.end(), Elts.begin(),
2387 BitsToDouble);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002388 if (isa<VectorType>(CurTy))
2389 V = ConstantDataVector::get(Context, Elts);
2390 else
2391 V = ConstantDataArray::get(Context, Elts);
2392 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002393 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002394 }
2395 break;
2396 }
2397
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002398 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002399 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002400 return error("Invalid record");
2401 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002402 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002403 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002404 } else {
2405 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2406 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002407 unsigned Flags = 0;
2408 if (Record.size() >= 4) {
2409 if (Opc == Instruction::Add ||
2410 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002411 Opc == Instruction::Mul ||
2412 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002413 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2414 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2415 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2416 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002417 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002418 Opc == Instruction::UDiv ||
2419 Opc == Instruction::LShr ||
2420 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002421 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002422 Flags |= SDivOperator::IsExact;
2423 }
2424 }
2425 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002426 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002427 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002428 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002429 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002430 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002431 return error("Invalid record");
2432 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002433 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002434 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002435 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002436 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002437 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002438 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002439 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002440 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2441 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002442 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002443 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002444 }
Dan Gohman1639c392009-07-27 21:53:46 +00002445 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002446 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002447 unsigned OpNum = 0;
2448 Type *PointeeType = nullptr;
2449 if (Record.size() % 2)
2450 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002451 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002452 while (OpNum != Record.size()) {
2453 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002454 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002455 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002456 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002457 }
David Blaikieb9263572015-03-13 21:03:36 +00002458
David Blaikieb9263572015-03-13 21:03:36 +00002459 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002460 PointeeType !=
2461 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2462 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002463 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002464 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002465
2466 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2467 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2468 BitCode ==
2469 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002470 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002471 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002472 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002473 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002474 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002475
2476 Type *SelectorTy = Type::getInt1Ty(Context);
2477
2478 // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
2479 // vector. Otherwise, it must be a single bit.
2480 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
2481 SelectorTy = VectorType::get(Type::getInt1Ty(Context),
2482 VTy->getNumElements());
2483
2484 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2485 SelectorTy),
2486 ValueList.getConstantFwdRef(Record[1],CurTy),
2487 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002488 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002489 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002490 case bitc::CST_CODE_CE_EXTRACTELT
2491 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002492 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002493 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002494 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002495 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002496 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002497 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002498 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002499 Constant *Op1 = nullptr;
2500 if (Record.size() == 4) {
2501 Type *IdxTy = getTypeByID(Record[2]);
2502 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002503 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002504 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2505 } else // TODO: Remove with llvm 4.0
2506 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2507 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002508 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002509 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002510 break;
2511 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002512 case bitc::CST_CODE_CE_INSERTELT
2513 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002514 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002515 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002516 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002517 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2518 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2519 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002520 Constant *Op2 = nullptr;
2521 if (Record.size() == 4) {
2522 Type *IdxTy = getTypeByID(Record[2]);
2523 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002524 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002525 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2526 } else // TODO: Remove with llvm 4.0
2527 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2528 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002529 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002530 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002531 break;
2532 }
2533 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002534 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002535 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002536 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002537 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2538 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002539 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002540 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002541 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002542 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002543 break;
2544 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002545 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002546 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2547 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002548 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002549 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002550 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002551 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2552 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002553 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002554 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002555 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002556 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002557 break;
2558 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002559 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002560 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002561 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002562 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002563 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002564 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002565 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2566 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2567
Duncan Sands9dff9be2010-02-15 16:12:20 +00002568 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002569 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002570 else
Owen Anderson487375e2009-07-29 18:55:55 +00002571 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002572 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002573 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002574 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002575 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002576 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002577 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002578 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002579 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002580 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002581 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002582 unsigned AsmStrSize = Record[1];
2583 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002584 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002585 unsigned ConstStrSize = Record[2+AsmStrSize];
2586 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002587 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002588
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002589 for (unsigned i = 0; i != AsmStrSize; ++i)
2590 AsmStr += (char)Record[2+i];
2591 for (unsigned i = 0; i != ConstStrSize; ++i)
2592 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002593 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002594 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002595 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002596 break;
2597 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002598 // This version adds support for the asm dialect keywords (e.g.,
2599 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002600 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002601 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002602 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002603 std::string AsmStr, ConstrStr;
2604 bool HasSideEffects = Record[0] & 1;
2605 bool IsAlignStack = (Record[0] >> 1) & 1;
2606 unsigned AsmDialect = Record[0] >> 2;
2607 unsigned AsmStrSize = Record[1];
2608 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002609 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002610 unsigned ConstStrSize = Record[2+AsmStrSize];
2611 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002612 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002613
2614 for (unsigned i = 0; i != AsmStrSize; ++i)
2615 AsmStr += (char)Record[2+i];
2616 for (unsigned i = 0; i != ConstStrSize; ++i)
2617 ConstrStr += (char)Record[3+AsmStrSize+i];
2618 PointerType *PTy = cast<PointerType>(CurTy);
2619 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2620 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002621 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002622 break;
2623 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002624 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002625 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002626 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002627 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002628 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002629 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002630 Function *Fn =
2631 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002632 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002633 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002634
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00002635 // Don't let Fn get dematerialized.
2636 BlockAddressesTaken.insert(Fn);
2637
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002638 // If the function is already parsed we can insert the block address right
2639 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002640 BasicBlock *BB;
2641 unsigned BBID = Record[2];
2642 if (!BBID)
2643 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002644 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002645 if (!Fn->empty()) {
2646 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002647 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002648 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002649 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002650 ++BBI;
2651 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002652 BB = BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002653 } else {
2654 // Otherwise insert a placeholder and remember it so it can be inserted
2655 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00002656 auto &FwdBBs = BasicBlockFwdRefs[Fn];
2657 if (FwdBBs.empty())
2658 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00002659 if (FwdBBs.size() < BBID + 1)
2660 FwdBBs.resize(BBID + 1);
2661 if (!FwdBBs[BBID])
2662 FwdBBs[BBID] = BasicBlock::Create(Context);
2663 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002664 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002665 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00002666 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002667 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002668 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002669
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00002670 if (ValueList.assignValue(V, NextCstNo))
2671 return error("Invalid forward reference");
Chris Lattner1663cca2007-04-24 05:48:56 +00002672 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002673 }
2674}
Chris Lattner1314b992007-04-22 06:23:29 +00002675
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002676std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00002677 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002678 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00002679
Chad Rosierca2567b2011-12-07 21:44:12 +00002680 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002681 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00002682 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002683 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002684
Chris Lattner27d38752013-01-20 02:13:19 +00002685 switch (Entry.Kind) {
2686 case BitstreamEntry::SubBlock: // Handled for us already.
2687 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002688 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002689 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002690 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002691 case BitstreamEntry::Record:
2692 // The interesting case.
2693 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002694 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002695
Chad Rosierca2567b2011-12-07 21:44:12 +00002696 // Read a use list record.
2697 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002698 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00002699 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00002700 default: // Default behavior: unknown type.
2701 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002702 case bitc::USELIST_CODE_BB:
2703 IsBB = true;
2704 // fallthrough
2705 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00002706 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002707 if (RecordLength < 3)
2708 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002709 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002710 unsigned ID = Record.back();
2711 Record.pop_back();
2712
2713 Value *V;
2714 if (IsBB) {
2715 assert(ID < FunctionBBs.size() && "Basic block not found");
2716 V = FunctionBBs[ID];
2717 } else
2718 V = ValueList[ID];
2719 unsigned NumUses = 0;
2720 SmallDenseMap<const Use *, unsigned, 16> Order;
2721 for (const Use &U : V->uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002722 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002723 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00002724 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00002725 }
2726 if (Order.size() != Record.size() || NumUses > Record.size())
2727 // Mismatches can happen if the functions are being materialized lazily
2728 // (out-of-order), or a value has been upgraded.
2729 break;
2730
2731 V->sortUseList([&](const Use &L, const Use &R) {
2732 return Order.lookup(&L) < Order.lookup(&R);
2733 });
Chad Rosierca2567b2011-12-07 21:44:12 +00002734 break;
2735 }
2736 }
2737 }
2738}
2739
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002740/// When we see the block for metadata, remember where it is and then skip it.
2741/// This lets us lazily deserialize the metadata.
2742std::error_code BitcodeReader::rememberAndSkipMetadata() {
2743 // Save the current stream state.
2744 uint64_t CurBit = Stream.GetCurrentBitNo();
2745 DeferredMetadataInfo.push_back(CurBit);
2746
2747 // Skip over the block for now.
2748 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002749 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002750 return std::error_code();
2751}
2752
2753std::error_code BitcodeReader::materializeMetadata() {
2754 for (uint64_t BitPos : DeferredMetadataInfo) {
2755 // Move the bit stream to the saved position.
2756 Stream.JumpToBit(BitPos);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002757 if (std::error_code EC = parseMetadata())
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002758 return EC;
2759 }
2760 DeferredMetadataInfo.clear();
2761 return std::error_code();
2762}
2763
Rafael Espindola468b8682015-04-01 14:44:59 +00002764void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00002765
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002766/// When we see the block for a function body, remember where it is and then
2767/// skip it. This lets us lazily deserialize the functions.
2768std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002769 // Get the function we are talking about.
2770 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002771 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002772
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002773 Function *Fn = FunctionsWithBodies.back();
2774 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002775
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002776 // Save the current stream state.
2777 uint64_t CurBit = Stream.GetCurrentBitNo();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00002778 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002779
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002780 // Skip over the function block for now.
2781 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002782 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002783 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002784}
2785
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002786std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002787 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002788 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002789 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002790 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002791
2792 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002793 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002794 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002795 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00002796 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002797 }
2798
2799 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00002800 for (GlobalVariable &GV : TheModule->globals())
2801 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00002802
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002803 // Force deallocation of memory for these vectors to favor the client that
2804 // want lazy deserialization.
2805 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
2806 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002807 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002808}
2809
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002810std::error_code BitcodeReader::parseModule(bool Resume,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002811 bool ShouldLazyLoadMetadata) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002812 if (Resume)
2813 Stream.JumpToBit(NextUnreadBit);
2814 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002815 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002816
Chris Lattner1314b992007-04-22 06:23:29 +00002817 SmallVector<uint64_t, 64> Record;
2818 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00002819 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00002820
2821 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00002822 while (1) {
2823 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00002824
Chris Lattner27d38752013-01-20 02:13:19 +00002825 switch (Entry.Kind) {
2826 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002827 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002828 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002829 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00002830
Chris Lattner27d38752013-01-20 02:13:19 +00002831 case BitstreamEntry::SubBlock:
2832 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00002833 default: // Skip unknown content.
2834 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002835 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002836 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002837 case bitc::BLOCKINFO_BLOCK_ID:
2838 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002839 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00002840 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002841 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002842 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002843 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00002844 break;
Bill Wendlingba629332013-02-10 23:24:25 +00002845 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002846 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002847 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00002848 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00002849 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002850 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002851 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00002852 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002853 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002854 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002855 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002856 SeenValueSymbolTable = true;
Chris Lattnerccaa4482007-04-23 21:26:05 +00002857 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002858 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002859 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002860 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002861 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002862 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002863 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00002864 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00002865 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
2866 if (std::error_code EC = rememberAndSkipMetadata())
2867 return EC;
2868 break;
2869 }
2870 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002871 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002872 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00002873 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002874 case bitc::FUNCTION_BLOCK_ID:
2875 // If this is the first function body we've seen, reverse the
2876 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002877 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002878 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002879 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002880 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002881 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002882 }
Joe Abbey97b7a172013-02-06 22:14:06 +00002883
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002884 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002885 return EC;
Rafael Espindola1c863ca2015-06-22 18:06:15 +00002886 // Suspend parsing when we reach the function bodies. Subsequent
2887 // materialization calls will resume it when necessary. If the bitcode
2888 // file is old, the symbol table will be at the end instead and will not
2889 // have been seen yet. In this case, just finish the parse now.
2890 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002891 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002892 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00002893 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00002894 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00002895 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002896 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00002897 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00002898 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002899 }
2900 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00002901
Chris Lattner27d38752013-01-20 02:13:19 +00002902 case BitstreamEntry::Record:
2903 // The interesting case.
2904 break;
Chris Lattner1314b992007-04-22 06:23:29 +00002905 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002906
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002907
Chris Lattner1314b992007-04-22 06:23:29 +00002908 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00002909 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattner1314b992007-04-22 06:23:29 +00002910 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002911 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00002912 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002913 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002914 // Only version #0 and #1 are supported so far.
2915 unsigned module_version = Record[0];
2916 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002917 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002918 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002919 case 0:
2920 UseRelativeIDs = false;
2921 break;
2922 case 1:
2923 UseRelativeIDs = true;
2924 break;
2925 }
Chris Lattner1314b992007-04-22 06:23:29 +00002926 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00002927 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002928 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002929 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002930 if (convertToString(Record, 0, S))
2931 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002932 TheModule->setTargetTriple(S);
2933 break;
2934 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002935 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002936 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002937 if (convertToString(Record, 0, S))
2938 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002939 TheModule->setDataLayout(S);
2940 break;
2941 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002942 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002943 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002944 if (convertToString(Record, 0, S))
2945 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002946 TheModule->setModuleInlineAsm(S);
2947 break;
2948 }
Bill Wendling706d3d62012-11-28 08:41:48 +00002949 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
2950 // FIXME: Remove in 4.0.
2951 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002952 if (convertToString(Record, 0, S))
2953 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00002954 // Ignore value.
2955 break;
2956 }
Chris Lattnere14cb882007-05-04 19:11:41 +00002957 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00002958 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002959 if (convertToString(Record, 0, S))
2960 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00002961 SectionTable.push_back(S);
2962 break;
2963 }
Gordon Henriksend930f912008-08-17 18:44:35 +00002964 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00002965 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002966 if (convertToString(Record, 0, S))
2967 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00002968 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00002969 break;
2970 }
David Majnemerdad0a642014-06-27 18:19:56 +00002971 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
2972 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002973 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00002974 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
2975 unsigned ComdatNameSize = Record[1];
2976 std::string ComdatName;
2977 ComdatName.reserve(ComdatNameSize);
2978 for (unsigned i = 0; i != ComdatNameSize; ++i)
2979 ComdatName += (char)Record[2 + i];
2980 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
2981 C->setSelectionKind(SK);
2982 ComdatList.push_back(C);
2983 break;
2984 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00002985 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00002986 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00002987 // unnamed_addr, externally_initialized, dllstorageclass,
2988 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00002989 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00002990 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002991 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002992 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002993 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002994 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00002995 bool isConstant = Record[1] & 1;
2996 bool explicitType = Record[1] & 2;
2997 unsigned AddressSpace;
2998 if (explicitType) {
2999 AddressSpace = Record[1] >> 2;
3000 } else {
3001 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003002 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003003 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3004 Ty = cast<PointerType>(Ty)->getElementType();
3005 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003006
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003007 uint64_t RawLinkage = Record[3];
3008 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003009 unsigned Alignment;
3010 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3011 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003012 std::string Section;
3013 if (Record[5]) {
3014 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003015 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003016 Section = SectionTable[Record[5]-1];
3017 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003018 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003019 // Local linkage must have default visibility.
3020 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3021 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003022 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003023
3024 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003025 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003026 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003027
Rafael Espindola45e6c192011-01-08 16:42:36 +00003028 bool UnnamedAddr = false;
3029 if (Record.size() > 8)
3030 UnnamedAddr = Record[8];
3031
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003032 bool ExternallyInitialized = false;
3033 if (Record.size() > 9)
3034 ExternallyInitialized = Record[9];
3035
Chris Lattner1314b992007-04-22 06:23:29 +00003036 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003037 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003038 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003039 NewGV->setAlignment(Alignment);
3040 if (!Section.empty())
3041 NewGV->setSection(Section);
3042 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003043 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003044
Nico Rieck7157bb72014-01-14 15:22:47 +00003045 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003046 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003047 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003048 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003049
Chris Lattnerccaa4482007-04-23 21:26:05 +00003050 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003051
Chris Lattner47d131b2007-04-24 00:18:21 +00003052 // Remember which value to use for the global initializer.
3053 if (unsigned InitID = Record[2])
3054 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003055
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003056 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003057 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003058 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003059 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003060 NewGV->setComdat(ComdatList[ComdatID - 1]);
3061 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003062 } else if (hasImplicitComdat(RawLinkage)) {
3063 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3064 }
Chris Lattner1314b992007-04-22 06:23:29 +00003065 break;
3066 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003067 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003068 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003069 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003070 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003071 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003072 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003073 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003074 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003075 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003076 if (auto *PTy = dyn_cast<PointerType>(Ty))
3077 Ty = PTy->getElementType();
3078 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003079 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003080 return error("Invalid type for value");
Chris Lattner1314b992007-04-22 06:23:29 +00003081
Gabor Greife9ecc682008-04-06 20:25:17 +00003082 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3083 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003084
Sandeep Patel68c5f472009-09-02 08:44:58 +00003085 Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003086 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003087 uint64_t RawLinkage = Record[3];
3088 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003089 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003090
JF Bastien30bf96b2015-02-22 19:32:03 +00003091 unsigned Alignment;
3092 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3093 return EC;
3094 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003095 if (Record[6]) {
3096 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003097 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003098 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003099 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003100 // Local linkage must have default visibility.
3101 if (!Func->hasLocalLinkage())
3102 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003103 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003104 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003105 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003106 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003107 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003108 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003109 bool UnnamedAddr = false;
3110 if (Record.size() > 9)
3111 UnnamedAddr = Record[9];
3112 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003113 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003114 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003115
3116 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003117 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003118 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003119 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003120
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003121 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003122 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003123 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003124 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003125 Func->setComdat(ComdatList[ComdatID - 1]);
3126 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003127 } else if (hasImplicitComdat(RawLinkage)) {
3128 Func->setComdat(reinterpret_cast<Comdat *>(1));
3129 }
David Majnemerdad0a642014-06-27 18:19:56 +00003130
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003131 if (Record.size() > 13 && Record[13] != 0)
3132 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3133
David Majnemer7fddecc2015-06-17 20:52:32 +00003134 if (Record.size() > 14 && Record[14] != 0)
3135 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3136
Chris Lattnerccaa4482007-04-23 21:26:05 +00003137 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003138
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003139 // If this is a function with a body, remember the prototype we are
3140 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003141 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003142 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003143 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003144 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003145 }
Chris Lattner1314b992007-04-22 06:23:29 +00003146 break;
3147 }
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003148 // ALIAS: [alias type, aliasee val#, linkage]
Nico Rieck7157bb72014-01-14 15:22:47 +00003149 // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
Chris Lattner831d4202007-04-26 03:27:58 +00003150 case bitc::MODULE_CODE_ALIAS: {
Chris Lattner44c17072007-04-26 02:46:40 +00003151 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003152 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003153 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003154 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003155 return error("Invalid record");
Rafael Espindolaa8004452014-05-16 14:22:33 +00003156 auto *PTy = dyn_cast<PointerType>(Ty);
3157 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003158 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003159
Rafael Espindolaa8004452014-05-16 14:22:33 +00003160 auto *NewGA =
David Blaikief64246b2015-04-29 21:22:39 +00003161 GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003162 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003163 // Local linkage must have default visibility.
3164 if (Record.size() > 3 && !NewGA->hasLocalLinkage())
3165 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003166 NewGA->setVisibility(getDecodedVisibility(Record[3]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003167 if (Record.size() > 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003168 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003169 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003170 upgradeDLLImportExportLinkage(NewGA, Record[2]);
Rafael Espindola59f7eba2014-05-28 18:15:43 +00003171 if (Record.size() > 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003172 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
Rafael Espindola42a4c9f2014-06-06 01:20:28 +00003173 if (Record.size() > 6)
NAKAMURA Takumi32c87ac2014-10-29 23:44:35 +00003174 NewGA->setUnnamedAddr(Record[6]);
Chris Lattner44c17072007-04-26 02:46:40 +00003175 ValueList.push_back(NewGA);
3176 AliasInits.push_back(std::make_pair(NewGA, Record[1]));
3177 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003178 }
Chris Lattner831d4202007-04-26 03:27:58 +00003179 /// MODULE_CODE_PURGEVALS: [numvals]
3180 case bitc::MODULE_CODE_PURGEVALS:
3181 // Trim down the value list to the specified size.
3182 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003183 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003184 ValueList.shrinkTo(Record[0]);
3185 break;
3186 }
Chris Lattner1314b992007-04-22 06:23:29 +00003187 Record.clear();
3188 }
Chris Lattner1314b992007-04-22 06:23:29 +00003189}
3190
Rafael Espindola1aabf982015-06-16 23:29:49 +00003191std::error_code
3192BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3193 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003194 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003195
Rafael Espindola1aabf982015-06-16 23:29:49 +00003196 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003197 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003198
Chris Lattner1314b992007-04-22 06:23:29 +00003199 // Sniff for the signature.
3200 if (Stream.Read(8) != 'B' ||
3201 Stream.Read(8) != 'C' ||
3202 Stream.Read(4) != 0x0 ||
3203 Stream.Read(4) != 0xC ||
3204 Stream.Read(4) != 0xE ||
3205 Stream.Read(4) != 0xD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003206 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003207
Chris Lattner1314b992007-04-22 06:23:29 +00003208 // We expect a number of well-defined blocks, though we don't necessarily
3209 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003210 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003211 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003212 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003213 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003214 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003215
Chris Lattner27d38752013-01-20 02:13:19 +00003216 BitstreamEntry Entry =
3217 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003218
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003219 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003220 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003221
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003222 if (Entry.ID == bitc::MODULE_BLOCK_ID)
3223 return parseModule(false, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003224
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003225 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003226 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003227 }
Chris Lattner1314b992007-04-22 06:23:29 +00003228}
Chris Lattner6694f602007-04-29 07:54:31 +00003229
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003230ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003231 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003232 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003233
3234 SmallVector<uint64_t, 64> Record;
3235
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003236 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003237 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003238 while (1) {
3239 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003240
Chris Lattner27d38752013-01-20 02:13:19 +00003241 switch (Entry.Kind) {
3242 case BitstreamEntry::SubBlock: // Handled for us already.
3243 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003244 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003245 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003246 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003247 case BitstreamEntry::Record:
3248 // The interesting case.
3249 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003250 }
3251
3252 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003253 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003254 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003255 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003256 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003257 if (convertToString(Record, 0, S))
3258 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003259 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003260 break;
3261 }
3262 }
3263 Record.clear();
3264 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003265 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003266}
3267
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003268ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003269 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003270 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003271
3272 // Sniff for the signature.
3273 if (Stream.Read(8) != 'B' ||
3274 Stream.Read(8) != 'C' ||
3275 Stream.Read(4) != 0x0 ||
3276 Stream.Read(4) != 0xC ||
3277 Stream.Read(4) != 0xE ||
3278 Stream.Read(4) != 0xD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003279 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003280
3281 // We expect a number of well-defined blocks, though we don't necessarily
3282 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003283 while (1) {
3284 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003285
Chris Lattner27d38752013-01-20 02:13:19 +00003286 switch (Entry.Kind) {
3287 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003288 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003289 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003290 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003291
Chris Lattner27d38752013-01-20 02:13:19 +00003292 case BitstreamEntry::SubBlock:
3293 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003294 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003295
Chris Lattner27d38752013-01-20 02:13:19 +00003296 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003297 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003298 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003299 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003300
Chris Lattner27d38752013-01-20 02:13:19 +00003301 case BitstreamEntry::Record:
3302 Stream.skipRecord(Entry.ID);
3303 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003304 }
3305 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003306}
3307
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003308/// Parse metadata attachments.
3309std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003310 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003311 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003312
Devang Patelaf206b82009-09-18 19:26:43 +00003313 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003314 while (1) {
3315 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003316
Chris Lattner27d38752013-01-20 02:13:19 +00003317 switch (Entry.Kind) {
3318 case BitstreamEntry::SubBlock: // Handled for us already.
3319 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003320 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003321 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003322 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003323 case BitstreamEntry::Record:
3324 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003325 break;
3326 }
Chris Lattner27d38752013-01-20 02:13:19 +00003327
Devang Patelaf206b82009-09-18 19:26:43 +00003328 // Read a metadata attachment record.
3329 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003330 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003331 default: // Default behavior: ignore.
3332 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003333 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003334 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003335 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003336 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003337 if (RecordLength % 2 == 0) {
3338 // A function attachment.
3339 for (unsigned I = 0; I != RecordLength; I += 2) {
3340 auto K = MDKindMap.find(Record[I]);
3341 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003342 return error("Invalid ID");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003343 Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
3344 F.setMetadata(K->second, cast<MDNode>(MD));
3345 }
3346 continue;
3347 }
3348
3349 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003350 Instruction *Inst = InstructionList[Record[0]];
3351 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003352 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003353 DenseMap<unsigned, unsigned>::iterator I =
3354 MDKindMap.find(Kind);
3355 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003356 return error("Invalid ID");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003357 Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
3358 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003359 // Drop the attachment. This used to be legal, but there's no
3360 // upgrade path.
3361 break;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003362 Inst->setMetadata(I->second, cast<MDNode>(Node));
Manman Ren209b17c2013-09-28 00:22:27 +00003363 if (I->second == LLVMContext::MD_tbaa)
3364 InstsWithTBAATag.push_back(Inst);
Devang Patelaf206b82009-09-18 19:26:43 +00003365 }
3366 break;
3367 }
3368 }
3369 }
Devang Patelaf206b82009-09-18 19:26:43 +00003370}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003371
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003372static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003373 Type *ValType, Type *PtrType) {
3374 if (!isa<PointerType>(PtrType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003375 return error(DH, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003376 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3377
3378 if (ValType && ValType != ElemType)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003379 return error(DH, "Explicit load/store type does not match pointee type of "
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003380 "pointer operand");
3381 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003382 return error(DH, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003383 return std::error_code();
3384}
3385
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003386/// Lazily parse the specified function body block.
3387std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003388 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003389 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003390
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003391 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003392 unsigned ModuleValueListSize = ValueList.size();
Dan Gohman26d837d2010-08-25 20:22:53 +00003393 unsigned ModuleMDValueListSize = MDValueList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003394
Chris Lattner85b7b402007-05-01 05:52:21 +00003395 // Add all the function arguments to the value table.
3396 for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
3397 ValueList.push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003398
Chris Lattner83930552007-05-01 07:01:57 +00003399 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003400 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003401 unsigned CurBBNo = 0;
3402
Chris Lattner07d09ed2010-04-03 02:17:50 +00003403 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003404 auto getLastInstruction = [&]() -> Instruction * {
3405 if (CurBB && !CurBB->empty())
3406 return &CurBB->back();
3407 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3408 !FunctionBBs[CurBBNo - 1]->empty())
3409 return &FunctionBBs[CurBBNo - 1]->back();
3410 return nullptr;
3411 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003412
Chris Lattner85b7b402007-05-01 05:52:21 +00003413 // Read all the records.
3414 SmallVector<uint64_t, 64> Record;
3415 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003416 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003417
Chris Lattner27d38752013-01-20 02:13:19 +00003418 switch (Entry.Kind) {
3419 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003420 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003421 case BitstreamEntry::EndBlock:
3422 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00003423
Chris Lattner27d38752013-01-20 02:13:19 +00003424 case BitstreamEntry::SubBlock:
3425 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00003426 default: // Skip unknown content.
3427 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003428 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003429 break;
3430 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003431 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003432 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00003433 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00003434 break;
3435 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003436 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003437 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00003438 break;
Devang Patelaf206b82009-09-18 19:26:43 +00003439 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003440 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003441 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003442 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003443 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003444 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003445 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00003446 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003447 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003448 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003449 return EC;
3450 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003451 }
3452 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003453
Chris Lattner27d38752013-01-20 02:13:19 +00003454 case BitstreamEntry::Record:
3455 // The interesting case.
3456 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00003457 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003458
Chris Lattner85b7b402007-05-01 05:52:21 +00003459 // Read a record.
3460 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00003461 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00003462 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00003463 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00003464 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003465 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003466 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00003467 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003468 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00003469 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003470 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003471
3472 // See if anything took the address of blocks in this function.
3473 auto BBFRI = BasicBlockFwdRefs.find(F);
3474 if (BBFRI == BasicBlockFwdRefs.end()) {
3475 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
3476 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
3477 } else {
3478 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003479 // Check for invalid basic block references.
3480 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003481 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003482 assert(!BBRefs.empty() && "Unexpected empty array");
3483 assert(!BBRefs.front() && "Invalid reference to entry block");
3484 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
3485 ++I)
3486 if (I < RE && BBRefs[I]) {
3487 BBRefs[I]->insertInto(F);
3488 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003489 } else {
3490 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
3491 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003492
3493 // Erase from the table.
3494 BasicBlockFwdRefs.erase(BBFRI);
3495 }
3496
Chris Lattner83930552007-05-01 07:01:57 +00003497 CurBB = FunctionBBs[0];
3498 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003499 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003500
Chris Lattner07d09ed2010-04-03 02:17:50 +00003501 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
3502 // This record indicates that the last instruction is at the same
3503 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003504 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003505
Craig Topper2617dcc2014-04-15 06:32:26 +00003506 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003507 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00003508 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003509 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003510 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003511
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00003512 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003513 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00003514 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003515 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003516
Chris Lattner07d09ed2010-04-03 02:17:50 +00003517 unsigned Line = Record[0], Col = Record[1];
3518 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003519
Craig Topper2617dcc2014-04-15 06:32:26 +00003520 MDNode *Scope = nullptr, *IA = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003521 if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
3522 if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
3523 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
3524 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00003525 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00003526 continue;
3527 }
3528
Chris Lattnere9759c22007-05-06 00:21:25 +00003529 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
3530 unsigned OpNum = 0;
3531 Value *LHS, *RHS;
3532 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003533 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00003534 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003535 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003536
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003537 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00003538 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003539 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00003540 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00003541 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00003542 if (OpNum < Record.size()) {
3543 if (Opc == Instruction::Add ||
3544 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003545 Opc == Instruction::Mul ||
3546 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00003547 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003548 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00003549 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00003550 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00003551 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00003552 Opc == Instruction::UDiv ||
3553 Opc == Instruction::LShr ||
3554 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00003555 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00003556 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003557 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00003558 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003559 if (FMF.any())
3560 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00003561 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00003562
Dan Gohman1b849082009-09-07 23:54:19 +00003563 }
Chris Lattner85b7b402007-05-01 05:52:21 +00003564 break;
3565 }
Chris Lattnere9759c22007-05-06 00:21:25 +00003566 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
3567 unsigned OpNum = 0;
3568 Value *Op;
3569 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
3570 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003571 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003572
Chris Lattner229907c2011-07-18 04:54:35 +00003573 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003574 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003575 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003576 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00003577 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00003578 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
3579 if (Temp) {
3580 InstructionList.push_back(Temp);
3581 CurBB->getInstList().push_back(Temp);
3582 }
3583 } else {
3584 I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
3585 }
Devang Patelaf206b82009-09-18 19:26:43 +00003586 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00003587 break;
3588 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00003589 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
3590 case bitc::FUNC_CODE_INST_GEP_OLD:
3591 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003592 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00003593
3594 Type *Ty;
3595 bool InBounds;
3596
3597 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
3598 InBounds = Record[OpNum++];
3599 Ty = getTypeByID(Record[OpNum++]);
3600 } else {
3601 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
3602 Ty = nullptr;
3603 }
3604
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003605 Value *BasePtr;
3606 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003607 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003608
David Blaikie60310f22015-05-08 00:42:26 +00003609 if (!Ty)
3610 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
3611 ->getElementType();
3612 else if (Ty !=
3613 cast<SequentialType>(BasePtr->getType()->getScalarType())
3614 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003615 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00003616 "Explicit gep type does not match pointee type of pointer operand");
3617
Chris Lattner5285b5e2007-05-02 05:46:45 +00003618 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003619 while (OpNum != Record.size()) {
3620 Value *Op;
3621 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003622 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003623 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003624 }
3625
David Blaikie096b1da2015-03-14 19:53:33 +00003626 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00003627
Devang Patelaf206b82009-09-18 19:26:43 +00003628 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00003629 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00003630 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003631 break;
3632 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003633
Dan Gohman1ecaf452008-05-31 00:58:22 +00003634 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
3635 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003636 unsigned OpNum = 0;
3637 Value *Agg;
3638 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003639 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003640
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003641 unsigned RecSize = Record.size();
3642 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003643 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003644
Dan Gohman1ecaf452008-05-31 00:58:22 +00003645 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003646 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003647 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003648 bool IsArray = CurTy->isArrayTy();
3649 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003650 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003651
3652 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003653 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003654 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003655 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003656 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003657 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003658 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003659 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003660 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003661
3662 if (IsStruct)
3663 CurTy = CurTy->subtypes()[Index];
3664 else
3665 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003666 }
3667
Jay Foad57aa6362011-07-13 10:26:04 +00003668 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003669 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003670 break;
3671 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003672
Dan Gohman1ecaf452008-05-31 00:58:22 +00003673 case bitc::FUNC_CODE_INST_INSERTVAL: {
3674 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00003675 unsigned OpNum = 0;
3676 Value *Agg;
3677 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003678 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003679 Value *Val;
3680 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003681 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00003682
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003683 unsigned RecSize = Record.size();
3684 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003685 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003686
Dan Gohman1ecaf452008-05-31 00:58:22 +00003687 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003688 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00003689 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003690 bool IsArray = CurTy->isArrayTy();
3691 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00003692 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003693
3694 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003695 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00003696 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003697 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003698 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003699 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003700 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003701 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003702
Dan Gohman1ecaf452008-05-31 00:58:22 +00003703 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00003704 if (IsStruct)
3705 CurTy = CurTy->subtypes()[Index];
3706 else
3707 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00003708 }
3709
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003710 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003711 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00003712
Jay Foad57aa6362011-07-13 10:26:04 +00003713 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00003714 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00003715 break;
3716 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003717
Chris Lattnere9759c22007-05-06 00:21:25 +00003718 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00003719 // obsolete form of select
3720 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00003721 unsigned OpNum = 0;
3722 Value *TrueVal, *FalseVal, *Cond;
3723 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003724 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
3725 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003726 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003727
Dan Gohmanc5d28922008-09-16 01:01:33 +00003728 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003729 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00003730 break;
3731 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Dan Gohmanc5d28922008-09-16 01:01:33 +00003733 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
3734 // new form of select
3735 // handles select i1 or select [N x i1]
3736 unsigned OpNum = 0;
3737 Value *TrueVal, *FalseVal, *Cond;
3738 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003739 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00003740 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003741 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00003742
3743 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00003744 if (VectorType* vector_type =
3745 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00003746 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003747 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003748 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00003749 } else {
3750 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003751 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003752 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003753 }
3754
Gabor Greife9ecc682008-04-06 20:25:17 +00003755 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00003756 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003757 break;
3758 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003759
Chris Lattner1fc27f02007-05-02 05:16:49 +00003760 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003761 unsigned OpNum = 0;
3762 Value *Vec, *Idx;
3763 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003764 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003765 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003766 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003767 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00003768 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003769 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003770 break;
3771 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003772
Chris Lattner1fc27f02007-05-02 05:16:49 +00003773 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00003774 unsigned OpNum = 0;
3775 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003776 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003777 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003778 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003779 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003780 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00003781 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00003782 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003783 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003784 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00003785 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003786 break;
3787 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003788
Chris Lattnere9759c22007-05-06 00:21:25 +00003789 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
3790 unsigned OpNum = 0;
3791 Value *Vec1, *Vec2, *Mask;
3792 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00003793 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003794 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00003795
Mon P Wang25f01062008-11-10 04:46:22 +00003796 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003797 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00003798 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003799 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00003800 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00003801 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00003802 break;
3803 }
Mon P Wang25f01062008-11-10 04:46:22 +00003804
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003805 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
3806 // Old form of ICmp/FCmp returning bool
3807 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
3808 // both legal on vectors but had different behaviour.
3809 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
3810 // FCmp/ICmp returning bool or vector of bool
3811
Chris Lattnerdf1233d2007-05-06 00:00:00 +00003812 unsigned OpNum = 0;
3813 Value *LHS, *RHS;
3814 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00003815 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
3816 return error("Invalid record");
3817
3818 unsigned PredVal = Record[OpNum];
3819 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
3820 FastMathFlags FMF;
3821 if (IsFP && Record.size() > OpNum+1)
3822 FMF = getDecodedFastMathFlags(Record[++OpNum]);
3823
3824 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003825 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003826
Duncan Sands9dff9be2010-02-15 16:12:20 +00003827 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00003828 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003829 else
James Molloy88eb5352015-07-10 12:52:00 +00003830 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
3831
3832 if (FMF.any())
3833 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00003834 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00003835 break;
3836 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00003837
Chris Lattnere53603e2007-05-02 04:27:25 +00003838 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00003839 {
3840 unsigned Size = Record.size();
3841 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00003842 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003843 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00003844 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003845 }
Devang Patelbbfd8742008-02-26 01:29:32 +00003846
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003847 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00003848 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00003849 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003850 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00003851 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003852 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003853
Chris Lattnerf1c87102011-06-17 18:09:11 +00003854 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003855 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00003856 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00003857 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003858 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00003859 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003860 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003861 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003862 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003863 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00003864
Devang Patelaf206b82009-09-18 19:26:43 +00003865 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00003866 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003867 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00003868 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00003869 else {
3870 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00003871 Value *Cond = getValue(Record, 2, NextValueNo,
3872 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00003873 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003874 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00003875 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003876 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00003877 }
3878 break;
3879 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00003880 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003881 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003882 return error("Invalid record");
3883 unsigned Idx = 0;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003884 Value *CleanupPad = getValue(Record, Idx++, NextValueNo,
3885 Type::getTokenTy(Context), OC_CleanupPad);
3886 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00003887 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003888 BasicBlock *UnwindDest = nullptr;
3889 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00003890 UnwindDest = getBasicBlock(Record[Idx++]);
3891 if (!UnwindDest)
3892 return error("Invalid record");
3893 }
3894
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003895 I = CleanupReturnInst::Create(cast<CleanupPadInst>(CleanupPad),
3896 UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00003897 InstructionList.push_back(I);
3898 break;
3899 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003900 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
3901 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00003902 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003903 unsigned Idx = 0;
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003904 Value *CatchPad = getValue(Record, Idx++, NextValueNo,
3905 Type::getTokenTy(Context), OC_CatchPad);
3906 if (!CatchPad)
3907 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003908 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00003909 if (!BB)
3910 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00003911
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003912 I = CatchReturnInst::Create(cast<CatchPadInst>(CatchPad), BB);
David Majnemer654e1302015-07-31 17:58:14 +00003913 InstructionList.push_back(I);
3914 break;
3915 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003916 case bitc::FUNC_CODE_INST_CATCHPAD: { // CATCHPAD: [bb#,bb#,num,(ty,val)*]
3917 if (Record.size() < 3)
David Majnemer654e1302015-07-31 17:58:14 +00003918 return error("Invalid record");
3919 unsigned Idx = 0;
David Majnemer654e1302015-07-31 17:58:14 +00003920 BasicBlock *NormalBB = getBasicBlock(Record[Idx++]);
3921 if (!NormalBB)
3922 return error("Invalid record");
3923 BasicBlock *UnwindBB = getBasicBlock(Record[Idx++]);
3924 if (!UnwindBB)
3925 return error("Invalid record");
3926 unsigned NumArgOperands = Record[Idx++];
3927 SmallVector<Value *, 2> Args;
3928 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3929 Value *Val;
3930 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3931 return error("Invalid record");
3932 Args.push_back(Val);
3933 }
3934 if (Record.size() != Idx)
3935 return error("Invalid record");
3936
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003937 I = CatchPadInst::Create(NormalBB, UnwindBB, Args);
David Majnemer654e1302015-07-31 17:58:14 +00003938 InstructionList.push_back(I);
3939 break;
3940 }
3941 case bitc::FUNC_CODE_INST_TERMINATEPAD: { // TERMINATEPAD: [bb#,num,(ty,val)*]
3942 if (Record.size() < 1)
3943 return error("Invalid record");
3944 unsigned Idx = 0;
3945 bool HasUnwindDest = !!Record[Idx++];
3946 BasicBlock *UnwindDest = nullptr;
3947 if (HasUnwindDest) {
3948 if (Idx == Record.size())
3949 return error("Invalid record");
3950 UnwindDest = getBasicBlock(Record[Idx++]);
3951 if (!UnwindDest)
3952 return error("Invalid record");
3953 }
3954 unsigned NumArgOperands = Record[Idx++];
3955 SmallVector<Value *, 2> Args;
3956 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3957 Value *Val;
3958 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3959 return error("Invalid record");
3960 Args.push_back(Val);
3961 }
3962 if (Record.size() != Idx)
3963 return error("Invalid record");
3964
3965 I = TerminatePadInst::Create(Context, UnwindDest, Args);
3966 InstructionList.push_back(I);
3967 break;
3968 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003969 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // CLEANUPPAD: [num,(ty,val)*]
3970 if (Record.size() < 1)
David Majnemer654e1302015-07-31 17:58:14 +00003971 return error("Invalid record");
3972 unsigned Idx = 0;
David Majnemer654e1302015-07-31 17:58:14 +00003973 unsigned NumArgOperands = Record[Idx++];
3974 SmallVector<Value *, 2> Args;
3975 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
3976 Value *Val;
3977 if (getValueTypePair(Record, Idx, NextValueNo, Val))
3978 return error("Invalid record");
3979 Args.push_back(Val);
3980 }
3981 if (Record.size() != Idx)
3982 return error("Invalid record");
3983
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00003984 I = CleanupPadInst::Create(Context, Args);
David Majnemer654e1302015-07-31 17:58:14 +00003985 InstructionList.push_back(I);
3986 break;
3987 }
3988 case bitc::FUNC_CODE_INST_CATCHENDPAD: { // CATCHENDPADINST: [bb#] or []
3989 if (Record.size() > 1)
3990 return error("Invalid record");
3991 BasicBlock *BB = nullptr;
3992 if (Record.size() == 1) {
3993 BB = getBasicBlock(Record[0]);
3994 if (!BB)
3995 return error("Invalid record");
3996 }
3997 I = CatchEndPadInst::Create(Context, BB);
3998 InstructionList.push_back(I);
3999 break;
4000 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004001 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004002 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004003 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004004 // "New" SwitchInst format with case ranges. The changes to write this
4005 // format were reverted but we still recognize bitcode that uses it.
4006 // Hopefully someday we will have support for case ranges and can use
4007 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004008
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004009 Type *OpTy = getTypeByID(Record[1]);
4010 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4011
Jan Wen Voungafaced02012-10-11 20:20:40 +00004012 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004013 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004014 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004015 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004016
4017 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004018
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004019 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4020 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004021
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004022 unsigned CurIdx = 5;
4023 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004024 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004025 unsigned NumItems = Record[CurIdx++];
4026 for (unsigned ci = 0; ci != NumItems; ++ci) {
4027 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004028
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004029 APInt Low;
4030 unsigned ActiveWords = 1;
4031 if (ValueBitWidth > 64)
4032 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004033 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004034 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004035 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004036
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004037 if (!isSingleNumber) {
4038 ActiveWords = 1;
4039 if (ValueBitWidth > 64)
4040 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004041 APInt High = readWideAPInt(
4042 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004043 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004044
4045 // FIXME: It is not clear whether values in the range should be
4046 // compared as signed or unsigned values. The partially
4047 // implemented changes that used this format in the past used
4048 // unsigned comparisons.
4049 for ( ; Low.ule(High); ++Low)
4050 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004051 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004052 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004053 }
4054 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004055 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4056 cve = CaseVals.end(); cvi != cve; ++cvi)
4057 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004058 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004059 I = SI;
4060 break;
4061 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004062
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004063 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004064
Chris Lattner5285b5e2007-05-02 05:46:45 +00004065 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004066 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004067 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004068 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004069 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004070 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004071 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004072 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004073 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004074 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004075 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004076 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004077 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4078 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004079 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004080 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004081 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004082 }
4083 SI->addCase(CaseVal, DestBB);
4084 }
4085 I = SI;
4086 break;
4087 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004088 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004089 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004090 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004091 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004092 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004093 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004094 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004095 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004096 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004097 InstructionList.push_back(IBI);
4098 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4099 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4100 IBI->addDestination(DestBB);
4101 } else {
4102 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004103 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004104 }
4105 }
4106 I = IBI;
4107 break;
4108 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004109
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004110 case bitc::FUNC_CODE_INST_INVOKE: {
4111 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004112 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004113 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004114 unsigned OpNum = 0;
4115 AttributeSet PAL = getAttributes(Record[OpNum++]);
4116 unsigned CCInfo = Record[OpNum++];
4117 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4118 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004119
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004120 FunctionType *FTy = nullptr;
4121 if (CCInfo >> 13 & 1 &&
4122 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004123 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004124
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004125 Value *Callee;
4126 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004127 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004128
Chris Lattner229907c2011-07-18 04:54:35 +00004129 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004130 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004131 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004132 if (!FTy) {
4133 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4134 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004135 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004136 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004137 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004138 "callee operand");
4139 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004140 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004141
Chris Lattner5285b5e2007-05-02 05:46:45 +00004142 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004143 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004144 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4145 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004146 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004147 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004148 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004149
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004150 if (!FTy->isVarArg()) {
4151 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004152 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004153 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004154 // Read type/value pairs for varargs params.
4155 while (OpNum != Record.size()) {
4156 Value *Op;
4157 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004158 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004159 Ops.push_back(Op);
4160 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004161 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004162
Jay Foad5bd375a2011-07-15 08:37:34 +00004163 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
Devang Patelaf206b82009-09-18 19:26:43 +00004164 InstructionList.push_back(I);
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004165 cast<InvokeInst>(I)
4166 ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004167 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004168 break;
4169 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004170 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4171 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004172 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004173 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004174 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004175 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004176 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004177 break;
4178 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004179 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004180 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004181 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004182 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004183 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004184 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004185 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004186 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004187 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004188 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004189
Jay Foad52131342011-03-30 11:28:46 +00004190 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004191 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004192
Chris Lattnere14cb882007-05-04 19:11:41 +00004193 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004194 Value *V;
4195 // With the new function encoding, it is possible that operands have
4196 // negative IDs (for forward references). Use a signed VBR
4197 // representation to keep the encoding small.
4198 if (UseRelativeIDs)
4199 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4200 else
4201 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004202 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004203 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004204 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004205 PN->addIncoming(V, BB);
4206 }
4207 I = PN;
4208 break;
4209 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004210
David Majnemer7fddecc2015-06-17 20:52:32 +00004211 case bitc::FUNC_CODE_INST_LANDINGPAD:
4212 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004213 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4214 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004215 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4216 if (Record.size() < 3)
4217 return error("Invalid record");
4218 } else {
4219 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4220 if (Record.size() < 4)
4221 return error("Invalid record");
4222 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004223 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004224 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004225 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004226 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4227 Value *PersFn = nullptr;
4228 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4229 return error("Invalid record");
4230
4231 if (!F->hasPersonalityFn())
4232 F->setPersonalityFn(cast<Constant>(PersFn));
4233 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4234 return error("Personality function mismatch");
4235 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004236
4237 bool IsCleanup = !!Record[Idx++];
4238 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004239 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004240 LP->setCleanup(IsCleanup);
4241 for (unsigned J = 0; J != NumClauses; ++J) {
4242 LandingPadInst::ClauseType CT =
4243 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4244 Value *Val;
4245
4246 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4247 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004248 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004249 }
4250
4251 assert((CT != LandingPadInst::Catch ||
4252 !isa<ArrayType>(Val->getType())) &&
4253 "Catch clause has a invalid type!");
4254 assert((CT != LandingPadInst::Filter ||
4255 isa<ArrayType>(Val->getType())) &&
4256 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004257 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004258 }
4259
4260 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004261 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004262 break;
4263 }
4264
Chris Lattnerf1c87102011-06-17 18:09:11 +00004265 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4266 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004267 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004268 uint64_t AlignRecord = Record[3];
4269 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004270 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Bob Wilson043ee652015-07-28 04:05:45 +00004271 // Reserve bit 7 for SwiftError flag.
4272 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
David Blaikiebdb49102015-04-28 16:51:01 +00004273 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004274 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004275 Type *Ty = getTypeByID(Record[0]);
4276 if ((AlignRecord & ExplicitTypeMask) == 0) {
4277 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4278 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004279 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004280 Ty = PTy->getElementType();
4281 }
4282 Type *OpTy = getTypeByID(Record[1]);
4283 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004284 unsigned Align;
4285 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004286 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004287 return EC;
4288 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004289 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004290 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004291 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004292 AI->setUsedWithInAlloca(InAlloca);
4293 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004294 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004295 break;
4296 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004297 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004298 unsigned OpNum = 0;
4299 Value *Op;
4300 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004301 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004302 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004303
4304 Type *Ty = nullptr;
4305 if (OpNum + 3 == Record.size())
4306 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004307 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004308 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004309 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004310 if (!Ty)
4311 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004312
JF Bastien30bf96b2015-02-22 19:32:03 +00004313 unsigned Align;
4314 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4315 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004316 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004317
Devang Patelaf206b82009-09-18 19:26:43 +00004318 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004319 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004320 }
Eli Friedman59b66882011-08-09 23:02:53 +00004321 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4322 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4323 unsigned OpNum = 0;
4324 Value *Op;
4325 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004326 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004327 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004328
David Blaikie85035652015-02-25 01:07:20 +00004329 Type *Ty = nullptr;
4330 if (OpNum + 5 == Record.size())
4331 Ty = getTypeByID(Record[OpNum++]);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004332 if (std::error_code EC =
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004333 typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004334 return EC;
4335 if (!Ty)
4336 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004337
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004338 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004339 if (Ordering == NotAtomic || Ordering == Release ||
4340 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004341 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004342 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004343 return error("Invalid record");
4344 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004345
JF Bastien30bf96b2015-02-22 19:32:03 +00004346 unsigned Align;
4347 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4348 return EC;
4349 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004350
Eli Friedman59b66882011-08-09 23:02:53 +00004351 InstructionList.push_back(I);
4352 break;
4353 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004354 case bitc::FUNC_CODE_INST_STORE:
4355 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004356 unsigned OpNum = 0;
4357 Value *Val, *Ptr;
4358 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004359 (BitCode == bitc::FUNC_CODE_INST_STORE
4360 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4361 : popValue(Record, OpNum, NextValueNo,
4362 cast<PointerType>(Ptr->getType())->getElementType(),
4363 Val)) ||
4364 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004365 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004366
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004367 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004368 DiagnosticHandler, Val->getType(), Ptr->getType()))
4369 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004370 unsigned Align;
4371 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4372 return EC;
4373 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004374 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004375 break;
4376 }
David Blaikie50a06152015-04-22 04:14:46 +00004377 case bitc::FUNC_CODE_INST_STOREATOMIC:
4378 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004379 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4380 unsigned OpNum = 0;
4381 Value *Val, *Ptr;
4382 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004383 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4384 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4385 : popValue(Record, OpNum, NextValueNo,
4386 cast<PointerType>(Ptr->getType())->getElementType(),
4387 Val)) ||
4388 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004389 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004390
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004391 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004392 DiagnosticHandler, Val->getType(), Ptr->getType()))
4393 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004394 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004395 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004396 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004397 return error("Invalid record");
4398 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004399 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004400 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004401
JF Bastien30bf96b2015-02-22 19:32:03 +00004402 unsigned Align;
4403 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4404 return EC;
4405 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004406 InstructionList.push_back(I);
4407 break;
4408 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004409 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004410 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004411 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004412 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004413 unsigned OpNum = 0;
4414 Value *Ptr, *Cmp, *New;
4415 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004416 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4417 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4418 : popValue(Record, OpNum, NextValueNo,
4419 cast<PointerType>(Ptr->getType())->getElementType(),
4420 Cmp)) ||
4421 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4422 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004423 return error("Invalid record");
4424 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00004425 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004426 return error("Invalid record");
4427 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00004428
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004429 if (std::error_code EC = typeCheckLoadStoreInst(
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004430 DiagnosticHandler, Cmp->getType(), Ptr->getType()))
4431 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00004432 AtomicOrdering FailureOrdering;
4433 if (Record.size() < 7)
4434 FailureOrdering =
4435 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
4436 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004437 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00004438
4439 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
4440 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004441 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00004442
4443 if (Record.size() < 8) {
4444 // Before weak cmpxchgs existed, the instruction simply returned the
4445 // value loaded from memory, so bitcode files from that era will be
4446 // expecting the first component of a modern cmpxchg.
4447 CurBB->getInstList().push_back(I);
4448 I = ExtractValueInst::Create(I, 0);
4449 } else {
4450 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
4451 }
4452
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004453 InstructionList.push_back(I);
4454 break;
4455 }
4456 case bitc::FUNC_CODE_INST_ATOMICRMW: {
4457 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
4458 unsigned OpNum = 0;
4459 Value *Ptr, *Val;
4460 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004461 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004462 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
4463 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004464 return error("Invalid record");
4465 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004466 if (Operation < AtomicRMWInst::FIRST_BINOP ||
4467 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004468 return error("Invalid record");
4469 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004470 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004471 return error("Invalid record");
4472 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004473 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
4474 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
4475 InstructionList.push_back(I);
4476 break;
4477 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00004478 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
4479 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004480 return error("Invalid record");
4481 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004482 if (Ordering == NotAtomic || Ordering == Unordered ||
4483 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004484 return error("Invalid record");
4485 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00004486 I = new FenceInst(Context, Ordering, SynchScope);
4487 InstructionList.push_back(I);
4488 break;
4489 }
Chris Lattnerc44070802011-06-17 18:17:37 +00004490 case bitc::FUNC_CODE_INST_CALL: {
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004491 // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
4492 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004493 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004494
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004495 unsigned OpNum = 0;
4496 AttributeSet PAL = getAttributes(Record[OpNum++]);
4497 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004498
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004499 FunctionType *FTy = nullptr;
4500 if (CCInfo >> 15 & 1 &&
4501 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004502 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004503
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004504 Value *Callee;
4505 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004506 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004507
Chris Lattner229907c2011-07-18 04:54:35 +00004508 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004509 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004510 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00004511 if (!FTy) {
4512 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
4513 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004514 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00004515 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004516 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00004517 "callee operand");
4518 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004519 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004520
Chris Lattner9f600c52007-05-03 22:04:19 +00004521 SmallVector<Value*, 16> Args;
4522 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004523 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00004524 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00004525 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00004526 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00004527 Args.push_back(getValue(Record, OpNum, NextValueNo,
4528 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004529 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004530 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004531 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004532
Chris Lattner9f600c52007-05-03 22:04:19 +00004533 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00004534 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004535 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004536 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004537 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004538 while (OpNum != Record.size()) {
4539 Value *Op;
4540 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004541 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004542 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00004543 }
4544 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004545
David Blaikie348de692015-04-23 21:36:23 +00004546 I = CallInst::Create(FTy, Callee, Args);
Devang Patelaf206b82009-09-18 19:26:43 +00004547 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00004548 cast<CallInst>(I)->setCallingConv(
Reid Kleckner5772b772014-04-24 20:14:34 +00004549 static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
4550 CallInst::TailCallKind TCK = CallInst::TCK_None;
4551 if (CCInfo & 1)
4552 TCK = CallInst::TCK_Tail;
4553 if (CCInfo & (1 << 14))
4554 TCK = CallInst::TCK_MustTail;
4555 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00004556 cast<CallInst>(I)->setAttributes(PAL);
Chris Lattner9f600c52007-05-03 22:04:19 +00004557 break;
4558 }
4559 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
4560 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004561 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004562 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004563 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00004564 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00004565 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004566 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00004567 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00004568 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00004569 break;
4570 }
Chris Lattner83930552007-05-01 07:01:57 +00004571 }
4572
4573 // Add instruction to end of current BB. If there is no current BB, reject
4574 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00004575 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00004576 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004577 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00004578 }
4579 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004580
Chris Lattner83930552007-05-01 07:01:57 +00004581 // If this was a terminator instruction, move to the next block.
4582 if (isa<TerminatorInst>(I)) {
4583 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00004584 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00004585 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004586
Chris Lattner83930552007-05-01 07:01:57 +00004587 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00004588 if (I && !I->getType()->isVoidTy())
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004589 if (ValueList.assignValue(I, NextValueNo++))
4590 return error("Invalid forward reference");
Chris Lattner85b7b402007-05-01 05:52:21 +00004591 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004592
Chris Lattner27d38752013-01-20 02:13:19 +00004593OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00004594
Chris Lattner83930552007-05-01 07:01:57 +00004595 // Check the function list for unresolved values.
4596 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00004597 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00004598 // We found at least one unresolved value. Nuke them all to avoid leaks.
4599 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00004600 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00004601 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00004602 delete A;
4603 }
4604 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004605 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00004606 }
Chris Lattner83930552007-05-01 07:01:57 +00004607 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004608
Dan Gohman9b9ff462010-08-25 20:23:38 +00004609 // FIXME: Check for unresolved forward-declared metadata references
4610 // and clean up leaks.
4611
Chris Lattner85b7b402007-05-01 05:52:21 +00004612 // Trim the value list down to the size it was before we parsed this function.
4613 ValueList.shrinkTo(ModuleValueListSize);
Dan Gohman26d837d2010-08-25 20:22:53 +00004614 MDValueList.shrinkTo(ModuleMDValueListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00004615 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004616 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004617}
4618
Rafael Espindola7d712032013-11-05 17:16:08 +00004619/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004620std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004621 Function *F,
4622 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004623 while (DeferredFunctionInfoIterator->second == 0) {
4624 if (Stream.AtEndOfStream())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004625 return error("Could not find function in stream");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004626 // ParseModule will parse the next body in the stream and set its
4627 // position in the DeferredFunctionInfo map.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004628 if (std::error_code EC = parseModule(true))
Rafael Espindola7d712032013-11-05 17:16:08 +00004629 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004630 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004631 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004632}
4633
Chris Lattner9eeada92007-05-18 04:02:46 +00004634//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004635// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00004636//===----------------------------------------------------------------------===//
4637
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00004638void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00004639
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00004640std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004641 if (std::error_code EC = materializeMetadata())
4642 return EC;
4643
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004644 Function *F = dyn_cast<Function>(GV);
4645 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004646 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004647 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004648
4649 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00004650 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004651 // If its position is recorded as 0, its body is somewhere in the stream
4652 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00004653 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004654 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004655 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004656
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004657 // Move the bit stream to the saved position of the deferred function body.
4658 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004659
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004660 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004661 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004662 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00004663
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00004664 if (StripDebugInfo)
4665 stripDebugInfo(*F);
4666
Chandler Carruth7132e002007-08-04 01:51:18 +00004667 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004668 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004669 for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
4670 User *U = *UI;
4671 ++UI;
4672 if (CallInst *CI = dyn_cast<CallInst>(U))
4673 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004674 }
4675 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004676
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004677 // Bring in any functions that this function forward-referenced via
4678 // blockaddresses.
4679 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00004680}
4681
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004682bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
4683 const Function *F = dyn_cast<Function>(GV);
4684 if (!F || F->isDeclaration())
4685 return false;
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004686
4687 // Dematerializing F would leave dangling references that wouldn't be
4688 // reconnected on re-materialization.
4689 if (BlockAddressesTaken.count(F))
4690 return false;
4691
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004692 return DeferredFunctionInfo.count(const_cast<Function*>(F));
4693}
4694
Eric Christopher97cb5652015-05-15 18:20:14 +00004695void BitcodeReader::dematerialize(GlobalValue *GV) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004696 Function *F = dyn_cast<Function>(GV);
4697 // If this function isn't dematerializable, this is a noop.
4698 if (!F || !isDematerializable(F))
Chris Lattner9eeada92007-05-18 04:02:46 +00004699 return;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004700
Chris Lattner9eeada92007-05-18 04:02:46 +00004701 assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004702
Chris Lattner9eeada92007-05-18 04:02:46 +00004703 // Just forget the function body, we can remat it later.
Petar Jovanovic7480e4d2014-09-23 12:54:19 +00004704 F->dropAllReferences();
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00004705 F->setIsMaterializable(true);
Chris Lattner9eeada92007-05-18 04:02:46 +00004706}
4707
Eric Christopher97cb5652015-05-15 18:20:14 +00004708std::error_code BitcodeReader::materializeModule(Module *M) {
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00004709 assert(M == TheModule &&
4710 "Can only Materialize the Module this BitcodeReader is attached to.");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004711
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004712 if (std::error_code EC = materializeMetadata())
4713 return EC;
4714
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004715 // Promise to materialize all forward references.
4716 WillMaterializeAllForwardRefs = true;
4717
Chris Lattner06310bf2009-06-16 05:15:21 +00004718 // Iterate over the module, deserializing any functions that are still on
4719 // disk.
4720 for (Module::iterator F = TheModule->begin(), E = TheModule->end();
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004721 F != E; ++F) {
Rafael Espindola246c4fb2014-11-01 16:46:18 +00004722 if (std::error_code EC = materialize(F))
4723 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00004724 }
Derek Schuff92ef9752012-02-29 00:07:09 +00004725 // At this point, if there are any function bodies, the current bit is
4726 // pointing to the END_BLOCK record after them. Now make sure the rest
4727 // of the bits in the module have been read.
4728 if (NextUnreadBit)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004729 parseModule(true);
Derek Schuff92ef9752012-02-29 00:07:09 +00004730
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004731 // Check that all block address forward references got resolved (as we
4732 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004733 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004734 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004735
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004736 // Upgrade any intrinsic calls that slipped through (should not happen!) and
4737 // delete the old functions to clean up. We can't do this unless the entire
4738 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00004739 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00004740 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004741 for (auto *U : I.first->users()) {
4742 if (CallInst *CI = dyn_cast<CallInst>(U))
4743 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00004744 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00004745 if (!I.first->use_empty())
4746 I.first->replaceAllUsesWith(I.second);
4747 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00004748 }
Rafael Espindola4e721212015-07-02 16:22:40 +00004749 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00004750
Manman Ren209b17c2013-09-28 00:22:27 +00004751 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
4752 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
4753
Manman Ren8b4306c2013-12-02 21:29:56 +00004754 UpgradeDebugInfo(*M);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004755 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00004756}
4757
Rafael Espindola2fa1e432014-12-03 07:18:23 +00004758std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
4759 return IdentifiedStructTypes;
4760}
4761
Rafael Espindola1aabf982015-06-16 23:29:49 +00004762std::error_code
4763BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00004764 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00004765 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004766 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004767}
4768
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004769std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00004770 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004771 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
4772
Rafael Espindola27435252014-07-29 21:01:24 +00004773 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004774 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004775
4776 // If we have a wrapper header, parse it and ignore the non-bc file contents.
4777 // The magic number is 0x0B17C0DE stored in little endian.
4778 if (isBitcodeWrapper(BufPtr, BufEnd))
4779 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004780 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004781
4782 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004783 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004784
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004785 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004786}
4787
Rafael Espindola1aabf982015-06-16 23:29:49 +00004788std::error_code
4789BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004790 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
4791 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00004792 auto OwnedBytes =
4793 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00004794 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00004795 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00004796 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004797
4798 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00004799 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004800 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004801
4802 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004803 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004804
4805 if (isBitcodeWrapper(buf, buf + 4)) {
4806 const unsigned char *bitcodeStart = buf;
4807 const unsigned char *bitcodeEnd = buf + 16;
4808 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00004809 Bytes.dropLeadingBytes(bitcodeStart - buf);
4810 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004811 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00004812 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00004813}
4814
4815namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00004816class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00004817 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00004818 return "llvm.bitcode";
4819 }
Craig Topper73156022014-03-02 09:09:27 +00004820 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004821 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004822 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004823 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00004824 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004825 case BitcodeError::CorruptedBitcode:
4826 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00004827 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00004828 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00004829 }
4830};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00004831}
Rafael Espindola48da4f42013-11-04 16:16:24 +00004832
Chris Bieneman770163e2014-09-19 20:29:02 +00004833static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
4834
Rafael Espindolac3f2e732014-07-29 20:22:46 +00004835const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00004836 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004837}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00004838
Chris Lattner6694f602007-04-29 07:54:31 +00004839//===----------------------------------------------------------------------===//
4840// External interface
4841//===----------------------------------------------------------------------===//
4842
Rafael Espindola456baad2015-06-17 01:15:47 +00004843static ErrorOr<std::unique_ptr<Module>>
4844getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
4845 BitcodeReader *R, LLVMContext &Context,
4846 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
4847 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
4848 M->setMaterializer(R);
4849
4850 auto cleanupOnError = [&](std::error_code EC) {
4851 R->releaseBuffer(); // Never take ownership on error.
4852 return EC;
4853 };
4854
4855 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
4856 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
4857 ShouldLazyLoadMetadata))
4858 return cleanupOnError(EC);
4859
4860 if (MaterializeAll) {
4861 // Read in the entire module, and destroy the BitcodeReader.
4862 if (std::error_code EC = M->materializeAllPermanently())
4863 return cleanupOnError(EC);
4864 } else {
4865 // Resolve forward references from blockaddresses.
4866 if (std::error_code EC = R->materializeForwardReferencedFunctions())
4867 return cleanupOnError(EC);
4868 }
4869 return std::move(M);
4870}
4871
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004872/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00004873///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004874/// This isn't always used in a lazy context. In particular, it's also used by
4875/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
4876/// in forward-referenced functions from block address references.
4877///
Rafael Espindola728074b2015-06-17 00:40:56 +00004878/// \param[in] MaterializeAll Set to \c true if we should materialize
4879/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004880static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00004881getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00004882 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004883 DiagnosticHandlerFunction DiagnosticHandler,
4884 bool ShouldLazyLoadMetadata = false) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004885 BitcodeReader *R =
4886 new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00004887
Rafael Espindola456baad2015-06-17 01:15:47 +00004888 ErrorOr<std::unique_ptr<Module>> Ret =
4889 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
4890 MaterializeAll, ShouldLazyLoadMetadata);
4891 if (!Ret)
4892 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00004893
Rafael Espindolae2c1d772014-08-26 22:00:09 +00004894 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00004895 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00004896}
4897
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004898ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
4899 std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
4900 DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004901 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00004902 DiagnosticHandler, ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00004903}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004904
Rafael Espindola1aabf982015-06-16 23:29:49 +00004905ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
4906 StringRef Name, std::unique_ptr<DataStreamer> Streamer,
4907 LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00004908 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola1aabf982015-06-16 23:29:49 +00004909 BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
Rafael Espindola456baad2015-06-17 01:15:47 +00004910
4911 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
4912 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00004913}
4914
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00004915ErrorOr<std::unique_ptr<Module>>
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004916llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
4917 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004918 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola728074b2015-06-17 00:40:56 +00004919 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
4920 DiagnosticHandler);
Chad Rosierca2567b2011-12-07 21:44:12 +00004921 // TODO: Restore the use-lists to the in-memory state when the bitcode was
4922 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00004923}
Bill Wendling0198ce02010-10-06 01:22:42 +00004924
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004925std::string
4926llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
4927 DiagnosticHandlerFunction DiagnosticHandler) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00004928 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindolad0b23be2015-01-10 00:07:30 +00004929 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
4930 DiagnosticHandler);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00004931 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00004932 if (Triple.getError())
4933 return "";
4934 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00004935}