blob: 85a331cc00ddd246f150e6a5286b140072482263 [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
Benjamin Kramer0a446fd2015-03-01 21:28:53 +000010#include "llvm/ADT/STLExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/SmallString.h"
12#include "llvm/ADT/SmallVector.h"
David Majnemer3087b222015-01-20 05:58:07 +000013#include "llvm/ADT/Triple.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000014#include "llvm/Bitcode/BitstreamReader.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000015#include "llvm/Bitcode/LLVMBitCodes.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000016#include "llvm/Bitcode/ReaderWriter.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"
Teresa Johnson26ab5772016-03-15 00:04:37 +000028#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/OperandTraits.h"
30#include "llvm/IR/Operator.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000031#include "llvm/IR/ValueHandle.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000032#include "llvm/Support/CommandLine.h"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000033#include "llvm/Support/DataStream.h"
Teresa Johnson916495d2016-04-04 18:52:58 +000034#include "llvm/Support/Debug.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000036#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000037#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000038#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000039#include <deque>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000040
Chris Lattner1314b992007-04-22 06:23:29 +000041using namespace llvm;
42
Teresa Johnson916495d2016-04-04 18:52:58 +000043static cl::opt<bool> PrintSummaryGUIDs(
44 "print-summary-global-ids", cl::init(false), cl::Hidden,
45 cl::desc(
46 "Print the global id for each value when reading the module summary"));
47
Benjamin Kramercced8be2015-03-17 20:40:24 +000048namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000049enum {
50 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
51};
52
Benjamin Kramercced8be2015-03-17 20:40:24 +000053class BitcodeReaderValueList {
54 std::vector<WeakVH> ValuePtrs;
55
Rafael Espindolacbdcb502015-06-15 20:55:37 +000056 /// As we resolve forward-referenced constants, we add information about them
57 /// to this vector. This allows us to resolve them in bulk instead of
58 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000059 /// ResolveConstantForwardRefs for more information about this.
60 ///
61 /// The key of this vector is the placeholder constant, the value is the slot
62 /// number that holds the resolved value.
63 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
64 ResolveConstantsTy ResolveConstants;
65 LLVMContext &Context;
66public:
67 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
68 ~BitcodeReaderValueList() {
69 assert(ResolveConstants.empty() && "Constants not resolved?");
70 }
71
72 // vector compatibility methods
73 unsigned size() const { return ValuePtrs.size(); }
74 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000075 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000076
77 void clear() {
78 assert(ResolveConstants.empty() && "Constants not resolved?");
79 ValuePtrs.clear();
80 }
81
82 Value *operator[](unsigned i) const {
83 assert(i < ValuePtrs.size());
84 return ValuePtrs[i];
85 }
86
87 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000088 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000089 bool empty() const { return ValuePtrs.empty(); }
90 void shrinkTo(unsigned N) {
91 assert(N <= size() && "Invalid shrinkTo request!");
92 ValuePtrs.resize(N);
93 }
94
95 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000096 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000097
David Majnemer8a1c45d2015-12-12 05:38:55 +000098 void 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
Teresa Johnson61b406e2015-12-29 23:00:22 +0000105class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000106 unsigned NumFwdRefs;
107 bool AnyFwdRefs;
108 unsigned MinFwdRef;
109 unsigned MaxFwdRef;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000110 std::vector<TrackingMDRef> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000111
112 LLVMContext &Context;
113public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000114 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000115 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000116
117 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000118 unsigned size() const { return MetadataPtrs.size(); }
119 void resize(unsigned N) { MetadataPtrs.resize(N); }
120 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
121 void clear() { MetadataPtrs.clear(); }
122 Metadata *back() const { return MetadataPtrs.back(); }
123 void pop_back() { MetadataPtrs.pop_back(); }
124 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000125
126 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000127 assert(i < MetadataPtrs.size());
128 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000129 }
130
131 void shrinkTo(unsigned N) {
132 assert(N <= size() && "Invalid shrinkTo request!");
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000133 assert(!AnyFwdRefs && "Unexpected forward refs");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000134 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000135 }
136
Justin Bognerae341c62016-03-17 20:12:06 +0000137 Metadata *getMetadataFwdRef(unsigned Idx);
138 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000139 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000140 void tryToResolveCycles();
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +0000141 bool hasFwdRefs() const { return AnyFwdRefs; }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000142};
143
144class BitcodeReader : public GVMaterializer {
145 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000146 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000147 std::unique_ptr<MemoryBuffer> Buffer;
148 std::unique_ptr<BitstreamReader> StreamFile;
149 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000150 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000151 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000152 // Last function offset found in the VST.
153 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000154 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000155 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000156 // Contains an arbitrary and optional string identifying the bitcode producer
157 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000158
159 std::vector<Type*> TypeList;
160 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000161 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000162 std::vector<Comdat *> ComdatList;
163 SmallVector<Instruction *, 64> InstructionList;
164
165 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000166 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000167 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
168 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000169 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000170
171 SmallVector<Instruction*, 64> InstsWithTBAATag;
172
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000173 bool HasSeenOldLoopTags = false;
174
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000175 /// The set of attributes by index. Index zero in the file is for null, and
176 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000177 std::vector<AttributeSet> MAttributes;
178
Karl Schimpf36440082015-08-31 16:43:55 +0000179 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000180 std::map<unsigned, AttributeSet> MAttributeGroups;
181
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000182 /// While parsing a function body, this is a list of the basic blocks for the
183 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000184 std::vector<BasicBlock*> FunctionBBs;
185
186 // When reading the module header, this list is populated with functions that
187 // have bodies later in the file.
188 std::vector<Function*> FunctionsWithBodies;
189
190 // When intrinsic functions are encountered which require upgrading they are
191 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000192 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000193 UpgradedIntrinsicMap UpgradedIntrinsics;
194
195 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
196 DenseMap<unsigned, unsigned> MDKindMap;
197
198 // Several operations happen after the module header has been read, but
199 // before function bodies are processed. This keeps track of whether
200 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000201 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000202
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000203 /// When function bodies are initially scanned, this map contains info about
204 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000205 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
206
207 /// When Metadata block is initially scanned when parsing the module, we may
208 /// choose to defer parsing of the metadata. This vector contains info about
209 /// which Metadata blocks are deferred.
210 std::vector<uint64_t> DeferredMetadataInfo;
211
212 /// These are basic blocks forward-referenced by block addresses. They are
213 /// inserted lazily into functions when they're loaded. The basic block ID is
214 /// its index into the vector.
215 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
216 std::deque<Function *> BasicBlockFwdRefQueue;
217
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000218 /// Indicates that we are using a new encoding for instruction operands where
219 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
220 /// instruction number, for a more compact encoding. Some instruction
221 /// operands are not relative to the instruction ID: basic block numbers, and
222 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000223 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000224 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000225
226 /// True if all functions will be materialized, negating the need to process
227 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000228 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000229
Benjamin Kramercced8be2015-03-17 20:40:24 +0000230 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000231 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000232
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000233 bool StripDebugInfo = false;
234
Peter Collingbourned4bff302015-11-05 22:03:56 +0000235 /// Functions that need to be matched with subprograms when upgrading old
236 /// metadata.
237 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
238
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000239 std::vector<std::string> BundleTags;
240
Benjamin Kramercced8be2015-03-17 20:40:24 +0000241public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000242 std::error_code error(BitcodeError E, const Twine &Message);
243 std::error_code error(BitcodeError E);
244 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000245
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000246 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
247 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000248 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000249
250 std::error_code materializeForwardReferencedFunctions();
251
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000252 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000253
254 void releaseBuffer();
255
Benjamin Kramercced8be2015-03-17 20:40:24 +0000256 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000257 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000258 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000259
Rafael Espindola6ace6852015-06-15 21:02:49 +0000260 /// \brief Main interface to parsing a bitcode buffer.
261 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000262 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
263 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000264 bool ShouldLazyLoadMetadata = false);
265
Rafael Espindola6ace6852015-06-15 21:02:49 +0000266 /// \brief Cheap mechanism to just extract module triple
267 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000268 ErrorOr<std::string> parseTriple();
269
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000270 /// Cheap mechanism to just extract the identification block out of bitcode.
271 ErrorOr<std::string> parseIdentificationBlock();
272
Benjamin Kramercced8be2015-03-17 20:40:24 +0000273 static uint64_t decodeSignRotatedValue(uint64_t V);
274
275 /// Materialize any deferred Metadata block.
276 std::error_code materializeMetadata() override;
277
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000278 void setStripDebugInfo() override;
279
Benjamin Kramercced8be2015-03-17 20:40:24 +0000280private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000281 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
282 // ProducerIdentification data member, and do some basic enforcement on the
283 // "epoch" encoded in the bitcode.
284 std::error_code parseBitcodeVersion();
285
Benjamin Kramercced8be2015-03-17 20:40:24 +0000286 std::vector<StructType *> IdentifiedStructTypes;
287 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
288 StructType *createIdentifiedStructType(LLVMContext &Context);
289
290 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000291 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000292 if (Ty && Ty->isMetadataTy())
293 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000294 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000295 }
296 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000297 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000298 }
299 BasicBlock *getBasicBlock(unsigned ID) const {
300 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
301 return FunctionBBs[ID];
302 }
303 AttributeSet getAttributes(unsigned i) const {
304 if (i-1 < MAttributes.size())
305 return MAttributes[i-1];
306 return AttributeSet();
307 }
308
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000309 /// Read a value/type pair out of the specified record from slot 'Slot'.
310 /// Increment Slot past the number of slots used in the record. Return true on
311 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000312 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
313 unsigned InstNum, Value *&ResVal) {
314 if (Slot == Record.size()) return true;
315 unsigned ValNo = (unsigned)Record[Slot++];
316 // Adjust the ValNo, if it was encoded relative to the InstNum.
317 if (UseRelativeIDs)
318 ValNo = InstNum - ValNo;
319 if (ValNo < InstNum) {
320 // If this is not a forward reference, just return the value we already
321 // have.
322 ResVal = getFnValueByID(ValNo, nullptr);
323 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000324 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000325 if (Slot == Record.size())
326 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000327
328 unsigned TypeNo = (unsigned)Record[Slot++];
329 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
330 return ResVal == nullptr;
331 }
332
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000333 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
334 /// past the number of slots used by the value in the record. Return true if
335 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000336 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000337 unsigned InstNum, Type *Ty, Value *&ResVal) {
338 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000339 return true;
340 // All values currently take a single record slot.
341 ++Slot;
342 return false;
343 }
344
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000345 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000346 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000347 unsigned InstNum, Type *Ty, Value *&ResVal) {
348 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000349 return ResVal == nullptr;
350 }
351
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000352 /// Version of getValue that returns ResVal directly, or 0 if there is an
353 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000354 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000355 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000356 if (Slot == Record.size()) return nullptr;
357 unsigned ValNo = (unsigned)Record[Slot];
358 // Adjust the ValNo, if it was encoded relative to the InstNum.
359 if (UseRelativeIDs)
360 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000361 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000362 }
363
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000364 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000365 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000366 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000367 if (Slot == Record.size()) return nullptr;
368 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
369 // Adjust the ValNo, if it was encoded relative to the InstNum.
370 if (UseRelativeIDs)
371 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000372 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000373 }
374
375 /// Converts alignment exponent (i.e. power of two (or zero)) to the
376 /// corresponding alignment to use. If alignment is too large, returns
377 /// a corresponding error code.
378 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000379 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000380 std::error_code parseModule(uint64_t ResumeBit,
381 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000382 std::error_code parseAttributeBlock();
383 std::error_code parseAttributeGroupBlock();
384 std::error_code parseTypeTable();
385 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000386 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000387
Teresa Johnsonff642b92015-09-17 20:12:00 +0000388 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
389 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000390 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000391 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000392 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000393 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000394 /// Save the positions of the Metadata blocks and skip parsing the blocks.
395 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000396 std::error_code parseFunctionBody(Function *F);
397 std::error_code globalCleanup();
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +0000398 std::error_code resolveGlobalAndIndirectSymbolInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000399 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000400 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
401 StringRef Blob,
402 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000403 std::error_code parseMetadataKinds();
404 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000405 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000406 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000407 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000408 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000409 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000410 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000411 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000412 Function *F,
413 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
414};
Teresa Johnson403a7872015-10-04 14:33:43 +0000415
416/// Class to manage reading and parsing function summary index bitcode
417/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000418class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000419 DiagnosticHandlerFunction DiagnosticHandler;
420
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000421 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000422 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000423
424 std::unique_ptr<MemoryBuffer> Buffer;
425 std::unique_ptr<BitstreamReader> StreamFile;
426 BitstreamCursor Stream;
427
428 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
429 ///
430 /// If false, the summary section is fully parsed into the index during
431 /// the initial parse. Otherwise, if true, the caller is expected to
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432 /// invoke \a readGlobalValueSummary for each summary needed, and the summary
Teresa Johnson403a7872015-10-04 14:33:43 +0000433 /// section is thus parsed lazily.
434 bool IsLazy = false;
435
436 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000437 /// of the global value summary bitcode section. All blocks are skipped,
438 /// but the SeenGlobalValSummary boolean is set.
439 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000440
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000441 /// Indicates whether we have encountered a global value summary section
442 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000443 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000444 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000445
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000446 /// Indicates whether we have already parsed the VST, used for error checking.
447 bool SeenValueSymbolTable = false;
448
449 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
450 /// Used to enable on-demand parsing of the VST.
451 uint64_t VSTOffset = 0;
452
453 // Map to save ValueId to GUID association that was recorded in the
454 // ValueSymbolTable. It is used after the VST is parsed to convert
455 // call graph edges read from the function summary from referencing
456 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000457 // they are recorded in the summary index being built.
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000458 DenseMap<unsigned, GlobalValue::GUID> ValueIdToCallGraphGUIDMap;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000459
460 /// Map to save the association between summary offset in the VST to the
461 /// GlobalValueInfo object created when parsing it. Used to access the
462 /// info object when parsing the summary section.
463 DenseMap<uint64_t, GlobalValueInfo *> SummaryOffsetToInfoMap;
Teresa Johnson403a7872015-10-04 14:33:43 +0000464
465 /// Map populated during module path string table parsing, from the
466 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000467 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000468 /// summary records.
469 DenseMap<uint64_t, StringRef> ModuleIdMap;
470
Teresa Johnsone1164de2016-02-10 21:55:02 +0000471 /// Original source file name recorded in a bitcode record.
472 std::string SourceFileName;
473
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000474public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000475 std::error_code error(BitcodeError E, const Twine &Message);
476 std::error_code error(BitcodeError E);
477 std::error_code error(const Twine &Message);
478
Teresa Johnson26ab5772016-03-15 00:04:37 +0000479 ModuleSummaryIndexBitcodeReader(
480 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
481 bool IsLazy = false, bool CheckGlobalValSummaryPresenceOnly = false);
482 ModuleSummaryIndexBitcodeReader(
483 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy = false,
484 bool CheckGlobalValSummaryPresenceOnly = false);
485 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000486
487 void freeState();
488
489 void releaseBuffer();
490
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000491 /// Check if the parser has encountered a summary section.
492 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000493
494 /// \brief Main interface to parsing a bitcode buffer.
495 /// \returns true if an error occurred.
496 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000497 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000498
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000499 /// \brief Interface for parsing a summary lazily.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000500 std::error_code
501 parseGlobalValueSummary(std::unique_ptr<DataStreamer> Streamer,
502 ModuleSummaryIndex *I, size_t SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000503
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000504private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000505 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000506 std::error_code parseValueSymbolTable(
507 uint64_t Offset,
508 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000509 std::error_code parseEntireSummary();
510 std::error_code parseModuleStringTable();
511 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
512 std::error_code initStreamFromBuffer();
513 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Mehdi Aminiad5741b2016-04-02 05:07:53 +0000514 GlobalValue::GUID getGUIDFromValueId(unsigned ValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000515 GlobalValueInfo *getInfoFromSummaryOffset(uint64_t Offset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000516};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000517} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000518
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000519BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
520 DiagnosticSeverity Severity,
521 const Twine &Msg)
522 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
523
524void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
525
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000526static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000527 std::error_code EC, const Twine &Message) {
528 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
529 DiagnosticHandler(DI);
530 return EC;
531}
532
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000533static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000534 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000535 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000536}
537
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000538static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000539 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000540 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
541 Message);
542}
543
544static std::error_code error(LLVMContext &Context, std::error_code EC) {
545 return error(Context, EC, EC.message());
546}
547
548static std::error_code error(LLVMContext &Context, const Twine &Message) {
549 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
550 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000551}
552
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000553std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000554 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000555 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000556 Message + " (Producer: '" + ProducerIdentification +
557 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000558 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000559 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000560}
561
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000562std::error_code BitcodeReader::error(const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000563 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000564 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000565 Message + " (Producer: '" + ProducerIdentification +
566 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000567 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000568 return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
569 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000570}
571
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000572std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000573 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000574}
575
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000576BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
577 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000578 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000579
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000580BitcodeReader::BitcodeReader(LLVMContext &Context)
581 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000582 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000583
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000584std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
585 if (WillMaterializeAllForwardRefs)
586 return std::error_code();
587
588 // Prevent recursion.
589 WillMaterializeAllForwardRefs = true;
590
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000591 while (!BasicBlockFwdRefQueue.empty()) {
592 Function *F = BasicBlockFwdRefQueue.front();
593 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000594 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000595 if (!BasicBlockFwdRefs.count(F))
596 // Already materialized.
597 continue;
598
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000599 // Check for a function that isn't materializable to prevent an infinite
600 // loop. When parsing a blockaddress stored in a global variable, there
601 // isn't a trivial way to check if a function will have a body without a
602 // linear search through FunctionsWithBodies, so just check it here.
603 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000604 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000605
606 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000607 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000608 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000609 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000610 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000611
612 // Reset state.
613 WillMaterializeAllForwardRefs = false;
614 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000615}
616
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000617void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000618 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000619 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000620 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000621 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000622 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000623
Bill Wendlinge94d8432012-12-07 23:16:57 +0000624 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000625 std::vector<BasicBlock*>().swap(FunctionBBs);
626 std::vector<Function*>().swap(FunctionsWithBodies);
627 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000628 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000629 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000630
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000631 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000632 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000633}
634
Chris Lattnerfee5a372007-05-04 03:30:17 +0000635//===----------------------------------------------------------------------===//
636// Helper functions to implement forward reference resolution, etc.
637//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000638
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000639/// Convert a string from a record into an std::string, return true on failure.
640template <typename StrTy>
641static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000642 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000643 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000644 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000645
Chris Lattnere14cb882007-05-04 19:11:41 +0000646 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
647 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000648 return false;
649}
650
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000651static bool hasImplicitComdat(size_t Val) {
652 switch (Val) {
653 default:
654 return false;
655 case 1: // Old WeakAnyLinkage
656 case 4: // Old LinkOnceAnyLinkage
657 case 10: // Old WeakODRLinkage
658 case 11: // Old LinkOnceODRLinkage
659 return true;
660 }
661}
662
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000663static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000664 switch (Val) {
665 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000666 case 0:
667 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000668 case 2:
669 return GlobalValue::AppendingLinkage;
670 case 3:
671 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000672 case 5:
673 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
674 case 6:
675 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
676 case 7:
677 return GlobalValue::ExternalWeakLinkage;
678 case 8:
679 return GlobalValue::CommonLinkage;
680 case 9:
681 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000682 case 12:
683 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000684 case 13:
685 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
686 case 14:
687 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000688 case 15:
689 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000690 case 1: // Old value with implicit comdat.
691 case 16:
692 return GlobalValue::WeakAnyLinkage;
693 case 10: // Old value with implicit comdat.
694 case 17:
695 return GlobalValue::WeakODRLinkage;
696 case 4: // Old value with implicit comdat.
697 case 18:
698 return GlobalValue::LinkOnceAnyLinkage;
699 case 11: // Old value with implicit comdat.
700 case 19:
701 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000702 }
703}
704
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000705static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000706 switch (Val) {
707 default: // Map unknown visibilities to default.
708 case 0: return GlobalValue::DefaultVisibility;
709 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000710 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000711 }
712}
713
Nico Rieck7157bb72014-01-14 15:22:47 +0000714static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000715getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000716 switch (Val) {
717 default: // Map unknown values to default.
718 case 0: return GlobalValue::DefaultStorageClass;
719 case 1: return GlobalValue::DLLImportStorageClass;
720 case 2: return GlobalValue::DLLExportStorageClass;
721 }
722}
723
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000724static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000725 switch (Val) {
726 case 0: return GlobalVariable::NotThreadLocal;
727 default: // Map unknown non-zero value to general dynamic.
728 case 1: return GlobalVariable::GeneralDynamicTLSModel;
729 case 2: return GlobalVariable::LocalDynamicTLSModel;
730 case 3: return GlobalVariable::InitialExecTLSModel;
731 case 4: return GlobalVariable::LocalExecTLSModel;
732 }
733}
734
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000735static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000736 switch (Val) {
737 default: return -1;
738 case bitc::CAST_TRUNC : return Instruction::Trunc;
739 case bitc::CAST_ZEXT : return Instruction::ZExt;
740 case bitc::CAST_SEXT : return Instruction::SExt;
741 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
742 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
743 case bitc::CAST_UITOFP : return Instruction::UIToFP;
744 case bitc::CAST_SITOFP : return Instruction::SIToFP;
745 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
746 case bitc::CAST_FPEXT : return Instruction::FPExt;
747 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
748 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
749 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000750 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000751 }
752}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000753
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000754static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000755 bool IsFP = Ty->isFPOrFPVectorTy();
756 // BinOps are only valid for int/fp or vector of int/fp types
757 if (!IsFP && !Ty->isIntOrIntVectorTy())
758 return -1;
759
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000760 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000761 default:
762 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000763 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000764 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000765 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000766 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000767 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000768 return IsFP ? Instruction::FMul : Instruction::Mul;
769 case bitc::BINOP_UDIV:
770 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000771 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000772 return IsFP ? Instruction::FDiv : Instruction::SDiv;
773 case bitc::BINOP_UREM:
774 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000775 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000776 return IsFP ? Instruction::FRem : Instruction::SRem;
777 case bitc::BINOP_SHL:
778 return IsFP ? -1 : Instruction::Shl;
779 case bitc::BINOP_LSHR:
780 return IsFP ? -1 : Instruction::LShr;
781 case bitc::BINOP_ASHR:
782 return IsFP ? -1 : Instruction::AShr;
783 case bitc::BINOP_AND:
784 return IsFP ? -1 : Instruction::And;
785 case bitc::BINOP_OR:
786 return IsFP ? -1 : Instruction::Or;
787 case bitc::BINOP_XOR:
788 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000789 }
790}
791
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000792static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000793 switch (Val) {
794 default: return AtomicRMWInst::BAD_BINOP;
795 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
796 case bitc::RMW_ADD: return AtomicRMWInst::Add;
797 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
798 case bitc::RMW_AND: return AtomicRMWInst::And;
799 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
800 case bitc::RMW_OR: return AtomicRMWInst::Or;
801 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
802 case bitc::RMW_MAX: return AtomicRMWInst::Max;
803 case bitc::RMW_MIN: return AtomicRMWInst::Min;
804 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
805 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
806 }
807}
808
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000809static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000810 switch (Val) {
811 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
812 case bitc::ORDERING_UNORDERED: return Unordered;
813 case bitc::ORDERING_MONOTONIC: return Monotonic;
814 case bitc::ORDERING_ACQUIRE: return Acquire;
815 case bitc::ORDERING_RELEASE: return Release;
816 case bitc::ORDERING_ACQREL: return AcquireRelease;
817 default: // Map unknown orderings to sequentially-consistent.
818 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
819 }
820}
821
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000822static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000823 switch (Val) {
824 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
825 default: // Map unknown scopes to cross-thread.
826 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
827 }
828}
829
David Majnemerdad0a642014-06-27 18:19:56 +0000830static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
831 switch (Val) {
832 default: // Map unknown selection kinds to any.
833 case bitc::COMDAT_SELECTION_KIND_ANY:
834 return Comdat::Any;
835 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
836 return Comdat::ExactMatch;
837 case bitc::COMDAT_SELECTION_KIND_LARGEST:
838 return Comdat::Largest;
839 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
840 return Comdat::NoDuplicates;
841 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
842 return Comdat::SameSize;
843 }
844}
845
James Molloy88eb5352015-07-10 12:52:00 +0000846static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
847 FastMathFlags FMF;
848 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
849 FMF.setUnsafeAlgebra();
850 if (0 != (Val & FastMathFlags::NoNaNs))
851 FMF.setNoNaNs();
852 if (0 != (Val & FastMathFlags::NoInfs))
853 FMF.setNoInfs();
854 if (0 != (Val & FastMathFlags::NoSignedZeros))
855 FMF.setNoSignedZeros();
856 if (0 != (Val & FastMathFlags::AllowReciprocal))
857 FMF.setAllowReciprocal();
858 return FMF;
859}
860
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000861static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000862 switch (Val) {
863 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
864 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
865 }
866}
867
Gabor Greiff6caff662008-05-10 08:32:32 +0000868namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000869namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000870/// \brief A class for maintaining the slot number definition
871/// as a placeholder for the actual definition for forward constants defs.
872class ConstantPlaceHolder : public ConstantExpr {
873 void operator=(const ConstantPlaceHolder &) = delete;
874
875public:
876 // allocate space for exactly one operand
877 void *operator new(size_t s) { return User::operator new(s, 1); }
878 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000879 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000880 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
881 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000882
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000883 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
884 static bool classof(const Value *V) {
885 return isa<ConstantExpr>(V) &&
886 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
887 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000888
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000889 /// Provide fast operand accessors
890 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
891};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000892} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000893
Chris Lattner2d8cd802009-03-31 22:55:09 +0000894// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000895template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000896struct OperandTraits<ConstantPlaceHolder> :
897 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000898};
Richard Trieue3d126c2014-11-21 02:42:08 +0000899DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000900} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000901
David Majnemer8a1c45d2015-12-12 05:38:55 +0000902void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000903 if (Idx == size()) {
904 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000905 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000906 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000907
Chris Lattner2d8cd802009-03-31 22:55:09 +0000908 if (Idx >= size())
909 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000910
Chris Lattner2d8cd802009-03-31 22:55:09 +0000911 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000912 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000913 OldV = V;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000914 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000915 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000916
Chris Lattner2d8cd802009-03-31 22:55:09 +0000917 // Handle constants and non-constants (e.g. instrs) differently for
918 // efficiency.
919 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
920 ResolveConstants.push_back(std::make_pair(PHC, Idx));
921 OldV = V;
922 } else {
923 // If there was a forward reference to this value, replace it.
924 Value *PrevVal = OldV;
925 OldV->replaceAllUsesWith(V);
926 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000927 }
928}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000929
Chris Lattner1663cca2007-04-24 05:48:56 +0000930Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000931 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000932 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000933 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000934
Chris Lattner2d8cd802009-03-31 22:55:09 +0000935 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000936 if (Ty != V->getType())
937 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000938 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000939 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000940
941 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000942 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000943 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000944 return C;
945}
946
David Majnemer8a1c45d2015-12-12 05:38:55 +0000947Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000948 // Bail out for a clearly invalid value. This would make us call resize(0)
949 if (Idx == UINT_MAX)
950 return nullptr;
951
Chris Lattner2d8cd802009-03-31 22:55:09 +0000952 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000953 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000954
Chris Lattner2d8cd802009-03-31 22:55:09 +0000955 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000956 // If the types don't match, it's invalid.
957 if (Ty && Ty != V->getType())
958 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000959 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000960 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000961
Chris Lattner1fc27f02007-05-02 05:16:49 +0000962 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000963 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000964
Chris Lattner83930552007-05-01 07:01:57 +0000965 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000966 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000967 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000968 return V;
969}
970
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000971/// Once all constants are read, this method bulk resolves any forward
972/// references. The idea behind this is that we sometimes get constants (such
973/// as large arrays) which reference *many* forward ref constants. Replacing
974/// each of these causes a lot of thrashing when building/reuniquing the
975/// constant. Instead of doing this, we look at all the uses and rewrite all
976/// the place holders at once for any constant that uses a placeholder.
977void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000978 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000979 // binary search.
980 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000981
Chris Lattner74429932008-08-21 02:34:16 +0000982 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000983
Chris Lattner74429932008-08-21 02:34:16 +0000984 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000985 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000986 Constant *Placeholder = ResolveConstants.back().first;
987 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000988
Chris Lattner74429932008-08-21 02:34:16 +0000989 // Loop over all users of the placeholder, updating them to reference the
990 // new value. If they reference more than one placeholder, update them all
991 // at once.
992 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000993 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000994 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000995
Chris Lattner74429932008-08-21 02:34:16 +0000996 // If the using object isn't uniqued, just update the operands. This
997 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000998 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000999 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001000 continue;
1001 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001002
Chris Lattner74429932008-08-21 02:34:16 +00001003 // Otherwise, we have a constant that uses the placeholder. Replace that
1004 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +00001005 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +00001006 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
1007 I != E; ++I) {
1008 Value *NewOp;
1009 if (!isa<ConstantPlaceHolder>(*I)) {
1010 // Not a placeholder reference.
1011 NewOp = *I;
1012 } else if (*I == Placeholder) {
1013 // Common case is that it just references this one placeholder.
1014 NewOp = RealVal;
1015 } else {
1016 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001017 ResolveConstantsTy::iterator It =
1018 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001019 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1020 0));
1021 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001022 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001023 }
1024
1025 NewOps.push_back(cast<Constant>(NewOp));
1026 }
1027
1028 // Make the new constant.
1029 Constant *NewC;
1030 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001031 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001032 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001033 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001034 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001035 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001036 } else {
1037 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001038 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001040
Chris Lattner74429932008-08-21 02:34:16 +00001041 UserC->replaceAllUsesWith(NewC);
1042 UserC->destroyConstant();
1043 NewOps.clear();
1044 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001045
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001046 // Update all ValueHandles, they should be the only users at this point.
1047 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001048 delete Placeholder;
1049 }
1050}
1051
Teresa Johnson61b406e2015-12-29 23:00:22 +00001052void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001053 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001054 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001055 return;
1056 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001057
Devang Patel05eb6172009-08-04 06:00:18 +00001058 if (Idx >= size())
1059 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001060
Teresa Johnson61b406e2015-12-29 23:00:22 +00001061 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001062 if (!OldMD) {
1063 OldMD.reset(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001064 return;
1065 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001066
Devang Patel05eb6172009-08-04 06:00:18 +00001067 // If there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001068 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001069 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001070 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001071}
1072
Justin Bognerae341c62016-03-17 20:12:06 +00001073Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001074 if (Idx >= size())
1075 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001076
Teresa Johnson61b406e2015-12-29 23:00:22 +00001077 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001078 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001079
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001080 // Track forward refs to be resolved later.
1081 if (AnyFwdRefs) {
1082 MinFwdRef = std::min(MinFwdRef, Idx);
1083 MaxFwdRef = std::max(MaxFwdRef, Idx);
1084 } else {
1085 AnyFwdRefs = true;
1086 MinFwdRef = MaxFwdRef = Idx;
1087 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001088 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001089
1090 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001091 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001092 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001093 return MD;
1094}
1095
Justin Bognerae341c62016-03-17 20:12:06 +00001096MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1097 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1098}
1099
Teresa Johnson61b406e2015-12-29 23:00:22 +00001100void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001101 if (!AnyFwdRefs)
1102 // Nothing to do.
1103 return;
1104
1105 if (NumFwdRefs)
1106 // Still forward references... can't resolve cycles.
1107 return;
1108
1109 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001110 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001111 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001112 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001113 if (!N)
1114 continue;
1115
1116 assert(!N->isTemporary() && "Unexpected forward reference");
1117 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001118 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001119
1120 // Make sure we return early again until there's another forward ref.
1121 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001122}
Chris Lattner1314b992007-04-22 06:23:29 +00001123
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001124Type *BitcodeReader::getTypeByID(unsigned ID) {
1125 // The type table size is always specified correctly.
1126 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001127 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001128
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001129 if (Type *Ty = TypeList[ID])
1130 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001131
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001132 // If we have a forward reference, the only possible case is when it is to a
1133 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001134 return TypeList[ID] = createIdentifiedStructType(Context);
1135}
1136
1137StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1138 StringRef Name) {
1139 auto *Ret = StructType::create(Context, Name);
1140 IdentifiedStructTypes.push_back(Ret);
1141 return Ret;
1142}
1143
1144StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1145 auto *Ret = StructType::create(Context);
1146 IdentifiedStructTypes.push_back(Ret);
1147 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001148}
1149
Chris Lattnerfee5a372007-05-04 03:30:17 +00001150//===----------------------------------------------------------------------===//
1151// Functions for parsing blocks from the bitcode file
1152//===----------------------------------------------------------------------===//
1153
Bill Wendling56aeccc2013-02-04 23:32:23 +00001154
1155/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1156/// been decoded from the given integer. This function must stay in sync with
1157/// 'encodeLLVMAttributesForBitcode'.
1158static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1159 uint64_t EncodedAttrs) {
1160 // FIXME: Remove in 4.0.
1161
1162 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1163 // the bits above 31 down by 11 bits.
1164 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1165 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1166 "Alignment must be a power of two.");
1167
1168 if (Alignment)
1169 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001170 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001171 (EncodedAttrs & 0xffff));
1172}
1173
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001174std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001175 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001176 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001177
Devang Patela05633e2008-09-26 22:53:05 +00001178 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001179 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001180
Chris Lattnerfee5a372007-05-04 03:30:17 +00001181 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001182
Bill Wendling71173cb2013-01-27 00:36:48 +00001183 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001184
Chris Lattnerfee5a372007-05-04 03:30:17 +00001185 // Read all the records.
1186 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001187 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001188
Chris Lattner27d38752013-01-20 02:13:19 +00001189 switch (Entry.Kind) {
1190 case BitstreamEntry::SubBlock: // Handled for us already.
1191 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001192 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001193 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001194 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001195 case BitstreamEntry::Record:
1196 // The interesting case.
1197 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001198 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001199
Chris Lattnerfee5a372007-05-04 03:30:17 +00001200 // Read a record.
1201 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001202 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001203 default: // Default behavior: ignore.
1204 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001205 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1206 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001207 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001208 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001209
Chris Lattnerfee5a372007-05-04 03:30:17 +00001210 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001211 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001212 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001213 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001214 }
Devang Patela05633e2008-09-26 22:53:05 +00001215
Bill Wendlinge94d8432012-12-07 23:16:57 +00001216 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001217 Attrs.clear();
1218 break;
1219 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001220 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1221 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1222 Attrs.push_back(MAttributeGroups[Record[i]]);
1223
1224 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1225 Attrs.clear();
1226 break;
1227 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001228 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001229 }
1230}
1231
Reid Klecknere9f36af2013-11-12 01:31:00 +00001232// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001233static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001234 switch (Code) {
1235 default:
1236 return Attribute::None;
1237 case bitc::ATTR_KIND_ALIGNMENT:
1238 return Attribute::Alignment;
1239 case bitc::ATTR_KIND_ALWAYS_INLINE:
1240 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001241 case bitc::ATTR_KIND_ARGMEMONLY:
1242 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001243 case bitc::ATTR_KIND_BUILTIN:
1244 return Attribute::Builtin;
1245 case bitc::ATTR_KIND_BY_VAL:
1246 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001247 case bitc::ATTR_KIND_IN_ALLOCA:
1248 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001249 case bitc::ATTR_KIND_COLD:
1250 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001251 case bitc::ATTR_KIND_CONVERGENT:
1252 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001253 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1254 return Attribute::InaccessibleMemOnly;
1255 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1256 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001257 case bitc::ATTR_KIND_INLINE_HINT:
1258 return Attribute::InlineHint;
1259 case bitc::ATTR_KIND_IN_REG:
1260 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001261 case bitc::ATTR_KIND_JUMP_TABLE:
1262 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001263 case bitc::ATTR_KIND_MIN_SIZE:
1264 return Attribute::MinSize;
1265 case bitc::ATTR_KIND_NAKED:
1266 return Attribute::Naked;
1267 case bitc::ATTR_KIND_NEST:
1268 return Attribute::Nest;
1269 case bitc::ATTR_KIND_NO_ALIAS:
1270 return Attribute::NoAlias;
1271 case bitc::ATTR_KIND_NO_BUILTIN:
1272 return Attribute::NoBuiltin;
1273 case bitc::ATTR_KIND_NO_CAPTURE:
1274 return Attribute::NoCapture;
1275 case bitc::ATTR_KIND_NO_DUPLICATE:
1276 return Attribute::NoDuplicate;
1277 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1278 return Attribute::NoImplicitFloat;
1279 case bitc::ATTR_KIND_NO_INLINE:
1280 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001281 case bitc::ATTR_KIND_NO_RECURSE:
1282 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001283 case bitc::ATTR_KIND_NON_LAZY_BIND:
1284 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001285 case bitc::ATTR_KIND_NON_NULL:
1286 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001287 case bitc::ATTR_KIND_DEREFERENCEABLE:
1288 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001289 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1290 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001291 case bitc::ATTR_KIND_NO_RED_ZONE:
1292 return Attribute::NoRedZone;
1293 case bitc::ATTR_KIND_NO_RETURN:
1294 return Attribute::NoReturn;
1295 case bitc::ATTR_KIND_NO_UNWIND:
1296 return Attribute::NoUnwind;
1297 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1298 return Attribute::OptimizeForSize;
1299 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1300 return Attribute::OptimizeNone;
1301 case bitc::ATTR_KIND_READ_NONE:
1302 return Attribute::ReadNone;
1303 case bitc::ATTR_KIND_READ_ONLY:
1304 return Attribute::ReadOnly;
1305 case bitc::ATTR_KIND_RETURNED:
1306 return Attribute::Returned;
1307 case bitc::ATTR_KIND_RETURNS_TWICE:
1308 return Attribute::ReturnsTwice;
1309 case bitc::ATTR_KIND_S_EXT:
1310 return Attribute::SExt;
1311 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1312 return Attribute::StackAlignment;
1313 case bitc::ATTR_KIND_STACK_PROTECT:
1314 return Attribute::StackProtect;
1315 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1316 return Attribute::StackProtectReq;
1317 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1318 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001319 case bitc::ATTR_KIND_SAFESTACK:
1320 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001321 case bitc::ATTR_KIND_STRUCT_RET:
1322 return Attribute::StructRet;
1323 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1324 return Attribute::SanitizeAddress;
1325 case bitc::ATTR_KIND_SANITIZE_THREAD:
1326 return Attribute::SanitizeThread;
1327 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1328 return Attribute::SanitizeMemory;
Manman Ren9bfd0d02016-04-01 21:41:15 +00001329 case bitc::ATTR_KIND_SWIFT_ERROR:
1330 return Attribute::SwiftError;
Manman Renf46262e2016-03-29 17:37:21 +00001331 case bitc::ATTR_KIND_SWIFT_SELF:
1332 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001333 case bitc::ATTR_KIND_UW_TABLE:
1334 return Attribute::UWTable;
1335 case bitc::ATTR_KIND_Z_EXT:
1336 return Attribute::ZExt;
1337 }
1338}
1339
JF Bastien30bf96b2015-02-22 19:32:03 +00001340std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1341 unsigned &Alignment) {
1342 // Note: Alignment in bitcode files is incremented by 1, so that zero
1343 // can be used for default alignment.
1344 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001345 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001346 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1347 return std::error_code();
1348}
1349
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001350std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001351 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001352 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001353 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001354 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001355 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001356 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001357}
1358
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001359std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001360 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001361 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001362
1363 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001364 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001365
1366 SmallVector<uint64_t, 64> Record;
1367
1368 // Read all the records.
1369 while (1) {
1370 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1371
1372 switch (Entry.Kind) {
1373 case BitstreamEntry::SubBlock: // Handled for us already.
1374 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001375 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001376 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001377 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001378 case BitstreamEntry::Record:
1379 // The interesting case.
1380 break;
1381 }
1382
1383 // Read a record.
1384 Record.clear();
1385 switch (Stream.readRecord(Entry.ID, Record)) {
1386 default: // Default behavior: ignore.
1387 break;
1388 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1389 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001390 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001391
Bill Wendlinge46707e2013-02-11 22:32:29 +00001392 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001393 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1394
1395 AttrBuilder B;
1396 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1397 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001398 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001399 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001400 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001401
1402 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001403 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001404 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001405 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001406 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001407 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001408 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001409 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001410 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001411 else if (Kind == Attribute::Dereferenceable)
1412 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001413 else if (Kind == Attribute::DereferenceableOrNull)
1414 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001415 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001416 assert((Record[i] == 3 || Record[i] == 4) &&
1417 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001418 bool HasValue = (Record[i++] == 4);
1419 SmallString<64> KindStr;
1420 SmallString<64> ValStr;
1421
1422 while (Record[i] != 0 && i != e)
1423 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001424 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001425
1426 if (HasValue) {
1427 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001428 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001429 while (Record[i] != 0 && i != e)
1430 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001431 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001432 }
1433
1434 B.addAttribute(KindStr.str(), ValStr.str());
1435 }
1436 }
1437
Bill Wendlinge46707e2013-02-11 22:32:29 +00001438 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001439 break;
1440 }
1441 }
1442 }
1443}
1444
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001445std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001446 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001447 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001448
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001449 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001450}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001451
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001452std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001453 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001454 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001455
1456 SmallVector<uint64_t, 64> Record;
1457 unsigned NumRecords = 0;
1458
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001459 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001460
Chris Lattner1314b992007-04-22 06:23:29 +00001461 // Read all the records for this type table.
1462 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001463 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001464
Chris Lattner27d38752013-01-20 02:13:19 +00001465 switch (Entry.Kind) {
1466 case BitstreamEntry::SubBlock: // Handled for us already.
1467 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001468 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001469 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001470 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001471 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001472 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001473 case BitstreamEntry::Record:
1474 // The interesting case.
1475 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001476 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001477
Chris Lattner1314b992007-04-22 06:23:29 +00001478 // Read a record.
1479 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001480 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001481 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001482 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001483 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001484 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1485 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1486 // type list. This allows us to reserve space.
1487 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001488 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001489 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001490 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001491 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001492 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001493 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001494 case bitc::TYPE_CODE_HALF: // HALF
1495 ResultTy = Type::getHalfTy(Context);
1496 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001497 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001498 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001499 break;
1500 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001501 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001502 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001503 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001504 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001505 break;
1506 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001507 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001508 break;
1509 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001510 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001511 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001512 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001513 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001514 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001515 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001516 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001517 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001518 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1519 ResultTy = Type::getX86_MMXTy(Context);
1520 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001521 case bitc::TYPE_CODE_TOKEN: // TOKEN
1522 ResultTy = Type::getTokenTy(Context);
1523 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001524 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001525 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001526 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001527
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001528 uint64_t NumBits = Record[0];
1529 if (NumBits < IntegerType::MIN_INT_BITS ||
1530 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001531 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001532 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001533 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001534 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001535 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001536 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001537 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001538 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001539 unsigned AddressSpace = 0;
1540 if (Record.size() == 2)
1541 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001542 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001543 if (!ResultTy ||
1544 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001545 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001546 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001547 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001548 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001549 case bitc::TYPE_CODE_FUNCTION_OLD: {
1550 // FIXME: attrid is dead, remove it in LLVM 4.0
1551 // FUNCTION: [vararg, attrid, retty, paramty x N]
1552 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001553 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001554 SmallVector<Type*, 8> ArgTys;
1555 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1556 if (Type *T = getTypeByID(Record[i]))
1557 ArgTys.push_back(T);
1558 else
1559 break;
1560 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001561
Nuno Lopes561dae02012-05-23 15:19:39 +00001562 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001563 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001564 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001565
1566 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1567 break;
1568 }
Chad Rosier95898722011-11-03 00:14:01 +00001569 case bitc::TYPE_CODE_FUNCTION: {
1570 // FUNCTION: [vararg, retty, paramty x N]
1571 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001572 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001573 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001574 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001575 if (Type *T = getTypeByID(Record[i])) {
1576 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001577 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001578 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001579 }
Chad Rosier95898722011-11-03 00:14:01 +00001580 else
1581 break;
1582 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001583
Chad Rosier95898722011-11-03 00:14:01 +00001584 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001585 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001586 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001587
1588 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1589 break;
1590 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001591 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001592 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001593 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001594 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001595 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1596 if (Type *T = getTypeByID(Record[i]))
1597 EltTys.push_back(T);
1598 else
1599 break;
1600 }
1601 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001603 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001604 break;
1605 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001606 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001607 if (convertToString(Record, 0, TypeName))
1608 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001609 continue;
1610
1611 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1612 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001613 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001614
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001615 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001616 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001617
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001618 // Check to see if this was forward referenced, if so fill in the temp.
1619 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1620 if (Res) {
1621 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001622 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001623 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001624 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001626
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001627 SmallVector<Type*, 8> EltTys;
1628 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1629 if (Type *T = getTypeByID(Record[i]))
1630 EltTys.push_back(T);
1631 else
1632 break;
1633 }
1634 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001635 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001636 Res->setBody(EltTys, Record[0]);
1637 ResultTy = Res;
1638 break;
1639 }
1640 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1641 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001642 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001643
1644 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001645 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001646
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 // Check to see if this was forward referenced, if so fill in the temp.
1648 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1649 if (Res) {
1650 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001651 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001652 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001653 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 TypeName.clear();
1655 ResultTy = Res;
1656 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001657 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001658 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1659 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001660 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001661 ResultTy = getTypeByID(Record[1]);
1662 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001663 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001664 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001665 break;
1666 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1667 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001668 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001669 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001670 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001671 ResultTy = getTypeByID(Record[1]);
1672 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001673 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001674 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001675 break;
1676 }
1677
1678 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001679 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001680 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001681 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001682 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001683 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001684 TypeList[NumRecords++] = ResultTy;
1685 }
1686}
1687
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001688std::error_code BitcodeReader::parseOperandBundleTags() {
1689 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1690 return error("Invalid record");
1691
1692 if (!BundleTags.empty())
1693 return error("Invalid multiple blocks");
1694
1695 SmallVector<uint64_t, 64> Record;
1696
1697 while (1) {
1698 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1699
1700 switch (Entry.Kind) {
1701 case BitstreamEntry::SubBlock: // Handled for us already.
1702 case BitstreamEntry::Error:
1703 return error("Malformed block");
1704 case BitstreamEntry::EndBlock:
1705 return std::error_code();
1706 case BitstreamEntry::Record:
1707 // The interesting case.
1708 break;
1709 }
1710
1711 // Tags are implicitly mapped to integers by their order.
1712
1713 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1714 return error("Invalid record");
1715
1716 // OPERAND_BUNDLE_TAG: [strchr x N]
1717 BundleTags.emplace_back();
1718 if (convertToString(Record, 0, BundleTags.back()))
1719 return error("Invalid record");
1720 Record.clear();
1721 }
1722}
1723
Teresa Johnsonff642b92015-09-17 20:12:00 +00001724/// Associate a value with its name from the given index in the provided record.
1725ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1726 unsigned NameIndex, Triple &TT) {
1727 SmallString<128> ValueName;
1728 if (convertToString(Record, NameIndex, ValueName))
1729 return error("Invalid record");
1730 unsigned ValueID = Record[0];
1731 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1732 return error("Invalid record");
1733 Value *V = ValueList[ValueID];
1734
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001735 StringRef NameStr(ValueName.data(), ValueName.size());
1736 if (NameStr.find_first_of(0) != StringRef::npos)
1737 return error("Invalid value name");
1738 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001739 auto *GO = dyn_cast<GlobalObject>(V);
1740 if (GO) {
1741 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1742 if (TT.isOSBinFormatMachO())
1743 GO->setComdat(nullptr);
1744 else
1745 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1746 }
1747 }
1748 return V;
1749}
1750
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001751/// Helper to note and return the current location, and jump to the given
1752/// offset.
1753static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1754 BitstreamCursor &Stream) {
1755 // Save the current parsing location so we can jump back at the end
1756 // of the VST read.
1757 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1758 Stream.JumpToBit(Offset * 32);
1759#ifndef NDEBUG
1760 // Do some checking if we are in debug mode.
1761 BitstreamEntry Entry = Stream.advance();
1762 assert(Entry.Kind == BitstreamEntry::SubBlock);
1763 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1764#else
1765 // In NDEBUG mode ignore the output so we don't get an unused variable
1766 // warning.
1767 Stream.advance();
1768#endif
1769 return CurrentBit;
1770}
1771
Teresa Johnsonff642b92015-09-17 20:12:00 +00001772/// Parse the value symbol table at either the current parsing location or
1773/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001774std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001775 uint64_t CurrentBit;
1776 // Pass in the Offset to distinguish between calling for the module-level
1777 // VST (where we want to jump to the VST offset) and the function-level
1778 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001779 if (Offset > 0)
1780 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001781
1782 // Compute the delta between the bitcode indices in the VST (the word offset
1783 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1784 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1785 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1786 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1787 // just before entering the VST subblock because: 1) the EnterSubBlock
1788 // changes the AbbrevID width; 2) the VST block is nested within the same
1789 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1790 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1791 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1792 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1793 unsigned FuncBitcodeOffsetDelta =
1794 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1795
Chris Lattner982ec1e2007-05-05 00:17:00 +00001796 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001797 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001798
1799 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001800
David Majnemer3087b222015-01-20 05:58:07 +00001801 Triple TT(TheModule->getTargetTriple());
1802
Chris Lattnerccaa4482007-04-23 21:26:05 +00001803 // Read all the records for this value table.
1804 SmallString<128> ValueName;
1805 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001806 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001807
Chris Lattner27d38752013-01-20 02:13:19 +00001808 switch (Entry.Kind) {
1809 case BitstreamEntry::SubBlock: // Handled for us already.
1810 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001811 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001812 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001813 if (Offset > 0)
1814 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001815 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001816 case BitstreamEntry::Record:
1817 // The interesting case.
1818 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001819 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001820
Chris Lattnerccaa4482007-04-23 21:26:05 +00001821 // Read a record.
1822 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001823 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001824 default: // Default behavior: unknown type.
1825 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001826 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001827 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1828 if (std::error_code EC = ValOrErr.getError())
1829 return EC;
1830 ValOrErr.get();
1831 break;
1832 }
1833 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001834 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001835 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1836 if (std::error_code EC = ValOrErr.getError())
1837 return EC;
1838 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001839
Teresa Johnsonff642b92015-09-17 20:12:00 +00001840 auto *GO = dyn_cast<GlobalObject>(V);
1841 if (!GO) {
1842 // If this is an alias, need to get the actual Function object
1843 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1844 auto *GA = dyn_cast<GlobalAlias>(V);
1845 if (GA)
1846 GO = GA->getBaseObject();
1847 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001848 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001849
1850 uint64_t FuncWordOffset = Record[1];
1851 Function *F = dyn_cast<Function>(GO);
1852 assert(F);
1853 uint64_t FuncBitOffset = FuncWordOffset * 32;
1854 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001855 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001856 // Later when parsing is resumed after function materialization,
1857 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001858 if (FuncBitOffset > LastFunctionBlockBit)
1859 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001860 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001861 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001862 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001863 if (convertToString(Record, 1, ValueName))
1864 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001865 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001866 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001867 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001868
Daniel Dunbard786b512009-07-26 00:34:27 +00001869 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001870 ValueName.clear();
1871 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001872 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001873 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001874 }
1875}
1876
Teresa Johnson12545072015-11-15 02:00:09 +00001877/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1878std::error_code
1879BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1880 if (Record.size() < 2)
1881 return error("Invalid record");
1882
1883 unsigned Kind = Record[0];
1884 SmallString<8> Name(Record.begin() + 1, Record.end());
1885
1886 unsigned NewKind = TheModule->getMDKindID(Name.str());
1887 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1888 return error("Conflicting METADATA_KIND records");
1889 return std::error_code();
1890}
1891
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001892static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1893
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001894std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
1895 StringRef Blob,
1896 unsigned &NextMetadataNo) {
1897 // All the MDStrings in the block are emitted together in a single
1898 // record. The strings are concatenated and stored in a blob along with
1899 // their sizes.
1900 if (Record.size() != 2)
1901 return error("Invalid record: metadata strings layout");
1902
1903 unsigned NumStrings = Record[0];
1904 unsigned StringsOffset = Record[1];
1905 if (!NumStrings)
1906 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00001907 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001908 return error("Invalid record: metadata strings corrupt offset");
1909
1910 StringRef Lengths = Blob.slice(0, StringsOffset);
1911 SimpleBitstreamCursor R(*StreamFile);
1912 R.jumpToPointer(Lengths.begin());
1913
1914 // Ensure that Blob doesn't get invalidated, even if this is reading from
1915 // a StreamingMemoryObject with corrupt data.
1916 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
1917
1918 StringRef Strings = Blob.drop_front(StringsOffset);
1919 do {
1920 if (R.AtEndOfStream())
1921 return error("Invalid record: metadata strings bad length");
1922
1923 unsigned Size = R.ReadVBR(6);
1924 if (Strings.size() < Size)
1925 return error("Invalid record: metadata strings truncated chars");
1926
1927 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
1928 NextMetadataNo++);
1929 Strings = Strings.drop_front(Size);
1930 } while (--NumStrings);
1931
1932 return std::error_code();
1933}
1934
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001935/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1936/// module level metadata.
1937std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001938 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001939 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001940
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00001941 if (!ModuleLevel && MetadataList.hasFwdRefs())
1942 return error("Invalid metadata: fwd refs into function blocks");
1943
Devang Patel7428d8a2009-07-22 17:43:22 +00001944 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001945 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001946
Devang Patel7428d8a2009-07-22 17:43:22 +00001947 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001948
Teresa Johnson61b406e2015-12-29 23:00:22 +00001949 auto getMD = [&](unsigned ID) -> Metadata * {
Justin Bognerae341c62016-03-17 20:12:06 +00001950 return MetadataList.getMetadataFwdRef(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00001951 };
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001952 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1953 if (ID)
1954 return getMD(ID - 1);
1955 return nullptr;
1956 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001957 auto getMDString = [&](unsigned ID) -> MDString *{
1958 // This requires that the ID is not really a forward reference. In
1959 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001960 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001961 };
1962
1963#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1964 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1965
Devang Patel7428d8a2009-07-22 17:43:22 +00001966 // Read all the records.
1967 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001968 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001969
Chris Lattner27d38752013-01-20 02:13:19 +00001970 switch (Entry.Kind) {
1971 case BitstreamEntry::SubBlock: // Handled for us already.
1972 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001973 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001974 case BitstreamEntry::EndBlock:
Teresa Johnson61b406e2015-12-29 23:00:22 +00001975 MetadataList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001976 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001977 case BitstreamEntry::Record:
1978 // The interesting case.
1979 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001980 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001981
Devang Patel7428d8a2009-07-22 17:43:22 +00001982 // Read a record.
1983 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001984 StringRef Blob;
1985 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001986 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001987 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001988 default: // Default behavior: ignore.
1989 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001990 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001991 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001992 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001993 Record.clear();
1994 Code = Stream.ReadCode();
1995
Chris Lattner27d38752013-01-20 02:13:19 +00001996 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001997 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001998 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001999
2000 // Read named metadata elements.
2001 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00002002 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00002003 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00002004 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002005 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002006 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00002007 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00002008 }
Devang Patel27c87ff2009-07-29 22:34:41 +00002009 break;
2010 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002011 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002012 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002013 // This is a LocalAsMetadata record, the only type of function-local
2014 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002015 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002016 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002017
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002018 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2019 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002020 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002021 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002022 };
2023 if (Record.size() != 2) {
2024 dropRecord();
2025 break;
2026 }
2027
2028 Type *Ty = getTypeByID(Record[0]);
2029 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2030 dropRecord();
2031 break;
2032 }
2033
Teresa Johnson61b406e2015-12-29 23:00:22 +00002034 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002035 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002036 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002037 break;
2038 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002039 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002040 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002041 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002042 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002043
Devang Patele059ba6e2009-07-23 01:07:34 +00002044 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002045 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002046 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002047 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002048 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002049 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002050 if (Ty->isMetadataTy())
Justin Bognerae341c62016-03-17 20:12:06 +00002051 Elts.push_back(MetadataList.getMetadataFwdRef(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002052 else if (!Ty->isVoidTy()) {
2053 auto *MD =
2054 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2055 assert(isa<ConstantAsMetadata>(MD) &&
2056 "Expected non-function-local metadata");
2057 Elts.push_back(MD);
2058 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002059 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002060 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002061 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002062 break;
2063 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002064 case bitc::METADATA_VALUE: {
2065 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002066 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002067
2068 Type *Ty = getTypeByID(Record[0]);
2069 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002070 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002071
Teresa Johnson61b406e2015-12-29 23:00:22 +00002072 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002073 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002074 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002075 break;
2076 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002077 case bitc::METADATA_DISTINCT_NODE:
2078 IsDistinct = true;
2079 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002080 case bitc::METADATA_NODE: {
2081 SmallVector<Metadata *, 8> Elts;
2082 Elts.reserve(Record.size());
2083 for (unsigned ID : Record)
Justin Bognerae341c62016-03-17 20:12:06 +00002084 Elts.push_back(ID ? MetadataList.getMetadataFwdRef(ID - 1) : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002085 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2086 : MDNode::get(Context, Elts),
2087 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002088 break;
2089 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002090 case bitc::METADATA_LOCATION: {
2091 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002092 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002093
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002094 unsigned Line = Record[1];
2095 unsigned Column = Record[2];
Justin Bognerae341c62016-03-17 20:12:06 +00002096 MDNode *Scope = MetadataList.getMDNodeFwdRefOrNull(Record[3]);
2097 if (!Scope)
2098 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002099 Metadata *InlinedAt =
Justin Bognerae341c62016-03-17 20:12:06 +00002100 Record[4] ? MetadataList.getMetadataFwdRef(Record[4] - 1) : nullptr;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002101 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002102 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002103 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002104 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002105 break;
2106 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002107 case bitc::METADATA_GENERIC_DEBUG: {
2108 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002109 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002110
2111 unsigned Tag = Record[1];
2112 unsigned Version = Record[2];
2113
2114 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002115 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002116
2117 auto *Header = getMDString(Record[3]);
2118 SmallVector<Metadata *, 8> DwarfOps;
2119 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Justin Bognerae341c62016-03-17 20:12:06 +00002120 DwarfOps.push_back(Record[I]
2121 ? MetadataList.getMetadataFwdRef(Record[I] - 1)
2122 : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002123 MetadataList.assignValue(
2124 GET_OR_DISTINCT(GenericDINode, Record[0],
2125 (Context, Tag, Header, DwarfOps)),
2126 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002127 break;
2128 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002129 case bitc::METADATA_SUBRANGE: {
2130 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002131 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002132
Teresa Johnson61b406e2015-12-29 23:00:22 +00002133 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002134 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002135 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002136 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002137 break;
2138 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002139 case bitc::METADATA_ENUMERATOR: {
2140 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002141 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002142
Teresa Johnson61b406e2015-12-29 23:00:22 +00002143 MetadataList.assignValue(
2144 GET_OR_DISTINCT(
2145 DIEnumerator, Record[0],
2146 (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2147 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002148 break;
2149 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002150 case bitc::METADATA_BASIC_TYPE: {
2151 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002152 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002153
Teresa Johnson61b406e2015-12-29 23:00:22 +00002154 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002155 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002156 (Context, Record[1], getMDString(Record[2]),
2157 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002158 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002159 break;
2160 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002161 case bitc::METADATA_DERIVED_TYPE: {
2162 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002163 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002164
Teresa Johnson61b406e2015-12-29 23:00:22 +00002165 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002166 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002167 (Context, Record[1], getMDString(Record[2]),
2168 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00002169 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2170 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002171 getMDOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002172 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002173 break;
2174 }
2175 case bitc::METADATA_COMPOSITE_TYPE: {
2176 if (Record.size() != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002177 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002178
Teresa Johnson61b406e2015-12-29 23:00:22 +00002179 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002180 GET_OR_DISTINCT(DICompositeType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002181 (Context, Record[1], getMDString(Record[2]),
2182 getMDOrNull(Record[3]), Record[4],
2183 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2184 Record[7], Record[8], Record[9], Record[10],
2185 getMDOrNull(Record[11]), Record[12],
2186 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2187 getMDString(Record[15]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002188 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002189 break;
2190 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002191 case bitc::METADATA_SUBROUTINE_TYPE: {
2192 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002193 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002194
Teresa Johnson61b406e2015-12-29 23:00:22 +00002195 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002196 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002197 (Context, Record[1], getMDOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002198 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002199 break;
2200 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002201
2202 case bitc::METADATA_MODULE: {
2203 if (Record.size() != 6)
2204 return error("Invalid record");
2205
Teresa Johnson61b406e2015-12-29 23:00:22 +00002206 MetadataList.assignValue(
Adrian Prantlab1243f2015-06-29 23:03:47 +00002207 GET_OR_DISTINCT(DIModule, Record[0],
2208 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002209 getMDString(Record[2]), getMDString(Record[3]),
2210 getMDString(Record[4]), getMDString(Record[5]))),
2211 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002212 break;
2213 }
2214
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002215 case bitc::METADATA_FILE: {
2216 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002217 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002218
Teresa Johnson61b406e2015-12-29 23:00:22 +00002219 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002220 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002221 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002222 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002223 break;
2224 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002225 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002226 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002227 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002228
Amjad Abouda9bcf162015-12-10 12:56:35 +00002229 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002230 // distinct. It's always distinct.
Teresa Johnson61b406e2015-12-29 23:00:22 +00002231 MetadataList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002232 DICompileUnit::getDistinct(
2233 Context, Record[1], getMDOrNull(Record[2]),
2234 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2235 Record[6], getMDString(Record[7]), Record[8],
2236 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2237 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002238 getMDOrNull(Record[13]),
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00002239 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002240 Record.size() <= 14 ? 0 : Record[14]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002241 NextMetadataNo++);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002242 break;
2243 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002244 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002245 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002246 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002247
Peter Collingbourned4bff302015-11-05 22:03:56 +00002248 bool HasFn = Record.size() == 19;
2249 DISubprogram *SP = GET_OR_DISTINCT(
2250 DISubprogram,
2251 Record[0] || Record[8], // All definitions should be distinct.
2252 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2253 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2254 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2255 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2256 Record[14], getMDOrNull(Record[15 + HasFn]),
2257 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002258 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002259
2260 // Upgrade sp->function mapping to function->sp mapping.
2261 if (HasFn && Record[15]) {
2262 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2263 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2264 if (F->isMaterializable())
2265 // Defer until materialized; unmaterialized functions may not have
2266 // metadata.
2267 FunctionsWithSPs[F] = SP;
2268 else if (!F->empty())
2269 F->setSubprogram(SP);
2270 }
2271 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002272 break;
2273 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002274 case bitc::METADATA_LEXICAL_BLOCK: {
2275 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002276 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002277
Teresa Johnson61b406e2015-12-29 23:00:22 +00002278 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002279 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002280 (Context, getMDOrNull(Record[1]),
2281 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002282 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002283 break;
2284 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002285 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2286 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002287 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002288
Teresa Johnson61b406e2015-12-29 23:00:22 +00002289 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002290 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002291 (Context, getMDOrNull(Record[1]),
2292 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002293 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002294 break;
2295 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002296 case bitc::METADATA_NAMESPACE: {
2297 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002298 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002299
Teresa Johnson61b406e2015-12-29 23:00:22 +00002300 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002301 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002302 (Context, getMDOrNull(Record[1]),
2303 getMDOrNull(Record[2]), getMDString(Record[3]),
2304 Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002305 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002306 break;
2307 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002308 case bitc::METADATA_MACRO: {
2309 if (Record.size() != 5)
2310 return error("Invalid record");
2311
Teresa Johnson61b406e2015-12-29 23:00:22 +00002312 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002313 GET_OR_DISTINCT(DIMacro, Record[0],
2314 (Context, Record[1], Record[2],
2315 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002316 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002317 break;
2318 }
2319 case bitc::METADATA_MACRO_FILE: {
2320 if (Record.size() != 5)
2321 return error("Invalid record");
2322
Teresa Johnson61b406e2015-12-29 23:00:22 +00002323 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002324 GET_OR_DISTINCT(DIMacroFile, Record[0],
2325 (Context, Record[1], Record[2],
2326 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002327 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002328 break;
2329 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002330 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002331 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002332 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002333
Teresa Johnson61b406e2015-12-29 23:00:22 +00002334 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2335 Record[0],
2336 (Context, getMDString(Record[1]),
2337 getMDOrNull(Record[2]))),
2338 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002339 break;
2340 }
2341 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002342 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002343 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002344
Teresa Johnson61b406e2015-12-29 23:00:22 +00002345 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002346 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002347 (Context, Record[1], getMDString(Record[2]),
2348 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002349 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002350 break;
2351 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002352 case bitc::METADATA_GLOBAL_VAR: {
2353 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002354 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002355
Teresa Johnson61b406e2015-12-29 23:00:22 +00002356 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002357 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002358 (Context, getMDOrNull(Record[1]),
2359 getMDString(Record[2]), getMDString(Record[3]),
2360 getMDOrNull(Record[4]), Record[5],
2361 getMDOrNull(Record[6]), Record[7], Record[8],
2362 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002363 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002364 break;
2365 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002366 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002367 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002368 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002369 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002370
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002371 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2372 // DW_TAG_arg_variable.
2373 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002374 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002375 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002376 (Context, getMDOrNull(Record[1 + HasTag]),
2377 getMDString(Record[2 + HasTag]),
2378 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2379 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2380 Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002381 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002382 break;
2383 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002384 case bitc::METADATA_EXPRESSION: {
2385 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002386 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002387
Teresa Johnson61b406e2015-12-29 23:00:22 +00002388 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002389 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002390 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002391 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002392 break;
2393 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002394 case bitc::METADATA_OBJC_PROPERTY: {
2395 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002396 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002397
Teresa Johnson61b406e2015-12-29 23:00:22 +00002398 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002399 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002400 (Context, getMDString(Record[1]),
2401 getMDOrNull(Record[2]), Record[3],
2402 getMDString(Record[4]), getMDString(Record[5]),
2403 Record[6], getMDOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002404 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002405 break;
2406 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002407 case bitc::METADATA_IMPORTED_ENTITY: {
2408 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002409 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002410
Teresa Johnson61b406e2015-12-29 23:00:22 +00002411 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002412 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002413 (Context, Record[1], getMDOrNull(Record[2]),
2414 getMDOrNull(Record[3]), Record[4],
2415 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002416 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002417 break;
2418 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002419 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002420 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002421
2422 // Test for upgrading !llvm.loop.
2423 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2424
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002425 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002426 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002427 break;
2428 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002429 case bitc::METADATA_STRINGS:
2430 if (std::error_code EC =
2431 parseMetadataStrings(Record, Blob, NextMetadataNo))
2432 return EC;
2433 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002434 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002435 // Support older bitcode files that had METADATA_KIND records in a
2436 // block with METADATA_BLOCK_ID.
2437 if (std::error_code EC = parseMetadataKindRecord(Record))
2438 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002439 break;
2440 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002441 }
2442 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002443#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002444}
2445
Teresa Johnson12545072015-11-15 02:00:09 +00002446/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2447std::error_code BitcodeReader::parseMetadataKinds() {
2448 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2449 return error("Invalid record");
2450
2451 SmallVector<uint64_t, 64> Record;
2452
2453 // Read all the records.
2454 while (1) {
2455 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2456
2457 switch (Entry.Kind) {
2458 case BitstreamEntry::SubBlock: // Handled for us already.
2459 case BitstreamEntry::Error:
2460 return error("Malformed block");
2461 case BitstreamEntry::EndBlock:
2462 return std::error_code();
2463 case BitstreamEntry::Record:
2464 // The interesting case.
2465 break;
2466 }
2467
2468 // Read a record.
2469 Record.clear();
2470 unsigned Code = Stream.readRecord(Entry.ID, Record);
2471 switch (Code) {
2472 default: // Default behavior: ignore.
2473 break;
2474 case bitc::METADATA_KIND: {
2475 if (std::error_code EC = parseMetadataKindRecord(Record))
2476 return EC;
2477 break;
2478 }
2479 }
2480 }
2481}
2482
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002483/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2484/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002485uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002486 if ((V & 1) == 0)
2487 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002488 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002489 return -(V >> 1);
2490 // There is no such thing as -0 with integers. "-0" really means MININT.
2491 return 1ULL << 63;
2492}
2493
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002494/// Resolve all of the initializers for global values and aliases that we can.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002495std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002496 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002497 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
2498 IndirectSymbolInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002499 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002500 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002501 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002502
Chris Lattner44c17072007-04-26 02:46:40 +00002503 GlobalInitWorklist.swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002504 IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002505 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002506 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002507 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002508
2509 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002510 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002511 if (ValID >= ValueList.size()) {
2512 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002513 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002514 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002515 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002516 GlobalInitWorklist.back().first->setInitializer(C);
2517 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002518 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002519 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002520 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002521 }
2522
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002523 while (!IndirectSymbolInitWorklist.empty()) {
2524 unsigned ValID = IndirectSymbolInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002525 if (ValID >= ValueList.size()) {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002526 IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002527 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002528 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2529 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002530 return error("Expected a constant");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002531 GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
2532 if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002533 return error("Alias and aliasee types don't match");
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002534 GIS->setIndirectSymbol(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002535 }
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00002536 IndirectSymbolInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002537 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002538
2539 while (!FunctionPrefixWorklist.empty()) {
2540 unsigned ValID = FunctionPrefixWorklist.back().second;
2541 if (ValID >= ValueList.size()) {
2542 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2543 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002544 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002545 FunctionPrefixWorklist.back().first->setPrefixData(C);
2546 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002547 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002548 }
2549 FunctionPrefixWorklist.pop_back();
2550 }
2551
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002552 while (!FunctionPrologueWorklist.empty()) {
2553 unsigned ValID = FunctionPrologueWorklist.back().second;
2554 if (ValID >= ValueList.size()) {
2555 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2556 } else {
2557 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2558 FunctionPrologueWorklist.back().first->setPrologueData(C);
2559 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002560 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002561 }
2562 FunctionPrologueWorklist.pop_back();
2563 }
2564
David Majnemer7fddecc2015-06-17 20:52:32 +00002565 while (!FunctionPersonalityFnWorklist.empty()) {
2566 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2567 if (ValID >= ValueList.size()) {
2568 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2569 } else {
2570 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2571 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2572 else
2573 return error("Expected a constant");
2574 }
2575 FunctionPersonalityFnWorklist.pop_back();
2576 }
2577
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002578 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002579}
2580
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002581static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002582 SmallVector<uint64_t, 8> Words(Vals.size());
2583 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002584 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002585
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002586 return APInt(TypeBits, Words);
2587}
2588
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002589std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002590 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002591 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002592
2593 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002594
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002595 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002596 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002597 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002598 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002599 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002600
Chris Lattner27d38752013-01-20 02:13:19 +00002601 switch (Entry.Kind) {
2602 case BitstreamEntry::SubBlock: // Handled for us already.
2603 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002604 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002605 case BitstreamEntry::EndBlock:
2606 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002607 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002608
Chris Lattner27d38752013-01-20 02:13:19 +00002609 // Once all the constants have been read, go through and resolve forward
2610 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002611 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002612 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002613 case BitstreamEntry::Record:
2614 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002615 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002616 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002617
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002618 // Read a record.
2619 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002620 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002621 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002622 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002623 default: // Default behavior: unknown constant
2624 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002625 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002626 break;
2627 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2628 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002629 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002630 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002631 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002632 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002633 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002634 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002635 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002636 break;
2637 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002638 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002639 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002640 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002641 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002642 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002643 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002644 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002645
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002646 APInt VInt =
2647 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002648 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002649
Chris Lattner08feb1e2007-04-24 04:04:35 +00002650 break;
2651 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002652 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002653 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002654 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002655 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002656 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2657 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002658 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002659 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2660 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002661 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002662 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2663 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002664 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002665 // Bits are not stored the same way as a normal i80 APInt, compensate.
2666 uint64_t Rearrange[2];
2667 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2668 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002669 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2670 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002671 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002672 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2673 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002674 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002675 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2676 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002677 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002678 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002679 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002680 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002681
Chris Lattnere14cb882007-05-04 19:11:41 +00002682 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2683 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002684 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002685
Chris Lattnere14cb882007-05-04 19:11:41 +00002686 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002687 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002688
Chris Lattner229907c2011-07-18 04:54:35 +00002689 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002690 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002691 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002692 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002693 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002694 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2695 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002696 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002697 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002698 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002699 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2700 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002701 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002702 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002703 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002704 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002705 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002706 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002707 break;
2708 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002709 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002710 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2711 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002712 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002713
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002714 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002715 V = ConstantDataArray::getString(Context, Elts,
2716 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002717 break;
2718 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002719 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2720 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002721 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002722
Chris Lattner372dd1e2012-01-30 00:51:16 +00002723 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002724 if (EltTy->isIntegerTy(8)) {
2725 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2726 if (isa<VectorType>(CurTy))
2727 V = ConstantDataVector::get(Context, Elts);
2728 else
2729 V = ConstantDataArray::get(Context, Elts);
2730 } else if (EltTy->isIntegerTy(16)) {
2731 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2732 if (isa<VectorType>(CurTy))
2733 V = ConstantDataVector::get(Context, Elts);
2734 else
2735 V = ConstantDataArray::get(Context, Elts);
2736 } else if (EltTy->isIntegerTy(32)) {
2737 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2738 if (isa<VectorType>(CurTy))
2739 V = ConstantDataVector::get(Context, Elts);
2740 else
2741 V = ConstantDataArray::get(Context, Elts);
2742 } else if (EltTy->isIntegerTy(64)) {
2743 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2744 if (isa<VectorType>(CurTy))
2745 V = ConstantDataVector::get(Context, Elts);
2746 else
2747 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002748 } else if (EltTy->isHalfTy()) {
2749 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2750 if (isa<VectorType>(CurTy))
2751 V = ConstantDataVector::getFP(Context, Elts);
2752 else
2753 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002754 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002755 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002756 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002757 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002758 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002759 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002760 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002761 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002762 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002763 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002764 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002765 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002766 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002767 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002768 }
2769 break;
2770 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002771 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002772 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002773 return error("Invalid record");
2774 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002775 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002776 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002777 } else {
2778 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2779 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002780 unsigned Flags = 0;
2781 if (Record.size() >= 4) {
2782 if (Opc == Instruction::Add ||
2783 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002784 Opc == Instruction::Mul ||
2785 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002786 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2787 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2788 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2789 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002790 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002791 Opc == Instruction::UDiv ||
2792 Opc == Instruction::LShr ||
2793 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002794 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002795 Flags |= SDivOperator::IsExact;
2796 }
2797 }
2798 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002799 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002800 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002801 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002802 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002803 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002804 return error("Invalid record");
2805 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002806 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002807 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002808 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002809 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002810 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002811 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002812 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002813 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2814 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002815 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002816 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002817 }
Dan Gohman1639c392009-07-27 21:53:46 +00002818 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002819 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002820 unsigned OpNum = 0;
2821 Type *PointeeType = nullptr;
2822 if (Record.size() % 2)
2823 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002824 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002825 while (OpNum != Record.size()) {
2826 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002827 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002828 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002829 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002830 }
David Blaikieb9263572015-03-13 21:03:36 +00002831
David Blaikieb9263572015-03-13 21:03:36 +00002832 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002833 PointeeType !=
2834 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2835 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002836 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002837 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002838
2839 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2840 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2841 BitCode ==
2842 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002843 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002844 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002845 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002846 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002847 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002848
2849 Type *SelectorTy = Type::getInt1Ty(Context);
2850
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002851 // The selector might be an i1 or an <n x i1>
2852 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002853 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002854 if (Value *V = ValueList[Record[0]])
2855 if (SelectorTy != V->getType())
2856 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002857
2858 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2859 SelectorTy),
2860 ValueList.getConstantFwdRef(Record[1],CurTy),
2861 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002862 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002863 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002864 case bitc::CST_CODE_CE_EXTRACTELT
2865 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002866 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002867 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002868 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002869 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002870 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002871 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002872 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002873 Constant *Op1 = nullptr;
2874 if (Record.size() == 4) {
2875 Type *IdxTy = getTypeByID(Record[2]);
2876 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002877 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002878 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2879 } else // TODO: Remove with llvm 4.0
2880 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2881 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002882 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002883 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002884 break;
2885 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002886 case bitc::CST_CODE_CE_INSERTELT
2887 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002888 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002889 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002890 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002891 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2892 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2893 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002894 Constant *Op2 = nullptr;
2895 if (Record.size() == 4) {
2896 Type *IdxTy = getTypeByID(Record[2]);
2897 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002898 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002899 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2900 } else // TODO: Remove with llvm 4.0
2901 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2902 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002903 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002904 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002905 break;
2906 }
2907 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002908 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002909 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002910 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002911 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2912 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002913 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002914 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002915 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002916 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002917 break;
2918 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002919 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002920 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2921 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002922 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002923 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002924 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002925 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2926 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002927 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002928 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002929 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002930 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002931 break;
2932 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002933 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002934 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002935 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002936 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002937 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002938 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002939 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2940 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2941
Duncan Sands9dff9be2010-02-15 16:12:20 +00002942 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002943 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002944 else
Owen Anderson487375e2009-07-29 18:55:55 +00002945 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002946 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002947 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002948 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002949 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002950 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002951 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002952 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002953 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002954 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002955 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002956 unsigned AsmStrSize = Record[1];
2957 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002958 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002959 unsigned ConstStrSize = Record[2+AsmStrSize];
2960 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002961 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002962
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002963 for (unsigned i = 0; i != AsmStrSize; ++i)
2964 AsmStr += (char)Record[2+i];
2965 for (unsigned i = 0; i != ConstStrSize; ++i)
2966 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002967 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002968 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002969 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002970 break;
2971 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002972 // This version adds support for the asm dialect keywords (e.g.,
2973 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002974 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002975 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002976 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002977 std::string AsmStr, ConstrStr;
2978 bool HasSideEffects = Record[0] & 1;
2979 bool IsAlignStack = (Record[0] >> 1) & 1;
2980 unsigned AsmDialect = Record[0] >> 2;
2981 unsigned AsmStrSize = Record[1];
2982 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002983 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002984 unsigned ConstStrSize = Record[2+AsmStrSize];
2985 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002986 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002987
2988 for (unsigned i = 0; i != AsmStrSize; ++i)
2989 AsmStr += (char)Record[2+i];
2990 for (unsigned i = 0; i != ConstStrSize; ++i)
2991 ConstrStr += (char)Record[3+AsmStrSize+i];
2992 PointerType *PTy = cast<PointerType>(CurTy);
2993 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2994 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002995 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002996 break;
2997 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002998 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002999 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003000 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003001 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00003002 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003003 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00003004 Function *Fn =
3005 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00003006 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003007 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003008
3009 // If the function is already parsed we can insert the block address right
3010 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003011 BasicBlock *BB;
3012 unsigned BBID = Record[2];
3013 if (!BBID)
3014 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003015 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003016 if (!Fn->empty()) {
3017 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003018 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003019 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003020 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003021 ++BBI;
3022 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003023 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003024 } else {
3025 // Otherwise insert a placeholder and remember it so it can be inserted
3026 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003027 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3028 if (FwdBBs.empty())
3029 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003030 if (FwdBBs.size() < BBID + 1)
3031 FwdBBs.resize(BBID + 1);
3032 if (!FwdBBs[BBID])
3033 FwdBBs[BBID] = BasicBlock::Create(Context);
3034 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003035 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003036 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003037 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003038 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003039 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003040
David Majnemer8a1c45d2015-12-12 05:38:55 +00003041 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003042 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003043 }
3044}
Chris Lattner1314b992007-04-22 06:23:29 +00003045
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003046std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003047 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003048 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003049
Chad Rosierca2567b2011-12-07 21:44:12 +00003050 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003051 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003052 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003053 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003054
Chris Lattner27d38752013-01-20 02:13:19 +00003055 switch (Entry.Kind) {
3056 case BitstreamEntry::SubBlock: // Handled for us already.
3057 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003058 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003059 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003060 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003061 case BitstreamEntry::Record:
3062 // The interesting case.
3063 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003064 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003065
Chad Rosierca2567b2011-12-07 21:44:12 +00003066 // Read a use list record.
3067 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003068 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003069 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003070 default: // Default behavior: unknown type.
3071 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003072 case bitc::USELIST_CODE_BB:
3073 IsBB = true;
3074 // fallthrough
3075 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003076 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003077 if (RecordLength < 3)
3078 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003079 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003080 unsigned ID = Record.back();
3081 Record.pop_back();
3082
3083 Value *V;
3084 if (IsBB) {
3085 assert(ID < FunctionBBs.size() && "Basic block not found");
3086 V = FunctionBBs[ID];
3087 } else
3088 V = ValueList[ID];
3089 unsigned NumUses = 0;
3090 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003091 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003092 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003093 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003094 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003095 }
3096 if (Order.size() != Record.size() || NumUses > Record.size())
3097 // Mismatches can happen if the functions are being materialized lazily
3098 // (out-of-order), or a value has been upgraded.
3099 break;
3100
3101 V->sortUseList([&](const Use &L, const Use &R) {
3102 return Order.lookup(&L) < Order.lookup(&R);
3103 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003104 break;
3105 }
3106 }
3107 }
3108}
3109
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003110/// When we see the block for metadata, remember where it is and then skip it.
3111/// This lets us lazily deserialize the metadata.
3112std::error_code BitcodeReader::rememberAndSkipMetadata() {
3113 // Save the current stream state.
3114 uint64_t CurBit = Stream.GetCurrentBitNo();
3115 DeferredMetadataInfo.push_back(CurBit);
3116
3117 // Skip over the block for now.
3118 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003119 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003120 return std::error_code();
3121}
3122
3123std::error_code BitcodeReader::materializeMetadata() {
3124 for (uint64_t BitPos : DeferredMetadataInfo) {
3125 // Move the bit stream to the saved position.
3126 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003127 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003128 return EC;
3129 }
3130 DeferredMetadataInfo.clear();
3131 return std::error_code();
3132}
3133
Rafael Espindola468b8682015-04-01 14:44:59 +00003134void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003135
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003136/// When we see the block for a function body, remember where it is and then
3137/// skip it. This lets us lazily deserialize the functions.
3138std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003139 // Get the function we are talking about.
3140 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003141 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003142
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003143 Function *Fn = FunctionsWithBodies.back();
3144 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003145
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003146 // Save the current stream state.
3147 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003148 assert(
3149 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3150 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003151 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003152
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003153 // Skip over the function block for now.
3154 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003155 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003156 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003157}
3158
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003159std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003160 // Patch the initializers for globals and aliases up.
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003161 resolveGlobalAndIndirectSymbolInits();
3162 if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003163 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003164
3165 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003166 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003167 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003168 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003169 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003170 }
3171
3172 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003173 for (GlobalVariable &GV : TheModule->globals())
3174 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003175
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003176 // Force deallocation of memory for these vectors to favor the client that
3177 // want lazy deserialization.
3178 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003179 std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
3180 IndirectSymbolInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003181 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003182}
3183
Teresa Johnson1493ad92015-10-10 14:18:36 +00003184/// Support for lazy parsing of function bodies. This is required if we
3185/// either have an old bitcode file without a VST forward declaration record,
3186/// or if we have an anonymous function being materialized, since anonymous
3187/// functions do not have a name and are therefore not in the VST.
3188std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3189 Stream.JumpToBit(NextUnreadBit);
3190
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003191 if (Stream.AtEndOfStream())
3192 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003193
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003194 if (!SeenFirstFunctionBody)
3195 return error("Trying to materialize functions before seeing function blocks");
3196
Teresa Johnson1493ad92015-10-10 14:18:36 +00003197 // An old bitcode file with the symbol table at the end would have
3198 // finished the parse greedily.
3199 assert(SeenValueSymbolTable);
3200
3201 SmallVector<uint64_t, 64> Record;
3202
3203 while (1) {
3204 BitstreamEntry Entry = Stream.advance();
3205 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003206 default:
3207 return error("Expect SubBlock");
3208 case BitstreamEntry::SubBlock:
3209 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003210 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003211 return error("Expect function block");
3212 case bitc::FUNCTION_BLOCK_ID:
3213 if (std::error_code EC = rememberAndSkipFunctionBody())
3214 return EC;
3215 NextUnreadBit = Stream.GetCurrentBitNo();
3216 return std::error_code();
3217 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003218 }
3219 }
3220}
3221
Mehdi Amini5d303282015-10-26 18:37:00 +00003222std::error_code BitcodeReader::parseBitcodeVersion() {
3223 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3224 return error("Invalid record");
3225
3226 // Read all the records.
3227 SmallVector<uint64_t, 64> Record;
3228 while (1) {
3229 BitstreamEntry Entry = Stream.advance();
3230
3231 switch (Entry.Kind) {
3232 default:
3233 case BitstreamEntry::Error:
3234 return error("Malformed block");
3235 case BitstreamEntry::EndBlock:
3236 return std::error_code();
3237 case BitstreamEntry::Record:
3238 // The interesting case.
3239 break;
3240 }
3241
3242 // Read a record.
3243 Record.clear();
3244 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3245 switch (BitCode) {
3246 default: // Default behavior: reject
3247 return error("Invalid value");
3248 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3249 // N]
3250 convertToString(Record, 0, ProducerIdentification);
3251 break;
3252 }
3253 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3254 unsigned epoch = (unsigned)Record[0];
3255 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003256 return error(
3257 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3258 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003259 }
3260 }
3261 }
3262 }
3263}
3264
Teresa Johnson1493ad92015-10-10 14:18:36 +00003265std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003266 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003267 if (ResumeBit)
3268 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003269 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003270 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003271
Chris Lattner1314b992007-04-22 06:23:29 +00003272 SmallVector<uint64_t, 64> Record;
3273 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003274 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003275
3276 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003277 while (1) {
3278 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003279
Chris Lattner27d38752013-01-20 02:13:19 +00003280 switch (Entry.Kind) {
3281 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003282 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003283 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003284 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003285
Chris Lattner27d38752013-01-20 02:13:19 +00003286 case BitstreamEntry::SubBlock:
3287 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003288 default: // Skip unknown content.
3289 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003290 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003291 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003292 case bitc::BLOCKINFO_BLOCK_ID:
3293 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003294 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003295 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003296 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003297 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003298 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003299 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003300 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003301 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003302 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003303 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003304 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003305 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003306 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003307 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003308 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003309 if (!SeenValueSymbolTable) {
3310 // Either this is an old form VST without function index and an
3311 // associated VST forward declaration record (which would have caused
3312 // the VST to be jumped to and parsed before it was encountered
3313 // normally in the stream), or there were no function blocks to
3314 // trigger an earlier parsing of the VST.
3315 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3316 if (std::error_code EC = parseValueSymbolTable())
3317 return EC;
3318 SeenValueSymbolTable = true;
3319 } else {
3320 // We must have had a VST forward declaration record, which caused
3321 // the parser to jump to and parse the VST earlier.
3322 assert(VSTOffset > 0);
3323 if (Stream.SkipBlock())
3324 return error("Invalid record");
3325 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003326 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003327 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003328 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003329 return EC;
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003330 if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003331 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003332 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003333 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003334 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3335 if (std::error_code EC = rememberAndSkipMetadata())
3336 return EC;
3337 break;
3338 }
3339 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003340 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003341 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003342 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003343 case bitc::METADATA_KIND_BLOCK_ID:
3344 if (std::error_code EC = parseMetadataKinds())
3345 return EC;
3346 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003347 case bitc::FUNCTION_BLOCK_ID:
3348 // If this is the first function body we've seen, reverse the
3349 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003350 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003351 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003352 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003353 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003354 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003355 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003356
Teresa Johnsonff642b92015-09-17 20:12:00 +00003357 if (VSTOffset > 0) {
3358 // If we have a VST forward declaration record, make sure we
3359 // parse the VST now if we haven't already. It is needed to
3360 // set up the DeferredFunctionInfo vector for lazy reading.
3361 if (!SeenValueSymbolTable) {
3362 if (std::error_code EC =
3363 BitcodeReader::parseValueSymbolTable(VSTOffset))
3364 return EC;
3365 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003366 // Fall through so that we record the NextUnreadBit below.
3367 // This is necessary in case we have an anonymous function that
3368 // is later materialized. Since it will not have a VST entry we
3369 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003370 } else {
3371 // If we have a VST forward declaration record, but have already
3372 // parsed the VST (just above, when the first function body was
3373 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003374 // materializing functions. The ResumeBit points to the
3375 // start of the last function block recorded in the
3376 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003377 if (Stream.SkipBlock())
3378 return error("Invalid record");
3379 continue;
3380 }
3381 }
3382
3383 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003384 // index in the VST, nor a VST forward declaration record, as
3385 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003386 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003387 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003388 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003389
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003390 // Suspend parsing when we reach the function bodies. Subsequent
3391 // materialization calls will resume it when necessary. If the bitcode
3392 // file is old, the symbol table will be at the end instead and will not
3393 // have been seen yet. In this case, just finish the parse now.
3394 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003395 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003396 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003397 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003398 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003399 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003400 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003401 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003402 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003403 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3404 if (std::error_code EC = parseOperandBundleTags())
3405 return EC;
3406 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003407 }
3408 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003409
Chris Lattner27d38752013-01-20 02:13:19 +00003410 case BitstreamEntry::Record:
3411 // The interesting case.
3412 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003413 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003414
Chris Lattner1314b992007-04-22 06:23:29 +00003415 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003416 auto BitCode = Stream.readRecord(Entry.ID, Record);
3417 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003418 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003419 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003420 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003421 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003422 // Only version #0 and #1 are supported so far.
3423 unsigned module_version = Record[0];
3424 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003425 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003426 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003427 case 0:
3428 UseRelativeIDs = false;
3429 break;
3430 case 1:
3431 UseRelativeIDs = true;
3432 break;
3433 }
Chris Lattner1314b992007-04-22 06:23:29 +00003434 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003435 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003436 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003437 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003438 if (convertToString(Record, 0, S))
3439 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003440 TheModule->setTargetTriple(S);
3441 break;
3442 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003443 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003444 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003445 if (convertToString(Record, 0, S))
3446 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003447 TheModule->setDataLayout(S);
3448 break;
3449 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003450 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003451 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003452 if (convertToString(Record, 0, S))
3453 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003454 TheModule->setModuleInlineAsm(S);
3455 break;
3456 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003457 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3458 // FIXME: Remove in 4.0.
3459 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003460 if (convertToString(Record, 0, S))
3461 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003462 // Ignore value.
3463 break;
3464 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003465 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003466 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003467 if (convertToString(Record, 0, S))
3468 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003469 SectionTable.push_back(S);
3470 break;
3471 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003472 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003473 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003474 if (convertToString(Record, 0, S))
3475 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003476 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003477 break;
3478 }
David Majnemerdad0a642014-06-27 18:19:56 +00003479 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3480 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003481 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003482 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3483 unsigned ComdatNameSize = Record[1];
3484 std::string ComdatName;
3485 ComdatName.reserve(ComdatNameSize);
3486 for (unsigned i = 0; i != ComdatNameSize; ++i)
3487 ComdatName += (char)Record[2 + i];
3488 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3489 C->setSelectionKind(SK);
3490 ComdatList.push_back(C);
3491 break;
3492 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003493 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003494 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003495 // unnamed_addr, externally_initialized, dllstorageclass,
3496 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003497 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003498 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003499 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003500 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003501 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003502 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003503 bool isConstant = Record[1] & 1;
3504 bool explicitType = Record[1] & 2;
3505 unsigned AddressSpace;
3506 if (explicitType) {
3507 AddressSpace = Record[1] >> 2;
3508 } else {
3509 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003510 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003511 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3512 Ty = cast<PointerType>(Ty)->getElementType();
3513 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003514
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003515 uint64_t RawLinkage = Record[3];
3516 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003517 unsigned Alignment;
3518 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3519 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003520 std::string Section;
3521 if (Record[5]) {
3522 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003523 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003524 Section = SectionTable[Record[5]-1];
3525 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003526 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003527 // Local linkage must have default visibility.
3528 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3529 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003530 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003531
3532 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003533 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003534 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003535
Rafael Espindola45e6c192011-01-08 16:42:36 +00003536 bool UnnamedAddr = false;
3537 if (Record.size() > 8)
3538 UnnamedAddr = Record[8];
3539
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003540 bool ExternallyInitialized = false;
3541 if (Record.size() > 9)
3542 ExternallyInitialized = Record[9];
3543
Chris Lattner1314b992007-04-22 06:23:29 +00003544 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003545 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003546 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003547 NewGV->setAlignment(Alignment);
3548 if (!Section.empty())
3549 NewGV->setSection(Section);
3550 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003551 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003552
Nico Rieck7157bb72014-01-14 15:22:47 +00003553 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003554 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003555 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003556 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003557
Chris Lattnerccaa4482007-04-23 21:26:05 +00003558 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003559
Chris Lattner47d131b2007-04-24 00:18:21 +00003560 // Remember which value to use for the global initializer.
3561 if (unsigned InitID = Record[2])
3562 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003563
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003564 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003565 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003566 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003567 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003568 NewGV->setComdat(ComdatList[ComdatID - 1]);
3569 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003570 } else if (hasImplicitComdat(RawLinkage)) {
3571 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3572 }
Chris Lattner1314b992007-04-22 06:23:29 +00003573 break;
3574 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003575 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003576 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003577 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003578 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003579 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003580 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003581 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003582 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003583 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003584 if (auto *PTy = dyn_cast<PointerType>(Ty))
3585 Ty = PTy->getElementType();
3586 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003587 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003588 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003589 auto CC = static_cast<CallingConv::ID>(Record[1]);
3590 if (CC & ~CallingConv::MaxID)
3591 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003592
Gabor Greife9ecc682008-04-06 20:25:17 +00003593 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3594 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003595
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003596 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003597 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003598 uint64_t RawLinkage = Record[3];
3599 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003600 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003601
JF Bastien30bf96b2015-02-22 19:32:03 +00003602 unsigned Alignment;
3603 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3604 return EC;
3605 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003606 if (Record[6]) {
3607 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003608 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003609 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003610 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003611 // Local linkage must have default visibility.
3612 if (!Func->hasLocalLinkage())
3613 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003614 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003615 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003616 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003617 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003618 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003619 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003620 bool UnnamedAddr = false;
3621 if (Record.size() > 9)
3622 UnnamedAddr = Record[9];
3623 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003624 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003625 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003626
3627 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003628 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003629 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003630 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003631
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003632 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003633 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003634 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003635 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003636 Func->setComdat(ComdatList[ComdatID - 1]);
3637 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003638 } else if (hasImplicitComdat(RawLinkage)) {
3639 Func->setComdat(reinterpret_cast<Comdat *>(1));
3640 }
David Majnemerdad0a642014-06-27 18:19:56 +00003641
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003642 if (Record.size() > 13 && Record[13] != 0)
3643 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3644
David Majnemer7fddecc2015-06-17 20:52:32 +00003645 if (Record.size() > 14 && Record[14] != 0)
3646 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3647
Chris Lattnerccaa4482007-04-23 21:26:05 +00003648 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003649
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003650 // If this is a function with a body, remember the prototype we are
3651 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003652 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003653 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003654 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003655 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003656 }
Chris Lattner1314b992007-04-22 06:23:29 +00003657 break;
3658 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003659 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3660 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3661 case bitc::MODULE_CODE_ALIAS:
3662 case bitc::MODULE_CODE_ALIAS_OLD: {
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003663 bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003664 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003665 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003666 unsigned OpNum = 0;
3667 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003668 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003669 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003670
David Blaikie6a51dbd2015-09-17 22:18:59 +00003671 unsigned AddrSpace;
3672 if (!NewRecord) {
3673 auto *PTy = dyn_cast<PointerType>(Ty);
3674 if (!PTy)
3675 return error("Invalid type for value");
3676 Ty = PTy->getElementType();
3677 AddrSpace = PTy->getAddressSpace();
3678 } else {
3679 AddrSpace = Record[OpNum++];
3680 }
3681
3682 auto Val = Record[OpNum++];
3683 auto Linkage = Record[OpNum++];
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003684 GlobalIndirectSymbol *NewGA;
3685 if (BitCode == bitc::MODULE_CODE_ALIAS ||
3686 BitCode == bitc::MODULE_CODE_ALIAS_OLD)
3687 NewGA = GlobalAlias::create(
David Blaikie6a51dbd2015-09-17 22:18:59 +00003688 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003689 else
3690 llvm_unreachable("Not an alias!");
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003691 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003692 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003693 if (OpNum != Record.size()) {
3694 auto VisInd = OpNum++;
3695 if (!NewGA->hasLocalLinkage())
3696 // FIXME: Change to an error if non-default in 4.0.
3697 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3698 }
3699 if (OpNum != Record.size())
3700 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003701 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003702 upgradeDLLImportExportLinkage(NewGA, Linkage);
3703 if (OpNum != Record.size())
3704 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3705 if (OpNum != Record.size())
3706 NewGA->setUnnamedAddr(Record[OpNum++]);
Chris Lattner44c17072007-04-26 02:46:40 +00003707 ValueList.push_back(NewGA);
Dmitry Polukhina3d5b0b2016-04-05 08:47:51 +00003708 IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003709 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003710 }
Chris Lattner831d4202007-04-26 03:27:58 +00003711 /// MODULE_CODE_PURGEVALS: [numvals]
3712 case bitc::MODULE_CODE_PURGEVALS:
3713 // Trim down the value list to the specified size.
3714 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003715 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003716 ValueList.shrinkTo(Record[0]);
3717 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003718 /// MODULE_CODE_VSTOFFSET: [offset]
3719 case bitc::MODULE_CODE_VSTOFFSET:
3720 if (Record.size() < 1)
3721 return error("Invalid record");
3722 VSTOffset = Record[0];
3723 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003724 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3725 case bitc::MODULE_CODE_SOURCE_FILENAME:
3726 SmallString<128> ValueName;
3727 if (convertToString(Record, 0, ValueName))
3728 return error("Invalid record");
3729 TheModule->setSourceFileName(ValueName);
3730 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003731 }
Chris Lattner1314b992007-04-22 06:23:29 +00003732 Record.clear();
3733 }
Chris Lattner1314b992007-04-22 06:23:29 +00003734}
3735
Teresa Johnson403a7872015-10-04 14:33:43 +00003736/// Helper to read the header common to all bitcode files.
3737static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3738 // Sniff for the signature.
3739 if (Stream.Read(8) != 'B' ||
3740 Stream.Read(8) != 'C' ||
3741 Stream.Read(4) != 0x0 ||
3742 Stream.Read(4) != 0xC ||
3743 Stream.Read(4) != 0xE ||
3744 Stream.Read(4) != 0xD)
3745 return false;
3746 return true;
3747}
3748
Rafael Espindola1aabf982015-06-16 23:29:49 +00003749std::error_code
3750BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3751 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003752 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003753
Rafael Espindola1aabf982015-06-16 23:29:49 +00003754 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003755 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003756
Chris Lattner1314b992007-04-22 06:23:29 +00003757 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003758 if (!hasValidBitcodeHeader(Stream))
3759 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003760
Chris Lattner1314b992007-04-22 06:23:29 +00003761 // We expect a number of well-defined blocks, though we don't necessarily
3762 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003763 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003764 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003765 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003766 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003767 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003768
Chris Lattner27d38752013-01-20 02:13:19 +00003769 BitstreamEntry Entry =
3770 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003771
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003772 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003773 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003774
Mehdi Amini5d303282015-10-26 18:37:00 +00003775 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3776 parseBitcodeVersion();
3777 continue;
3778 }
3779
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003780 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00003781 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003782
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003783 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003784 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003785 }
Chris Lattner1314b992007-04-22 06:23:29 +00003786}
Chris Lattner6694f602007-04-29 07:54:31 +00003787
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003788ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003789 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003790 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003791
3792 SmallVector<uint64_t, 64> Record;
3793
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003794 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003795 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003796 while (1) {
3797 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003798
Chris Lattner27d38752013-01-20 02:13:19 +00003799 switch (Entry.Kind) {
3800 case BitstreamEntry::SubBlock: // Handled for us already.
3801 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003802 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003803 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003804 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003805 case BitstreamEntry::Record:
3806 // The interesting case.
3807 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003808 }
3809
3810 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003811 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003812 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003813 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003814 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003815 if (convertToString(Record, 0, S))
3816 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003817 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003818 break;
3819 }
3820 }
3821 Record.clear();
3822 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003823 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003824}
3825
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003826ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003827 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003828 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003829
3830 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003831 if (!hasValidBitcodeHeader(Stream))
3832 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003833
3834 // We expect a number of well-defined blocks, though we don't necessarily
3835 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003836 while (1) {
3837 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003838
Chris Lattner27d38752013-01-20 02:13:19 +00003839 switch (Entry.Kind) {
3840 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003841 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003842 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003843 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003844
Chris Lattner27d38752013-01-20 02:13:19 +00003845 case BitstreamEntry::SubBlock:
3846 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003847 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003848
Chris Lattner27d38752013-01-20 02:13:19 +00003849 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003850 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003851 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003852 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003853
Chris Lattner27d38752013-01-20 02:13:19 +00003854 case BitstreamEntry::Record:
3855 Stream.skipRecord(Entry.ID);
3856 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003857 }
3858 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003859}
3860
Mehdi Amini3383ccc2015-11-09 02:46:41 +00003861ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3862 if (std::error_code EC = initStream(nullptr))
3863 return EC;
3864
3865 // Sniff for the signature.
3866 if (!hasValidBitcodeHeader(Stream))
3867 return error("Invalid bitcode signature");
3868
3869 // We expect a number of well-defined blocks, though we don't necessarily
3870 // need to understand them all.
3871 while (1) {
3872 BitstreamEntry Entry = Stream.advance();
3873 switch (Entry.Kind) {
3874 case BitstreamEntry::Error:
3875 return error("Malformed block");
3876 case BitstreamEntry::EndBlock:
3877 return std::error_code();
3878
3879 case BitstreamEntry::SubBlock:
3880 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3881 if (std::error_code EC = parseBitcodeVersion())
3882 return EC;
3883 return ProducerIdentification;
3884 }
3885 // Ignore other sub-blocks.
3886 if (Stream.SkipBlock())
3887 return error("Malformed block");
3888 continue;
3889 case BitstreamEntry::Record:
3890 Stream.skipRecord(Entry.ID);
3891 continue;
3892 }
3893 }
3894}
3895
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003896/// Parse metadata attachments.
3897std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003898 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003899 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003900
Devang Patelaf206b82009-09-18 19:26:43 +00003901 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003902 while (1) {
3903 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003904
Chris Lattner27d38752013-01-20 02:13:19 +00003905 switch (Entry.Kind) {
3906 case BitstreamEntry::SubBlock: // Handled for us already.
3907 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003908 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003909 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003910 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003911 case BitstreamEntry::Record:
3912 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003913 break;
3914 }
Chris Lattner27d38752013-01-20 02:13:19 +00003915
Devang Patelaf206b82009-09-18 19:26:43 +00003916 // Read a metadata attachment record.
3917 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003918 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003919 default: // Default behavior: ignore.
3920 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003921 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003922 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003923 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003924 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003925 if (RecordLength % 2 == 0) {
3926 // A function attachment.
3927 for (unsigned I = 0; I != RecordLength; I += 2) {
3928 auto K = MDKindMap.find(Record[I]);
3929 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003930 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003931 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
3932 if (!MD)
3933 return error("Invalid metadata attachment");
3934 F.setMetadata(K->second, MD);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003935 }
3936 continue;
3937 }
3938
3939 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003940 Instruction *Inst = InstructionList[Record[0]];
3941 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003942 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003943 DenseMap<unsigned, unsigned>::iterator I =
3944 MDKindMap.find(Kind);
3945 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003946 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003947 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003948 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003949 // Drop the attachment. This used to be legal, but there's no
3950 // upgrade path.
3951 break;
Justin Bognerae341c62016-03-17 20:12:06 +00003952 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
3953 if (!MD)
3954 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003955
3956 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
3957 MD = upgradeInstructionLoopAttachment(*MD);
3958
Justin Bognerae341c62016-03-17 20:12:06 +00003959 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003960 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00003961 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003962 continue;
3963 }
Devang Patelaf206b82009-09-18 19:26:43 +00003964 }
3965 break;
3966 }
3967 }
3968 }
Devang Patelaf206b82009-09-18 19:26:43 +00003969}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003970
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003971static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3972 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003973 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003974 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003975 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3976
3977 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003978 return error(Context, "Explicit load/store type does not match pointee "
3979 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003980 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003981 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003982 return std::error_code();
3983}
3984
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003985/// Lazily parse the specified function body block.
3986std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003987 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003988 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003989
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00003990 // Unexpected unresolved metadata when parsing function.
3991 if (MetadataList.hasFwdRefs())
3992 return error("Invalid function metadata: incoming forward references");
3993
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003994 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003995 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00003996 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003997
Chris Lattner85b7b402007-05-01 05:52:21 +00003998 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003999 for (Argument &I : F->args())
4000 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004001
Chris Lattner83930552007-05-01 07:01:57 +00004002 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00004003 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00004004 unsigned CurBBNo = 0;
4005
Chris Lattner07d09ed2010-04-03 02:17:50 +00004006 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004007 auto getLastInstruction = [&]() -> Instruction * {
4008 if (CurBB && !CurBB->empty())
4009 return &CurBB->back();
4010 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
4011 !FunctionBBs[CurBBNo - 1]->empty())
4012 return &FunctionBBs[CurBBNo - 1]->back();
4013 return nullptr;
4014 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004015
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004016 std::vector<OperandBundleDef> OperandBundles;
4017
Chris Lattner85b7b402007-05-01 05:52:21 +00004018 // Read all the records.
4019 SmallVector<uint64_t, 64> Record;
4020 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00004021 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00004022
Chris Lattner27d38752013-01-20 02:13:19 +00004023 switch (Entry.Kind) {
4024 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004025 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004026 case BitstreamEntry::EndBlock:
4027 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004028
Chris Lattner27d38752013-01-20 02:13:19 +00004029 case BitstreamEntry::SubBlock:
4030 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004031 default: // Skip unknown content.
4032 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004033 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004034 break;
4035 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004036 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004037 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004038 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004039 break;
4040 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004041 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004042 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004043 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004044 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004045 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004046 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004047 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004048 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004049 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004050 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004051 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004052 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004053 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004054 return EC;
4055 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004056 }
4057 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004058
Chris Lattner27d38752013-01-20 02:13:19 +00004059 case BitstreamEntry::Record:
4060 // The interesting case.
4061 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004062 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004063
Chris Lattner85b7b402007-05-01 05:52:21 +00004064 // Read a record.
4065 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004066 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004067 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004068 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004069 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004070 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004071 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004072 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004073 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004074 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004075 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004076
4077 // See if anything took the address of blocks in this function.
4078 auto BBFRI = BasicBlockFwdRefs.find(F);
4079 if (BBFRI == BasicBlockFwdRefs.end()) {
4080 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4081 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4082 } else {
4083 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004084 // Check for invalid basic block references.
4085 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004086 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004087 assert(!BBRefs.empty() && "Unexpected empty array");
4088 assert(!BBRefs.front() && "Invalid reference to entry block");
4089 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4090 ++I)
4091 if (I < RE && BBRefs[I]) {
4092 BBRefs[I]->insertInto(F);
4093 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004094 } else {
4095 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4096 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004097
4098 // Erase from the table.
4099 BasicBlockFwdRefs.erase(BBFRI);
4100 }
4101
Chris Lattner83930552007-05-01 07:01:57 +00004102 CurBB = FunctionBBs[0];
4103 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004104 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004105
Chris Lattner07d09ed2010-04-03 02:17:50 +00004106 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4107 // This record indicates that the last instruction is at the same
4108 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004109 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004110
Craig Topper2617dcc2014-04-15 06:32:26 +00004111 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004112 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004113 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004114 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004115 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004116
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004117 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004118 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004119 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004120 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004121
Chris Lattner07d09ed2010-04-03 02:17:50 +00004122 unsigned Line = Record[0], Col = Record[1];
4123 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004124
Craig Topper2617dcc2014-04-15 06:32:26 +00004125 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004126 if (ScopeID) {
4127 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4128 if (!Scope)
4129 return error("Invalid record");
4130 }
4131 if (IAID) {
4132 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4133 if (!IA)
4134 return error("Invalid record");
4135 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004136 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4137 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004138 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004139 continue;
4140 }
4141
Chris Lattnere9759c22007-05-06 00:21:25 +00004142 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4143 unsigned OpNum = 0;
4144 Value *LHS, *RHS;
4145 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004146 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004147 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004148 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004149
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004150 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004151 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004152 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004153 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004154 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004155 if (OpNum < Record.size()) {
4156 if (Opc == Instruction::Add ||
4157 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004158 Opc == Instruction::Mul ||
4159 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004160 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004161 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004162 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004163 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004164 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004165 Opc == Instruction::UDiv ||
4166 Opc == Instruction::LShr ||
4167 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004168 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004169 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004170 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004171 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004172 if (FMF.any())
4173 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004174 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004175
Dan Gohman1b849082009-09-07 23:54:19 +00004176 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004177 break;
4178 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004179 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4180 unsigned OpNum = 0;
4181 Value *Op;
4182 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4183 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004184 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004185
Chris Lattner229907c2011-07-18 04:54:35 +00004186 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004187 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004188 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004189 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004190 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004191 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4192 if (Temp) {
4193 InstructionList.push_back(Temp);
4194 CurBB->getInstList().push_back(Temp);
4195 }
4196 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004197 auto CastOp = (Instruction::CastOps)Opc;
4198 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4199 return error("Invalid cast");
4200 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004201 }
Devang Patelaf206b82009-09-18 19:26:43 +00004202 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004203 break;
4204 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004205 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4206 case bitc::FUNC_CODE_INST_GEP_OLD:
4207 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004208 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004209
4210 Type *Ty;
4211 bool InBounds;
4212
4213 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4214 InBounds = Record[OpNum++];
4215 Ty = getTypeByID(Record[OpNum++]);
4216 } else {
4217 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4218 Ty = nullptr;
4219 }
4220
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004221 Value *BasePtr;
4222 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004223 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004224
David Blaikie60310f22015-05-08 00:42:26 +00004225 if (!Ty)
4226 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4227 ->getElementType();
4228 else if (Ty !=
4229 cast<SequentialType>(BasePtr->getType()->getScalarType())
4230 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004231 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004232 "Explicit gep type does not match pointee type of pointer operand");
4233
Chris Lattner5285b5e2007-05-02 05:46:45 +00004234 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004235 while (OpNum != Record.size()) {
4236 Value *Op;
4237 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004238 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004239 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004240 }
4241
David Blaikie096b1da2015-03-14 19:53:33 +00004242 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004243
Devang Patelaf206b82009-09-18 19:26:43 +00004244 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004245 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004246 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004247 break;
4248 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004249
Dan Gohman1ecaf452008-05-31 00:58:22 +00004250 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4251 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004252 unsigned OpNum = 0;
4253 Value *Agg;
4254 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004255 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004256
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004257 unsigned RecSize = Record.size();
4258 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004259 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004260
Dan Gohman1ecaf452008-05-31 00:58:22 +00004261 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004262 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004263 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004264 bool IsArray = CurTy->isArrayTy();
4265 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004266 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004267
4268 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004269 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004270 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004271 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004272 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004273 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004274 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004275 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004276 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004277
4278 if (IsStruct)
4279 CurTy = CurTy->subtypes()[Index];
4280 else
4281 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004282 }
4283
Jay Foad57aa6362011-07-13 10:26:04 +00004284 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004285 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004286 break;
4287 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004288
Dan Gohman1ecaf452008-05-31 00:58:22 +00004289 case bitc::FUNC_CODE_INST_INSERTVAL: {
4290 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004291 unsigned OpNum = 0;
4292 Value *Agg;
4293 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004294 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004295 Value *Val;
4296 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004297 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004298
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004299 unsigned RecSize = Record.size();
4300 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004301 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004302
Dan Gohman1ecaf452008-05-31 00:58:22 +00004303 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004304 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004305 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004306 bool IsArray = CurTy->isArrayTy();
4307 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004308 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004309
4310 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004311 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004312 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004313 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004314 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004315 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004316 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004317 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004318
Dan Gohman1ecaf452008-05-31 00:58:22 +00004319 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004320 if (IsStruct)
4321 CurTy = CurTy->subtypes()[Index];
4322 else
4323 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004324 }
4325
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004326 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004327 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004328
Jay Foad57aa6362011-07-13 10:26:04 +00004329 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004330 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004331 break;
4332 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004333
Chris Lattnere9759c22007-05-06 00:21:25 +00004334 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004335 // obsolete form of select
4336 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004337 unsigned OpNum = 0;
4338 Value *TrueVal, *FalseVal, *Cond;
4339 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004340 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4341 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004342 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004343
Dan Gohmanc5d28922008-09-16 01:01:33 +00004344 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004345 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004346 break;
4347 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004348
Dan Gohmanc5d28922008-09-16 01:01:33 +00004349 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4350 // new form of select
4351 // handles select i1 or select [N x i1]
4352 unsigned OpNum = 0;
4353 Value *TrueVal, *FalseVal, *Cond;
4354 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004355 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004356 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004357 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004358
4359 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004360 if (VectorType* vector_type =
4361 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004362 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004363 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004364 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004365 } else {
4366 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004367 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004368 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004369 }
4370
Gabor Greife9ecc682008-04-06 20:25:17 +00004371 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004372 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004373 break;
4374 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004375
Chris Lattner1fc27f02007-05-02 05:16:49 +00004376 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004377 unsigned OpNum = 0;
4378 Value *Vec, *Idx;
4379 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004380 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004381 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004382 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004383 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004384 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004385 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004386 break;
4387 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004388
Chris Lattner1fc27f02007-05-02 05:16:49 +00004389 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004390 unsigned OpNum = 0;
4391 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004392 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004393 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004394 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004395 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004396 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004397 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004398 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004399 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004400 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004401 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004402 break;
4403 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004404
Chris Lattnere9759c22007-05-06 00:21:25 +00004405 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4406 unsigned OpNum = 0;
4407 Value *Vec1, *Vec2, *Mask;
4408 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004409 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004410 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004411
Mon P Wang25f01062008-11-10 04:46:22 +00004412 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004413 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004414 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004415 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004416 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004417 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004418 break;
4419 }
Mon P Wang25f01062008-11-10 04:46:22 +00004420
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004421 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4422 // Old form of ICmp/FCmp returning bool
4423 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4424 // both legal on vectors but had different behaviour.
4425 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4426 // FCmp/ICmp returning bool or vector of bool
4427
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004428 unsigned OpNum = 0;
4429 Value *LHS, *RHS;
4430 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004431 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4432 return error("Invalid record");
4433
4434 unsigned PredVal = Record[OpNum];
4435 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4436 FastMathFlags FMF;
4437 if (IsFP && Record.size() > OpNum+1)
4438 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4439
4440 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004441 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004442
Duncan Sands9dff9be2010-02-15 16:12:20 +00004443 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004444 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004445 else
James Molloy88eb5352015-07-10 12:52:00 +00004446 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4447
4448 if (FMF.any())
4449 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004450 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004451 break;
4452 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004453
Chris Lattnere53603e2007-05-02 04:27:25 +00004454 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004455 {
4456 unsigned Size = Record.size();
4457 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004458 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004459 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004460 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004461 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004462
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004463 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004464 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004465 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004466 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004467 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004468 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004469
Chris Lattnerf1c87102011-06-17 18:09:11 +00004470 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004471 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004472 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004473 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004474 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004475 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004476 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004477 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004478 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004479 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004480
Devang Patelaf206b82009-09-18 19:26:43 +00004481 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004482 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004483 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004484 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004485 else {
4486 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004487 Value *Cond = getValue(Record, 2, NextValueNo,
4488 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004489 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004490 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004491 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004492 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004493 }
4494 break;
4495 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004496 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004497 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004498 return error("Invalid record");
4499 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004500 Value *CleanupPad =
4501 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004502 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004503 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004504 BasicBlock *UnwindDest = nullptr;
4505 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004506 UnwindDest = getBasicBlock(Record[Idx++]);
4507 if (!UnwindDest)
4508 return error("Invalid record");
4509 }
4510
David Majnemer8a1c45d2015-12-12 05:38:55 +00004511 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004512 InstructionList.push_back(I);
4513 break;
4514 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004515 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4516 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004517 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004518 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004519 Value *CatchPad =
4520 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004521 if (!CatchPad)
4522 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004523 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004524 if (!BB)
4525 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004526
David Majnemer8a1c45d2015-12-12 05:38:55 +00004527 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004528 InstructionList.push_back(I);
4529 break;
4530 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004531 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4532 // We must have, at minimum, the outer scope and the number of arguments.
4533 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004534 return error("Invalid record");
4535
David Majnemer654e1302015-07-31 17:58:14 +00004536 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004537
4538 Value *ParentPad =
4539 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4540
4541 unsigned NumHandlers = Record[Idx++];
4542
4543 SmallVector<BasicBlock *, 2> Handlers;
4544 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4545 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4546 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004547 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004548 Handlers.push_back(BB);
4549 }
4550
4551 BasicBlock *UnwindDest = nullptr;
4552 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004553 UnwindDest = getBasicBlock(Record[Idx++]);
4554 if (!UnwindDest)
4555 return error("Invalid record");
4556 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004557
4558 if (Record.size() != Idx)
4559 return error("Invalid record");
4560
4561 auto *CatchSwitch =
4562 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4563 for (BasicBlock *Handler : Handlers)
4564 CatchSwitch->addHandler(Handler);
4565 I = CatchSwitch;
4566 InstructionList.push_back(I);
4567 break;
4568 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004569 case bitc::FUNC_CODE_INST_CATCHPAD:
4570 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4571 // We must have, at minimum, the outer scope and the number of arguments.
4572 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004573 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004574
David Majnemer654e1302015-07-31 17:58:14 +00004575 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004576
4577 Value *ParentPad =
4578 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4579
David Majnemer654e1302015-07-31 17:58:14 +00004580 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004581
David Majnemer654e1302015-07-31 17:58:14 +00004582 SmallVector<Value *, 2> Args;
4583 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4584 Value *Val;
4585 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4586 return error("Invalid record");
4587 Args.push_back(Val);
4588 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004589
David Majnemer654e1302015-07-31 17:58:14 +00004590 if (Record.size() != Idx)
4591 return error("Invalid record");
4592
David Majnemer8a1c45d2015-12-12 05:38:55 +00004593 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4594 I = CleanupPadInst::Create(ParentPad, Args);
4595 else
4596 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004597 InstructionList.push_back(I);
4598 break;
4599 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004600 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004601 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004602 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004603 // "New" SwitchInst format with case ranges. The changes to write this
4604 // format were reverted but we still recognize bitcode that uses it.
4605 // Hopefully someday we will have support for case ranges and can use
4606 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004607
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004608 Type *OpTy = getTypeByID(Record[1]);
4609 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4610
Jan Wen Voungafaced02012-10-11 20:20:40 +00004611 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004612 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004613 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004614 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004615
4616 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004617
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004618 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4619 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004620
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004621 unsigned CurIdx = 5;
4622 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004623 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004624 unsigned NumItems = Record[CurIdx++];
4625 for (unsigned ci = 0; ci != NumItems; ++ci) {
4626 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004627
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004628 APInt Low;
4629 unsigned ActiveWords = 1;
4630 if (ValueBitWidth > 64)
4631 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004632 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004633 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004634 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004635
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004636 if (!isSingleNumber) {
4637 ActiveWords = 1;
4638 if (ValueBitWidth > 64)
4639 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004640 APInt High = readWideAPInt(
4641 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004642 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004643
4644 // FIXME: It is not clear whether values in the range should be
4645 // compared as signed or unsigned values. The partially
4646 // implemented changes that used this format in the past used
4647 // unsigned comparisons.
4648 for ( ; Low.ule(High); ++Low)
4649 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004650 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004651 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004652 }
4653 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004654 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4655 cve = CaseVals.end(); cvi != cve; ++cvi)
4656 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004657 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004658 I = SI;
4659 break;
4660 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004661
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004662 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004663
Chris Lattner5285b5e2007-05-02 05:46:45 +00004664 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004665 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004666 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004667 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004668 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004669 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004670 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004671 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004672 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004673 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004674 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004675 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004676 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4677 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004678 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004679 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004680 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004681 }
4682 SI->addCase(CaseVal, DestBB);
4683 }
4684 I = SI;
4685 break;
4686 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004687 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004688 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004689 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004690 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004691 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004692 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004693 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004694 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004695 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004696 InstructionList.push_back(IBI);
4697 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4698 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4699 IBI->addDestination(DestBB);
4700 } else {
4701 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004702 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004703 }
4704 }
4705 I = IBI;
4706 break;
4707 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004708
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004709 case bitc::FUNC_CODE_INST_INVOKE: {
4710 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004711 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004712 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004713 unsigned OpNum = 0;
4714 AttributeSet PAL = getAttributes(Record[OpNum++]);
4715 unsigned CCInfo = Record[OpNum++];
4716 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4717 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004718
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004719 FunctionType *FTy = nullptr;
4720 if (CCInfo >> 13 & 1 &&
4721 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004722 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004723
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004724 Value *Callee;
4725 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004726 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004727
Chris Lattner229907c2011-07-18 04:54:35 +00004728 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004729 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004730 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004731 if (!FTy) {
4732 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4733 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004734 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004735 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004736 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004737 "callee operand");
4738 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004739 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004740
Chris Lattner5285b5e2007-05-02 05:46:45 +00004741 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004742 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004743 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4744 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004745 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004746 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004747 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004748
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004749 if (!FTy->isVarArg()) {
4750 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004751 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004752 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004753 // Read type/value pairs for varargs params.
4754 while (OpNum != Record.size()) {
4755 Value *Op;
4756 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004757 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004758 Ops.push_back(Op);
4759 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004760 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004761
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004762 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4763 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004764 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004765 cast<InvokeInst>(I)->setCallingConv(
4766 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004767 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004768 break;
4769 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004770 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4771 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004772 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004773 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004774 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004775 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004776 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004777 break;
4778 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004779 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004780 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004781 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004782 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004783 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004784 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004785 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004786 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004787 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004788 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004789
Jay Foad52131342011-03-30 11:28:46 +00004790 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004791 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004792
Chris Lattnere14cb882007-05-04 19:11:41 +00004793 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004794 Value *V;
4795 // With the new function encoding, it is possible that operands have
4796 // negative IDs (for forward references). Use a signed VBR
4797 // representation to keep the encoding small.
4798 if (UseRelativeIDs)
4799 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4800 else
4801 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004802 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004803 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004804 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004805 PN->addIncoming(V, BB);
4806 }
4807 I = PN;
4808 break;
4809 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004810
David Majnemer7fddecc2015-06-17 20:52:32 +00004811 case bitc::FUNC_CODE_INST_LANDINGPAD:
4812 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004813 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4814 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004815 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4816 if (Record.size() < 3)
4817 return error("Invalid record");
4818 } else {
4819 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4820 if (Record.size() < 4)
4821 return error("Invalid record");
4822 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004823 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004824 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004825 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004826 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4827 Value *PersFn = nullptr;
4828 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4829 return error("Invalid record");
4830
4831 if (!F->hasPersonalityFn())
4832 F->setPersonalityFn(cast<Constant>(PersFn));
4833 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4834 return error("Personality function mismatch");
4835 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004836
4837 bool IsCleanup = !!Record[Idx++];
4838 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004839 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004840 LP->setCleanup(IsCleanup);
4841 for (unsigned J = 0; J != NumClauses; ++J) {
4842 LandingPadInst::ClauseType CT =
4843 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4844 Value *Val;
4845
4846 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4847 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004848 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004849 }
4850
4851 assert((CT != LandingPadInst::Catch ||
4852 !isa<ArrayType>(Val->getType())) &&
4853 "Catch clause has a invalid type!");
4854 assert((CT != LandingPadInst::Filter ||
4855 isa<ArrayType>(Val->getType())) &&
4856 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004857 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004858 }
4859
4860 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004861 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004862 break;
4863 }
4864
Chris Lattnerf1c87102011-06-17 18:09:11 +00004865 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4866 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004867 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004868 uint64_t AlignRecord = Record[3];
4869 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004870 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004871 const uint64_t SwiftErrorMask = uint64_t(1) << 7;
4872 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
4873 SwiftErrorMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004874 bool InAlloca = AlignRecord & InAllocaMask;
Manman Ren9bfd0d02016-04-01 21:41:15 +00004875 bool SwiftError = AlignRecord & SwiftErrorMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004876 Type *Ty = getTypeByID(Record[0]);
4877 if ((AlignRecord & ExplicitTypeMask) == 0) {
4878 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4879 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004880 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004881 Ty = PTy->getElementType();
4882 }
4883 Type *OpTy = getTypeByID(Record[1]);
4884 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004885 unsigned Align;
4886 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004887 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004888 return EC;
4889 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004890 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004891 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004892 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004893 AI->setUsedWithInAlloca(InAlloca);
Manman Ren9bfd0d02016-04-01 21:41:15 +00004894 AI->setSwiftError(SwiftError);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004895 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004896 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004897 break;
4898 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004899 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004900 unsigned OpNum = 0;
4901 Value *Op;
4902 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004903 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004904 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004905
4906 Type *Ty = nullptr;
4907 if (OpNum + 3 == Record.size())
4908 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004909 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004910 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004911 if (!Ty)
4912 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004913
JF Bastien30bf96b2015-02-22 19:32:03 +00004914 unsigned Align;
4915 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4916 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004917 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004918
Devang Patelaf206b82009-09-18 19:26:43 +00004919 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004920 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004921 }
Eli Friedman59b66882011-08-09 23:02:53 +00004922 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4923 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4924 unsigned OpNum = 0;
4925 Value *Op;
4926 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004927 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004928 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004929
David Blaikie85035652015-02-25 01:07:20 +00004930 Type *Ty = nullptr;
4931 if (OpNum + 5 == Record.size())
4932 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004933 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004934 return EC;
4935 if (!Ty)
4936 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004937
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004938 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004939 if (Ordering == NotAtomic || Ordering == Release ||
4940 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004941 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004942 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004943 return error("Invalid record");
4944 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004945
JF Bastien30bf96b2015-02-22 19:32:03 +00004946 unsigned Align;
4947 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4948 return EC;
4949 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004950
Eli Friedman59b66882011-08-09 23:02:53 +00004951 InstructionList.push_back(I);
4952 break;
4953 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004954 case bitc::FUNC_CODE_INST_STORE:
4955 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004956 unsigned OpNum = 0;
4957 Value *Val, *Ptr;
4958 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004959 (BitCode == bitc::FUNC_CODE_INST_STORE
4960 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4961 : popValue(Record, OpNum, NextValueNo,
4962 cast<PointerType>(Ptr->getType())->getElementType(),
4963 Val)) ||
4964 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004965 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004966
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004967 if (std::error_code EC =
4968 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004969 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004970 unsigned Align;
4971 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4972 return EC;
4973 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004974 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004975 break;
4976 }
David Blaikie50a06152015-04-22 04:14:46 +00004977 case bitc::FUNC_CODE_INST_STOREATOMIC:
4978 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004979 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4980 unsigned OpNum = 0;
4981 Value *Val, *Ptr;
4982 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004983 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4984 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4985 : popValue(Record, OpNum, NextValueNo,
4986 cast<PointerType>(Ptr->getType())->getElementType(),
4987 Val)) ||
4988 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004989 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004990
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004991 if (std::error_code EC =
4992 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004993 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004994 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004995 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004996 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004997 return error("Invalid record");
4998 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004999 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005000 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00005001
JF Bastien30bf96b2015-02-22 19:32:03 +00005002 unsigned Align;
5003 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
5004 return EC;
5005 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00005006 InstructionList.push_back(I);
5007 break;
5008 }
David Blaikie2a661cd2015-04-28 04:30:29 +00005009 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005010 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00005011 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00005012 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005013 unsigned OpNum = 0;
5014 Value *Ptr, *Cmp, *New;
5015 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00005016 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
5017 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
5018 : popValue(Record, OpNum, NextValueNo,
5019 cast<PointerType>(Ptr->getType())->getElementType(),
5020 Cmp)) ||
5021 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
5022 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005023 return error("Invalid record");
5024 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00005025 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005026 return error("Invalid record");
5027 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005028
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005029 if (std::error_code EC =
5030 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005031 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005032 AtomicOrdering FailureOrdering;
5033 if (Record.size() < 7)
5034 FailureOrdering =
5035 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5036 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005037 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005038
5039 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5040 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005041 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005042
5043 if (Record.size() < 8) {
5044 // Before weak cmpxchgs existed, the instruction simply returned the
5045 // value loaded from memory, so bitcode files from that era will be
5046 // expecting the first component of a modern cmpxchg.
5047 CurBB->getInstList().push_back(I);
5048 I = ExtractValueInst::Create(I, 0);
5049 } else {
5050 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5051 }
5052
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005053 InstructionList.push_back(I);
5054 break;
5055 }
5056 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5057 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5058 unsigned OpNum = 0;
5059 Value *Ptr, *Val;
5060 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005061 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005062 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5063 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005064 return error("Invalid record");
5065 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005066 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5067 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005068 return error("Invalid record");
5069 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00005070 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005071 return error("Invalid record");
5072 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005073 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5074 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5075 InstructionList.push_back(I);
5076 break;
5077 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005078 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5079 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005080 return error("Invalid record");
5081 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005082 if (Ordering == NotAtomic || Ordering == Unordered ||
5083 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005084 return error("Invalid record");
5085 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005086 I = new FenceInst(Context, Ordering, SynchScope);
5087 InstructionList.push_back(I);
5088 break;
5089 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005090 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005091 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005092 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005093 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005094
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005095 unsigned OpNum = 0;
5096 AttributeSet PAL = getAttributes(Record[OpNum++]);
5097 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005098
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005099 FastMathFlags FMF;
5100 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5101 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5102 if (!FMF.any())
5103 return error("Fast math flags indicator set for call with no FMF");
5104 }
5105
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005106 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005107 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005108 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005109 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005110
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005111 Value *Callee;
5112 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005113 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005114
Chris Lattner229907c2011-07-18 04:54:35 +00005115 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005116 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005117 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005118 if (!FTy) {
5119 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5120 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005121 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005122 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005123 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005124 "callee operand");
5125 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005126 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005127
Chris Lattner9f600c52007-05-03 22:04:19 +00005128 SmallVector<Value*, 16> Args;
5129 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005130 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005131 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005132 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005133 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005134 Args.push_back(getValue(Record, OpNum, NextValueNo,
5135 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005136 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005137 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005138 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005139
Chris Lattner9f600c52007-05-03 22:04:19 +00005140 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005141 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005142 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005143 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005144 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005145 while (OpNum != Record.size()) {
5146 Value *Op;
5147 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005148 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005149 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005150 }
5151 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005152
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005153 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5154 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005155 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005156 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005157 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005158 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005159 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005160 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005161 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005162 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005163 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005164 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005165 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005166 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005167 if (FMF.any()) {
5168 if (!isa<FPMathOperator>(I))
5169 return error("Fast-math-flags specified for call without "
5170 "floating-point scalar or vector return type");
5171 I->setFastMathFlags(FMF);
5172 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005173 break;
5174 }
5175 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5176 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005177 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005178 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005179 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005180 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005181 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005182 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005183 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005184 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005185 break;
5186 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005187
5188 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5189 // A call or an invoke can be optionally prefixed with some variable
5190 // number of operand bundle blocks. These blocks are read into
5191 // OperandBundles and consumed at the next call or invoke instruction.
5192
5193 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5194 return error("Invalid record");
5195
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005196 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005197
5198 unsigned OpNum = 1;
5199 while (OpNum != Record.size()) {
5200 Value *Op;
5201 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5202 return error("Invalid record");
5203 Inputs.push_back(Op);
5204 }
5205
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005206 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005207 continue;
5208 }
Chris Lattner83930552007-05-01 07:01:57 +00005209 }
5210
5211 // Add instruction to end of current BB. If there is no current BB, reject
5212 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005213 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005214 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005215 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005216 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005217 if (!OperandBundles.empty()) {
5218 delete I;
5219 return error("Operand bundles found with no consumer");
5220 }
Chris Lattner83930552007-05-01 07:01:57 +00005221 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005222
Chris Lattner83930552007-05-01 07:01:57 +00005223 // If this was a terminator instruction, move to the next block.
5224 if (isa<TerminatorInst>(I)) {
5225 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005226 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005227 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005228
Chris Lattner83930552007-05-01 07:01:57 +00005229 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005230 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005231 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005232 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005233
Chris Lattner27d38752013-01-20 02:13:19 +00005234OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005235
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005236 if (!OperandBundles.empty())
5237 return error("Operand bundles found with no consumer");
5238
Chris Lattner83930552007-05-01 07:01:57 +00005239 // Check the function list for unresolved values.
5240 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005241 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005242 // We found at least one unresolved value. Nuke them all to avoid leaks.
5243 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005244 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005245 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005246 delete A;
5247 }
5248 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005249 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005250 }
Chris Lattner83930552007-05-01 07:01:57 +00005251 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005252
Duncan P. N. Exon Smith8742de92016-04-02 14:55:01 +00005253 // Unexpected unresolved metadata about to be dropped.
5254 if (MetadataList.hasFwdRefs())
5255 return error("Invalid function metadata: outgoing forward refs");
Dan Gohman9b9ff462010-08-25 20:23:38 +00005256
Chris Lattner85b7b402007-05-01 05:52:21 +00005257 // Trim the value list down to the size it was before we parsed this function.
5258 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005259 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005260 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005261 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005262}
5263
Rafael Espindola7d712032013-11-05 17:16:08 +00005264/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005265std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005266 Function *F,
5267 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005268 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005269 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005270 // didn't contain the function index in the VST, or when we have
5271 // an anonymous function which would not have a VST entry.
5272 // Assert that we have one of those two cases.
5273 assert(VSTOffset == 0 || !F->hasName());
5274 // Parse the next body in the stream and set its position in the
5275 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005276 if (std::error_code EC = rememberAndSkipFunctionBodies())
5277 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005278 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005279 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005280}
5281
Chris Lattner9eeada92007-05-18 04:02:46 +00005282//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005283// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005284//===----------------------------------------------------------------------===//
5285
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005286void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005287
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005288std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Duncan P. N. Exon Smith68f56242016-03-25 01:29:50 +00005289 if (std::error_code EC = materializeMetadata())
5290 return EC;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005291
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005292 Function *F = dyn_cast<Function>(GV);
5293 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005294 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005295 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005296
5297 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005298 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005299 // If its position is recorded as 0, its body is somewhere in the stream
5300 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005301 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005302 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005303 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005304
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005305 // Move the bit stream to the saved position of the deferred function body.
5306 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005307
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005308 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005309 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005310 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005311
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005312 if (StripDebugInfo)
5313 stripDebugInfo(*F);
5314
Chandler Carruth7132e002007-08-04 01:51:18 +00005315 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005316 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005317 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5318 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005319 User *U = *UI;
5320 ++UI;
5321 if (CallInst *CI = dyn_cast<CallInst>(U))
5322 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005323 }
5324 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005325
Peter Collingbourned4bff302015-11-05 22:03:56 +00005326 // Finish fn->subprogram upgrade for materialized functions.
5327 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5328 F->setSubprogram(SP);
5329
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005330 // Bring in any functions that this function forward-referenced via
5331 // blockaddresses.
5332 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005333}
5334
Rafael Espindola79753a02015-12-18 21:18:57 +00005335std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005336 if (std::error_code EC = materializeMetadata())
5337 return EC;
5338
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005339 // Promise to materialize all forward references.
5340 WillMaterializeAllForwardRefs = true;
5341
Chris Lattner06310bf2009-06-16 05:15:21 +00005342 // Iterate over the module, deserializing any functions that are still on
5343 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005344 for (Function &F : *TheModule) {
5345 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005346 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005347 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005348 // At this point, if there are any function bodies, parse the rest of
5349 // the bits in the module past the last function block we have recorded
5350 // through either lazy scanning or the VST.
5351 if (LastFunctionBlockBit || NextUnreadBit)
5352 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5353 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005354
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005355 // Check that all block address forward references got resolved (as we
5356 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005357 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005358 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005359
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005360 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5361 // to prevent this instructions with TBAA tags should be upgraded first.
5362 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5363 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5364
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005365 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5366 // delete the old functions to clean up. We can't do this unless the entire
5367 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005368 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005369 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005370 for (auto *U : I.first->users()) {
5371 if (CallInst *CI = dyn_cast<CallInst>(U))
5372 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005373 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005374 if (!I.first->use_empty())
5375 I.first->replaceAllUsesWith(I.second);
5376 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005377 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005378 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005379
Rafael Espindola79753a02015-12-18 21:18:57 +00005380 UpgradeDebugInfo(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005381 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005382}
5383
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005384std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5385 return IdentifiedStructTypes;
5386}
5387
Rafael Espindola1aabf982015-06-16 23:29:49 +00005388std::error_code
5389BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005390 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005391 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005392 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005393}
5394
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005395std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005396 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005397 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5398
Rafael Espindola27435252014-07-29 21:01:24 +00005399 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005400 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005401
5402 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5403 // The magic number is 0x0B17C0DE stored in little endian.
5404 if (isBitcodeWrapper(BufPtr, BufEnd))
5405 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005406 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005407
5408 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005409 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005410
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005411 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005412}
5413
Rafael Espindola1aabf982015-06-16 23:29:49 +00005414std::error_code
5415BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005416 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5417 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005418 auto OwnedBytes =
5419 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005420 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005421 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005422 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005423
5424 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005425 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005426 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005427
5428 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005429 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005430
5431 if (isBitcodeWrapper(buf, buf + 4)) {
5432 const unsigned char *bitcodeStart = buf;
5433 const unsigned char *bitcodeEnd = buf + 16;
5434 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005435 Bytes.dropLeadingBytes(bitcodeStart - buf);
5436 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005437 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005438 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005439}
5440
Teresa Johnson26ab5772016-03-15 00:04:37 +00005441std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5442 const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005443 return ::error(DiagnosticHandler, make_error_code(E), Message);
5444}
5445
Teresa Johnson26ab5772016-03-15 00:04:37 +00005446std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005447 return ::error(DiagnosticHandler,
5448 make_error_code(BitcodeError::CorruptedBitcode), Message);
5449}
5450
Teresa Johnson26ab5772016-03-15 00:04:37 +00005451std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005452 return ::error(DiagnosticHandler, make_error_code(E));
5453}
5454
Teresa Johnson26ab5772016-03-15 00:04:37 +00005455ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005456 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005457 bool IsLazy, bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005458 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005459 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005460
Teresa Johnson26ab5772016-03-15 00:04:37 +00005461ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005462 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005463 bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005464 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005465 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005466
Teresa Johnson26ab5772016-03-15 00:04:37 +00005467void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005468
Teresa Johnson26ab5772016-03-15 00:04:37 +00005469void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005470
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005471GlobalValue::GUID
5472ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005473 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5474 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5475 return VGI->second;
5476}
5477
5478GlobalValueInfo *
Teresa Johnson26ab5772016-03-15 00:04:37 +00005479ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005480 auto I = SummaryOffsetToInfoMap.find(Offset);
5481 assert(I != SummaryOffsetToInfoMap.end());
5482 return I->second;
5483}
5484
5485// Specialized value symbol table parser used when reading module index
Teresa Johnson403a7872015-10-04 14:33:43 +00005486// blocks where we don't actually create global values.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005487// At the end of this routine the module index is populated with a map
5488// from global value name to GlobalValueInfo. The global value info contains
5489// the function block's bitcode offset (if applicable), or the offset into the
5490// summary section for the combined index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005491std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005492 uint64_t Offset,
5493 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5494 assert(Offset > 0 && "Expected non-zero VST offset");
5495 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5496
Teresa Johnson403a7872015-10-04 14:33:43 +00005497 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5498 return error("Invalid record");
5499
5500 SmallVector<uint64_t, 64> Record;
5501
5502 // Read all the records for this value table.
5503 SmallString<128> ValueName;
5504 while (1) {
5505 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5506
5507 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005508 case BitstreamEntry::SubBlock: // Handled for us already.
5509 case BitstreamEntry::Error:
5510 return error("Malformed block");
5511 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005512 // Done parsing VST, jump back to wherever we came from.
5513 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005514 return std::error_code();
5515 case BitstreamEntry::Record:
5516 // The interesting case.
5517 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005518 }
5519
5520 // Read a record.
5521 Record.clear();
5522 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005523 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5524 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005525 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5526 if (convertToString(Record, 1, ValueName))
5527 return error("Invalid record");
5528 unsigned ValueID = Record[0];
5529 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5530 llvm::make_unique<GlobalValueInfo>();
5531 assert(!SourceFileName.empty());
5532 auto VLI = ValueIdToLinkageMap.find(ValueID);
5533 assert(VLI != ValueIdToLinkageMap.end() &&
5534 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005535 std::string GlobalId = GlobalValue::getGlobalIdentifier(
5536 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005537 auto ValueGUID = GlobalValue::getGUID(GlobalId);
5538 if (PrintSummaryGUIDs)
5539 dbgs() << "GUID " << ValueGUID << " is " << ValueName << "\n";
5540 TheIndex->addGlobalValueInfo(ValueGUID, std::move(GlobalValInfo));
5541 ValueIdToCallGraphGUIDMap[ValueID] = ValueGUID;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005542 ValueName.clear();
5543 break;
5544 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005545 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005546 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005547 if (convertToString(Record, 2, ValueName))
5548 return error("Invalid record");
5549 unsigned ValueID = Record[0];
5550 uint64_t FuncOffset = Record[1];
Teresa Johnsone1164de2016-02-10 21:55:02 +00005551 assert(!IsLazy && "Lazy summary read only supported for combined index");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005552 std::unique_ptr<GlobalValueInfo> FuncInfo =
5553 llvm::make_unique<GlobalValueInfo>(FuncOffset);
5554 assert(!SourceFileName.empty());
5555 auto VLI = ValueIdToLinkageMap.find(ValueID);
5556 assert(VLI != ValueIdToLinkageMap.end() &&
5557 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005558 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5559 ValueName, VLI->second, SourceFileName);
Teresa Johnson916495d2016-04-04 18:52:58 +00005560 auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
5561 if (PrintSummaryGUIDs)
5562 dbgs() << "GUID " << FunctionGUID << " is " << ValueName << "\n";
5563 TheIndex->addGlobalValueInfo(FunctionGUID, std::move(FuncInfo));
5564 ValueIdToCallGraphGUIDMap[ValueID] = FunctionGUID;
Teresa Johnson403a7872015-10-04 14:33:43 +00005565
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005566 ValueName.clear();
5567 break;
5568 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005569 case bitc::VST_CODE_COMBINED_GVDEFENTRY: {
5570 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid]
5571 unsigned ValueID = Record[0];
5572 uint64_t GlobalValSummaryOffset = Record[1];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005573 GlobalValue::GUID GlobalValGUID = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005574 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5575 llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset);
5576 SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get();
5577 TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo));
5578 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID;
5579 break;
5580 }
5581 case bitc::VST_CODE_COMBINED_ENTRY: {
5582 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5583 unsigned ValueID = Record[0];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005584 GlobalValue::GUID RefGUID = Record[1];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005585 ValueIdToCallGraphGUIDMap[ValueID] = RefGUID;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005586 break;
5587 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005588 }
5589 }
5590}
5591
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005592// Parse just the blocks needed for building the index out of the module.
5593// At the end of this routine the module Index is populated with a map
5594// from global value name to GlobalValueInfo. The global value info contains
5595// either the parsed summary information (when parsing summaries
5596// eagerly), or just to the summary record's offset
Teresa Johnson403a7872015-10-04 14:33:43 +00005597// if parsing lazily (IsLazy).
Teresa Johnson26ab5772016-03-15 00:04:37 +00005598std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005599 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5600 return error("Invalid record");
5601
Teresa Johnsone1164de2016-02-10 21:55:02 +00005602 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005603 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5604 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005605
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005606 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005607 while (1) {
5608 BitstreamEntry Entry = Stream.advance();
5609
5610 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005611 case BitstreamEntry::Error:
5612 return error("Malformed block");
5613 case BitstreamEntry::EndBlock:
5614 return std::error_code();
5615
5616 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005617 if (CheckGlobalValSummaryPresenceOnly) {
5618 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5619 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005620 // No need to parse the rest since we found the summary.
5621 return std::error_code();
5622 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005623 if (Stream.SkipBlock())
5624 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005625 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005626 }
5627 switch (Entry.ID) {
5628 default: // Skip unknown content.
5629 if (Stream.SkipBlock())
5630 return error("Invalid record");
5631 break;
5632 case bitc::BLOCKINFO_BLOCK_ID:
5633 // Need to parse these to get abbrev ids (e.g. for VST)
5634 if (Stream.ReadBlockInfoBlock())
5635 return error("Malformed block");
5636 break;
5637 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005638 // Should have been parsed earlier via VSTOffset, unless there
5639 // is no summary section.
5640 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5641 !SeenGlobalValSummary) &&
5642 "Expected early VST parse via VSTOffset record");
5643 if (Stream.SkipBlock())
5644 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005645 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005646 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5647 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5648 assert(!SeenValueSymbolTable &&
5649 "Already read VST when parsing summary block?");
5650 if (std::error_code EC =
5651 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5652 return EC;
5653 SeenValueSymbolTable = true;
5654 SeenGlobalValSummary = true;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005655 if (IsLazy) {
5656 // Lazy parsing of summary info, skip it.
5657 if (Stream.SkipBlock())
5658 return error("Invalid record");
5659 } else if (std::error_code EC = parseEntireSummary())
5660 return EC;
5661 break;
5662 case bitc::MODULE_STRTAB_BLOCK_ID:
5663 if (std::error_code EC = parseModuleStringTable())
5664 return EC;
5665 break;
5666 }
5667 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005668
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005669 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005670 Record.clear();
5671 auto BitCode = Stream.readRecord(Entry.ID, Record);
5672 switch (BitCode) {
5673 default:
5674 break; // Default behavior, ignore unknown content.
5675 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005676 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005677 SmallString<128> ValueName;
5678 if (convertToString(Record, 0, ValueName))
5679 return error("Invalid record");
5680 SourceFileName = ValueName.c_str();
5681 break;
5682 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005683 /// MODULE_CODE_HASH: [5*i32]
5684 case bitc::MODULE_CODE_HASH: {
5685 if (Record.size() != 5)
5686 return error("Invalid hash length " + Twine(Record.size()).str());
5687 if (!TheIndex)
5688 break;
5689 if (TheIndex->modulePaths().empty())
5690 // Does not have any summary emitted.
5691 break;
5692 if (TheIndex->modulePaths().size() != 1)
5693 return error("Don't expect multiple modules defined?");
5694 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5695 int Pos = 0;
5696 for (auto &Val : Record) {
5697 assert(!(Val >> 32) && "Unexpected high bits set");
5698 Hash[Pos++] = Val;
5699 }
5700 break;
5701 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005702 /// MODULE_CODE_VSTOFFSET: [offset]
5703 case bitc::MODULE_CODE_VSTOFFSET:
5704 if (Record.size() < 1)
5705 return error("Invalid record");
5706 VSTOffset = Record[0];
5707 break;
5708 // GLOBALVAR: [pointer type, isconst, initid,
5709 // linkage, alignment, section, visibility, threadlocal,
5710 // unnamed_addr, externally_initialized, dllstorageclass,
5711 // comdat]
5712 case bitc::MODULE_CODE_GLOBALVAR: {
5713 if (Record.size() < 6)
5714 return error("Invalid record");
5715 uint64_t RawLinkage = Record[3];
5716 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5717 ValueIdToLinkageMap[ValueId++] = Linkage;
5718 break;
5719 }
5720 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5721 // alignment, section, visibility, gc, unnamed_addr,
5722 // prologuedata, dllstorageclass, comdat, prefixdata]
5723 case bitc::MODULE_CODE_FUNCTION: {
5724 if (Record.size() < 8)
5725 return error("Invalid record");
5726 uint64_t RawLinkage = Record[3];
5727 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5728 ValueIdToLinkageMap[ValueId++] = Linkage;
5729 break;
5730 }
5731 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
5732 // dllstorageclass]
5733 case bitc::MODULE_CODE_ALIAS: {
5734 if (Record.size() < 6)
5735 return error("Invalid record");
5736 uint64_t RawLinkage = Record[3];
5737 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5738 ValueIdToLinkageMap[ValueId++] = Linkage;
5739 break;
5740 }
5741 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005742 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005743 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005744 }
5745 }
5746}
5747
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005748// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5749// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005750std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005751 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005752 return error("Invalid record");
5753
5754 SmallVector<uint64_t, 64> Record;
5755
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005756 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00005757 while (1) {
5758 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5759
5760 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005761 case BitstreamEntry::SubBlock: // Handled for us already.
5762 case BitstreamEntry::Error:
5763 return error("Malformed block");
5764 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005765 // For a per-module index, remove any entries that still have empty
5766 // summaries. The VST parsing creates entries eagerly for all symbols,
5767 // but not all have associated summaries (e.g. it doesn't know how to
5768 // distinguish between VST_CODE_ENTRY for function declarations vs global
5769 // variables with initializers that end up with a summary). Remove those
5770 // entries now so that we don't need to rely on the combined index merger
5771 // to clean them up (especially since that may not run for the first
5772 // module's index if we merge into that).
5773 if (!Combined)
5774 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005775 return std::error_code();
5776 case BitstreamEntry::Record:
5777 // The interesting case.
5778 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005779 }
5780
5781 // Read a record. The record format depends on whether this
5782 // is a per-module index or a combined index file. In the per-module
5783 // case the records contain the associated value's ID for correlation
5784 // with VST entries. In the combined index the correlation is done
5785 // via the bitcode offset of the summary records (which were saved
5786 // in the combined index VST entries). The records also contain
5787 // information used for ThinLTO renaming and importing.
5788 Record.clear();
5789 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005790 auto BitCode = Stream.readRecord(Entry.ID, Record);
5791 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005792 default: // Default behavior: ignore.
5793 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005794 // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid,
5795 // n x (valueid, callsitecount)]
5796 // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs,
5797 // numrefs x valueid,
5798 // n x (valueid, callsitecount, profilecount)]
5799 case bitc::FS_PERMODULE:
5800 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005801 unsigned ValueID = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005802 uint64_t RawLinkage = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005803 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005804 unsigned NumRefs = Record[3];
5805 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5806 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005807 // The module path string ref set in the summary must be owned by the
5808 // index's module string table. Since we don't have a module path
5809 // string table section in the per-module index, we create a single
5810 // module path string table entry with an empty (0) ID to take
5811 // ownership.
5812 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005813 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005814 static int RefListStartIndex = 4;
5815 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5816 assert(Record.size() >= RefListStartIndex + NumRefs &&
5817 "Record size inconsistent with number of references");
5818 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5819 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005820 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005821 FS->addRefEdge(RefGUID);
5822 }
5823 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5824 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5825 ++I) {
5826 unsigned CalleeValueId = Record[I];
5827 unsigned CallsiteCount = Record[++I];
5828 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005829 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005830 FS->addCallGraphEdge(CalleeGUID,
5831 CalleeInfo(CallsiteCount, ProfileCount));
5832 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005833 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00005834 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005835 assert(!Info->summary() && "Expected a single summary per VST entry");
5836 Info->setSummary(std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005837 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005838 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005839 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid]
5840 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5841 unsigned ValueID = Record[0];
5842 uint64_t RawLinkage = Record[1];
5843 std::unique_ptr<GlobalVarSummary> FS =
5844 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5845 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005846 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005847 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5848 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005849 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005850 FS->addRefEdge(RefGUID);
5851 }
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005852 GlobalValue::GUID GUID = getGUIDFromValueId(ValueID);
Teresa Johnsonfb7c7642016-04-05 00:40:16 +00005853 auto *Info = TheIndex->getGlobalValueInfo(GUID);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005854 assert(!Info->summary() && "Expected a single summary per VST entry");
5855 Info->setSummary(std::move(FS));
5856 break;
5857 }
5858 // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid,
5859 // n x (valueid, callsitecount)]
5860 // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs,
5861 // numrefs x valueid,
5862 // n x (valueid, callsitecount, profilecount)]
5863 case bitc::FS_COMBINED:
5864 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005865 uint64_t ModuleId = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005866 uint64_t RawLinkage = Record[1];
5867 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005868 unsigned NumRefs = Record[3];
5869 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5870 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005871 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005872 static int RefListStartIndex = 4;
5873 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5874 assert(Record.size() >= RefListStartIndex + NumRefs &&
5875 "Record size inconsistent with number of references");
5876 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5877 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005878 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005879 FS->addRefEdge(RefGUID);
5880 }
5881 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5882 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5883 ++I) {
5884 unsigned CalleeValueId = Record[I];
5885 unsigned CallsiteCount = Record[++I];
5886 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005887 GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005888 FS->addCallGraphEdge(CalleeGUID,
5889 CalleeInfo(CallsiteCount, ProfileCount));
5890 }
5891 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5892 assert(!Info->summary() && "Expected a single summary per VST entry");
5893 Info->setSummary(std::move(FS));
5894 Combined = true;
5895 break;
5896 }
5897 // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid]
5898 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5899 uint64_t ModuleId = Record[0];
5900 uint64_t RawLinkage = Record[1];
5901 std::unique_ptr<GlobalVarSummary> FS =
5902 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5903 FS->setModulePath(ModuleIdMap[ModuleId]);
5904 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5905 unsigned RefValueId = Record[I];
Mehdi Aminiad5741b2016-04-02 05:07:53 +00005906 GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005907 FS->addRefEdge(RefGUID);
5908 }
5909 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5910 assert(!Info->summary() && "Expected a single summary per VST entry");
5911 Info->setSummary(std::move(FS));
5912 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005913 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005914 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005915 }
5916 }
5917 llvm_unreachable("Exit infinite loop");
5918}
5919
5920// Parse the module string table block into the Index.
5921// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005922std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005923 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5924 return error("Invalid record");
5925
5926 SmallVector<uint64_t, 64> Record;
5927
5928 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005929 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00005930 while (1) {
5931 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5932
5933 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005934 case BitstreamEntry::SubBlock: // Handled for us already.
5935 case BitstreamEntry::Error:
5936 return error("Malformed block");
5937 case BitstreamEntry::EndBlock:
5938 return std::error_code();
5939 case BitstreamEntry::Record:
5940 // The interesting case.
5941 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005942 }
5943
5944 Record.clear();
5945 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005946 default: // Default behavior: ignore.
5947 break;
5948 case bitc::MST_CODE_ENTRY: {
5949 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005950 uint64_t ModuleId = Record[0];
5951
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005952 if (convertToString(Record, 1, ModulePath))
5953 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005954
5955 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
5956 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5957
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005958 ModulePath.clear();
5959 break;
5960 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005961 /// MST_CODE_HASH: [5*i32]
5962 case bitc::MST_CODE_HASH: {
5963 if (Record.size() != 5)
5964 return error("Invalid hash length " + Twine(Record.size()).str());
5965 if (LastSeenModulePath == TheIndex->modulePaths().end())
5966 return error("Invalid hash that does not follow a module path");
5967 int Pos = 0;
5968 for (auto &Val : Record) {
5969 assert(!(Val >> 32) && "Unexpected high bits set");
5970 LastSeenModulePath->second.second[Pos++] = Val;
5971 }
5972 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5973 LastSeenModulePath = TheIndex->modulePaths().end();
5974 break;
5975 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005976 }
5977 }
5978 llvm_unreachable("Exit infinite loop");
5979}
5980
5981// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005982std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
5983 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005984 TheIndex = I;
5985
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005986 if (std::error_code EC = initStream(std::move(Streamer)))
5987 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005988
5989 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005990 if (!hasValidBitcodeHeader(Stream))
5991 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005992
5993 // We expect a number of well-defined blocks, though we don't necessarily
5994 // need to understand them all.
5995 while (1) {
5996 if (Stream.AtEndOfStream()) {
5997 // We didn't really read a proper Module block.
5998 return error("Malformed block");
5999 }
6000
6001 BitstreamEntry Entry =
6002 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
6003
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006004 if (Entry.Kind != BitstreamEntry::SubBlock)
6005 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00006006
6007 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
6008 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006009 if (Entry.ID == bitc::MODULE_BLOCK_ID)
6010 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00006011
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006012 if (Stream.SkipBlock())
6013 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006014 }
6015}
6016
Teresa Johnson26ab5772016-03-15 00:04:37 +00006017// Parse the summary information at the given offset in the buffer into
6018// the index. Used to support lazy parsing of summaries from the
Teresa Johnson403a7872015-10-04 14:33:43 +00006019// combined index during importing.
6020// TODO: This function is not yet complete as it won't have a consumer
6021// until ThinLTO function importing is added.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006022std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary(
6023 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I,
6024 size_t SummaryOffset) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006025 TheIndex = I;
6026
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006027 if (std::error_code EC = initStream(std::move(Streamer)))
6028 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006029
6030 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006031 if (!hasValidBitcodeHeader(Stream))
6032 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006033
Teresa Johnson26ab5772016-03-15 00:04:37 +00006034 Stream.JumpToBit(SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +00006035
6036 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6037
6038 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006039 default:
6040 return error("Malformed block");
6041 case BitstreamEntry::Record:
6042 // The expected case.
6043 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006044 }
6045
6046 // TODO: Read a record. This interface will be completed when ThinLTO
6047 // importing is added so that it can be tested.
6048 SmallVector<uint64_t, 64> Record;
6049 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006050 case bitc::FS_COMBINED:
6051 case bitc::FS_COMBINED_PROFILE:
6052 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006053 default:
6054 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006055 }
6056
6057 return std::error_code();
6058}
6059
Teresa Johnson26ab5772016-03-15 00:04:37 +00006060std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6061 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006062 if (Streamer)
6063 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006064 return initStreamFromBuffer();
6065}
6066
Teresa Johnson26ab5772016-03-15 00:04:37 +00006067std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006068 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6069 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6070
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006071 if (Buffer->getBufferSize() & 3)
6072 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006073
6074 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6075 // The magic number is 0x0B17C0DE stored in little endian.
6076 if (isBitcodeWrapper(BufPtr, BufEnd))
6077 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6078 return error("Invalid bitcode wrapper header");
6079
6080 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6081 Stream.init(&*StreamFile);
6082
6083 return std::error_code();
6084}
6085
Teresa Johnson26ab5772016-03-15 00:04:37 +00006086std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006087 std::unique_ptr<DataStreamer> Streamer) {
6088 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6089 // see it.
6090 auto OwnedBytes =
6091 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6092 StreamingMemoryObject &Bytes = *OwnedBytes;
6093 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6094 Stream.init(&*StreamFile);
6095
6096 unsigned char buf[16];
6097 if (Bytes.readBytes(buf, 16, 0) != 16)
6098 return error("Invalid bitcode signature");
6099
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006100 if (!isBitcode(buf, buf + 16))
6101 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006102
6103 if (isBitcodeWrapper(buf, buf + 4)) {
6104 const unsigned char *bitcodeStart = buf;
6105 const unsigned char *bitcodeEnd = buf + 16;
6106 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6107 Bytes.dropLeadingBytes(bitcodeStart - buf);
6108 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6109 }
6110 return std::error_code();
6111}
6112
Rafael Espindola48da4f42013-11-04 16:16:24 +00006113namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00006114class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006115 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006116 return "llvm.bitcode";
6117 }
Craig Topper73156022014-03-02 09:09:27 +00006118 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006119 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006120 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006121 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006122 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006123 case BitcodeError::CorruptedBitcode:
6124 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006125 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006126 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006127 }
6128};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006129} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006130
Chris Bieneman770163e2014-09-19 20:29:02 +00006131static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6132
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006133const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006134 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006135}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006136
Chris Lattner6694f602007-04-29 07:54:31 +00006137//===----------------------------------------------------------------------===//
6138// External interface
6139//===----------------------------------------------------------------------===//
6140
Rafael Espindola456baad2015-06-17 01:15:47 +00006141static ErrorOr<std::unique_ptr<Module>>
6142getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6143 BitcodeReader *R, LLVMContext &Context,
6144 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6145 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6146 M->setMaterializer(R);
6147
6148 auto cleanupOnError = [&](std::error_code EC) {
6149 R->releaseBuffer(); // Never take ownership on error.
6150 return EC;
6151 };
6152
6153 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6154 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6155 ShouldLazyLoadMetadata))
6156 return cleanupOnError(EC);
6157
6158 if (MaterializeAll) {
6159 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006160 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006161 return cleanupOnError(EC);
6162 } else {
6163 // Resolve forward references from blockaddresses.
6164 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6165 return cleanupOnError(EC);
6166 }
6167 return std::move(M);
6168}
6169
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006170/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006171///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006172/// This isn't always used in a lazy context. In particular, it's also used by
6173/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6174/// in forward-referenced functions from block address references.
6175///
Rafael Espindola728074b2015-06-17 00:40:56 +00006176/// \param[in] MaterializeAll Set to \c true if we should materialize
6177/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006178static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006179getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006180 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006181 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006182 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006183
Rafael Espindola456baad2015-06-17 01:15:47 +00006184 ErrorOr<std::unique_ptr<Module>> Ret =
6185 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6186 MaterializeAll, ShouldLazyLoadMetadata);
6187 if (!Ret)
6188 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006189
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006190 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006191 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006192}
6193
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006194ErrorOr<std::unique_ptr<Module>>
6195llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6196 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006197 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006198 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006199}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006200
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006201ErrorOr<std::unique_ptr<Module>>
6202llvm::getStreamedBitcodeModule(StringRef Name,
6203 std::unique_ptr<DataStreamer> Streamer,
6204 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006205 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006206 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006207
6208 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6209 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006210}
6211
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006212ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6213 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006214 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006215 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006216 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6217 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006218}
Bill Wendling0198ce02010-10-06 01:22:42 +00006219
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006220std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6221 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006222 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006223 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006224 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006225 if (Triple.getError())
6226 return "";
6227 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006228}
Teresa Johnson403a7872015-10-04 14:33:43 +00006229
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006230std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6231 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006232 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006233 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006234 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6235 if (ProducerString.getError())
6236 return "";
6237 return ProducerString.get();
6238}
6239
Teresa Johnson403a7872015-10-04 14:33:43 +00006240// Parse the specified bitcode buffer, returning the function info index.
6241// If IsLazy is false, parse the entire function summary into
6242// the index. Otherwise skip the function summary section, and only create
6243// an index object with a map from function name to function summary offset.
6244// The index is used to perform lazy function summary reading later.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006245ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6246llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
6247 DiagnosticHandlerFunction DiagnosticHandler,
6248 bool IsLazy) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006249 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006250 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
Teresa Johnson403a7872015-10-04 14:33:43 +00006251
Teresa Johnson26ab5772016-03-15 00:04:37 +00006252 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006253
6254 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006255 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006256 return EC;
6257 };
6258
6259 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6260 return cleanupOnError(EC);
6261
Teresa Johnson26ab5772016-03-15 00:04:37 +00006262 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006263 return std::move(Index);
6264}
6265
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006266// Check if the given bitcode buffer contains a global value summary block.
6267bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6268 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006269 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006270 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006271
6272 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006273 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006274 return false;
6275 };
6276
6277 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6278 return cleanupOnError(EC);
6279
Teresa Johnson26ab5772016-03-15 00:04:37 +00006280 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006281 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006282}
6283
Teresa Johnson26ab5772016-03-15 00:04:37 +00006284// This method supports lazy reading of summary data from the combined
Teresa Johnson403a7872015-10-04 14:33:43 +00006285// index during ThinLTO function importing. When reading the combined index
Teresa Johnson26ab5772016-03-15 00:04:37 +00006286// file, getModuleSummaryIndex is first invoked with IsLazy=true.
6287// Then this method is called for each value considered for importing,
6288// to parse the summary information for the given value name into
Teresa Johnson403a7872015-10-04 14:33:43 +00006289// the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006290std::error_code llvm::readGlobalValueSummary(
Mehdi Amini354f5202015-11-19 05:52:29 +00006291 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson26ab5772016-03-15 00:04:37 +00006292 StringRef ValueName, std::unique_ptr<ModuleSummaryIndex> Index) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006293 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006294 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler);
Teresa Johnson403a7872015-10-04 14:33:43 +00006295
6296 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006297 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006298 return EC;
6299 };
6300
Teresa Johnson26ab5772016-03-15 00:04:37 +00006301 // Lookup the given value name in the GlobalValueMap, which may
6302 // contain a list of global value infos in the case of a COMDAT. Walk through
6303 // and parse each summary info at the summary offset
Teresa Johnson403a7872015-10-04 14:33:43 +00006304 // recorded when parsing the value symbol table.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006305 for (const auto &FI : Index->getGlobalValueInfoList(ValueName)) {
6306 size_t SummaryOffset = FI->bitcodeIndex();
Teresa Johnson403a7872015-10-04 14:33:43 +00006307 if (std::error_code EC =
Teresa Johnson26ab5772016-03-15 00:04:37 +00006308 R.parseGlobalValueSummary(nullptr, Index.get(), SummaryOffset))
Teresa Johnson403a7872015-10-04 14:33:43 +00006309 return cleanupOnError(EC);
6310 }
6311
Teresa Johnson26ab5772016-03-15 00:04:37 +00006312 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006313 return std::error_code();
6314}