blob: 1840b60cc01280f97b5da542106d33423e08cfdf [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"
Derek Schuff8b2dcad2012-02-06 22:30:29 +000032#include "llvm/Support/DataStream.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000033#include "llvm/Support/ManagedStatic.h"
Chris Lattner08feb1e2007-04-24 04:04:35 +000034#include "llvm/Support/MathExtras.h"
Chris Lattner6694f602007-04-29 07:54:31 +000035#include "llvm/Support/MemoryBuffer.h"
Tobias Grosser0a8e12f2013-07-26 04:16:55 +000036#include "llvm/Support/raw_ostream.h"
Benjamin Kramercced8be2015-03-17 20:40:24 +000037#include <deque>
Eugene Zelenko6ac3f732016-01-26 18:48:36 +000038
Chris Lattner1314b992007-04-22 06:23:29 +000039using namespace llvm;
40
Benjamin Kramercced8be2015-03-17 20:40:24 +000041namespace {
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +000042enum {
43 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
44};
45
Benjamin Kramercced8be2015-03-17 20:40:24 +000046class BitcodeReaderValueList {
47 std::vector<WeakVH> ValuePtrs;
48
Rafael Espindolacbdcb502015-06-15 20:55:37 +000049 /// As we resolve forward-referenced constants, we add information about them
50 /// to this vector. This allows us to resolve them in bulk instead of
51 /// resolving each reference at a time. See the code in
Benjamin Kramercced8be2015-03-17 20:40:24 +000052 /// ResolveConstantForwardRefs for more information about this.
53 ///
54 /// The key of this vector is the placeholder constant, the value is the slot
55 /// number that holds the resolved value.
56 typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
57 ResolveConstantsTy ResolveConstants;
58 LLVMContext &Context;
59public:
60 BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
61 ~BitcodeReaderValueList() {
62 assert(ResolveConstants.empty() && "Constants not resolved?");
63 }
64
65 // vector compatibility methods
66 unsigned size() const { return ValuePtrs.size(); }
67 void resize(unsigned N) { ValuePtrs.resize(N); }
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +000068 void push_back(Value *V) { ValuePtrs.emplace_back(V); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000069
70 void clear() {
71 assert(ResolveConstants.empty() && "Constants not resolved?");
72 ValuePtrs.clear();
73 }
74
75 Value *operator[](unsigned i) const {
76 assert(i < ValuePtrs.size());
77 return ValuePtrs[i];
78 }
79
80 Value *back() const { return ValuePtrs.back(); }
Duncan P. N. Exon Smith7457ecb2016-03-30 04:21:52 +000081 void pop_back() { ValuePtrs.pop_back(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +000082 bool empty() const { return ValuePtrs.empty(); }
83 void shrinkTo(unsigned N) {
84 assert(N <= size() && "Invalid shrinkTo request!");
85 ValuePtrs.resize(N);
86 }
87
88 Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
David Majnemer8a1c45d2015-12-12 05:38:55 +000089 Value *getValueFwdRef(unsigned Idx, Type *Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +000090
David Majnemer8a1c45d2015-12-12 05:38:55 +000091 void assignValue(Value *V, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +000092
Rafael Espindolacbdcb502015-06-15 20:55:37 +000093 /// Once all constants are read, this method bulk resolves any forward
94 /// references.
95 void resolveConstantForwardRefs();
Benjamin Kramercced8be2015-03-17 20:40:24 +000096};
97
Teresa Johnson61b406e2015-12-29 23:00:22 +000098class BitcodeReaderMetadataList {
Benjamin Kramercced8be2015-03-17 20:40:24 +000099 unsigned NumFwdRefs;
100 bool AnyFwdRefs;
101 unsigned MinFwdRef;
102 unsigned MaxFwdRef;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000103 std::vector<TrackingMDRef> MetadataPtrs;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000104
105 LLVMContext &Context;
106public:
Teresa Johnson61b406e2015-12-29 23:00:22 +0000107 BitcodeReaderMetadataList(LLVMContext &C)
Teresa Johnson34702952015-12-21 15:38:13 +0000108 : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
Benjamin Kramercced8be2015-03-17 20:40:24 +0000109
110 // vector compatibility methods
Teresa Johnson61b406e2015-12-29 23:00:22 +0000111 unsigned size() const { return MetadataPtrs.size(); }
112 void resize(unsigned N) { MetadataPtrs.resize(N); }
113 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
114 void clear() { MetadataPtrs.clear(); }
115 Metadata *back() const { return MetadataPtrs.back(); }
116 void pop_back() { MetadataPtrs.pop_back(); }
117 bool empty() const { return MetadataPtrs.empty(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000118
119 Metadata *operator[](unsigned i) const {
Teresa Johnson61b406e2015-12-29 23:00:22 +0000120 assert(i < MetadataPtrs.size());
121 return MetadataPtrs[i];
Benjamin Kramercced8be2015-03-17 20:40:24 +0000122 }
123
124 void shrinkTo(unsigned N) {
125 assert(N <= size() && "Invalid shrinkTo request!");
Teresa Johnson61b406e2015-12-29 23:00:22 +0000126 MetadataPtrs.resize(N);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000127 }
128
Justin Bognerae341c62016-03-17 20:12:06 +0000129 Metadata *getMetadataFwdRef(unsigned Idx);
130 MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000131 void assignValue(Metadata *MD, unsigned Idx);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000132 void tryToResolveCycles();
133};
134
135class BitcodeReader : public GVMaterializer {
136 LLVMContext &Context;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000137 Module *TheModule = nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000138 std::unique_ptr<MemoryBuffer> Buffer;
139 std::unique_ptr<BitstreamReader> StreamFile;
140 BitstreamCursor Stream;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000141 // Next offset to start scanning for lazy parsing of function bodies.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000142 uint64_t NextUnreadBit = 0;
Teresa Johnson1493ad92015-10-10 14:18:36 +0000143 // Last function offset found in the VST.
144 uint64_t LastFunctionBlockBit = 0;
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000145 bool SeenValueSymbolTable = false;
Peter Collingbourne128a9762015-10-27 23:01:25 +0000146 uint64_t VSTOffset = 0;
Mehdi Amini5d303282015-10-26 18:37:00 +0000147 // Contains an arbitrary and optional string identifying the bitcode producer
148 std::string ProducerIdentification;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000149
150 std::vector<Type*> TypeList;
151 BitcodeReaderValueList ValueList;
Teresa Johnson61b406e2015-12-29 23:00:22 +0000152 BitcodeReaderMetadataList MetadataList;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000153 std::vector<Comdat *> ComdatList;
154 SmallVector<Instruction *, 64> InstructionList;
155
156 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
157 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
158 std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
159 std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
David Majnemer7fddecc2015-06-17 20:52:32 +0000160 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000161
162 SmallVector<Instruction*, 64> InstsWithTBAATag;
163
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +0000164 bool HasSeenOldLoopTags = false;
165
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000166 /// The set of attributes by index. Index zero in the file is for null, and
167 /// is thus not represented here. As such all indices are off by one.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000168 std::vector<AttributeSet> MAttributes;
169
Karl Schimpf36440082015-08-31 16:43:55 +0000170 /// The set of attribute groups.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000171 std::map<unsigned, AttributeSet> MAttributeGroups;
172
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000173 /// While parsing a function body, this is a list of the basic blocks for the
174 /// function.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000175 std::vector<BasicBlock*> FunctionBBs;
176
177 // When reading the module header, this list is populated with functions that
178 // have bodies later in the file.
179 std::vector<Function*> FunctionsWithBodies;
180
181 // When intrinsic functions are encountered which require upgrading they are
182 // stored here with their replacement function.
Rafael Espindola4e721212015-07-02 16:22:40 +0000183 typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000184 UpgradedIntrinsicMap UpgradedIntrinsics;
185
186 // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
187 DenseMap<unsigned, unsigned> MDKindMap;
188
189 // Several operations happen after the module header has been read, but
190 // before function bodies are processed. This keeps track of whether
191 // we've done this yet.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000192 bool SeenFirstFunctionBody = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000193
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000194 /// When function bodies are initially scanned, this map contains info about
195 /// where to find deferred function body in the stream.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000196 DenseMap<Function*, uint64_t> DeferredFunctionInfo;
197
198 /// When Metadata block is initially scanned when parsing the module, we may
199 /// choose to defer parsing of the metadata. This vector contains info about
200 /// which Metadata blocks are deferred.
201 std::vector<uint64_t> DeferredMetadataInfo;
202
203 /// These are basic blocks forward-referenced by block addresses. They are
204 /// inserted lazily into functions when they're loaded. The basic block ID is
205 /// its index into the vector.
206 DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
207 std::deque<Function *> BasicBlockFwdRefQueue;
208
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000209 /// Indicates that we are using a new encoding for instruction operands where
210 /// most operands in the current FUNCTION_BLOCK are encoded relative to the
211 /// instruction number, for a more compact encoding. Some instruction
212 /// operands are not relative to the instruction ID: basic block numbers, and
213 /// types. Once the old style function blocks have been phased out, we would
Benjamin Kramercced8be2015-03-17 20:40:24 +0000214 /// not need this flag.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000215 bool UseRelativeIDs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000216
217 /// True if all functions will be materialized, negating the need to process
218 /// (e.g.) blockaddress forward references.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000219 bool WillMaterializeAllForwardRefs = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000220
Benjamin Kramercced8be2015-03-17 20:40:24 +0000221 /// True if any Metadata block has been materialized.
Rafael Espindola4223a1f2015-06-15 20:08:17 +0000222 bool IsMetadataMaterialized = false;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000223
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000224 bool StripDebugInfo = false;
225
Peter Collingbourned4bff302015-11-05 22:03:56 +0000226 /// Functions that need to be matched with subprograms when upgrading old
227 /// metadata.
228 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
229
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000230 std::vector<std::string> BundleTags;
231
Benjamin Kramercced8be2015-03-17 20:40:24 +0000232public:
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000233 std::error_code error(BitcodeError E, const Twine &Message);
234 std::error_code error(BitcodeError E);
235 std::error_code error(const Twine &Message);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000236
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000237 BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context);
238 BitcodeReader(LLVMContext &Context);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000239 ~BitcodeReader() override { freeState(); }
Benjamin Kramercced8be2015-03-17 20:40:24 +0000240
241 std::error_code materializeForwardReferencedFunctions();
242
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000243 void freeState();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000244
245 void releaseBuffer();
246
Benjamin Kramercced8be2015-03-17 20:40:24 +0000247 std::error_code materialize(GlobalValue *GV) override;
Rafael Espindola79753a02015-12-18 21:18:57 +0000248 std::error_code materializeModule() override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000249 std::vector<StructType *> getIdentifiedStructTypes() const override;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000250
Rafael Espindola6ace6852015-06-15 21:02:49 +0000251 /// \brief Main interface to parsing a bitcode buffer.
252 /// \returns true if an error occurred.
Rafael Espindola1aabf982015-06-16 23:29:49 +0000253 std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
254 Module *M,
Benjamin Kramercced8be2015-03-17 20:40:24 +0000255 bool ShouldLazyLoadMetadata = false);
256
Rafael Espindola6ace6852015-06-15 21:02:49 +0000257 /// \brief Cheap mechanism to just extract module triple
258 /// \returns true if an error occurred.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000259 ErrorOr<std::string> parseTriple();
260
Mehdi Amini3383ccc2015-11-09 02:46:41 +0000261 /// Cheap mechanism to just extract the identification block out of bitcode.
262 ErrorOr<std::string> parseIdentificationBlock();
263
Benjamin Kramercced8be2015-03-17 20:40:24 +0000264 static uint64_t decodeSignRotatedValue(uint64_t V);
265
266 /// Materialize any deferred Metadata block.
267 std::error_code materializeMetadata() override;
268
Rafael Espindola0d68b4c2015-03-30 21:36:43 +0000269 void setStripDebugInfo() override;
270
Benjamin Kramercced8be2015-03-17 20:40:24 +0000271private:
Mehdi Amini5d303282015-10-26 18:37:00 +0000272 /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
273 // ProducerIdentification data member, and do some basic enforcement on the
274 // "epoch" encoded in the bitcode.
275 std::error_code parseBitcodeVersion();
276
Benjamin Kramercced8be2015-03-17 20:40:24 +0000277 std::vector<StructType *> IdentifiedStructTypes;
278 StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
279 StructType *createIdentifiedStructType(LLVMContext &Context);
280
281 Type *getTypeByID(unsigned ID);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000282 Value *getFnValueByID(unsigned ID, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000283 if (Ty && Ty->isMetadataTy())
284 return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
David Majnemer8a1c45d2015-12-12 05:38:55 +0000285 return ValueList.getValueFwdRef(ID, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000286 }
287 Metadata *getFnMetadataByID(unsigned ID) {
Justin Bognerae341c62016-03-17 20:12:06 +0000288 return MetadataList.getMetadataFwdRef(ID);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000289 }
290 BasicBlock *getBasicBlock(unsigned ID) const {
291 if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
292 return FunctionBBs[ID];
293 }
294 AttributeSet getAttributes(unsigned i) const {
295 if (i-1 < MAttributes.size())
296 return MAttributes[i-1];
297 return AttributeSet();
298 }
299
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000300 /// Read a value/type pair out of the specified record from slot 'Slot'.
301 /// Increment Slot past the number of slots used in the record. Return true on
302 /// failure.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000303 bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
304 unsigned InstNum, Value *&ResVal) {
305 if (Slot == Record.size()) return true;
306 unsigned ValNo = (unsigned)Record[Slot++];
307 // Adjust the ValNo, if it was encoded relative to the InstNum.
308 if (UseRelativeIDs)
309 ValNo = InstNum - ValNo;
310 if (ValNo < InstNum) {
311 // If this is not a forward reference, just return the value we already
312 // have.
313 ResVal = getFnValueByID(ValNo, nullptr);
314 return ResVal == nullptr;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000315 }
David Blaikiedbe6e0f2015-04-17 06:40:14 +0000316 if (Slot == Record.size())
317 return true;
Benjamin Kramercced8be2015-03-17 20:40:24 +0000318
319 unsigned TypeNo = (unsigned)Record[Slot++];
320 ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
321 return ResVal == nullptr;
322 }
323
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000324 /// Read a value out of the specified record from slot 'Slot'. Increment Slot
325 /// past the number of slots used by the value in the record. Return true if
326 /// there is an error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000327 bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000328 unsigned InstNum, Type *Ty, Value *&ResVal) {
329 if (getValue(Record, Slot, InstNum, Ty, ResVal))
Benjamin Kramercced8be2015-03-17 20:40:24 +0000330 return true;
331 // All values currently take a single record slot.
332 ++Slot;
333 return false;
334 }
335
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000336 /// Like popValue, but does not increment the Slot number.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000337 bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000338 unsigned InstNum, Type *Ty, Value *&ResVal) {
339 ResVal = getValue(Record, Slot, InstNum, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000340 return ResVal == nullptr;
341 }
342
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000343 /// Version of getValue that returns ResVal directly, or 0 if there is an
344 /// error.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000345 Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000346 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000347 if (Slot == Record.size()) return nullptr;
348 unsigned ValNo = (unsigned)Record[Slot];
349 // Adjust the ValNo, if it was encoded relative to the InstNum.
350 if (UseRelativeIDs)
351 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000352 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000353 }
354
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000355 /// Like getValue, but decodes signed VBRs.
Benjamin Kramercced8be2015-03-17 20:40:24 +0000356 Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
David Majnemer8a1c45d2015-12-12 05:38:55 +0000357 unsigned InstNum, Type *Ty) {
Benjamin Kramercced8be2015-03-17 20:40:24 +0000358 if (Slot == Record.size()) return nullptr;
359 unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
360 // Adjust the ValNo, if it was encoded relative to the InstNum.
361 if (UseRelativeIDs)
362 ValNo = InstNum - ValNo;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000363 return getFnValueByID(ValNo, Ty);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000364 }
365
366 /// Converts alignment exponent (i.e. power of two (or zero)) to the
367 /// corresponding alignment to use. If alignment is too large, returns
368 /// a corresponding error code.
369 std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000370 std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
Teresa Johnson1493ad92015-10-10 14:18:36 +0000371 std::error_code parseModule(uint64_t ResumeBit,
372 bool ShouldLazyLoadMetadata = false);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000373 std::error_code parseAttributeBlock();
374 std::error_code parseAttributeGroupBlock();
375 std::error_code parseTypeTable();
376 std::error_code parseTypeTableBody();
Sanjoy Dasb513a9f2015-09-24 23:34:52 +0000377 std::error_code parseOperandBundleTags();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000378
Teresa Johnsonff642b92015-09-17 20:12:00 +0000379 ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
380 unsigned NameIndex, Triple &TT);
Peter Collingbourne128a9762015-10-27 23:01:25 +0000381 std::error_code parseValueSymbolTable(uint64_t Offset = 0);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000382 std::error_code parseConstants();
Teresa Johnson1493ad92015-10-10 14:18:36 +0000383 std::error_code rememberAndSkipFunctionBodies();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000384 std::error_code rememberAndSkipFunctionBody();
Benjamin Kramercced8be2015-03-17 20:40:24 +0000385 /// Save the positions of the Metadata blocks and skip parsing the blocks.
386 std::error_code rememberAndSkipMetadata();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000387 std::error_code parseFunctionBody(Function *F);
388 std::error_code globalCleanup();
389 std::error_code resolveGlobalAndAliasInits();
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +0000390 std::error_code parseMetadata(bool ModuleLevel = false);
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +0000391 std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
392 StringRef Blob,
393 unsigned &NextMetadataNo);
Teresa Johnson12545072015-11-15 02:00:09 +0000394 std::error_code parseMetadataKinds();
395 std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000396 std::error_code parseMetadataAttachment(Function &F);
Benjamin Kramercced8be2015-03-17 20:40:24 +0000397 ErrorOr<std::string> parseModuleTriple();
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000398 std::error_code parseUseLists();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000399 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000400 std::error_code initStreamFromBuffer();
Rafael Espindola1aabf982015-06-16 23:29:49 +0000401 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000402 std::error_code findFunctionInStream(
Benjamin Kramercced8be2015-03-17 20:40:24 +0000403 Function *F,
404 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
405};
Teresa Johnson403a7872015-10-04 14:33:43 +0000406
407/// Class to manage reading and parsing function summary index bitcode
408/// files/sections.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000409class ModuleSummaryIndexBitcodeReader {
Teresa Johnson403a7872015-10-04 14:33:43 +0000410 DiagnosticHandlerFunction DiagnosticHandler;
411
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000412 /// Eventually points to the module index built during parsing.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000413 ModuleSummaryIndex *TheIndex = nullptr;
Teresa Johnson403a7872015-10-04 14:33:43 +0000414
415 std::unique_ptr<MemoryBuffer> Buffer;
416 std::unique_ptr<BitstreamReader> StreamFile;
417 BitstreamCursor Stream;
418
419 /// \brief Used to indicate whether we are doing lazy parsing of summary data.
420 ///
421 /// If false, the summary section is fully parsed into the index during
422 /// the initial parse. Otherwise, if true, the caller is expected to
Teresa Johnson26ab5772016-03-15 00:04:37 +0000423 /// invoke \a readGlobalValueSummary for each summary needed, and the summary
Teresa Johnson403a7872015-10-04 14:33:43 +0000424 /// section is thus parsed lazily.
425 bool IsLazy = false;
426
427 /// Used to indicate whether caller only wants to check for the presence
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000428 /// of the global value summary bitcode section. All blocks are skipped,
429 /// but the SeenGlobalValSummary boolean is set.
430 bool CheckGlobalValSummaryPresenceOnly = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000431
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000432 /// Indicates whether we have encountered a global value summary section
433 /// yet during parsing, used when checking if file contains global value
Teresa Johnson403a7872015-10-04 14:33:43 +0000434 /// summary section.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000435 bool SeenGlobalValSummary = false;
Teresa Johnson403a7872015-10-04 14:33:43 +0000436
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000437 /// Indicates whether we have already parsed the VST, used for error checking.
438 bool SeenValueSymbolTable = false;
439
440 /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
441 /// Used to enable on-demand parsing of the VST.
442 uint64_t VSTOffset = 0;
443
444 // Map to save ValueId to GUID association that was recorded in the
445 // ValueSymbolTable. It is used after the VST is parsed to convert
446 // call graph edges read from the function summary from referencing
447 // callees by their ValueId to using the GUID instead, which is how
Teresa Johnson26ab5772016-03-15 00:04:37 +0000448 // they are recorded in the summary index being built.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000449 DenseMap<unsigned, uint64_t> ValueIdToCallGraphGUIDMap;
450
451 /// Map to save the association between summary offset in the VST to the
452 /// GlobalValueInfo object created when parsing it. Used to access the
453 /// info object when parsing the summary section.
454 DenseMap<uint64_t, GlobalValueInfo *> SummaryOffsetToInfoMap;
Teresa Johnson403a7872015-10-04 14:33:43 +0000455
456 /// Map populated during module path string table parsing, from the
457 /// module ID to a string reference owned by the index's module
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000458 /// path string table, used to correlate with combined index
Teresa Johnson403a7872015-10-04 14:33:43 +0000459 /// summary records.
460 DenseMap<uint64_t, StringRef> ModuleIdMap;
461
Teresa Johnsone1164de2016-02-10 21:55:02 +0000462 /// Original source file name recorded in a bitcode record.
463 std::string SourceFileName;
464
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000465public:
Teresa Johnson403a7872015-10-04 14:33:43 +0000466 std::error_code error(BitcodeError E, const Twine &Message);
467 std::error_code error(BitcodeError E);
468 std::error_code error(const Twine &Message);
469
Teresa Johnson26ab5772016-03-15 00:04:37 +0000470 ModuleSummaryIndexBitcodeReader(
471 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
472 bool IsLazy = false, bool CheckGlobalValSummaryPresenceOnly = false);
473 ModuleSummaryIndexBitcodeReader(
474 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy = false,
475 bool CheckGlobalValSummaryPresenceOnly = false);
476 ~ModuleSummaryIndexBitcodeReader() { freeState(); }
Teresa Johnson403a7872015-10-04 14:33:43 +0000477
478 void freeState();
479
480 void releaseBuffer();
481
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000482 /// Check if the parser has encountered a summary section.
483 bool foundGlobalValSummary() { return SeenGlobalValSummary; }
Teresa Johnson403a7872015-10-04 14:33:43 +0000484
485 /// \brief Main interface to parsing a bitcode buffer.
486 /// \returns true if an error occurred.
487 std::error_code parseSummaryIndexInto(std::unique_ptr<DataStreamer> Streamer,
Teresa Johnson26ab5772016-03-15 00:04:37 +0000488 ModuleSummaryIndex *I);
Teresa Johnson403a7872015-10-04 14:33:43 +0000489
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000490 /// \brief Interface for parsing a summary lazily.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000491 std::error_code
492 parseGlobalValueSummary(std::unique_ptr<DataStreamer> Streamer,
493 ModuleSummaryIndex *I, size_t SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000494
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000495private:
Teresa Johnson403a7872015-10-04 14:33:43 +0000496 std::error_code parseModule();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000497 std::error_code parseValueSymbolTable(
498 uint64_t Offset,
499 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
Teresa Johnson403a7872015-10-04 14:33:43 +0000500 std::error_code parseEntireSummary();
501 std::error_code parseModuleStringTable();
502 std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
503 std::error_code initStreamFromBuffer();
504 std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000505 uint64_t getGUIDFromValueId(unsigned ValueId);
506 GlobalValueInfo *getInfoFromSummaryOffset(uint64_t Offset);
Teresa Johnson403a7872015-10-04 14:33:43 +0000507};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000508} // end anonymous namespace
Benjamin Kramercced8be2015-03-17 20:40:24 +0000509
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000510BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
511 DiagnosticSeverity Severity,
512 const Twine &Msg)
513 : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
514
515void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
516
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000517static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000518 std::error_code EC, const Twine &Message) {
519 BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
520 DiagnosticHandler(DI);
521 return EC;
522}
523
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000524static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000525 std::error_code EC) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000526 return error(DiagnosticHandler, EC, EC.message());
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000527}
528
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000529static std::error_code error(LLVMContext &Context, std::error_code EC,
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000530 const Twine &Message) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000531 return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
532 Message);
533}
534
535static std::error_code error(LLVMContext &Context, std::error_code EC) {
536 return error(Context, EC, EC.message());
537}
538
539static std::error_code error(LLVMContext &Context, const Twine &Message) {
540 return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
541 Message);
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +0000542}
543
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000544std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
Mehdi Amini5d303282015-10-26 18:37:00 +0000545 if (!ProducerIdentification.empty()) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000546 return ::error(Context, make_error_code(E),
Filipe Cabecinhasf3e167a2015-11-03 13:48:21 +0000547 Message + " (Producer: '" + ProducerIdentification +
548 "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
Mehdi Amini5d303282015-10-26 18:37:00 +0000549 }
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000550 return ::error(Context, make_error_code(E), Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000551}
552
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000553std::error_code BitcodeReader::error(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(BitcodeError::CorruptedBitcode),
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(BitcodeError::CorruptedBitcode),
560 Message);
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000561}
562
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000563std::error_code BitcodeReader::error(BitcodeError E) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000564 return ::error(Context, make_error_code(E));
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000565}
566
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000567BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context)
568 : Context(Context), Buffer(Buffer), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000569 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000570
Rafael Espindola9d2bfc42015-12-14 23:17:03 +0000571BitcodeReader::BitcodeReader(LLVMContext &Context)
572 : Context(Context), Buffer(nullptr), ValueList(Context),
Teresa Johnson61b406e2015-12-29 23:00:22 +0000573 MetadataList(Context) {}
Rafael Espindolad0b23be2015-01-10 00:07:30 +0000574
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000575std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
576 if (WillMaterializeAllForwardRefs)
577 return std::error_code();
578
579 // Prevent recursion.
580 WillMaterializeAllForwardRefs = true;
581
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000582 while (!BasicBlockFwdRefQueue.empty()) {
583 Function *F = BasicBlockFwdRefQueue.front();
584 BasicBlockFwdRefQueue.pop_front();
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000585 assert(F && "Expected valid function");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000586 if (!BasicBlockFwdRefs.count(F))
587 // Already materialized.
588 continue;
589
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000590 // Check for a function that isn't materializable to prevent an infinite
591 // loop. When parsing a blockaddress stored in a global variable, there
592 // isn't a trivial way to check if a function will have a body without a
593 // linear search through FunctionsWithBodies, so just check it here.
594 if (!F->isMaterializable())
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000595 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000596
597 // Try to materialize F.
Rafael Espindola5a52e6d2014-10-24 22:50:48 +0000598 if (std::error_code EC = materialize(F))
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000599 return EC;
Rafael Espindolab7993462012-01-02 07:49:53 +0000600 }
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000601 assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +0000602
603 // Reset state.
604 WillMaterializeAllForwardRefs = false;
605 return std::error_code();
Rafael Espindolab7993462012-01-02 07:49:53 +0000606}
607
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000608void BitcodeReader::freeState() {
Craig Topper2617dcc2014-04-15 06:32:26 +0000609 Buffer = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000610 std::vector<Type*>().swap(TypeList);
Chris Lattner9eeada92007-05-18 04:02:46 +0000611 ValueList.clear();
Teresa Johnson61b406e2015-12-29 23:00:22 +0000612 MetadataList.clear();
David Majnemerdad0a642014-06-27 18:19:56 +0000613 std::vector<Comdat *>().swap(ComdatList);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000614
Bill Wendlinge94d8432012-12-07 23:16:57 +0000615 std::vector<AttributeSet>().swap(MAttributes);
Chris Lattner9eeada92007-05-18 04:02:46 +0000616 std::vector<BasicBlock*>().swap(FunctionBBs);
617 std::vector<Function*>().swap(FunctionsWithBodies);
618 DeferredFunctionInfo.clear();
Manman Ren4a9b0eb2015-03-13 19:24:30 +0000619 DeferredMetadataInfo.clear();
Dan Gohman43aa8f02010-07-20 21:42:28 +0000620 MDKindMap.clear();
Benjamin Kramer736a4fc2012-09-21 14:34:31 +0000621
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +0000622 assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +0000623 BasicBlockFwdRefQueue.clear();
Chris Lattner6694f602007-04-29 07:54:31 +0000624}
625
Chris Lattnerfee5a372007-05-04 03:30:17 +0000626//===----------------------------------------------------------------------===//
627// Helper functions to implement forward reference resolution, etc.
628//===----------------------------------------------------------------------===//
Chris Lattner6694f602007-04-29 07:54:31 +0000629
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000630/// Convert a string from a record into an std::string, return true on failure.
631template <typename StrTy>
632static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
Chris Lattnerccaa4482007-04-23 21:26:05 +0000633 StrTy &Result) {
Chris Lattnere14cb882007-05-04 19:11:41 +0000634 if (Idx > Record.size())
Chris Lattner1314b992007-04-22 06:23:29 +0000635 return true;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000636
Chris Lattnere14cb882007-05-04 19:11:41 +0000637 for (unsigned i = Idx, e = Record.size(); i != e; ++i)
638 Result += (char)Record[i];
Chris Lattner1314b992007-04-22 06:23:29 +0000639 return false;
640}
641
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000642static bool hasImplicitComdat(size_t Val) {
643 switch (Val) {
644 default:
645 return false;
646 case 1: // Old WeakAnyLinkage
647 case 4: // Old LinkOnceAnyLinkage
648 case 10: // Old WeakODRLinkage
649 case 11: // Old LinkOnceODRLinkage
650 return true;
651 }
652}
653
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000654static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000655 switch (Val) {
656 default: // Map unknown/new linkages to external
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000657 case 0:
658 return GlobalValue::ExternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000659 case 2:
660 return GlobalValue::AppendingLinkage;
661 case 3:
662 return GlobalValue::InternalLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000663 case 5:
664 return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
665 case 6:
666 return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
667 case 7:
668 return GlobalValue::ExternalWeakLinkage;
669 case 8:
670 return GlobalValue::CommonLinkage;
671 case 9:
672 return GlobalValue::PrivateLinkage;
Rafael Espindola7b4b2dc2015-01-08 15:36:32 +0000673 case 12:
674 return GlobalValue::AvailableExternallyLinkage;
Rafael Espindola2fb5bc32014-03-13 23:18:37 +0000675 case 13:
676 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
677 case 14:
678 return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
Rafael Espindolabec6af62015-01-08 15:39:50 +0000679 case 15:
680 return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000681 case 1: // Old value with implicit comdat.
682 case 16:
683 return GlobalValue::WeakAnyLinkage;
684 case 10: // Old value with implicit comdat.
685 case 17:
686 return GlobalValue::WeakODRLinkage;
687 case 4: // Old value with implicit comdat.
688 case 18:
689 return GlobalValue::LinkOnceAnyLinkage;
690 case 11: // Old value with implicit comdat.
691 case 19:
692 return GlobalValue::LinkOnceODRLinkage;
Chris Lattner1314b992007-04-22 06:23:29 +0000693 }
694}
695
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000696static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
Chris Lattner1314b992007-04-22 06:23:29 +0000697 switch (Val) {
698 default: // Map unknown visibilities to default.
699 case 0: return GlobalValue::DefaultVisibility;
700 case 1: return GlobalValue::HiddenVisibility;
Anton Korobeynikov31fc4f92007-04-29 20:56:48 +0000701 case 2: return GlobalValue::ProtectedVisibility;
Chris Lattner1314b992007-04-22 06:23:29 +0000702 }
703}
704
Nico Rieck7157bb72014-01-14 15:22:47 +0000705static GlobalValue::DLLStorageClassTypes
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000706getDecodedDLLStorageClass(unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000707 switch (Val) {
708 default: // Map unknown values to default.
709 case 0: return GlobalValue::DefaultStorageClass;
710 case 1: return GlobalValue::DLLImportStorageClass;
711 case 2: return GlobalValue::DLLExportStorageClass;
712 }
713}
714
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000715static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
Hans Wennborgcbe34b42012-06-23 11:37:03 +0000716 switch (Val) {
717 case 0: return GlobalVariable::NotThreadLocal;
718 default: // Map unknown non-zero value to general dynamic.
719 case 1: return GlobalVariable::GeneralDynamicTLSModel;
720 case 2: return GlobalVariable::LocalDynamicTLSModel;
721 case 3: return GlobalVariable::InitialExecTLSModel;
722 case 4: return GlobalVariable::LocalExecTLSModel;
723 }
724}
725
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000726static int getDecodedCastOpcode(unsigned Val) {
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000727 switch (Val) {
728 default: return -1;
729 case bitc::CAST_TRUNC : return Instruction::Trunc;
730 case bitc::CAST_ZEXT : return Instruction::ZExt;
731 case bitc::CAST_SEXT : return Instruction::SExt;
732 case bitc::CAST_FPTOUI : return Instruction::FPToUI;
733 case bitc::CAST_FPTOSI : return Instruction::FPToSI;
734 case bitc::CAST_UITOFP : return Instruction::UIToFP;
735 case bitc::CAST_SITOFP : return Instruction::SIToFP;
736 case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
737 case bitc::CAST_FPEXT : return Instruction::FPExt;
738 case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
739 case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
740 case bitc::CAST_BITCAST : return Instruction::BitCast;
Matt Arsenault3aa9b032013-11-18 02:51:33 +0000741 case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000742 }
743}
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000744
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000745static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000746 bool IsFP = Ty->isFPOrFPVectorTy();
747 // BinOps are only valid for int/fp or vector of int/fp types
748 if (!IsFP && !Ty->isIntOrIntVectorTy())
749 return -1;
750
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000751 switch (Val) {
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000752 default:
753 return -1;
Dan Gohmana5b96452009-06-04 22:49:04 +0000754 case bitc::BINOP_ADD:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000755 return IsFP ? Instruction::FAdd : Instruction::Add;
Dan Gohmana5b96452009-06-04 22:49:04 +0000756 case bitc::BINOP_SUB:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000757 return IsFP ? Instruction::FSub : Instruction::Sub;
Dan Gohmana5b96452009-06-04 22:49:04 +0000758 case bitc::BINOP_MUL:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000759 return IsFP ? Instruction::FMul : Instruction::Mul;
760 case bitc::BINOP_UDIV:
761 return IsFP ? -1 : Instruction::UDiv;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000762 case bitc::BINOP_SDIV:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000763 return IsFP ? Instruction::FDiv : Instruction::SDiv;
764 case bitc::BINOP_UREM:
765 return IsFP ? -1 : Instruction::URem;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000766 case bitc::BINOP_SREM:
Filipe Cabecinhasea79c5b2015-04-22 09:06:21 +0000767 return IsFP ? Instruction::FRem : Instruction::SRem;
768 case bitc::BINOP_SHL:
769 return IsFP ? -1 : Instruction::Shl;
770 case bitc::BINOP_LSHR:
771 return IsFP ? -1 : Instruction::LShr;
772 case bitc::BINOP_ASHR:
773 return IsFP ? -1 : Instruction::AShr;
774 case bitc::BINOP_AND:
775 return IsFP ? -1 : Instruction::And;
776 case bitc::BINOP_OR:
777 return IsFP ? -1 : Instruction::Or;
778 case bitc::BINOP_XOR:
779 return IsFP ? -1 : Instruction::Xor;
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000780 }
781}
782
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000783static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
Eli Friedmanc9a551e2011-07-28 21:48:00 +0000784 switch (Val) {
785 default: return AtomicRMWInst::BAD_BINOP;
786 case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
787 case bitc::RMW_ADD: return AtomicRMWInst::Add;
788 case bitc::RMW_SUB: return AtomicRMWInst::Sub;
789 case bitc::RMW_AND: return AtomicRMWInst::And;
790 case bitc::RMW_NAND: return AtomicRMWInst::Nand;
791 case bitc::RMW_OR: return AtomicRMWInst::Or;
792 case bitc::RMW_XOR: return AtomicRMWInst::Xor;
793 case bitc::RMW_MAX: return AtomicRMWInst::Max;
794 case bitc::RMW_MIN: return AtomicRMWInst::Min;
795 case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
796 case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
797 }
798}
799
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000800static AtomicOrdering getDecodedOrdering(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000801 switch (Val) {
802 case bitc::ORDERING_NOTATOMIC: return NotAtomic;
803 case bitc::ORDERING_UNORDERED: return Unordered;
804 case bitc::ORDERING_MONOTONIC: return Monotonic;
805 case bitc::ORDERING_ACQUIRE: return Acquire;
806 case bitc::ORDERING_RELEASE: return Release;
807 case bitc::ORDERING_ACQREL: return AcquireRelease;
808 default: // Map unknown orderings to sequentially-consistent.
809 case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
810 }
811}
812
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000813static SynchronizationScope getDecodedSynchScope(unsigned Val) {
Eli Friedmanfee02c62011-07-25 23:16:38 +0000814 switch (Val) {
815 case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
816 default: // Map unknown scopes to cross-thread.
817 case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
818 }
819}
820
David Majnemerdad0a642014-06-27 18:19:56 +0000821static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
822 switch (Val) {
823 default: // Map unknown selection kinds to any.
824 case bitc::COMDAT_SELECTION_KIND_ANY:
825 return Comdat::Any;
826 case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
827 return Comdat::ExactMatch;
828 case bitc::COMDAT_SELECTION_KIND_LARGEST:
829 return Comdat::Largest;
830 case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
831 return Comdat::NoDuplicates;
832 case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
833 return Comdat::SameSize;
834 }
835}
836
James Molloy88eb5352015-07-10 12:52:00 +0000837static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
838 FastMathFlags FMF;
839 if (0 != (Val & FastMathFlags::UnsafeAlgebra))
840 FMF.setUnsafeAlgebra();
841 if (0 != (Val & FastMathFlags::NoNaNs))
842 FMF.setNoNaNs();
843 if (0 != (Val & FastMathFlags::NoInfs))
844 FMF.setNoInfs();
845 if (0 != (Val & FastMathFlags::NoSignedZeros))
846 FMF.setNoSignedZeros();
847 if (0 != (Val & FastMathFlags::AllowReciprocal))
848 FMF.setAllowReciprocal();
849 return FMF;
850}
851
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000852static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
Nico Rieck7157bb72014-01-14 15:22:47 +0000853 switch (Val) {
854 case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
855 case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
856 }
857}
858
Gabor Greiff6caff662008-05-10 08:32:32 +0000859namespace llvm {
Chris Lattner1663cca2007-04-24 05:48:56 +0000860namespace {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000861/// \brief A class for maintaining the slot number definition
862/// as a placeholder for the actual definition for forward constants defs.
863class ConstantPlaceHolder : public ConstantExpr {
864 void operator=(const ConstantPlaceHolder &) = delete;
865
866public:
867 // allocate space for exactly one operand
868 void *operator new(size_t s) { return User::operator new(s, 1); }
869 explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
Gabor Greiff6caff662008-05-10 08:32:32 +0000870 : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000871 Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
872 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000873
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000874 /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
875 static bool classof(const Value *V) {
876 return isa<ConstantExpr>(V) &&
877 cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
878 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000879
Rafael Espindola64a27fb2015-06-15 21:04:27 +0000880 /// Provide fast operand accessors
881 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
882};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000883} // end anonymous namespace
Chris Lattner1663cca2007-04-24 05:48:56 +0000884
Chris Lattner2d8cd802009-03-31 22:55:09 +0000885// FIXME: can we inherit this from ConstantExpr?
Gabor Greiff6caff662008-05-10 08:32:32 +0000886template <>
Jay Foadc8adf5f2011-01-11 15:07:38 +0000887struct OperandTraits<ConstantPlaceHolder> :
888 public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
Gabor Greiff6caff662008-05-10 08:32:32 +0000889};
Richard Trieue3d126c2014-11-21 02:42:08 +0000890DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
Eugene Zelenko6ac3f732016-01-26 18:48:36 +0000891} // end namespace llvm
Gabor Greiff6caff662008-05-10 08:32:32 +0000892
David Majnemer8a1c45d2015-12-12 05:38:55 +0000893void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000894 if (Idx == size()) {
895 push_back(V);
David Majnemer8a1c45d2015-12-12 05:38:55 +0000896 return;
Chris Lattner2d8cd802009-03-31 22:55:09 +0000897 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000898
Chris Lattner2d8cd802009-03-31 22:55:09 +0000899 if (Idx >= size())
900 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000901
Chris Lattner2d8cd802009-03-31 22:55:09 +0000902 WeakVH &OldV = ValuePtrs[Idx];
Craig Topper2617dcc2014-04-15 06:32:26 +0000903 if (!OldV) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000904 OldV = 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 // Handle constants and non-constants (e.g. instrs) differently for
909 // efficiency.
910 if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
911 ResolveConstants.push_back(std::make_pair(PHC, Idx));
912 OldV = V;
913 } else {
914 // If there was a forward reference to this value, replace it.
915 Value *PrevVal = OldV;
916 OldV->replaceAllUsesWith(V);
917 delete PrevVal;
Gabor Greiff6caff662008-05-10 08:32:32 +0000918 }
919}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000920
Chris Lattner1663cca2007-04-24 05:48:56 +0000921Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
Chris Lattner229907c2011-07-18 04:54:35 +0000922 Type *Ty) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000923 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000924 resize(Idx + 1);
Chris Lattner1663cca2007-04-24 05:48:56 +0000925
Chris Lattner2d8cd802009-03-31 22:55:09 +0000926 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhas6a92a3f2015-05-27 01:05:40 +0000927 if (Ty != V->getType())
928 report_fatal_error("Type mismatch in constant table!");
Chris Lattner83930552007-05-01 07:01:57 +0000929 return cast<Constant>(V);
Chris Lattner1e16bcf72007-04-24 07:07:11 +0000930 }
Chris Lattner1663cca2007-04-24 05:48:56 +0000931
932 // Create and return a placeholder, which will later be RAUW'd.
Owen Andersone9f98042009-07-07 20:18:58 +0000933 Constant *C = new ConstantPlaceHolder(Ty, Context);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000934 ValuePtrs[Idx] = C;
Chris Lattner1663cca2007-04-24 05:48:56 +0000935 return C;
936}
937
David Majnemer8a1c45d2015-12-12 05:38:55 +0000938Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
Filipe Cabecinhasbad07792015-04-30 00:52:42 +0000939 // Bail out for a clearly invalid value. This would make us call resize(0)
940 if (Idx == UINT_MAX)
941 return nullptr;
942
Chris Lattner2d8cd802009-03-31 22:55:09 +0000943 if (Idx >= size())
Gabor Greiff6caff662008-05-10 08:32:32 +0000944 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000945
Chris Lattner2d8cd802009-03-31 22:55:09 +0000946 if (Value *V = ValuePtrs[Idx]) {
Filipe Cabecinhasb435d0f2015-04-28 20:18:47 +0000947 // If the types don't match, it's invalid.
948 if (Ty && Ty != V->getType())
949 return nullptr;
David Majnemer8a1c45d2015-12-12 05:38:55 +0000950 return V;
Chris Lattner83930552007-05-01 07:01:57 +0000951 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000952
Chris Lattner1fc27f02007-05-02 05:16:49 +0000953 // No type specified, must be invalid reference.
Craig Topper2617dcc2014-04-15 06:32:26 +0000954 if (!Ty) return nullptr;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000955
Chris Lattner83930552007-05-01 07:01:57 +0000956 // Create and return a placeholder, which will later be RAUW'd.
David Majnemer8a1c45d2015-12-12 05:38:55 +0000957 Value *V = new Argument(Ty);
Chris Lattner2d8cd802009-03-31 22:55:09 +0000958 ValuePtrs[Idx] = V;
Chris Lattner83930552007-05-01 07:01:57 +0000959 return V;
960}
961
Rafael Espindolacbdcb502015-06-15 20:55:37 +0000962/// Once all constants are read, this method bulk resolves any forward
963/// references. The idea behind this is that we sometimes get constants (such
964/// as large arrays) which reference *many* forward ref constants. Replacing
965/// each of these causes a lot of thrashing when building/reuniquing the
966/// constant. Instead of doing this, we look at all the uses and rewrite all
967/// the place holders at once for any constant that uses a placeholder.
968void BitcodeReaderValueList::resolveConstantForwardRefs() {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000969 // Sort the values by-pointer so that they are efficient to look up with a
Chris Lattner74429932008-08-21 02:34:16 +0000970 // binary search.
971 std::sort(ResolveConstants.begin(), ResolveConstants.end());
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000972
Chris Lattner74429932008-08-21 02:34:16 +0000973 SmallVector<Constant*, 64> NewOps;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000974
Chris Lattner74429932008-08-21 02:34:16 +0000975 while (!ResolveConstants.empty()) {
Chris Lattner2d8cd802009-03-31 22:55:09 +0000976 Value *RealVal = operator[](ResolveConstants.back().second);
Chris Lattner74429932008-08-21 02:34:16 +0000977 Constant *Placeholder = ResolveConstants.back().first;
978 ResolveConstants.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000979
Chris Lattner74429932008-08-21 02:34:16 +0000980 // Loop over all users of the placeholder, updating them to reference the
981 // new value. If they reference more than one placeholder, update them all
982 // at once.
983 while (!Placeholder->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000984 auto UI = Placeholder->user_begin();
Gabor Greif2c0ab482010-07-09 16:01:21 +0000985 User *U = *UI;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000986
Chris Lattner74429932008-08-21 02:34:16 +0000987 // If the using object isn't uniqued, just update the operands. This
988 // handles instructions and initializers for global variables.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000989 if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
Chris Lattner479c5d92008-08-21 17:31:45 +0000990 UI.getUse().set(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +0000991 continue;
992 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +0000993
Chris Lattner74429932008-08-21 02:34:16 +0000994 // Otherwise, we have a constant that uses the placeholder. Replace that
995 // constant with a new constant that has *all* placeholder uses updated.
Gabor Greif2c0ab482010-07-09 16:01:21 +0000996 Constant *UserC = cast<Constant>(U);
Chris Lattner74429932008-08-21 02:34:16 +0000997 for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
998 I != E; ++I) {
999 Value *NewOp;
1000 if (!isa<ConstantPlaceHolder>(*I)) {
1001 // Not a placeholder reference.
1002 NewOp = *I;
1003 } else if (*I == Placeholder) {
1004 // Common case is that it just references this one placeholder.
1005 NewOp = RealVal;
1006 } else {
1007 // Otherwise, look up the placeholder in ResolveConstants.
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001008 ResolveConstantsTy::iterator It =
1009 std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
Chris Lattner74429932008-08-21 02:34:16 +00001010 std::pair<Constant*, unsigned>(cast<Constant>(*I),
1011 0));
1012 assert(It != ResolveConstants.end() && It->first == *I);
Chris Lattner2d8cd802009-03-31 22:55:09 +00001013 NewOp = operator[](It->second);
Chris Lattner74429932008-08-21 02:34:16 +00001014 }
1015
1016 NewOps.push_back(cast<Constant>(NewOp));
1017 }
1018
1019 // Make the new constant.
1020 Constant *NewC;
1021 if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
Jay Foad83be3612011-06-22 09:24:39 +00001022 NewC = ConstantArray::get(UserCA->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001023 } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
Chris Lattnercc19efa2011-06-20 04:01:31 +00001024 NewC = ConstantStruct::get(UserCS->getType(), NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001025 } else if (isa<ConstantVector>(UserC)) {
Chris Lattner69229312011-02-15 00:14:00 +00001026 NewC = ConstantVector::get(NewOps);
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001027 } else {
1028 assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
Jay Foad5c984e562011-04-13 13:46:01 +00001029 NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
Chris Lattner74429932008-08-21 02:34:16 +00001030 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001031
Chris Lattner74429932008-08-21 02:34:16 +00001032 UserC->replaceAllUsesWith(NewC);
1033 UserC->destroyConstant();
1034 NewOps.clear();
1035 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001036
Nick Lewyckyb8f9b7a2009-05-10 20:57:05 +00001037 // Update all ValueHandles, they should be the only users at this point.
1038 Placeholder->replaceAllUsesWith(RealVal);
Chris Lattner74429932008-08-21 02:34:16 +00001039 delete Placeholder;
1040 }
1041}
1042
Teresa Johnson61b406e2015-12-29 23:00:22 +00001043void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001044 if (Idx == size()) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001045 push_back(MD);
Devang Patel05eb6172009-08-04 06:00:18 +00001046 return;
1047 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001048
Devang Patel05eb6172009-08-04 06:00:18 +00001049 if (Idx >= size())
1050 resize(Idx+1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001051
Teresa Johnson61b406e2015-12-29 23:00:22 +00001052 TrackingMDRef &OldMD = MetadataPtrs[Idx];
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001053 if (!OldMD) {
1054 OldMD.reset(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 there was a forward reference to this value, replace it.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001059 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001060 PrevMD->replaceAllUsesWith(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001061 --NumFwdRefs;
Devang Patel05eb6172009-08-04 06:00:18 +00001062}
1063
Justin Bognerae341c62016-03-17 20:12:06 +00001064Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
Devang Patel05eb6172009-08-04 06:00:18 +00001065 if (Idx >= size())
1066 resize(Idx + 1);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001067
Teresa Johnson61b406e2015-12-29 23:00:22 +00001068 if (Metadata *MD = MetadataPtrs[Idx])
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001069 return MD;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001070
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001071 // Track forward refs to be resolved later.
1072 if (AnyFwdRefs) {
1073 MinFwdRef = std::min(MinFwdRef, Idx);
1074 MaxFwdRef = std::max(MaxFwdRef, Idx);
1075 } else {
1076 AnyFwdRefs = true;
1077 MinFwdRef = MaxFwdRef = Idx;
1078 }
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001079 ++NumFwdRefs;
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001080
1081 // Create and return a placeholder, which will later be RAUW'd.
Duncan P. N. Exon Smith7d823132015-01-19 21:30:18 +00001082 Metadata *MD = MDNode::getTemporary(Context, None).release();
Teresa Johnson61b406e2015-12-29 23:00:22 +00001083 MetadataPtrs[Idx].reset(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001084 return MD;
1085}
1086
Justin Bognerae341c62016-03-17 20:12:06 +00001087MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
1088 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
1089}
1090
Teresa Johnson61b406e2015-12-29 23:00:22 +00001091void BitcodeReaderMetadataList::tryToResolveCycles() {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001092 if (!AnyFwdRefs)
1093 // Nothing to do.
1094 return;
1095
1096 if (NumFwdRefs)
1097 // Still forward references... can't resolve cycles.
1098 return;
1099
1100 // Resolve any cycles.
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001101 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
Teresa Johnson61b406e2015-12-29 23:00:22 +00001102 auto &MD = MetadataPtrs[I];
Duncan P. N. Exon Smith2bc00f42015-01-19 23:13:14 +00001103 auto *N = dyn_cast_or_null<MDNode>(MD);
Duncan P. N. Exon Smith946fdcc2015-01-19 20:36:39 +00001104 if (!N)
1105 continue;
1106
1107 assert(!N->isTemporary() && "Unexpected forward reference");
1108 N->resolveCycles();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001109 }
Duncan P. N. Exon Smith060ee622015-02-16 19:18:01 +00001110
1111 // Make sure we return early again until there's another forward ref.
1112 AnyFwdRefs = false;
Devang Patel05eb6172009-08-04 06:00:18 +00001113}
Chris Lattner1314b992007-04-22 06:23:29 +00001114
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001115Type *BitcodeReader::getTypeByID(unsigned ID) {
1116 // The type table size is always specified correctly.
1117 if (ID >= TypeList.size())
Craig Topper2617dcc2014-04-15 06:32:26 +00001118 return nullptr;
Derek Schuff206dddd2012-02-06 19:03:04 +00001119
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001120 if (Type *Ty = TypeList[ID])
1121 return Ty;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001122
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001123 // If we have a forward reference, the only possible case is when it is to a
1124 // named struct. Just create a placeholder for now.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001125 return TypeList[ID] = createIdentifiedStructType(Context);
1126}
1127
1128StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
1129 StringRef Name) {
1130 auto *Ret = StructType::create(Context, Name);
1131 IdentifiedStructTypes.push_back(Ret);
1132 return Ret;
1133}
1134
1135StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
1136 auto *Ret = StructType::create(Context);
1137 IdentifiedStructTypes.push_back(Ret);
1138 return Ret;
Chris Lattner1314b992007-04-22 06:23:29 +00001139}
1140
Chris Lattnerfee5a372007-05-04 03:30:17 +00001141//===----------------------------------------------------------------------===//
1142// Functions for parsing blocks from the bitcode file
1143//===----------------------------------------------------------------------===//
1144
Bill Wendling56aeccc2013-02-04 23:32:23 +00001145
1146/// \brief This fills an AttrBuilder object with the LLVM attributes that have
1147/// been decoded from the given integer. This function must stay in sync with
1148/// 'encodeLLVMAttributesForBitcode'.
1149static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
1150 uint64_t EncodedAttrs) {
1151 // FIXME: Remove in 4.0.
1152
1153 // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
1154 // the bits above 31 down by 11 bits.
1155 unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
1156 assert((!Alignment || isPowerOf2_32(Alignment)) &&
1157 "Alignment must be a power of two.");
1158
1159 if (Alignment)
1160 B.addAlignmentAttr(Alignment);
Kostya Serebryanyd688bab2013-02-11 08:13:54 +00001161 B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
Bill Wendling56aeccc2013-02-04 23:32:23 +00001162 (EncodedAttrs & 0xffff));
1163}
1164
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001165std::error_code BitcodeReader::parseAttributeBlock() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00001166 if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001167 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001168
Devang Patela05633e2008-09-26 22:53:05 +00001169 if (!MAttributes.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001170 return error("Invalid multiple blocks");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001171
Chris Lattnerfee5a372007-05-04 03:30:17 +00001172 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001173
Bill Wendling71173cb2013-01-27 00:36:48 +00001174 SmallVector<AttributeSet, 8> Attrs;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001175
Chris Lattnerfee5a372007-05-04 03:30:17 +00001176 // Read all the records.
1177 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001178 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001179
Chris Lattner27d38752013-01-20 02:13:19 +00001180 switch (Entry.Kind) {
1181 case BitstreamEntry::SubBlock: // Handled for us already.
1182 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001183 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001184 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001185 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001186 case BitstreamEntry::Record:
1187 // The interesting case.
1188 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00001189 }
Joe Abbey97b7a172013-02-06 22:14:06 +00001190
Chris Lattnerfee5a372007-05-04 03:30:17 +00001191 // Read a record.
1192 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001193 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerfee5a372007-05-04 03:30:17 +00001194 default: // Default behavior: ignore.
1195 break;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001196 case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
1197 // FIXME: Remove in 4.0.
Chris Lattnerfee5a372007-05-04 03:30:17 +00001198 if (Record.size() & 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001199 return error("Invalid record");
Chris Lattnerfee5a372007-05-04 03:30:17 +00001200
Chris Lattnerfee5a372007-05-04 03:30:17 +00001201 for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
Bill Wendling60011b82013-01-29 01:43:29 +00001202 AttrBuilder B;
Bill Wendling56aeccc2013-02-04 23:32:23 +00001203 decodeLLVMAttributesForBitcode(B, Record[i+1]);
Bill Wendling60011b82013-01-29 01:43:29 +00001204 Attrs.push_back(AttributeSet::get(Context, Record[i], B));
Devang Patela05633e2008-09-26 22:53:05 +00001205 }
Devang Patela05633e2008-09-26 22:53:05 +00001206
Bill Wendlinge94d8432012-12-07 23:16:57 +00001207 MAttributes.push_back(AttributeSet::get(Context, Attrs));
Chris Lattnerfee5a372007-05-04 03:30:17 +00001208 Attrs.clear();
1209 break;
1210 }
Bill Wendling0dc08912013-02-12 08:13:50 +00001211 case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
1212 for (unsigned i = 0, e = Record.size(); i != e; ++i)
1213 Attrs.push_back(MAttributeGroups[Record[i]]);
1214
1215 MAttributes.push_back(AttributeSet::get(Context, Attrs));
1216 Attrs.clear();
1217 break;
1218 }
Duncan Sands04eb67e2007-11-20 14:09:29 +00001219 }
Chris Lattnerfee5a372007-05-04 03:30:17 +00001220 }
1221}
1222
Reid Klecknere9f36af2013-11-12 01:31:00 +00001223// Returns Attribute::None on unrecognized codes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001224static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
Reid Klecknere9f36af2013-11-12 01:31:00 +00001225 switch (Code) {
1226 default:
1227 return Attribute::None;
1228 case bitc::ATTR_KIND_ALIGNMENT:
1229 return Attribute::Alignment;
1230 case bitc::ATTR_KIND_ALWAYS_INLINE:
1231 return Attribute::AlwaysInline;
Igor Laevsky39d662f2015-07-11 10:30:36 +00001232 case bitc::ATTR_KIND_ARGMEMONLY:
1233 return Attribute::ArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001234 case bitc::ATTR_KIND_BUILTIN:
1235 return Attribute::Builtin;
1236 case bitc::ATTR_KIND_BY_VAL:
1237 return Attribute::ByVal;
Reid Klecknera534a382013-12-19 02:14:12 +00001238 case bitc::ATTR_KIND_IN_ALLOCA:
1239 return Attribute::InAlloca;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001240 case bitc::ATTR_KIND_COLD:
1241 return Attribute::Cold;
Owen Anderson85fa7d52015-05-26 23:48:40 +00001242 case bitc::ATTR_KIND_CONVERGENT:
1243 return Attribute::Convergent;
Vaivaswatha Nagarajfb3f4902015-12-16 16:16:19 +00001244 case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
1245 return Attribute::InaccessibleMemOnly;
1246 case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
1247 return Attribute::InaccessibleMemOrArgMemOnly;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001248 case bitc::ATTR_KIND_INLINE_HINT:
1249 return Attribute::InlineHint;
1250 case bitc::ATTR_KIND_IN_REG:
1251 return Attribute::InReg;
Tom Roeder44cb65f2014-06-05 19:29:43 +00001252 case bitc::ATTR_KIND_JUMP_TABLE:
1253 return Attribute::JumpTable;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001254 case bitc::ATTR_KIND_MIN_SIZE:
1255 return Attribute::MinSize;
1256 case bitc::ATTR_KIND_NAKED:
1257 return Attribute::Naked;
1258 case bitc::ATTR_KIND_NEST:
1259 return Attribute::Nest;
1260 case bitc::ATTR_KIND_NO_ALIAS:
1261 return Attribute::NoAlias;
1262 case bitc::ATTR_KIND_NO_BUILTIN:
1263 return Attribute::NoBuiltin;
1264 case bitc::ATTR_KIND_NO_CAPTURE:
1265 return Attribute::NoCapture;
1266 case bitc::ATTR_KIND_NO_DUPLICATE:
1267 return Attribute::NoDuplicate;
1268 case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
1269 return Attribute::NoImplicitFloat;
1270 case bitc::ATTR_KIND_NO_INLINE:
1271 return Attribute::NoInline;
James Molloye6f87ca2015-11-06 10:32:53 +00001272 case bitc::ATTR_KIND_NO_RECURSE:
1273 return Attribute::NoRecurse;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001274 case bitc::ATTR_KIND_NON_LAZY_BIND:
1275 return Attribute::NonLazyBind;
Nick Lewyckyd52b1522014-05-20 01:23:40 +00001276 case bitc::ATTR_KIND_NON_NULL:
1277 return Attribute::NonNull;
Hal Finkelb0407ba2014-07-18 15:51:28 +00001278 case bitc::ATTR_KIND_DEREFERENCEABLE:
1279 return Attribute::Dereferenceable;
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001280 case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
1281 return Attribute::DereferenceableOrNull;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001282 case bitc::ATTR_KIND_NO_RED_ZONE:
1283 return Attribute::NoRedZone;
1284 case bitc::ATTR_KIND_NO_RETURN:
1285 return Attribute::NoReturn;
1286 case bitc::ATTR_KIND_NO_UNWIND:
1287 return Attribute::NoUnwind;
1288 case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
1289 return Attribute::OptimizeForSize;
1290 case bitc::ATTR_KIND_OPTIMIZE_NONE:
1291 return Attribute::OptimizeNone;
1292 case bitc::ATTR_KIND_READ_NONE:
1293 return Attribute::ReadNone;
1294 case bitc::ATTR_KIND_READ_ONLY:
1295 return Attribute::ReadOnly;
1296 case bitc::ATTR_KIND_RETURNED:
1297 return Attribute::Returned;
1298 case bitc::ATTR_KIND_RETURNS_TWICE:
1299 return Attribute::ReturnsTwice;
1300 case bitc::ATTR_KIND_S_EXT:
1301 return Attribute::SExt;
1302 case bitc::ATTR_KIND_STACK_ALIGNMENT:
1303 return Attribute::StackAlignment;
1304 case bitc::ATTR_KIND_STACK_PROTECT:
1305 return Attribute::StackProtect;
1306 case bitc::ATTR_KIND_STACK_PROTECT_REQ:
1307 return Attribute::StackProtectReq;
1308 case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
1309 return Attribute::StackProtectStrong;
Peter Collingbourne82437bf2015-06-15 21:07:11 +00001310 case bitc::ATTR_KIND_SAFESTACK:
1311 return Attribute::SafeStack;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001312 case bitc::ATTR_KIND_STRUCT_RET:
1313 return Attribute::StructRet;
1314 case bitc::ATTR_KIND_SANITIZE_ADDRESS:
1315 return Attribute::SanitizeAddress;
1316 case bitc::ATTR_KIND_SANITIZE_THREAD:
1317 return Attribute::SanitizeThread;
1318 case bitc::ATTR_KIND_SANITIZE_MEMORY:
1319 return Attribute::SanitizeMemory;
Manman Renf46262e2016-03-29 17:37:21 +00001320 case bitc::ATTR_KIND_SWIFT_SELF:
1321 return Attribute::SwiftSelf;
Reid Klecknere9f36af2013-11-12 01:31:00 +00001322 case bitc::ATTR_KIND_UW_TABLE:
1323 return Attribute::UWTable;
1324 case bitc::ATTR_KIND_Z_EXT:
1325 return Attribute::ZExt;
1326 }
1327}
1328
JF Bastien30bf96b2015-02-22 19:32:03 +00001329std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
1330 unsigned &Alignment) {
1331 // Note: Alignment in bitcode files is incremented by 1, so that zero
1332 // can be used for default alignment.
1333 if (Exponent > Value::MaxAlignmentExponent + 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001334 return error("Invalid alignment value");
JF Bastien30bf96b2015-02-22 19:32:03 +00001335 Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
1336 return std::error_code();
1337}
1338
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001339std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001340 Attribute::AttrKind *Kind) {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001341 *Kind = getAttrFromCode(Code);
Reid Klecknere9f36af2013-11-12 01:31:00 +00001342 if (*Kind == Attribute::None)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001343 return error(BitcodeError::CorruptedBitcode,
Rafael Espindolad0b23be2015-01-10 00:07:30 +00001344 "Unknown attribute kind (" + Twine(Code) + ")");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001345 return std::error_code();
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001346}
1347
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001348std::error_code BitcodeReader::parseAttributeGroupBlock() {
Bill Wendlingba629332013-02-10 23:24:25 +00001349 if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001350 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001351
1352 if (!MAttributeGroups.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001353 return error("Invalid multiple blocks");
Bill Wendlingba629332013-02-10 23:24:25 +00001354
1355 SmallVector<uint64_t, 64> Record;
1356
1357 // Read all the records.
1358 while (1) {
1359 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1360
1361 switch (Entry.Kind) {
1362 case BitstreamEntry::SubBlock: // Handled for us already.
1363 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001364 return error("Malformed block");
Bill Wendlingba629332013-02-10 23:24:25 +00001365 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001366 return std::error_code();
Bill Wendlingba629332013-02-10 23:24:25 +00001367 case BitstreamEntry::Record:
1368 // The interesting case.
1369 break;
1370 }
1371
1372 // Read a record.
1373 Record.clear();
1374 switch (Stream.readRecord(Entry.ID, Record)) {
1375 default: // Default behavior: ignore.
1376 break;
1377 case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
1378 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001379 return error("Invalid record");
Bill Wendlingba629332013-02-10 23:24:25 +00001380
Bill Wendlinge46707e2013-02-11 22:32:29 +00001381 uint64_t GrpID = Record[0];
Bill Wendlingba629332013-02-10 23:24:25 +00001382 uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
1383
1384 AttrBuilder B;
1385 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
1386 if (Record[i] == 0) { // Enum attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001387 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001388 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001389 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001390
1391 B.addAttribute(Kind);
Hal Finkele15442c2014-07-18 06:51:55 +00001392 } else if (Record[i] == 1) { // Integer attribute
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001393 Attribute::AttrKind Kind;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001394 if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
Rafael Espindola48da4f42013-11-04 16:16:24 +00001395 return EC;
Tobias Grosser0a8e12f2013-07-26 04:16:55 +00001396 if (Kind == Attribute::Alignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001397 B.addAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001398 else if (Kind == Attribute::StackAlignment)
Bill Wendlingba629332013-02-10 23:24:25 +00001399 B.addStackAlignmentAttr(Record[++i]);
Hal Finkelb0407ba2014-07-18 15:51:28 +00001400 else if (Kind == Attribute::Dereferenceable)
1401 B.addDereferenceableAttr(Record[++i]);
Sanjoy Das31ea6d12015-04-16 20:29:50 +00001402 else if (Kind == Attribute::DereferenceableOrNull)
1403 B.addDereferenceableOrNullAttr(Record[++i]);
Bill Wendlingba629332013-02-10 23:24:25 +00001404 } else { // String attribute
Bill Wendlinge46707e2013-02-11 22:32:29 +00001405 assert((Record[i] == 3 || Record[i] == 4) &&
1406 "Invalid attribute group entry");
Bill Wendlingba629332013-02-10 23:24:25 +00001407 bool HasValue = (Record[i++] == 4);
1408 SmallString<64> KindStr;
1409 SmallString<64> ValStr;
1410
1411 while (Record[i] != 0 && i != e)
1412 KindStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001413 assert(Record[i] == 0 && "Kind string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001414
1415 if (HasValue) {
1416 // Has a value associated with it.
Bill Wendlinge46707e2013-02-11 22:32:29 +00001417 ++i; // Skip the '0' that terminates the "kind" string.
Bill Wendlingba629332013-02-10 23:24:25 +00001418 while (Record[i] != 0 && i != e)
1419 ValStr += Record[i++];
Bill Wendlinge46707e2013-02-11 22:32:29 +00001420 assert(Record[i] == 0 && "Value string not null terminated");
Bill Wendlingba629332013-02-10 23:24:25 +00001421 }
1422
1423 B.addAttribute(KindStr.str(), ValStr.str());
1424 }
1425 }
1426
Bill Wendlinge46707e2013-02-11 22:32:29 +00001427 MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
Bill Wendlingba629332013-02-10 23:24:25 +00001428 break;
1429 }
1430 }
1431 }
1432}
1433
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001434std::error_code BitcodeReader::parseTypeTable() {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001435 if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001436 return error("Invalid record");
Derek Schuff206dddd2012-02-06 19:03:04 +00001437
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001438 return parseTypeTableBody();
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001439}
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001440
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001441std::error_code BitcodeReader::parseTypeTableBody() {
Chris Lattner1314b992007-04-22 06:23:29 +00001442 if (!TypeList.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001443 return error("Invalid multiple blocks");
Chris Lattner1314b992007-04-22 06:23:29 +00001444
1445 SmallVector<uint64_t, 64> Record;
1446 unsigned NumRecords = 0;
1447
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001448 SmallString<64> TypeName;
Derek Schuff206dddd2012-02-06 19:03:04 +00001449
Chris Lattner1314b992007-04-22 06:23:29 +00001450 // Read all the records for this type table.
1451 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001452 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001453
Chris Lattner27d38752013-01-20 02:13:19 +00001454 switch (Entry.Kind) {
1455 case BitstreamEntry::SubBlock: // Handled for us already.
1456 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001457 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001458 case BitstreamEntry::EndBlock:
Chris Lattner1314b992007-04-22 06:23:29 +00001459 if (NumRecords != TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001460 return error("Malformed block");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001461 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001462 case BitstreamEntry::Record:
1463 // The interesting case.
1464 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001465 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001466
Chris Lattner1314b992007-04-22 06:23:29 +00001467 // Read a record.
1468 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00001469 Type *ResultTy = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00001470 switch (Stream.readRecord(Entry.ID, Record)) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00001471 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001472 return error("Invalid value");
Chris Lattner1314b992007-04-22 06:23:29 +00001473 case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
1474 // TYPE_CODE_NUMENTRY contains a count of the number of types in the
1475 // type list. This allows us to reserve space.
1476 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001477 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001478 TypeList.resize(Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001479 continue;
Chris Lattner1314b992007-04-22 06:23:29 +00001480 case bitc::TYPE_CODE_VOID: // VOID
Owen Anderson55f1c092009-08-13 21:58:54 +00001481 ResultTy = Type::getVoidTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001482 break;
Dan Gohman518cda42011-12-17 00:04:22 +00001483 case bitc::TYPE_CODE_HALF: // HALF
1484 ResultTy = Type::getHalfTy(Context);
1485 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001486 case bitc::TYPE_CODE_FLOAT: // FLOAT
Owen Anderson55f1c092009-08-13 21:58:54 +00001487 ResultTy = Type::getFloatTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001488 break;
1489 case bitc::TYPE_CODE_DOUBLE: // DOUBLE
Owen Anderson55f1c092009-08-13 21:58:54 +00001490 ResultTy = Type::getDoubleTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001491 break;
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001492 case bitc::TYPE_CODE_X86_FP80: // X86_FP80
Owen Anderson55f1c092009-08-13 21:58:54 +00001493 ResultTy = Type::getX86_FP80Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001494 break;
1495 case bitc::TYPE_CODE_FP128: // FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001496 ResultTy = Type::getFP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001497 break;
1498 case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
Owen Anderson55f1c092009-08-13 21:58:54 +00001499 ResultTy = Type::getPPC_FP128Ty(Context);
Dale Johannesenff4c3be2007-08-03 01:03:46 +00001500 break;
Chris Lattner1314b992007-04-22 06:23:29 +00001501 case bitc::TYPE_CODE_LABEL: // LABEL
Owen Anderson55f1c092009-08-13 21:58:54 +00001502 ResultTy = Type::getLabelTy(Context);
Chris Lattner1314b992007-04-22 06:23:29 +00001503 break;
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001504 case bitc::TYPE_CODE_METADATA: // METADATA
Owen Anderson55f1c092009-08-13 21:58:54 +00001505 ResultTy = Type::getMetadataTy(Context);
Nick Lewyckyadbc2842009-05-30 05:06:04 +00001506 break;
Dale Johannesenbaa5d042010-09-10 20:55:01 +00001507 case bitc::TYPE_CODE_X86_MMX: // X86_MMX
1508 ResultTy = Type::getX86_MMXTy(Context);
1509 break;
David Majnemerb611e3f2015-08-14 05:09:07 +00001510 case bitc::TYPE_CODE_TOKEN: // TOKEN
1511 ResultTy = Type::getTokenTy(Context);
1512 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001513 case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
Chris Lattner1314b992007-04-22 06:23:29 +00001514 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001515 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001516
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001517 uint64_t NumBits = Record[0];
1518 if (NumBits < IntegerType::MIN_INT_BITS ||
1519 NumBits > IntegerType::MAX_INT_BITS)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001520 return error("Bitwidth for integer type out of range");
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001521 ResultTy = IntegerType::get(Context, NumBits);
Chris Lattner1314b992007-04-22 06:23:29 +00001522 break;
Filipe Cabecinhasfcd044b2015-01-30 18:13:50 +00001523 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001524 case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001525 // [pointee type, address space]
Chris Lattner1314b992007-04-22 06:23:29 +00001526 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001527 return error("Invalid record");
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001528 unsigned AddressSpace = 0;
1529 if (Record.size() == 2)
1530 AddressSpace = Record[1];
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001531 ResultTy = getTypeByID(Record[0]);
Filipe Cabecinhasd8a1bcd2015-04-29 02:27:28 +00001532 if (!ResultTy ||
1533 !PointerType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001534 return error("Invalid type");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001535 ResultTy = PointerType::get(ResultTy, AddressSpace);
Chris Lattner1314b992007-04-22 06:23:29 +00001536 break;
Christopher Lamb54dd24c2007-12-11 08:59:05 +00001537 }
Nuno Lopes561dae02012-05-23 15:19:39 +00001538 case bitc::TYPE_CODE_FUNCTION_OLD: {
1539 // FIXME: attrid is dead, remove it in LLVM 4.0
1540 // FUNCTION: [vararg, attrid, retty, paramty x N]
1541 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001542 return error("Invalid record");
Nuno Lopes561dae02012-05-23 15:19:39 +00001543 SmallVector<Type*, 8> ArgTys;
1544 for (unsigned i = 3, e = Record.size(); i != e; ++i) {
1545 if (Type *T = getTypeByID(Record[i]))
1546 ArgTys.push_back(T);
1547 else
1548 break;
1549 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001550
Nuno Lopes561dae02012-05-23 15:19:39 +00001551 ResultTy = getTypeByID(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001552 if (!ResultTy || ArgTys.size() < Record.size()-3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001553 return error("Invalid type");
Nuno Lopes561dae02012-05-23 15:19:39 +00001554
1555 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1556 break;
1557 }
Chad Rosier95898722011-11-03 00:14:01 +00001558 case bitc::TYPE_CODE_FUNCTION: {
1559 // FUNCTION: [vararg, retty, paramty x N]
1560 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001561 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001562 SmallVector<Type*, 8> ArgTys;
Chad Rosier95898722011-11-03 00:14:01 +00001563 for (unsigned i = 2, e = Record.size(); i != e; ++i) {
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001564 if (Type *T = getTypeByID(Record[i])) {
1565 if (!FunctionType::isValidArgumentType(T))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001566 return error("Invalid function argument type");
Chad Rosier95898722011-11-03 00:14:01 +00001567 ArgTys.push_back(T);
Filipe Cabecinhas32af5422015-05-19 01:21:06 +00001568 }
Chad Rosier95898722011-11-03 00:14:01 +00001569 else
1570 break;
1571 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001572
Chad Rosier95898722011-11-03 00:14:01 +00001573 ResultTy = getTypeByID(Record[1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001574 if (!ResultTy || ArgTys.size() < Record.size()-2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001575 return error("Invalid type");
Chad Rosier95898722011-11-03 00:14:01 +00001576
1577 ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
1578 break;
1579 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001580 case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
Chris Lattner3c5616e2007-05-06 08:21:50 +00001581 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001582 return error("Invalid record");
Chris Lattnercc3aaf12012-01-27 03:15:49 +00001583 SmallVector<Type*, 8> EltTys;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001584 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1585 if (Type *T = getTypeByID(Record[i]))
1586 EltTys.push_back(T);
1587 else
1588 break;
1589 }
1590 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001591 return error("Invalid type");
Owen Anderson03cb69f2009-08-05 23:16:16 +00001592 ResultTy = StructType::get(Context, EltTys, Record[0]);
Chris Lattner1314b992007-04-22 06:23:29 +00001593 break;
1594 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001595 case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001596 if (convertToString(Record, 0, TypeName))
1597 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001598 continue;
1599
1600 case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
1601 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001602 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001603
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001604 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001605 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001606
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001607 // Check to see if this was forward referenced, if so fill in the temp.
1608 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1609 if (Res) {
1610 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001611 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001612 } else // Otherwise, create a new struct.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001613 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001614 TypeName.clear();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001615
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001616 SmallVector<Type*, 8> EltTys;
1617 for (unsigned i = 1, e = Record.size(); i != e; ++i) {
1618 if (Type *T = getTypeByID(Record[i]))
1619 EltTys.push_back(T);
1620 else
1621 break;
1622 }
1623 if (EltTys.size() != Record.size()-1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001624 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001625 Res->setBody(EltTys, Record[0]);
1626 ResultTy = Res;
1627 break;
1628 }
1629 case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
1630 if (Record.size() != 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001631 return error("Invalid record");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001632
1633 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001634 return error("Invalid TYPE table");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001635
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001636 // Check to see if this was forward referenced, if so fill in the temp.
1637 StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
1638 if (Res) {
1639 Res->setName(TypeName);
Craig Topper2617dcc2014-04-15 06:32:26 +00001640 TypeList[NumRecords] = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001641 } else // Otherwise, create a new struct with no body.
Rafael Espindola2fa1e432014-12-03 07:18:23 +00001642 Res = createIdentifiedStructType(Context, TypeName);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001643 TypeName.clear();
1644 ResultTy = Res;
1645 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00001646 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001647 case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
1648 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001649 return error("Invalid record");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001650 ResultTy = getTypeByID(Record[1]);
1651 if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001652 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001653 ResultTy = ArrayType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001654 break;
1655 case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
1656 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001657 return error("Invalid record");
Filipe Cabecinhas8e421902015-06-03 00:05:30 +00001658 if (Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001659 return error("Invalid vector length");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001660 ResultTy = getTypeByID(Record[1]);
1661 if (!ResultTy || !StructType::isValidElementType(ResultTy))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001662 return error("Invalid type");
Filipe Cabecinhas6fe8aab2015-04-29 02:36:08 +00001663 ResultTy = VectorType::get(ResultTy, Record[0]);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001664 break;
1665 }
1666
1667 if (NumRecords >= TypeList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001668 return error("Invalid TYPE table");
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001669 if (TypeList[NumRecords])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001670 return error(
Filipe Cabecinhasd0858e12015-01-30 10:57:58 +00001671 "Invalid TYPE table: Only named structs can be forward referenced");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001672 assert(ResultTy && "Didn't read a type?");
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00001673 TypeList[NumRecords++] = ResultTy;
1674 }
1675}
1676
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00001677std::error_code BitcodeReader::parseOperandBundleTags() {
1678 if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
1679 return error("Invalid record");
1680
1681 if (!BundleTags.empty())
1682 return error("Invalid multiple blocks");
1683
1684 SmallVector<uint64_t, 64> Record;
1685
1686 while (1) {
1687 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1688
1689 switch (Entry.Kind) {
1690 case BitstreamEntry::SubBlock: // Handled for us already.
1691 case BitstreamEntry::Error:
1692 return error("Malformed block");
1693 case BitstreamEntry::EndBlock:
1694 return std::error_code();
1695 case BitstreamEntry::Record:
1696 // The interesting case.
1697 break;
1698 }
1699
1700 // Tags are implicitly mapped to integers by their order.
1701
1702 if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
1703 return error("Invalid record");
1704
1705 // OPERAND_BUNDLE_TAG: [strchr x N]
1706 BundleTags.emplace_back();
1707 if (convertToString(Record, 0, BundleTags.back()))
1708 return error("Invalid record");
1709 Record.clear();
1710 }
1711}
1712
Teresa Johnsonff642b92015-09-17 20:12:00 +00001713/// Associate a value with its name from the given index in the provided record.
1714ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
1715 unsigned NameIndex, Triple &TT) {
1716 SmallString<128> ValueName;
1717 if (convertToString(Record, NameIndex, ValueName))
1718 return error("Invalid record");
1719 unsigned ValueID = Record[0];
1720 if (ValueID >= ValueList.size() || !ValueList[ValueID])
1721 return error("Invalid record");
1722 Value *V = ValueList[ValueID];
1723
Filipe Cabecinhasa2b0ac42015-11-04 14:53:36 +00001724 StringRef NameStr(ValueName.data(), ValueName.size());
1725 if (NameStr.find_first_of(0) != StringRef::npos)
1726 return error("Invalid value name");
1727 V->setName(NameStr);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001728 auto *GO = dyn_cast<GlobalObject>(V);
1729 if (GO) {
1730 if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
1731 if (TT.isOSBinFormatMachO())
1732 GO->setComdat(nullptr);
1733 else
1734 GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
1735 }
1736 }
1737 return V;
1738}
1739
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001740/// Helper to note and return the current location, and jump to the given
1741/// offset.
1742static uint64_t jumpToValueSymbolTable(uint64_t Offset,
1743 BitstreamCursor &Stream) {
1744 // Save the current parsing location so we can jump back at the end
1745 // of the VST read.
1746 uint64_t CurrentBit = Stream.GetCurrentBitNo();
1747 Stream.JumpToBit(Offset * 32);
1748#ifndef NDEBUG
1749 // Do some checking if we are in debug mode.
1750 BitstreamEntry Entry = Stream.advance();
1751 assert(Entry.Kind == BitstreamEntry::SubBlock);
1752 assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
1753#else
1754 // In NDEBUG mode ignore the output so we don't get an unused variable
1755 // warning.
1756 Stream.advance();
1757#endif
1758 return CurrentBit;
1759}
1760
Teresa Johnsonff642b92015-09-17 20:12:00 +00001761/// Parse the value symbol table at either the current parsing location or
1762/// at the given bit offset if provided.
Peter Collingbourne128a9762015-10-27 23:01:25 +00001763std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00001764 uint64_t CurrentBit;
1765 // Pass in the Offset to distinguish between calling for the module-level
1766 // VST (where we want to jump to the VST offset) and the function-level
1767 // VST (where we don't).
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00001768 if (Offset > 0)
1769 CurrentBit = jumpToValueSymbolTable(Offset, Stream);
Teresa Johnsonff642b92015-09-17 20:12:00 +00001770
1771 // Compute the delta between the bitcode indices in the VST (the word offset
1772 // to the word-aligned ENTER_SUBBLOCK for the function block, and that
1773 // expected by the lazy reader. The reader's EnterSubBlock expects to have
1774 // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
1775 // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
1776 // just before entering the VST subblock because: 1) the EnterSubBlock
1777 // changes the AbbrevID width; 2) the VST block is nested within the same
1778 // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
1779 // AbbrevID width before calling EnterSubBlock; and 3) when we want to
1780 // jump to the FUNCTION_BLOCK using this offset later, we don't want
1781 // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
1782 unsigned FuncBitcodeOffsetDelta =
1783 Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
1784
Chris Lattner982ec1e2007-05-05 00:17:00 +00001785 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001786 return error("Invalid record");
Chris Lattnerccaa4482007-04-23 21:26:05 +00001787
1788 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001789
David Majnemer3087b222015-01-20 05:58:07 +00001790 Triple TT(TheModule->getTargetTriple());
1791
Chris Lattnerccaa4482007-04-23 21:26:05 +00001792 // Read all the records for this value table.
1793 SmallString<128> ValueName;
1794 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001795 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001796
Chris Lattner27d38752013-01-20 02:13:19 +00001797 switch (Entry.Kind) {
1798 case BitstreamEntry::SubBlock: // Handled for us already.
1799 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001800 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001801 case BitstreamEntry::EndBlock:
Teresa Johnsonff642b92015-09-17 20:12:00 +00001802 if (Offset > 0)
1803 Stream.JumpToBit(CurrentBit);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001804 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001805 case BitstreamEntry::Record:
1806 // The interesting case.
1807 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001808 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001809
Chris Lattnerccaa4482007-04-23 21:26:05 +00001810 // Read a record.
1811 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00001812 switch (Stream.readRecord(Entry.ID, Record)) {
Chris Lattnerccaa4482007-04-23 21:26:05 +00001813 default: // Default behavior: unknown type.
1814 break;
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001815 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001816 ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
1817 if (std::error_code EC = ValOrErr.getError())
1818 return EC;
1819 ValOrErr.get();
1820 break;
1821 }
1822 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00001823 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonff642b92015-09-17 20:12:00 +00001824 ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
1825 if (std::error_code EC = ValOrErr.getError())
1826 return EC;
1827 Value *V = ValOrErr.get();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001828
Teresa Johnsonff642b92015-09-17 20:12:00 +00001829 auto *GO = dyn_cast<GlobalObject>(V);
1830 if (!GO) {
1831 // If this is an alias, need to get the actual Function object
1832 // it aliases, in order to set up the DeferredFunctionInfo entry below.
1833 auto *GA = dyn_cast<GlobalAlias>(V);
1834 if (GA)
1835 GO = GA->getBaseObject();
1836 assert(GO);
Rafael Espindola12ca34f2015-01-19 15:16:06 +00001837 }
Teresa Johnsonff642b92015-09-17 20:12:00 +00001838
1839 uint64_t FuncWordOffset = Record[1];
1840 Function *F = dyn_cast<Function>(GO);
1841 assert(F);
1842 uint64_t FuncBitOffset = FuncWordOffset * 32;
1843 DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
Teresa Johnson1493ad92015-10-10 14:18:36 +00001844 // Set the LastFunctionBlockBit to point to the last function block.
Teresa Johnsonff642b92015-09-17 20:12:00 +00001845 // Later when parsing is resumed after function materialization,
1846 // we can simply skip that last function block.
Teresa Johnson1493ad92015-10-10 14:18:36 +00001847 if (FuncBitOffset > LastFunctionBlockBit)
1848 LastFunctionBlockBit = FuncBitOffset;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001849 break;
Reid Spencerdea02bd2007-05-04 01:43:33 +00001850 }
Bill Wendling35a9c3c2011-04-10 23:18:04 +00001851 case bitc::VST_CODE_BBENTRY: {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001852 if (convertToString(Record, 1, ValueName))
1853 return error("Invalid record");
Chris Lattner6be58c62007-05-03 22:18:21 +00001854 BasicBlock *BB = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001855 if (!BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001856 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001857
Daniel Dunbard786b512009-07-26 00:34:27 +00001858 BB->setName(StringRef(ValueName.data(), ValueName.size()));
Chris Lattner6be58c62007-05-03 22:18:21 +00001859 ValueName.clear();
1860 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00001861 }
Reid Spencerdea02bd2007-05-04 01:43:33 +00001862 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00001863 }
1864}
1865
Teresa Johnson12545072015-11-15 02:00:09 +00001866/// Parse a single METADATA_KIND record, inserting result in MDKindMap.
1867std::error_code
1868BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
1869 if (Record.size() < 2)
1870 return error("Invalid record");
1871
1872 unsigned Kind = Record[0];
1873 SmallString<8> Name(Record.begin() + 1, Record.end());
1874
1875 unsigned NewKind = TheModule->getMDKindID(Name.str());
1876 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1877 return error("Conflicting METADATA_KIND records");
1878 return std::error_code();
1879}
1880
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00001881static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
1882
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001883std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
1884 StringRef Blob,
1885 unsigned &NextMetadataNo) {
1886 // All the MDStrings in the block are emitted together in a single
1887 // record. The strings are concatenated and stored in a blob along with
1888 // their sizes.
1889 if (Record.size() != 2)
1890 return error("Invalid record: metadata strings layout");
1891
1892 unsigned NumStrings = Record[0];
1893 unsigned StringsOffset = Record[1];
1894 if (!NumStrings)
1895 return error("Invalid record: metadata strings with no strings");
Duncan P. N. Exon Smithbb7ce3b2016-03-29 05:25:17 +00001896 if (StringsOffset > Blob.size())
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001897 return error("Invalid record: metadata strings corrupt offset");
1898
1899 StringRef Lengths = Blob.slice(0, StringsOffset);
1900 SimpleBitstreamCursor R(*StreamFile);
1901 R.jumpToPointer(Lengths.begin());
1902
1903 // Ensure that Blob doesn't get invalidated, even if this is reading from
1904 // a StreamingMemoryObject with corrupt data.
1905 R.setArtificialByteLimit(R.getCurrentByteNo() + StringsOffset);
1906
1907 StringRef Strings = Blob.drop_front(StringsOffset);
1908 do {
1909 if (R.AtEndOfStream())
1910 return error("Invalid record: metadata strings bad length");
1911
1912 unsigned Size = R.ReadVBR(6);
1913 if (Strings.size() < Size)
1914 return error("Invalid record: metadata strings truncated chars");
1915
1916 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
1917 NextMetadataNo++);
1918 Strings = Strings.drop_front(Size);
1919 } while (--NumStrings);
1920
1921 return std::error_code();
1922}
1923
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00001924/// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
1925/// module level metadata.
1926std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00001927 IsMetadataMaterialized = true;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001928 unsigned NextMetadataNo = MetadataList.size();
Devang Patel7428d8a2009-07-22 17:43:22 +00001929
1930 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001931 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001932
Devang Patel7428d8a2009-07-22 17:43:22 +00001933 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001934
Teresa Johnson61b406e2015-12-29 23:00:22 +00001935 auto getMD = [&](unsigned ID) -> Metadata * {
Justin Bognerae341c62016-03-17 20:12:06 +00001936 return MetadataList.getMetadataFwdRef(ID);
Teresa Johnson61b406e2015-12-29 23:00:22 +00001937 };
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001938 auto getMDOrNull = [&](unsigned ID) -> Metadata *{
1939 if (ID)
1940 return getMD(ID - 1);
1941 return nullptr;
1942 };
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001943 auto getMDString = [&](unsigned ID) -> MDString *{
1944 // This requires that the ID is not really a forward reference. In
1945 // particular, the MDString must already have been resolved.
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00001946 return cast_or_null<MDString>(getMDOrNull(ID));
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00001947 };
1948
1949#define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
1950 (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
1951
Devang Patel7428d8a2009-07-22 17:43:22 +00001952 // Read all the records.
1953 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00001954 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00001955
Chris Lattner27d38752013-01-20 02:13:19 +00001956 switch (Entry.Kind) {
1957 case BitstreamEntry::SubBlock: // Handled for us already.
1958 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001959 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00001960 case BitstreamEntry::EndBlock:
Teresa Johnson61b406e2015-12-29 23:00:22 +00001961 MetadataList.tryToResolveCycles();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00001962 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00001963 case BitstreamEntry::Record:
1964 // The interesting case.
1965 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00001966 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00001967
Devang Patel7428d8a2009-07-22 17:43:22 +00001968 // Read a record.
1969 Record.clear();
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00001970 StringRef Blob;
1971 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00001972 bool IsDistinct = false;
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00001973 switch (Code) {
Devang Patel7428d8a2009-07-22 17:43:22 +00001974 default: // Default behavior: ignore.
1975 break;
Devang Patel27c87ff2009-07-29 22:34:41 +00001976 case bitc::METADATA_NAME: {
Chris Lattner8d140532013-01-20 02:54:05 +00001977 // Read name of the named metadata.
Benjamin Kramer9704ed02012-05-28 14:10:31 +00001978 SmallString<8> Name(Record.begin(), Record.end());
Devang Patel27c87ff2009-07-29 22:34:41 +00001979 Record.clear();
1980 Code = Stream.ReadCode();
1981
Chris Lattner27d38752013-01-20 02:13:19 +00001982 unsigned NextBitCode = Stream.readRecord(Code, Record);
Filipe Cabecinhas14e68672015-05-30 00:17:20 +00001983 if (NextBitCode != bitc::METADATA_NAMED_NODE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001984 return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
Devang Patel27c87ff2009-07-29 22:34:41 +00001985
1986 // Read named metadata elements.
1987 unsigned Size = Record.size();
Dan Gohman2637cc12010-07-21 23:38:33 +00001988 NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
Devang Patel27c87ff2009-07-29 22:34:41 +00001989 for (unsigned i = 0; i != Size; ++i) {
Justin Bognerae341c62016-03-17 20:12:06 +00001990 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
Craig Topper2617dcc2014-04-15 06:32:26 +00001991 if (!MD)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00001992 return error("Invalid record");
Dan Gohman2637cc12010-07-21 23:38:33 +00001993 NMD->addOperand(MD);
Devang Patel27c87ff2009-07-29 22:34:41 +00001994 }
Devang Patel27c87ff2009-07-29 22:34:41 +00001995 break;
1996 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00001997 case bitc::METADATA_OLD_FN_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00001998 // FIXME: Remove in 4.0.
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001999 // This is a LocalAsMetadata record, the only type of function-local
2000 // metadata.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002001 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002002 return error("Invalid record");
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002003
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002004 // If this isn't a LocalAsMetadata record, we're dropping it. This used
2005 // to be legal, but there's no upgrade path.
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002006 auto dropRecord = [&] {
Teresa Johnson61b406e2015-12-29 23:00:22 +00002007 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002008 };
2009 if (Record.size() != 2) {
2010 dropRecord();
2011 break;
2012 }
2013
2014 Type *Ty = getTypeByID(Record[0]);
2015 if (Ty->isMetadataTy() || Ty->isVoidTy()) {
2016 dropRecord();
2017 break;
2018 }
2019
Teresa Johnson61b406e2015-12-29 23:00:22 +00002020 MetadataList.assignValue(
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002021 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002022 NextMetadataNo++);
Duncan P. N. Exon Smithda41af92014-12-06 01:26:49 +00002023 break;
2024 }
Duncan P. N. Exon Smith005f9f42014-12-11 22:30:48 +00002025 case bitc::METADATA_OLD_NODE: {
Duncan P. N. Exon Smith5bd34e52014-12-12 02:11:31 +00002026 // FIXME: Remove in 4.0.
Dan Gohman1e0213a2010-07-13 19:33:27 +00002027 if (Record.size() % 2 == 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002028 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002029
Devang Patele059ba6e2009-07-23 01:07:34 +00002030 unsigned Size = Record.size();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002031 SmallVector<Metadata *, 8> Elts;
Devang Patele059ba6e2009-07-23 01:07:34 +00002032 for (unsigned i = 0; i != Size; i += 2) {
Chris Lattner229907c2011-07-18 04:54:35 +00002033 Type *Ty = getTypeByID(Record[i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002034 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002035 return error("Invalid record");
Chris Lattnerfdd87902009-10-05 05:54:46 +00002036 if (Ty->isMetadataTy())
Justin Bognerae341c62016-03-17 20:12:06 +00002037 Elts.push_back(MetadataList.getMetadataFwdRef(Record[i + 1]));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002038 else if (!Ty->isVoidTy()) {
2039 auto *MD =
2040 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
2041 assert(isa<ConstantAsMetadata>(MD) &&
2042 "Expected non-function-local metadata");
2043 Elts.push_back(MD);
2044 } else
Craig Topper2617dcc2014-04-15 06:32:26 +00002045 Elts.push_back(nullptr);
Devang Patele059ba6e2009-07-23 01:07:34 +00002046 }
Teresa Johnson61b406e2015-12-29 23:00:22 +00002047 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
Devang Patele059ba6e2009-07-23 01:07:34 +00002048 break;
2049 }
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002050 case bitc::METADATA_VALUE: {
2051 if (Record.size() != 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002052 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002053
2054 Type *Ty = getTypeByID(Record[0]);
2055 if (Ty->isMetadataTy() || Ty->isVoidTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002056 return error("Invalid record");
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002057
Teresa Johnson61b406e2015-12-29 23:00:22 +00002058 MetadataList.assignValue(
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002059 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002060 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002061 break;
2062 }
Duncan P. N. Exon Smith090a19b2015-01-08 22:38:29 +00002063 case bitc::METADATA_DISTINCT_NODE:
2064 IsDistinct = true;
2065 // fallthrough...
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002066 case bitc::METADATA_NODE: {
2067 SmallVector<Metadata *, 8> Elts;
2068 Elts.reserve(Record.size());
2069 for (unsigned ID : Record)
Justin Bognerae341c62016-03-17 20:12:06 +00002070 Elts.push_back(ID ? MetadataList.getMetadataFwdRef(ID - 1) : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002071 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
2072 : MDNode::get(Context, Elts),
2073 NextMetadataNo++);
Duncan P. N. Exon Smith5c7006e2014-12-11 23:02:24 +00002074 break;
2075 }
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002076 case bitc::METADATA_LOCATION: {
2077 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002078 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002079
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002080 unsigned Line = Record[1];
2081 unsigned Column = Record[2];
Justin Bognerae341c62016-03-17 20:12:06 +00002082 MDNode *Scope = MetadataList.getMDNodeFwdRefOrNull(Record[3]);
2083 if (!Scope)
2084 return error("Invalid record");
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002085 Metadata *InlinedAt =
Justin Bognerae341c62016-03-17 20:12:06 +00002086 Record[4] ? MetadataList.getMetadataFwdRef(Record[4] - 1) : nullptr;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002087 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002088 GET_OR_DISTINCT(DILocation, Record[0],
Duncan P. N. Exon Smith26489982015-03-26 22:05:04 +00002089 (Context, Line, Column, Scope, InlinedAt)),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002090 NextMetadataNo++);
Duncan P. N. Exon Smith6a484832015-01-13 21:10:44 +00002091 break;
2092 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002093 case bitc::METADATA_GENERIC_DEBUG: {
2094 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002095 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002096
2097 unsigned Tag = Record[1];
2098 unsigned Version = Record[2];
2099
2100 if (Tag >= 1u << 16 || Version != 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002101 return error("Invalid record");
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002102
2103 auto *Header = getMDString(Record[3]);
2104 SmallVector<Metadata *, 8> DwarfOps;
2105 for (unsigned I = 4, E = Record.size(); I != E; ++I)
Justin Bognerae341c62016-03-17 20:12:06 +00002106 DwarfOps.push_back(Record[I]
2107 ? MetadataList.getMetadataFwdRef(Record[I] - 1)
2108 : nullptr);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002109 MetadataList.assignValue(
2110 GET_OR_DISTINCT(GenericDINode, Record[0],
2111 (Context, Tag, Header, DwarfOps)),
2112 NextMetadataNo++);
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002113 break;
2114 }
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002115 case bitc::METADATA_SUBRANGE: {
2116 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002117 return error("Invalid record");
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002118
Teresa Johnson61b406e2015-12-29 23:00:22 +00002119 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002120 GET_OR_DISTINCT(DISubrange, Record[0],
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002121 (Context, Record[1], unrotateSign(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002122 NextMetadataNo++);
Duncan P. N. Exon Smithc7363f12015-02-13 01:10:38 +00002123 break;
2124 }
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002125 case bitc::METADATA_ENUMERATOR: {
2126 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002127 return error("Invalid record");
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002128
Teresa Johnson61b406e2015-12-29 23:00:22 +00002129 MetadataList.assignValue(
2130 GET_OR_DISTINCT(
2131 DIEnumerator, Record[0],
2132 (Context, unrotateSign(Record[1]), getMDString(Record[2]))),
2133 NextMetadataNo++);
Duncan P. N. Exon Smith87754762015-02-13 01:14:11 +00002134 break;
2135 }
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002136 case bitc::METADATA_BASIC_TYPE: {
2137 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002138 return error("Invalid record");
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002139
Teresa Johnson61b406e2015-12-29 23:00:22 +00002140 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002141 GET_OR_DISTINCT(DIBasicType, Record[0],
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002142 (Context, Record[1], getMDString(Record[2]),
2143 Record[3], Record[4], Record[5])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002144 NextMetadataNo++);
Duncan P. N. Exon Smith09e03f32015-02-13 01:14:58 +00002145 break;
2146 }
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002147 case bitc::METADATA_DERIVED_TYPE: {
2148 if (Record.size() != 12)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002149 return error("Invalid record");
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002150
Teresa Johnson61b406e2015-12-29 23:00:22 +00002151 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002152 GET_OR_DISTINCT(DIDerivedType, Record[0],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002153 (Context, Record[1], getMDString(Record[2]),
2154 getMDOrNull(Record[3]), Record[4],
Duncan P. N. Exon Smithad6eb1272015-02-20 03:17:58 +00002155 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2156 Record[7], Record[8], Record[9], Record[10],
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002157 getMDOrNull(Record[11]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002158 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002159 break;
2160 }
2161 case bitc::METADATA_COMPOSITE_TYPE: {
2162 if (Record.size() != 16)
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(DICompositeType, 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],
2169 getMDOrNull(Record[5]), getMDOrNull(Record[6]),
2170 Record[7], Record[8], Record[9], Record[10],
2171 getMDOrNull(Record[11]), Record[12],
2172 getMDOrNull(Record[13]), getMDOrNull(Record[14]),
2173 getMDString(Record[15]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002174 NextMetadataNo++);
Duncan P. N. Exon Smith171d0772015-02-13 01:20:38 +00002175 break;
2176 }
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002177 case bitc::METADATA_SUBROUTINE_TYPE: {
2178 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002179 return error("Invalid record");
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002180
Teresa Johnson61b406e2015-12-29 23:00:22 +00002181 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002182 GET_OR_DISTINCT(DISubroutineType, Record[0],
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002183 (Context, Record[1], getMDOrNull(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002184 NextMetadataNo++);
Duncan P. N. Exon Smith54e2bc62015-02-13 01:22:59 +00002185 break;
2186 }
Adrian Prantlab1243f2015-06-29 23:03:47 +00002187
2188 case bitc::METADATA_MODULE: {
2189 if (Record.size() != 6)
2190 return error("Invalid record");
2191
Teresa Johnson61b406e2015-12-29 23:00:22 +00002192 MetadataList.assignValue(
Adrian Prantlab1243f2015-06-29 23:03:47 +00002193 GET_OR_DISTINCT(DIModule, Record[0],
2194 (Context, getMDOrNull(Record[1]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002195 getMDString(Record[2]), getMDString(Record[3]),
2196 getMDString(Record[4]), getMDString(Record[5]))),
2197 NextMetadataNo++);
Adrian Prantlab1243f2015-06-29 23:03:47 +00002198 break;
2199 }
2200
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002201 case bitc::METADATA_FILE: {
2202 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002203 return error("Invalid record");
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002204
Teresa Johnson61b406e2015-12-29 23:00:22 +00002205 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002206 GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002207 getMDString(Record[2]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002208 NextMetadataNo++);
Duncan P. N. Exon Smithf14b9c72015-02-13 01:19:14 +00002209 break;
2210 }
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002211 case bitc::METADATA_COMPILE_UNIT: {
Amjad Abouda9bcf162015-12-10 12:56:35 +00002212 if (Record.size() < 14 || Record.size() > 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002213 return error("Invalid record");
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002214
Amjad Abouda9bcf162015-12-10 12:56:35 +00002215 // Ignore Record[0], which indicates whether this compile unit is
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002216 // distinct. It's always distinct.
Teresa Johnson61b406e2015-12-29 23:00:22 +00002217 MetadataList.assignValue(
Duncan P. N. Exon Smith55ca9642015-08-03 17:26:41 +00002218 DICompileUnit::getDistinct(
2219 Context, Record[1], getMDOrNull(Record[2]),
2220 getMDString(Record[3]), Record[4], getMDString(Record[5]),
2221 Record[6], getMDString(Record[7]), Record[8],
2222 getMDOrNull(Record[9]), getMDOrNull(Record[10]),
2223 getMDOrNull(Record[11]), getMDOrNull(Record[12]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002224 getMDOrNull(Record[13]),
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00002225 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
Amjad Abouda9bcf162015-12-10 12:56:35 +00002226 Record.size() <= 14 ? 0 : Record[14]),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002227 NextMetadataNo++);
Duncan P. N. Exon Smithc1f1acc2015-02-13 01:25:10 +00002228 break;
2229 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002230 case bitc::METADATA_SUBPROGRAM: {
Peter Collingbourned4bff302015-11-05 22:03:56 +00002231 if (Record.size() != 18 && Record.size() != 19)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002232 return error("Invalid record");
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002233
Peter Collingbourned4bff302015-11-05 22:03:56 +00002234 bool HasFn = Record.size() == 19;
2235 DISubprogram *SP = GET_OR_DISTINCT(
2236 DISubprogram,
2237 Record[0] || Record[8], // All definitions should be distinct.
2238 (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
2239 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
2240 getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
2241 getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
2242 Record[14], getMDOrNull(Record[15 + HasFn]),
2243 getMDOrNull(Record[16 + HasFn]), getMDOrNull(Record[17 + HasFn])));
Teresa Johnson61b406e2015-12-29 23:00:22 +00002244 MetadataList.assignValue(SP, NextMetadataNo++);
Peter Collingbourned4bff302015-11-05 22:03:56 +00002245
2246 // Upgrade sp->function mapping to function->sp mapping.
2247 if (HasFn && Record[15]) {
2248 if (auto *CMD = dyn_cast<ConstantAsMetadata>(getMDOrNull(Record[15])))
2249 if (auto *F = dyn_cast<Function>(CMD->getValue())) {
2250 if (F->isMaterializable())
2251 // Defer until materialized; unmaterialized functions may not have
2252 // metadata.
2253 FunctionsWithSPs[F] = SP;
2254 else if (!F->empty())
2255 F->setSubprogram(SP);
2256 }
2257 }
Duncan P. N. Exon Smith19fc5ed2015-02-13 01:26:47 +00002258 break;
2259 }
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002260 case bitc::METADATA_LEXICAL_BLOCK: {
2261 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002262 return error("Invalid record");
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002263
Teresa Johnson61b406e2015-12-29 23:00:22 +00002264 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002265 GET_OR_DISTINCT(DILexicalBlock, Record[0],
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002266 (Context, getMDOrNull(Record[1]),
2267 getMDOrNull(Record[2]), Record[3], Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002268 NextMetadataNo++);
Duncan P. N. Exon Smitha96d4092015-02-13 01:29:28 +00002269 break;
2270 }
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002271 case bitc::METADATA_LEXICAL_BLOCK_FILE: {
2272 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002273 return error("Invalid record");
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002274
Teresa Johnson61b406e2015-12-29 23:00:22 +00002275 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002276 GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002277 (Context, getMDOrNull(Record[1]),
2278 getMDOrNull(Record[2]), Record[3])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002279 NextMetadataNo++);
Duncan P. N. Exon Smith06a07022015-02-13 01:30:42 +00002280 break;
2281 }
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002282 case bitc::METADATA_NAMESPACE: {
2283 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002284 return error("Invalid record");
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002285
Teresa Johnson61b406e2015-12-29 23:00:22 +00002286 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002287 GET_OR_DISTINCT(DINamespace, Record[0],
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002288 (Context, getMDOrNull(Record[1]),
2289 getMDOrNull(Record[2]), getMDString(Record[3]),
2290 Record[4])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002291 NextMetadataNo++);
Duncan P. N. Exon Smithe1460002015-02-13 01:32:09 +00002292 break;
2293 }
Amjad Abouda9bcf162015-12-10 12:56:35 +00002294 case bitc::METADATA_MACRO: {
2295 if (Record.size() != 5)
2296 return error("Invalid record");
2297
Teresa Johnson61b406e2015-12-29 23:00:22 +00002298 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002299 GET_OR_DISTINCT(DIMacro, Record[0],
2300 (Context, Record[1], Record[2],
2301 getMDString(Record[3]), getMDString(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002302 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002303 break;
2304 }
2305 case bitc::METADATA_MACRO_FILE: {
2306 if (Record.size() != 5)
2307 return error("Invalid record");
2308
Teresa Johnson61b406e2015-12-29 23:00:22 +00002309 MetadataList.assignValue(
Amjad Abouda9bcf162015-12-10 12:56:35 +00002310 GET_OR_DISTINCT(DIMacroFile, Record[0],
2311 (Context, Record[1], Record[2],
2312 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002313 NextMetadataNo++);
Amjad Abouda9bcf162015-12-10 12:56:35 +00002314 break;
2315 }
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002316 case bitc::METADATA_TEMPLATE_TYPE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002317 if (Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002318 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002319
Teresa Johnson61b406e2015-12-29 23:00:22 +00002320 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
2321 Record[0],
2322 (Context, getMDString(Record[1]),
2323 getMDOrNull(Record[2]))),
2324 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002325 break;
2326 }
2327 case bitc::METADATA_TEMPLATE_VALUE: {
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002328 if (Record.size() != 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002329 return error("Invalid record");
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002330
Teresa Johnson61b406e2015-12-29 23:00:22 +00002331 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002332 GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
Duncan P. N. Exon Smith3d62bba2015-02-19 00:37:21 +00002333 (Context, Record[1], getMDString(Record[2]),
2334 getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002335 NextMetadataNo++);
Duncan P. N. Exon Smith2847f382015-02-13 01:34:32 +00002336 break;
2337 }
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002338 case bitc::METADATA_GLOBAL_VAR: {
2339 if (Record.size() != 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002340 return error("Invalid record");
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002341
Teresa Johnson61b406e2015-12-29 23:00:22 +00002342 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002343 GET_OR_DISTINCT(DIGlobalVariable, Record[0],
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002344 (Context, getMDOrNull(Record[1]),
2345 getMDString(Record[2]), getMDString(Record[3]),
2346 getMDOrNull(Record[4]), Record[5],
2347 getMDOrNull(Record[6]), Record[7], Record[8],
2348 getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002349 NextMetadataNo++);
Duncan P. N. Exon Smithc8f810a2015-02-13 01:35:40 +00002350 break;
2351 }
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002352 case bitc::METADATA_LOCAL_VAR: {
Duncan P. N. Exon Smith62e0f452015-04-15 22:29:27 +00002353 // 10th field is for the obseleted 'inlinedAt:' field.
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002354 if (Record.size() < 8 || Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002355 return error("Invalid record");
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002356
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002357 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
2358 // DW_TAG_arg_variable.
2359 bool HasTag = Record.size() > 8;
Teresa Johnson61b406e2015-12-29 23:00:22 +00002360 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002361 GET_OR_DISTINCT(DILocalVariable, Record[0],
Duncan P. N. Exon Smithed013cd2015-07-31 18:58:39 +00002362 (Context, getMDOrNull(Record[1 + HasTag]),
2363 getMDString(Record[2 + HasTag]),
2364 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
2365 getMDOrNull(Record[5 + HasTag]), Record[6 + HasTag],
2366 Record[7 + HasTag])),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002367 NextMetadataNo++);
Duncan P. N. Exon Smith72fe2d02015-02-13 01:39:44 +00002368 break;
2369 }
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002370 case bitc::METADATA_EXPRESSION: {
2371 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002372 return error("Invalid record");
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002373
Teresa Johnson61b406e2015-12-29 23:00:22 +00002374 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002375 GET_OR_DISTINCT(DIExpression, Record[0],
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002376 (Context, makeArrayRef(Record).slice(1))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002377 NextMetadataNo++);
Duncan P. N. Exon Smith0c5c0122015-02-13 01:42:09 +00002378 break;
2379 }
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002380 case bitc::METADATA_OBJC_PROPERTY: {
2381 if (Record.size() != 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002382 return error("Invalid record");
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002383
Teresa Johnson61b406e2015-12-29 23:00:22 +00002384 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002385 GET_OR_DISTINCT(DIObjCProperty, Record[0],
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002386 (Context, getMDString(Record[1]),
2387 getMDOrNull(Record[2]), Record[3],
2388 getMDString(Record[4]), getMDString(Record[5]),
2389 Record[6], getMDOrNull(Record[7]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002390 NextMetadataNo++);
Duncan P. N. Exon Smithd45ce962015-02-13 01:43:22 +00002391 break;
2392 }
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002393 case bitc::METADATA_IMPORTED_ENTITY: {
2394 if (Record.size() != 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002395 return error("Invalid record");
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002396
Teresa Johnson61b406e2015-12-29 23:00:22 +00002397 MetadataList.assignValue(
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00002398 GET_OR_DISTINCT(DIImportedEntity, Record[0],
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002399 (Context, Record[1], getMDOrNull(Record[2]),
2400 getMDOrNull(Record[3]), Record[4],
2401 getMDString(Record[5]))),
Teresa Johnson61b406e2015-12-29 23:00:22 +00002402 NextMetadataNo++);
Duncan P. N. Exon Smith1c931162015-02-13 01:46:02 +00002403 break;
2404 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002405 case bitc::METADATA_STRING_OLD: {
Eli Bendersky5d5e18d2014-06-25 15:41:00 +00002406 std::string String(Record.begin(), Record.end());
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00002407
2408 // Test for upgrading !llvm.loop.
2409 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
2410
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002411 Metadata *MD = MDString::get(Context, String);
Teresa Johnson61b406e2015-12-29 23:00:22 +00002412 MetadataList.assignValue(MD, NextMetadataNo++);
Devang Patel7428d8a2009-07-22 17:43:22 +00002413 break;
2414 }
Duncan P. N. Exon Smith6565a0d2016-03-27 23:17:54 +00002415 case bitc::METADATA_STRINGS:
2416 if (std::error_code EC =
2417 parseMetadataStrings(Record, Blob, NextMetadataNo))
2418 return EC;
2419 break;
Devang Patelaf206b82009-09-18 19:26:43 +00002420 case bitc::METADATA_KIND: {
Teresa Johnson12545072015-11-15 02:00:09 +00002421 // Support older bitcode files that had METADATA_KIND records in a
2422 // block with METADATA_BLOCK_ID.
2423 if (std::error_code EC = parseMetadataKindRecord(Record))
2424 return EC;
Devang Patelaf206b82009-09-18 19:26:43 +00002425 break;
2426 }
Devang Patel7428d8a2009-07-22 17:43:22 +00002427 }
2428 }
Duncan P. N. Exon Smith4e4aa702015-02-03 21:54:14 +00002429#undef GET_OR_DISTINCT
Devang Patel7428d8a2009-07-22 17:43:22 +00002430}
2431
Teresa Johnson12545072015-11-15 02:00:09 +00002432/// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
2433std::error_code BitcodeReader::parseMetadataKinds() {
2434 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
2435 return error("Invalid record");
2436
2437 SmallVector<uint64_t, 64> Record;
2438
2439 // Read all the records.
2440 while (1) {
2441 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
2442
2443 switch (Entry.Kind) {
2444 case BitstreamEntry::SubBlock: // Handled for us already.
2445 case BitstreamEntry::Error:
2446 return error("Malformed block");
2447 case BitstreamEntry::EndBlock:
2448 return std::error_code();
2449 case BitstreamEntry::Record:
2450 // The interesting case.
2451 break;
2452 }
2453
2454 // Read a record.
2455 Record.clear();
2456 unsigned Code = Stream.readRecord(Entry.ID, Record);
2457 switch (Code) {
2458 default: // Default behavior: ignore.
2459 break;
2460 case bitc::METADATA_KIND: {
2461 if (std::error_code EC = parseMetadataKindRecord(Record))
2462 return EC;
2463 break;
2464 }
2465 }
2466 }
2467}
2468
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002469/// Decode a signed value stored with the sign bit in the LSB for dense VBR
2470/// encoding.
Jan Wen Voungafaced02012-10-11 20:20:40 +00002471uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
Chris Lattner08feb1e2007-04-24 04:04:35 +00002472 if ((V & 1) == 0)
2473 return V >> 1;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002474 if (V != 1)
Chris Lattner08feb1e2007-04-24 04:04:35 +00002475 return -(V >> 1);
2476 // There is no such thing as -0 with integers. "-0" really means MININT.
2477 return 1ULL << 63;
2478}
2479
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002480/// Resolve all of the initializers for global values and aliases that we can.
2481std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
Chris Lattner44c17072007-04-26 02:46:40 +00002482 std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
2483 std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002484 std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002485 std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
David Majnemer7fddecc2015-06-17 20:52:32 +00002486 std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002487
Chris Lattner44c17072007-04-26 02:46:40 +00002488 GlobalInitWorklist.swap(GlobalInits);
2489 AliasInitWorklist.swap(AliasInits);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002490 FunctionPrefixWorklist.swap(FunctionPrefixes);
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002491 FunctionPrologueWorklist.swap(FunctionPrologues);
David Majnemer7fddecc2015-06-17 20:52:32 +00002492 FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
Chris Lattner44c17072007-04-26 02:46:40 +00002493
2494 while (!GlobalInitWorklist.empty()) {
Chris Lattner831d4202007-04-26 03:27:58 +00002495 unsigned ValID = GlobalInitWorklist.back().second;
Chris Lattner44c17072007-04-26 02:46:40 +00002496 if (ValID >= ValueList.size()) {
2497 // Not ready to resolve this yet, it requires something later in the file.
Chris Lattner831d4202007-04-26 03:27:58 +00002498 GlobalInits.push_back(GlobalInitWorklist.back());
Chris Lattner44c17072007-04-26 02:46:40 +00002499 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002500 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Chris Lattner44c17072007-04-26 02:46:40 +00002501 GlobalInitWorklist.back().first->setInitializer(C);
2502 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002503 return error("Expected a constant");
Chris Lattner44c17072007-04-26 02:46:40 +00002504 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002505 GlobalInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002506 }
2507
2508 while (!AliasInitWorklist.empty()) {
2509 unsigned ValID = AliasInitWorklist.back().second;
2510 if (ValID >= ValueList.size()) {
2511 AliasInits.push_back(AliasInitWorklist.back());
2512 } else {
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002513 Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
2514 if (!C)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002515 return error("Expected a constant");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002516 GlobalAlias *Alias = AliasInitWorklist.back().first;
2517 if (C->getType() != Alias->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002518 return error("Alias and aliasee types don't match");
Filipe Cabecinhasa911af02015-06-06 20:44:53 +00002519 Alias->setAliasee(C);
Chris Lattner44c17072007-04-26 02:46:40 +00002520 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002521 AliasInitWorklist.pop_back();
Chris Lattner44c17072007-04-26 02:46:40 +00002522 }
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002523
2524 while (!FunctionPrefixWorklist.empty()) {
2525 unsigned ValID = FunctionPrefixWorklist.back().second;
2526 if (ValID >= ValueList.size()) {
2527 FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
2528 } else {
Karthik Bhat82540e92014-03-27 12:08:23 +00002529 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002530 FunctionPrefixWorklist.back().first->setPrefixData(C);
2531 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002532 return error("Expected a constant");
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00002533 }
2534 FunctionPrefixWorklist.pop_back();
2535 }
2536
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002537 while (!FunctionPrologueWorklist.empty()) {
2538 unsigned ValID = FunctionPrologueWorklist.back().second;
2539 if (ValID >= ValueList.size()) {
2540 FunctionPrologues.push_back(FunctionPrologueWorklist.back());
2541 } else {
2542 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2543 FunctionPrologueWorklist.back().first->setPrologueData(C);
2544 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002545 return error("Expected a constant");
Peter Collingbourne51d2de72014-12-03 02:08:38 +00002546 }
2547 FunctionPrologueWorklist.pop_back();
2548 }
2549
David Majnemer7fddecc2015-06-17 20:52:32 +00002550 while (!FunctionPersonalityFnWorklist.empty()) {
2551 unsigned ValID = FunctionPersonalityFnWorklist.back().second;
2552 if (ValID >= ValueList.size()) {
2553 FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
2554 } else {
2555 if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
2556 FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
2557 else
2558 return error("Expected a constant");
2559 }
2560 FunctionPersonalityFnWorklist.pop_back();
2561 }
2562
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002563 return std::error_code();
Chris Lattner44c17072007-04-26 02:46:40 +00002564}
2565
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002566static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002567 SmallVector<uint64_t, 8> Words(Vals.size());
2568 std::transform(Vals.begin(), Vals.end(), Words.begin(),
Jan Wen Voungafaced02012-10-11 20:20:40 +00002569 BitcodeReader::decodeSignRotatedValue);
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002570
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002571 return APInt(TypeBits, Words);
2572}
2573
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002574std::error_code BitcodeReader::parseConstants() {
Chris Lattner982ec1e2007-05-05 00:17:00 +00002575 if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002576 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002577
2578 SmallVector<uint64_t, 64> Record;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002579
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002580 // Read all the records for this value table.
Chris Lattner229907c2011-07-18 04:54:35 +00002581 Type *CurTy = Type::getInt32Ty(Context);
Chris Lattner1663cca2007-04-24 05:48:56 +00002582 unsigned NextCstNo = ValueList.size();
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002583 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00002584 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00002585
Chris Lattner27d38752013-01-20 02:13:19 +00002586 switch (Entry.Kind) {
2587 case BitstreamEntry::SubBlock: // Handled for us already.
2588 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002589 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00002590 case BitstreamEntry::EndBlock:
2591 if (NextCstNo != ValueList.size())
George Burgess IV1030d682016-01-20 22:15:23 +00002592 return error("Invalid constant reference");
Joe Abbey97b7a172013-02-06 22:14:06 +00002593
Chris Lattner27d38752013-01-20 02:13:19 +00002594 // Once all the constants have been read, go through and resolve forward
2595 // references.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002596 ValueList.resolveConstantForwardRefs();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00002597 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00002598 case BitstreamEntry::Record:
2599 // The interesting case.
Chris Lattner74429932008-08-21 02:34:16 +00002600 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002601 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002602
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002603 // Read a record.
2604 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00002605 Value *V = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00002606 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00002607 switch (BitCode) {
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002608 default: // Default behavior: unknown constant
2609 case bitc::CST_CODE_UNDEF: // UNDEF
Owen Andersonb292b8c2009-07-30 23:03:37 +00002610 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002611 break;
2612 case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
2613 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002614 return error("Invalid record");
Karthik Bhat82540e92014-03-27 12:08:23 +00002615 if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002616 return error("Invalid record");
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002617 CurTy = TypeList[Record[0]];
Chris Lattner08feb1e2007-04-24 04:04:35 +00002618 continue; // Skip the ValueList manipulation.
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002619 case bitc::CST_CODE_NULL: // NULL
Owen Anderson5a1acd92009-07-31 20:28:14 +00002620 V = Constant::getNullValue(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002621 break;
2622 case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002623 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002624 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00002625 V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
Chris Lattner08feb1e2007-04-24 04:04:35 +00002626 break;
Chris Lattnere14cb882007-05-04 19:11:41 +00002627 case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
Duncan Sands19d0b472010-02-16 11:11:14 +00002628 if (!CurTy->isIntegerTy() || Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002629 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002630
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002631 APInt VInt =
2632 readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00002633 V = ConstantInt::get(Context, VInt);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002634
Chris Lattner08feb1e2007-04-24 04:04:35 +00002635 break;
2636 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002637 case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
Chris Lattner08feb1e2007-04-24 04:04:35 +00002638 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002639 return error("Invalid record");
Dan Gohman518cda42011-12-17 00:04:22 +00002640 if (CurTy->isHalfTy())
Tim Northover29178a32013-01-22 09:46:31 +00002641 V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
2642 APInt(16, (uint16_t)Record[0])));
Dan Gohman518cda42011-12-17 00:04:22 +00002643 else if (CurTy->isFloatTy())
Tim Northover29178a32013-01-22 09:46:31 +00002644 V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
2645 APInt(32, (uint32_t)Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002646 else if (CurTy->isDoubleTy())
Tim Northover29178a32013-01-22 09:46:31 +00002647 V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
2648 APInt(64, Record[0])));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002649 else if (CurTy->isX86_FP80Ty()) {
Dale Johannesen93eefa02009-03-23 21:16:53 +00002650 // Bits are not stored the same way as a normal i80 APInt, compensate.
2651 uint64_t Rearrange[2];
2652 Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
2653 Rearrange[1] = Record[0] >> 48;
Tim Northover29178a32013-01-22 09:46:31 +00002654 V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
2655 APInt(80, Rearrange)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002656 } else if (CurTy->isFP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002657 V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
2658 APInt(128, Record)));
Chris Lattnerfdd87902009-10-05 05:54:46 +00002659 else if (CurTy->isPPC_FP128Ty())
Tim Northover29178a32013-01-22 09:46:31 +00002660 V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
2661 APInt(128, Record)));
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002662 else
Owen Andersonb292b8c2009-07-30 23:03:37 +00002663 V = UndefValue::get(CurTy);
Chris Lattnerfbc1d332007-04-24 03:30:34 +00002664 break;
Dale Johannesen245dceb2007-09-11 18:32:33 +00002665 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002666
Chris Lattnere14cb882007-05-04 19:11:41 +00002667 case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
2668 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002669 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002670
Chris Lattnere14cb882007-05-04 19:11:41 +00002671 unsigned Size = Record.size();
Chris Lattnercc3aaf12012-01-27 03:15:49 +00002672 SmallVector<Constant*, 16> Elts;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002673
Chris Lattner229907c2011-07-18 04:54:35 +00002674 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
Chris Lattner1663cca2007-04-24 05:48:56 +00002675 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002676 Elts.push_back(ValueList.getConstantFwdRef(Record[i],
Chris Lattner1663cca2007-04-24 05:48:56 +00002677 STy->getElementType(i)));
Owen Anderson45308b52009-07-27 22:29:26 +00002678 V = ConstantStruct::get(STy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002679 } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
2680 Type *EltTy = ATy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002681 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002682 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Andersonc2c79322009-07-28 18:32:17 +00002683 V = ConstantArray::get(ATy, Elts);
Chris Lattner229907c2011-07-18 04:54:35 +00002684 } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
2685 Type *EltTy = VTy->getElementType();
Chris Lattner1663cca2007-04-24 05:48:56 +00002686 for (unsigned i = 0; i != Size; ++i)
Chris Lattnere14cb882007-05-04 19:11:41 +00002687 Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
Owen Anderson4aa32952009-07-28 21:19:26 +00002688 V = ConstantVector::get(Elts);
Chris Lattner1663cca2007-04-24 05:48:56 +00002689 } else {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002690 V = UndefValue::get(CurTy);
Chris Lattner1663cca2007-04-24 05:48:56 +00002691 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002692 break;
2693 }
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002694 case bitc::CST_CODE_STRING: // STRING: [values]
Chris Lattnerf25f7102007-05-06 00:53:07 +00002695 case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
2696 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002697 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002698
Benjamin Kramer9704ed02012-05-28 14:10:31 +00002699 SmallString<16> Elts(Record.begin(), Record.end());
Chris Lattnerbb8278a2012-02-05 02:41:35 +00002700 V = ConstantDataArray::getString(Context, Elts,
2701 BitCode == bitc::CST_CODE_CSTRING);
Chris Lattnerf25f7102007-05-06 00:53:07 +00002702 break;
2703 }
Chris Lattner372dd1e2012-01-30 00:51:16 +00002704 case bitc::CST_CODE_DATA: {// DATA: [n x value]
2705 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002706 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00002707
Chris Lattner372dd1e2012-01-30 00:51:16 +00002708 Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
Chris Lattner372dd1e2012-01-30 00:51:16 +00002709 if (EltTy->isIntegerTy(8)) {
2710 SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
2711 if (isa<VectorType>(CurTy))
2712 V = ConstantDataVector::get(Context, Elts);
2713 else
2714 V = ConstantDataArray::get(Context, Elts);
2715 } else if (EltTy->isIntegerTy(16)) {
2716 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2717 if (isa<VectorType>(CurTy))
2718 V = ConstantDataVector::get(Context, Elts);
2719 else
2720 V = ConstantDataArray::get(Context, Elts);
2721 } else if (EltTy->isIntegerTy(32)) {
2722 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
2723 if (isa<VectorType>(CurTy))
2724 V = ConstantDataVector::get(Context, Elts);
2725 else
2726 V = ConstantDataArray::get(Context, Elts);
2727 } else if (EltTy->isIntegerTy(64)) {
2728 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
2729 if (isa<VectorType>(CurTy))
2730 V = ConstantDataVector::get(Context, Elts);
2731 else
2732 V = ConstantDataArray::get(Context, Elts);
Justin Bognera43eacb2016-01-06 22:31:32 +00002733 } else if (EltTy->isHalfTy()) {
2734 SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
2735 if (isa<VectorType>(CurTy))
2736 V = ConstantDataVector::getFP(Context, Elts);
2737 else
2738 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002739 } else if (EltTy->isFloatTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002740 SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002741 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002742 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002743 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002744 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002745 } else if (EltTy->isDoubleTy()) {
Justin Bognera43eacb2016-01-06 22:31:32 +00002746 SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
Chris Lattner372dd1e2012-01-30 00:51:16 +00002747 if (isa<VectorType>(CurTy))
Justin Bognera43eacb2016-01-06 22:31:32 +00002748 V = ConstantDataVector::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002749 else
Justin Bognera43eacb2016-01-06 22:31:32 +00002750 V = ConstantDataArray::getFP(Context, Elts);
Chris Lattner372dd1e2012-01-30 00:51:16 +00002751 } else {
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002752 return error("Invalid type for value");
Chris Lattner372dd1e2012-01-30 00:51:16 +00002753 }
2754 break;
2755 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002756 case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002757 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002758 return error("Invalid record");
2759 int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002760 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002761 V = UndefValue::get(CurTy); // Unknown binop.
Chris Lattner890683d2007-04-24 18:15:21 +00002762 } else {
2763 Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
2764 Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
Dan Gohman1b849082009-09-07 23:54:19 +00002765 unsigned Flags = 0;
2766 if (Record.size() >= 4) {
2767 if (Opc == Instruction::Add ||
2768 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002769 Opc == Instruction::Mul ||
2770 Opc == Instruction::Shl) {
Dan Gohman1b849082009-09-07 23:54:19 +00002771 if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2772 Flags |= OverflowingBinaryOperator::NoSignedWrap;
2773 if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2774 Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
Chris Lattner35315d02011-02-06 21:44:57 +00002775 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00002776 Opc == Instruction::UDiv ||
2777 Opc == Instruction::LShr ||
2778 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00002779 if (Record[3] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00002780 Flags |= SDivOperator::IsExact;
2781 }
2782 }
2783 V = ConstantExpr::get(Opc, LHS, RHS, Flags);
Chris Lattner890683d2007-04-24 18:15:21 +00002784 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002785 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002786 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002787 case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002788 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002789 return error("Invalid record");
2790 int Opc = getDecodedCastOpcode(Record[0]);
Chris Lattner890683d2007-04-24 18:15:21 +00002791 if (Opc < 0) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00002792 V = UndefValue::get(CurTy); // Unknown cast.
Chris Lattner890683d2007-04-24 18:15:21 +00002793 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002794 Type *OpTy = getTypeByID(Record[1]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002795 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002796 return error("Invalid record");
Chris Lattner890683d2007-04-24 18:15:21 +00002797 Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00002798 V = UpgradeBitCastExpr(Opc, Op, CurTy);
2799 if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
Chris Lattner890683d2007-04-24 18:15:21 +00002800 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002801 break;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002802 }
Dan Gohman1639c392009-07-27 21:53:46 +00002803 case bitc::CST_CODE_CE_INBOUNDS_GEP:
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002804 case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
David Blaikieb9263572015-03-13 21:03:36 +00002805 unsigned OpNum = 0;
2806 Type *PointeeType = nullptr;
2807 if (Record.size() % 2)
2808 PointeeType = getTypeByID(Record[OpNum++]);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002809 SmallVector<Constant*, 16> Elts;
David Blaikieb9263572015-03-13 21:03:36 +00002810 while (OpNum != Record.size()) {
2811 Type *ElTy = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00002812 if (!ElTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002813 return error("Invalid record");
David Blaikieb9263572015-03-13 21:03:36 +00002814 Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002815 }
David Blaikieb9263572015-03-13 21:03:36 +00002816
David Blaikieb9263572015-03-13 21:03:36 +00002817 if (PointeeType &&
David Blaikie4a2e73b2015-04-02 18:55:32 +00002818 PointeeType !=
2819 cast<SequentialType>(Elts[0]->getType()->getScalarType())
2820 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002821 return error("Explicit gep operator type does not match pointee type "
David Blaikie12cf5d702015-03-16 22:03:50 +00002822 "of pointer operand");
David Blaikie4a2e73b2015-04-02 18:55:32 +00002823
2824 ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
2825 V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
2826 BitCode ==
2827 bitc::CST_CODE_CE_INBOUNDS_GEP);
Chris Lattner890683d2007-04-24 18:15:21 +00002828 break;
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002829 }
Joe Abbey1a6e7702013-09-12 22:02:31 +00002830 case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002831 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002832 return error("Invalid record");
Joe Abbey1a6e7702013-09-12 22:02:31 +00002833
2834 Type *SelectorTy = Type::getInt1Ty(Context);
2835
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002836 // The selector might be an i1 or an <n x i1>
2837 // Get the type from the ValueList before getting a forward ref.
Joe Abbey1a6e7702013-09-12 22:02:31 +00002838 if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
Filipe Cabecinhas984fefd2015-08-31 18:00:30 +00002839 if (Value *V = ValueList[Record[0]])
2840 if (SelectorTy != V->getType())
2841 SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
Joe Abbey1a6e7702013-09-12 22:02:31 +00002842
2843 V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
2844 SelectorTy),
2845 ValueList.getConstantFwdRef(Record[1],CurTy),
2846 ValueList.getConstantFwdRef(Record[2],CurTy));
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002847 break;
Joe Abbey1a6e7702013-09-12 22:02:31 +00002848 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002849 case bitc::CST_CODE_CE_EXTRACTELT
2850 : { // CE_EXTRACTELT: [opty, opval, opty, opval]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002851 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002852 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002853 VectorType *OpTy =
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002854 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002855 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002856 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002857 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002858 Constant *Op1 = nullptr;
2859 if (Record.size() == 4) {
2860 Type *IdxTy = getTypeByID(Record[2]);
2861 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002862 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002863 Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2864 } else // TODO: Remove with llvm 4.0
2865 Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2866 if (!Op1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002867 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002868 V = ConstantExpr::getExtractElement(Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002869 break;
2870 }
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002871 case bitc::CST_CODE_CE_INSERTELT
2872 : { // CE_INSERTELT: [opval, opval, opty, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002873 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002874 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002875 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002876 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2877 Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
2878 OpTy->getElementType());
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002879 Constant *Op2 = nullptr;
2880 if (Record.size() == 4) {
2881 Type *IdxTy = getTypeByID(Record[2]);
2882 if (!IdxTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002883 return error("Invalid record");
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00002884 Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
2885 } else // TODO: Remove with llvm 4.0
2886 Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
2887 if (!Op2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002888 return error("Invalid record");
Owen Anderson487375e2009-07-29 18:55:55 +00002889 V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002890 break;
2891 }
2892 case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002893 VectorType *OpTy = dyn_cast<VectorType>(CurTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00002894 if (Record.size() < 3 || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002895 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002896 Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
2897 Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002898 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002899 OpTy->getNumElements());
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002900 Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002901 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002902 break;
2903 }
Nate Begeman94aa38d2009-02-12 21:28:33 +00002904 case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
Chris Lattner229907c2011-07-18 04:54:35 +00002905 VectorType *RTy = dyn_cast<VectorType>(CurTy);
2906 VectorType *OpTy =
Duncan Sands89d412a2010-10-28 15:47:26 +00002907 dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
Craig Topper2617dcc2014-04-15 06:32:26 +00002908 if (Record.size() < 4 || !RTy || !OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002909 return error("Invalid record");
Nate Begeman94aa38d2009-02-12 21:28:33 +00002910 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2911 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00002912 Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
Owen Andersone9f98042009-07-07 20:18:58 +00002913 RTy->getNumElements());
Nate Begeman94aa38d2009-02-12 21:28:33 +00002914 Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
Owen Anderson487375e2009-07-29 18:55:55 +00002915 V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
Nate Begeman94aa38d2009-02-12 21:28:33 +00002916 break;
2917 }
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002918 case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
Rafael Espindola48da4f42013-11-04 16:16:24 +00002919 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002920 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002921 Type *OpTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002922 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002923 return error("Invalid record");
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002924 Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
2925 Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
2926
Duncan Sands9dff9be2010-02-15 16:12:20 +00002927 if (OpTy->isFPOrFPVectorTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002928 V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
Nate Begemand2195702008-05-12 19:01:56 +00002929 else
Owen Anderson487375e2009-07-29 18:55:55 +00002930 V = ConstantExpr::getICmp(Record[3], Op0, Op1);
Chris Lattner1e16bcf72007-04-24 07:07:11 +00002931 break;
Chris Lattner1663cca2007-04-24 05:48:56 +00002932 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002933 // This maintains backward compatibility, pre-asm dialect keywords.
Chad Rosier5895eda2012-09-05 06:28:52 +00002934 // FIXME: Remove with the 4.0 release.
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002935 case bitc::CST_CODE_INLINEASM_OLD: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002936 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002937 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002938 std::string AsmStr, ConstrStr;
Dale Johannesenfd04c742009-10-13 20:46:56 +00002939 bool HasSideEffects = Record[0] & 1;
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002940 bool IsAlignStack = Record[0] >> 1;
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002941 unsigned AsmStrSize = Record[1];
2942 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002943 return error("Invalid record");
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002944 unsigned ConstStrSize = Record[2+AsmStrSize];
2945 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002946 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00002947
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002948 for (unsigned i = 0; i != AsmStrSize; ++i)
2949 AsmStr += (char)Record[2+i];
2950 for (unsigned i = 0; i != ConstStrSize; ++i)
2951 ConstrStr += (char)Record[3+AsmStrSize+i];
Chris Lattner229907c2011-07-18 04:54:35 +00002952 PointerType *PTy = cast<PointerType>(CurTy);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002953 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
Dale Johannesen1cfb9582009-10-21 23:28:00 +00002954 AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
Chris Lattneraf8fffc2007-05-06 01:58:20 +00002955 break;
2956 }
Chad Rosierd8c76102012-09-05 19:00:49 +00002957 // This version adds support for the asm dialect keywords (e.g.,
2958 // inteldialect).
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002959 case bitc::CST_CODE_INLINEASM: {
Rafael Espindola48da4f42013-11-04 16:16:24 +00002960 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002961 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002962 std::string AsmStr, ConstrStr;
2963 bool HasSideEffects = Record[0] & 1;
2964 bool IsAlignStack = (Record[0] >> 1) & 1;
2965 unsigned AsmDialect = Record[0] >> 2;
2966 unsigned AsmStrSize = Record[1];
2967 if (2+AsmStrSize >= Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002968 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002969 unsigned ConstStrSize = Record[2+AsmStrSize];
2970 if (3+AsmStrSize+ConstStrSize > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002971 return error("Invalid record");
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002972
2973 for (unsigned i = 0; i != AsmStrSize; ++i)
2974 AsmStr += (char)Record[2+i];
2975 for (unsigned i = 0; i != ConstStrSize; ++i)
2976 ConstrStr += (char)Record[3+AsmStrSize+i];
2977 PointerType *PTy = cast<PointerType>(CurTy);
2978 V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
2979 AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
Chad Rosierd8c76102012-09-05 19:00:49 +00002980 InlineAsm::AsmDialect(AsmDialect));
Chad Rosier18fcdcf2012-09-05 00:56:20 +00002981 break;
2982 }
Chris Lattner5956dc82009-10-28 05:53:48 +00002983 case bitc::CST_CODE_BLOCKADDRESS:{
Rafael Espindola48da4f42013-11-04 16:16:24 +00002984 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002985 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00002986 Type *FnTy = getTypeByID(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00002987 if (!FnTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002988 return error("Invalid record");
Chris Lattner5956dc82009-10-28 05:53:48 +00002989 Function *Fn =
2990 dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
Craig Topper2617dcc2014-04-15 06:32:26 +00002991 if (!Fn)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00002992 return error("Invalid record");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00002993
2994 // If the function is already parsed we can insert the block address right
2995 // away.
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00002996 BasicBlock *BB;
2997 unsigned BBID = Record[2];
2998 if (!BBID)
2999 // Invalid reference to entry block.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003000 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003001 if (!Fn->empty()) {
3002 Function::iterator BBI = Fn->begin(), BBE = Fn->end();
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003003 for (size_t I = 0, E = BBID; I != E; ++I) {
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003004 if (BBI == BBE)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003005 return error("Invalid ID");
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003006 ++BBI;
3007 }
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003008 BB = &*BBI;
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003009 } else {
3010 // Otherwise insert a placeholder and remember it so it can be inserted
3011 // when the function is parsed.
Duncan P. N. Exon Smith5a511b52014-08-05 17:49:48 +00003012 auto &FwdBBs = BasicBlockFwdRefs[Fn];
3013 if (FwdBBs.empty())
3014 BasicBlockFwdRefQueue.push_back(Fn);
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00003015 if (FwdBBs.size() < BBID + 1)
3016 FwdBBs.resize(BBID + 1);
3017 if (!FwdBBs[BBID])
3018 FwdBBs[BBID] = BasicBlock::Create(Context);
3019 BB = FwdBBs[BBID];
Benjamin Kramer736a4fc2012-09-21 14:34:31 +00003020 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00003021 V = BlockAddress::get(Fn, BB);
Chris Lattner5956dc82009-10-28 05:53:48 +00003022 break;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003023 }
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003024 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003025
David Majnemer8a1c45d2015-12-12 05:38:55 +00003026 ValueList.assignValue(V, NextCstNo);
Chris Lattner1663cca2007-04-24 05:48:56 +00003027 ++NextCstNo;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003028 }
3029}
Chris Lattner1314b992007-04-22 06:23:29 +00003030
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003031std::error_code BitcodeReader::parseUseLists() {
Chad Rosierca2567b2011-12-07 21:44:12 +00003032 if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003033 return error("Invalid record");
Chad Rosierca2567b2011-12-07 21:44:12 +00003034
Chad Rosierca2567b2011-12-07 21:44:12 +00003035 // Read all the records.
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003036 SmallVector<uint64_t, 64> Record;
Chad Rosierca2567b2011-12-07 21:44:12 +00003037 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003038 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003039
Chris Lattner27d38752013-01-20 02:13:19 +00003040 switch (Entry.Kind) {
3041 case BitstreamEntry::SubBlock: // Handled for us already.
3042 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003043 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003044 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003045 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003046 case BitstreamEntry::Record:
3047 // The interesting case.
3048 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003049 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003050
Chad Rosierca2567b2011-12-07 21:44:12 +00003051 // Read a use list record.
3052 Record.clear();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003053 bool IsBB = false;
Chris Lattner27d38752013-01-20 02:13:19 +00003054 switch (Stream.readRecord(Entry.ID, Record)) {
Chad Rosierca2567b2011-12-07 21:44:12 +00003055 default: // Default behavior: unknown type.
3056 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003057 case bitc::USELIST_CODE_BB:
3058 IsBB = true;
3059 // fallthrough
3060 case bitc::USELIST_CODE_DEFAULT: {
Chad Rosierca2567b2011-12-07 21:44:12 +00003061 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003062 if (RecordLength < 3)
3063 // Records should have at least an ID and two indexes.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003064 return error("Invalid record");
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003065 unsigned ID = Record.back();
3066 Record.pop_back();
3067
3068 Value *V;
3069 if (IsBB) {
3070 assert(ID < FunctionBBs.size() && "Basic block not found");
3071 V = FunctionBBs[ID];
3072 } else
3073 V = ValueList[ID];
3074 unsigned NumUses = 0;
3075 SmallDenseMap<const Use *, unsigned, 16> Order;
Rafael Espindola257a3532016-01-15 19:00:20 +00003076 for (const Use &U : V->materialized_uses()) {
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003077 if (++NumUses > Record.size())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003078 break;
Duncan P. N. Exon Smith13183642014-08-16 01:54:34 +00003079 Order[&U] = Record[NumUses - 1];
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00003080 }
3081 if (Order.size() != Record.size() || NumUses > Record.size())
3082 // Mismatches can happen if the functions are being materialized lazily
3083 // (out-of-order), or a value has been upgraded.
3084 break;
3085
3086 V->sortUseList([&](const Use &L, const Use &R) {
3087 return Order.lookup(&L) < Order.lookup(&R);
3088 });
Chad Rosierca2567b2011-12-07 21:44:12 +00003089 break;
3090 }
3091 }
3092 }
3093}
3094
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003095/// When we see the block for metadata, remember where it is and then skip it.
3096/// This lets us lazily deserialize the metadata.
3097std::error_code BitcodeReader::rememberAndSkipMetadata() {
3098 // Save the current stream state.
3099 uint64_t CurBit = Stream.GetCurrentBitNo();
3100 DeferredMetadataInfo.push_back(CurBit);
3101
3102 // Skip over the block for now.
3103 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003104 return error("Invalid record");
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003105 return std::error_code();
3106}
3107
3108std::error_code BitcodeReader::materializeMetadata() {
3109 for (uint64_t BitPos : DeferredMetadataInfo) {
3110 // Move the bit stream to the saved position.
3111 Stream.JumpToBit(BitPos);
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003112 if (std::error_code EC = parseMetadata(true))
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003113 return EC;
3114 }
3115 DeferredMetadataInfo.clear();
3116 return std::error_code();
3117}
3118
Rafael Espindola468b8682015-04-01 14:44:59 +00003119void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00003120
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003121/// When we see the block for a function body, remember where it is and then
3122/// skip it. This lets us lazily deserialize the functions.
3123std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003124 // Get the function we are talking about.
3125 if (FunctionsWithBodies.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003126 return error("Insufficient function protos");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003127
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003128 Function *Fn = FunctionsWithBodies.back();
3129 FunctionsWithBodies.pop_back();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003130
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003131 // Save the current stream state.
3132 uint64_t CurBit = Stream.GetCurrentBitNo();
Teresa Johnson1493ad92015-10-10 14:18:36 +00003133 assert(
3134 (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
3135 "Mismatch between VST and scanned function offsets");
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00003136 DeferredFunctionInfo[Fn] = CurBit;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003137
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003138 // Skip over the function block for now.
3139 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003140 return error("Invalid record");
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003141 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003142}
3143
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003144std::error_code BitcodeReader::globalCleanup() {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003145 // Patch the initializers for globals and aliases up.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003146 resolveGlobalAndAliasInits();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003147 if (!GlobalInits.empty() || !AliasInits.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003148 return error("Malformed global initializer set");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003149
3150 // Look for intrinsic functions which need to be upgraded at some point
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003151 for (Function &F : *TheModule) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003152 Function *NewFn;
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003153 if (UpgradeIntrinsicFunction(&F, NewFn))
Rafael Espindola4e721212015-07-02 16:22:40 +00003154 UpgradedIntrinsics[&F] = NewFn;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003155 }
3156
3157 // Look for global variables which need to be renamed.
Yaron Kerenef5e7ad2015-06-12 18:13:20 +00003158 for (GlobalVariable &GV : TheModule->globals())
3159 UpgradeGlobalVariable(&GV);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00003160
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003161 // Force deallocation of memory for these vectors to favor the client that
3162 // want lazy deserialization.
3163 std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
3164 std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003165 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003166}
3167
Teresa Johnson1493ad92015-10-10 14:18:36 +00003168/// Support for lazy parsing of function bodies. This is required if we
3169/// either have an old bitcode file without a VST forward declaration record,
3170/// or if we have an anonymous function being materialized, since anonymous
3171/// functions do not have a name and are therefore not in the VST.
3172std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
3173 Stream.JumpToBit(NextUnreadBit);
3174
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003175 if (Stream.AtEndOfStream())
3176 return error("Could not find function in stream");
Teresa Johnson1493ad92015-10-10 14:18:36 +00003177
Filipe Cabecinhas7aae2f22015-11-03 13:48:26 +00003178 if (!SeenFirstFunctionBody)
3179 return error("Trying to materialize functions before seeing function blocks");
3180
Teresa Johnson1493ad92015-10-10 14:18:36 +00003181 // An old bitcode file with the symbol table at the end would have
3182 // finished the parse greedily.
3183 assert(SeenValueSymbolTable);
3184
3185 SmallVector<uint64_t, 64> Record;
3186
3187 while (1) {
3188 BitstreamEntry Entry = Stream.advance();
3189 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003190 default:
3191 return error("Expect SubBlock");
3192 case BitstreamEntry::SubBlock:
3193 switch (Entry.ID) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003194 default:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003195 return error("Expect function block");
3196 case bitc::FUNCTION_BLOCK_ID:
3197 if (std::error_code EC = rememberAndSkipFunctionBody())
3198 return EC;
3199 NextUnreadBit = Stream.GetCurrentBitNo();
3200 return std::error_code();
3201 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00003202 }
3203 }
3204}
3205
Mehdi Amini5d303282015-10-26 18:37:00 +00003206std::error_code BitcodeReader::parseBitcodeVersion() {
3207 if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
3208 return error("Invalid record");
3209
3210 // Read all the records.
3211 SmallVector<uint64_t, 64> Record;
3212 while (1) {
3213 BitstreamEntry Entry = Stream.advance();
3214
3215 switch (Entry.Kind) {
3216 default:
3217 case BitstreamEntry::Error:
3218 return error("Malformed block");
3219 case BitstreamEntry::EndBlock:
3220 return std::error_code();
3221 case BitstreamEntry::Record:
3222 // The interesting case.
3223 break;
3224 }
3225
3226 // Read a record.
3227 Record.clear();
3228 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
3229 switch (BitCode) {
3230 default: // Default behavior: reject
3231 return error("Invalid value");
3232 case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
3233 // N]
3234 convertToString(Record, 0, ProducerIdentification);
3235 break;
3236 }
3237 case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
3238 unsigned epoch = (unsigned)Record[0];
3239 if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
Oleksiy Vyalov6c2403f2015-10-26 22:37:36 +00003240 return error(
3241 Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
3242 "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
Mehdi Amini5d303282015-10-26 18:37:00 +00003243 }
3244 }
3245 }
3246 }
3247}
3248
Teresa Johnson1493ad92015-10-10 14:18:36 +00003249std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003250 bool ShouldLazyLoadMetadata) {
Teresa Johnson1493ad92015-10-10 14:18:36 +00003251 if (ResumeBit)
3252 Stream.JumpToBit(ResumeBit);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003253 else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003254 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003255
Chris Lattner1314b992007-04-22 06:23:29 +00003256 SmallVector<uint64_t, 64> Record;
3257 std::vector<std::string> SectionTable;
Gordon Henriksend930f912008-08-17 18:44:35 +00003258 std::vector<std::string> GCTable;
Chris Lattner1314b992007-04-22 06:23:29 +00003259
3260 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003261 while (1) {
3262 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003263
Chris Lattner27d38752013-01-20 02:13:19 +00003264 switch (Entry.Kind) {
3265 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003266 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003267 case BitstreamEntry::EndBlock:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003268 return globalCleanup();
Joe Abbey97b7a172013-02-06 22:14:06 +00003269
Chris Lattner27d38752013-01-20 02:13:19 +00003270 case BitstreamEntry::SubBlock:
3271 switch (Entry.ID) {
Chris Lattner1314b992007-04-22 06:23:29 +00003272 default: // Skip unknown content.
3273 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003274 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003275 break;
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003276 case bitc::BLOCKINFO_BLOCK_ID:
3277 if (Stream.ReadBlockInfoBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003278 return error("Malformed block");
Chris Lattner6eeea5d2007-05-05 18:57:30 +00003279 break;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003280 case bitc::PARAMATTR_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003281 if (std::error_code EC = parseAttributeBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003282 return EC;
Chris Lattnerfee5a372007-05-04 03:30:17 +00003283 break;
Bill Wendlingba629332013-02-10 23:24:25 +00003284 case bitc::PARAMATTR_GROUP_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003285 if (std::error_code EC = parseAttributeGroupBlock())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003286 return EC;
Bill Wendlingba629332013-02-10 23:24:25 +00003287 break;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00003288 case bitc::TYPE_BLOCK_ID_NEW:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003289 if (std::error_code EC = parseTypeTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003290 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003291 break;
Chris Lattnerccaa4482007-04-23 21:26:05 +00003292 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnsonff642b92015-09-17 20:12:00 +00003293 if (!SeenValueSymbolTable) {
3294 // Either this is an old form VST without function index and an
3295 // associated VST forward declaration record (which would have caused
3296 // the VST to be jumped to and parsed before it was encountered
3297 // normally in the stream), or there were no function blocks to
3298 // trigger an earlier parsing of the VST.
3299 assert(VSTOffset == 0 || FunctionsWithBodies.empty());
3300 if (std::error_code EC = parseValueSymbolTable())
3301 return EC;
3302 SeenValueSymbolTable = true;
3303 } else {
3304 // We must have had a VST forward declaration record, which caused
3305 // the parser to jump to and parse the VST earlier.
3306 assert(VSTOffset > 0);
3307 if (Stream.SkipBlock())
3308 return error("Invalid record");
3309 }
Chris Lattnerccaa4482007-04-23 21:26:05 +00003310 break;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003311 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003312 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003313 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003314 if (std::error_code EC = resolveGlobalAndAliasInits())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003315 return EC;
Chris Lattnerfbc1d332007-04-24 03:30:34 +00003316 break;
Devang Patel7428d8a2009-07-22 17:43:22 +00003317 case bitc::METADATA_BLOCK_ID:
Manman Ren4a9b0eb2015-03-13 19:24:30 +00003318 if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
3319 if (std::error_code EC = rememberAndSkipMetadata())
3320 return EC;
3321 break;
3322 }
3323 assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
Teresa Johnsond4d3dfd2015-11-20 14:51:27 +00003324 if (std::error_code EC = parseMetadata(true))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003325 return EC;
Devang Patel7428d8a2009-07-22 17:43:22 +00003326 break;
Teresa Johnson12545072015-11-15 02:00:09 +00003327 case bitc::METADATA_KIND_BLOCK_ID:
3328 if (std::error_code EC = parseMetadataKinds())
3329 return EC;
3330 break;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003331 case bitc::FUNCTION_BLOCK_ID:
3332 // If this is the first function body we've seen, reverse the
3333 // FunctionsWithBodies list.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003334 if (!SeenFirstFunctionBody) {
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003335 std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003336 if (std::error_code EC = globalCleanup())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003337 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003338 SeenFirstFunctionBody = true;
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003339 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003340
Teresa Johnsonff642b92015-09-17 20:12:00 +00003341 if (VSTOffset > 0) {
3342 // If we have a VST forward declaration record, make sure we
3343 // parse the VST now if we haven't already. It is needed to
3344 // set up the DeferredFunctionInfo vector for lazy reading.
3345 if (!SeenValueSymbolTable) {
3346 if (std::error_code EC =
3347 BitcodeReader::parseValueSymbolTable(VSTOffset))
3348 return EC;
3349 SeenValueSymbolTable = true;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003350 // Fall through so that we record the NextUnreadBit below.
3351 // This is necessary in case we have an anonymous function that
3352 // is later materialized. Since it will not have a VST entry we
3353 // need to fall back to the lazy parse to find its offset.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003354 } else {
3355 // If we have a VST forward declaration record, but have already
3356 // parsed the VST (just above, when the first function body was
3357 // encountered here), then we are resuming the parse after
Teresa Johnson1493ad92015-10-10 14:18:36 +00003358 // materializing functions. The ResumeBit points to the
3359 // start of the last function block recorded in the
3360 // DeferredFunctionInfo map. Skip it.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003361 if (Stream.SkipBlock())
3362 return error("Invalid record");
3363 continue;
3364 }
3365 }
3366
3367 // Support older bitcode files that did not have the function
Teresa Johnson1493ad92015-10-10 14:18:36 +00003368 // index in the VST, nor a VST forward declaration record, as
3369 // well as anonymous functions that do not have VST entries.
Teresa Johnsonff642b92015-09-17 20:12:00 +00003370 // Build the DeferredFunctionInfo vector on the fly.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003371 if (std::error_code EC = rememberAndSkipFunctionBody())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003372 return EC;
Teresa Johnson1493ad92015-10-10 14:18:36 +00003373
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003374 // Suspend parsing when we reach the function bodies. Subsequent
3375 // materialization calls will resume it when necessary. If the bitcode
3376 // file is old, the symbol table will be at the end instead and will not
3377 // have been seen yet. In this case, just finish the parse now.
3378 if (SeenValueSymbolTable) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003379 NextUnreadBit = Stream.GetCurrentBitNo();
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003380 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003381 }
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003382 break;
Chad Rosierca2567b2011-12-07 21:44:12 +00003383 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003384 if (std::error_code EC = parseUseLists())
Rafael Espindola48da4f42013-11-04 16:16:24 +00003385 return EC;
Chad Rosierca2567b2011-12-07 21:44:12 +00003386 break;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003387 case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
3388 if (std::error_code EC = parseOperandBundleTags())
3389 return EC;
3390 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003391 }
3392 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003393
Chris Lattner27d38752013-01-20 02:13:19 +00003394 case BitstreamEntry::Record:
3395 // The interesting case.
3396 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003397 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003398
Chris Lattner1314b992007-04-22 06:23:29 +00003399 // Read a record.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003400 auto BitCode = Stream.readRecord(Entry.ID, Record);
3401 switch (BitCode) {
Chris Lattner1314b992007-04-22 06:23:29 +00003402 default: break; // Default behavior, ignore unknown content.
Jan Wen Voungafaced02012-10-11 20:20:40 +00003403 case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
Chris Lattner1314b992007-04-22 06:23:29 +00003404 if (Record.size() < 1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003405 return error("Invalid record");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003406 // Only version #0 and #1 are supported so far.
3407 unsigned module_version = Record[0];
3408 switch (module_version) {
Rafael Espindola48da4f42013-11-04 16:16:24 +00003409 default:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003410 return error("Invalid value");
Jan Wen Voungafaced02012-10-11 20:20:40 +00003411 case 0:
3412 UseRelativeIDs = false;
3413 break;
3414 case 1:
3415 UseRelativeIDs = true;
3416 break;
3417 }
Chris Lattner1314b992007-04-22 06:23:29 +00003418 break;
Jan Wen Voungafaced02012-10-11 20:20:40 +00003419 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003420 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003421 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003422 if (convertToString(Record, 0, S))
3423 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003424 TheModule->setTargetTriple(S);
3425 break;
3426 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003427 case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003428 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003429 if (convertToString(Record, 0, S))
3430 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003431 TheModule->setDataLayout(S);
3432 break;
3433 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003434 case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003435 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003436 if (convertToString(Record, 0, S))
3437 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003438 TheModule->setModuleInlineAsm(S);
3439 break;
3440 }
Bill Wendling706d3d62012-11-28 08:41:48 +00003441 case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
3442 // FIXME: Remove in 4.0.
3443 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003444 if (convertToString(Record, 0, S))
3445 return error("Invalid record");
Bill Wendling706d3d62012-11-28 08:41:48 +00003446 // Ignore value.
3447 break;
3448 }
Chris Lattnere14cb882007-05-04 19:11:41 +00003449 case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
Chris Lattner1314b992007-04-22 06:23:29 +00003450 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003451 if (convertToString(Record, 0, S))
3452 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003453 SectionTable.push_back(S);
3454 break;
3455 }
Gordon Henriksend930f912008-08-17 18:44:35 +00003456 case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
Gordon Henriksen71183b62007-12-10 03:18:06 +00003457 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003458 if (convertToString(Record, 0, S))
3459 return error("Invalid record");
Gordon Henriksend930f912008-08-17 18:44:35 +00003460 GCTable.push_back(S);
Gordon Henriksen71183b62007-12-10 03:18:06 +00003461 break;
3462 }
David Majnemerdad0a642014-06-27 18:19:56 +00003463 case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
3464 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003465 return error("Invalid record");
David Majnemerdad0a642014-06-27 18:19:56 +00003466 Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
3467 unsigned ComdatNameSize = Record[1];
3468 std::string ComdatName;
3469 ComdatName.reserve(ComdatNameSize);
3470 for (unsigned i = 0; i != ComdatNameSize; ++i)
3471 ComdatName += (char)Record[2 + i];
3472 Comdat *C = TheModule->getOrInsertComdat(ComdatName);
3473 C->setSelectionKind(SK);
3474 ComdatList.push_back(C);
3475 break;
3476 }
Christopher Lamb54dd24c2007-12-11 08:59:05 +00003477 // GLOBALVAR: [pointer type, isconst, initid,
Rafael Espindola45e6c192011-01-08 16:42:36 +00003478 // linkage, alignment, section, visibility, threadlocal,
Peter Collingbourne69ba0162015-02-04 00:42:45 +00003479 // unnamed_addr, externally_initialized, dllstorageclass,
3480 // comdat]
Chris Lattner1314b992007-04-22 06:23:29 +00003481 case bitc::MODULE_CODE_GLOBALVAR: {
Chris Lattner4b00d922007-04-23 16:04:05 +00003482 if (Record.size() < 6)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003483 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003484 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003485 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003486 return error("Invalid record");
David Blaikie1a848da2015-04-27 19:58:56 +00003487 bool isConstant = Record[1] & 1;
3488 bool explicitType = Record[1] & 2;
3489 unsigned AddressSpace;
3490 if (explicitType) {
3491 AddressSpace = Record[1] >> 2;
3492 } else {
3493 if (!Ty->isPointerTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003494 return error("Invalid type for value");
David Blaikie1a848da2015-04-27 19:58:56 +00003495 AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
3496 Ty = cast<PointerType>(Ty)->getElementType();
3497 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003498
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003499 uint64_t RawLinkage = Record[3];
3500 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
JF Bastien30bf96b2015-02-22 19:32:03 +00003501 unsigned Alignment;
3502 if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
3503 return EC;
Chris Lattner1314b992007-04-22 06:23:29 +00003504 std::string Section;
3505 if (Record[5]) {
3506 if (Record[5]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003507 return error("Invalid ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003508 Section = SectionTable[Record[5]-1];
3509 }
Chris Lattner4b00d922007-04-23 16:04:05 +00003510 GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003511 // Local linkage must have default visibility.
3512 if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
3513 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003514 Visibility = getDecodedVisibility(Record[6]);
Hans Wennborgcbe34b42012-06-23 11:37:03 +00003515
3516 GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
Chris Lattner53862f72007-05-06 19:27:46 +00003517 if (Record.size() > 7)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003518 TLM = getDecodedThreadLocalMode(Record[7]);
Chris Lattner1314b992007-04-22 06:23:29 +00003519
Rafael Espindola45e6c192011-01-08 16:42:36 +00003520 bool UnnamedAddr = false;
3521 if (Record.size() > 8)
3522 UnnamedAddr = Record[8];
3523
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003524 bool ExternallyInitialized = false;
3525 if (Record.size() > 9)
3526 ExternallyInitialized = Record[9];
3527
Chris Lattner1314b992007-04-22 06:23:29 +00003528 GlobalVariable *NewGV =
Craig Topper2617dcc2014-04-15 06:32:26 +00003529 new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
Michael Gottesman27e7ef32013-02-05 05:57:38 +00003530 TLM, AddressSpace, ExternallyInitialized);
Chris Lattner1314b992007-04-22 06:23:29 +00003531 NewGV->setAlignment(Alignment);
3532 if (!Section.empty())
3533 NewGV->setSection(Section);
3534 NewGV->setVisibility(Visibility);
Rafael Espindola45e6c192011-01-08 16:42:36 +00003535 NewGV->setUnnamedAddr(UnnamedAddr);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003536
Nico Rieck7157bb72014-01-14 15:22:47 +00003537 if (Record.size() > 10)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003538 NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003539 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003540 upgradeDLLImportExportLinkage(NewGV, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003541
Chris Lattnerccaa4482007-04-23 21:26:05 +00003542 ValueList.push_back(NewGV);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003543
Chris Lattner47d131b2007-04-24 00:18:21 +00003544 // Remember which value to use for the global initializer.
3545 if (unsigned InitID = Record[2])
3546 GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
David Majnemerdad0a642014-06-27 18:19:56 +00003547
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003548 if (Record.size() > 11) {
David Majnemerdad0a642014-06-27 18:19:56 +00003549 if (unsigned ComdatID = Record[11]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003550 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003551 return error("Invalid global variable comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003552 NewGV->setComdat(ComdatList[ComdatID - 1]);
3553 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003554 } else if (hasImplicitComdat(RawLinkage)) {
3555 NewGV->setComdat(reinterpret_cast<Comdat *>(1));
3556 }
Chris Lattner1314b992007-04-22 06:23:29 +00003557 break;
3558 }
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003559 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
Nico Rieck7157bb72014-01-14 15:22:47 +00003560 // alignment, section, visibility, gc, unnamed_addr,
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003561 // prologuedata, dllstorageclass, comdat, prefixdata]
Chris Lattner1314b992007-04-22 06:23:29 +00003562 case bitc::MODULE_CODE_FUNCTION: {
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003563 if (Record.size() < 8)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003564 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00003565 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003566 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003567 return error("Invalid record");
David Blaikie561a1572015-04-17 16:28:26 +00003568 if (auto *PTy = dyn_cast<PointerType>(Ty))
3569 Ty = PTy->getElementType();
3570 auto *FTy = dyn_cast<FunctionType>(Ty);
Chris Lattner1314b992007-04-22 06:23:29 +00003571 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003572 return error("Invalid type for value");
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003573 auto CC = static_cast<CallingConv::ID>(Record[1]);
3574 if (CC & ~CallingConv::MaxID)
3575 return error("Invalid calling convention ID");
Chris Lattner1314b992007-04-22 06:23:29 +00003576
Gabor Greife9ecc682008-04-06 20:25:17 +00003577 Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
3578 "", TheModule);
Chris Lattner1314b992007-04-22 06:23:29 +00003579
Vedant Kumarad6d6e72015-10-27 21:17:06 +00003580 Func->setCallingConv(CC);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003581 bool isProto = Record[2];
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003582 uint64_t RawLinkage = Record[3];
3583 Func->setLinkage(getDecodedLinkage(RawLinkage));
Devang Patel4c758ea2008-09-25 21:00:45 +00003584 Func->setAttributes(getAttributes(Record[4]));
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003585
JF Bastien30bf96b2015-02-22 19:32:03 +00003586 unsigned Alignment;
3587 if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
3588 return EC;
3589 Func->setAlignment(Alignment);
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003590 if (Record[6]) {
3591 if (Record[6]-1 >= SectionTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003592 return error("Invalid ID");
Chris Lattner4c0a6d62007-05-08 05:38:01 +00003593 Func->setSection(SectionTable[Record[6]-1]);
Chris Lattner1314b992007-04-22 06:23:29 +00003594 }
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003595 // Local linkage must have default visibility.
3596 if (!Func->hasLocalLinkage())
3597 // FIXME: Change to an error if non-default in 4.0.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003598 Func->setVisibility(getDecodedVisibility(Record[7]));
Gordon Henriksen71183b62007-12-10 03:18:06 +00003599 if (Record.size() > 8 && Record[8]) {
Filipe Cabecinhasf8a16a92015-04-30 04:09:41 +00003600 if (Record[8]-1 >= GCTable.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003601 return error("Invalid ID");
Gordon Henriksend930f912008-08-17 18:44:35 +00003602 Func->setGC(GCTable[Record[8]-1].c_str());
Gordon Henriksen71183b62007-12-10 03:18:06 +00003603 }
Rafael Espindola45e6c192011-01-08 16:42:36 +00003604 bool UnnamedAddr = false;
3605 if (Record.size() > 9)
3606 UnnamedAddr = Record[9];
3607 Func->setUnnamedAddr(UnnamedAddr);
Peter Collingbourne3fa50f92013-09-16 01:08:15 +00003608 if (Record.size() > 10 && Record[10] != 0)
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003609 FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
Nico Rieck7157bb72014-01-14 15:22:47 +00003610
3611 if (Record.size() > 11)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003612 Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003613 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003614 upgradeDLLImportExportLinkage(Func, RawLinkage);
Nico Rieck7157bb72014-01-14 15:22:47 +00003615
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003616 if (Record.size() > 12) {
David Majnemerdad0a642014-06-27 18:19:56 +00003617 if (unsigned ComdatID = Record[12]) {
Filipe Cabecinhas0eb8a592015-05-26 23:00:56 +00003618 if (ComdatID > ComdatList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003619 return error("Invalid function comdat ID");
David Majnemerdad0a642014-06-27 18:19:56 +00003620 Func->setComdat(ComdatList[ComdatID - 1]);
3621 }
Rafael Espindola12ca34f2015-01-19 15:16:06 +00003622 } else if (hasImplicitComdat(RawLinkage)) {
3623 Func->setComdat(reinterpret_cast<Comdat *>(1));
3624 }
David Majnemerdad0a642014-06-27 18:19:56 +00003625
Peter Collingbourne51d2de72014-12-03 02:08:38 +00003626 if (Record.size() > 13 && Record[13] != 0)
3627 FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
3628
David Majnemer7fddecc2015-06-17 20:52:32 +00003629 if (Record.size() > 14 && Record[14] != 0)
3630 FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
3631
Chris Lattnerccaa4482007-04-23 21:26:05 +00003632 ValueList.push_back(Func);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003633
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003634 // If this is a function with a body, remember the prototype we are
3635 // creating now, so that we can match up the body with them later.
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003636 if (!isProto) {
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00003637 Func->setIsMaterializable(true);
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003638 FunctionsWithBodies.push_back(Func);
Rafael Espindola1c863ca2015-06-22 18:06:15 +00003639 DeferredFunctionInfo[Func] = 0;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00003640 }
Chris Lattner1314b992007-04-22 06:23:29 +00003641 break;
3642 }
David Blaikie6a51dbd2015-09-17 22:18:59 +00003643 // ALIAS: [alias type, addrspace, aliasee val#, linkage]
3644 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
3645 case bitc::MODULE_CODE_ALIAS:
3646 case bitc::MODULE_CODE_ALIAS_OLD: {
3647 bool NewRecord = BitCode == bitc::MODULE_CODE_ALIAS;
Aaron Ballman2d0f38c2015-09-18 13:31:42 +00003648 if (Record.size() < (3 + (unsigned)NewRecord))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003649 return error("Invalid record");
David Blaikie6a51dbd2015-09-17 22:18:59 +00003650 unsigned OpNum = 0;
3651 Type *Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00003652 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003653 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003654
David Blaikie6a51dbd2015-09-17 22:18:59 +00003655 unsigned AddrSpace;
3656 if (!NewRecord) {
3657 auto *PTy = dyn_cast<PointerType>(Ty);
3658 if (!PTy)
3659 return error("Invalid type for value");
3660 Ty = PTy->getElementType();
3661 AddrSpace = PTy->getAddressSpace();
3662 } else {
3663 AddrSpace = Record[OpNum++];
3664 }
3665
3666 auto Val = Record[OpNum++];
3667 auto Linkage = Record[OpNum++];
3668 auto *NewGA = GlobalAlias::create(
3669 Ty, AddrSpace, getDecodedLinkage(Linkage), "", TheModule);
Anton Korobeynikov2f22e3f2008-03-12 00:49:19 +00003670 // Old bitcode files didn't have visibility field.
Duncan P. N. Exon Smithb80de102014-05-07 22:57:20 +00003671 // Local linkage must have default visibility.
David Blaikie6a51dbd2015-09-17 22:18:59 +00003672 if (OpNum != Record.size()) {
3673 auto VisInd = OpNum++;
3674 if (!NewGA->hasLocalLinkage())
3675 // FIXME: Change to an error if non-default in 4.0.
3676 NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
3677 }
3678 if (OpNum != Record.size())
3679 NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
Nico Rieck7157bb72014-01-14 15:22:47 +00003680 else
David Blaikie6a51dbd2015-09-17 22:18:59 +00003681 upgradeDLLImportExportLinkage(NewGA, Linkage);
3682 if (OpNum != Record.size())
3683 NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
3684 if (OpNum != Record.size())
3685 NewGA->setUnnamedAddr(Record[OpNum++]);
Chris Lattner44c17072007-04-26 02:46:40 +00003686 ValueList.push_back(NewGA);
David Blaikie6a51dbd2015-09-17 22:18:59 +00003687 AliasInits.push_back(std::make_pair(NewGA, Val));
Chris Lattner44c17072007-04-26 02:46:40 +00003688 break;
Chris Lattner1314b992007-04-22 06:23:29 +00003689 }
Chris Lattner831d4202007-04-26 03:27:58 +00003690 /// MODULE_CODE_PURGEVALS: [numvals]
3691 case bitc::MODULE_CODE_PURGEVALS:
3692 // Trim down the value list to the specified size.
3693 if (Record.size() < 1 || Record[0] > ValueList.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003694 return error("Invalid record");
Chris Lattner831d4202007-04-26 03:27:58 +00003695 ValueList.shrinkTo(Record[0]);
3696 break;
Teresa Johnsonff642b92015-09-17 20:12:00 +00003697 /// MODULE_CODE_VSTOFFSET: [offset]
3698 case bitc::MODULE_CODE_VSTOFFSET:
3699 if (Record.size() < 1)
3700 return error("Invalid record");
3701 VSTOffset = Record[0];
3702 break;
Teresa Johnsone1164de2016-02-10 21:55:02 +00003703 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
3704 case bitc::MODULE_CODE_SOURCE_FILENAME:
3705 SmallString<128> ValueName;
3706 if (convertToString(Record, 0, ValueName))
3707 return error("Invalid record");
3708 TheModule->setSourceFileName(ValueName);
3709 break;
Chris Lattner831d4202007-04-26 03:27:58 +00003710 }
Chris Lattner1314b992007-04-22 06:23:29 +00003711 Record.clear();
3712 }
Chris Lattner1314b992007-04-22 06:23:29 +00003713}
3714
Teresa Johnson403a7872015-10-04 14:33:43 +00003715/// Helper to read the header common to all bitcode files.
3716static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
3717 // Sniff for the signature.
3718 if (Stream.Read(8) != 'B' ||
3719 Stream.Read(8) != 'C' ||
3720 Stream.Read(4) != 0x0 ||
3721 Stream.Read(4) != 0xC ||
3722 Stream.Read(4) != 0xE ||
3723 Stream.Read(4) != 0xD)
3724 return false;
3725 return true;
3726}
3727
Rafael Espindola1aabf982015-06-16 23:29:49 +00003728std::error_code
3729BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
3730 Module *M, bool ShouldLazyLoadMetadata) {
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003731 TheModule = M;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003732
Rafael Espindola1aabf982015-06-16 23:29:49 +00003733 if (std::error_code EC = initStream(std::move(Streamer)))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003734 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003735
Chris Lattner1314b992007-04-22 06:23:29 +00003736 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003737 if (!hasValidBitcodeHeader(Stream))
3738 return error("Invalid bitcode signature");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003739
Chris Lattner1314b992007-04-22 06:23:29 +00003740 // We expect a number of well-defined blocks, though we don't necessarily
3741 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003742 while (1) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003743 if (Stream.AtEndOfStream()) {
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003744 // We didn't really read a proper Module.
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003745 return error("Malformed IR file");
Filipe Cabecinhas22554272015-04-14 14:07:15 +00003746 }
Joe Abbey97b7a172013-02-06 22:14:06 +00003747
Chris Lattner27d38752013-01-20 02:13:19 +00003748 BitstreamEntry Entry =
3749 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
Joe Abbey97b7a172013-02-06 22:14:06 +00003750
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003751 if (Entry.Kind != BitstreamEntry::SubBlock)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003752 return error("Malformed block");
Joe Abbey97b7a172013-02-06 22:14:06 +00003753
Mehdi Amini5d303282015-10-26 18:37:00 +00003754 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3755 parseBitcodeVersion();
3756 continue;
3757 }
3758
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003759 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Teresa Johnson1493ad92015-10-10 14:18:36 +00003760 return parseModule(0, ShouldLazyLoadMetadata);
Joe Abbey97b7a172013-02-06 22:14:06 +00003761
Rafael Espindolac6afe0d2015-06-16 20:03:39 +00003762 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003763 return error("Invalid record");
Chris Lattner1314b992007-04-22 06:23:29 +00003764 }
Chris Lattner1314b992007-04-22 06:23:29 +00003765}
Chris Lattner6694f602007-04-29 07:54:31 +00003766
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003767ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
Bill Wendling0198ce02010-10-06 01:22:42 +00003768 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003769 return error("Invalid record");
Bill Wendling0198ce02010-10-06 01:22:42 +00003770
3771 SmallVector<uint64_t, 64> Record;
3772
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003773 std::string Triple;
Bill Wendling0198ce02010-10-06 01:22:42 +00003774 // Read all the records for this module.
Chris Lattner27d38752013-01-20 02:13:19 +00003775 while (1) {
3776 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003777
Chris Lattner27d38752013-01-20 02:13:19 +00003778 switch (Entry.Kind) {
3779 case BitstreamEntry::SubBlock: // Handled for us already.
3780 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003781 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003782 case BitstreamEntry::EndBlock:
Rafael Espindolae6107792014-07-04 20:05:56 +00003783 return Triple;
Chris Lattner27d38752013-01-20 02:13:19 +00003784 case BitstreamEntry::Record:
3785 // The interesting case.
3786 break;
Bill Wendling0198ce02010-10-06 01:22:42 +00003787 }
3788
3789 // Read a record.
Chris Lattner27d38752013-01-20 02:13:19 +00003790 switch (Stream.readRecord(Entry.ID, Record)) {
Bill Wendling0198ce02010-10-06 01:22:42 +00003791 default: break; // Default behavior, ignore unknown content.
Bill Wendling0198ce02010-10-06 01:22:42 +00003792 case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003793 std::string S;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003794 if (convertToString(Record, 0, S))
3795 return error("Invalid record");
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003796 Triple = S;
Bill Wendling0198ce02010-10-06 01:22:42 +00003797 break;
3798 }
3799 }
3800 Record.clear();
3801 }
Rafael Espindolae6107792014-07-04 20:05:56 +00003802 llvm_unreachable("Exit infinite loop");
Bill Wendling0198ce02010-10-06 01:22:42 +00003803}
3804
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00003805ErrorOr<std::string> BitcodeReader::parseTriple() {
Rafael Espindola1aabf982015-06-16 23:29:49 +00003806 if (std::error_code EC = initStream(nullptr))
Rafael Espindola48da4f42013-11-04 16:16:24 +00003807 return EC;
Bill Wendling0198ce02010-10-06 01:22:42 +00003808
3809 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00003810 if (!hasValidBitcodeHeader(Stream))
3811 return error("Invalid bitcode signature");
Bill Wendling0198ce02010-10-06 01:22:42 +00003812
3813 // We expect a number of well-defined blocks, though we don't necessarily
3814 // need to understand them all.
Chris Lattner27d38752013-01-20 02:13:19 +00003815 while (1) {
3816 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003817
Chris Lattner27d38752013-01-20 02:13:19 +00003818 switch (Entry.Kind) {
3819 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003820 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003821 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003822 return std::error_code();
Joe Abbey97b7a172013-02-06 22:14:06 +00003823
Chris Lattner27d38752013-01-20 02:13:19 +00003824 case BitstreamEntry::SubBlock:
3825 if (Entry.ID == bitc::MODULE_BLOCK_ID)
Rafael Espindolad346cc82014-07-04 13:52:01 +00003826 return parseModuleTriple();
Joe Abbey97b7a172013-02-06 22:14:06 +00003827
Chris Lattner27d38752013-01-20 02:13:19 +00003828 // Ignore other sub-blocks.
Rafael Espindola48da4f42013-11-04 16:16:24 +00003829 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003830 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003831 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00003832
Chris Lattner27d38752013-01-20 02:13:19 +00003833 case BitstreamEntry::Record:
3834 Stream.skipRecord(Entry.ID);
3835 continue;
Bill Wendling0198ce02010-10-06 01:22:42 +00003836 }
3837 }
Bill Wendling0198ce02010-10-06 01:22:42 +00003838}
3839
Mehdi Amini3383ccc2015-11-09 02:46:41 +00003840ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
3841 if (std::error_code EC = initStream(nullptr))
3842 return EC;
3843
3844 // Sniff for the signature.
3845 if (!hasValidBitcodeHeader(Stream))
3846 return error("Invalid bitcode signature");
3847
3848 // We expect a number of well-defined blocks, though we don't necessarily
3849 // need to understand them all.
3850 while (1) {
3851 BitstreamEntry Entry = Stream.advance();
3852 switch (Entry.Kind) {
3853 case BitstreamEntry::Error:
3854 return error("Malformed block");
3855 case BitstreamEntry::EndBlock:
3856 return std::error_code();
3857
3858 case BitstreamEntry::SubBlock:
3859 if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
3860 if (std::error_code EC = parseBitcodeVersion())
3861 return EC;
3862 return ProducerIdentification;
3863 }
3864 // Ignore other sub-blocks.
3865 if (Stream.SkipBlock())
3866 return error("Malformed block");
3867 continue;
3868 case BitstreamEntry::Record:
3869 Stream.skipRecord(Entry.ID);
3870 continue;
3871 }
3872 }
3873}
3874
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003875/// Parse metadata attachments.
3876std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
Devang Patelaf206b82009-09-18 19:26:43 +00003877 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003878 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003879
Devang Patelaf206b82009-09-18 19:26:43 +00003880 SmallVector<uint64_t, 64> Record;
Chris Lattner27d38752013-01-20 02:13:19 +00003881 while (1) {
3882 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
Joe Abbey97b7a172013-02-06 22:14:06 +00003883
Chris Lattner27d38752013-01-20 02:13:19 +00003884 switch (Entry.Kind) {
3885 case BitstreamEntry::SubBlock: // Handled for us already.
3886 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003887 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00003888 case BitstreamEntry::EndBlock:
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00003889 return std::error_code();
Chris Lattner27d38752013-01-20 02:13:19 +00003890 case BitstreamEntry::Record:
3891 // The interesting case.
Devang Patelaf206b82009-09-18 19:26:43 +00003892 break;
3893 }
Chris Lattner27d38752013-01-20 02:13:19 +00003894
Devang Patelaf206b82009-09-18 19:26:43 +00003895 // Read a metadata attachment record.
3896 Record.clear();
Chris Lattner27d38752013-01-20 02:13:19 +00003897 switch (Stream.readRecord(Entry.ID, Record)) {
Devang Patelaf206b82009-09-18 19:26:43 +00003898 default: // Default behavior: ignore.
3899 break;
Chris Lattnerb8778552011-06-17 17:50:30 +00003900 case bitc::METADATA_ATTACHMENT: {
Devang Patelaf206b82009-09-18 19:26:43 +00003901 unsigned RecordLength = Record.size();
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003902 if (Record.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003903 return error("Invalid record");
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003904 if (RecordLength % 2 == 0) {
3905 // A function attachment.
3906 for (unsigned I = 0; I != RecordLength; I += 2) {
3907 auto K = MDKindMap.find(Record[I]);
3908 if (K == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003909 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003910 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
3911 if (!MD)
3912 return error("Invalid metadata attachment");
3913 F.setMetadata(K->second, MD);
Duncan P. N. Exon Smith3d4cd752015-04-24 22:04:41 +00003914 }
3915 continue;
3916 }
3917
3918 // An instruction attachment.
Devang Patelaf206b82009-09-18 19:26:43 +00003919 Instruction *Inst = InstructionList[Record[0]];
3920 for (unsigned i = 1; i != RecordLength; i = i+2) {
Devang Patelb1a44772009-09-28 21:14:55 +00003921 unsigned Kind = Record[i];
Dan Gohman43aa8f02010-07-20 21:42:28 +00003922 DenseMap<unsigned, unsigned>::iterator I =
3923 MDKindMap.find(Kind);
3924 if (I == MDKindMap.end())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003925 return error("Invalid ID");
Justin Bognerae341c62016-03-17 20:12:06 +00003926 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00003927 if (isa<LocalAsMetadata>(Node))
Duncan P. N. Exon Smith35303fd2014-12-06 02:29:44 +00003928 // Drop the attachment. This used to be legal, but there's no
3929 // upgrade path.
3930 break;
Justin Bognerae341c62016-03-17 20:12:06 +00003931 MDNode *MD = dyn_cast_or_null<MDNode>(Node);
3932 if (!MD)
3933 return error("Invalid metadata attachment");
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003934
3935 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
3936 MD = upgradeInstructionLoopAttachment(*MD);
3937
Justin Bognerae341c62016-03-17 20:12:06 +00003938 Inst->setMetadata(I->second, MD);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003939 if (I->second == LLVMContext::MD_tbaa) {
Manman Ren209b17c2013-09-28 00:22:27 +00003940 InstsWithTBAATag.push_back(Inst);
Duncan P. N. Exon Smithefe16c82016-03-25 00:56:13 +00003941 continue;
3942 }
Devang Patelaf206b82009-09-18 19:26:43 +00003943 }
3944 break;
3945 }
3946 }
3947 }
Devang Patelaf206b82009-09-18 19:26:43 +00003948}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00003949
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003950static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
3951 LLVMContext &Context = PtrType->getContext();
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003952 if (!isa<PointerType>(PtrType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003953 return error(Context, "Load/Store operand is not a pointer type");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003954 Type *ElemType = cast<PointerType>(PtrType)->getElementType();
3955
3956 if (ValType && ValType != ElemType)
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003957 return error(Context, "Explicit load/store type does not match pointee "
3958 "type of pointer operand");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003959 if (!PointerType::isLoadableOrStorableType(ElemType))
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00003960 return error(Context, "Cannot load/store from pointer");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00003961 return std::error_code();
3962}
3963
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003964/// Lazily parse the specified function body block.
3965std::error_code BitcodeReader::parseFunctionBody(Function *F) {
Chris Lattner982ec1e2007-05-05 00:17:00 +00003966 if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00003967 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003968
Nick Lewyckya72e1af2010-02-25 08:30:17 +00003969 InstructionList.clear();
Chris Lattner85b7b402007-05-01 05:52:21 +00003970 unsigned ModuleValueListSize = ValueList.size();
Teresa Johnson61b406e2015-12-29 23:00:22 +00003971 unsigned ModuleMetadataListSize = MetadataList.size();
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003972
Chris Lattner85b7b402007-05-01 05:52:21 +00003973 // Add all the function arguments to the value table.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00003974 for (Argument &I : F->args())
3975 ValueList.push_back(&I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00003976
Chris Lattner83930552007-05-01 07:01:57 +00003977 unsigned NextValueNo = ValueList.size();
Craig Topper2617dcc2014-04-15 06:32:26 +00003978 BasicBlock *CurBB = nullptr;
Chris Lattnere53603e2007-05-02 04:27:25 +00003979 unsigned CurBBNo = 0;
3980
Chris Lattner07d09ed2010-04-03 02:17:50 +00003981 DebugLoc LastLoc;
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00003982 auto getLastInstruction = [&]() -> Instruction * {
3983 if (CurBB && !CurBB->empty())
3984 return &CurBB->back();
3985 else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
3986 !FunctionBBs[CurBBNo - 1]->empty())
3987 return &FunctionBBs[CurBBNo - 1]->back();
3988 return nullptr;
3989 };
Michael Ilseman26ee2b82012-11-15 22:34:00 +00003990
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00003991 std::vector<OperandBundleDef> OperandBundles;
3992
Chris Lattner85b7b402007-05-01 05:52:21 +00003993 // Read all the records.
3994 SmallVector<uint64_t, 64> Record;
3995 while (1) {
Chris Lattner27d38752013-01-20 02:13:19 +00003996 BitstreamEntry Entry = Stream.advance();
Joe Abbey97b7a172013-02-06 22:14:06 +00003997
Chris Lattner27d38752013-01-20 02:13:19 +00003998 switch (Entry.Kind) {
3999 case BitstreamEntry::Error:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004000 return error("Malformed block");
Chris Lattner27d38752013-01-20 02:13:19 +00004001 case BitstreamEntry::EndBlock:
4002 goto OutOfRecordLoop;
Joe Abbey97b7a172013-02-06 22:14:06 +00004003
Chris Lattner27d38752013-01-20 02:13:19 +00004004 case BitstreamEntry::SubBlock:
4005 switch (Entry.ID) {
Chris Lattner85b7b402007-05-01 05:52:21 +00004006 default: // Skip unknown content.
4007 if (Stream.SkipBlock())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004008 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004009 break;
4010 case bitc::CONSTANTS_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004011 if (std::error_code EC = parseConstants())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004012 return EC;
Chris Lattner83930552007-05-01 07:01:57 +00004013 NextValueNo = ValueList.size();
Chris Lattner85b7b402007-05-01 05:52:21 +00004014 break;
4015 case bitc::VALUE_SYMTAB_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004016 if (std::error_code EC = parseValueSymbolTable())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004017 return EC;
Chris Lattner85b7b402007-05-01 05:52:21 +00004018 break;
Devang Patelaf206b82009-09-18 19:26:43 +00004019 case bitc::METADATA_ATTACHMENT_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004020 if (std::error_code EC = parseMetadataAttachment(*F))
Rafael Espindola48da4f42013-11-04 16:16:24 +00004021 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004022 break;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004023 case bitc::METADATA_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004024 if (std::error_code EC = parseMetadata())
Rafael Espindola48da4f42013-11-04 16:16:24 +00004025 return EC;
Victor Hernandez108d3ac2010-01-13 19:34:08 +00004026 break;
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004027 case bitc::USELIST_BLOCK_ID:
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004028 if (std::error_code EC = parseUseLists())
Duncan P. N. Exon Smith1f66c852014-07-28 21:19:41 +00004029 return EC;
4030 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004031 }
4032 continue;
Joe Abbey97b7a172013-02-06 22:14:06 +00004033
Chris Lattner27d38752013-01-20 02:13:19 +00004034 case BitstreamEntry::Record:
4035 // The interesting case.
4036 break;
Chris Lattner85b7b402007-05-01 05:52:21 +00004037 }
Joe Abbey97b7a172013-02-06 22:14:06 +00004038
Chris Lattner85b7b402007-05-01 05:52:21 +00004039 // Read a record.
4040 Record.clear();
Craig Topper2617dcc2014-04-15 06:32:26 +00004041 Instruction *I = nullptr;
Chris Lattner27d38752013-01-20 02:13:19 +00004042 unsigned BitCode = Stream.readRecord(Entry.ID, Record);
Dan Gohman0ebd6962009-07-20 21:19:07 +00004043 switch (BitCode) {
Chris Lattner83930552007-05-01 07:01:57 +00004044 default: // Default behavior: reject
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004045 return error("Invalid value");
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004046 case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
Chris Lattner83930552007-05-01 07:01:57 +00004047 if (Record.size() < 1 || Record[0] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004048 return error("Invalid record");
Chris Lattner85b7b402007-05-01 05:52:21 +00004049 // Create all the basic blocks for the function.
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004050 FunctionBBs.resize(Record[0]);
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004051
4052 // See if anything took the address of blocks in this function.
4053 auto BBFRI = BasicBlockFwdRefs.find(F);
4054 if (BBFRI == BasicBlockFwdRefs.end()) {
4055 for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
4056 FunctionBBs[i] = BasicBlock::Create(Context, "", F);
4057 } else {
4058 auto &BBRefs = BBFRI->second;
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004059 // Check for invalid basic block references.
4060 if (BBRefs.size() > FunctionBBs.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004061 return error("Invalid ID");
Duncan P. N. Exon Smith5a5fd7b2014-08-16 01:54:37 +00004062 assert(!BBRefs.empty() && "Unexpected empty array");
4063 assert(!BBRefs.front() && "Invalid reference to entry block");
4064 for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
4065 ++I)
4066 if (I < RE && BBRefs[I]) {
4067 BBRefs[I]->insertInto(F);
4068 FunctionBBs[I] = BBRefs[I];
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004069 } else {
4070 FunctionBBs[I] = BasicBlock::Create(Context, "", F);
4071 }
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004072
4073 // Erase from the table.
4074 BasicBlockFwdRefs.erase(BBFRI);
4075 }
4076
Chris Lattner83930552007-05-01 07:01:57 +00004077 CurBB = FunctionBBs[0];
4078 continue;
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00004079 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004080
Chris Lattner07d09ed2010-04-03 02:17:50 +00004081 case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
4082 // This record indicates that the last instruction is at the same
4083 // location as the previous instruction with a location.
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004084 I = getLastInstruction();
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004085
Craig Topper2617dcc2014-04-15 06:32:26 +00004086 if (!I)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004087 return error("Invalid record");
Chris Lattner07d09ed2010-04-03 02:17:50 +00004088 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004089 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004090 continue;
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004091
Duncan P. N. Exon Smith9ed19662015-01-09 17:53:27 +00004092 case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
Duncan P. N. Exon Smith52d0f162015-01-09 02:51:45 +00004093 I = getLastInstruction();
Craig Topper2617dcc2014-04-15 06:32:26 +00004094 if (!I || Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004095 return error("Invalid record");
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004096
Chris Lattner07d09ed2010-04-03 02:17:50 +00004097 unsigned Line = Record[0], Col = Record[1];
4098 unsigned ScopeID = Record[2], IAID = Record[3];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004099
Craig Topper2617dcc2014-04-15 06:32:26 +00004100 MDNode *Scope = nullptr, *IA = nullptr;
Justin Bognerae341c62016-03-17 20:12:06 +00004101 if (ScopeID) {
4102 Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
4103 if (!Scope)
4104 return error("Invalid record");
4105 }
4106 if (IAID) {
4107 IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
4108 if (!IA)
4109 return error("Invalid record");
4110 }
Chris Lattner07d09ed2010-04-03 02:17:50 +00004111 LastLoc = DebugLoc::get(Line, Col, Scope, IA);
4112 I->setDebugLoc(LastLoc);
Craig Topper2617dcc2014-04-15 06:32:26 +00004113 I = nullptr;
Chris Lattner07d09ed2010-04-03 02:17:50 +00004114 continue;
4115 }
4116
Chris Lattnere9759c22007-05-06 00:21:25 +00004117 case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
4118 unsigned OpNum = 0;
4119 Value *LHS, *RHS;
4120 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004121 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
Dan Gohman0ebd6962009-07-20 21:19:07 +00004122 OpNum+1 > Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004123 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004124
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004125 int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
Rafael Espindola48da4f42013-11-04 16:16:24 +00004126 if (Opc == -1)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004127 return error("Invalid record");
Gabor Greife1f6e4b2008-05-16 19:29:10 +00004128 I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Devang Patelaf206b82009-09-18 19:26:43 +00004129 InstructionList.push_back(I);
Dan Gohman1b849082009-09-07 23:54:19 +00004130 if (OpNum < Record.size()) {
4131 if (Opc == Instruction::Add ||
4132 Opc == Instruction::Sub ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004133 Opc == Instruction::Mul ||
4134 Opc == Instruction::Shl) {
Dan Gohman00f47472010-01-25 21:55:39 +00004135 if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004136 cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
Dan Gohman00f47472010-01-25 21:55:39 +00004137 if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
Dan Gohman1b849082009-09-07 23:54:19 +00004138 cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
Chris Lattner35315d02011-02-06 21:44:57 +00004139 } else if (Opc == Instruction::SDiv ||
Chris Lattnera676c0f2011-02-07 16:40:21 +00004140 Opc == Instruction::UDiv ||
4141 Opc == Instruction::LShr ||
4142 Opc == Instruction::AShr) {
Chris Lattner35315d02011-02-06 21:44:57 +00004143 if (Record[OpNum] & (1 << bitc::PEO_EXACT))
Dan Gohman1b849082009-09-07 23:54:19 +00004144 cast<BinaryOperator>(I)->setIsExact(true);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004145 } else if (isa<FPMathOperator>(I)) {
James Molloy88eb5352015-07-10 12:52:00 +00004146 FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004147 if (FMF.any())
4148 I->setFastMathFlags(FMF);
Dan Gohman1b849082009-09-07 23:54:19 +00004149 }
Michael Ilseman9978d7e2012-11-27 00:43:38 +00004150
Dan Gohman1b849082009-09-07 23:54:19 +00004151 }
Chris Lattner85b7b402007-05-01 05:52:21 +00004152 break;
4153 }
Chris Lattnere9759c22007-05-06 00:21:25 +00004154 case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
4155 unsigned OpNum = 0;
4156 Value *Op;
4157 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
4158 OpNum+2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004159 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004160
Chris Lattner229907c2011-07-18 04:54:35 +00004161 Type *ResTy = getTypeByID(Record[OpNum]);
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004162 int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004163 if (Opc == -1 || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004164 return error("Invalid record");
Craig Topper2617dcc2014-04-15 06:32:26 +00004165 Instruction *Temp = nullptr;
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004166 if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
4167 if (Temp) {
4168 InstructionList.push_back(Temp);
4169 CurBB->getInstList().push_back(Temp);
4170 }
4171 } else {
Filipe Cabecinhasb70fd872015-10-06 12:37:54 +00004172 auto CastOp = (Instruction::CastOps)Opc;
4173 if (!CastInst::castIsValid(CastOp, Op, ResTy))
4174 return error("Invalid cast");
4175 I = CastInst::Create(CastOp, Op, ResTy);
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00004176 }
Devang Patelaf206b82009-09-18 19:26:43 +00004177 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004178 break;
4179 }
David Blaikieb5b5efd2015-02-25 01:08:52 +00004180 case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
4181 case bitc::FUNC_CODE_INST_GEP_OLD:
4182 case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004183 unsigned OpNum = 0;
David Blaikieb5b5efd2015-02-25 01:08:52 +00004184
4185 Type *Ty;
4186 bool InBounds;
4187
4188 if (BitCode == bitc::FUNC_CODE_INST_GEP) {
4189 InBounds = Record[OpNum++];
4190 Ty = getTypeByID(Record[OpNum++]);
4191 } else {
4192 InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
4193 Ty = nullptr;
4194 }
4195
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004196 Value *BasePtr;
4197 if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004198 return error("Invalid record");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004199
David Blaikie60310f22015-05-08 00:42:26 +00004200 if (!Ty)
4201 Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
4202 ->getElementType();
4203 else if (Ty !=
4204 cast<SequentialType>(BasePtr->getType()->getScalarType())
4205 ->getElementType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004206 return error(
David Blaikie675e8cb2015-03-16 21:35:48 +00004207 "Explicit gep type does not match pointee type of pointer operand");
4208
Chris Lattner5285b5e2007-05-02 05:46:45 +00004209 SmallVector<Value*, 16> GEPIdx;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004210 while (OpNum != Record.size()) {
4211 Value *Op;
4212 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004213 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004214 GEPIdx.push_back(Op);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004215 }
4216
David Blaikie096b1da2015-03-14 19:53:33 +00004217 I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
David Blaikie675e8cb2015-03-16 21:35:48 +00004218
Devang Patelaf206b82009-09-18 19:26:43 +00004219 InstructionList.push_back(I);
David Blaikieb5b5efd2015-02-25 01:08:52 +00004220 if (InBounds)
Dan Gohman1b849082009-09-07 23:54:19 +00004221 cast<GetElementPtrInst>(I)->setIsInBounds(true);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004222 break;
4223 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004224
Dan Gohman1ecaf452008-05-31 00:58:22 +00004225 case bitc::FUNC_CODE_INST_EXTRACTVAL: {
4226 // EXTRACTVAL: [opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004227 unsigned OpNum = 0;
4228 Value *Agg;
4229 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004230 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004231
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004232 unsigned RecSize = Record.size();
4233 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004234 return error("EXTRACTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004235
Dan Gohman1ecaf452008-05-31 00:58:22 +00004236 SmallVector<unsigned, 4> EXTRACTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004237 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004238 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004239 bool IsArray = CurTy->isArrayTy();
4240 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004241 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004242
4243 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004244 return error("EXTRACTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004245 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004246 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004247 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004248 return error("EXTRACTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004249 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004250 return error("EXTRACTVAL: Invalid array index");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004251 EXTRACTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004252
4253 if (IsStruct)
4254 CurTy = CurTy->subtypes()[Index];
4255 else
4256 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004257 }
4258
Jay Foad57aa6362011-07-13 10:26:04 +00004259 I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004260 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004261 break;
4262 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004263
Dan Gohman1ecaf452008-05-31 00:58:22 +00004264 case bitc::FUNC_CODE_INST_INSERTVAL: {
4265 // INSERTVAL: [opty, opval, opty, opval, n x indices]
Dan Gohman30499842008-05-23 01:55:30 +00004266 unsigned OpNum = 0;
4267 Value *Agg;
4268 if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004269 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004270 Value *Val;
4271 if (getValueTypePair(Record, OpNum, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004272 return error("Invalid record");
Dan Gohman30499842008-05-23 01:55:30 +00004273
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004274 unsigned RecSize = Record.size();
4275 if (OpNum == RecSize)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004276 return error("INSERTVAL: Invalid instruction with 0 indices");
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004277
Dan Gohman1ecaf452008-05-31 00:58:22 +00004278 SmallVector<unsigned, 4> INSERTVALIdx;
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004279 Type *CurTy = Agg->getType();
Filipe Cabecinhas1c299d02015-05-16 00:33:12 +00004280 for (; OpNum != RecSize; ++OpNum) {
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004281 bool IsArray = CurTy->isArrayTy();
4282 bool IsStruct = CurTy->isStructTy();
Dan Gohman1ecaf452008-05-31 00:58:22 +00004283 uint64_t Index = Record[OpNum];
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004284
4285 if (!IsStruct && !IsArray)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004286 return error("INSERTVAL: Invalid type");
Dan Gohman1ecaf452008-05-31 00:58:22 +00004287 if ((unsigned)Index != Index)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004288 return error("Invalid value");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004289 if (IsStruct && Index >= CurTy->subtypes().size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004290 return error("INSERTVAL: Invalid struct index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004291 if (IsArray && Index >= CurTy->getArrayNumElements())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004292 return error("INSERTVAL: Invalid array index");
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004293
Dan Gohman1ecaf452008-05-31 00:58:22 +00004294 INSERTVALIdx.push_back((unsigned)Index);
Filipe Cabecinhasecf8f7f2015-02-16 00:03:11 +00004295 if (IsStruct)
4296 CurTy = CurTy->subtypes()[Index];
4297 else
4298 CurTy = CurTy->subtypes()[0];
Dan Gohman30499842008-05-23 01:55:30 +00004299 }
4300
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004301 if (CurTy != Val->getType())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004302 return error("Inserted value type doesn't match aggregate type");
Filipe Cabecinhas4708a022015-05-18 22:27:11 +00004303
Jay Foad57aa6362011-07-13 10:26:04 +00004304 I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
Devang Patelaf206b82009-09-18 19:26:43 +00004305 InstructionList.push_back(I);
Dan Gohman30499842008-05-23 01:55:30 +00004306 break;
4307 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004308
Chris Lattnere9759c22007-05-06 00:21:25 +00004309 case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
Dan Gohmanc5d28922008-09-16 01:01:33 +00004310 // obsolete form of select
4311 // handles select i1 ... in old bitcode
Chris Lattnere9759c22007-05-06 00:21:25 +00004312 unsigned OpNum = 0;
4313 Value *TrueVal, *FalseVal, *Cond;
4314 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004315 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
4316 popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004317 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004318
Dan Gohmanc5d28922008-09-16 01:01:33 +00004319 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004320 InstructionList.push_back(I);
Dan Gohmanc5d28922008-09-16 01:01:33 +00004321 break;
4322 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004323
Dan Gohmanc5d28922008-09-16 01:01:33 +00004324 case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
4325 // new form of select
4326 // handles select i1 or select [N x i1]
4327 unsigned OpNum = 0;
4328 Value *TrueVal, *FalseVal, *Cond;
4329 if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004330 popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
Dan Gohmanc5d28922008-09-16 01:01:33 +00004331 getValueTypePair(Record, OpNum, NextValueNo, Cond))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004332 return error("Invalid record");
Dan Gohmanc579d972008-09-09 01:02:47 +00004333
4334 // select condition can be either i1 or [N x i1]
Chris Lattner229907c2011-07-18 04:54:35 +00004335 if (VectorType* vector_type =
4336 dyn_cast<VectorType>(Cond->getType())) {
Dan Gohmanc579d972008-09-09 01:02:47 +00004337 // expect <n x i1>
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004338 if (vector_type->getElementType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004339 return error("Invalid type for value");
Dan Gohmanc579d972008-09-09 01:02:47 +00004340 } else {
4341 // expect i1
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004342 if (Cond->getType() != Type::getInt1Ty(Context))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004343 return error("Invalid type for value");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004344 }
4345
Gabor Greife9ecc682008-04-06 20:25:17 +00004346 I = SelectInst::Create(Cond, TrueVal, FalseVal);
Devang Patelaf206b82009-09-18 19:26:43 +00004347 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004348 break;
4349 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004350
Chris Lattner1fc27f02007-05-02 05:16:49 +00004351 case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004352 unsigned OpNum = 0;
4353 Value *Vec, *Idx;
4354 if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004355 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004356 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004357 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004358 return error("Invalid type for value");
Eric Christopherc9742252009-07-25 02:28:41 +00004359 I = ExtractElementInst::Create(Vec, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004360 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004361 break;
4362 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004363
Chris Lattner1fc27f02007-05-02 05:16:49 +00004364 case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
Chris Lattnere9759c22007-05-06 00:21:25 +00004365 unsigned OpNum = 0;
4366 Value *Vec, *Elt, *Idx;
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004367 if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004368 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004369 if (!Vec->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004370 return error("Invalid type for value");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004371 if (popValue(Record, OpNum, NextValueNo,
Chris Lattnere9759c22007-05-06 00:21:25 +00004372 cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
Michael J. Spencer1f10c5ea2014-05-01 22:12:39 +00004373 getValueTypePair(Record, OpNum, NextValueNo, Idx))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004374 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004375 I = InsertElementInst::Create(Vec, Elt, Idx);
Devang Patelaf206b82009-09-18 19:26:43 +00004376 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004377 break;
4378 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004379
Chris Lattnere9759c22007-05-06 00:21:25 +00004380 case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
4381 unsigned OpNum = 0;
4382 Value *Vec1, *Vec2, *Mask;
4383 if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00004384 popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004385 return error("Invalid record");
Chris Lattnere9759c22007-05-06 00:21:25 +00004386
Mon P Wang25f01062008-11-10 04:46:22 +00004387 if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004388 return error("Invalid record");
Filipe Cabecinhasff1e2342015-04-24 11:30:15 +00004389 if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004390 return error("Invalid type for value");
Chris Lattner1fc27f02007-05-02 05:16:49 +00004391 I = new ShuffleVectorInst(Vec1, Vec2, Mask);
Devang Patelaf206b82009-09-18 19:26:43 +00004392 InstructionList.push_back(I);
Chris Lattner1fc27f02007-05-02 05:16:49 +00004393 break;
4394 }
Mon P Wang25f01062008-11-10 04:46:22 +00004395
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004396 case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
4397 // Old form of ICmp/FCmp returning bool
4398 // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
4399 // both legal on vectors but had different behaviour.
4400 case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
4401 // FCmp/ICmp returning bool or vector of bool
4402
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004403 unsigned OpNum = 0;
4404 Value *LHS, *RHS;
4405 if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
James Molloy88eb5352015-07-10 12:52:00 +00004406 popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
4407 return error("Invalid record");
4408
4409 unsigned PredVal = Record[OpNum];
4410 bool IsFP = LHS->getType()->isFPOrFPVectorTy();
4411 FastMathFlags FMF;
4412 if (IsFP && Record.size() > OpNum+1)
4413 FMF = getDecodedFastMathFlags(Record[++OpNum]);
4414
4415 if (OpNum+1 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004416 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004417
Duncan Sands9dff9be2010-02-15 16:12:20 +00004418 if (LHS->getType()->isFPOrFPVectorTy())
James Molloy88eb5352015-07-10 12:52:00 +00004419 I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004420 else
James Molloy88eb5352015-07-10 12:52:00 +00004421 I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
4422
4423 if (FMF.any())
4424 I->setFastMathFlags(FMF);
Devang Patelaf206b82009-09-18 19:26:43 +00004425 InstructionList.push_back(I);
Dan Gohmanc579d972008-09-09 01:02:47 +00004426 break;
4427 }
Nick Lewyckya21d3da2009-07-08 03:04:38 +00004428
Chris Lattnere53603e2007-05-02 04:27:25 +00004429 case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
Devang Patelbbfd8742008-02-26 01:29:32 +00004430 {
4431 unsigned Size = Record.size();
4432 if (Size == 0) {
Owen Anderson55f1c092009-08-13 21:58:54 +00004433 I = ReturnInst::Create(Context);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004434 InstructionList.push_back(I);
Devang Patelbbfd8742008-02-26 01:29:32 +00004435 break;
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004436 }
Devang Patelbbfd8742008-02-26 01:29:32 +00004437
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004438 unsigned OpNum = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004439 Value *Op = nullptr;
Chris Lattnerf1c87102011-06-17 18:09:11 +00004440 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004441 return error("Invalid record");
Chris Lattnerf1c87102011-06-17 18:09:11 +00004442 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004443 return error("Invalid record");
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004444
Chris Lattnerf1c87102011-06-17 18:09:11 +00004445 I = ReturnInst::Create(Context, Op);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004446 InstructionList.push_back(I);
Dan Gohmanfa1211f2008-07-23 00:34:11 +00004447 break;
Chris Lattnere53603e2007-05-02 04:27:25 +00004448 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004449 case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
Chris Lattner6ce15cb2007-05-03 22:09:51 +00004450 if (Record.size() != 1 && Record.size() != 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004451 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004452 BasicBlock *TrueDest = getBasicBlock(Record[0]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004453 if (!TrueDest)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004454 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004455
Devang Patelaf206b82009-09-18 19:26:43 +00004456 if (Record.size() == 1) {
Gabor Greife9ecc682008-04-06 20:25:17 +00004457 I = BranchInst::Create(TrueDest);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004458 InstructionList.push_back(I);
Devang Patelaf206b82009-09-18 19:26:43 +00004459 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004460 else {
4461 BasicBlock *FalseDest = getBasicBlock(Record[1]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004462 Value *Cond = getValue(Record, 2, NextValueNo,
4463 Type::getInt1Ty(Context));
Craig Topper2617dcc2014-04-15 06:32:26 +00004464 if (!FalseDest || !Cond)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004465 return error("Invalid record");
Gabor Greife9ecc682008-04-06 20:25:17 +00004466 I = BranchInst::Create(TrueDest, FalseDest, Cond);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004467 InstructionList.push_back(I);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004468 }
4469 break;
4470 }
David Majnemerb01aa9f2015-08-23 19:22:31 +00004471 case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004472 if (Record.size() != 1 && Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004473 return error("Invalid record");
4474 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004475 Value *CleanupPad =
4476 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004477 if (!CleanupPad)
David Majnemer654e1302015-07-31 17:58:14 +00004478 return error("Invalid record");
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004479 BasicBlock *UnwindDest = nullptr;
4480 if (Record.size() == 2) {
David Majnemer654e1302015-07-31 17:58:14 +00004481 UnwindDest = getBasicBlock(Record[Idx++]);
4482 if (!UnwindDest)
4483 return error("Invalid record");
4484 }
4485
David Majnemer8a1c45d2015-12-12 05:38:55 +00004486 I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
David Majnemer654e1302015-07-31 17:58:14 +00004487 InstructionList.push_back(I);
4488 break;
4489 }
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004490 case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
4491 if (Record.size() != 2)
David Majnemer654e1302015-07-31 17:58:14 +00004492 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004493 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004494 Value *CatchPad =
4495 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
Joseph Tremoulet8220bcc2015-08-23 00:26:33 +00004496 if (!CatchPad)
4497 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004498 BasicBlock *BB = getBasicBlock(Record[Idx++]);
David Majnemer654e1302015-07-31 17:58:14 +00004499 if (!BB)
4500 return error("Invalid record");
David Majnemer0bc0eef2015-08-15 02:46:08 +00004501
David Majnemer8a1c45d2015-12-12 05:38:55 +00004502 I = CatchReturnInst::Create(CatchPad, BB);
David Majnemer654e1302015-07-31 17:58:14 +00004503 InstructionList.push_back(I);
4504 break;
4505 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004506 case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
4507 // We must have, at minimum, the outer scope and the number of arguments.
4508 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004509 return error("Invalid record");
4510
David Majnemer654e1302015-07-31 17:58:14 +00004511 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004512
4513 Value *ParentPad =
4514 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4515
4516 unsigned NumHandlers = Record[Idx++];
4517
4518 SmallVector<BasicBlock *, 2> Handlers;
4519 for (unsigned Op = 0; Op != NumHandlers; ++Op) {
4520 BasicBlock *BB = getBasicBlock(Record[Idx++]);
4521 if (!BB)
David Majnemer654e1302015-07-31 17:58:14 +00004522 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004523 Handlers.push_back(BB);
4524 }
4525
4526 BasicBlock *UnwindDest = nullptr;
4527 if (Idx + 1 == Record.size()) {
David Majnemer654e1302015-07-31 17:58:14 +00004528 UnwindDest = getBasicBlock(Record[Idx++]);
4529 if (!UnwindDest)
4530 return error("Invalid record");
4531 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004532
4533 if (Record.size() != Idx)
4534 return error("Invalid record");
4535
4536 auto *CatchSwitch =
4537 CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
4538 for (BasicBlock *Handler : Handlers)
4539 CatchSwitch->addHandler(Handler);
4540 I = CatchSwitch;
4541 InstructionList.push_back(I);
4542 break;
4543 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004544 case bitc::FUNC_CODE_INST_CATCHPAD:
4545 case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
4546 // We must have, at minimum, the outer scope and the number of arguments.
4547 if (Record.size() < 2)
David Majnemer654e1302015-07-31 17:58:14 +00004548 return error("Invalid record");
David Majnemer8a1c45d2015-12-12 05:38:55 +00004549
David Majnemer654e1302015-07-31 17:58:14 +00004550 unsigned Idx = 0;
David Majnemer8a1c45d2015-12-12 05:38:55 +00004551
4552 Value *ParentPad =
4553 getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
4554
David Majnemer654e1302015-07-31 17:58:14 +00004555 unsigned NumArgOperands = Record[Idx++];
David Majnemer8a1c45d2015-12-12 05:38:55 +00004556
David Majnemer654e1302015-07-31 17:58:14 +00004557 SmallVector<Value *, 2> Args;
4558 for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
4559 Value *Val;
4560 if (getValueTypePair(Record, Idx, NextValueNo, Val))
4561 return error("Invalid record");
4562 Args.push_back(Val);
4563 }
David Majnemer8a1c45d2015-12-12 05:38:55 +00004564
David Majnemer654e1302015-07-31 17:58:14 +00004565 if (Record.size() != Idx)
4566 return error("Invalid record");
4567
David Majnemer8a1c45d2015-12-12 05:38:55 +00004568 if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
4569 I = CleanupPadInst::Create(ParentPad, Args);
4570 else
4571 I = CatchPadInst::Create(ParentPad, Args);
Joseph Tremoulet9ce71f72015-09-03 09:09:43 +00004572 InstructionList.push_back(I);
4573 break;
4574 }
Chris Lattner3ed871f2009-10-27 19:13:16 +00004575 case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004576 // Check magic
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004577 if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
Bob Wilsone4077362013-09-09 19:14:35 +00004578 // "New" SwitchInst format with case ranges. The changes to write this
4579 // format were reverted but we still recognize bitcode that uses it.
4580 // Hopefully someday we will have support for case ranges and can use
4581 // this format again.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004582
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004583 Type *OpTy = getTypeByID(Record[1]);
4584 unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
4585
Jan Wen Voungafaced02012-10-11 20:20:40 +00004586 Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004587 BasicBlock *Default = getBasicBlock(Record[3]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004588 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004589 return error("Invalid record");
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004590
4591 unsigned NumCases = Record[4];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004592
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004593 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
4594 InstructionList.push_back(SI);
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004595
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004596 unsigned CurIdx = 5;
4597 for (unsigned i = 0; i != NumCases; ++i) {
Bob Wilsone4077362013-09-09 19:14:35 +00004598 SmallVector<ConstantInt*, 1> CaseVals;
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004599 unsigned NumItems = Record[CurIdx++];
4600 for (unsigned ci = 0; ci != NumItems; ++ci) {
4601 bool isSingleNumber = Record[CurIdx++];
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004602
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004603 APInt Low;
4604 unsigned ActiveWords = 1;
4605 if (ValueBitWidth > 64)
4606 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004607 Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
Benjamin Kramer9704ed02012-05-28 14:10:31 +00004608 ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004609 CurIdx += ActiveWords;
Stepan Dyatkovskiye3e19cb2012-05-28 12:39:09 +00004610
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004611 if (!isSingleNumber) {
4612 ActiveWords = 1;
4613 if (ValueBitWidth > 64)
4614 ActiveWords = Record[CurIdx++];
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004615 APInt High = readWideAPInt(
4616 makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004617 CurIdx += ActiveWords;
Bob Wilsone4077362013-09-09 19:14:35 +00004618
4619 // FIXME: It is not clear whether values in the range should be
4620 // compared as signed or unsigned values. The partially
4621 // implemented changes that used this format in the past used
4622 // unsigned comparisons.
4623 for ( ; Low.ule(High); ++Low)
4624 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004625 } else
Bob Wilsone4077362013-09-09 19:14:35 +00004626 CaseVals.push_back(ConstantInt::get(Context, Low));
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004627 }
4628 BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
Bob Wilsone4077362013-09-09 19:14:35 +00004629 for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
4630 cve = CaseVals.end(); cvi != cve; ++cvi)
4631 SI->addCase(*cvi, DestBB);
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004632 }
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004633 I = SI;
4634 break;
4635 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004636
Stepan Dyatkovskiy0beab5e2012-05-12 10:48:17 +00004637 // Old SwitchInst format without case ranges.
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004638
Chris Lattner5285b5e2007-05-02 05:46:45 +00004639 if (Record.size() < 3 || (Record.size() & 1) == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004640 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004641 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004642 Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004643 BasicBlock *Default = getBasicBlock(Record[2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004644 if (!OpTy || !Cond || !Default)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004645 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004646 unsigned NumCases = (Record.size()-3)/2;
Gabor Greife9ecc682008-04-06 20:25:17 +00004647 SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
Devang Patelaf206b82009-09-18 19:26:43 +00004648 InstructionList.push_back(SI);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004649 for (unsigned i = 0, e = NumCases; i != e; ++i) {
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004650 ConstantInt *CaseVal =
Chris Lattner5285b5e2007-05-02 05:46:45 +00004651 dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
4652 BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
Craig Topper2617dcc2014-04-15 06:32:26 +00004653 if (!CaseVal || !DestBB) {
Chris Lattner5285b5e2007-05-02 05:46:45 +00004654 delete SI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004655 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004656 }
4657 SI->addCase(CaseVal, DestBB);
4658 }
4659 I = SI;
4660 break;
4661 }
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004662 case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
Chris Lattner3ed871f2009-10-27 19:13:16 +00004663 if (Record.size() < 2)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004664 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004665 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00004666 Value *Address = getValue(Record, 1, NextValueNo, OpTy);
Craig Topper2617dcc2014-04-15 06:32:26 +00004667 if (!OpTy || !Address)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004668 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004669 unsigned NumDests = Record.size()-2;
Chris Lattnerd04cb6d2009-10-28 00:19:10 +00004670 IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
Chris Lattner3ed871f2009-10-27 19:13:16 +00004671 InstructionList.push_back(IBI);
4672 for (unsigned i = 0, e = NumDests; i != e; ++i) {
4673 if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
4674 IBI->addDestination(DestBB);
4675 } else {
4676 delete IBI;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004677 return error("Invalid record");
Chris Lattner3ed871f2009-10-27 19:13:16 +00004678 }
4679 }
4680 I = IBI;
4681 break;
4682 }
Michael Ilseman26ee2b82012-11-15 22:34:00 +00004683
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00004684 case bitc::FUNC_CODE_INST_INVOKE: {
4685 // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
Rafael Espindola48da4f42013-11-04 16:16:24 +00004686 if (Record.size() < 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004687 return error("Invalid record");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004688 unsigned OpNum = 0;
4689 AttributeSet PAL = getAttributes(Record[OpNum++]);
4690 unsigned CCInfo = Record[OpNum++];
4691 BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
4692 BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004693
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004694 FunctionType *FTy = nullptr;
4695 if (CCInfo >> 13 & 1 &&
4696 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004697 return error("Explicit invoke type is not a function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004698
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004699 Value *Callee;
4700 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004701 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004702
Chris Lattner229907c2011-07-18 04:54:35 +00004703 PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004704 if (!CalleeTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004705 return error("Callee is not a pointer");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004706 if (!FTy) {
4707 FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
4708 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004709 return error("Callee is not of pointer to function type");
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004710 } else if (CalleeTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004711 return error("Explicit invoke type does not match pointee type of "
David Blaikie5ea1f7b2015-04-24 18:06:06 +00004712 "callee operand");
4713 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004714 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004715
Chris Lattner5285b5e2007-05-02 05:46:45 +00004716 SmallVector<Value*, 16> Ops;
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004717 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004718 Ops.push_back(getValue(Record, OpNum, NextValueNo,
4719 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00004720 if (!Ops.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004721 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004722 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004723
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004724 if (!FTy->isVarArg()) {
4725 if (Record.size() != OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004726 return error("Invalid record");
Chris Lattner5285b5e2007-05-02 05:46:45 +00004727 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004728 // Read type/value pairs for varargs params.
4729 while (OpNum != Record.size()) {
4730 Value *Op;
4731 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004732 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004733 Ops.push_back(Op);
4734 }
Chris Lattner5285b5e2007-05-02 05:46:45 +00004735 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004736
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00004737 I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
4738 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00004739 InstructionList.push_back(I);
Vedant Kumarad6d6e72015-10-27 21:17:06 +00004740 cast<InvokeInst>(I)->setCallingConv(
4741 static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
Devang Patel4c758ea2008-09-25 21:00:45 +00004742 cast<InvokeInst>(I)->setAttributes(PAL);
Chris Lattner5285b5e2007-05-02 05:46:45 +00004743 break;
4744 }
Bill Wendlingf891bf82011-07-31 06:30:59 +00004745 case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
4746 unsigned Idx = 0;
Craig Topper2617dcc2014-04-15 06:32:26 +00004747 Value *Val = nullptr;
Bill Wendlingf891bf82011-07-31 06:30:59 +00004748 if (getValueTypePair(Record, Idx, NextValueNo, Val))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004749 return error("Invalid record");
Bill Wendlingf891bf82011-07-31 06:30:59 +00004750 I = ResumeInst::Create(Val);
Bill Wendlingb9a89992011-09-01 00:50:20 +00004751 InstructionList.push_back(I);
Bill Wendlingf891bf82011-07-31 06:30:59 +00004752 break;
4753 }
Chris Lattnere53603e2007-05-02 04:27:25 +00004754 case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
Owen Anderson55f1c092009-08-13 21:58:54 +00004755 I = new UnreachableInst(Context);
Devang Patelaf206b82009-09-18 19:26:43 +00004756 InstructionList.push_back(I);
Chris Lattnere53603e2007-05-02 04:27:25 +00004757 break;
Chris Lattnere9759c22007-05-06 00:21:25 +00004758 case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
Chris Lattnere14cb882007-05-04 19:11:41 +00004759 if (Record.size() < 1 || ((Record.size()-1)&1))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004760 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00004761 Type *Ty = getTypeByID(Record[0]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004762 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004763 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004764
Jay Foad52131342011-03-30 11:28:46 +00004765 PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
Devang Patelaf206b82009-09-18 19:26:43 +00004766 InstructionList.push_back(PN);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004767
Chris Lattnere14cb882007-05-04 19:11:41 +00004768 for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
Jan Wen Voungafaced02012-10-11 20:20:40 +00004769 Value *V;
4770 // With the new function encoding, it is possible that operands have
4771 // negative IDs (for forward references). Use a signed VBR
4772 // representation to keep the encoding small.
4773 if (UseRelativeIDs)
4774 V = getValueSigned(Record, 1+i, NextValueNo, Ty);
4775 else
4776 V = getValue(Record, 1+i, NextValueNo, Ty);
Chris Lattnere14cb882007-05-04 19:11:41 +00004777 BasicBlock *BB = getBasicBlock(Record[2+i]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004778 if (!V || !BB)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004779 return error("Invalid record");
Chris Lattnerc332bba2007-05-03 18:58:09 +00004780 PN->addIncoming(V, BB);
4781 }
4782 I = PN;
4783 break;
4784 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00004785
David Majnemer7fddecc2015-06-17 20:52:32 +00004786 case bitc::FUNC_CODE_INST_LANDINGPAD:
4787 case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
Bill Wendlingfae14752011-08-12 20:24:12 +00004788 // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
4789 unsigned Idx = 0;
David Majnemer7fddecc2015-06-17 20:52:32 +00004790 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
4791 if (Record.size() < 3)
4792 return error("Invalid record");
4793 } else {
4794 assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
4795 if (Record.size() < 4)
4796 return error("Invalid record");
4797 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004798 Type *Ty = getTypeByID(Record[Idx++]);
Rafael Espindola48da4f42013-11-04 16:16:24 +00004799 if (!Ty)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004800 return error("Invalid record");
David Majnemer7fddecc2015-06-17 20:52:32 +00004801 if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
4802 Value *PersFn = nullptr;
4803 if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
4804 return error("Invalid record");
4805
4806 if (!F->hasPersonalityFn())
4807 F->setPersonalityFn(cast<Constant>(PersFn));
4808 else if (F->getPersonalityFn() != cast<Constant>(PersFn))
4809 return error("Personality function mismatch");
4810 }
Bill Wendlingfae14752011-08-12 20:24:12 +00004811
4812 bool IsCleanup = !!Record[Idx++];
4813 unsigned NumClauses = Record[Idx++];
David Majnemer7fddecc2015-06-17 20:52:32 +00004814 LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
Bill Wendlingfae14752011-08-12 20:24:12 +00004815 LP->setCleanup(IsCleanup);
4816 for (unsigned J = 0; J != NumClauses; ++J) {
4817 LandingPadInst::ClauseType CT =
4818 LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
4819 Value *Val;
4820
4821 if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
4822 delete LP;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004823 return error("Invalid record");
Bill Wendlingfae14752011-08-12 20:24:12 +00004824 }
4825
4826 assert((CT != LandingPadInst::Catch ||
4827 !isa<ArrayType>(Val->getType())) &&
4828 "Catch clause has a invalid type!");
4829 assert((CT != LandingPadInst::Filter ||
4830 isa<ArrayType>(Val->getType())) &&
4831 "Filter clause has invalid type!");
Rafael Espindola4dc5dfc2014-06-04 18:51:31 +00004832 LP->addClause(cast<Constant>(Val));
Bill Wendlingfae14752011-08-12 20:24:12 +00004833 }
4834
4835 I = LP;
Bill Wendlingb9a89992011-09-01 00:50:20 +00004836 InstructionList.push_back(I);
Bill Wendlingfae14752011-08-12 20:24:12 +00004837 break;
4838 }
4839
Chris Lattnerf1c87102011-06-17 18:09:11 +00004840 case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
4841 if (Record.size() != 4)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004842 return error("Invalid record");
JF Bastien30bf96b2015-02-22 19:32:03 +00004843 uint64_t AlignRecord = Record[3];
4844 const uint64_t InAllocaMask = uint64_t(1) << 5;
David Blaikiebdb49102015-04-28 16:51:01 +00004845 const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
Bob Wilson043ee652015-07-28 04:05:45 +00004846 // Reserve bit 7 for SwiftError flag.
4847 // const uint64_t SwiftErrorMask = uint64_t(1) << 7;
David Blaikiebdb49102015-04-28 16:51:01 +00004848 const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
JF Bastien30bf96b2015-02-22 19:32:03 +00004849 bool InAlloca = AlignRecord & InAllocaMask;
David Blaikiebdb49102015-04-28 16:51:01 +00004850 Type *Ty = getTypeByID(Record[0]);
4851 if ((AlignRecord & ExplicitTypeMask) == 0) {
4852 auto *PTy = dyn_cast_or_null<PointerType>(Ty);
4853 if (!PTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004854 return error("Old-style alloca with a non-pointer type");
David Blaikiebdb49102015-04-28 16:51:01 +00004855 Ty = PTy->getElementType();
4856 }
4857 Type *OpTy = getTypeByID(Record[1]);
4858 Value *Size = getFnValueByID(Record[2], OpTy);
JF Bastien30bf96b2015-02-22 19:32:03 +00004859 unsigned Align;
4860 if (std::error_code EC =
David Blaikiebdb49102015-04-28 16:51:01 +00004861 parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
JF Bastien30bf96b2015-02-22 19:32:03 +00004862 return EC;
4863 }
Rafael Espindola48da4f42013-11-04 16:16:24 +00004864 if (!Ty || !Size)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004865 return error("Invalid record");
David Blaikiebdb49102015-04-28 16:51:01 +00004866 AllocaInst *AI = new AllocaInst(Ty, Size, Align);
Reid Kleckner56b56ea2014-07-16 01:34:27 +00004867 AI->setUsedWithInAlloca(InAlloca);
4868 I = AI;
Devang Patelaf206b82009-09-18 19:26:43 +00004869 InstructionList.push_back(I);
Chris Lattnerc332bba2007-05-03 18:58:09 +00004870 break;
4871 }
Chris Lattner9f600c52007-05-03 22:04:19 +00004872 case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
Chris Lattnerdf1233d2007-05-06 00:00:00 +00004873 unsigned OpNum = 0;
4874 Value *Op;
4875 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004876 (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004877 return error("Invalid record");
David Blaikie85035652015-02-25 01:07:20 +00004878
4879 Type *Ty = nullptr;
4880 if (OpNum + 3 == Record.size())
4881 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004882 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004883 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004884 if (!Ty)
4885 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004886
JF Bastien30bf96b2015-02-22 19:32:03 +00004887 unsigned Align;
4888 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4889 return EC;
David Blaikieb7a029872015-04-17 19:56:21 +00004890 I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
David Blaikie85035652015-02-25 01:07:20 +00004891
Devang Patelaf206b82009-09-18 19:26:43 +00004892 InstructionList.push_back(I);
Chris Lattner83930552007-05-01 07:01:57 +00004893 break;
Chris Lattner9f600c52007-05-03 22:04:19 +00004894 }
Eli Friedman59b66882011-08-09 23:02:53 +00004895 case bitc::FUNC_CODE_INST_LOADATOMIC: {
4896 // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
4897 unsigned OpNum = 0;
4898 Value *Op;
4899 if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
David Blaikie85035652015-02-25 01:07:20 +00004900 (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004901 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004902
David Blaikie85035652015-02-25 01:07:20 +00004903 Type *Ty = nullptr;
4904 if (OpNum + 5 == Record.size())
4905 Ty = getTypeByID(Record[OpNum++]);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004906 if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004907 return EC;
4908 if (!Ty)
4909 Ty = cast<PointerType>(Op->getType())->getElementType();
David Blaikie85035652015-02-25 01:07:20 +00004910
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004911 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00004912 if (Ordering == NotAtomic || Ordering == Release ||
4913 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004914 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004915 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004916 return error("Invalid record");
4917 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004918
JF Bastien30bf96b2015-02-22 19:32:03 +00004919 unsigned Align;
4920 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4921 return EC;
4922 I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
David Blaikie85035652015-02-25 01:07:20 +00004923
Eli Friedman59b66882011-08-09 23:02:53 +00004924 InstructionList.push_back(I);
4925 break;
4926 }
David Blaikie612ddbf2015-04-22 04:14:42 +00004927 case bitc::FUNC_CODE_INST_STORE:
4928 case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004929 unsigned OpNum = 0;
4930 Value *Val, *Ptr;
4931 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie612ddbf2015-04-22 04:14:42 +00004932 (BitCode == bitc::FUNC_CODE_INST_STORE
4933 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4934 : popValue(Record, OpNum, NextValueNo,
4935 cast<PointerType>(Ptr->getType())->getElementType(),
4936 Val)) ||
4937 OpNum + 2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004938 return error("Invalid record");
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004939
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004940 if (std::error_code EC =
4941 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004942 return EC;
JF Bastien30bf96b2015-02-22 19:32:03 +00004943 unsigned Align;
4944 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4945 return EC;
4946 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
Devang Patelaf206b82009-09-18 19:26:43 +00004947 InstructionList.push_back(I);
Christopher Lamb54dd24c2007-12-11 08:59:05 +00004948 break;
4949 }
David Blaikie50a06152015-04-22 04:14:46 +00004950 case bitc::FUNC_CODE_INST_STOREATOMIC:
4951 case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
Eli Friedman59b66882011-08-09 23:02:53 +00004952 // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
4953 unsigned OpNum = 0;
4954 Value *Val, *Ptr;
4955 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie50a06152015-04-22 04:14:46 +00004956 (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
4957 ? getValueTypePair(Record, OpNum, NextValueNo, Val)
4958 : popValue(Record, OpNum, NextValueNo,
4959 cast<PointerType>(Ptr->getType())->getElementType(),
4960 Val)) ||
4961 OpNum + 4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004962 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004963
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00004964 if (std::error_code EC =
4965 typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00004966 return EC;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004967 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman222b5a42011-09-19 19:41:28 +00004968 if (Ordering == NotAtomic || Ordering == Acquire ||
Eli Friedman59b66882011-08-09 23:02:53 +00004969 Ordering == AcquireRelease)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004970 return error("Invalid record");
4971 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedman59b66882011-08-09 23:02:53 +00004972 if (Ordering != NotAtomic && Record[OpNum] == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004973 return error("Invalid record");
Eli Friedman59b66882011-08-09 23:02:53 +00004974
JF Bastien30bf96b2015-02-22 19:32:03 +00004975 unsigned Align;
4976 if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
4977 return EC;
4978 I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
Eli Friedman59b66882011-08-09 23:02:53 +00004979 InstructionList.push_back(I);
4980 break;
4981 }
David Blaikie2a661cd2015-04-28 04:30:29 +00004982 case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004983 case bitc::FUNC_CODE_INST_CMPXCHG: {
Tim Northovere94a5182014-03-11 10:48:52 +00004984 // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
Tim Northover420a2162014-06-13 14:24:07 +00004985 // failureordering?, isweak?]
Eli Friedmanc9a551e2011-07-28 21:48:00 +00004986 unsigned OpNum = 0;
4987 Value *Ptr, *Cmp, *New;
4988 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
David Blaikie2a661cd2015-04-28 04:30:29 +00004989 (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
4990 ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
4991 : popValue(Record, OpNum, NextValueNo,
4992 cast<PointerType>(Ptr->getType())->getElementType(),
4993 Cmp)) ||
4994 popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
4995 Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004996 return error("Invalid record");
4997 AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
Tim Northovere94a5182014-03-11 10:48:52 +00004998 if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00004999 return error("Invalid record");
5000 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
Tim Northovere94a5182014-03-11 10:48:52 +00005001
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00005002 if (std::error_code EC =
5003 typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
Filipe Cabecinhas11bb8492015-05-18 21:48:55 +00005004 return EC;
Tim Northovere94a5182014-03-11 10:48:52 +00005005 AtomicOrdering FailureOrdering;
5006 if (Record.size() < 7)
5007 FailureOrdering =
5008 AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
5009 else
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005010 FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
Tim Northovere94a5182014-03-11 10:48:52 +00005011
5012 I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
5013 SynchScope);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005014 cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
Tim Northover420a2162014-06-13 14:24:07 +00005015
5016 if (Record.size() < 8) {
5017 // Before weak cmpxchgs existed, the instruction simply returned the
5018 // value loaded from memory, so bitcode files from that era will be
5019 // expecting the first component of a modern cmpxchg.
5020 CurBB->getInstList().push_back(I);
5021 I = ExtractValueInst::Create(I, 0);
5022 } else {
5023 cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
5024 }
5025
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005026 InstructionList.push_back(I);
5027 break;
5028 }
5029 case bitc::FUNC_CODE_INST_ATOMICRMW: {
5030 // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
5031 unsigned OpNum = 0;
5032 Value *Ptr, *Val;
5033 if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
Jan Wen Voungafaced02012-10-11 20:20:40 +00005034 popValue(Record, OpNum, NextValueNo,
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005035 cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
5036 OpNum+4 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005037 return error("Invalid record");
5038 AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005039 if (Operation < AtomicRMWInst::FIRST_BINOP ||
5040 Operation > AtomicRMWInst::LAST_BINOP)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005041 return error("Invalid record");
5042 AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
Eli Friedman59b66882011-08-09 23:02:53 +00005043 if (Ordering == NotAtomic || Ordering == Unordered)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005044 return error("Invalid record");
5045 SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
Eli Friedmanc9a551e2011-07-28 21:48:00 +00005046 I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
5047 cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
5048 InstructionList.push_back(I);
5049 break;
5050 }
Eli Friedmanfee02c62011-07-25 23:16:38 +00005051 case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
5052 if (2 != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005053 return error("Invalid record");
5054 AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005055 if (Ordering == NotAtomic || Ordering == Unordered ||
5056 Ordering == Monotonic)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005057 return error("Invalid record");
5058 SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
Eli Friedmanfee02c62011-07-25 23:16:38 +00005059 I = new FenceInst(Context, Ordering, SynchScope);
5060 InstructionList.push_back(I);
5061 break;
5062 }
Chris Lattnerc44070802011-06-17 18:17:37 +00005063 case bitc::FUNC_CODE_INST_CALL: {
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005064 // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
Duncan Sandsad0ea2d2007-11-27 13:23:08 +00005065 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005066 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005067
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005068 unsigned OpNum = 0;
5069 AttributeSet PAL = getAttributes(Record[OpNum++]);
5070 unsigned CCInfo = Record[OpNum++];
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005071
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005072 FastMathFlags FMF;
5073 if ((CCInfo >> bitc::CALL_FMF) & 1) {
5074 FMF = getDecodedFastMathFlags(Record[OpNum++]);
5075 if (!FMF.any())
5076 return error("Fast math flags indicator set for call with no FMF");
5077 }
5078
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005079 FunctionType *FTy = nullptr;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005080 if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005081 !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005082 return error("Explicit call type is not a function type");
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005083
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005084 Value *Callee;
5085 if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005086 return error("Invalid record");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005087
Chris Lattner229907c2011-07-18 04:54:35 +00005088 PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005089 if (!OpTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005090 return error("Callee is not a pointer type");
David Blaikie348de692015-04-23 21:36:23 +00005091 if (!FTy) {
5092 FTy = dyn_cast<FunctionType>(OpTy->getElementType());
5093 if (!FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005094 return error("Callee is not of pointer to function type");
David Blaikie348de692015-04-23 21:36:23 +00005095 } else if (OpTy->getElementType() != FTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005096 return error("Explicit call type does not match pointee type of "
David Blaikiedbe6e0f2015-04-17 06:40:14 +00005097 "callee operand");
5098 if (Record.size() < FTy->getNumParams() + OpNum)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005099 return error("Insufficient operands to call");
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005100
Chris Lattner9f600c52007-05-03 22:04:19 +00005101 SmallVector<Value*, 16> Args;
5102 // Read the fixed params.
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005103 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
Chris Lattnerb1ed91f2011-07-09 17:41:24 +00005104 if (FTy->getParamType(i)->isLabelTy())
Dale Johannesen4646aa32007-11-05 21:20:28 +00005105 Args.push_back(getBasicBlock(Record[OpNum]));
Dan Gohmanbbcd04d2010-09-13 18:00:48 +00005106 else
Jan Wen Voungafaced02012-10-11 20:20:40 +00005107 Args.push_back(getValue(Record, OpNum, NextValueNo,
5108 FTy->getParamType(i)));
Craig Topper2617dcc2014-04-15 06:32:26 +00005109 if (!Args.back())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005110 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005111 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005112
Chris Lattner9f600c52007-05-03 22:04:19 +00005113 // Read type/value pairs for varargs params.
Chris Lattner9f600c52007-05-03 22:04:19 +00005114 if (!FTy->isVarArg()) {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005115 if (OpNum != Record.size())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005116 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005117 } else {
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005118 while (OpNum != Record.size()) {
5119 Value *Op;
5120 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005121 return error("Invalid record");
Chris Lattnerdf1233d2007-05-06 00:00:00 +00005122 Args.push_back(Op);
Chris Lattner9f600c52007-05-03 22:04:19 +00005123 }
5124 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005125
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005126 I = CallInst::Create(FTy, Callee, Args, OperandBundles);
5127 OperandBundles.clear();
Devang Patelaf206b82009-09-18 19:26:43 +00005128 InstructionList.push_back(I);
Sandeep Patel68c5f472009-09-02 08:44:58 +00005129 cast<CallInst>(I)->setCallingConv(
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005130 static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
Reid Kleckner5772b772014-04-24 20:14:34 +00005131 CallInst::TailCallKind TCK = CallInst::TCK_None;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005132 if (CCInfo & 1 << bitc::CALL_TAIL)
Reid Kleckner5772b772014-04-24 20:14:34 +00005133 TCK = CallInst::TCK_Tail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005134 if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
Reid Kleckner5772b772014-04-24 20:14:34 +00005135 TCK = CallInst::TCK_MustTail;
Akira Hatanaka97cb3972015-11-07 02:48:49 +00005136 if (CCInfo & (1 << bitc::CALL_NOTAIL))
Akira Hatanaka5cfcce122015-11-06 23:55:38 +00005137 TCK = CallInst::TCK_NoTail;
Reid Kleckner5772b772014-04-24 20:14:34 +00005138 cast<CallInst>(I)->setTailCallKind(TCK);
Devang Patel4c758ea2008-09-25 21:00:45 +00005139 cast<CallInst>(I)->setAttributes(PAL);
Sanjay Patelfa54ace2015-12-14 21:59:03 +00005140 if (FMF.any()) {
5141 if (!isa<FPMathOperator>(I))
5142 return error("Fast-math-flags specified for call without "
5143 "floating-point scalar or vector return type");
5144 I->setFastMathFlags(FMF);
5145 }
Chris Lattner9f600c52007-05-03 22:04:19 +00005146 break;
5147 }
5148 case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
5149 if (Record.size() < 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005150 return error("Invalid record");
Chris Lattner229907c2011-07-18 04:54:35 +00005151 Type *OpTy = getTypeByID(Record[0]);
Jan Wen Voungafaced02012-10-11 20:20:40 +00005152 Value *Op = getValue(Record, 1, NextValueNo, OpTy);
Chris Lattner229907c2011-07-18 04:54:35 +00005153 Type *ResTy = getTypeByID(Record[2]);
Chris Lattner9f600c52007-05-03 22:04:19 +00005154 if (!OpTy || !Op || !ResTy)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005155 return error("Invalid record");
Chris Lattner9f600c52007-05-03 22:04:19 +00005156 I = new VAArgInst(Op, ResTy);
Devang Patelaf206b82009-09-18 19:26:43 +00005157 InstructionList.push_back(I);
Chris Lattner9f600c52007-05-03 22:04:19 +00005158 break;
5159 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005160
5161 case bitc::FUNC_CODE_OPERAND_BUNDLE: {
5162 // A call or an invoke can be optionally prefixed with some variable
5163 // number of operand bundle blocks. These blocks are read into
5164 // OperandBundles and consumed at the next call or invoke instruction.
5165
5166 if (Record.size() < 1 || Record[0] >= BundleTags.size())
5167 return error("Invalid record");
5168
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005169 std::vector<Value *> Inputs;
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005170
5171 unsigned OpNum = 1;
5172 while (OpNum != Record.size()) {
5173 Value *Op;
5174 if (getValueTypePair(Record, OpNum, NextValueNo, Op))
5175 return error("Invalid record");
5176 Inputs.push_back(Op);
5177 }
5178
Sanjoy Dasf79d3442015-11-18 08:30:07 +00005179 OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005180 continue;
5181 }
Chris Lattner83930552007-05-01 07:01:57 +00005182 }
5183
5184 // Add instruction to end of current BB. If there is no current BB, reject
5185 // this file.
Craig Topper2617dcc2014-04-15 06:32:26 +00005186 if (!CurBB) {
Chris Lattner83930552007-05-01 07:01:57 +00005187 delete I;
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005188 return error("Invalid instruction with no BB");
Chris Lattner83930552007-05-01 07:01:57 +00005189 }
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005190 if (!OperandBundles.empty()) {
5191 delete I;
5192 return error("Operand bundles found with no consumer");
5193 }
Chris Lattner83930552007-05-01 07:01:57 +00005194 CurBB->getInstList().push_back(I);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005195
Chris Lattner83930552007-05-01 07:01:57 +00005196 // If this was a terminator instruction, move to the next block.
5197 if (isa<TerminatorInst>(I)) {
5198 ++CurBBNo;
Craig Topper2617dcc2014-04-15 06:32:26 +00005199 CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
Chris Lattner83930552007-05-01 07:01:57 +00005200 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005201
Chris Lattner83930552007-05-01 07:01:57 +00005202 // Non-void values get registered in the value table for future use.
Benjamin Kramerccce8ba2010-01-05 13:12:22 +00005203 if (I && !I->getType()->isVoidTy())
David Majnemer8a1c45d2015-12-12 05:38:55 +00005204 ValueList.assignValue(I, NextValueNo++);
Chris Lattner85b7b402007-05-01 05:52:21 +00005205 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005206
Chris Lattner27d38752013-01-20 02:13:19 +00005207OutOfRecordLoop:
Joe Abbey97b7a172013-02-06 22:14:06 +00005208
Sanjoy Dasb513a9f2015-09-24 23:34:52 +00005209 if (!OperandBundles.empty())
5210 return error("Operand bundles found with no consumer");
5211
Chris Lattner83930552007-05-01 07:01:57 +00005212 // Check the function list for unresolved values.
5213 if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
Craig Topper2617dcc2014-04-15 06:32:26 +00005214 if (!A->getParent()) {
Chris Lattner83930552007-05-01 07:01:57 +00005215 // We found at least one unresolved value. Nuke them all to avoid leaks.
5216 for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
Craig Topper2617dcc2014-04-15 06:32:26 +00005217 if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
Owen Andersonb292b8c2009-07-30 23:03:37 +00005218 A->replaceAllUsesWith(UndefValue::get(A->getType()));
Chris Lattner83930552007-05-01 07:01:57 +00005219 delete A;
5220 }
5221 }
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005222 return error("Never resolved value found in function");
Chris Lattner83930552007-05-01 07:01:57 +00005223 }
Chris Lattner83930552007-05-01 07:01:57 +00005224 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005225
Dan Gohman9b9ff462010-08-25 20:23:38 +00005226 // FIXME: Check for unresolved forward-declared metadata references
5227 // and clean up leaks.
5228
Chris Lattner85b7b402007-05-01 05:52:21 +00005229 // Trim the value list down to the size it was before we parsed this function.
5230 ValueList.shrinkTo(ModuleValueListSize);
Teresa Johnson61b406e2015-12-29 23:00:22 +00005231 MetadataList.shrinkTo(ModuleMetadataListSize);
Chris Lattner85b7b402007-05-01 05:52:21 +00005232 std::vector<BasicBlock*>().swap(FunctionBBs);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005233 return std::error_code();
Chris Lattner51ffe7c2007-05-01 04:59:48 +00005234}
5235
Rafael Espindola7d712032013-11-05 17:16:08 +00005236/// Find the function body in the bitcode stream
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005237std::error_code BitcodeReader::findFunctionInStream(
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005238 Function *F,
5239 DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005240 while (DeferredFunctionInfoIterator->second == 0) {
Teresa Johnsonff642b92015-09-17 20:12:00 +00005241 // This is the fallback handling for the old format bitcode that
Teresa Johnson1493ad92015-10-10 14:18:36 +00005242 // didn't contain the function index in the VST, or when we have
5243 // an anonymous function which would not have a VST entry.
5244 // Assert that we have one of those two cases.
5245 assert(VSTOffset == 0 || !F->hasName());
5246 // Parse the next body in the stream and set its position in the
5247 // DeferredFunctionInfo map.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005248 if (std::error_code EC = rememberAndSkipFunctionBodies())
5249 return EC;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005250 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005251 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005252}
5253
Chris Lattner9eeada92007-05-18 04:02:46 +00005254//===----------------------------------------------------------------------===//
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005255// GVMaterializer implementation
Chris Lattner9eeada92007-05-18 04:02:46 +00005256//===----------------------------------------------------------------------===//
5257
Rafael Espindolac3f9b5a2014-06-23 21:53:12 +00005258void BitcodeReader::releaseBuffer() { Buffer.release(); }
Chris Lattner9eeada92007-05-18 04:02:46 +00005259
Rafael Espindola5a52e6d2014-10-24 22:50:48 +00005260std::error_code BitcodeReader::materialize(GlobalValue *GV) {
Duncan P. N. Exon Smith68f56242016-03-25 01:29:50 +00005261 if (std::error_code EC = materializeMetadata())
5262 return EC;
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005263
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005264 Function *F = dyn_cast<Function>(GV);
5265 // If it's not a function or is already material, ignore the request.
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005266 if (!F || !F->isMaterializable())
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005267 return std::error_code();
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005268
5269 DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
Chris Lattner9eeada92007-05-18 04:02:46 +00005270 assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005271 // If its position is recorded as 0, its body is somewhere in the stream
5272 // but we haven't seen it yet.
Rafael Espindola1c863ca2015-06-22 18:06:15 +00005273 if (DFII->second == 0)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005274 if (std::error_code EC = findFunctionInStream(F, DFII))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005275 return EC;
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005276
Jeffrey Yasskin091217b2010-01-27 20:34:15 +00005277 // Move the bit stream to the saved position of the deferred function body.
5278 Stream.JumpToBit(DFII->second);
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005279
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005280 if (std::error_code EC = parseFunctionBody(F))
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005281 return EC;
Rafael Espindolad4bcefc2014-10-24 18:13:04 +00005282 F->setIsMaterializable(false);
Chandler Carruth7132e002007-08-04 01:51:18 +00005283
Rafael Espindola0d68b4c2015-03-30 21:36:43 +00005284 if (StripDebugInfo)
5285 stripDebugInfo(*F);
5286
Chandler Carruth7132e002007-08-04 01:51:18 +00005287 // Upgrade any old intrinsic calls in the function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005288 for (auto &I : UpgradedIntrinsics) {
Rafael Espindola257a3532016-01-15 19:00:20 +00005289 for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
5290 UI != UE;) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005291 User *U = *UI;
5292 ++UI;
5293 if (CallInst *CI = dyn_cast<CallInst>(U))
5294 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005295 }
5296 }
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005297
Peter Collingbourned4bff302015-11-05 22:03:56 +00005298 // Finish fn->subprogram upgrade for materialized functions.
5299 if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
5300 F->setSubprogram(SP);
5301
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005302 // Bring in any functions that this function forward-referenced via
5303 // blockaddresses.
5304 return materializeForwardReferencedFunctions();
Chris Lattner9eeada92007-05-18 04:02:46 +00005305}
5306
Rafael Espindola79753a02015-12-18 21:18:57 +00005307std::error_code BitcodeReader::materializeModule() {
Manman Ren4a9b0eb2015-03-13 19:24:30 +00005308 if (std::error_code EC = materializeMetadata())
5309 return EC;
5310
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005311 // Promise to materialize all forward references.
5312 WillMaterializeAllForwardRefs = true;
5313
Chris Lattner06310bf2009-06-16 05:15:21 +00005314 // Iterate over the module, deserializing any functions that are still on
5315 // disk.
Duncan P. N. Exon Smithfb1743a32015-10-13 16:48:55 +00005316 for (Function &F : *TheModule) {
5317 if (std::error_code EC = materialize(&F))
Rafael Espindola246c4fb2014-11-01 16:46:18 +00005318 return EC;
Rafael Espindola2b11ad42013-11-05 19:36:34 +00005319 }
Teresa Johnson1493ad92015-10-10 14:18:36 +00005320 // At this point, if there are any function bodies, parse the rest of
5321 // the bits in the module past the last function block we have recorded
5322 // through either lazy scanning or the VST.
5323 if (LastFunctionBlockBit || NextUnreadBit)
5324 parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
5325 : NextUnreadBit);
Derek Schuff92ef9752012-02-29 00:07:09 +00005326
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005327 // Check that all block address forward references got resolved (as we
5328 // promised above).
Duncan P. N. Exon Smith00f20ac2014-08-01 21:51:52 +00005329 if (!BasicBlockFwdRefs.empty())
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005330 return error("Never resolved function from blockaddress");
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00005331
Chris Bieneman671d0dd2016-03-16 23:17:54 +00005332 // Upgrading intrinsic calls before TBAA can cause TBAA metadata to be lost,
5333 // to prevent this instructions with TBAA tags should be upgraded first.
5334 for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
5335 UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
5336
Daniel Dunbar7d6781b2009-09-20 02:20:51 +00005337 // Upgrade any intrinsic calls that slipped through (should not happen!) and
5338 // delete the old functions to clean up. We can't do this unless the entire
5339 // module is materialized because there could always be another function body
Chandler Carruth7132e002007-08-04 01:51:18 +00005340 // with calls to the old function.
Rafael Espindola86e33402015-07-02 15:55:09 +00005341 for (auto &I : UpgradedIntrinsics) {
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005342 for (auto *U : I.first->users()) {
5343 if (CallInst *CI = dyn_cast<CallInst>(U))
5344 UpgradeIntrinsicCall(CI, I.second);
Chandler Carruth7132e002007-08-04 01:51:18 +00005345 }
Filipe Cabecinhas0011c582015-07-03 20:12:01 +00005346 if (!I.first->use_empty())
5347 I.first->replaceAllUsesWith(I.second);
5348 I.first->eraseFromParent();
Chandler Carruth7132e002007-08-04 01:51:18 +00005349 }
Rafael Espindola4e721212015-07-02 16:22:40 +00005350 UpgradedIntrinsics.clear();
Devang Patel80ae3492009-08-28 23:24:31 +00005351
Rafael Espindola79753a02015-12-18 21:18:57 +00005352 UpgradeDebugInfo(*TheModule);
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005353 return std::error_code();
Chris Lattner9eeada92007-05-18 04:02:46 +00005354}
5355
Rafael Espindola2fa1e432014-12-03 07:18:23 +00005356std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
5357 return IdentifiedStructTypes;
5358}
5359
Rafael Espindola1aabf982015-06-16 23:29:49 +00005360std::error_code
5361BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
Rafael Espindola4223a1f2015-06-15 20:08:17 +00005362 if (Streamer)
Rafael Espindola1aabf982015-06-16 23:29:49 +00005363 return initLazyStream(std::move(Streamer));
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005364 return initStreamFromBuffer();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005365}
5366
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005367std::error_code BitcodeReader::initStreamFromBuffer() {
Roman Divacky4717a8d2012-09-06 15:42:13 +00005368 const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005369 const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
5370
Rafael Espindola27435252014-07-29 21:01:24 +00005371 if (Buffer->getBufferSize() & 3)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005372 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005373
5374 // If we have a wrapper header, parse it and ignore the non-bc file contents.
5375 // The magic number is 0x0B17C0DE stored in little endian.
5376 if (isBitcodeWrapper(BufPtr, BufEnd))
5377 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005378 return error("Invalid bitcode wrapper header");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005379
5380 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005381 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005382
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005383 return std::error_code();
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005384}
5385
Rafael Espindola1aabf982015-06-16 23:29:49 +00005386std::error_code
5387BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005388 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
5389 // see it.
Rafael Espindola1aabf982015-06-16 23:29:49 +00005390 auto OwnedBytes =
5391 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
Rafael Espindola7d727b52014-12-18 05:08:43 +00005392 StreamingMemoryObject &Bytes = *OwnedBytes;
Yaron Keren06d69302014-12-18 10:03:35 +00005393 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
Rafael Espindolade1e5b82014-11-12 14:48:38 +00005394 Stream.init(&*StreamFile);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005395
5396 unsigned char buf[16];
Rafael Espindola7d727b52014-12-18 05:08:43 +00005397 if (Bytes.readBytes(buf, 16, 0) != 16)
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005398 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005399
5400 if (!isBitcode(buf, buf + 16))
Rafael Espindolacbdcb502015-06-15 20:55:37 +00005401 return error("Invalid bitcode signature");
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005402
5403 if (isBitcodeWrapper(buf, buf + 4)) {
5404 const unsigned char *bitcodeStart = buf;
5405 const unsigned char *bitcodeEnd = buf + 16;
5406 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
Rafael Espindola7d727b52014-12-18 05:08:43 +00005407 Bytes.dropLeadingBytes(bitcodeStart - buf);
5408 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00005409 }
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +00005410 return std::error_code();
Rafael Espindola48da4f42013-11-04 16:16:24 +00005411}
5412
Teresa Johnson26ab5772016-03-15 00:04:37 +00005413std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E,
5414 const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005415 return ::error(DiagnosticHandler, make_error_code(E), Message);
5416}
5417
Teresa Johnson26ab5772016-03-15 00:04:37 +00005418std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005419 return ::error(DiagnosticHandler,
5420 make_error_code(BitcodeError::CorruptedBitcode), Message);
5421}
5422
Teresa Johnson26ab5772016-03-15 00:04:37 +00005423std::error_code ModuleSummaryIndexBitcodeReader::error(BitcodeError E) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005424 return ::error(DiagnosticHandler, make_error_code(E));
5425}
5426
Teresa Johnson26ab5772016-03-15 00:04:37 +00005427ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005428 MemoryBuffer *Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005429 bool IsLazy, bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005430 : DiagnosticHandler(DiagnosticHandler), Buffer(Buffer), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005431 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005432
Teresa Johnson26ab5772016-03-15 00:04:37 +00005433ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
Mehdi Amini354f5202015-11-19 05:52:29 +00005434 DiagnosticHandlerFunction DiagnosticHandler, bool IsLazy,
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005435 bool CheckGlobalValSummaryPresenceOnly)
Mehdi Amini354f5202015-11-19 05:52:29 +00005436 : DiagnosticHandler(DiagnosticHandler), Buffer(nullptr), IsLazy(IsLazy),
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005437 CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
Teresa Johnson403a7872015-10-04 14:33:43 +00005438
Teresa Johnson26ab5772016-03-15 00:04:37 +00005439void ModuleSummaryIndexBitcodeReader::freeState() { Buffer = nullptr; }
Teresa Johnson403a7872015-10-04 14:33:43 +00005440
Teresa Johnson26ab5772016-03-15 00:04:37 +00005441void ModuleSummaryIndexBitcodeReader::releaseBuffer() { Buffer.release(); }
Teresa Johnson403a7872015-10-04 14:33:43 +00005442
Teresa Johnson26ab5772016-03-15 00:04:37 +00005443uint64_t ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005444 auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
5445 assert(VGI != ValueIdToCallGraphGUIDMap.end());
5446 return VGI->second;
5447}
5448
5449GlobalValueInfo *
Teresa Johnson26ab5772016-03-15 00:04:37 +00005450ModuleSummaryIndexBitcodeReader::getInfoFromSummaryOffset(uint64_t Offset) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005451 auto I = SummaryOffsetToInfoMap.find(Offset);
5452 assert(I != SummaryOffsetToInfoMap.end());
5453 return I->second;
5454}
5455
5456// Specialized value symbol table parser used when reading module index
Teresa Johnson403a7872015-10-04 14:33:43 +00005457// blocks where we don't actually create global values.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005458// At the end of this routine the module index is populated with a map
5459// from global value name to GlobalValueInfo. The global value info contains
5460// the function block's bitcode offset (if applicable), or the offset into the
5461// summary section for the combined index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005462std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005463 uint64_t Offset,
5464 DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
5465 assert(Offset > 0 && "Expected non-zero VST offset");
5466 uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
5467
Teresa Johnson403a7872015-10-04 14:33:43 +00005468 if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
5469 return error("Invalid record");
5470
5471 SmallVector<uint64_t, 64> Record;
5472
5473 // Read all the records for this value table.
5474 SmallString<128> ValueName;
5475 while (1) {
5476 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5477
5478 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005479 case BitstreamEntry::SubBlock: // Handled for us already.
5480 case BitstreamEntry::Error:
5481 return error("Malformed block");
5482 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005483 // Done parsing VST, jump back to wherever we came from.
5484 Stream.JumpToBit(CurrentBit);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005485 return std::error_code();
5486 case BitstreamEntry::Record:
5487 // The interesting case.
5488 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005489 }
5490
5491 // Read a record.
5492 Record.clear();
5493 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005494 default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
5495 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005496 case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
5497 if (convertToString(Record, 1, ValueName))
5498 return error("Invalid record");
5499 unsigned ValueID = Record[0];
5500 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5501 llvm::make_unique<GlobalValueInfo>();
5502 assert(!SourceFileName.empty());
5503 auto VLI = ValueIdToLinkageMap.find(ValueID);
5504 assert(VLI != ValueIdToLinkageMap.end() &&
5505 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005506 std::string GlobalId = GlobalValue::getGlobalIdentifier(
5507 ValueName, VLI->second, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005508 TheIndex->addGlobalValueInfo(GlobalId, std::move(GlobalValInfo));
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005509 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValue::getGUID(GlobalId);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005510 ValueName.clear();
5511 break;
5512 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005513 case bitc::VST_CODE_FNENTRY: {
Teresa Johnson79d4e2f2016-02-10 15:02:51 +00005514 // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005515 if (convertToString(Record, 2, ValueName))
5516 return error("Invalid record");
5517 unsigned ValueID = Record[0];
5518 uint64_t FuncOffset = Record[1];
Teresa Johnsone1164de2016-02-10 21:55:02 +00005519 assert(!IsLazy && "Lazy summary read only supported for combined index");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005520 std::unique_ptr<GlobalValueInfo> FuncInfo =
5521 llvm::make_unique<GlobalValueInfo>(FuncOffset);
5522 assert(!SourceFileName.empty());
5523 auto VLI = ValueIdToLinkageMap.find(ValueID);
5524 assert(VLI != ValueIdToLinkageMap.end() &&
5525 "No linkage found for VST entry?");
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005526 std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
5527 ValueName, VLI->second, SourceFileName);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005528 TheIndex->addGlobalValueInfo(FunctionGlobalId, std::move(FuncInfo));
Teresa Johnsonb43027d2016-03-15 02:13:19 +00005529 ValueIdToCallGraphGUIDMap[ValueID] =
5530 GlobalValue::getGUID(FunctionGlobalId);
Teresa Johnson403a7872015-10-04 14:33:43 +00005531
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005532 ValueName.clear();
5533 break;
5534 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005535 case bitc::VST_CODE_COMBINED_GVDEFENTRY: {
5536 // VST_CODE_COMBINED_GVDEFENTRY: [valueid, offset, guid]
5537 unsigned ValueID = Record[0];
5538 uint64_t GlobalValSummaryOffset = Record[1];
5539 uint64_t GlobalValGUID = Record[2];
5540 std::unique_ptr<GlobalValueInfo> GlobalValInfo =
5541 llvm::make_unique<GlobalValueInfo>(GlobalValSummaryOffset);
5542 SummaryOffsetToInfoMap[GlobalValSummaryOffset] = GlobalValInfo.get();
5543 TheIndex->addGlobalValueInfo(GlobalValGUID, std::move(GlobalValInfo));
5544 ValueIdToCallGraphGUIDMap[ValueID] = GlobalValGUID;
5545 break;
5546 }
5547 case bitc::VST_CODE_COMBINED_ENTRY: {
5548 // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
5549 unsigned ValueID = Record[0];
5550 uint64_t RefGUID = Record[1];
5551 ValueIdToCallGraphGUIDMap[ValueID] = RefGUID;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005552 break;
5553 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005554 }
5555 }
5556}
5557
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005558// Parse just the blocks needed for building the index out of the module.
5559// At the end of this routine the module Index is populated with a map
5560// from global value name to GlobalValueInfo. The global value info contains
5561// either the parsed summary information (when parsing summaries
5562// eagerly), or just to the summary record's offset
Teresa Johnson403a7872015-10-04 14:33:43 +00005563// if parsing lazily (IsLazy).
Teresa Johnson26ab5772016-03-15 00:04:37 +00005564std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005565 if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
5566 return error("Invalid record");
5567
Teresa Johnsone1164de2016-02-10 21:55:02 +00005568 SmallVector<uint64_t, 64> Record;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005569 DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
5570 unsigned ValueId = 0;
Teresa Johnsone1164de2016-02-10 21:55:02 +00005571
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005572 // Read the index for this module.
Teresa Johnson403a7872015-10-04 14:33:43 +00005573 while (1) {
5574 BitstreamEntry Entry = Stream.advance();
5575
5576 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005577 case BitstreamEntry::Error:
5578 return error("Malformed block");
5579 case BitstreamEntry::EndBlock:
5580 return std::error_code();
5581
5582 case BitstreamEntry::SubBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005583 if (CheckGlobalValSummaryPresenceOnly) {
5584 if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
5585 SeenGlobalValSummary = true;
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005586 // No need to parse the rest since we found the summary.
5587 return std::error_code();
5588 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005589 if (Stream.SkipBlock())
5590 return error("Invalid record");
Teresa Johnson6290dbc2015-11-21 21:55:48 +00005591 continue;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005592 }
5593 switch (Entry.ID) {
5594 default: // Skip unknown content.
5595 if (Stream.SkipBlock())
5596 return error("Invalid record");
5597 break;
5598 case bitc::BLOCKINFO_BLOCK_ID:
5599 // Need to parse these to get abbrev ids (e.g. for VST)
5600 if (Stream.ReadBlockInfoBlock())
5601 return error("Malformed block");
5602 break;
5603 case bitc::VALUE_SYMTAB_BLOCK_ID:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005604 // Should have been parsed earlier via VSTOffset, unless there
5605 // is no summary section.
5606 assert(((SeenValueSymbolTable && VSTOffset > 0) ||
5607 !SeenGlobalValSummary) &&
5608 "Expected early VST parse via VSTOffset record");
5609 if (Stream.SkipBlock())
5610 return error("Invalid record");
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005611 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005612 case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
5613 assert(VSTOffset > 0 && "Expected non-zero VST offset");
5614 assert(!SeenValueSymbolTable &&
5615 "Already read VST when parsing summary block?");
5616 if (std::error_code EC =
5617 parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
5618 return EC;
5619 SeenValueSymbolTable = true;
5620 SeenGlobalValSummary = true;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005621 if (IsLazy) {
5622 // Lazy parsing of summary info, skip it.
5623 if (Stream.SkipBlock())
5624 return error("Invalid record");
5625 } else if (std::error_code EC = parseEntireSummary())
5626 return EC;
5627 break;
5628 case bitc::MODULE_STRTAB_BLOCK_ID:
5629 if (std::error_code EC = parseModuleStringTable())
5630 return EC;
5631 break;
5632 }
5633 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005634
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005635 case BitstreamEntry::Record: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005636 Record.clear();
5637 auto BitCode = Stream.readRecord(Entry.ID, Record);
5638 switch (BitCode) {
5639 default:
5640 break; // Default behavior, ignore unknown content.
5641 /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005642 case bitc::MODULE_CODE_SOURCE_FILENAME: {
Teresa Johnsone1164de2016-02-10 21:55:02 +00005643 SmallString<128> ValueName;
5644 if (convertToString(Record, 0, ValueName))
5645 return error("Invalid record");
5646 SourceFileName = ValueName.c_str();
5647 break;
5648 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005649 /// MODULE_CODE_HASH: [5*i32]
5650 case bitc::MODULE_CODE_HASH: {
5651 if (Record.size() != 5)
5652 return error("Invalid hash length " + Twine(Record.size()).str());
5653 if (!TheIndex)
5654 break;
5655 if (TheIndex->modulePaths().empty())
5656 // Does not have any summary emitted.
5657 break;
5658 if (TheIndex->modulePaths().size() != 1)
5659 return error("Don't expect multiple modules defined?");
5660 auto &Hash = TheIndex->modulePaths().begin()->second.second;
5661 int Pos = 0;
5662 for (auto &Val : Record) {
5663 assert(!(Val >> 32) && "Unexpected high bits set");
5664 Hash[Pos++] = Val;
5665 }
5666 break;
5667 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005668 /// MODULE_CODE_VSTOFFSET: [offset]
5669 case bitc::MODULE_CODE_VSTOFFSET:
5670 if (Record.size() < 1)
5671 return error("Invalid record");
5672 VSTOffset = Record[0];
5673 break;
5674 // GLOBALVAR: [pointer type, isconst, initid,
5675 // linkage, alignment, section, visibility, threadlocal,
5676 // unnamed_addr, externally_initialized, dllstorageclass,
5677 // comdat]
5678 case bitc::MODULE_CODE_GLOBALVAR: {
5679 if (Record.size() < 6)
5680 return error("Invalid record");
5681 uint64_t RawLinkage = Record[3];
5682 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5683 ValueIdToLinkageMap[ValueId++] = Linkage;
5684 break;
5685 }
5686 // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
5687 // alignment, section, visibility, gc, unnamed_addr,
5688 // prologuedata, dllstorageclass, comdat, prefixdata]
5689 case bitc::MODULE_CODE_FUNCTION: {
5690 if (Record.size() < 8)
5691 return error("Invalid record");
5692 uint64_t RawLinkage = Record[3];
5693 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5694 ValueIdToLinkageMap[ValueId++] = Linkage;
5695 break;
5696 }
5697 // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
5698 // dllstorageclass]
5699 case bitc::MODULE_CODE_ALIAS: {
5700 if (Record.size() < 6)
5701 return error("Invalid record");
5702 uint64_t RawLinkage = Record[3];
5703 GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
5704 ValueIdToLinkageMap[ValueId++] = Linkage;
5705 break;
5706 }
5707 }
Teresa Johnsone1164de2016-02-10 21:55:02 +00005708 }
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005709 continue;
Teresa Johnson403a7872015-10-04 14:33:43 +00005710 }
5711 }
5712}
5713
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005714// Eagerly parse the entire summary block. This populates the GlobalValueSummary
5715// objects in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005716std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005717 if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
Teresa Johnson403a7872015-10-04 14:33:43 +00005718 return error("Invalid record");
5719
5720 SmallVector<uint64_t, 64> Record;
5721
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005722 bool Combined = false;
Teresa Johnson403a7872015-10-04 14:33:43 +00005723 while (1) {
5724 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5725
5726 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005727 case BitstreamEntry::SubBlock: // Handled for us already.
5728 case BitstreamEntry::Error:
5729 return error("Malformed block");
5730 case BitstreamEntry::EndBlock:
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005731 // For a per-module index, remove any entries that still have empty
5732 // summaries. The VST parsing creates entries eagerly for all symbols,
5733 // but not all have associated summaries (e.g. it doesn't know how to
5734 // distinguish between VST_CODE_ENTRY for function declarations vs global
5735 // variables with initializers that end up with a summary). Remove those
5736 // entries now so that we don't need to rely on the combined index merger
5737 // to clean them up (especially since that may not run for the first
5738 // module's index if we merge into that).
5739 if (!Combined)
5740 TheIndex->removeEmptySummaryEntries();
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005741 return std::error_code();
5742 case BitstreamEntry::Record:
5743 // The interesting case.
5744 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005745 }
5746
5747 // Read a record. The record format depends on whether this
5748 // is a per-module index or a combined index file. In the per-module
5749 // case the records contain the associated value's ID for correlation
5750 // with VST entries. In the combined index the correlation is done
5751 // via the bitcode offset of the summary records (which were saved
5752 // in the combined index VST entries). The records also contain
5753 // information used for ThinLTO renaming and importing.
5754 Record.clear();
5755 uint64_t CurRecordBit = Stream.GetCurrentBitNo();
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005756 auto BitCode = Stream.readRecord(Entry.ID, Record);
5757 switch (BitCode) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005758 default: // Default behavior: ignore.
5759 break;
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005760 // FS_PERMODULE: [valueid, linkage, instcount, numrefs, numrefs x valueid,
5761 // n x (valueid, callsitecount)]
5762 // FS_PERMODULE_PROFILE: [valueid, linkage, instcount, numrefs,
5763 // numrefs x valueid,
5764 // n x (valueid, callsitecount, profilecount)]
5765 case bitc::FS_PERMODULE:
5766 case bitc::FS_PERMODULE_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005767 unsigned ValueID = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005768 uint64_t RawLinkage = Record[1];
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005769 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005770 unsigned NumRefs = Record[3];
5771 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5772 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005773 // The module path string ref set in the summary must be owned by the
5774 // index's module string table. Since we don't have a module path
5775 // string table section in the per-module index, we create a single
5776 // module path string table entry with an empty (0) ID to take
5777 // ownership.
5778 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005779 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005780 static int RefListStartIndex = 4;
5781 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5782 assert(Record.size() >= RefListStartIndex + NumRefs &&
5783 "Record size inconsistent with number of references");
5784 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5785 unsigned RefValueId = Record[I];
5786 uint64_t RefGUID = getGUIDFromValueId(RefValueId);
5787 FS->addRefEdge(RefGUID);
5788 }
5789 bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
5790 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5791 ++I) {
5792 unsigned CalleeValueId = Record[I];
5793 unsigned CallsiteCount = Record[++I];
5794 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
5795 uint64_t CalleeGUID = getGUIDFromValueId(CalleeValueId);
5796 FS->addCallGraphEdge(CalleeGUID,
5797 CalleeInfo(CallsiteCount, ProfileCount));
5798 }
5799 uint64_t GUID = getGUIDFromValueId(ValueID);
5800 auto InfoList = TheIndex->findGlobalValueInfoList(GUID);
5801 assert(InfoList != TheIndex->end() &&
5802 "Expected VST parse to create GlobalValueInfo entry");
5803 assert(InfoList->second.size() == 1 &&
5804 "Expected a single GlobalValueInfo per GUID in module");
5805 auto &Info = InfoList->second[0];
5806 assert(!Info->summary() && "Expected a single summary per VST entry");
5807 Info->setSummary(std::move(FS));
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005808 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005809 }
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005810 // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, linkage, n x valueid]
5811 case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
5812 unsigned ValueID = Record[0];
5813 uint64_t RawLinkage = Record[1];
5814 std::unique_ptr<GlobalVarSummary> FS =
5815 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5816 FS->setModulePath(
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005817 TheIndex->addModulePath(Buffer->getBufferIdentifier(), 0)->first());
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005818 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5819 unsigned RefValueId = Record[I];
5820 uint64_t RefGUID = getGUIDFromValueId(RefValueId);
5821 FS->addRefEdge(RefGUID);
5822 }
5823 uint64_t GUID = getGUIDFromValueId(ValueID);
5824 auto InfoList = TheIndex->findGlobalValueInfoList(GUID);
5825 assert(InfoList != TheIndex->end() &&
5826 "Expected VST parse to create GlobalValueInfo entry");
5827 assert(InfoList->second.size() == 1 &&
5828 "Expected a single GlobalValueInfo per GUID in module");
5829 auto &Info = InfoList->second[0];
5830 assert(!Info->summary() && "Expected a single summary per VST entry");
5831 Info->setSummary(std::move(FS));
5832 break;
5833 }
5834 // FS_COMBINED: [modid, linkage, instcount, numrefs, numrefs x valueid,
5835 // n x (valueid, callsitecount)]
5836 // FS_COMBINED_PROFILE: [modid, linkage, instcount, numrefs,
5837 // numrefs x valueid,
5838 // n x (valueid, callsitecount, profilecount)]
5839 case bitc::FS_COMBINED:
5840 case bitc::FS_COMBINED_PROFILE: {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005841 uint64_t ModuleId = Record[0];
Teresa Johnson5e22e442016-02-06 16:07:35 +00005842 uint64_t RawLinkage = Record[1];
5843 unsigned InstCount = Record[2];
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005844 unsigned NumRefs = Record[3];
5845 std::unique_ptr<FunctionSummary> FS = llvm::make_unique<FunctionSummary>(
5846 getDecodedLinkage(RawLinkage), InstCount);
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005847 FS->setModulePath(ModuleIdMap[ModuleId]);
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00005848 static int RefListStartIndex = 4;
5849 int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
5850 assert(Record.size() >= RefListStartIndex + NumRefs &&
5851 "Record size inconsistent with number of references");
5852 for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
5853 unsigned RefValueId = Record[I];
5854 uint64_t RefGUID = getGUIDFromValueId(RefValueId);
5855 FS->addRefEdge(RefGUID);
5856 }
5857 bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
5858 for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
5859 ++I) {
5860 unsigned CalleeValueId = Record[I];
5861 unsigned CallsiteCount = Record[++I];
5862 uint64_t ProfileCount = HasProfile ? Record[++I] : 0;
5863 uint64_t CalleeGUID = getGUIDFromValueId(CalleeValueId);
5864 FS->addCallGraphEdge(CalleeGUID,
5865 CalleeInfo(CallsiteCount, ProfileCount));
5866 }
5867 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5868 assert(!Info->summary() && "Expected a single summary per VST entry");
5869 Info->setSummary(std::move(FS));
5870 Combined = true;
5871 break;
5872 }
5873 // FS_COMBINED_GLOBALVAR_INIT_REFS: [modid, linkage, n x valueid]
5874 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
5875 uint64_t ModuleId = Record[0];
5876 uint64_t RawLinkage = Record[1];
5877 std::unique_ptr<GlobalVarSummary> FS =
5878 llvm::make_unique<GlobalVarSummary>(getDecodedLinkage(RawLinkage));
5879 FS->setModulePath(ModuleIdMap[ModuleId]);
5880 for (unsigned I = 2, E = Record.size(); I != E; ++I) {
5881 unsigned RefValueId = Record[I];
5882 uint64_t RefGUID = getGUIDFromValueId(RefValueId);
5883 FS->addRefEdge(RefGUID);
5884 }
5885 auto *Info = getInfoFromSummaryOffset(CurRecordBit);
5886 assert(!Info->summary() && "Expected a single summary per VST entry");
5887 Info->setSummary(std::move(FS));
5888 Combined = true;
Teresa Johnsonbbe05452016-02-24 17:57:28 +00005889 break;
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005890 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005891 }
5892 }
5893 llvm_unreachable("Exit infinite loop");
5894}
5895
5896// Parse the module string table block into the Index.
5897// This populates the ModulePathStringTable map in the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005898std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
Teresa Johnson403a7872015-10-04 14:33:43 +00005899 if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
5900 return error("Invalid record");
5901
5902 SmallVector<uint64_t, 64> Record;
5903
5904 SmallString<128> ModulePath;
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005905 ModulePathStringTableTy::iterator LastSeenModulePath;
Teresa Johnson403a7872015-10-04 14:33:43 +00005906 while (1) {
5907 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
5908
5909 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005910 case BitstreamEntry::SubBlock: // Handled for us already.
5911 case BitstreamEntry::Error:
5912 return error("Malformed block");
5913 case BitstreamEntry::EndBlock:
5914 return std::error_code();
5915 case BitstreamEntry::Record:
5916 // The interesting case.
5917 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00005918 }
5919
5920 Record.clear();
5921 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005922 default: // Default behavior: ignore.
5923 break;
5924 case bitc::MST_CODE_ENTRY: {
5925 // MST_ENTRY: [modid, namechar x N]
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005926 uint64_t ModuleId = Record[0];
5927
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005928 if (convertToString(Record, 1, ModulePath))
5929 return error("Invalid record");
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005930
5931 LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
5932 ModuleIdMap[ModuleId] = LastSeenModulePath->first();
5933
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005934 ModulePath.clear();
5935 break;
5936 }
Mehdi Aminid7ad2212016-04-01 05:33:11 +00005937 /// MST_CODE_HASH: [5*i32]
5938 case bitc::MST_CODE_HASH: {
5939 if (Record.size() != 5)
5940 return error("Invalid hash length " + Twine(Record.size()).str());
5941 if (LastSeenModulePath == TheIndex->modulePaths().end())
5942 return error("Invalid hash that does not follow a module path");
5943 int Pos = 0;
5944 for (auto &Val : Record) {
5945 assert(!(Val >> 32) && "Unexpected high bits set");
5946 LastSeenModulePath->second.second[Pos++] = Val;
5947 }
5948 // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
5949 LastSeenModulePath = TheIndex->modulePaths().end();
5950 break;
5951 }
Teresa Johnson403a7872015-10-04 14:33:43 +00005952 }
5953 }
5954 llvm_unreachable("Exit infinite loop");
5955}
5956
5957// Parse the function info index from the bitcode streamer into the given index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005958std::error_code ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(
5959 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I) {
Teresa Johnson403a7872015-10-04 14:33:43 +00005960 TheIndex = I;
5961
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005962 if (std::error_code EC = initStream(std::move(Streamer)))
5963 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00005964
5965 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005966 if (!hasValidBitcodeHeader(Stream))
5967 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00005968
5969 // We expect a number of well-defined blocks, though we don't necessarily
5970 // need to understand them all.
5971 while (1) {
5972 if (Stream.AtEndOfStream()) {
5973 // We didn't really read a proper Module block.
5974 return error("Malformed block");
5975 }
5976
5977 BitstreamEntry Entry =
5978 Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
5979
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005980 if (Entry.Kind != BitstreamEntry::SubBlock)
5981 return error("Malformed block");
Teresa Johnson403a7872015-10-04 14:33:43 +00005982
5983 // If we see a MODULE_BLOCK, parse it to find the blocks needed for
5984 // building the function summary index.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005985 if (Entry.ID == bitc::MODULE_BLOCK_ID)
5986 return parseModule();
Teresa Johnson403a7872015-10-04 14:33:43 +00005987
Teresa Johnsonf72278f2015-11-02 18:02:11 +00005988 if (Stream.SkipBlock())
5989 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00005990 }
5991}
5992
Teresa Johnson26ab5772016-03-15 00:04:37 +00005993// Parse the summary information at the given offset in the buffer into
5994// the index. Used to support lazy parsing of summaries from the
Teresa Johnson403a7872015-10-04 14:33:43 +00005995// combined index during importing.
5996// TODO: This function is not yet complete as it won't have a consumer
5997// until ThinLTO function importing is added.
Teresa Johnson26ab5772016-03-15 00:04:37 +00005998std::error_code ModuleSummaryIndexBitcodeReader::parseGlobalValueSummary(
5999 std::unique_ptr<DataStreamer> Streamer, ModuleSummaryIndex *I,
6000 size_t SummaryOffset) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006001 TheIndex = I;
6002
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006003 if (std::error_code EC = initStream(std::move(Streamer)))
6004 return EC;
Teresa Johnson403a7872015-10-04 14:33:43 +00006005
6006 // Sniff for the signature.
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006007 if (!hasValidBitcodeHeader(Stream))
6008 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006009
Teresa Johnson26ab5772016-03-15 00:04:37 +00006010 Stream.JumpToBit(SummaryOffset);
Teresa Johnson403a7872015-10-04 14:33:43 +00006011
6012 BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
6013
6014 switch (Entry.Kind) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006015 default:
6016 return error("Malformed block");
6017 case BitstreamEntry::Record:
6018 // The expected case.
6019 break;
Teresa Johnson403a7872015-10-04 14:33:43 +00006020 }
6021
6022 // TODO: Read a record. This interface will be completed when ThinLTO
6023 // importing is added so that it can be tested.
6024 SmallVector<uint64_t, 64> Record;
6025 switch (Stream.readRecord(Entry.ID, Record)) {
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006026 case bitc::FS_COMBINED:
6027 case bitc::FS_COMBINED_PROFILE:
6028 case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS:
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006029 default:
6030 return error("Invalid record");
Teresa Johnson403a7872015-10-04 14:33:43 +00006031 }
6032
6033 return std::error_code();
6034}
6035
Teresa Johnson26ab5772016-03-15 00:04:37 +00006036std::error_code ModuleSummaryIndexBitcodeReader::initStream(
6037 std::unique_ptr<DataStreamer> Streamer) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006038 if (Streamer)
6039 return initLazyStream(std::move(Streamer));
Teresa Johnson403a7872015-10-04 14:33:43 +00006040 return initStreamFromBuffer();
6041}
6042
Teresa Johnson26ab5772016-03-15 00:04:37 +00006043std::error_code ModuleSummaryIndexBitcodeReader::initStreamFromBuffer() {
Teresa Johnson403a7872015-10-04 14:33:43 +00006044 const unsigned char *BufPtr = (const unsigned char *)Buffer->getBufferStart();
6045 const unsigned char *BufEnd = BufPtr + Buffer->getBufferSize();
6046
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006047 if (Buffer->getBufferSize() & 3)
6048 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006049
6050 // If we have a wrapper header, parse it and ignore the non-bc file contents.
6051 // The magic number is 0x0B17C0DE stored in little endian.
6052 if (isBitcodeWrapper(BufPtr, BufEnd))
6053 if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
6054 return error("Invalid bitcode wrapper header");
6055
6056 StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
6057 Stream.init(&*StreamFile);
6058
6059 return std::error_code();
6060}
6061
Teresa Johnson26ab5772016-03-15 00:04:37 +00006062std::error_code ModuleSummaryIndexBitcodeReader::initLazyStream(
Teresa Johnson403a7872015-10-04 14:33:43 +00006063 std::unique_ptr<DataStreamer> Streamer) {
6064 // Check and strip off the bitcode wrapper; BitstreamReader expects never to
6065 // see it.
6066 auto OwnedBytes =
6067 llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
6068 StreamingMemoryObject &Bytes = *OwnedBytes;
6069 StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
6070 Stream.init(&*StreamFile);
6071
6072 unsigned char buf[16];
6073 if (Bytes.readBytes(buf, 16, 0) != 16)
6074 return error("Invalid bitcode signature");
6075
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006076 if (!isBitcode(buf, buf + 16))
6077 return error("Invalid bitcode signature");
Teresa Johnson403a7872015-10-04 14:33:43 +00006078
6079 if (isBitcodeWrapper(buf, buf + 4)) {
6080 const unsigned char *bitcodeStart = buf;
6081 const unsigned char *bitcodeEnd = buf + 16;
6082 SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
6083 Bytes.dropLeadingBytes(bitcodeStart - buf);
6084 Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
6085 }
6086 return std::error_code();
6087}
6088
Rafael Espindola48da4f42013-11-04 16:16:24 +00006089namespace {
Rafael Espindola25188c92014-06-12 01:45:43 +00006090class BitcodeErrorCategoryType : public std::error_category {
Rafael Espindolaf5d07fa2014-06-10 21:26:47 +00006091 const char *name() const LLVM_NOEXCEPT override {
Rafael Espindola48da4f42013-11-04 16:16:24 +00006092 return "llvm.bitcode";
6093 }
Craig Topper73156022014-03-02 09:09:27 +00006094 std::string message(int IE) const override {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006095 BitcodeError E = static_cast<BitcodeError>(IE);
Rafael Espindola48da4f42013-11-04 16:16:24 +00006096 switch (E) {
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006097 case BitcodeError::InvalidBitcodeSignature:
Rafael Espindola48da4f42013-11-04 16:16:24 +00006098 return "Invalid bitcode signature";
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006099 case BitcodeError::CorruptedBitcode:
6100 return "Corrupted bitcode";
Rafael Espindola48da4f42013-11-04 16:16:24 +00006101 }
Benjamin Kramer77db1632013-11-05 13:45:09 +00006102 llvm_unreachable("Unknown error type!");
Rafael Espindola48da4f42013-11-04 16:16:24 +00006103 }
6104};
Eugene Zelenko6ac3f732016-01-26 18:48:36 +00006105} // end anonymous namespace
Rafael Espindola48da4f42013-11-04 16:16:24 +00006106
Chris Bieneman770163e2014-09-19 20:29:02 +00006107static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
6108
Rafael Espindolac3f2e732014-07-29 20:22:46 +00006109const std::error_category &llvm::BitcodeErrorCategory() {
Chris Bieneman770163e2014-09-19 20:29:02 +00006110 return *ErrorCategory;
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006111}
Chris Lattner51ffe7c2007-05-01 04:59:48 +00006112
Chris Lattner6694f602007-04-29 07:54:31 +00006113//===----------------------------------------------------------------------===//
6114// External interface
6115//===----------------------------------------------------------------------===//
6116
Rafael Espindola456baad2015-06-17 01:15:47 +00006117static ErrorOr<std::unique_ptr<Module>>
6118getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
6119 BitcodeReader *R, LLVMContext &Context,
6120 bool MaterializeAll, bool ShouldLazyLoadMetadata) {
6121 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
6122 M->setMaterializer(R);
6123
6124 auto cleanupOnError = [&](std::error_code EC) {
6125 R->releaseBuffer(); // Never take ownership on error.
6126 return EC;
6127 };
6128
6129 // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
6130 if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
6131 ShouldLazyLoadMetadata))
6132 return cleanupOnError(EC);
6133
6134 if (MaterializeAll) {
6135 // Read in the entire module, and destroy the BitcodeReader.
Rafael Espindolac4a03482015-12-18 20:13:39 +00006136 if (std::error_code EC = M->materializeAll())
Rafael Espindola456baad2015-06-17 01:15:47 +00006137 return cleanupOnError(EC);
6138 } else {
6139 // Resolve forward references from blockaddresses.
6140 if (std::error_code EC = R->materializeForwardReferencedFunctions())
6141 return cleanupOnError(EC);
6142 }
6143 return std::move(M);
6144}
6145
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006146/// \brief Get a lazy one-at-time loading module from bitcode.
Chris Lattner6694f602007-04-29 07:54:31 +00006147///
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006148/// This isn't always used in a lazy context. In particular, it's also used by
6149/// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
6150/// in forward-referenced functions from block address references.
6151///
Rafael Espindola728074b2015-06-17 00:40:56 +00006152/// \param[in] MaterializeAll Set to \c true if we should materialize
6153/// everything.
Rafael Espindoladcd1dca2015-06-16 22:27:55 +00006154static ErrorOr<std::unique_ptr<Module>>
Rafael Espindola68812152014-09-03 17:31:46 +00006155getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
Rafael Espindola728074b2015-06-17 00:40:56 +00006156 LLVMContext &Context, bool MaterializeAll,
Manman Ren4a9b0eb2015-03-13 19:24:30 +00006157 bool ShouldLazyLoadMetadata = false) {
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006158 BitcodeReader *R = new BitcodeReader(Buffer.get(), Context);
Duncan P. N. Exon Smith908d8092014-08-01 21:11:34 +00006159
Rafael Espindola456baad2015-06-17 01:15:47 +00006160 ErrorOr<std::unique_ptr<Module>> Ret =
6161 getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
6162 MaterializeAll, ShouldLazyLoadMetadata);
6163 if (!Ret)
6164 return Ret;
Rafael Espindolab7993462012-01-02 07:49:53 +00006165
Rafael Espindolae2c1d772014-08-26 22:00:09 +00006166 Buffer.release(); // The BitcodeReader owns it now.
Rafael Espindola456baad2015-06-17 01:15:47 +00006167 return Ret;
Chris Lattner6694f602007-04-29 07:54:31 +00006168}
6169
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006170ErrorOr<std::unique_ptr<Module>>
6171llvm::getLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
6172 LLVMContext &Context, bool ShouldLazyLoadMetadata) {
Rafael Espindolad0b23be2015-01-10 00:07:30 +00006173 return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006174 ShouldLazyLoadMetadata);
Duncan P. N. Exon Smith6e1009b2014-08-01 22:27:19 +00006175}
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006176
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006177ErrorOr<std::unique_ptr<Module>>
6178llvm::getStreamedBitcodeModule(StringRef Name,
6179 std::unique_ptr<DataStreamer> Streamer,
6180 LLVMContext &Context) {
Rafael Espindola7d727b52014-12-18 05:08:43 +00006181 std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006182 BitcodeReader *R = new BitcodeReader(Context);
Rafael Espindola456baad2015-06-17 01:15:47 +00006183
6184 return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
6185 false);
Derek Schuff8b2dcad2012-02-06 22:30:29 +00006186}
6187
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006188ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
6189 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006190 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006191 return getLazyBitcodeModuleImpl(std::move(Buf), Context, true);
Chad Rosierca2567b2011-12-07 21:44:12 +00006192 // TODO: Restore the use-lists to the in-memory state when the bitcode was
6193 // written. We must defer until the Module has been fully materialized.
Chris Lattner6694f602007-04-29 07:54:31 +00006194}
Bill Wendling0198ce02010-10-06 01:22:42 +00006195
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006196std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
6197 LLVMContext &Context) {
Rafael Espindolad96d5532014-08-26 21:49:01 +00006198 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006199 auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context);
Rafael Espindolac75c4fa2014-07-04 20:02:42 +00006200 ErrorOr<std::string> Triple = R->parseTriple();
Rafael Espindolad346cc82014-07-04 13:52:01 +00006201 if (Triple.getError())
6202 return "";
6203 return Triple.get();
Bill Wendling0198ce02010-10-06 01:22:42 +00006204}
Teresa Johnson403a7872015-10-04 14:33:43 +00006205
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006206std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
6207 LLVMContext &Context) {
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006208 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00006209 BitcodeReader R(Buf.release(), Context);
Mehdi Amini3383ccc2015-11-09 02:46:41 +00006210 ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
6211 if (ProducerString.getError())
6212 return "";
6213 return ProducerString.get();
6214}
6215
Teresa Johnson403a7872015-10-04 14:33:43 +00006216// Parse the specified bitcode buffer, returning the function info index.
6217// If IsLazy is false, parse the entire function summary into
6218// the index. Otherwise skip the function summary section, and only create
6219// an index object with a map from function name to function summary offset.
6220// The index is used to perform lazy function summary reading later.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006221ErrorOr<std::unique_ptr<ModuleSummaryIndex>>
6222llvm::getModuleSummaryIndex(MemoryBufferRef Buffer,
6223 DiagnosticHandlerFunction DiagnosticHandler,
6224 bool IsLazy) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006225 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006226 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, IsLazy);
Teresa Johnson403a7872015-10-04 14:33:43 +00006227
Teresa Johnson26ab5772016-03-15 00:04:37 +00006228 auto Index = llvm::make_unique<ModuleSummaryIndex>();
Teresa Johnson403a7872015-10-04 14:33:43 +00006229
6230 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006231 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006232 return EC;
6233 };
6234
6235 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, Index.get()))
6236 return cleanupOnError(EC);
6237
Teresa Johnson26ab5772016-03-15 00:04:37 +00006238 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006239 return std::move(Index);
6240}
6241
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006242// Check if the given bitcode buffer contains a global value summary block.
6243bool llvm::hasGlobalValueSummary(MemoryBufferRef Buffer,
6244 DiagnosticHandlerFunction DiagnosticHandler) {
Teresa Johnson403a7872015-10-04 14:33:43 +00006245 std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
Teresa Johnson26ab5772016-03-15 00:04:37 +00006246 ModuleSummaryIndexBitcodeReader R(Buf.get(), DiagnosticHandler, false, true);
Teresa Johnson403a7872015-10-04 14:33:43 +00006247
6248 auto cleanupOnError = [&](std::error_code EC) {
Teresa Johnsonf72278f2015-11-02 18:02:11 +00006249 R.releaseBuffer(); // Never take ownership on error.
Teresa Johnson403a7872015-10-04 14:33:43 +00006250 return false;
6251 };
6252
6253 if (std::error_code EC = R.parseSummaryIndexInto(nullptr, nullptr))
6254 return cleanupOnError(EC);
6255
Teresa Johnson26ab5772016-03-15 00:04:37 +00006256 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson76a1c1d2016-03-11 18:52:24 +00006257 return R.foundGlobalValSummary();
Teresa Johnson403a7872015-10-04 14:33:43 +00006258}
6259
Teresa Johnson26ab5772016-03-15 00:04:37 +00006260// This method supports lazy reading of summary data from the combined
Teresa Johnson403a7872015-10-04 14:33:43 +00006261// index during ThinLTO function importing. When reading the combined index
Teresa Johnson26ab5772016-03-15 00:04:37 +00006262// file, getModuleSummaryIndex is first invoked with IsLazy=true.
6263// Then this method is called for each value considered for importing,
6264// to parse the summary information for the given value name into
Teresa Johnson403a7872015-10-04 14:33:43 +00006265// the index.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006266std::error_code llvm::readGlobalValueSummary(
Mehdi Amini354f5202015-11-19 05:52:29 +00006267 MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
Teresa Johnson26ab5772016-03-15 00:04:37 +00006268 StringRef ValueName, std::unique_ptr<ModuleSummaryIndex> Index) {
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);
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 EC;
6275 };
6276
Teresa Johnson26ab5772016-03-15 00:04:37 +00006277 // Lookup the given value name in the GlobalValueMap, which may
6278 // contain a list of global value infos in the case of a COMDAT. Walk through
6279 // and parse each summary info at the summary offset
Teresa Johnson403a7872015-10-04 14:33:43 +00006280 // recorded when parsing the value symbol table.
Teresa Johnson26ab5772016-03-15 00:04:37 +00006281 for (const auto &FI : Index->getGlobalValueInfoList(ValueName)) {
6282 size_t SummaryOffset = FI->bitcodeIndex();
Teresa Johnson403a7872015-10-04 14:33:43 +00006283 if (std::error_code EC =
Teresa Johnson26ab5772016-03-15 00:04:37 +00006284 R.parseGlobalValueSummary(nullptr, Index.get(), SummaryOffset))
Teresa Johnson403a7872015-10-04 14:33:43 +00006285 return cleanupOnError(EC);
6286 }
6287
Teresa Johnson26ab5772016-03-15 00:04:37 +00006288 Buf.release(); // The ModuleSummaryIndexBitcodeReader owns it now.
Teresa Johnson403a7872015-10-04 14:33:43 +00006289 return std::error_code();
6290}